edited_code
stringlengths
17
978k
original_code
stringlengths
17
978k
from __future__ import division from pyomo.environ import * import numpy as np import pandas as pd from folium import Map, CircleMarker, FeatureGroup, LayerControl import os.path class linear_program: def construct_inputs(self): # Construct the files needed for input from the demand output file # Read in demand input # Load Sets # Create each file # Calculate Travel Times from google_api and Calculate Penalty Matrix # def load(self): # Create a model model = AbstractModel() # Import sets set_df = pd.read_csv('../data/interim/lp_data/input_data/Set_List.csv') node_list = list(set_df['B'])[:95] charger_list = list(set_df['K'])[:2] # 72 because three representative days time_list = list(set_df['T'])[:72] # line_list = list(set_df['L'])[:772] # Create pyomo sets model.B = Set(initialize=node_list) model.K = Set(initialize=charger_list) model.T = Set(initialize=time_list) model.L = Set(initialize=line_list) # Create Model Parameters model.F = Param(model.B, model.K) model.D = Param(model.B, model.K) model.p = Param(model.B, model.L) model.A = Param(model.B, model.T) model.G = Param(model.T) model.C = Param(model.B, model.K) model.N = Param(model.K) model.E = Param(model.B, model.K) model.S = Param(model.B) model.M = Param(initialize=100) model.VW = Param(model.B, model.K, model.T) model.P_H_U = Param(model.L, model.T) # Load data into model parameters data = DataPortal() data.load(filename='../data/interim/lp_data/input_data/Fixed_Cost.csv', param=model.F, index=(model.B, model.K)) data.load(filename='../data/interim/lp_data/input_data/Demand_Charge.csv', param=model.D, index=(model.B, model.K)) data.load(filename='../data/interim/lp_data/input_data/Incidence_Matrix.tab', param=model.p, format='array') data.load(filename='../data/interim/lp_data/input_data/Demand.csv', param=model.A, index=(model.B, model.T)) data.load(filename='../data/interim/lp_data/input_data/Charging_Efficiency.csv', param=model.G, index=(model.T)) data.load(filename='../data/interim/lp_data/input_data/Plug_in_Limit.csv', param=model.C, index=(model.B, model.K)) data.load(filename='../data/interim/lp_data/input_data/Charger_Capacity.csv', param=model.N, index=(model.K)) data.load(filename='../data/interim/lp_data/input_data/Existing_Capacity.csv', param=model.E, index=(model.B, model.K)) data.load(filename='../data/interim/lp_data/input_data/Site_Develop_Cost.csv', param=model.S, index=(model.B)) data.load(filename='../data/interim/lp_data/input_data/V_Times_W.csv', param=model.VW, index=(model.B, model.K, model.T)) data.load(filename='../data/interim/lp_data/input_data/P_H_U.csv', param=model.P_H_U, index=(model.L, model.T)) # Create Decision Variables model.x = Var(model.B, model.K, within=NonNegativeReals) model.n = Var(model.B, model.K, within=NonNegativeIntegers) model.y = Var(model.B, model.K, model.T, within=NonNegativeReals) model.f = Var(model.L, model.T, within=NonNegativeReals) model.v = Var(model.B, within=Binary) # Objective Function def obj_expression(model): return summation(model.S, model.v) + \ summation(model.F, model.x) + \ summation(model.D, model.x) + \ summation(model.VW, model.y) + \ summation(model.P_H_U, model.f) model.OBJ = Objective(rule=obj_expression, sense=minimize) # Constraint One def first_constraint_rule(model, b, t): return (sum(model.y[b, k, t] for k in model.K) + sum(model.p[b, l] * model.f[l, t] for l in model.L)) \ >= (model.A[b, t]) model.FirstConstraint = Constraint(model.B, model.T, rule=first_constraint_rule) # Constraint Two def second_constraint_rule(model, b, k, t): return (model.y[b, k, t] <= (model.x[b, k] + model.E[b, k]) * model.G[t]) model.SecondConstraint = Constraint(model.B, model.K, model.T, rule=second_constraint_rule) # Create model instance instance = model.create_instance(data) return instance def run(self): instance = self.load() # Create and solve the LP solver = pyomo.opt.SolverFactory('glpk') solver.solve(instance, tee=True, keepfiles=True) # Save the instance results self.save(instance) def save(self, instance): # Write out results ind_x = list(instance.x) val_x = list(instance.x[:, :].value) ind_v = list(instance.v) val_v = list(instance.v[:].value) ind_y = list(instance.y) val_y = list(instance.y[:, :, :].value) ind_f = list(instance.f) val_f = list(instance.f[:, :].value) result_x = [i + tuple([j]) for i, j in zip(ind_x, val_x)] result_v = [i for i in zip(ind_v, val_v)] result_y = [i + tuple([j]) for i, j in zip(ind_y, val_y)] result_f = [i + tuple([j]) for i, j in zip(ind_f, val_f)] pd.DataFrame(np.array(result_x)).to_csv('../data/processed/lp_data/output_data/x.csv', index=False) pd.DataFrame(np.array(result_v)).to_csv('../data/processed/lp_data/output_data/v.csv', index=False) pd.DataFrame(np.array(result_y)).to_csv('../data/processed/lp_data/output_data/y.csv', index=False) pd.DataFrame(np.array(result_f)).to_csv('../data/processed/lp_data/output_data/f.csv', index=False) def show(self): # Function should take the LP output, join with h3 hexagons to get geometries # And plot the proposed charging stations # Could add functionality for overlap with def map_multiple_outputs_points(directory: str, map_center=None, save_path=None): """ Creates a folium map of single or multiple outputs from the LP model. Circle markers communicate both location of station and forecast demand (diameter). Good for outputs from LP model that outputs points - not hexes. """ station_locations = open_station_locations() if not map_center: m_lat = station_locations[:1]['latitude'] m_long = station_locations[:1]['longitude'] else: m_lat = map_center[0] m_long = map_center[1] m = Map( location=[m_lat, m_long], tiles='cartodbpositron', zoom_start=9 ) colors = ['blue', 'crimson', 'violet', 'orange', 'yellow', 'black'] cnt = 0 for file in os.listdir(directory): open_path_1 = f'data/GIS/LP_outputs/{file}' print(file) name = file.rstrip('.csv') proposed_stations_1 = open_lp_proposed_stations(lp_proposed_stations_path=open_path_1) proposed_stations_1.set_index('id', inplace=True) proposed_stations_1 = join_dfs(station_locations, proposed_stations_1) feature_group = FeatureGroup(name=name) for i, row in proposed_stations_1.iterrows(): if row['demand'] == 0: pass else: c = CircleMarker( radius=row['demand'], location=[row["latitude"], row["longitude"]], tooltip=f"Station ID: {row.name} \n Demand: {row["demand"]} kWh", color=colors[cnt], fill=True, fill_color=colors[cnt] ) c.add_to(feature_group) feature_group.add_to(m) cnt += 1 LayerControl('bottomright', collapsed=False).add_to(m) if save_path: m.save(save_path) return m def join_hex_ids()
from __future__ import division from pyomo.environ import * import numpy as np import pandas as pd from folium import Map, CircleMarker, FeatureGroup, LayerControl import os.path class linear_program: def construct_inputs(self): # Construct the files needed for input from the demand output file # Read in demand input # Load Sets # Create each file # Calculate Travel Times from google_api and Calculate Penalty Matrix # def load(self): # Create a model model = AbstractModel() # Import sets set_df = pd.read_csv('../data/interim/lp_data/input_data/Set_List.csv') node_list = list(set_df['B'])[:95] charger_list = list(set_df['K'])[:2] # 72 because three representative days time_list = list(set_df['T'])[:72] # line_list = list(set_df['L'])[:772] # Create pyomo sets model.B = Set(initialize=node_list) model.K = Set(initialize=charger_list) model.T = Set(initialize=time_list) model.L = Set(initialize=line_list) # Create Model Parameters model.F = Param(model.B, model.K) model.D = Param(model.B, model.K) model.p = Param(model.B, model.L) model.A = Param(model.B, model.T) model.G = Param(model.T) model.C = Param(model.B, model.K) model.N = Param(model.K) model.E = Param(model.B, model.K) model.S = Param(model.B) model.M = Param(initialize=100) model.VW = Param(model.B, model.K, model.T) model.P_H_U = Param(model.L, model.T) # Load data into model parameters data = DataPortal() data.load(filename='../data/interim/lp_data/input_data/Fixed_Cost.csv', param=model.F, index=(model.B, model.K)) data.load(filename='../data/interim/lp_data/input_data/Demand_Charge.csv', param=model.D, index=(model.B, model.K)) data.load(filename='../data/interim/lp_data/input_data/Incidence_Matrix.tab', param=model.p, format='array') data.load(filename='../data/interim/lp_data/input_data/Demand.csv', param=model.A, index=(model.B, model.T)) data.load(filename='../data/interim/lp_data/input_data/Charging_Efficiency.csv', param=model.G, index=(model.T)) data.load(filename='../data/interim/lp_data/input_data/Plug_in_Limit.csv', param=model.C, index=(model.B, model.K)) data.load(filename='../data/interim/lp_data/input_data/Charger_Capacity.csv', param=model.N, index=(model.K)) data.load(filename='../data/interim/lp_data/input_data/Existing_Capacity.csv', param=model.E, index=(model.B, model.K)) data.load(filename='../data/interim/lp_data/input_data/Site_Develop_Cost.csv', param=model.S, index=(model.B)) data.load(filename='../data/interim/lp_data/input_data/V_Times_W.csv', param=model.VW, index=(model.B, model.K, model.T)) data.load(filename='../data/interim/lp_data/input_data/P_H_U.csv', param=model.P_H_U, index=(model.L, model.T)) # Create Decision Variables model.x = Var(model.B, model.K, within=NonNegativeReals) model.n = Var(model.B, model.K, within=NonNegativeIntegers) model.y = Var(model.B, model.K, model.T, within=NonNegativeReals) model.f = Var(model.L, model.T, within=NonNegativeReals) model.v = Var(model.B, within=Binary) # Objective Function def obj_expression(model): return summation(model.S, model.v) + \ summation(model.F, model.x) + \ summation(model.D, model.x) + \ summation(model.VW, model.y) + \ summation(model.P_H_U, model.f) model.OBJ = Objective(rule=obj_expression, sense=minimize) # Constraint One def first_constraint_rule(model, b, t): return (sum(model.y[b, k, t] for k in model.K) + sum(model.p[b, l] * model.f[l, t] for l in model.L)) \ >= (model.A[b, t]) model.FirstConstraint = Constraint(model.B, model.T, rule=first_constraint_rule) # Constraint Two def second_constraint_rule(model, b, k, t): return (model.y[b, k, t] <= (model.x[b, k] + model.E[b, k]) * model.G[t]) model.SecondConstraint = Constraint(model.B, model.K, model.T, rule=second_constraint_rule) # Create model instance instance = model.create_instance(data) return instance def run(self): instance = self.load() # Create and solve the LP solver = pyomo.opt.SolverFactory('glpk') solver.solve(instance, tee=True, keepfiles=True) # Save the instance results self.save(instance) def save(self, instance): # Write out results ind_x = list(instance.x) val_x = list(instance.x[:, :].value) ind_v = list(instance.v) val_v = list(instance.v[:].value) ind_y = list(instance.y) val_y = list(instance.y[:, :, :].value) ind_f = list(instance.f) val_f = list(instance.f[:, :].value) result_x = [i + tuple([j]) for i, j in zip(ind_x, val_x)] result_v = [i for i in zip(ind_v, val_v)] result_y = [i + tuple([j]) for i, j in zip(ind_y, val_y)] result_f = [i + tuple([j]) for i, j in zip(ind_f, val_f)] pd.DataFrame(np.array(result_x)).to_csv('../data/processed/lp_data/output_data/x.csv', index=False) pd.DataFrame(np.array(result_v)).to_csv('../data/processed/lp_data/output_data/v.csv', index=False) pd.DataFrame(np.array(result_y)).to_csv('../data/processed/lp_data/output_data/y.csv', index=False) pd.DataFrame(np.array(result_f)).to_csv('../data/processed/lp_data/output_data/f.csv', index=False) def show(self): # Function should take the LP output, join with h3 hexagons to get geometries # And plot the proposed charging stations # Could add functionality for overlap with def map_multiple_outputs_points(directory: str, map_center=None, save_path=None): """ Creates a folium map of single or multiple outputs from the LP model. Circle markers communicate both location of station and forecast demand (diameter). Good for outputs from LP model that outputs points - not hexes. """ station_locations = open_station_locations() if not map_center: m_lat = station_locations[:1]['latitude'] m_long = station_locations[:1]['longitude'] else: m_lat = map_center[0] m_long = map_center[1] m = Map( location=[m_lat, m_long], tiles='cartodbpositron', zoom_start=9 ) colors = ['blue', 'crimson', 'violet', 'orange', 'yellow', 'black'] cnt = 0 for file in os.listdir(directory): open_path_1 = f'data/GIS/LP_outputs/{file}' print(file) name = file.rstrip('.csv') proposed_stations_1 = open_lp_proposed_stations(lp_proposed_stations_path=open_path_1) proposed_stations_1.set_index('id', inplace=True) proposed_stations_1 = join_dfs(station_locations, proposed_stations_1) feature_group = FeatureGroup(name=name) for i, row in proposed_stations_1.iterrows(): if row['demand'] == 0: pass else: c = CircleMarker( radius=row['demand'], location=[row["latitude"], row["longitude"]], tooltip=f"Station ID: {row.name} \n Demand: {row['demand']} kWh", color=colors[cnt], fill=True, fill_color=colors[cnt] ) c.add_to(feature_group) feature_group.add_to(m) cnt += 1 LayerControl('bottomright', collapsed=False).add_to(m) if save_path: m.save(save_path) return m def join_hex_ids()
# -*- coding: utf-8 -*- from typing import List import dash_core_components as dcc import dash_daq as daq import dash_html_components as html from dash import dash from dash.dependencies import Input, Output, State from zvt.api.trader_info_api import AccountStatsReader, OrderReader, get_order_securities from zvt.api.trader_info_api import get_trader_info from zvt.contract import Mixin from zvt.contract import zvt_context, IntervalLevel from zvt.contract.api import get_entities, get_schema_by_name, get_schema_columns from zvt.contract.drawer import StackedDrawer from zvt.domain import TraderInfo from zvt.ui import zvt_app from zvt.ui.components.dcc_components import get_account_stats_figure from zvt.utils import pd_is_not_null account_readers = [] order_readers = [] # init the data traders: List[TraderInfo] = [] trader_names: List[str] = [] def order_type_flag(order_type): if order_type == 'order_long' or order_type == 'order_close_short': return 'B' else: return 'S' def order_type_color(order_type): if order_type == 'order_long' or order_type == 'order_close_short': return "#ec0000" else: return "#00da3c" def load_traders(): global traders global trader_names traders = get_trader_info(return_type='domain') account_readers.clear() order_readers.clear() for trader in traders: account_readers.append(AccountStatsReader(level=trader.level, trader_names=[trader.trader_name])) order_readers.append( OrderReader(start_timestamp=trader.start_timestamp, level=trader.level, trader_names=[trader.trader_name])) trader_names = [item.trader_name for item in traders] load_traders() def factor_layout(): layout = html.Div( [ # controls html.Div( className="three columns card", children=[ html.Div( className="bg-white user-control", children=[ html.Div( className="padding-top-bot", children=[ html.H6("select trader:"), dcc.Dropdown(id='trader-selector', placeholder='select the trader', options=[{'label': item, 'value': i} for i, item in enumerate(trader_names)] ), ], ), # select entity_type html.Div( className="padding-top-bot", children=[ html.H6("select entity type:"), dcc.Dropdown(id='entity-type-selector', placeholder='select entity type', options=[{'label': name, 'value': name} for name in zvt_context.tradable_schema_map.keys()], value='stock', clearable=False) ], ), # select entity html.Div( className="padding-top-bot", children=[ html.H6("select entity:"), dcc.Dropdown(id='entity-selector', placeholder='select entity') ], ), # select levels html.Div( className="padding-top-bot", children=[ html.H6("select levels:"), dcc.Dropdown( id='levels-selector', options=[{'label': level.name, 'value': level.value} for level in (IntervalLevel.LEVEL_1WEEK, IntervalLevel.LEVEL_1DAY)], value='1d', multi=True ) ], ), # select factor html.Div( className="padding-top-bot", children=[ html.H6("select factor:"), dcc.Dropdown(id='factor-selector', placeholder='select factor', options=[{'label': name, 'value': name} for name in zvt_context.factor_cls_registry.keys()], value='TechnicalFactor') ] ), # select data html.Div( children=[ html.Div( [ html.H6("related/all data to show in sub graph", style={"display": "inline-block"}), daq.BooleanSwitch( id='data-switch', on=True, style={"display": "inline-block", "float": "right", "vertical-align": "middle", "padding": "8px"} ), ], ), dcc.Dropdown(id='data-selector', placeholder='schema') ], style={"padding-top": "12px"} ), # select properties html.Div( children=[ dcc.Dropdown(id='schema-column-selector', placeholder='properties') ], style={"padding-top": "6px"} ), ]) ]), # Graph html.Div( className="nine columns card-left", children=[ html.Div( id='trader-details', className="bg-white", ), html.Div( id='factor-details' ) ]) ] ) return layout @zvt_app.callback( [Output('trader-details', 'children'), Output('entity-type-selector', 'options'), Output('entity-selector', 'options')], [Input('trader-selector', 'value'), Input('entity-type-selector', 'value')]) def update_trader_details(trader_index, entity_type): if trader_index is not None: # change entity_type options entity_type = traders[trader_index].entity_type if not entity_type: entity_type = 'stock' entity_type_options = [{'label': entity_type, 'value': entity_type}] # account stats account_stats = get_account_stats_figure(account_stats_reader=account_readers[trader_index]) # entities entity_ids = get_order_securities(trader_name=trader_names[trader_index]) df = get_entities(entity_type=entity_type, entity_ids=entity_ids, columns=['entity_id', 'code', 'name'], index='entity_id') entity_options = [{'label': f'{entity_id}({entity['name']})', 'value': entity_id} for entity_id, entity in df.iterrows()] return account_stats, entity_type_options, entity_options else: entity_type_options = [{'label': name, 'value': name} for name in zvt_context.tradable_schema_map.keys()] account_stats = None df = get_entities(entity_type=entity_type, columns=['entity_id', 'code', 'name'], index='entity_id') entity_options = [{'label': f'{entity_id}({entity['name']})', 'value': entity_id} for entity_id, entity in df.iterrows()] return account_stats, entity_type_options, entity_options @zvt_app.callback( Output('data-selector', 'options'), [Input('entity-type-selector', 'value'), Input('data-switch', 'on')]) def update_entity_selector(entity_type, related): if entity_type is not None: if related: schemas = zvt_context.entity_map_schemas.get(entity_type) else: schemas = zvt_context.schemas return [{'label': schema.__name__, 'value': schema.__name__} for schema in schemas] raise dash.PreventUpdate() @zvt_app.callback( Output('schema-column-selector', 'options'), [Input('data-selector', 'value')]) def update_column_selector(schema_name): if schema_name: schema = get_schema_by_name(name=schema_name) cols = get_schema_columns(schema=schema) return [{'label': col, 'value': col} for col in cols] raise dash.PreventUpdate() @zvt_app.callback( Output('factor-details', 'children'), [Input('factor-selector', 'value'), Input('entity-type-selector', 'value'), Input('entity-selector', 'value'), Input('levels-selector', 'value'), Input('schema-column-selector', 'value')], state=[State('trader-selector', 'value'), State('data-selector', 'value')]) def update_factor_details(factor, entity_type, entity, levels, columns, trader_index, schema_name): if factor and entity_type and entity and levels: sub_df = None # add sub graph if columns: if type(columns) == str: columns = [columns] columns = columns + ['entity_id', 'timestamp'] schema: Mixin = get_schema_by_name(name=schema_name) sub_df = schema.query_data(entity_id=entity, columns=columns) # add trading signals as annotation annotation_df = None if trader_index is not None: order_reader = order_readers[trader_index] annotation_df = order_reader.data_df.copy() annotation_df = annotation_df[annotation_df.entity_id == entity].copy() if pd_is_not_null(annotation_df): annotation_df['value'] = annotation_df['order_price'] annotation_df['flag'] = annotation_df['order_type'].apply(lambda x: order_type_flag(x)) annotation_df['color'] = annotation_df['order_type'].apply(lambda x: order_type_color(x)) print(annotation_df.tail()) if type(levels) is list and len(levels) >= 2: levels.sort() drawers = [] for level in levels: drawers.append(zvt_context.factor_cls_registry[factor]( entity_schema=zvt_context.tradable_schema_map[entity_type], level=level, entity_ids=[entity]).drawer()) stacked = StackedDrawer(*drawers) return dcc.Graph( id=f'{factor}-{entity_type}-{entity}', figure=stacked.draw_kline(show=False, height=900)) else: if type(levels) is list: level = levels[0] else: level = levels drawer = zvt_context.factor_cls_registry[factor](entity_schema=zvt_context.tradable_schema_map[entity_type], level=level, entity_ids=[entity], need_persist=False).drawer() if pd_is_not_null(sub_df): drawer.add_sub_df(sub_df) if pd_is_not_null(annotation_df): drawer.annotation_df = annotation_df return dcc.Graph( id=f'{factor}-{entity_type}-{entity}', figure=drawer.draw_kline(show=False, height=800)) raise dash.PreventUpdate()
# -*- coding: utf-8 -*- from typing import List import dash_core_components as dcc import dash_daq as daq import dash_html_components as html from dash import dash from dash.dependencies import Input, Output, State from zvt.api.trader_info_api import AccountStatsReader, OrderReader, get_order_securities from zvt.api.trader_info_api import get_trader_info from zvt.contract import Mixin from zvt.contract import zvt_context, IntervalLevel from zvt.contract.api import get_entities, get_schema_by_name, get_schema_columns from zvt.contract.drawer import StackedDrawer from zvt.domain import TraderInfo from zvt.ui import zvt_app from zvt.ui.components.dcc_components import get_account_stats_figure from zvt.utils import pd_is_not_null account_readers = [] order_readers = [] # init the data traders: List[TraderInfo] = [] trader_names: List[str] = [] def order_type_flag(order_type): if order_type == 'order_long' or order_type == 'order_close_short': return 'B' else: return 'S' def order_type_color(order_type): if order_type == 'order_long' or order_type == 'order_close_short': return "#ec0000" else: return "#00da3c" def load_traders(): global traders global trader_names traders = get_trader_info(return_type='domain') account_readers.clear() order_readers.clear() for trader in traders: account_readers.append(AccountStatsReader(level=trader.level, trader_names=[trader.trader_name])) order_readers.append( OrderReader(start_timestamp=trader.start_timestamp, level=trader.level, trader_names=[trader.trader_name])) trader_names = [item.trader_name for item in traders] load_traders() def factor_layout(): layout = html.Div( [ # controls html.Div( className="three columns card", children=[ html.Div( className="bg-white user-control", children=[ html.Div( className="padding-top-bot", children=[ html.H6("select trader:"), dcc.Dropdown(id='trader-selector', placeholder='select the trader', options=[{'label': item, 'value': i} for i, item in enumerate(trader_names)] ), ], ), # select entity_type html.Div( className="padding-top-bot", children=[ html.H6("select entity type:"), dcc.Dropdown(id='entity-type-selector', placeholder='select entity type', options=[{'label': name, 'value': name} for name in zvt_context.tradable_schema_map.keys()], value='stock', clearable=False) ], ), # select entity html.Div( className="padding-top-bot", children=[ html.H6("select entity:"), dcc.Dropdown(id='entity-selector', placeholder='select entity') ], ), # select levels html.Div( className="padding-top-bot", children=[ html.H6("select levels:"), dcc.Dropdown( id='levels-selector', options=[{'label': level.name, 'value': level.value} for level in (IntervalLevel.LEVEL_1WEEK, IntervalLevel.LEVEL_1DAY)], value='1d', multi=True ) ], ), # select factor html.Div( className="padding-top-bot", children=[ html.H6("select factor:"), dcc.Dropdown(id='factor-selector', placeholder='select factor', options=[{'label': name, 'value': name} for name in zvt_context.factor_cls_registry.keys()], value='TechnicalFactor') ] ), # select data html.Div( children=[ html.Div( [ html.H6("related/all data to show in sub graph", style={"display": "inline-block"}), daq.BooleanSwitch( id='data-switch', on=True, style={"display": "inline-block", "float": "right", "vertical-align": "middle", "padding": "8px"} ), ], ), dcc.Dropdown(id='data-selector', placeholder='schema') ], style={"padding-top": "12px"} ), # select properties html.Div( children=[ dcc.Dropdown(id='schema-column-selector', placeholder='properties') ], style={"padding-top": "6px"} ), ]) ]), # Graph html.Div( className="nine columns card-left", children=[ html.Div( id='trader-details', className="bg-white", ), html.Div( id='factor-details' ) ]) ] ) return layout @zvt_app.callback( [Output('trader-details', 'children'), Output('entity-type-selector', 'options'), Output('entity-selector', 'options')], [Input('trader-selector', 'value'), Input('entity-type-selector', 'value')]) def update_trader_details(trader_index, entity_type): if trader_index is not None: # change entity_type options entity_type = traders[trader_index].entity_type if not entity_type: entity_type = 'stock' entity_type_options = [{'label': entity_type, 'value': entity_type}] # account stats account_stats = get_account_stats_figure(account_stats_reader=account_readers[trader_index]) # entities entity_ids = get_order_securities(trader_name=trader_names[trader_index]) df = get_entities(entity_type=entity_type, entity_ids=entity_ids, columns=['entity_id', 'code', 'name'], index='entity_id') entity_options = [{'label': f'{entity_id}({entity["name"]})', 'value': entity_id} for entity_id, entity in df.iterrows()] return account_stats, entity_type_options, entity_options else: entity_type_options = [{'label': name, 'value': name} for name in zvt_context.tradable_schema_map.keys()] account_stats = None df = get_entities(entity_type=entity_type, columns=['entity_id', 'code', 'name'], index='entity_id') entity_options = [{'label': f'{entity_id}({entity["name"]})', 'value': entity_id} for entity_id, entity in df.iterrows()] return account_stats, entity_type_options, entity_options @zvt_app.callback( Output('data-selector', 'options'), [Input('entity-type-selector', 'value'), Input('data-switch', 'on')]) def update_entity_selector(entity_type, related): if entity_type is not None: if related: schemas = zvt_context.entity_map_schemas.get(entity_type) else: schemas = zvt_context.schemas return [{'label': schema.__name__, 'value': schema.__name__} for schema in schemas] raise dash.PreventUpdate() @zvt_app.callback( Output('schema-column-selector', 'options'), [Input('data-selector', 'value')]) def update_column_selector(schema_name): if schema_name: schema = get_schema_by_name(name=schema_name) cols = get_schema_columns(schema=schema) return [{'label': col, 'value': col} for col in cols] raise dash.PreventUpdate() @zvt_app.callback( Output('factor-details', 'children'), [Input('factor-selector', 'value'), Input('entity-type-selector', 'value'), Input('entity-selector', 'value'), Input('levels-selector', 'value'), Input('schema-column-selector', 'value')], state=[State('trader-selector', 'value'), State('data-selector', 'value')]) def update_factor_details(factor, entity_type, entity, levels, columns, trader_index, schema_name): if factor and entity_type and entity and levels: sub_df = None # add sub graph if columns: if type(columns) == str: columns = [columns] columns = columns + ['entity_id', 'timestamp'] schema: Mixin = get_schema_by_name(name=schema_name) sub_df = schema.query_data(entity_id=entity, columns=columns) # add trading signals as annotation annotation_df = None if trader_index is not None: order_reader = order_readers[trader_index] annotation_df = order_reader.data_df.copy() annotation_df = annotation_df[annotation_df.entity_id == entity].copy() if pd_is_not_null(annotation_df): annotation_df['value'] = annotation_df['order_price'] annotation_df['flag'] = annotation_df['order_type'].apply(lambda x: order_type_flag(x)) annotation_df['color'] = annotation_df['order_type'].apply(lambda x: order_type_color(x)) print(annotation_df.tail()) if type(levels) is list and len(levels) >= 2: levels.sort() drawers = [] for level in levels: drawers.append(zvt_context.factor_cls_registry[factor]( entity_schema=zvt_context.tradable_schema_map[entity_type], level=level, entity_ids=[entity]).drawer()) stacked = StackedDrawer(*drawers) return dcc.Graph( id=f'{factor}-{entity_type}-{entity}', figure=stacked.draw_kline(show=False, height=900)) else: if type(levels) is list: level = levels[0] else: level = levels drawer = zvt_context.factor_cls_registry[factor](entity_schema=zvt_context.tradable_schema_map[entity_type], level=level, entity_ids=[entity], need_persist=False).drawer() if pd_is_not_null(sub_df): drawer.add_sub_df(sub_df) if pd_is_not_null(annotation_df): drawer.annotation_df = annotation_df return dcc.Graph( id=f'{factor}-{entity_type}-{entity}', figure=drawer.draw_kline(show=False, height=800)) raise dash.PreventUpdate()
# SPDX-License-Identifier: MIT import os, shutil, sys, stat, subprocess, urlcache, zipfile, logging, firmware from util import * class OSInstaller(PackageInstaller): PART_ALIGNMENT = 1024 * 1024 def __init__(self, dutil, data, template): super().__init__() self.dutil = dutil self.data = data self.template = template self.name = template["default_os_name"] self.ucache = None self.efi_part = None self.idata_targets = [] @property def default_os_name(self): return self.template["default_os_name"] @property def min_size(self): return sum(self.align(psize(part["size"])) for part in self.template["partitions"]) @property def expandable(self): return any(part.get("expand", False) for part in self.template["partitions"]) @property def needs_firmware(self): return any(p.get("copy_firmware", False) for p in self.template["partitions"]) def align(self, v): return align_up(v, self.PART_ALIGNMENT) def load_package(self): package = self.template.get("package", None) if not package: return package = os.environ.get("REPO_BASE", ".") + "/os/" + package logging.info(f"OS package URL: {package}") if package.startswith("http"): p_progress("Downloading OS package info...") self.ucache = urlcache.URLCache(package) self.pkg = zipfile.ZipFile(self.ucache) else: p_progress("Loading OS package info...") self.pkg = zipfile.ZipFile(open(package, "rb")) self.flush_progress() logging.info(f"OS package opened") def flush_progress(self): if self.ucache: self.ucache.flush_progress() def partition_disk(self, prev, total_size=None): self.part_info = [] logging.info("OSInstaller.partition_disk({prev}=!r)") if total_size is None: expand_size = 0 else: expand_size = total_size - self.min_size assert expand_size >= 0 for part in self.template["partitions"]: logging.info(f"Adding partition: {part}") size = self.align(psize(part["size"])) ptype = part["type"] fmt = part.get("format", None) name = f"{part["name"]} - {self.name}" logging.info(f"Partition Name: {name}") if part.get("expand", False): size += expand_size logging.info(f"Expanded to {size} (+{expand_size})") p_progress(f"Adding partition {part["name"]} ({ssize(size)})...") info = self.dutil.addPartition(prev, f"%{ptype}%", "%noformat%", size) if ptype == "EFI": self.efi_part = info self.part_info.append(info) if fmt == "fat": p_plain(" Formatting as FAT...") args = ["newfs_msdos", "-F", "32", "-v", name[:11]] if "volume_id" in part: args.extend(["-I", part["volume_id"]]) args.append(f"/dev/r{info.name}") logging.info(f"Run: {args!r}") subprocess.run(args, check=True, stdout=subprocess.PIPE) elif fmt: raise Exception(f"Unsupported format {fmt}") prev = info.name def install(self, boot_obj_path): p_progress("Installing OS...") logging.info("OSInstaller.install()") for part, info in zip(self.template["partitions"], self.part_info): logging.info(f"Installing partition {part!r} -> {info.name}") image = part.get("image", None) if image: p_plain(f" Extracting {image} into {info.name} partition...") logging.info(f"Extract: {image}") zinfo = self.pkg.getinfo(image) with self.pkg.open(image) as sfd, \ open(f"/dev/r{info.name}", "r+b") as dfd: self.fdcopy(sfd, dfd, zinfo.file_size) self.flush_progress() source = part.get("source", None) if source: p_plain(f" Copying from {source} into {info.name} partition...") mountpoint = self.dutil.mount(info.name) logging.info(f"Copy: {source} -> {mountpoint}") self.extract_tree(source, mountpoint) self.flush_progress() if part.get("copy_firmware", False): mountpoint = self.dutil.mount(info.name) p_plain(f" Copying firmware into {info.name} partition...") base = os.path.join(mountpoint, "vendorfw") logging.info(f"Firmware -> {base}") os.makedirs(base, exist_ok=True) shutil.copy(self.firmware_package.path, os.path.join(base, "firmware.tar")) self.firmware_package.save_manifest(os.path.join(base, "manifest.txt")) if part.get("copy_installer_data", False): mountpoint = self.dutil.mount(info.name) data_path = os.path.join(mountpoint, "asahi") os.makedirs(data_path, exist_ok=True) self.idata_targets.append(data_path) p_progress("Preparing to finish installation...") logging.info(f"Building boot object") boot_object = self.template["boot_object"] next_object = self.template.get("next_object", None) logging.info(f" Boot object: {boot_object}") logging.info(f" Next object: {next_object}") with open(os.path.join("boot", boot_object), "rb") as fd: m1n1_data = fd.read() m1n1_vars = [] if self.efi_part: m1n1_vars.append(f"chosen.asahi,efi-system-partition={self.efi_part.uuid.lower()}") if next_object is not None: assert self.efi_part is not None m1n1_vars.append(f"chainload={self.efi_part.uuid.lower()};{next_object}") logging.info(f"m1n1 vars:") for i in m1n1_vars: logging.info(f" {i}") m1n1_data += b"".join(i.encode("ascii") + b"\n" for i in m1n1_vars) + b"\0\0\0\0" with open(boot_obj_path, "wb") as fd: fd.write(m1n1_data) logging.info(f"Built boot object at {boot_obj_path}")
# SPDX-License-Identifier: MIT import os, shutil, sys, stat, subprocess, urlcache, zipfile, logging, firmware from util import * class OSInstaller(PackageInstaller): PART_ALIGNMENT = 1024 * 1024 def __init__(self, dutil, data, template): super().__init__() self.dutil = dutil self.data = data self.template = template self.name = template["default_os_name"] self.ucache = None self.efi_part = None self.idata_targets = [] @property def default_os_name(self): return self.template["default_os_name"] @property def min_size(self): return sum(self.align(psize(part["size"])) for part in self.template["partitions"]) @property def expandable(self): return any(part.get("expand", False) for part in self.template["partitions"]) @property def needs_firmware(self): return any(p.get("copy_firmware", False) for p in self.template["partitions"]) def align(self, v): return align_up(v, self.PART_ALIGNMENT) def load_package(self): package = self.template.get("package", None) if not package: return package = os.environ.get("REPO_BASE", ".") + "/os/" + package logging.info(f"OS package URL: {package}") if package.startswith("http"): p_progress("Downloading OS package info...") self.ucache = urlcache.URLCache(package) self.pkg = zipfile.ZipFile(self.ucache) else: p_progress("Loading OS package info...") self.pkg = zipfile.ZipFile(open(package, "rb")) self.flush_progress() logging.info(f"OS package opened") def flush_progress(self): if self.ucache: self.ucache.flush_progress() def partition_disk(self, prev, total_size=None): self.part_info = [] logging.info("OSInstaller.partition_disk({prev}=!r)") if total_size is None: expand_size = 0 else: expand_size = total_size - self.min_size assert expand_size >= 0 for part in self.template["partitions"]: logging.info(f"Adding partition: {part}") size = self.align(psize(part["size"])) ptype = part["type"] fmt = part.get("format", None) name = f"{part['name']} - {self.name}" logging.info(f"Partition Name: {name}") if part.get("expand", False): size += expand_size logging.info(f"Expanded to {size} (+{expand_size})") p_progress(f"Adding partition {part['name']} ({ssize(size)})...") info = self.dutil.addPartition(prev, f"%{ptype}%", "%noformat%", size) if ptype == "EFI": self.efi_part = info self.part_info.append(info) if fmt == "fat": p_plain(" Formatting as FAT...") args = ["newfs_msdos", "-F", "32", "-v", name[:11]] if "volume_id" in part: args.extend(["-I", part["volume_id"]]) args.append(f"/dev/r{info.name}") logging.info(f"Run: {args!r}") subprocess.run(args, check=True, stdout=subprocess.PIPE) elif fmt: raise Exception(f"Unsupported format {fmt}") prev = info.name def install(self, boot_obj_path): p_progress("Installing OS...") logging.info("OSInstaller.install()") for part, info in zip(self.template["partitions"], self.part_info): logging.info(f"Installing partition {part!r} -> {info.name}") image = part.get("image", None) if image: p_plain(f" Extracting {image} into {info.name} partition...") logging.info(f"Extract: {image}") zinfo = self.pkg.getinfo(image) with self.pkg.open(image) as sfd, \ open(f"/dev/r{info.name}", "r+b") as dfd: self.fdcopy(sfd, dfd, zinfo.file_size) self.flush_progress() source = part.get("source", None) if source: p_plain(f" Copying from {source} into {info.name} partition...") mountpoint = self.dutil.mount(info.name) logging.info(f"Copy: {source} -> {mountpoint}") self.extract_tree(source, mountpoint) self.flush_progress() if part.get("copy_firmware", False): mountpoint = self.dutil.mount(info.name) p_plain(f" Copying firmware into {info.name} partition...") base = os.path.join(mountpoint, "vendorfw") logging.info(f"Firmware -> {base}") os.makedirs(base, exist_ok=True) shutil.copy(self.firmware_package.path, os.path.join(base, "firmware.tar")) self.firmware_package.save_manifest(os.path.join(base, "manifest.txt")) if part.get("copy_installer_data", False): mountpoint = self.dutil.mount(info.name) data_path = os.path.join(mountpoint, "asahi") os.makedirs(data_path, exist_ok=True) self.idata_targets.append(data_path) p_progress("Preparing to finish installation...") logging.info(f"Building boot object") boot_object = self.template["boot_object"] next_object = self.template.get("next_object", None) logging.info(f" Boot object: {boot_object}") logging.info(f" Next object: {next_object}") with open(os.path.join("boot", boot_object), "rb") as fd: m1n1_data = fd.read() m1n1_vars = [] if self.efi_part: m1n1_vars.append(f"chosen.asahi,efi-system-partition={self.efi_part.uuid.lower()}") if next_object is not None: assert self.efi_part is not None m1n1_vars.append(f"chainload={self.efi_part.uuid.lower()};{next_object}") logging.info(f"m1n1 vars:") for i in m1n1_vars: logging.info(f" {i}") m1n1_data += b"".join(i.encode("ascii") + b"\n" for i in m1n1_vars) + b"\0\0\0\0" with open(boot_obj_path, "wb") as fd: fd.write(m1n1_data) logging.info(f"Built boot object at {boot_obj_path}")
# deepROC.py # # Copyright 2021 Ottawa Hospital Research Institute # # 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. # # Revision history: # Original Matlab version by Andre Carrington, 2018 # Ported to Python by Yusuf Sheikh and Andre Carrington, 2020 # Imports the Transcript class # Additions and corrections from Partial-AUC-C to create DeepROC by Andre Carrington, 2021 # # Functions: # makeLabels01 # getSkewWithRates # getSkew # distance_point_to_line # optimal_ROC_point_indices # getListValuesByIndex # computeCalibrationCurve # plotCalibrationCurve # calibrationOK # doCalibration # doAdvancedMeasures # deepROC # # inputs: testNum, verbose # outputs: results displayed and logged to a file # # Uses test vectors from Fawcett[1], Hilden[2], Carrington et al[3] # This function runs tests that compute expected equalities for whole # and partial AUC and c statistic measures discussed in Carrington # et al [3]. It uses the trapezoid rule to compute area. # # Whole measures: AUC, c # Partial measures: pAUCc, cDelta, pAUC (pAUCy), pAUCx # Normalized partial: pAUCcn, cDeltan, pAUCn, pAUCxn, cLocal # # References: # 1. Fawcett T. An Introduction to ROC Analysis, Pattern # Recognition Letters, 2005. # 2. Hilden J. The Area under the ROC Curve and Its Competitors, # Medical Decision Making, 1991. # 3. Carrington AM, Fieguth P, Qazi H, Holzinger A, Chen H, Mayr F # Manuel D. A new concordant partial AUC and partial c statistic # for imbalanced data in the evaluation of machine learning # algorithms. BMC Medical Informatics and Decision Making, 2020. # # see beginning of runtime logic at the end of this file # runtime parameters # choose one of the following as input (file supercedes others if multiple): useFile = True useSingleTestVector = False useAllTestVectors = False # specify file input parameters mydata = ['040', '356', '529', '536', '581', '639', '643'] fileName = f'input-matlab/result{mydata[2]}.mat' # a matlab file (or future: csv file) for input scoreVarColumn = 'yscoreTest' # yscoreTest, yscore targetVarColumn = 'ytest' # ytest, yhatTest, yhat, ytrain #scoreVarColumn = 'yscore' # yscoreTest, yscore #targetVarColumn = 'yhat' # ytest, yhatTest, yhat, ytrain # specify single test vector input parameters singleTestVectorNum = 13 # which of 12 test vectors the function get_ROC_test_scores_labels_ranges below # choose data science parameters rangeAxis = 'FPR' # examine ranges (next) by FPR or TPR filePAUCranges = [[0.0, 1/3], [1/3, 2/3], [2/3, 1.0]] # ranges, as few or many as you like useCloseRangePoint = False # automatically alter the ranges to match with the closest points in data # useful if you want the discrete form of balanced accuracy to exactly match # because we don't bother to interpolate that one costs = dict(cFP=1, cFN=1, cTP=0, cTN=0) # specify relative costs explicitly (default shown) #costs = {} # use the default costs rates = False # treat costs as rates, e.g. cFPR (default False) # choose what to show sanityCheckWholeAUC = True showPlot = True showData = False showError = True # areas in ROC plots that represent error import do_pAUCc as ac import getPDF as acKDE import numpy as np import pandas as pd import scipy.io as sio import matplotlib.pyplot as plt import matplotlib.ticker as ticker import sklearn.calibration as cal from sklearn import metrics import time import math import transcript from os.path import splitext import ntpath import re # this function is a duplicate of the one in do_pAUCc.py def makeLabels01(labels, posclass): ''' insert docstring here ''' # STATUS: COMPLETE posIndex = list(np.argwhere(np.array(labels) == posclass).flatten()) negIndex = list(np.argwhere(np.array(labels) != posclass).flatten()) newlabels = labels.copy() for i in posIndex: newlabels[i] = 1 for i in negIndex: newlabels[i] = 0 return newlabels #enddef def getSkew_withRates(labels, posclass, quiet, rates=True, cFP=None, cFN=None, cTP=None, cTN=None): if rates is False: raise ValueError('rates should be True') cFPR, cFNR, cTPR, cTNR = (cFP, cFN, cTP, cTN) # these are rates return getSkew(labels, posclass, quiet, rates=rates, cFP=cFPR, cFN=cFNR, cTP=cTPR, cTN=cTNR) #enddef def getSkew(labels, posclass, quiet, rates=None, cFP=None, cFN=None, cTP=None, cTN=None): labels = makeLabels01(labels, posclass) # forces labels to the set {0,1} P = int(sum(labels)) # assumes labels are in set {0,1} N = len(labels) - P msg = '' if rates == None or rates == False: # assumes costs are counts not rates ratetxt = '' ratechr = '' else: # but also handles costs as rates if needed ratetxt = 'rate unit ' ratechr = 'R' # endif if cFP is None: msg = msg + f'\nCost of a false positive {ratetxt}(cFP{ratechr}): 1 (default, since not specified)' cFP = 1 else: msg = msg + f'\nCost of a false positive {ratetxt}(cFP{ratechr}): {cFP:0.1f}' # endif if cFN is None: msg = msg + f'\nCost of a false negative {ratetxt}(cFN{ratechr}): 1 (default, since not specified)' cFN = 1 else: msg = msg + f'\nCost of a false negative {ratetxt}(cFN{ratechr}): {cFN:0.1f}' # endif if cTP is None: msg = msg + f'\nCost of a true positive {ratetxt}(cTP{ratechr}): 0 (default, since not specified)' cTP = 0 else: msg = msg + f'\nCost of a true positive {ratetxt}(cTP{ratechr}): {cTP:0.1f}' # endif if cTN is None: msg = msg + f'\nCost of a true negative {ratetxt}(cTN{ratechr}): 0 (default, since not specified)' cTN = 0 else: msg = msg + f'\nCost of a true negative {ratetxt}(cTN{ratechr}): {cTN:0.1f}' # endif if len(msg) and not quiet: print(f'{msg}\n') #endif # assumes costs are counts (not rates) if rates == None or rates == False: skew = (N / P) * (cFP - cTN) / (cFN - cTP) else: cFPR, cFNR, cTPR, cTNR = (cFP, cFN, cTP, cTN) # these are rates skew = ((N / P)**2) * (cFPR - cTNR) / (cFNR - cTPR) # see paper by Carrington for derivation return skew, N, P #enddef def distance_point_to_line(qx, qy, px, py, m): # point p (px,py) and slope m define a line # query point q (qx,qy): how far is q from the line? if m == 0: # slope is zero (horizontal line), distance is vertical only return abs(qy-py) #raise ValueError('slope is zero') #endif if np.isinf(m): # slope is infinite (vertical line), distance is horizontal only return abs(qx-px) #raise ValueError('slope is infinite') #endif # line through p: y = m *(x-px)+py # perpendicular slope: -1/m # perpendicular line from q: y = (-1/m)*(x-qx)+qy # equate both lines to find intersection at (x0,y0) x0 = (m*px - py + qx/m + qy) / (m + 1/m) # then find y_0 using first line definition y0 = m*(x0-px) + py return math.sqrt( (qx-x0)**2 + (qy-y0)**2 ) #enddef def optimal_ROC_point_indices(fpr, tpr, skew): n = len(fpr) mindist = math.inf min_idx = [] # define a line with slope skew passing through the top-left ROC point (x,y)=(0,1) # for each point in (fpr,tpr) get the distance from that point to the line for i in np.arange(0, n): d = distance_point_to_line(fpr[i], tpr[i], 0, 1, skew) #print(f'd: {d}') if d == mindist: min_idx = min_idx + [i] elif d < mindist: mindist = d min_idx = [i] #endif #endif # now min_idx contains the indices for the point(s) with the minimum distance # return those indices for the optimal ROC points return min_idx #enddef def getListValuesByIndex(a, idx_list): b = [] for i in idx_list: b = b + [a[i]] return b # enddef def computeCalibrationCurve(plotTitle, dataTitle, quiet, params): prob_true, prob_predicted = cal.calibration_curve(**params) # cal.calibration_curve(labels, scores, normalize=False, strategy=strategy, n_bins=bins) actual_bins = len(prob_true) bins = params['n_bins'] if bins > actual_bins and not quiet: print(f'Used {actual_bins} bins instead of the {bins} bins requested.') #endif # plt.plot(prob_predicted, prob_true, "s-", label=dataTitle) # plt.xlabel('Predicted risk/probability') # plt.ylabel('Observed risk/probability') return prob_predicted, prob_true # enddef def plotCalibrationCurve(plotTitle, dataTitle, quiet, params): prob_true, prob_predicted = \ cal.calibration_curve(**params) #cal.calibration_curve(labels, scores, normalize=False, strategy=strategy, n_bins=bins) actual_bins = len(prob_true) bins = params['n_bins'] if bins > actual_bins and not quiet: print(f'Used {actual_bins} bins instead of the {bins} bins requested.') #endif fig = plt.figure() ax = fig.add_subplot(1, 1, 1) plt.plot(prob_predicted, prob_true, "s-", label=dataTitle) plt.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated") plt.xlabel('Predicted risk/probability') plt.ylabel('Observed risk/probability') plt.title(plotTitle) plt.xlim(0.0, 1.0) plt.ylim(0.0, 1.0) ax.axes.xaxis.set_major_locator(ticker.MultipleLocator(0.1)) ax.axes.yaxis.set_major_locator(ticker.MultipleLocator(0.1)) plotGrey = lambda x, y: plt.fill(x, y, 'k', alpha=0.3, linewidth=None) x = [] y = [] shadeWidth = int(round(actual_bins / 3)) step = shadeWidth * 2 # 3 bins=skip 2; 6 bins=skip 4; 9 bins=skip 6 for i in range(0, actual_bins, step): x0 = i * 1/actual_bins x1 = (i+shadeWidth) * 1/actual_bins x = x + [x0] + [x0] + [x1] + [x1] y = y + [0] + [1] + [1] + [0] #endfor plotGrey(x, y) return fig, ax # enddef def calibrationOK(numScores, bins): if (numScores/25) >= bins: return 1 elif (numScores / 10) >= bins: return 0.5 else: return 0 #endif def doCalibration(scores, labels, posclass, fileNum, showPlot, quiet): scores, newlabels, labels = ac.sortScoresFixLabels(scores, labels, posclass, True) # True = ascending maxScore = float(max(scores)) minScore = float(min(scores)) if not quiet: print(f'Before: min,max = {minScore},{maxScore}') #endif scores_np = (np.array(scores) - minScore) / (maxScore - minScore) maxScore = float(max(scores_np)) minScore = float(min(scores_np)) if not quiet: print(f'After: min,max = {minScore},{maxScore}') #endif numScores = int(len(scores_np)) #Xc_cts, Y = acKDE.getPDF(scores_np, 'epanechnikov', 'new', quiet) #Y1D = Y[:, 0] #y2 = np.interp(scores_np, Xc_cts, Y1D) #if showPlot: # plt.plot(scores_np, y2) # plt.show() ##endif for bins in [3, 6, 9]: if calibrationOK(numScores, bins) == 0 and (not quiet): print(f'Not plotted: insufficient scores ({numScores}) for {bins} bins') else: plotTitle = f'Calibration plot with {bins} bins' dataTitle = 'Classifier' if calibrationOK(numScores, bins) == 0.5 and (not quiet): print(f'Plotted despite insufficient scores ({numScores}) for {bins} bins') # endif params = dict(y_true=newlabels, y_prob=scores_np, normalize=False, strategy='uniform', n_bins=bins) if showPlot: fig, ax = plotCalibrationCurve(plotTitle, dataTitle, quiet, params) else: prob_predicted, prob_true = computeCalibrationCurve(plotTitle, dataTitle, quiet, params) #endif if showPlot: plt.show() fig.savefig(f'output/calib_{fileNum}-{bins}.png') #endif # endif # endfor #enddef def deepROC(testNum='1', costs={}, sanityCheckWholeAUC=True, showPlot=True, showData=True, showError=True, globalP=1, globalN=1, useCloseRangePoint=False, pAUCranges={}, scores=[], labels=[], posclass=1, rangeAxis='FPR', quiet=False): doCalibration(scores, labels, posclass, testNum, showPlot, quiet) ep = 1*(10**-12) if ('rates' in costs) and costs['rates'] is True: skew, N, P = getSkew_withRates(labels, posclass, quiet, **costs) # **costs includes rates if not quiet: print(f'Skew (slope) = N * N * cFPR-cTNR = {skew:0.1f}') print( ' - - ---------') print( ' P P cFNR-cTPR') #endif else: skew, N, P = getSkew(labels, posclass, quiet, **costs) # **costs includes rates if not quiet: print(f'Skew (slope) = N * cFP-cTN = {skew:0.1f}') print( ' - -------') print( ' P cFN-cTP') #endif #endif if not quiet: print(' ') print(f"{"N":15s} = {N}") print(f"{"P":15s} = {P}") print(' ') #endif showThresh = 25 # show 20 scores per plot # Get standard fpr, tpr, thresholds from the labels scores fpr, tpr, thresholds = metrics.roc_curve(labels, scores, pos_label=posclass) # data are returned, sorted in ascending order by fpr, then tpr within fpr # note that this AUC may differ slightly from that obtained via full ROC #AUC = metrics.auc(fpr, tpr) # do not use this general auc function because it sometimes gives an error: # ValueError: x is neither increasing nor decreasing #AUC = metrics.roc_auc_score(labels, scores) #if not quiet: # print(f"{"Python AUC":15s} = {AUC:0.4f}") ##endif # Get and show the optimal ROC points (per Metz) opt_idx = optimal_ROC_point_indices(fpr, tpr, skew) fpr_opt = getListValuesByIndex(fpr, opt_idx) tpr_opt = getListValuesByIndex(tpr, opt_idx) thresh_opt = getListValuesByIndex(thresholds, opt_idx) if not quiet: for fprx, tprx, threshx in zip(fpr_opt, tpr_opt, thresh_opt): print(f"{"optimalROCpoint":15s} = ({fprx:0.4f},{tprx:0.4f}) at threshold: {threshx:0.4f}") #endfor #endif pAUCranges_copy = pAUCranges.copy() if sanityCheckWholeAUC == True: pAUCranges_copy.insert(0, [0, 1]) indices = np.arange(0, len(pAUCranges_copy)) # include index 0 as wholeAUC else: indices = np.arange(1, len(pAUCranges_copy)+1) # index 1,2,... for partial curves #endif if not quiet: print(f'indices: {indices}') #endif passALLeq = True; cDelta_sum = 0; pAUC_sum = 0; pAUCx_sum = 0; cpAUC_sum = 0 resultsPerGroup = [] for pAUCrange, index in zip(pAUCranges_copy, indices): passEQ, cDelta, cpAUC, pAUC, pAUCx, cDeltan, cpAUCn, pAUCn, pAUCxn, extras_dict \ = ac.do_pAUCc(mode='testing', index=index, pAUCrange=pAUCrange, labels=labels, scores=scores, posclass=posclass, fpr=fpr, tpr=tpr, thresh=thresholds, fpr_opt=fpr_opt, tpr_opt=tpr_opt, thresh_opt=thresh_opt, numShowThresh=showThresh, testNum=testNum, showPlot=showPlot, showData=showData, showError=showError, globalP=globalP, globalN=globalN, ep=ep, rangeAxis=rangeAxis, useCloseRangePoint=useCloseRangePoint, quiet=quiet) main_result_dict = dict(cDelta=cDelta, cpAUC=cpAUC, pAUC=pAUC, pAUCx=pAUCx, cDeltan=cDeltan, cpAUCn=cpAUCn, pAUCn=pAUCn, pAUCxn=pAUCxn, passEQ=passEQ) main_result_dict.update(extras_dict) resultsPerGroup.append(main_result_dict) passALLeq = passALLeq and passEQ if index > 0: cDelta_sum = cDelta_sum + cDelta cpAUC_sum = cpAUC_sum + cpAUC pAUC_sum = pAUC_sum + pAUC pAUCx_sum = pAUCx_sum + pAUCx #endif if index == 0: AUC = extras_dict['AUC'] c = extras_dict['c'] #endif #endfor if ~quiet: print(' ') #endif # code to check for PASS here if sanityCheckWholeAUC: pass1 = ac.areEpsilonEqual(cDelta_sum, c, 'cDelta_sum', 'c', ep, quiet) #endif pass2 = ac.areEpsilonEqual(cpAUC_sum, AUC, 'cpAUC_sum', 'AUC', ep, quiet) pass3 = ac.areEpsilonEqual(pAUC_sum , AUC, 'pAUC_sum', 'AUC', ep, quiet) pass4 = ac.areEpsilonEqual(pAUCx_sum, AUC, 'pAUCx_sum', 'AUC', ep, quiet) if sanityCheckWholeAUC: passALLeq = passALLeq and pass1 and pass2 and pass3 and pass4 else: passALLeq = passALLeq and pass2 and pass3 and pass4 #endif return resultsPerGroup, passALLeq #enddef
# deepROC.py # # Copyright 2021 Ottawa Hospital Research Institute # # 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. # # Revision history: # Original Matlab version by Andre Carrington, 2018 # Ported to Python by Yusuf Sheikh and Andre Carrington, 2020 # Imports the Transcript class # Additions and corrections from Partial-AUC-C to create DeepROC by Andre Carrington, 2021 # # Functions: # makeLabels01 # getSkewWithRates # getSkew # distance_point_to_line # optimal_ROC_point_indices # getListValuesByIndex # computeCalibrationCurve # plotCalibrationCurve # calibrationOK # doCalibration # doAdvancedMeasures # deepROC # # inputs: testNum, verbose # outputs: results displayed and logged to a file # # Uses test vectors from Fawcett[1], Hilden[2], Carrington et al[3] # This function runs tests that compute expected equalities for whole # and partial AUC and c statistic measures discussed in Carrington # et al [3]. It uses the trapezoid rule to compute area. # # Whole measures: AUC, c # Partial measures: pAUCc, cDelta, pAUC (pAUCy), pAUCx # Normalized partial: pAUCcn, cDeltan, pAUCn, pAUCxn, cLocal # # References: # 1. Fawcett T. An Introduction to ROC Analysis, Pattern # Recognition Letters, 2005. # 2. Hilden J. The Area under the ROC Curve and Its Competitors, # Medical Decision Making, 1991. # 3. Carrington AM, Fieguth P, Qazi H, Holzinger A, Chen H, Mayr F # Manuel D. A new concordant partial AUC and partial c statistic # for imbalanced data in the evaluation of machine learning # algorithms. BMC Medical Informatics and Decision Making, 2020. # # see beginning of runtime logic at the end of this file # runtime parameters # choose one of the following as input (file supercedes others if multiple): useFile = True useSingleTestVector = False useAllTestVectors = False # specify file input parameters mydata = ['040', '356', '529', '536', '581', '639', '643'] fileName = f'input-matlab/result{mydata[2]}.mat' # a matlab file (or future: csv file) for input scoreVarColumn = 'yscoreTest' # yscoreTest, yscore targetVarColumn = 'ytest' # ytest, yhatTest, yhat, ytrain #scoreVarColumn = 'yscore' # yscoreTest, yscore #targetVarColumn = 'yhat' # ytest, yhatTest, yhat, ytrain # specify single test vector input parameters singleTestVectorNum = 13 # which of 12 test vectors the function get_ROC_test_scores_labels_ranges below # choose data science parameters rangeAxis = 'FPR' # examine ranges (next) by FPR or TPR filePAUCranges = [[0.0, 1/3], [1/3, 2/3], [2/3, 1.0]] # ranges, as few or many as you like useCloseRangePoint = False # automatically alter the ranges to match with the closest points in data # useful if you want the discrete form of balanced accuracy to exactly match # because we don't bother to interpolate that one costs = dict(cFP=1, cFN=1, cTP=0, cTN=0) # specify relative costs explicitly (default shown) #costs = {} # use the default costs rates = False # treat costs as rates, e.g. cFPR (default False) # choose what to show sanityCheckWholeAUC = True showPlot = True showData = False showError = True # areas in ROC plots that represent error import do_pAUCc as ac import getPDF as acKDE import numpy as np import pandas as pd import scipy.io as sio import matplotlib.pyplot as plt import matplotlib.ticker as ticker import sklearn.calibration as cal from sklearn import metrics import time import math import transcript from os.path import splitext import ntpath import re # this function is a duplicate of the one in do_pAUCc.py def makeLabels01(labels, posclass): ''' insert docstring here ''' # STATUS: COMPLETE posIndex = list(np.argwhere(np.array(labels) == posclass).flatten()) negIndex = list(np.argwhere(np.array(labels) != posclass).flatten()) newlabels = labels.copy() for i in posIndex: newlabels[i] = 1 for i in negIndex: newlabels[i] = 0 return newlabels #enddef def getSkew_withRates(labels, posclass, quiet, rates=True, cFP=None, cFN=None, cTP=None, cTN=None): if rates is False: raise ValueError('rates should be True') cFPR, cFNR, cTPR, cTNR = (cFP, cFN, cTP, cTN) # these are rates return getSkew(labels, posclass, quiet, rates=rates, cFP=cFPR, cFN=cFNR, cTP=cTPR, cTN=cTNR) #enddef def getSkew(labels, posclass, quiet, rates=None, cFP=None, cFN=None, cTP=None, cTN=None): labels = makeLabels01(labels, posclass) # forces labels to the set {0,1} P = int(sum(labels)) # assumes labels are in set {0,1} N = len(labels) - P msg = '' if rates == None or rates == False: # assumes costs are counts not rates ratetxt = '' ratechr = '' else: # but also handles costs as rates if needed ratetxt = 'rate unit ' ratechr = 'R' # endif if cFP is None: msg = msg + f'\nCost of a false positive {ratetxt}(cFP{ratechr}): 1 (default, since not specified)' cFP = 1 else: msg = msg + f'\nCost of a false positive {ratetxt}(cFP{ratechr}): {cFP:0.1f}' # endif if cFN is None: msg = msg + f'\nCost of a false negative {ratetxt}(cFN{ratechr}): 1 (default, since not specified)' cFN = 1 else: msg = msg + f'\nCost of a false negative {ratetxt}(cFN{ratechr}): {cFN:0.1f}' # endif if cTP is None: msg = msg + f'\nCost of a true positive {ratetxt}(cTP{ratechr}): 0 (default, since not specified)' cTP = 0 else: msg = msg + f'\nCost of a true positive {ratetxt}(cTP{ratechr}): {cTP:0.1f}' # endif if cTN is None: msg = msg + f'\nCost of a true negative {ratetxt}(cTN{ratechr}): 0 (default, since not specified)' cTN = 0 else: msg = msg + f'\nCost of a true negative {ratetxt}(cTN{ratechr}): {cTN:0.1f}' # endif if len(msg) and not quiet: print(f'{msg}\n') #endif # assumes costs are counts (not rates) if rates == None or rates == False: skew = (N / P) * (cFP - cTN) / (cFN - cTP) else: cFPR, cFNR, cTPR, cTNR = (cFP, cFN, cTP, cTN) # these are rates skew = ((N / P)**2) * (cFPR - cTNR) / (cFNR - cTPR) # see paper by Carrington for derivation return skew, N, P #enddef def distance_point_to_line(qx, qy, px, py, m): # point p (px,py) and slope m define a line # query point q (qx,qy): how far is q from the line? if m == 0: # slope is zero (horizontal line), distance is vertical only return abs(qy-py) #raise ValueError('slope is zero') #endif if np.isinf(m): # slope is infinite (vertical line), distance is horizontal only return abs(qx-px) #raise ValueError('slope is infinite') #endif # line through p: y = m *(x-px)+py # perpendicular slope: -1/m # perpendicular line from q: y = (-1/m)*(x-qx)+qy # equate both lines to find intersection at (x0,y0) x0 = (m*px - py + qx/m + qy) / (m + 1/m) # then find y_0 using first line definition y0 = m*(x0-px) + py return math.sqrt( (qx-x0)**2 + (qy-y0)**2 ) #enddef def optimal_ROC_point_indices(fpr, tpr, skew): n = len(fpr) mindist = math.inf min_idx = [] # define a line with slope skew passing through the top-left ROC point (x,y)=(0,1) # for each point in (fpr,tpr) get the distance from that point to the line for i in np.arange(0, n): d = distance_point_to_line(fpr[i], tpr[i], 0, 1, skew) #print(f'd: {d}') if d == mindist: min_idx = min_idx + [i] elif d < mindist: mindist = d min_idx = [i] #endif #endif # now min_idx contains the indices for the point(s) with the minimum distance # return those indices for the optimal ROC points return min_idx #enddef def getListValuesByIndex(a, idx_list): b = [] for i in idx_list: b = b + [a[i]] return b # enddef def computeCalibrationCurve(plotTitle, dataTitle, quiet, params): prob_true, prob_predicted = cal.calibration_curve(**params) # cal.calibration_curve(labels, scores, normalize=False, strategy=strategy, n_bins=bins) actual_bins = len(prob_true) bins = params['n_bins'] if bins > actual_bins and not quiet: print(f'Used {actual_bins} bins instead of the {bins} bins requested.') #endif # plt.plot(prob_predicted, prob_true, "s-", label=dataTitle) # plt.xlabel('Predicted risk/probability') # plt.ylabel('Observed risk/probability') return prob_predicted, prob_true # enddef def plotCalibrationCurve(plotTitle, dataTitle, quiet, params): prob_true, prob_predicted = \ cal.calibration_curve(**params) #cal.calibration_curve(labels, scores, normalize=False, strategy=strategy, n_bins=bins) actual_bins = len(prob_true) bins = params['n_bins'] if bins > actual_bins and not quiet: print(f'Used {actual_bins} bins instead of the {bins} bins requested.') #endif fig = plt.figure() ax = fig.add_subplot(1, 1, 1) plt.plot(prob_predicted, prob_true, "s-", label=dataTitle) plt.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated") plt.xlabel('Predicted risk/probability') plt.ylabel('Observed risk/probability') plt.title(plotTitle) plt.xlim(0.0, 1.0) plt.ylim(0.0, 1.0) ax.axes.xaxis.set_major_locator(ticker.MultipleLocator(0.1)) ax.axes.yaxis.set_major_locator(ticker.MultipleLocator(0.1)) plotGrey = lambda x, y: plt.fill(x, y, 'k', alpha=0.3, linewidth=None) x = [] y = [] shadeWidth = int(round(actual_bins / 3)) step = shadeWidth * 2 # 3 bins=skip 2; 6 bins=skip 4; 9 bins=skip 6 for i in range(0, actual_bins, step): x0 = i * 1/actual_bins x1 = (i+shadeWidth) * 1/actual_bins x = x + [x0] + [x0] + [x1] + [x1] y = y + [0] + [1] + [1] + [0] #endfor plotGrey(x, y) return fig, ax # enddef def calibrationOK(numScores, bins): if (numScores/25) >= bins: return 1 elif (numScores / 10) >= bins: return 0.5 else: return 0 #endif def doCalibration(scores, labels, posclass, fileNum, showPlot, quiet): scores, newlabels, labels = ac.sortScoresFixLabels(scores, labels, posclass, True) # True = ascending maxScore = float(max(scores)) minScore = float(min(scores)) if not quiet: print(f'Before: min,max = {minScore},{maxScore}') #endif scores_np = (np.array(scores) - minScore) / (maxScore - minScore) maxScore = float(max(scores_np)) minScore = float(min(scores_np)) if not quiet: print(f'After: min,max = {minScore},{maxScore}') #endif numScores = int(len(scores_np)) #Xc_cts, Y = acKDE.getPDF(scores_np, 'epanechnikov', 'new', quiet) #Y1D = Y[:, 0] #y2 = np.interp(scores_np, Xc_cts, Y1D) #if showPlot: # plt.plot(scores_np, y2) # plt.show() ##endif for bins in [3, 6, 9]: if calibrationOK(numScores, bins) == 0 and (not quiet): print(f'Not plotted: insufficient scores ({numScores}) for {bins} bins') else: plotTitle = f'Calibration plot with {bins} bins' dataTitle = 'Classifier' if calibrationOK(numScores, bins) == 0.5 and (not quiet): print(f'Plotted despite insufficient scores ({numScores}) for {bins} bins') # endif params = dict(y_true=newlabels, y_prob=scores_np, normalize=False, strategy='uniform', n_bins=bins) if showPlot: fig, ax = plotCalibrationCurve(plotTitle, dataTitle, quiet, params) else: prob_predicted, prob_true = computeCalibrationCurve(plotTitle, dataTitle, quiet, params) #endif if showPlot: plt.show() fig.savefig(f'output/calib_{fileNum}-{bins}.png') #endif # endif # endfor #enddef def deepROC(testNum='1', costs={}, sanityCheckWholeAUC=True, showPlot=True, showData=True, showError=True, globalP=1, globalN=1, useCloseRangePoint=False, pAUCranges={}, scores=[], labels=[], posclass=1, rangeAxis='FPR', quiet=False): doCalibration(scores, labels, posclass, testNum, showPlot, quiet) ep = 1*(10**-12) if ('rates' in costs) and costs['rates'] is True: skew, N, P = getSkew_withRates(labels, posclass, quiet, **costs) # **costs includes rates if not quiet: print(f'Skew (slope) = N * N * cFPR-cTNR = {skew:0.1f}') print( ' - - ---------') print( ' P P cFNR-cTPR') #endif else: skew, N, P = getSkew(labels, posclass, quiet, **costs) # **costs includes rates if not quiet: print(f'Skew (slope) = N * cFP-cTN = {skew:0.1f}') print( ' - -------') print( ' P cFN-cTP') #endif #endif if not quiet: print(' ') print(f"{'N':15s} = {N}") print(f"{'P':15s} = {P}") print(' ') #endif showThresh = 25 # show 20 scores per plot # Get standard fpr, tpr, thresholds from the labels scores fpr, tpr, thresholds = metrics.roc_curve(labels, scores, pos_label=posclass) # data are returned, sorted in ascending order by fpr, then tpr within fpr # note that this AUC may differ slightly from that obtained via full ROC #AUC = metrics.auc(fpr, tpr) # do not use this general auc function because it sometimes gives an error: # ValueError: x is neither increasing nor decreasing #AUC = metrics.roc_auc_score(labels, scores) #if not quiet: # print(f"{'Python AUC':15s} = {AUC:0.4f}") ##endif # Get and show the optimal ROC points (per Metz) opt_idx = optimal_ROC_point_indices(fpr, tpr, skew) fpr_opt = getListValuesByIndex(fpr, opt_idx) tpr_opt = getListValuesByIndex(tpr, opt_idx) thresh_opt = getListValuesByIndex(thresholds, opt_idx) if not quiet: for fprx, tprx, threshx in zip(fpr_opt, tpr_opt, thresh_opt): print(f"{'optimalROCpoint':15s} = ({fprx:0.4f},{tprx:0.4f}) at threshold: {threshx:0.4f}") #endfor #endif pAUCranges_copy = pAUCranges.copy() if sanityCheckWholeAUC == True: pAUCranges_copy.insert(0, [0, 1]) indices = np.arange(0, len(pAUCranges_copy)) # include index 0 as wholeAUC else: indices = np.arange(1, len(pAUCranges_copy)+1) # index 1,2,... for partial curves #endif if not quiet: print(f'indices: {indices}') #endif passALLeq = True; cDelta_sum = 0; pAUC_sum = 0; pAUCx_sum = 0; cpAUC_sum = 0 resultsPerGroup = [] for pAUCrange, index in zip(pAUCranges_copy, indices): passEQ, cDelta, cpAUC, pAUC, pAUCx, cDeltan, cpAUCn, pAUCn, pAUCxn, extras_dict \ = ac.do_pAUCc(mode='testing', index=index, pAUCrange=pAUCrange, labels=labels, scores=scores, posclass=posclass, fpr=fpr, tpr=tpr, thresh=thresholds, fpr_opt=fpr_opt, tpr_opt=tpr_opt, thresh_opt=thresh_opt, numShowThresh=showThresh, testNum=testNum, showPlot=showPlot, showData=showData, showError=showError, globalP=globalP, globalN=globalN, ep=ep, rangeAxis=rangeAxis, useCloseRangePoint=useCloseRangePoint, quiet=quiet) main_result_dict = dict(cDelta=cDelta, cpAUC=cpAUC, pAUC=pAUC, pAUCx=pAUCx, cDeltan=cDeltan, cpAUCn=cpAUCn, pAUCn=pAUCn, pAUCxn=pAUCxn, passEQ=passEQ) main_result_dict.update(extras_dict) resultsPerGroup.append(main_result_dict) passALLeq = passALLeq and passEQ if index > 0: cDelta_sum = cDelta_sum + cDelta cpAUC_sum = cpAUC_sum + cpAUC pAUC_sum = pAUC_sum + pAUC pAUCx_sum = pAUCx_sum + pAUCx #endif if index == 0: AUC = extras_dict['AUC'] c = extras_dict['c'] #endif #endfor if ~quiet: print(' ') #endif # code to check for PASS here if sanityCheckWholeAUC: pass1 = ac.areEpsilonEqual(cDelta_sum, c, 'cDelta_sum', 'c', ep, quiet) #endif pass2 = ac.areEpsilonEqual(cpAUC_sum, AUC, 'cpAUC_sum', 'AUC', ep, quiet) pass3 = ac.areEpsilonEqual(pAUC_sum , AUC, 'pAUC_sum', 'AUC', ep, quiet) pass4 = ac.areEpsilonEqual(pAUCx_sum, AUC, 'pAUCx_sum', 'AUC', ep, quiet) if sanityCheckWholeAUC: passALLeq = passALLeq and pass1 and pass2 and pass3 and pass4 else: passALLeq = passALLeq and pass2 and pass3 and pass4 #endif return resultsPerGroup, passALLeq #enddef
""" Copyright (c) 2020-2021 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import hashlib import logging import os import requests import subprocess import yaml from tempfile import NamedTemporaryFile def sha256sum(filename): """ Computes sha256sum. """ h = hashlib.sha256() b = bytearray(128 * 1024) mv = memoryview(b) with open(filename, 'rb', buffering=0) as f: for n in iter(lambda: f.readinto(mv), 0): h.update(mv[:n]) return h.hexdigest() def get_file_size_and_sha256(snapshot): """ Gets size and sha256 of a file. """ return { 'sha256': sha256sum(snapshot), 'size': os.path.getsize(snapshot), 'name': os.path.basename(snapshot), 'source': snapshot } def get_work_dir(cfg, update_config): overridden_work_dir = update_config.get('work_dir', None) return overridden_work_dir[0][1] if overridden_work_dir else cfg.work_dir def download_snapshot_if_not_yet(template_file, output_folder): with open(template_file) as read_file: content = yaml.load(read_file, yaml.SafeLoader) for dependency in content['dependencies']: destination = dependency['destination'] if destination == 'snapshot.pth': source = dependency['source'] expected_size = dependency['size'] expected_sha256 = dependency['sha256'] if os.path.exists(os.path.join(output_folder, destination)): actual = get_file_size_and_sha256(os.path.join(output_folder, destination)) if expected_size == actual['size'] and expected_sha256 == actual['sha256']: logging.info(f'{source} has been already downloaded.') return logging.info(f'Downloading {source}') destination_file = os.path.join(output_folder, destination) if 'google.com' in source: file_id = source.split('id=')[-1] session = requests.Session() gdrive_url = 'https://docs.google.com/uc?export=download' response = session.get(gdrive_url, params={'id': file_id}, stream=True) response.raise_for_status() for key, value in response.cookies.items(): if key.startswith('download_warning'): response = session.get(gdrive_url, params={'id': file_id, 'confirm': value}, stream=True) response.raise_for_status() with open(destination_file, 'wb') as f: f.write(response.content) else: subprocess.run(f'wget -q -O {destination_file} {source}', check=True, shell=True) logging.info(f'Downloading {source} has been completed.') actual = get_file_size_and_sha256(os.path.join(output_folder, destination)) assert expected_size == actual['size'], f'{template_file} actual_size {actual['size']}' assert expected_sha256 == actual['sha256'], f'{template_file} actual_sha256 {actual['sha256']}' return raise RuntimeError('Failed to find snapshot.pth') def convert_bash_command_for_log(cmd): if not cmd: return '' if isinstance(cmd, list): cmd = ' '.join(cmd) cmd = cmd.replace(';', '; ') cmd = cmd.split() if len(cmd) == 1: return cmd[0] shift_str = ' ' * 4 split_str = ' \\\n' + shift_str semicolon_split_str = ' \\\n' max_line_len = 40 max_chunk_len_to_keep_line = 30 min_line_len_to_split_big_chunk = 10 cur_line = cmd[0] cmdstr = '' for chunk in cmd[1:]: assert chunk if len(cur_line) > max_line_len: cmdstr += cur_line + split_str cur_line = '' if cur_line and chunk.startswith('--'): cmdstr += cur_line + split_str cur_line = '' if cur_line and chunk.startswith('|'): cmdstr += cur_line + split_str cur_line = '' if (cur_line and len(chunk) > max_chunk_len_to_keep_line and len(cur_line) >= min_line_len_to_split_big_chunk): cmdstr += cur_line + split_str cur_line = '' if cur_line: cur_line += ' ' cur_line += chunk if cur_line.endswith(';'): cmdstr += cur_line + semicolon_split_str cur_line = '' cmdstr += cur_line while cmdstr.endswith(' ') or cmdstr.endswith('\n'): cmdstr = cmdstr[:-1] return cmdstr def log_shell_cmd(cmd, prefix='Running through shell cmd'): cmdstr = convert_bash_command_for_log(cmd) logging.debug(f'{prefix}\n`{cmdstr}\n`') def run_through_shell(cmd, verbose=True, check=True): assert isinstance(cmd, str) log_shell_cmd(cmd) std_streams_args = {} if verbose else {'stdout': subprocess.DEVNULL, 'stderr': subprocess.DEVNULL} return subprocess.run(cmd, shell=True, check=check, executable="/bin/bash", **std_streams_args) def get_cuda_device_count(): # move `import torch` inside this function to import the function in ote venv import torch if torch.cuda.is_available(): return torch.cuda.device_count() return 0 def generate_random_suffix(): random_suffix = os.path.basename(NamedTemporaryFile().name) prefix = 'tmp' if random_suffix.startswith(prefix): random_suffix = random_suffix[len(prefix):] return random_suffix
""" Copyright (c) 2020-2021 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import hashlib import logging import os import requests import subprocess import yaml from tempfile import NamedTemporaryFile def sha256sum(filename): """ Computes sha256sum. """ h = hashlib.sha256() b = bytearray(128 * 1024) mv = memoryview(b) with open(filename, 'rb', buffering=0) as f: for n in iter(lambda: f.readinto(mv), 0): h.update(mv[:n]) return h.hexdigest() def get_file_size_and_sha256(snapshot): """ Gets size and sha256 of a file. """ return { 'sha256': sha256sum(snapshot), 'size': os.path.getsize(snapshot), 'name': os.path.basename(snapshot), 'source': snapshot } def get_work_dir(cfg, update_config): overridden_work_dir = update_config.get('work_dir', None) return overridden_work_dir[0][1] if overridden_work_dir else cfg.work_dir def download_snapshot_if_not_yet(template_file, output_folder): with open(template_file) as read_file: content = yaml.load(read_file, yaml.SafeLoader) for dependency in content['dependencies']: destination = dependency['destination'] if destination == 'snapshot.pth': source = dependency['source'] expected_size = dependency['size'] expected_sha256 = dependency['sha256'] if os.path.exists(os.path.join(output_folder, destination)): actual = get_file_size_and_sha256(os.path.join(output_folder, destination)) if expected_size == actual['size'] and expected_sha256 == actual['sha256']: logging.info(f'{source} has been already downloaded.') return logging.info(f'Downloading {source}') destination_file = os.path.join(output_folder, destination) if 'google.com' in source: file_id = source.split('id=')[-1] session = requests.Session() gdrive_url = 'https://docs.google.com/uc?export=download' response = session.get(gdrive_url, params={'id': file_id}, stream=True) response.raise_for_status() for key, value in response.cookies.items(): if key.startswith('download_warning'): response = session.get(gdrive_url, params={'id': file_id, 'confirm': value}, stream=True) response.raise_for_status() with open(destination_file, 'wb') as f: f.write(response.content) else: subprocess.run(f'wget -q -O {destination_file} {source}', check=True, shell=True) logging.info(f'Downloading {source} has been completed.') actual = get_file_size_and_sha256(os.path.join(output_folder, destination)) assert expected_size == actual['size'], f'{template_file} actual_size {actual["size"]}' assert expected_sha256 == actual['sha256'], f'{template_file} actual_sha256 {actual["sha256"]}' return raise RuntimeError('Failed to find snapshot.pth') def convert_bash_command_for_log(cmd): if not cmd: return '' if isinstance(cmd, list): cmd = ' '.join(cmd) cmd = cmd.replace(';', '; ') cmd = cmd.split() if len(cmd) == 1: return cmd[0] shift_str = ' ' * 4 split_str = ' \\\n' + shift_str semicolon_split_str = ' \\\n' max_line_len = 40 max_chunk_len_to_keep_line = 30 min_line_len_to_split_big_chunk = 10 cur_line = cmd[0] cmdstr = '' for chunk in cmd[1:]: assert chunk if len(cur_line) > max_line_len: cmdstr += cur_line + split_str cur_line = '' if cur_line and chunk.startswith('--'): cmdstr += cur_line + split_str cur_line = '' if cur_line and chunk.startswith('|'): cmdstr += cur_line + split_str cur_line = '' if (cur_line and len(chunk) > max_chunk_len_to_keep_line and len(cur_line) >= min_line_len_to_split_big_chunk): cmdstr += cur_line + split_str cur_line = '' if cur_line: cur_line += ' ' cur_line += chunk if cur_line.endswith(';'): cmdstr += cur_line + semicolon_split_str cur_line = '' cmdstr += cur_line while cmdstr.endswith(' ') or cmdstr.endswith('\n'): cmdstr = cmdstr[:-1] return cmdstr def log_shell_cmd(cmd, prefix='Running through shell cmd'): cmdstr = convert_bash_command_for_log(cmd) logging.debug(f'{prefix}\n`{cmdstr}\n`') def run_through_shell(cmd, verbose=True, check=True): assert isinstance(cmd, str) log_shell_cmd(cmd) std_streams_args = {} if verbose else {'stdout': subprocess.DEVNULL, 'stderr': subprocess.DEVNULL} return subprocess.run(cmd, shell=True, check=check, executable="/bin/bash", **std_streams_args) def get_cuda_device_count(): # move `import torch` inside this function to import the function in ote venv import torch if torch.cuda.is_available(): return torch.cuda.device_count() return 0 def generate_random_suffix(): random_suffix = os.path.basename(NamedTemporaryFile().name) prefix = 'tmp' if random_suffix.startswith(prefix): random_suffix = random_suffix[len(prefix):] return random_suffix
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from decimal import Decimal from bitarray import bitarray import __builtin__ class port(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module brocade-xstp-ext - based on the path /brocade_xstp_ext_rpc/get-stp-brief-info/output/spanning-tree-info/pvstp/port. Each member element of the container is represented as a class variable - with a specific YANG type. """ __slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__interface_type','__interface_name','__spanningtree_enabled','__if_index','__interface_id','__if_role','__if_state','__external_path_cost','__internal_path_cost','__configured_path_cost','__designated_port_id','__port_priority','__designated_bridge_id','__port_hello_time','__forward_transitions_count','__received_stp_type','__transmitted_stp_type','__edge_port','__auto_edge','__admin_edge','__edge_delay','__configured_root_guard','__oper_root_guard','__boundary_port','__oper_bpdu_guard','__link_type','__rx_bpdu_count','__tx_bpdu_count',) _yang_name = 'port' _rest_name = 'port' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): path_helper_ = kwargs.pop("path_helper", None) if path_helper_ is False: self._path_helper = False elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper): self._path_helper = path_helper_ elif hasattr(self, "_parent"): path_helper_ = getattr(self._parent, "_path_helper", False) self._path_helper = path_helper_ else: self._path_helper = False extmethods = kwargs.pop("extmethods", None) if extmethods is False: self._extmethods = False elif extmethods is not None and isinstance(extmethods, dict): self._extmethods = extmethods elif hasattr(self, "_parent"): extmethods = getattr(self._parent, "_extmethods", None) self._extmethods = extmethods else: self._extmethods = False self.__boundary_port = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="boundary-port", rest_name="boundary-port", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True) self.__internal_path_cost = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="internal-path-cost", rest_name="internal-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) self.__if_state = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'listening': {'value': 4}, u'discarding': {'value': 7}, u'disabled': {'value': 2}, u'learning': {'value': 5}, u'error': {'value': 1}, u'forwarding': {'value': 6}, u'blocking': {'value': 3}},), is_leaf=True, yang_name="if-state", rest_name="if-state", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-port-state', is_config=True) self.__interface_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u've': {'value': 8}, u'loopback': {'value': 7}, u'tunnel': {'value': 12}, u'unknown': {'value': 1}, u'port-channel': {'value': 5}, u'fibrechannel': {'value': 11}, u'ethernet': {'value': 10}, u'l2vlan': {'value': 6}},), is_leaf=True, yang_name="interface-type", rest_name="interface-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u"The type of the interface. An 'unknown' type \nrepresents error scenario and should not be used."}}, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='enumeration', is_config=True) self.__forward_transitions_count = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="forward-transitions-count", rest_name="forward-transitions-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) self.__transmitted_stp_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'none': {'value': 1}, u'rstp': {'value': 3}, u'mstp': {'value': 4}, u'rpvstp': {'value': 6}, u'pvstp': {'value': 5}, u'stp': {'value': 2}},), is_leaf=True, yang_name="transmitted-stp-type", rest_name="transmitted-stp-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-type', is_config=True) self.__interface_id = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="interface-id", rest_name="interface-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) self.__port_hello_time = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="port-hello-time", rest_name="port-hello-time", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) self.__if_index = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="if-index", rest_name="if-index", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) self.__external_path_cost = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="external-path-cost", rest_name="external-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) self.__designated_bridge_id = YANGDynClass(base=unicode, is_leaf=True, yang_name="designated-bridge-id", rest_name="designated-bridge-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='bridge-id-type', is_config=True) self.__tx_bpdu_count = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-bpdu-count", rest_name="tx-bpdu-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) self.__received_stp_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'none': {'value': 1}, u'rstp': {'value': 3}, u'mstp': {'value': 4}, u'rpvstp': {'value': 6}, u'pvstp': {'value': 5}, u'stp': {'value': 2}},), is_leaf=True, yang_name="received-stp-type", rest_name="received-stp-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-type', is_config=True) self.__configured_root_guard = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="configured-root-guard", rest_name="configured-root-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) self.__edge_port = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="edge-port", rest_name="edge-port", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) self.__interface_name = YANGDynClass(base=[RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'((([0-9]|[1][0-6]))/([1-9]|[1-9][0-9]|[1-9][0-9][0-9])(:[1-4])?)', 'length': [u'3..16']}),RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..1024']}),RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..4090']}),], is_leaf=True, yang_name="interface-name", rest_name="interface-name", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u'The Interface value.'}}, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='union', is_config=True) self.__configured_path_cost = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="configured-path-cost", rest_name="configured-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) self.__link_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'shared': {'value': 2}, u'point-to-point': {'value': 1}},), is_leaf=True, yang_name="link-type", rest_name="link-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-link-type', is_config=True) self.__admin_edge = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="admin-edge", rest_name="admin-edge", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True) self.__spanningtree_enabled = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="spanningtree-enabled", rest_name="spanningtree-enabled", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='boolean', is_config=True) self.__port_priority = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="port-priority", rest_name="port-priority", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) self.__rx_bpdu_count = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-bpdu-count", rest_name="rx-bpdu-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) self.__designated_port_id = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="designated-port-id", rest_name="designated-port-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) self.__auto_edge = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="auto-edge", rest_name="auto-edge", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True) self.__edge_delay = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="edge-delay", rest_name="edge-delay", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) self.__oper_bpdu_guard = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="oper-bpdu-guard", rest_name="oper-bpdu-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) self.__oper_root_guard = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="oper-root-guard", rest_name="oper-root-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) self.__if_role = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'backup': {'value': 5}, u'alternate': {'value': 4}, u'designated': {'value': 2}, u'disabled': {'value': 6}, u'master': {'value': 7}, u'error': {'value': 1}, u'root': {'value': 3}},), is_leaf=True, yang_name="if-role", rest_name="if-role", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-port-role', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return [u'brocade_xstp_ext_rpc', u'get-stp-brief-info', u'output', u'spanning-tree-info', u'pvstp', u'port'] def _rest_path(self): if hasattr(self, "_parent"): if self._rest_name: return self._parent._rest_path()+[self._rest_name] else: return self._parent._rest_path() else: return [u'get-stp-brief-info', u'output', u'spanning-tree-info', u'pvstp', u'port'] def _get_interface_type(self): """ Getter method for interface_type, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/interface_type (enumeration) YANG Description: The type of the interface. An 'unknown' type represents error scenario and should not be used. """ return self.__interface_type def _set_interface_type(self, v, load=False): """ Setter method for interface_type, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/interface_type (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_interface_type is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_interface_type() directly. YANG Description: The type of the interface. An 'unknown' type represents error scenario and should not be used. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u've': {'value': 8}, u'loopback': {'value': 7}, u'tunnel': {'value': 12}, u'unknown': {'value': 1}, u'port-channel': {'value': 5}, u'fibrechannel': {'value': 11}, u'ethernet': {'value': 10}, u'l2vlan': {'value': 6}},), is_leaf=True, yang_name="interface-type", rest_name="interface-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u"The type of the interface. An 'unknown' type \nrepresents error scenario and should not be used."}}, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='enumeration', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """interface_type must be of a type compatible with enumeration""", 'defined-type': "brocade-xstp-ext:enumeration", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u've': {'value': 8}, u'loopback': {'value': 7}, u'tunnel': {'value': 12}, u'unknown': {'value': 1}, u'port-channel': {'value': 5}, u'fibrechannel': {'value': 11}, u'ethernet': {'value': 10}, u'l2vlan': {'value': 6}},), is_leaf=True, yang_name="interface-type", rest_name="interface-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u"The type of the interface. An 'unknown' type \nrepresents error scenario and should not be used."}}, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='enumeration', is_config=True)""", }) self.__interface_type = t if hasattr(self, '_set'): self._set() def _unset_interface_type(self): self.__interface_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u've': {'value': 8}, u'loopback': {'value': 7}, u'tunnel': {'value': 12}, u'unknown': {'value': 1}, u'port-channel': {'value': 5}, u'fibrechannel': {'value': 11}, u'ethernet': {'value': 10}, u'l2vlan': {'value': 6}},), is_leaf=True, yang_name="interface-type", rest_name="interface-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u"The type of the interface. An 'unknown' type \nrepresents error scenario and should not be used."}}, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='enumeration', is_config=True) def _get_interface_name(self): """ Getter method for interface_name, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/interface_name (union) YANG Description: The Interface value. The interface value is always interpreted within the context of the value of 'interface-type' leaf: interface-type interface-name ----------------- -------------------- ethernet slot/port port-channel Port channel ID l2vlan Vlan ID loopback Loopback ID ve VE Interface ID unknown Zero-length string. The value of an 'interface-name' must always be consistent with the value of the associated 'interface-type'. Attempts to set an interface-name to a value inconsistent with the associated 'interface-type' must fail with an error. """ return self.__interface_name def _set_interface_name(self, v, load=False): """ Setter method for interface_name, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/interface_name (union) If this variable is read-only (config: false) in the source YANG file, then _set_interface_name is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_interface_name() directly. YANG Description: The Interface value. The interface value is always interpreted within the context of the value of 'interface-type' leaf: interface-type interface-name ----------------- -------------------- ethernet slot/port port-channel Port channel ID l2vlan Vlan ID loopback Loopback ID ve VE Interface ID unknown Zero-length string. The value of an 'interface-name' must always be consistent with the value of the associated 'interface-type'. Attempts to set an interface-name to a value inconsistent with the associated 'interface-type' must fail with an error. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=[RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'((([0-9]|[1][0-6]))/([1-9]|[1-9][0-9]|[1-9][0-9][0-9])(:[1-4])?)', 'length': [u'3..16']}),RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..1024']}),RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..4090']}),], is_leaf=True, yang_name="interface-name", rest_name="interface-name", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u'The Interface value.'}}, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='union', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """interface_name must be of a type compatible with union""", 'defined-type': "brocade-xstp-ext:union", 'generated-type': """YANGDynClass(base=[RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'((([0-9]|[1][0-6]))/([1-9]|[1-9][0-9]|[1-9][0-9][0-9])(:[1-4])?)', 'length': [u'3..16']}),RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..1024']}),RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..4090']}),], is_leaf=True, yang_name="interface-name", rest_name="interface-name", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u'The Interface value.'}}, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='union', is_config=True)""", }) self.__interface_name = t if hasattr(self, '_set'): self._set() def _unset_interface_name(self): self.__interface_name = YANGDynClass(base=[RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'((([0-9]|[1][0-6]))/([1-9]|[1-9][0-9]|[1-9][0-9][0-9])(:[1-4])?)', 'length': [u'3..16']}),RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..1024']}),RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..4090']}),], is_leaf=True, yang_name="interface-name", rest_name="interface-name", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u'The Interface value.'}}, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='union', is_config=True) def _get_spanningtree_enabled(self): """ Getter method for spanningtree_enabled, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/spanningtree_enabled (boolean) YANG Description: Is spanning tree enabled """ return self.__spanningtree_enabled def _set_spanningtree_enabled(self, v, load=False): """ Setter method for spanningtree_enabled, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/spanningtree_enabled (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_spanningtree_enabled is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_spanningtree_enabled() directly. YANG Description: Is spanning tree enabled """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="spanningtree-enabled", rest_name="spanningtree-enabled", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """spanningtree_enabled must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="spanningtree-enabled", rest_name="spanningtree-enabled", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='boolean', is_config=True)""", }) self.__spanningtree_enabled = t if hasattr(self, '_set'): self._set() def _unset_spanningtree_enabled(self): self.__spanningtree_enabled = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="spanningtree-enabled", rest_name="spanningtree-enabled", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='boolean', is_config=True) def _get_if_index(self): """ Getter method for if_index, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/if_index (uint64) YANG Description: Interface index """ return self.__if_index def _set_if_index(self, v, load=False): """ Setter method for if_index, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/if_index (uint64) If this variable is read-only (config: false) in the source YANG file, then _set_if_index is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_if_index() directly. YANG Description: Interface index """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="if-index", rest_name="if-index", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """if_index must be of a type compatible with uint64""", 'defined-type': "uint64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="if-index", rest_name="if-index", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True)""", }) self.__if_index = t if hasattr(self, '_set'): self._set() def _unset_if_index(self): self.__if_index = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="if-index", rest_name="if-index", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) def _get_interface_id(self): """ Getter method for interface_id, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/interface_id (uint64) YANG Description: Interface id """ return self.__interface_id def _set_interface_id(self, v, load=False): """ Setter method for interface_id, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/interface_id (uint64) If this variable is read-only (config: false) in the source YANG file, then _set_interface_id is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_interface_id() directly. YANG Description: Interface id """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="interface-id", rest_name="interface-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """interface_id must be of a type compatible with uint64""", 'defined-type': "uint64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="interface-id", rest_name="interface-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True)""", }) self.__interface_id = t if hasattr(self, '_set'): self._set() def _unset_interface_id(self): self.__interface_id = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="interface-id", rest_name="interface-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) def _get_if_role(self): """ Getter method for if_role, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/if_role (stp-port-role) YANG Description: Interface role """ return self.__if_role def _set_if_role(self, v, load=False): """ Setter method for if_role, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/if_role (stp-port-role) If this variable is read-only (config: false) in the source YANG file, then _set_if_role is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_if_role() directly. YANG Description: Interface role """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'backup': {'value': 5}, u'alternate': {'value': 4}, u'designated': {'value': 2}, u'disabled': {'value': 6}, u'master': {'value': 7}, u'error': {'value': 1}, u'root': {'value': 3}},), is_leaf=True, yang_name="if-role", rest_name="if-role", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-port-role', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """if_role must be of a type compatible with stp-port-role""", 'defined-type': "brocade-xstp-ext:stp-port-role", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'backup': {'value': 5}, u'alternate': {'value': 4}, u'designated': {'value': 2}, u'disabled': {'value': 6}, u'master': {'value': 7}, u'error': {'value': 1}, u'root': {'value': 3}},), is_leaf=True, yang_name="if-role", rest_name="if-role", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-port-role', is_config=True)""", }) self.__if_role = t if hasattr(self, '_set'): self._set() def _unset_if_role(self): self.__if_role = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'backup': {'value': 5}, u'alternate': {'value': 4}, u'designated': {'value': 2}, u'disabled': {'value': 6}, u'master': {'value': 7}, u'error': {'value': 1}, u'root': {'value': 3}},), is_leaf=True, yang_name="if-role", rest_name="if-role", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-port-role', is_config=True) def _get_if_state(self): """ Getter method for if_state, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/if_state (stp-port-state) YANG Description: Interface state """ return self.__if_state def _set_if_state(self, v, load=False): """ Setter method for if_state, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/if_state (stp-port-state) If this variable is read-only (config: false) in the source YANG file, then _set_if_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_if_state() directly. YANG Description: Interface state """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'listening': {'value': 4}, u'discarding': {'value': 7}, u'disabled': {'value': 2}, u'learning': {'value': 5}, u'error': {'value': 1}, u'forwarding': {'value': 6}, u'blocking': {'value': 3}},), is_leaf=True, yang_name="if-state", rest_name="if-state", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-port-state', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """if_state must be of a type compatible with stp-port-state""", 'defined-type': "brocade-xstp-ext:stp-port-state", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'listening': {'value': 4}, u'discarding': {'value': 7}, u'disabled': {'value': 2}, u'learning': {'value': 5}, u'error': {'value': 1}, u'forwarding': {'value': 6}, u'blocking': {'value': 3}},), is_leaf=True, yang_name="if-state", rest_name="if-state", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-port-state', is_config=True)""", }) self.__if_state = t if hasattr(self, '_set'): self._set() def _unset_if_state(self): self.__if_state = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'listening': {'value': 4}, u'discarding': {'value': 7}, u'disabled': {'value': 2}, u'learning': {'value': 5}, u'error': {'value': 1}, u'forwarding': {'value': 6}, u'blocking': {'value': 3}},), is_leaf=True, yang_name="if-state", rest_name="if-state", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-port-state', is_config=True) def _get_external_path_cost(self): """ Getter method for external_path_cost, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/external_path_cost (uint32) YANG Description: Designated external path cost """ return self.__external_path_cost def _set_external_path_cost(self, v, load=False): """ Setter method for external_path_cost, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/external_path_cost (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_external_path_cost is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_external_path_cost() directly. YANG Description: Designated external path cost """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="external-path-cost", rest_name="external-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """external_path_cost must be of a type compatible with uint32""", 'defined-type': "uint32", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="external-path-cost", rest_name="external-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True)""", }) self.__external_path_cost = t if hasattr(self, '_set'): self._set() def _unset_external_path_cost(self): self.__external_path_cost = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="external-path-cost", rest_name="external-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) def _get_internal_path_cost(self): """ Getter method for internal_path_cost, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/internal_path_cost (uint32) YANG Description: Designated internal path cost """ return self.__internal_path_cost def _set_internal_path_cost(self, v, load=False): """ Setter method for internal_path_cost, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/internal_path_cost (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_internal_path_cost is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_internal_path_cost() directly. YANG Description: Designated internal path cost """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="internal-path-cost", rest_name="internal-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """internal_path_cost must be of a type compatible with uint32""", 'defined-type': "uint32", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="internal-path-cost", rest_name="internal-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True)""", }) self.__internal_path_cost = t if hasattr(self, '_set'): self._set() def _unset_internal_path_cost(self): self.__internal_path_cost = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="internal-path-cost", rest_name="internal-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) def _get_configured_path_cost(self): """ Getter method for configured_path_cost, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/configured_path_cost (uint32) YANG Description: Configured path cost """ return self.__configured_path_cost def _set_configured_path_cost(self, v, load=False): """ Setter method for configured_path_cost, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/configured_path_cost (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_configured_path_cost is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_configured_path_cost() directly. YANG Description: Configured path cost """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="configured-path-cost", rest_name="configured-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """configured_path_cost must be of a type compatible with uint32""", 'defined-type': "uint32", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="configured-path-cost", rest_name="configured-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True)""", }) self.__configured_path_cost = t if hasattr(self, '_set'): self._set() def _unset_configured_path_cost(self): self.__configured_path_cost = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="configured-path-cost", rest_name="configured-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) def _get_designated_port_id(self): """ Getter method for designated_port_id, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/designated_port_id (uint64) YANG Description: Designated port id """ return self.__designated_port_id def _set_designated_port_id(self, v, load=False): """ Setter method for designated_port_id, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/designated_port_id (uint64) If this variable is read-only (config: false) in the source YANG file, then _set_designated_port_id is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_designated_port_id() directly. YANG Description: Designated port id """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="designated-port-id", rest_name="designated-port-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """designated_port_id must be of a type compatible with uint64""", 'defined-type': "uint64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="designated-port-id", rest_name="designated-port-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True)""", }) self.__designated_port_id = t if hasattr(self, '_set'): self._set() def _unset_designated_port_id(self): self.__designated_port_id = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="designated-port-id", rest_name="designated-port-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) def _get_port_priority(self): """ Getter method for port_priority, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/port_priority (uint32) YANG Description: Port priority """ return self.__port_priority def _set_port_priority(self, v, load=False): """ Setter method for port_priority, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/port_priority (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_port_priority is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_port_priority() directly. YANG Description: Port priority """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="port-priority", rest_name="port-priority", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """port_priority must be of a type compatible with uint32""", 'defined-type': "uint32", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="port-priority", rest_name="port-priority", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True)""", }) self.__port_priority = t if hasattr(self, '_set'): self._set() def _unset_port_priority(self): self.__port_priority = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="port-priority", rest_name="port-priority", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) def _get_designated_bridge_id(self): """ Getter method for designated_bridge_id, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/designated_bridge_id (bridge-id-type) YANG Description: Designated bridge Id """ return self.__designated_bridge_id def _set_designated_bridge_id(self, v, load=False): """ Setter method for designated_bridge_id, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/designated_bridge_id (bridge-id-type) If this variable is read-only (config: false) in the source YANG file, then _set_designated_bridge_id is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_designated_bridge_id() directly. YANG Description: Designated bridge Id """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=unicode, is_leaf=True, yang_name="designated-bridge-id", rest_name="designated-bridge-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='bridge-id-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """designated_bridge_id must be of a type compatible with bridge-id-type""", 'defined-type': "brocade-xstp-ext:bridge-id-type", 'generated-type': """YANGDynClass(base=unicode, is_leaf=True, yang_name="designated-bridge-id", rest_name="designated-bridge-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='bridge-id-type', is_config=True)""", }) self.__designated_bridge_id = t if hasattr(self, '_set'): self._set() def _unset_designated_bridge_id(self): self.__designated_bridge_id = YANGDynClass(base=unicode, is_leaf=True, yang_name="designated-bridge-id", rest_name="designated-bridge-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='bridge-id-type', is_config=True) def _get_port_hello_time(self): """ Getter method for port_hello_time, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/port_hello_time (uint32) YANG Description: Port hello time """ return self.__port_hello_time def _set_port_hello_time(self, v, load=False): """ Setter method for port_hello_time, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/port_hello_time (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_port_hello_time is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_port_hello_time() directly. YANG Description: Port hello time """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="port-hello-time", rest_name="port-hello-time", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """port_hello_time must be of a type compatible with uint32""", 'defined-type': "uint32", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="port-hello-time", rest_name="port-hello-time", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True)""", }) self.__port_hello_time = t if hasattr(self, '_set'): self._set() def _unset_port_hello_time(self): self.__port_hello_time = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="port-hello-time", rest_name="port-hello-time", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) def _get_forward_transitions_count(self): """ Getter method for forward_transitions_count, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/forward_transitions_count (uint32) YANG Description: Number of forward transitions """ return self.__forward_transitions_count def _set_forward_transitions_count(self, v, load=False): """ Setter method for forward_transitions_count, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/forward_transitions_count (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_forward_transitions_count is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_forward_transitions_count() directly. YANG Description: Number of forward transitions """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="forward-transitions-count", rest_name="forward-transitions-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """forward_transitions_count must be of a type compatible with uint32""", 'defined-type': "uint32", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="forward-transitions-count", rest_name="forward-transitions-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True)""", }) self.__forward_transitions_count = t if hasattr(self, '_set'): self._set() def _unset_forward_transitions_count(self): self.__forward_transitions_count = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="forward-transitions-count", rest_name="forward-transitions-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) def _get_received_stp_type(self): """ Getter method for received_stp_type, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/received_stp_type (stp-type) YANG Description: Received (rx) stp type """ return self.__received_stp_type def _set_received_stp_type(self, v, load=False): """ Setter method for received_stp_type, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/received_stp_type (stp-type) If this variable is read-only (config: false) in the source YANG file, then _set_received_stp_type is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_received_stp_type() directly. YANG Description: Received (rx) stp type """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'none': {'value': 1}, u'rstp': {'value': 3}, u'mstp': {'value': 4}, u'rpvstp': {'value': 6}, u'pvstp': {'value': 5}, u'stp': {'value': 2}},), is_leaf=True, yang_name="received-stp-type", rest_name="received-stp-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """received_stp_type must be of a type compatible with stp-type""", 'defined-type': "brocade-xstp-ext:stp-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'none': {'value': 1}, u'rstp': {'value': 3}, u'mstp': {'value': 4}, u'rpvstp': {'value': 6}, u'pvstp': {'value': 5}, u'stp': {'value': 2}},), is_leaf=True, yang_name="received-stp-type", rest_name="received-stp-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-type', is_config=True)""", }) self.__received_stp_type = t if hasattr(self, '_set'): self._set() def _unset_received_stp_type(self): self.__received_stp_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'none': {'value': 1}, u'rstp': {'value': 3}, u'mstp': {'value': 4}, u'rpvstp': {'value': 6}, u'pvstp': {'value': 5}, u'stp': {'value': 2}},), is_leaf=True, yang_name="received-stp-type", rest_name="received-stp-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-type', is_config=True) def _get_transmitted_stp_type(self): """ Getter method for transmitted_stp_type, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/transmitted_stp_type (stp-type) YANG Description: Transmitted (tx) stp type """ return self.__transmitted_stp_type def _set_transmitted_stp_type(self, v, load=False): """ Setter method for transmitted_stp_type, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/transmitted_stp_type (stp-type) If this variable is read-only (config: false) in the source YANG file, then _set_transmitted_stp_type is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_transmitted_stp_type() directly. YANG Description: Transmitted (tx) stp type """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'none': {'value': 1}, u'rstp': {'value': 3}, u'mstp': {'value': 4}, u'rpvstp': {'value': 6}, u'pvstp': {'value': 5}, u'stp': {'value': 2}},), is_leaf=True, yang_name="transmitted-stp-type", rest_name="transmitted-stp-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """transmitted_stp_type must be of a type compatible with stp-type""", 'defined-type': "brocade-xstp-ext:stp-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'none': {'value': 1}, u'rstp': {'value': 3}, u'mstp': {'value': 4}, u'rpvstp': {'value': 6}, u'pvstp': {'value': 5}, u'stp': {'value': 2}},), is_leaf=True, yang_name="transmitted-stp-type", rest_name="transmitted-stp-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-type', is_config=True)""", }) self.__transmitted_stp_type = t if hasattr(self, '_set'): self._set() def _unset_transmitted_stp_type(self): self.__transmitted_stp_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'none': {'value': 1}, u'rstp': {'value': 3}, u'mstp': {'value': 4}, u'rpvstp': {'value': 6}, u'pvstp': {'value': 5}, u'stp': {'value': 2}},), is_leaf=True, yang_name="transmitted-stp-type", rest_name="transmitted-stp-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-type', is_config=True) def _get_edge_port(self): """ Getter method for edge_port, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/edge_port (on-off-type) YANG Description: Edge Port mode """ return self.__edge_port def _set_edge_port(self, v, load=False): """ Setter method for edge_port, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/edge_port (on-off-type) If this variable is read-only (config: false) in the source YANG file, then _set_edge_port is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_edge_port() directly. YANG Description: Edge Port mode """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="edge-port", rest_name="edge-port", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """edge_port must be of a type compatible with on-off-type""", 'defined-type': "brocade-xstp-ext:on-off-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="edge-port", rest_name="edge-port", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True)""", }) self.__edge_port = t if hasattr(self, '_set'): self._set() def _unset_edge_port(self): self.__edge_port = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="edge-port", rest_name="edge-port", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) def _get_auto_edge(self): """ Getter method for auto_edge, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/auto_edge (yes-no-type) YANG Description: Auto Edge """ return self.__auto_edge def _set_auto_edge(self, v, load=False): """ Setter method for auto_edge, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/auto_edge (yes-no-type) If this variable is read-only (config: false) in the source YANG file, then _set_auto_edge is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_auto_edge() directly. YANG Description: Auto Edge """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="auto-edge", rest_name="auto-edge", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """auto_edge must be of a type compatible with yes-no-type""", 'defined-type': "brocade-xstp-ext:yes-no-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="auto-edge", rest_name="auto-edge", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True)""", }) self.__auto_edge = t if hasattr(self, '_set'): self._set() def _unset_auto_edge(self): self.__auto_edge = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="auto-edge", rest_name="auto-edge", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True) def _get_admin_edge(self): """ Getter method for admin_edge, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/admin_edge (yes-no-type) YANG Description: Admin Edge """ return self.__admin_edge def _set_admin_edge(self, v, load=False): """ Setter method for admin_edge, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/admin_edge (yes-no-type) If this variable is read-only (config: false) in the source YANG file, then _set_admin_edge is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_admin_edge() directly. YANG Description: Admin Edge """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="admin-edge", rest_name="admin-edge", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """admin_edge must be of a type compatible with yes-no-type""", 'defined-type': "brocade-xstp-ext:yes-no-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="admin-edge", rest_name="admin-edge", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True)""", }) self.__admin_edge = t if hasattr(self, '_set'): self._set() def _unset_admin_edge(self): self.__admin_edge = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="admin-edge", rest_name="admin-edge", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True) def _get_edge_delay(self): """ Getter method for edge_delay, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/edge_delay (uint32) YANG Description: Edge delay """ return self.__edge_delay def _set_edge_delay(self, v, load=False): """ Setter method for edge_delay, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/edge_delay (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_edge_delay is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_edge_delay() directly. YANG Description: Edge delay """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="edge-delay", rest_name="edge-delay", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """edge_delay must be of a type compatible with uint32""", 'defined-type': "uint32", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="edge-delay", rest_name="edge-delay", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True)""", }) self.__edge_delay = t if hasattr(self, '_set'): self._set() def _unset_edge_delay(self): self.__edge_delay = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="edge-delay", rest_name="edge-delay", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) def _get_configured_root_guard(self): """ Getter method for configured_root_guard, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/configured_root_guard (on-off-type) YANG Description: Configured root guard """ return self.__configured_root_guard def _set_configured_root_guard(self, v, load=False): """ Setter method for configured_root_guard, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/configured_root_guard (on-off-type) If this variable is read-only (config: false) in the source YANG file, then _set_configured_root_guard is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_configured_root_guard() directly. YANG Description: Configured root guard """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="configured-root-guard", rest_name="configured-root-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """configured_root_guard must be of a type compatible with on-off-type""", 'defined-type': "brocade-xstp-ext:on-off-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="configured-root-guard", rest_name="configured-root-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True)""", }) self.__configured_root_guard = t if hasattr(self, '_set'): self._set() def _unset_configured_root_guard(self): self.__configured_root_guard = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="configured-root-guard", rest_name="configured-root-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) def _get_oper_root_guard(self): """ Getter method for oper_root_guard, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/oper_root_guard (on-off-type) YANG Description: Operational root guard """ return self.__oper_root_guard def _set_oper_root_guard(self, v, load=False): """ Setter method for oper_root_guard, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/oper_root_guard (on-off-type) If this variable is read-only (config: false) in the source YANG file, then _set_oper_root_guard is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_oper_root_guard() directly. YANG Description: Operational root guard """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="oper-root-guard", rest_name="oper-root-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """oper_root_guard must be of a type compatible with on-off-type""", 'defined-type': "brocade-xstp-ext:on-off-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="oper-root-guard", rest_name="oper-root-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True)""", }) self.__oper_root_guard = t if hasattr(self, '_set'): self._set() def _unset_oper_root_guard(self): self.__oper_root_guard = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="oper-root-guard", rest_name="oper-root-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) def _get_boundary_port(self): """ Getter method for boundary_port, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/boundary_port (yes-no-type) YANG Description: Is boundary """ return self.__boundary_port def _set_boundary_port(self, v, load=False): """ Setter method for boundary_port, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/boundary_port (yes-no-type) If this variable is read-only (config: false) in the source YANG file, then _set_boundary_port is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_boundary_port() directly. YANG Description: Is boundary """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="boundary-port", rest_name="boundary-port", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """boundary_port must be of a type compatible with yes-no-type""", 'defined-type': "brocade-xstp-ext:yes-no-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="boundary-port", rest_name="boundary-port", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True)""", }) self.__boundary_port = t if hasattr(self, '_set'): self._set() def _unset_boundary_port(self): self.__boundary_port = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="boundary-port", rest_name="boundary-port", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True) def _get_oper_bpdu_guard(self): """ Getter method for oper_bpdu_guard, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/oper_bpdu_guard (on-off-type) YANG Description: Operational BPDU guard """ return self.__oper_bpdu_guard def _set_oper_bpdu_guard(self, v, load=False): """ Setter method for oper_bpdu_guard, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/oper_bpdu_guard (on-off-type) If this variable is read-only (config: false) in the source YANG file, then _set_oper_bpdu_guard is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_oper_bpdu_guard() directly. YANG Description: Operational BPDU guard """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="oper-bpdu-guard", rest_name="oper-bpdu-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """oper_bpdu_guard must be of a type compatible with on-off-type""", 'defined-type': "brocade-xstp-ext:on-off-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="oper-bpdu-guard", rest_name="oper-bpdu-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True)""", }) self.__oper_bpdu_guard = t if hasattr(self, '_set'): self._set() def _unset_oper_bpdu_guard(self): self.__oper_bpdu_guard = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="oper-bpdu-guard", rest_name="oper-bpdu-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) def _get_link_type(self): """ Getter method for link_type, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/link_type (stp-link-type) """ return self.__link_type def _set_link_type(self, v, load=False): """ Setter method for link_type, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/link_type (stp-link-type) If this variable is read-only (config: false) in the source YANG file, then _set_link_type is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_link_type() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'shared': {'value': 2}, u'point-to-point': {'value': 1}},), is_leaf=True, yang_name="link-type", rest_name="link-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-link-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """link_type must be of a type compatible with stp-link-type""", 'defined-type': "brocade-xstp-ext:stp-link-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'shared': {'value': 2}, u'point-to-point': {'value': 1}},), is_leaf=True, yang_name="link-type", rest_name="link-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-link-type', is_config=True)""", }) self.__link_type = t if hasattr(self, '_set'): self._set() def _unset_link_type(self): self.__link_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'shared': {'value': 2}, u'point-to-point': {'value': 1}},), is_leaf=True, yang_name="link-type", rest_name="link-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-link-type', is_config=True) def _get_rx_bpdu_count(self): """ Getter method for rx_bpdu_count, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/rx_bpdu_count (uint64) YANG Description: Received Bpdu count """ return self.__rx_bpdu_count def _set_rx_bpdu_count(self, v, load=False): """ Setter method for rx_bpdu_count, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/rx_bpdu_count (uint64) If this variable is read-only (config: false) in the source YANG file, then _set_rx_bpdu_count is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_rx_bpdu_count() directly. YANG Description: Received Bpdu count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-bpdu-count", rest_name="rx-bpdu-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """rx_bpdu_count must be of a type compatible with uint64""", 'defined-type': "uint64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-bpdu-count", rest_name="rx-bpdu-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True)""", }) self.__rx_bpdu_count = t if hasattr(self, '_set'): self._set() def _unset_rx_bpdu_count(self): self.__rx_bpdu_count = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-bpdu-count", rest_name="rx-bpdu-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) def _get_tx_bpdu_count(self): """ Getter method for tx_bpdu_count, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/tx_bpdu_count (uint64) YANG Description: Transmitted Bpdu count """ return self.__tx_bpdu_count def _set_tx_bpdu_count(self, v, load=False): """ Setter method for tx_bpdu_count, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/tx_bpdu_count (uint64) If this variable is read-only (config: false) in the source YANG file, then _set_tx_bpdu_count is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_tx_bpdu_count() directly. YANG Description: Transmitted Bpdu count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-bpdu-count", rest_name="tx-bpdu-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """tx_bpdu_count must be of a type compatible with uint64""", 'defined-type': "uint64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-bpdu-count", rest_name="tx-bpdu-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True)""", }) self.__tx_bpdu_count = t if hasattr(self, '_set'): self._set() def _unset_tx_bpdu_count(self): self.__tx_bpdu_count = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-bpdu-count", rest_name="tx-bpdu-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) interface_type = __builtin__.property(_get_interface_type, _set_interface_type) interface_name = __builtin__.property(_get_interface_name, _set_interface_name) spanningtree_enabled = __builtin__.property(_get_spanningtree_enabled, _set_spanningtree_enabled) if_index = __builtin__.property(_get_if_index, _set_if_index) interface_id = __builtin__.property(_get_interface_id, _set_interface_id) if_role = __builtin__.property(_get_if_role, _set_if_role) if_state = __builtin__.property(_get_if_state, _set_if_state) external_path_cost = __builtin__.property(_get_external_path_cost, _set_external_path_cost) internal_path_cost = __builtin__.property(_get_internal_path_cost, _set_internal_path_cost) configured_path_cost = __builtin__.property(_get_configured_path_cost, _set_configured_path_cost) designated_port_id = __builtin__.property(_get_designated_port_id, _set_designated_port_id) port_priority = __builtin__.property(_get_port_priority, _set_port_priority) designated_bridge_id = __builtin__.property(_get_designated_bridge_id, _set_designated_bridge_id) port_hello_time = __builtin__.property(_get_port_hello_time, _set_port_hello_time) forward_transitions_count = __builtin__.property(_get_forward_transitions_count, _set_forward_transitions_count) received_stp_type = __builtin__.property(_get_received_stp_type, _set_received_stp_type) transmitted_stp_type = __builtin__.property(_get_transmitted_stp_type, _set_transmitted_stp_type) edge_port = __builtin__.property(_get_edge_port, _set_edge_port) auto_edge = __builtin__.property(_get_auto_edge, _set_auto_edge) admin_edge = __builtin__.property(_get_admin_edge, _set_admin_edge) edge_delay = __builtin__.property(_get_edge_delay, _set_edge_delay) configured_root_guard = __builtin__.property(_get_configured_root_guard, _set_configured_root_guard) oper_root_guard = __builtin__.property(_get_oper_root_guard, _set_oper_root_guard) boundary_port = __builtin__.property(_get_boundary_port, _set_boundary_port) oper_bpdu_guard = __builtin__.property(_get_oper_bpdu_guard, _set_oper_bpdu_guard) link_type = __builtin__.property(_get_link_type, _set_link_type) rx_bpdu_count = __builtin__.property(_get_rx_bpdu_count, _set_rx_bpdu_count) tx_bpdu_count = __builtin__.property(_get_tx_bpdu_count, _set_tx_bpdu_count) __choices__ = {u'spanning-tree-mode': {u'pvstp': [u'interface_type', u'interface_name', u'spanningtree_enabled', u'if_index', u'interface_id', u'if_role', u'if_state', u'external_path_cost', u'internal_path_cost', u'configured_path_cost', u'designated_port_id', u'port_priority', u'designated_bridge_id', u'port_hello_time', u'forward_transitions_count', u'received_stp_type', u'transmitted_stp_type', u'edge_port', u'auto_edge', u'admin_edge', u'edge_delay', u'configured_root_guard', u'oper_root_guard', u'boundary_port', u'oper_bpdu_guard', u'link_type', u'rx_bpdu_count', u'tx_bpdu_count']}} _pyangbind_elements = {'interface_type': interface_type, 'interface_name': interface_name, 'spanningtree_enabled': spanningtree_enabled, 'if_index': if_index, 'interface_id': interface_id, 'if_role': if_role, 'if_state': if_state, 'external_path_cost': external_path_cost, 'internal_path_cost': internal_path_cost, 'configured_path_cost': configured_path_cost, 'designated_port_id': designated_port_id, 'port_priority': port_priority, 'designated_bridge_id': designated_bridge_id, 'port_hello_time': port_hello_time, 'forward_transitions_count': forward_transitions_count, 'received_stp_type': received_stp_type, 'transmitted_stp_type': transmitted_stp_type, 'edge_port': edge_port, 'auto_edge': auto_edge, 'admin_edge': admin_edge, 'edge_delay': edge_delay, 'configured_root_guard': configured_root_guard, 'oper_root_guard': oper_root_guard, 'boundary_port': boundary_port, 'oper_bpdu_guard': oper_bpdu_guard, 'link_type': link_type, 'rx_bpdu_count': rx_bpdu_count, 'tx_bpdu_count': tx_bpdu_count, }
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from decimal import Decimal from bitarray import bitarray import __builtin__ class port(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module brocade-xstp-ext - based on the path /brocade_xstp_ext_rpc/get-stp-brief-info/output/spanning-tree-info/pvstp/port. Each member element of the container is represented as a class variable - with a specific YANG type. """ __slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__interface_type','__interface_name','__spanningtree_enabled','__if_index','__interface_id','__if_role','__if_state','__external_path_cost','__internal_path_cost','__configured_path_cost','__designated_port_id','__port_priority','__designated_bridge_id','__port_hello_time','__forward_transitions_count','__received_stp_type','__transmitted_stp_type','__edge_port','__auto_edge','__admin_edge','__edge_delay','__configured_root_guard','__oper_root_guard','__boundary_port','__oper_bpdu_guard','__link_type','__rx_bpdu_count','__tx_bpdu_count',) _yang_name = 'port' _rest_name = 'port' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): path_helper_ = kwargs.pop("path_helper", None) if path_helper_ is False: self._path_helper = False elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper): self._path_helper = path_helper_ elif hasattr(self, "_parent"): path_helper_ = getattr(self._parent, "_path_helper", False) self._path_helper = path_helper_ else: self._path_helper = False extmethods = kwargs.pop("extmethods", None) if extmethods is False: self._extmethods = False elif extmethods is not None and isinstance(extmethods, dict): self._extmethods = extmethods elif hasattr(self, "_parent"): extmethods = getattr(self._parent, "_extmethods", None) self._extmethods = extmethods else: self._extmethods = False self.__boundary_port = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="boundary-port", rest_name="boundary-port", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True) self.__internal_path_cost = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="internal-path-cost", rest_name="internal-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) self.__if_state = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'listening': {'value': 4}, u'discarding': {'value': 7}, u'disabled': {'value': 2}, u'learning': {'value': 5}, u'error': {'value': 1}, u'forwarding': {'value': 6}, u'blocking': {'value': 3}},), is_leaf=True, yang_name="if-state", rest_name="if-state", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-port-state', is_config=True) self.__interface_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u've': {'value': 8}, u'loopback': {'value': 7}, u'tunnel': {'value': 12}, u'unknown': {'value': 1}, u'port-channel': {'value': 5}, u'fibrechannel': {'value': 11}, u'ethernet': {'value': 10}, u'l2vlan': {'value': 6}},), is_leaf=True, yang_name="interface-type", rest_name="interface-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u"The type of the interface. An 'unknown' type \nrepresents error scenario and should not be used."}}, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='enumeration', is_config=True) self.__forward_transitions_count = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="forward-transitions-count", rest_name="forward-transitions-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) self.__transmitted_stp_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'none': {'value': 1}, u'rstp': {'value': 3}, u'mstp': {'value': 4}, u'rpvstp': {'value': 6}, u'pvstp': {'value': 5}, u'stp': {'value': 2}},), is_leaf=True, yang_name="transmitted-stp-type", rest_name="transmitted-stp-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-type', is_config=True) self.__interface_id = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="interface-id", rest_name="interface-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) self.__port_hello_time = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="port-hello-time", rest_name="port-hello-time", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) self.__if_index = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="if-index", rest_name="if-index", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) self.__external_path_cost = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="external-path-cost", rest_name="external-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) self.__designated_bridge_id = YANGDynClass(base=unicode, is_leaf=True, yang_name="designated-bridge-id", rest_name="designated-bridge-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='bridge-id-type', is_config=True) self.__tx_bpdu_count = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-bpdu-count", rest_name="tx-bpdu-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) self.__received_stp_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'none': {'value': 1}, u'rstp': {'value': 3}, u'mstp': {'value': 4}, u'rpvstp': {'value': 6}, u'pvstp': {'value': 5}, u'stp': {'value': 2}},), is_leaf=True, yang_name="received-stp-type", rest_name="received-stp-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-type', is_config=True) self.__configured_root_guard = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="configured-root-guard", rest_name="configured-root-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) self.__edge_port = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="edge-port", rest_name="edge-port", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) self.__interface_name = YANGDynClass(base=[RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'((([0-9]|[1][0-6]))/([1-9]|[1-9][0-9]|[1-9][0-9][0-9])(:[1-4])?)', 'length': [u'3..16']}),RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..1024']}),RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..4090']}),], is_leaf=True, yang_name="interface-name", rest_name="interface-name", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u'The Interface value.'}}, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='union', is_config=True) self.__configured_path_cost = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="configured-path-cost", rest_name="configured-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) self.__link_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'shared': {'value': 2}, u'point-to-point': {'value': 1}},), is_leaf=True, yang_name="link-type", rest_name="link-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-link-type', is_config=True) self.__admin_edge = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="admin-edge", rest_name="admin-edge", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True) self.__spanningtree_enabled = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="spanningtree-enabled", rest_name="spanningtree-enabled", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='boolean', is_config=True) self.__port_priority = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="port-priority", rest_name="port-priority", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) self.__rx_bpdu_count = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-bpdu-count", rest_name="rx-bpdu-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) self.__designated_port_id = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="designated-port-id", rest_name="designated-port-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) self.__auto_edge = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="auto-edge", rest_name="auto-edge", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True) self.__edge_delay = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="edge-delay", rest_name="edge-delay", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) self.__oper_bpdu_guard = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="oper-bpdu-guard", rest_name="oper-bpdu-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) self.__oper_root_guard = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="oper-root-guard", rest_name="oper-root-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) self.__if_role = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'backup': {'value': 5}, u'alternate': {'value': 4}, u'designated': {'value': 2}, u'disabled': {'value': 6}, u'master': {'value': 7}, u'error': {'value': 1}, u'root': {'value': 3}},), is_leaf=True, yang_name="if-role", rest_name="if-role", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-port-role', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return [u'brocade_xstp_ext_rpc', u'get-stp-brief-info', u'output', u'spanning-tree-info', u'pvstp', u'port'] def _rest_path(self): if hasattr(self, "_parent"): if self._rest_name: return self._parent._rest_path()+[self._rest_name] else: return self._parent._rest_path() else: return [u'get-stp-brief-info', u'output', u'spanning-tree-info', u'pvstp', u'port'] def _get_interface_type(self): """ Getter method for interface_type, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/interface_type (enumeration) YANG Description: The type of the interface. An 'unknown' type represents error scenario and should not be used. """ return self.__interface_type def _set_interface_type(self, v, load=False): """ Setter method for interface_type, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/interface_type (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_interface_type is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_interface_type() directly. YANG Description: The type of the interface. An 'unknown' type represents error scenario and should not be used. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u've': {'value': 8}, u'loopback': {'value': 7}, u'tunnel': {'value': 12}, u'unknown': {'value': 1}, u'port-channel': {'value': 5}, u'fibrechannel': {'value': 11}, u'ethernet': {'value': 10}, u'l2vlan': {'value': 6}},), is_leaf=True, yang_name="interface-type", rest_name="interface-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u"The type of the interface. An 'unknown' type \nrepresents error scenario and should not be used."}}, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='enumeration', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """interface_type must be of a type compatible with enumeration""", 'defined-type': "brocade-xstp-ext:enumeration", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u've': {'value': 8}, u'loopback': {'value': 7}, u'tunnel': {'value': 12}, u'unknown': {'value': 1}, u'port-channel': {'value': 5}, u'fibrechannel': {'value': 11}, u'ethernet': {'value': 10}, u'l2vlan': {'value': 6}},), is_leaf=True, yang_name="interface-type", rest_name="interface-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u"The type of the interface. An 'unknown' type \nrepresents error scenario and should not be used."}}, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='enumeration', is_config=True)""", }) self.__interface_type = t if hasattr(self, '_set'): self._set() def _unset_interface_type(self): self.__interface_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u've': {'value': 8}, u'loopback': {'value': 7}, u'tunnel': {'value': 12}, u'unknown': {'value': 1}, u'port-channel': {'value': 5}, u'fibrechannel': {'value': 11}, u'ethernet': {'value': 10}, u'l2vlan': {'value': 6}},), is_leaf=True, yang_name="interface-type", rest_name="interface-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u"The type of the interface. An 'unknown' type \nrepresents error scenario and should not be used."}}, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='enumeration', is_config=True) def _get_interface_name(self): """ Getter method for interface_name, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/interface_name (union) YANG Description: The Interface value. The interface value is always interpreted within the context of the value of 'interface-type' leaf: interface-type interface-name ----------------- -------------------- ethernet slot/port port-channel Port channel ID l2vlan Vlan ID loopback Loopback ID ve VE Interface ID unknown Zero-length string. The value of an 'interface-name' must always be consistent with the value of the associated 'interface-type'. Attempts to set an interface-name to a value inconsistent with the associated 'interface-type' must fail with an error. """ return self.__interface_name def _set_interface_name(self, v, load=False): """ Setter method for interface_name, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/interface_name (union) If this variable is read-only (config: false) in the source YANG file, then _set_interface_name is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_interface_name() directly. YANG Description: The Interface value. The interface value is always interpreted within the context of the value of 'interface-type' leaf: interface-type interface-name ----------------- -------------------- ethernet slot/port port-channel Port channel ID l2vlan Vlan ID loopback Loopback ID ve VE Interface ID unknown Zero-length string. The value of an 'interface-name' must always be consistent with the value of the associated 'interface-type'. Attempts to set an interface-name to a value inconsistent with the associated 'interface-type' must fail with an error. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=[RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'((([0-9]|[1][0-6]))/([1-9]|[1-9][0-9]|[1-9][0-9][0-9])(:[1-4])?)', 'length': [u'3..16']}),RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..1024']}),RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..4090']}),], is_leaf=True, yang_name="interface-name", rest_name="interface-name", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u'The Interface value.'}}, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='union', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """interface_name must be of a type compatible with union""", 'defined-type': "brocade-xstp-ext:union", 'generated-type': """YANGDynClass(base=[RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'((([0-9]|[1][0-6]))/([1-9]|[1-9][0-9]|[1-9][0-9][0-9])(:[1-4])?)', 'length': [u'3..16']}),RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..1024']}),RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..4090']}),], is_leaf=True, yang_name="interface-name", rest_name="interface-name", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u'The Interface value.'}}, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='union', is_config=True)""", }) self.__interface_name = t if hasattr(self, '_set'): self._set() def _unset_interface_name(self): self.__interface_name = YANGDynClass(base=[RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'((([0-9]|[1][0-6]))/([1-9]|[1-9][0-9]|[1-9][0-9][0-9])(:[1-4])?)', 'length': [u'3..16']}),RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..1024']}),RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..4090']}),], is_leaf=True, yang_name="interface-name", rest_name="interface-name", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u'The Interface value.'}}, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='union', is_config=True) def _get_spanningtree_enabled(self): """ Getter method for spanningtree_enabled, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/spanningtree_enabled (boolean) YANG Description: Is spanning tree enabled """ return self.__spanningtree_enabled def _set_spanningtree_enabled(self, v, load=False): """ Setter method for spanningtree_enabled, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/spanningtree_enabled (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_spanningtree_enabled is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_spanningtree_enabled() directly. YANG Description: Is spanning tree enabled """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="spanningtree-enabled", rest_name="spanningtree-enabled", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """spanningtree_enabled must be of a type compatible with boolean""", 'defined-type': "boolean", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="spanningtree-enabled", rest_name="spanningtree-enabled", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='boolean', is_config=True)""", }) self.__spanningtree_enabled = t if hasattr(self, '_set'): self._set() def _unset_spanningtree_enabled(self): self.__spanningtree_enabled = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="spanningtree-enabled", rest_name="spanningtree-enabled", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='boolean', is_config=True) def _get_if_index(self): """ Getter method for if_index, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/if_index (uint64) YANG Description: Interface index """ return self.__if_index def _set_if_index(self, v, load=False): """ Setter method for if_index, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/if_index (uint64) If this variable is read-only (config: false) in the source YANG file, then _set_if_index is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_if_index() directly. YANG Description: Interface index """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="if-index", rest_name="if-index", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """if_index must be of a type compatible with uint64""", 'defined-type': "uint64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="if-index", rest_name="if-index", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True)""", }) self.__if_index = t if hasattr(self, '_set'): self._set() def _unset_if_index(self): self.__if_index = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="if-index", rest_name="if-index", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) def _get_interface_id(self): """ Getter method for interface_id, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/interface_id (uint64) YANG Description: Interface id """ return self.__interface_id def _set_interface_id(self, v, load=False): """ Setter method for interface_id, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/interface_id (uint64) If this variable is read-only (config: false) in the source YANG file, then _set_interface_id is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_interface_id() directly. YANG Description: Interface id """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="interface-id", rest_name="interface-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """interface_id must be of a type compatible with uint64""", 'defined-type': "uint64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="interface-id", rest_name="interface-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True)""", }) self.__interface_id = t if hasattr(self, '_set'): self._set() def _unset_interface_id(self): self.__interface_id = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="interface-id", rest_name="interface-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) def _get_if_role(self): """ Getter method for if_role, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/if_role (stp-port-role) YANG Description: Interface role """ return self.__if_role def _set_if_role(self, v, load=False): """ Setter method for if_role, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/if_role (stp-port-role) If this variable is read-only (config: false) in the source YANG file, then _set_if_role is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_if_role() directly. YANG Description: Interface role """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'backup': {'value': 5}, u'alternate': {'value': 4}, u'designated': {'value': 2}, u'disabled': {'value': 6}, u'master': {'value': 7}, u'error': {'value': 1}, u'root': {'value': 3}},), is_leaf=True, yang_name="if-role", rest_name="if-role", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-port-role', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """if_role must be of a type compatible with stp-port-role""", 'defined-type': "brocade-xstp-ext:stp-port-role", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'backup': {'value': 5}, u'alternate': {'value': 4}, u'designated': {'value': 2}, u'disabled': {'value': 6}, u'master': {'value': 7}, u'error': {'value': 1}, u'root': {'value': 3}},), is_leaf=True, yang_name="if-role", rest_name="if-role", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-port-role', is_config=True)""", }) self.__if_role = t if hasattr(self, '_set'): self._set() def _unset_if_role(self): self.__if_role = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'backup': {'value': 5}, u'alternate': {'value': 4}, u'designated': {'value': 2}, u'disabled': {'value': 6}, u'master': {'value': 7}, u'error': {'value': 1}, u'root': {'value': 3}},), is_leaf=True, yang_name="if-role", rest_name="if-role", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-port-role', is_config=True) def _get_if_state(self): """ Getter method for if_state, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/if_state (stp-port-state) YANG Description: Interface state """ return self.__if_state def _set_if_state(self, v, load=False): """ Setter method for if_state, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/if_state (stp-port-state) If this variable is read-only (config: false) in the source YANG file, then _set_if_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_if_state() directly. YANG Description: Interface state """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'listening': {'value': 4}, u'discarding': {'value': 7}, u'disabled': {'value': 2}, u'learning': {'value': 5}, u'error': {'value': 1}, u'forwarding': {'value': 6}, u'blocking': {'value': 3}},), is_leaf=True, yang_name="if-state", rest_name="if-state", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-port-state', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """if_state must be of a type compatible with stp-port-state""", 'defined-type': "brocade-xstp-ext:stp-port-state", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'listening': {'value': 4}, u'discarding': {'value': 7}, u'disabled': {'value': 2}, u'learning': {'value': 5}, u'error': {'value': 1}, u'forwarding': {'value': 6}, u'blocking': {'value': 3}},), is_leaf=True, yang_name="if-state", rest_name="if-state", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-port-state', is_config=True)""", }) self.__if_state = t if hasattr(self, '_set'): self._set() def _unset_if_state(self): self.__if_state = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'listening': {'value': 4}, u'discarding': {'value': 7}, u'disabled': {'value': 2}, u'learning': {'value': 5}, u'error': {'value': 1}, u'forwarding': {'value': 6}, u'blocking': {'value': 3}},), is_leaf=True, yang_name="if-state", rest_name="if-state", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-port-state', is_config=True) def _get_external_path_cost(self): """ Getter method for external_path_cost, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/external_path_cost (uint32) YANG Description: Designated external path cost """ return self.__external_path_cost def _set_external_path_cost(self, v, load=False): """ Setter method for external_path_cost, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/external_path_cost (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_external_path_cost is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_external_path_cost() directly. YANG Description: Designated external path cost """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="external-path-cost", rest_name="external-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """external_path_cost must be of a type compatible with uint32""", 'defined-type': "uint32", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="external-path-cost", rest_name="external-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True)""", }) self.__external_path_cost = t if hasattr(self, '_set'): self._set() def _unset_external_path_cost(self): self.__external_path_cost = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="external-path-cost", rest_name="external-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) def _get_internal_path_cost(self): """ Getter method for internal_path_cost, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/internal_path_cost (uint32) YANG Description: Designated internal path cost """ return self.__internal_path_cost def _set_internal_path_cost(self, v, load=False): """ Setter method for internal_path_cost, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/internal_path_cost (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_internal_path_cost is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_internal_path_cost() directly. YANG Description: Designated internal path cost """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="internal-path-cost", rest_name="internal-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """internal_path_cost must be of a type compatible with uint32""", 'defined-type': "uint32", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="internal-path-cost", rest_name="internal-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True)""", }) self.__internal_path_cost = t if hasattr(self, '_set'): self._set() def _unset_internal_path_cost(self): self.__internal_path_cost = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="internal-path-cost", rest_name="internal-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) def _get_configured_path_cost(self): """ Getter method for configured_path_cost, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/configured_path_cost (uint32) YANG Description: Configured path cost """ return self.__configured_path_cost def _set_configured_path_cost(self, v, load=False): """ Setter method for configured_path_cost, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/configured_path_cost (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_configured_path_cost is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_configured_path_cost() directly. YANG Description: Configured path cost """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="configured-path-cost", rest_name="configured-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """configured_path_cost must be of a type compatible with uint32""", 'defined-type': "uint32", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="configured-path-cost", rest_name="configured-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True)""", }) self.__configured_path_cost = t if hasattr(self, '_set'): self._set() def _unset_configured_path_cost(self): self.__configured_path_cost = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="configured-path-cost", rest_name="configured-path-cost", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) def _get_designated_port_id(self): """ Getter method for designated_port_id, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/designated_port_id (uint64) YANG Description: Designated port id """ return self.__designated_port_id def _set_designated_port_id(self, v, load=False): """ Setter method for designated_port_id, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/designated_port_id (uint64) If this variable is read-only (config: false) in the source YANG file, then _set_designated_port_id is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_designated_port_id() directly. YANG Description: Designated port id """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="designated-port-id", rest_name="designated-port-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """designated_port_id must be of a type compatible with uint64""", 'defined-type': "uint64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="designated-port-id", rest_name="designated-port-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True)""", }) self.__designated_port_id = t if hasattr(self, '_set'): self._set() def _unset_designated_port_id(self): self.__designated_port_id = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="designated-port-id", rest_name="designated-port-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) def _get_port_priority(self): """ Getter method for port_priority, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/port_priority (uint32) YANG Description: Port priority """ return self.__port_priority def _set_port_priority(self, v, load=False): """ Setter method for port_priority, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/port_priority (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_port_priority is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_port_priority() directly. YANG Description: Port priority """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="port-priority", rest_name="port-priority", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """port_priority must be of a type compatible with uint32""", 'defined-type': "uint32", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="port-priority", rest_name="port-priority", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True)""", }) self.__port_priority = t if hasattr(self, '_set'): self._set() def _unset_port_priority(self): self.__port_priority = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="port-priority", rest_name="port-priority", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) def _get_designated_bridge_id(self): """ Getter method for designated_bridge_id, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/designated_bridge_id (bridge-id-type) YANG Description: Designated bridge Id """ return self.__designated_bridge_id def _set_designated_bridge_id(self, v, load=False): """ Setter method for designated_bridge_id, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/designated_bridge_id (bridge-id-type) If this variable is read-only (config: false) in the source YANG file, then _set_designated_bridge_id is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_designated_bridge_id() directly. YANG Description: Designated bridge Id """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=unicode, is_leaf=True, yang_name="designated-bridge-id", rest_name="designated-bridge-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='bridge-id-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """designated_bridge_id must be of a type compatible with bridge-id-type""", 'defined-type': "brocade-xstp-ext:bridge-id-type", 'generated-type': """YANGDynClass(base=unicode, is_leaf=True, yang_name="designated-bridge-id", rest_name="designated-bridge-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='bridge-id-type', is_config=True)""", }) self.__designated_bridge_id = t if hasattr(self, '_set'): self._set() def _unset_designated_bridge_id(self): self.__designated_bridge_id = YANGDynClass(base=unicode, is_leaf=True, yang_name="designated-bridge-id", rest_name="designated-bridge-id", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='bridge-id-type', is_config=True) def _get_port_hello_time(self): """ Getter method for port_hello_time, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/port_hello_time (uint32) YANG Description: Port hello time """ return self.__port_hello_time def _set_port_hello_time(self, v, load=False): """ Setter method for port_hello_time, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/port_hello_time (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_port_hello_time is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_port_hello_time() directly. YANG Description: Port hello time """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="port-hello-time", rest_name="port-hello-time", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """port_hello_time must be of a type compatible with uint32""", 'defined-type': "uint32", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="port-hello-time", rest_name="port-hello-time", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True)""", }) self.__port_hello_time = t if hasattr(self, '_set'): self._set() def _unset_port_hello_time(self): self.__port_hello_time = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="port-hello-time", rest_name="port-hello-time", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) def _get_forward_transitions_count(self): """ Getter method for forward_transitions_count, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/forward_transitions_count (uint32) YANG Description: Number of forward transitions """ return self.__forward_transitions_count def _set_forward_transitions_count(self, v, load=False): """ Setter method for forward_transitions_count, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/forward_transitions_count (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_forward_transitions_count is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_forward_transitions_count() directly. YANG Description: Number of forward transitions """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="forward-transitions-count", rest_name="forward-transitions-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """forward_transitions_count must be of a type compatible with uint32""", 'defined-type': "uint32", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="forward-transitions-count", rest_name="forward-transitions-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True)""", }) self.__forward_transitions_count = t if hasattr(self, '_set'): self._set() def _unset_forward_transitions_count(self): self.__forward_transitions_count = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="forward-transitions-count", rest_name="forward-transitions-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) def _get_received_stp_type(self): """ Getter method for received_stp_type, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/received_stp_type (stp-type) YANG Description: Received (rx) stp type """ return self.__received_stp_type def _set_received_stp_type(self, v, load=False): """ Setter method for received_stp_type, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/received_stp_type (stp-type) If this variable is read-only (config: false) in the source YANG file, then _set_received_stp_type is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_received_stp_type() directly. YANG Description: Received (rx) stp type """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'none': {'value': 1}, u'rstp': {'value': 3}, u'mstp': {'value': 4}, u'rpvstp': {'value': 6}, u'pvstp': {'value': 5}, u'stp': {'value': 2}},), is_leaf=True, yang_name="received-stp-type", rest_name="received-stp-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """received_stp_type must be of a type compatible with stp-type""", 'defined-type': "brocade-xstp-ext:stp-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'none': {'value': 1}, u'rstp': {'value': 3}, u'mstp': {'value': 4}, u'rpvstp': {'value': 6}, u'pvstp': {'value': 5}, u'stp': {'value': 2}},), is_leaf=True, yang_name="received-stp-type", rest_name="received-stp-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-type', is_config=True)""", }) self.__received_stp_type = t if hasattr(self, '_set'): self._set() def _unset_received_stp_type(self): self.__received_stp_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'none': {'value': 1}, u'rstp': {'value': 3}, u'mstp': {'value': 4}, u'rpvstp': {'value': 6}, u'pvstp': {'value': 5}, u'stp': {'value': 2}},), is_leaf=True, yang_name="received-stp-type", rest_name="received-stp-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-type', is_config=True) def _get_transmitted_stp_type(self): """ Getter method for transmitted_stp_type, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/transmitted_stp_type (stp-type) YANG Description: Transmitted (tx) stp type """ return self.__transmitted_stp_type def _set_transmitted_stp_type(self, v, load=False): """ Setter method for transmitted_stp_type, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/transmitted_stp_type (stp-type) If this variable is read-only (config: false) in the source YANG file, then _set_transmitted_stp_type is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_transmitted_stp_type() directly. YANG Description: Transmitted (tx) stp type """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'none': {'value': 1}, u'rstp': {'value': 3}, u'mstp': {'value': 4}, u'rpvstp': {'value': 6}, u'pvstp': {'value': 5}, u'stp': {'value': 2}},), is_leaf=True, yang_name="transmitted-stp-type", rest_name="transmitted-stp-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """transmitted_stp_type must be of a type compatible with stp-type""", 'defined-type': "brocade-xstp-ext:stp-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'none': {'value': 1}, u'rstp': {'value': 3}, u'mstp': {'value': 4}, u'rpvstp': {'value': 6}, u'pvstp': {'value': 5}, u'stp': {'value': 2}},), is_leaf=True, yang_name="transmitted-stp-type", rest_name="transmitted-stp-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-type', is_config=True)""", }) self.__transmitted_stp_type = t if hasattr(self, '_set'): self._set() def _unset_transmitted_stp_type(self): self.__transmitted_stp_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'none': {'value': 1}, u'rstp': {'value': 3}, u'mstp': {'value': 4}, u'rpvstp': {'value': 6}, u'pvstp': {'value': 5}, u'stp': {'value': 2}},), is_leaf=True, yang_name="transmitted-stp-type", rest_name="transmitted-stp-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-type', is_config=True) def _get_edge_port(self): """ Getter method for edge_port, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/edge_port (on-off-type) YANG Description: Edge Port mode """ return self.__edge_port def _set_edge_port(self, v, load=False): """ Setter method for edge_port, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/edge_port (on-off-type) If this variable is read-only (config: false) in the source YANG file, then _set_edge_port is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_edge_port() directly. YANG Description: Edge Port mode """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="edge-port", rest_name="edge-port", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """edge_port must be of a type compatible with on-off-type""", 'defined-type': "brocade-xstp-ext:on-off-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="edge-port", rest_name="edge-port", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True)""", }) self.__edge_port = t if hasattr(self, '_set'): self._set() def _unset_edge_port(self): self.__edge_port = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="edge-port", rest_name="edge-port", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) def _get_auto_edge(self): """ Getter method for auto_edge, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/auto_edge (yes-no-type) YANG Description: Auto Edge """ return self.__auto_edge def _set_auto_edge(self, v, load=False): """ Setter method for auto_edge, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/auto_edge (yes-no-type) If this variable is read-only (config: false) in the source YANG file, then _set_auto_edge is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_auto_edge() directly. YANG Description: Auto Edge """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="auto-edge", rest_name="auto-edge", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """auto_edge must be of a type compatible with yes-no-type""", 'defined-type': "brocade-xstp-ext:yes-no-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="auto-edge", rest_name="auto-edge", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True)""", }) self.__auto_edge = t if hasattr(self, '_set'): self._set() def _unset_auto_edge(self): self.__auto_edge = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="auto-edge", rest_name="auto-edge", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True) def _get_admin_edge(self): """ Getter method for admin_edge, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/admin_edge (yes-no-type) YANG Description: Admin Edge """ return self.__admin_edge def _set_admin_edge(self, v, load=False): """ Setter method for admin_edge, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/admin_edge (yes-no-type) If this variable is read-only (config: false) in the source YANG file, then _set_admin_edge is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_admin_edge() directly. YANG Description: Admin Edge """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="admin-edge", rest_name="admin-edge", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """admin_edge must be of a type compatible with yes-no-type""", 'defined-type': "brocade-xstp-ext:yes-no-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="admin-edge", rest_name="admin-edge", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True)""", }) self.__admin_edge = t if hasattr(self, '_set'): self._set() def _unset_admin_edge(self): self.__admin_edge = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="admin-edge", rest_name="admin-edge", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True) def _get_edge_delay(self): """ Getter method for edge_delay, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/edge_delay (uint32) YANG Description: Edge delay """ return self.__edge_delay def _set_edge_delay(self, v, load=False): """ Setter method for edge_delay, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/edge_delay (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_edge_delay is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_edge_delay() directly. YANG Description: Edge delay """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="edge-delay", rest_name="edge-delay", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """edge_delay must be of a type compatible with uint32""", 'defined-type': "uint32", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="edge-delay", rest_name="edge-delay", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True)""", }) self.__edge_delay = t if hasattr(self, '_set'): self._set() def _unset_edge_delay(self): self.__edge_delay = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="edge-delay", rest_name="edge-delay", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint32', is_config=True) def _get_configured_root_guard(self): """ Getter method for configured_root_guard, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/configured_root_guard (on-off-type) YANG Description: Configured root guard """ return self.__configured_root_guard def _set_configured_root_guard(self, v, load=False): """ Setter method for configured_root_guard, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/configured_root_guard (on-off-type) If this variable is read-only (config: false) in the source YANG file, then _set_configured_root_guard is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_configured_root_guard() directly. YANG Description: Configured root guard """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="configured-root-guard", rest_name="configured-root-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """configured_root_guard must be of a type compatible with on-off-type""", 'defined-type': "brocade-xstp-ext:on-off-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="configured-root-guard", rest_name="configured-root-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True)""", }) self.__configured_root_guard = t if hasattr(self, '_set'): self._set() def _unset_configured_root_guard(self): self.__configured_root_guard = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="configured-root-guard", rest_name="configured-root-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) def _get_oper_root_guard(self): """ Getter method for oper_root_guard, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/oper_root_guard (on-off-type) YANG Description: Operational root guard """ return self.__oper_root_guard def _set_oper_root_guard(self, v, load=False): """ Setter method for oper_root_guard, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/oper_root_guard (on-off-type) If this variable is read-only (config: false) in the source YANG file, then _set_oper_root_guard is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_oper_root_guard() directly. YANG Description: Operational root guard """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="oper-root-guard", rest_name="oper-root-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """oper_root_guard must be of a type compatible with on-off-type""", 'defined-type': "brocade-xstp-ext:on-off-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="oper-root-guard", rest_name="oper-root-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True)""", }) self.__oper_root_guard = t if hasattr(self, '_set'): self._set() def _unset_oper_root_guard(self): self.__oper_root_guard = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="oper-root-guard", rest_name="oper-root-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) def _get_boundary_port(self): """ Getter method for boundary_port, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/boundary_port (yes-no-type) YANG Description: Is boundary """ return self.__boundary_port def _set_boundary_port(self, v, load=False): """ Setter method for boundary_port, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/boundary_port (yes-no-type) If this variable is read-only (config: false) in the source YANG file, then _set_boundary_port is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_boundary_port() directly. YANG Description: Is boundary """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="boundary-port", rest_name="boundary-port", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """boundary_port must be of a type compatible with yes-no-type""", 'defined-type': "brocade-xstp-ext:yes-no-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="boundary-port", rest_name="boundary-port", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True)""", }) self.__boundary_port = t if hasattr(self, '_set'): self._set() def _unset_boundary_port(self): self.__boundary_port = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'yes': {'value': 2}, u'no': {'value': 1}},), is_leaf=True, yang_name="boundary-port", rest_name="boundary-port", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='yes-no-type', is_config=True) def _get_oper_bpdu_guard(self): """ Getter method for oper_bpdu_guard, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/oper_bpdu_guard (on-off-type) YANG Description: Operational BPDU guard """ return self.__oper_bpdu_guard def _set_oper_bpdu_guard(self, v, load=False): """ Setter method for oper_bpdu_guard, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/oper_bpdu_guard (on-off-type) If this variable is read-only (config: false) in the source YANG file, then _set_oper_bpdu_guard is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_oper_bpdu_guard() directly. YANG Description: Operational BPDU guard """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="oper-bpdu-guard", rest_name="oper-bpdu-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """oper_bpdu_guard must be of a type compatible with on-off-type""", 'defined-type': "brocade-xstp-ext:on-off-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="oper-bpdu-guard", rest_name="oper-bpdu-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True)""", }) self.__oper_bpdu_guard = t if hasattr(self, '_set'): self._set() def _unset_oper_bpdu_guard(self): self.__oper_bpdu_guard = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'on': {'value': 2}, u'off': {'value': 1}},), is_leaf=True, yang_name="oper-bpdu-guard", rest_name="oper-bpdu-guard", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='on-off-type', is_config=True) def _get_link_type(self): """ Getter method for link_type, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/link_type (stp-link-type) """ return self.__link_type def _set_link_type(self, v, load=False): """ Setter method for link_type, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/link_type (stp-link-type) If this variable is read-only (config: false) in the source YANG file, then _set_link_type is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_link_type() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'shared': {'value': 2}, u'point-to-point': {'value': 1}},), is_leaf=True, yang_name="link-type", rest_name="link-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-link-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """link_type must be of a type compatible with stp-link-type""", 'defined-type': "brocade-xstp-ext:stp-link-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'shared': {'value': 2}, u'point-to-point': {'value': 1}},), is_leaf=True, yang_name="link-type", rest_name="link-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-link-type', is_config=True)""", }) self.__link_type = t if hasattr(self, '_set'): self._set() def _unset_link_type(self): self.__link_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'shared': {'value': 2}, u'point-to-point': {'value': 1}},), is_leaf=True, yang_name="link-type", rest_name="link-type", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='stp-link-type', is_config=True) def _get_rx_bpdu_count(self): """ Getter method for rx_bpdu_count, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/rx_bpdu_count (uint64) YANG Description: Received Bpdu count """ return self.__rx_bpdu_count def _set_rx_bpdu_count(self, v, load=False): """ Setter method for rx_bpdu_count, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/rx_bpdu_count (uint64) If this variable is read-only (config: false) in the source YANG file, then _set_rx_bpdu_count is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_rx_bpdu_count() directly. YANG Description: Received Bpdu count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-bpdu-count", rest_name="rx-bpdu-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """rx_bpdu_count must be of a type compatible with uint64""", 'defined-type': "uint64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-bpdu-count", rest_name="rx-bpdu-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True)""", }) self.__rx_bpdu_count = t if hasattr(self, '_set'): self._set() def _unset_rx_bpdu_count(self): self.__rx_bpdu_count = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-bpdu-count", rest_name="rx-bpdu-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) def _get_tx_bpdu_count(self): """ Getter method for tx_bpdu_count, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/tx_bpdu_count (uint64) YANG Description: Transmitted Bpdu count """ return self.__tx_bpdu_count def _set_tx_bpdu_count(self, v, load=False): """ Setter method for tx_bpdu_count, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/port/tx_bpdu_count (uint64) If this variable is read-only (config: false) in the source YANG file, then _set_tx_bpdu_count is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_tx_bpdu_count() directly. YANG Description: Transmitted Bpdu count """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-bpdu-count", rest_name="tx-bpdu-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """tx_bpdu_count must be of a type compatible with uint64""", 'defined-type': "uint64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-bpdu-count", rest_name="tx-bpdu-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True)""", }) self.__tx_bpdu_count = t if hasattr(self, '_set'): self._set() def _unset_tx_bpdu_count(self): self.__tx_bpdu_count = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-bpdu-count", rest_name="tx-bpdu-count", parent=self, choice=(u'spanning-tree-mode', u'pvstp'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-xstp-ext', defining_module='brocade-xstp-ext', yang_type='uint64', is_config=True) interface_type = __builtin__.property(_get_interface_type, _set_interface_type) interface_name = __builtin__.property(_get_interface_name, _set_interface_name) spanningtree_enabled = __builtin__.property(_get_spanningtree_enabled, _set_spanningtree_enabled) if_index = __builtin__.property(_get_if_index, _set_if_index) interface_id = __builtin__.property(_get_interface_id, _set_interface_id) if_role = __builtin__.property(_get_if_role, _set_if_role) if_state = __builtin__.property(_get_if_state, _set_if_state) external_path_cost = __builtin__.property(_get_external_path_cost, _set_external_path_cost) internal_path_cost = __builtin__.property(_get_internal_path_cost, _set_internal_path_cost) configured_path_cost = __builtin__.property(_get_configured_path_cost, _set_configured_path_cost) designated_port_id = __builtin__.property(_get_designated_port_id, _set_designated_port_id) port_priority = __builtin__.property(_get_port_priority, _set_port_priority) designated_bridge_id = __builtin__.property(_get_designated_bridge_id, _set_designated_bridge_id) port_hello_time = __builtin__.property(_get_port_hello_time, _set_port_hello_time) forward_transitions_count = __builtin__.property(_get_forward_transitions_count, _set_forward_transitions_count) received_stp_type = __builtin__.property(_get_received_stp_type, _set_received_stp_type) transmitted_stp_type = __builtin__.property(_get_transmitted_stp_type, _set_transmitted_stp_type) edge_port = __builtin__.property(_get_edge_port, _set_edge_port) auto_edge = __builtin__.property(_get_auto_edge, _set_auto_edge) admin_edge = __builtin__.property(_get_admin_edge, _set_admin_edge) edge_delay = __builtin__.property(_get_edge_delay, _set_edge_delay) configured_root_guard = __builtin__.property(_get_configured_root_guard, _set_configured_root_guard) oper_root_guard = __builtin__.property(_get_oper_root_guard, _set_oper_root_guard) boundary_port = __builtin__.property(_get_boundary_port, _set_boundary_port) oper_bpdu_guard = __builtin__.property(_get_oper_bpdu_guard, _set_oper_bpdu_guard) link_type = __builtin__.property(_get_link_type, _set_link_type) rx_bpdu_count = __builtin__.property(_get_rx_bpdu_count, _set_rx_bpdu_count) tx_bpdu_count = __builtin__.property(_get_tx_bpdu_count, _set_tx_bpdu_count) __choices__ = {u'spanning-tree-mode': {u'pvstp': [u'interface_type', u'interface_name', u'spanningtree_enabled', u'if_index', u'interface_id', u'if_role', u'if_state', u'external_path_cost', u'internal_path_cost', u'configured_path_cost', u'designated_port_id', u'port_priority', u'designated_bridge_id', u'port_hello_time', u'forward_transitions_count', u'received_stp_type', u'transmitted_stp_type', u'edge_port', u'auto_edge', u'admin_edge', u'edge_delay', u'configured_root_guard', u'oper_root_guard', u'boundary_port', u'oper_bpdu_guard', u'link_type', u'rx_bpdu_count', u'tx_bpdu_count']}} _pyangbind_elements = {'interface_type': interface_type, 'interface_name': interface_name, 'spanningtree_enabled': spanningtree_enabled, 'if_index': if_index, 'interface_id': interface_id, 'if_role': if_role, 'if_state': if_state, 'external_path_cost': external_path_cost, 'internal_path_cost': internal_path_cost, 'configured_path_cost': configured_path_cost, 'designated_port_id': designated_port_id, 'port_priority': port_priority, 'designated_bridge_id': designated_bridge_id, 'port_hello_time': port_hello_time, 'forward_transitions_count': forward_transitions_count, 'received_stp_type': received_stp_type, 'transmitted_stp_type': transmitted_stp_type, 'edge_port': edge_port, 'auto_edge': auto_edge, 'admin_edge': admin_edge, 'edge_delay': edge_delay, 'configured_root_guard': configured_root_guard, 'oper_root_guard': oper_root_guard, 'boundary_port': boundary_port, 'oper_bpdu_guard': oper_bpdu_guard, 'link_type': link_type, 'rx_bpdu_count': rx_bpdu_count, 'tx_bpdu_count': tx_bpdu_count, }
# Copyright (c) 2013 - 2020 Adam Caudill and Contributors. # This file is part of YAWAST which is released under the MIT license. # See the LICENSE file or go to https://yawast.org/license/ for full license details. from typing import List, cast from cryptography import x509 from cryptography.hazmat.primitives import hashes from sslyze import server_connectivity_tester, synchronous_scanner, __version__ from sslyze.plugins import ( certificate_info_plugin, openssl_cipher_suites_plugin, compression_plugin, fallback_scsv_plugin, heartbleed_plugin, openssl_ccs_injection_plugin, session_renegotiation_plugin, session_resumption_plugin, robot_plugin, early_data_plugin, ) from validator_collection import checkers from yawast.reporting import reporter, issue from yawast.reporting.enums import Vulnerabilities from yawast.scanner.plugins.dns import basic from yawast.scanner.plugins.ssl import cert_info from yawast.scanner.session import Session from yawast.shared import output, utils def scan(session: Session): output.norm( f"Beginning SSL scan using sslyze {__version__} (this could take a minute or two)" ) output.empty() ips = basic.get_ips(session.domain) for ip in ips: try: conn_tester = server_connectivity_tester.ServerConnectivityTester( hostname=session.domain, port=utils.get_port(session.url), ip_address=ip ) output.norm(f"IP: {conn_tester.ip_address}:{conn_tester.port}") server_info = conn_tester.perform() scanner = synchronous_scanner.SynchronousScanner() cinfo = scanner.run_scan_command( server_info, certificate_info_plugin.CertificateInfoScanCommand() ) cinfo = cast(certificate_info_plugin.CertificateInfoScanResult, cinfo) # print info on the server cert _get_leaf_cert_info(cinfo.verified_certificate_chain[0]) # get all but the first element _get_cert_chain(cinfo.verified_certificate_chain[1:], session.url) # list the root stores this is trusted by trust = "" for t in _get_trusted_root_stores(cinfo): trust += f"{t} (trusted) " output.norm(f"\tRoot Stores: {trust}") output.empty() # get info for the various versions of SSL/TLS output.norm("\tCipher Suite Support:") sslv2 = scanner.run_scan_command( server_info, openssl_cipher_suites_plugin.Sslv20ScanCommand() ) sslv2 = cast(openssl_cipher_suites_plugin.CipherSuiteScanResult, sslv2) _get_suite_info("SSLv2", sslv2, session.url) sslv3 = scanner.run_scan_command( server_info, openssl_cipher_suites_plugin.Sslv30ScanCommand() ) sslv3 = cast(openssl_cipher_suites_plugin.CipherSuiteScanResult, sslv3) _get_suite_info("SSLv3", sslv3, session.url) tls10 = scanner.run_scan_command( server_info, openssl_cipher_suites_plugin.Tlsv10ScanCommand() ) tls10 = cast(openssl_cipher_suites_plugin.CipherSuiteScanResult, tls10) _get_suite_info("TLSv1.0", tls10, session.url) tls11 = scanner.run_scan_command( server_info, openssl_cipher_suites_plugin.Tlsv11ScanCommand() ) tls11 = cast(openssl_cipher_suites_plugin.CipherSuiteScanResult, tls11) _get_suite_info("TLSv1.1", tls11, session.url) tls12 = scanner.run_scan_command( server_info, openssl_cipher_suites_plugin.Tlsv12ScanCommand() ) tls12 = cast(openssl_cipher_suites_plugin.CipherSuiteScanResult, tls12) _get_suite_info("TLSv1.2", tls12, session.url) tls13 = scanner.run_scan_command( server_info, openssl_cipher_suites_plugin.Tlsv13ScanCommand() ) tls13 = cast(openssl_cipher_suites_plugin.CipherSuiteScanResult, tls13) _get_suite_info("TLSv1.3", tls13, session.url) output.empty() # check compression compression = scanner.run_scan_command( server_info, compression_plugin.CompressionScanCommand() ) compression = cast(compression_plugin.CompressionScanResult, compression) if compression.compression_name is not None: reporter.display( f"\tCompression: {compression.compression_name}", issue.Issue( Vulnerabilities.TLS_COMPRESSION_ENABLED, session.url, {} ), ) else: output.norm("\tCompression: None") # check TLS_FALLBACK_SCSV fallback = scanner.run_scan_command( server_info, fallback_scsv_plugin.FallbackScsvScanCommand() ) fallback = cast(fallback_scsv_plugin.FallbackScsvScanResult, fallback) if fallback.supports_fallback_scsv: output.norm("\tDowngrade Prevention: Yes") else: reporter.display( "\tDowngrade Prevention: No", issue.Issue( Vulnerabilities.TLS_FALLBACK_SCSV_MISSING, session.url, {} ), ) # check Heartbleed heartbleed = scanner.run_scan_command( server_info, heartbleed_plugin.HeartbleedScanCommand() ) heartbleed = cast(heartbleed_plugin.HeartbleedScanResult, heartbleed) if heartbleed.is_vulnerable_to_heartbleed: reporter.display( "\tHeartbleed: Vulnerable", issue.Issue(Vulnerabilities.TLS_HEARTBLEED, session.url, {}), ) else: output.norm("\tHeartbleed: No") # check OpenSSL CCS injection vulnerability (CVE-2014-0224) openssl_ccs = scanner.run_scan_command( server_info, openssl_ccs_injection_plugin.OpenSslCcsInjectionScanCommand(), ) openssl_ccs = cast( openssl_ccs_injection_plugin.OpenSslCcsInjectionScanResult, openssl_ccs ) if openssl_ccs.is_vulnerable_to_ccs_injection: reporter.display( "\tOpenSSL CCS (CVE-2014-0224): Vulnerable", issue.Issue( Vulnerabilities.TLS_OPENSSL_CVE_2014_0224, session.url, {} ), ) else: output.norm("\tOpenSSL CCS (CVE-2014-0224): No") # check SessionRenegotiation sr = scanner.run_scan_command( server_info, session_renegotiation_plugin.SessionRenegotiationScanCommand(), ) sr = cast(session_renegotiation_plugin.SessionRenegotiationScanResult, sr) if sr.accepts_client_renegotiation: output.norm( "\tSecure Renegotiation: client-initiated renegotiation supported" ) if sr.supports_secure_renegotiation: output.norm("\tSecure Renegotiation: secure renegotiation supported") # check SessionResumption resump = scanner.run_scan_command( server_info, session_resumption_plugin.SessionResumptionSupportScanCommand(), ) resump = cast( session_resumption_plugin.SessionResumptionSupportScanResult, resump ) output.norm( f"\tSession Resumption Tickets Supported: {resump.is_ticket_resumption_supported}" ) output.norm( f"\tSession Resumption: {resump.successful_resumptions_nb} of " f"{resump.attempted_resumptions_nb} successful" ) # check ROBOT robot = scanner.run_scan_command( server_info, robot_plugin.RobotScanCommand() ) robot = cast(robot_plugin.RobotScanResult, robot) if ( robot.robot_result_enum == robot_plugin.RobotScanResultEnum.VULNERABLE_WEAK_ORACLE ): reporter.display( "\tROBOT: Vulnerable - Not Exploitable", issue.Issue(Vulnerabilities.TLS_ROBOT_ORACLE_WEAK, session.url, {}), ) elif ( robot.robot_result_enum == robot_plugin.RobotScanResultEnum.VULNERABLE_STRONG_ORACLE ): reporter.display( "\tROBOT: Vulnerable - Exploitable", issue.Issue( Vulnerabilities.TLS_ROBOT_ORACLE_STRONG, session.url, {} ), ) elif ( robot.robot_result_enum == robot_plugin.RobotScanResultEnum.UNKNOWN_INCONSISTENT_RESULTS ): output.error("\tROBOT: Test Failed (Inconsistent Results)") else: output.norm("\tROBOT: No") # check TLS 1.3 Early Data ed = scanner.run_scan_command( server_info, early_data_plugin.EarlyDataScanCommand() ) ed = cast(early_data_plugin.EarlyDataScanResult, ed) if ed.is_early_data_supported: output.info("\tTLS 1.3 0-RTT Support: Yes") else: output.norm("\tTLS 1.3 0-RTT Support: No") if cinfo.ocsp_response_status is not None: output.norm("\tOCSP Stapling: Yes") else: reporter.display( "\tOCSP Stapling: No", issue.Issue( Vulnerabilities.TLS_OCSP_STAPLE_MISSING, session.url, {} ), ) output.empty() except server_connectivity_tester.ServerConnectivityError as error: output.debug_exception() if checkers.is_ipv6(ip): output.error( "\tError connecting to IPv6 IP. Please ensure that your system is configured properly." ) output.error(f"\tConnection failed ({str(error)})") output.empty() except Exception as error: output.debug_exception() output.error(f"Error performing TLS scan: #{str(error)}") def _get_leaf_cert_info(cert: x509.Certificate): output.norm("Certificate Information:") output.norm(f"\tSubject: {cert.subject.rfc4514_string()}") output.norm(f'\tCommon Names: {' '.join(cert_info.get_common_names(cert))}') output.norm("\tAlternative names:") alt_names = cert_info.get_alt_names(cert) for name in alt_names: output.norm(f"\t\t{name}") output.norm(f'\tNot Before: {cert.not_valid_before.isoformat(' ')}') output.norm(f'\tNot After: {cert.not_valid_after.isoformat(' ')}') output.norm(f"\tKey: {cert.signature_algorithm_oid._name}") # TODO: Public Key Hash serial = format(cert.serial_number, "02x") output.norm(f"\tSerial: {serial}") output.norm(f"\tIssuer: {cert.issuer.rfc4514_string()}") output.norm(f"\tOCSP Must Staple: {cert_info.get_must_staple(cert)}") output.empty() exts = cert_info.format_extensions(cert) for ext in exts: output.norm(f"\tExtensions: {ext}") output.empty() scts = cert_info.get_scts(cert) for sct in scts: output.norm( f'\tSCT: {cert_info.get_ct_log_name(sct[1])} - {sct[2].isoformat(' ')}' ) output.empty() cert_hash = bytes.hex(cert.fingerprint(hashes.SHA1())) output.norm(f"\tFingerprint: {cert_hash}") output.norm(f"\t\thttps://censys.io/certificates?q={cert_hash}") output.norm(f"\t\thttps://crt.sh/?q={cert_hash}") output.empty() def _get_cert_chain(chain: List[x509.Certificate], url: str): if len(chain) > 0: output.norm("\tCertificate Chain:") for cert in chain: output.norm(f"\t\tSubject: {cert.subject.rfc4514_string()}") output.norm(f"\t\t Signature: {cert.signature_algorithm_oid._name}") fp = bytes.hex(cert.fingerprint(hashes.SHA256())) if cert_info.check_symantec_root(fp): reporter.display( "\t\t Untrusted Symantec Root", issue.Issue( Vulnerabilities.TLS_SYMANTEC_ROOT, url, {"fingerprint": fp} ), ) output.norm( f"\t\t https://crt.sh/?q={bytes.hex(cert.fingerprint(hashes.SHA1()))}" ) output.empty() def _get_trusted_root_stores( result: certificate_info_plugin.CertificateInfoScanResult ) -> List[str]: trusted = [] for res in result.path_validation_result_list: if res.was_validation_successful: trusted.append(res.trust_store.name) return trusted def _get_suite_info( proto: str, result: openssl_cipher_suites_plugin.CipherSuiteScanResult, url: str ): output.norm(f"\t\t{proto}:") if len(result.accepted_cipher_list) > 0: for suite in result.accepted_cipher_list: name = openssl_cipher_suites_plugin.OPENSSL_TO_RFC_NAMES_MAPPING[ suite.ssl_version ].get(suite.openssl_name, suite.openssl_name) if _is_cipher_suite_secure(suite, name): if "CBC" in name: output.info(f"\t\t {name.ljust(50)} - {suite.key_size}-bits") reporter.register( issue.Issue( Vulnerabilities.TLS_CBC_CIPHER_SUITE, url, {"cipher": name} ) ) else: output.norm(f"\t\t {name.ljust(50)} - {suite.key_size}-bits") else: output.vuln(f"\t\t {name.ljust(50)} - {suite.key_size}-bits") reporter.register( issue.Issue( Vulnerabilities.TLS_INSECURE_CIPHER_SUITE, url, {"cipher": name} ) ) output.norm(f"\t\t ({len(result.rejected_cipher_list)} suites rejected)") else: output.norm(f"\t\t (all suites ({len(result.rejected_cipher_list)}) rejected)") def _is_cipher_suite_secure( suite: openssl_cipher_suites_plugin.AcceptedCipherSuite, name: str ) -> bool: ret = True if suite.is_anonymous: ret = False if "RC4" in name: ret = False if "DES" in name: ret = False if suite.key_size is not None: if suite.key_size < 128: ret = False return ret
# Copyright (c) 2013 - 2020 Adam Caudill and Contributors. # This file is part of YAWAST which is released under the MIT license. # See the LICENSE file or go to https://yawast.org/license/ for full license details. from typing import List, cast from cryptography import x509 from cryptography.hazmat.primitives import hashes from sslyze import server_connectivity_tester, synchronous_scanner, __version__ from sslyze.plugins import ( certificate_info_plugin, openssl_cipher_suites_plugin, compression_plugin, fallback_scsv_plugin, heartbleed_plugin, openssl_ccs_injection_plugin, session_renegotiation_plugin, session_resumption_plugin, robot_plugin, early_data_plugin, ) from validator_collection import checkers from yawast.reporting import reporter, issue from yawast.reporting.enums import Vulnerabilities from yawast.scanner.plugins.dns import basic from yawast.scanner.plugins.ssl import cert_info from yawast.scanner.session import Session from yawast.shared import output, utils def scan(session: Session): output.norm( f"Beginning SSL scan using sslyze {__version__} (this could take a minute or two)" ) output.empty() ips = basic.get_ips(session.domain) for ip in ips: try: conn_tester = server_connectivity_tester.ServerConnectivityTester( hostname=session.domain, port=utils.get_port(session.url), ip_address=ip ) output.norm(f"IP: {conn_tester.ip_address}:{conn_tester.port}") server_info = conn_tester.perform() scanner = synchronous_scanner.SynchronousScanner() cinfo = scanner.run_scan_command( server_info, certificate_info_plugin.CertificateInfoScanCommand() ) cinfo = cast(certificate_info_plugin.CertificateInfoScanResult, cinfo) # print info on the server cert _get_leaf_cert_info(cinfo.verified_certificate_chain[0]) # get all but the first element _get_cert_chain(cinfo.verified_certificate_chain[1:], session.url) # list the root stores this is trusted by trust = "" for t in _get_trusted_root_stores(cinfo): trust += f"{t} (trusted) " output.norm(f"\tRoot Stores: {trust}") output.empty() # get info for the various versions of SSL/TLS output.norm("\tCipher Suite Support:") sslv2 = scanner.run_scan_command( server_info, openssl_cipher_suites_plugin.Sslv20ScanCommand() ) sslv2 = cast(openssl_cipher_suites_plugin.CipherSuiteScanResult, sslv2) _get_suite_info("SSLv2", sslv2, session.url) sslv3 = scanner.run_scan_command( server_info, openssl_cipher_suites_plugin.Sslv30ScanCommand() ) sslv3 = cast(openssl_cipher_suites_plugin.CipherSuiteScanResult, sslv3) _get_suite_info("SSLv3", sslv3, session.url) tls10 = scanner.run_scan_command( server_info, openssl_cipher_suites_plugin.Tlsv10ScanCommand() ) tls10 = cast(openssl_cipher_suites_plugin.CipherSuiteScanResult, tls10) _get_suite_info("TLSv1.0", tls10, session.url) tls11 = scanner.run_scan_command( server_info, openssl_cipher_suites_plugin.Tlsv11ScanCommand() ) tls11 = cast(openssl_cipher_suites_plugin.CipherSuiteScanResult, tls11) _get_suite_info("TLSv1.1", tls11, session.url) tls12 = scanner.run_scan_command( server_info, openssl_cipher_suites_plugin.Tlsv12ScanCommand() ) tls12 = cast(openssl_cipher_suites_plugin.CipherSuiteScanResult, tls12) _get_suite_info("TLSv1.2", tls12, session.url) tls13 = scanner.run_scan_command( server_info, openssl_cipher_suites_plugin.Tlsv13ScanCommand() ) tls13 = cast(openssl_cipher_suites_plugin.CipherSuiteScanResult, tls13) _get_suite_info("TLSv1.3", tls13, session.url) output.empty() # check compression compression = scanner.run_scan_command( server_info, compression_plugin.CompressionScanCommand() ) compression = cast(compression_plugin.CompressionScanResult, compression) if compression.compression_name is not None: reporter.display( f"\tCompression: {compression.compression_name}", issue.Issue( Vulnerabilities.TLS_COMPRESSION_ENABLED, session.url, {} ), ) else: output.norm("\tCompression: None") # check TLS_FALLBACK_SCSV fallback = scanner.run_scan_command( server_info, fallback_scsv_plugin.FallbackScsvScanCommand() ) fallback = cast(fallback_scsv_plugin.FallbackScsvScanResult, fallback) if fallback.supports_fallback_scsv: output.norm("\tDowngrade Prevention: Yes") else: reporter.display( "\tDowngrade Prevention: No", issue.Issue( Vulnerabilities.TLS_FALLBACK_SCSV_MISSING, session.url, {} ), ) # check Heartbleed heartbleed = scanner.run_scan_command( server_info, heartbleed_plugin.HeartbleedScanCommand() ) heartbleed = cast(heartbleed_plugin.HeartbleedScanResult, heartbleed) if heartbleed.is_vulnerable_to_heartbleed: reporter.display( "\tHeartbleed: Vulnerable", issue.Issue(Vulnerabilities.TLS_HEARTBLEED, session.url, {}), ) else: output.norm("\tHeartbleed: No") # check OpenSSL CCS injection vulnerability (CVE-2014-0224) openssl_ccs = scanner.run_scan_command( server_info, openssl_ccs_injection_plugin.OpenSslCcsInjectionScanCommand(), ) openssl_ccs = cast( openssl_ccs_injection_plugin.OpenSslCcsInjectionScanResult, openssl_ccs ) if openssl_ccs.is_vulnerable_to_ccs_injection: reporter.display( "\tOpenSSL CCS (CVE-2014-0224): Vulnerable", issue.Issue( Vulnerabilities.TLS_OPENSSL_CVE_2014_0224, session.url, {} ), ) else: output.norm("\tOpenSSL CCS (CVE-2014-0224): No") # check SessionRenegotiation sr = scanner.run_scan_command( server_info, session_renegotiation_plugin.SessionRenegotiationScanCommand(), ) sr = cast(session_renegotiation_plugin.SessionRenegotiationScanResult, sr) if sr.accepts_client_renegotiation: output.norm( "\tSecure Renegotiation: client-initiated renegotiation supported" ) if sr.supports_secure_renegotiation: output.norm("\tSecure Renegotiation: secure renegotiation supported") # check SessionResumption resump = scanner.run_scan_command( server_info, session_resumption_plugin.SessionResumptionSupportScanCommand(), ) resump = cast( session_resumption_plugin.SessionResumptionSupportScanResult, resump ) output.norm( f"\tSession Resumption Tickets Supported: {resump.is_ticket_resumption_supported}" ) output.norm( f"\tSession Resumption: {resump.successful_resumptions_nb} of " f"{resump.attempted_resumptions_nb} successful" ) # check ROBOT robot = scanner.run_scan_command( server_info, robot_plugin.RobotScanCommand() ) robot = cast(robot_plugin.RobotScanResult, robot) if ( robot.robot_result_enum == robot_plugin.RobotScanResultEnum.VULNERABLE_WEAK_ORACLE ): reporter.display( "\tROBOT: Vulnerable - Not Exploitable", issue.Issue(Vulnerabilities.TLS_ROBOT_ORACLE_WEAK, session.url, {}), ) elif ( robot.robot_result_enum == robot_plugin.RobotScanResultEnum.VULNERABLE_STRONG_ORACLE ): reporter.display( "\tROBOT: Vulnerable - Exploitable", issue.Issue( Vulnerabilities.TLS_ROBOT_ORACLE_STRONG, session.url, {} ), ) elif ( robot.robot_result_enum == robot_plugin.RobotScanResultEnum.UNKNOWN_INCONSISTENT_RESULTS ): output.error("\tROBOT: Test Failed (Inconsistent Results)") else: output.norm("\tROBOT: No") # check TLS 1.3 Early Data ed = scanner.run_scan_command( server_info, early_data_plugin.EarlyDataScanCommand() ) ed = cast(early_data_plugin.EarlyDataScanResult, ed) if ed.is_early_data_supported: output.info("\tTLS 1.3 0-RTT Support: Yes") else: output.norm("\tTLS 1.3 0-RTT Support: No") if cinfo.ocsp_response_status is not None: output.norm("\tOCSP Stapling: Yes") else: reporter.display( "\tOCSP Stapling: No", issue.Issue( Vulnerabilities.TLS_OCSP_STAPLE_MISSING, session.url, {} ), ) output.empty() except server_connectivity_tester.ServerConnectivityError as error: output.debug_exception() if checkers.is_ipv6(ip): output.error( "\tError connecting to IPv6 IP. Please ensure that your system is configured properly." ) output.error(f"\tConnection failed ({str(error)})") output.empty() except Exception as error: output.debug_exception() output.error(f"Error performing TLS scan: #{str(error)}") def _get_leaf_cert_info(cert: x509.Certificate): output.norm("Certificate Information:") output.norm(f"\tSubject: {cert.subject.rfc4514_string()}") output.norm(f'\tCommon Names: {" ".join(cert_info.get_common_names(cert))}') output.norm("\tAlternative names:") alt_names = cert_info.get_alt_names(cert) for name in alt_names: output.norm(f"\t\t{name}") output.norm(f'\tNot Before: {cert.not_valid_before.isoformat(" ")}') output.norm(f'\tNot After: {cert.not_valid_after.isoformat(" ")}') output.norm(f"\tKey: {cert.signature_algorithm_oid._name}") # TODO: Public Key Hash serial = format(cert.serial_number, "02x") output.norm(f"\tSerial: {serial}") output.norm(f"\tIssuer: {cert.issuer.rfc4514_string()}") output.norm(f"\tOCSP Must Staple: {cert_info.get_must_staple(cert)}") output.empty() exts = cert_info.format_extensions(cert) for ext in exts: output.norm(f"\tExtensions: {ext}") output.empty() scts = cert_info.get_scts(cert) for sct in scts: output.norm( f'\tSCT: {cert_info.get_ct_log_name(sct[1])} - {sct[2].isoformat(" ")}' ) output.empty() cert_hash = bytes.hex(cert.fingerprint(hashes.SHA1())) output.norm(f"\tFingerprint: {cert_hash}") output.norm(f"\t\thttps://censys.io/certificates?q={cert_hash}") output.norm(f"\t\thttps://crt.sh/?q={cert_hash}") output.empty() def _get_cert_chain(chain: List[x509.Certificate], url: str): if len(chain) > 0: output.norm("\tCertificate Chain:") for cert in chain: output.norm(f"\t\tSubject: {cert.subject.rfc4514_string()}") output.norm(f"\t\t Signature: {cert.signature_algorithm_oid._name}") fp = bytes.hex(cert.fingerprint(hashes.SHA256())) if cert_info.check_symantec_root(fp): reporter.display( "\t\t Untrusted Symantec Root", issue.Issue( Vulnerabilities.TLS_SYMANTEC_ROOT, url, {"fingerprint": fp} ), ) output.norm( f"\t\t https://crt.sh/?q={bytes.hex(cert.fingerprint(hashes.SHA1()))}" ) output.empty() def _get_trusted_root_stores( result: certificate_info_plugin.CertificateInfoScanResult ) -> List[str]: trusted = [] for res in result.path_validation_result_list: if res.was_validation_successful: trusted.append(res.trust_store.name) return trusted def _get_suite_info( proto: str, result: openssl_cipher_suites_plugin.CipherSuiteScanResult, url: str ): output.norm(f"\t\t{proto}:") if len(result.accepted_cipher_list) > 0: for suite in result.accepted_cipher_list: name = openssl_cipher_suites_plugin.OPENSSL_TO_RFC_NAMES_MAPPING[ suite.ssl_version ].get(suite.openssl_name, suite.openssl_name) if _is_cipher_suite_secure(suite, name): if "CBC" in name: output.info(f"\t\t {name.ljust(50)} - {suite.key_size}-bits") reporter.register( issue.Issue( Vulnerabilities.TLS_CBC_CIPHER_SUITE, url, {"cipher": name} ) ) else: output.norm(f"\t\t {name.ljust(50)} - {suite.key_size}-bits") else: output.vuln(f"\t\t {name.ljust(50)} - {suite.key_size}-bits") reporter.register( issue.Issue( Vulnerabilities.TLS_INSECURE_CIPHER_SUITE, url, {"cipher": name} ) ) output.norm(f"\t\t ({len(result.rejected_cipher_list)} suites rejected)") else: output.norm(f"\t\t (all suites ({len(result.rejected_cipher_list)}) rejected)") def _is_cipher_suite_secure( suite: openssl_cipher_suites_plugin.AcceptedCipherSuite, name: str ) -> bool: ret = True if suite.is_anonymous: ret = False if "RC4" in name: ret = False if "DES" in name: ret = False if suite.key_size is not None: if suite.key_size < 128: ret = False return ret
from checkov.common.models.enums import CheckCategories, CheckResult from checkov.kubernetes.base_spec_check import BaseK8Check class ApiServerEncryptionProviders(BaseK8Check): def __init__(self): id = "CKV_K8S_104" name = "Ensure that encryption providers are appropriately configured" categories = [CheckCategories.KUBERNETES] supported_entities = ['containers'] super().__init__(name=name, id=id, categories=categories, supported_entities=supported_entities) def get_resource_id(self, conf): return f'{conf['parent']} - {conf['name']}' def scan_spec_conf(self, conf): keys=[] values=[] if "command" in conf: for cmd in conf["command"]: if "=" in cmd: firstEqual = cmd.index("=") [key, value] = [cmd[:firstEqual], cmd[firstEqual+1:]] keys.append(key) values.append(value) else: keys.append(cmd) values.append(None) if "kube-apiserver" in keys: if "--encryption-provider-config" not in keys: return CheckResult.FAILED return CheckResult.PASSED check = ApiServerEncryptionProviders()
from checkov.common.models.enums import CheckCategories, CheckResult from checkov.kubernetes.base_spec_check import BaseK8Check class ApiServerEncryptionProviders(BaseK8Check): def __init__(self): id = "CKV_K8S_104" name = "Ensure that encryption providers are appropriately configured" categories = [CheckCategories.KUBERNETES] supported_entities = ['containers'] super().__init__(name=name, id=id, categories=categories, supported_entities=supported_entities) def get_resource_id(self, conf): return f'{conf["parent"]} - {conf["name"]}' def scan_spec_conf(self, conf): keys=[] values=[] if "command" in conf: for cmd in conf["command"]: if "=" in cmd: firstEqual = cmd.index("=") [key, value] = [cmd[:firstEqual], cmd[firstEqual+1:]] keys.append(key) values.append(value) else: keys.append(cmd) values.append(None) if "kube-apiserver" in keys: if "--encryption-provider-config" not in keys: return CheckResult.FAILED return CheckResult.PASSED check = ApiServerEncryptionProviders()
import base64 import logging from typing import List from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.main import BaseModel from sqlalchemy.orm import Session from dispatch.exceptions import NotFoundError from dispatch.conversation import service as conversation_service from dispatch.conversation.enums import ConversationButtonActions from dispatch.database.core import resolve_attr from dispatch.enums import Visibility from dispatch.incident import service as incident_service from dispatch.incident.enums import IncidentStatus from dispatch.incident.messaging import send_incident_resources_ephemeral_message_to_participant from dispatch.participant import service as participant_service from dispatch.participant_role import service as participant_role_service from dispatch.participant_role.models import ParticipantRoleType from dispatch.plugin import service as plugin_service from dispatch.plugins.dispatch_slack import service as dispatch_slack_service from dispatch.plugins.dispatch_slack.models import TaskButton from dispatch.project import service as project_service from dispatch.task import service as task_service from dispatch.task.enums import TaskStatus from dispatch.task.models import Task from .config import ( SLACK_APP_USER_SLUG, SLACK_COMMAND_ADD_TIMELINE_EVENT_SLUG, SLACK_COMMAND_ASSIGN_ROLE_SLUG, SLACK_COMMAND_ENGAGE_ONCALL_SLUG, SLACK_COMMAND_LIST_INCIDENTS_SLUG, SLACK_COMMAND_LIST_MY_TASKS_SLUG, SLACK_COMMAND_LIST_PARTICIPANTS_SLUG, SLACK_COMMAND_LIST_RESOURCES_SLUG, SLACK_COMMAND_LIST_TASKS_SLUG, SLACK_COMMAND_REPORT_EXECUTIVE_SLUG, SLACK_COMMAND_REPORT_INCIDENT_SLUG, SLACK_COMMAND_REPORT_TACTICAL_SLUG, SLACK_COMMAND_UPDATE_INCIDENT_SLUG, SLACK_COMMAND_UPDATE_NOTIFICATIONS_GROUP_SLUG, SLACK_COMMAND_UPDATE_PARTICIPANT_SLUG, SLACK_COMMAND_RUN_WORKFLOW_SLUG, SLACK_COMMAND_LIST_WORKFLOWS_SLUG, ) from .decorators import ( get_organization_scope_from_channel_id, slack_background_task, ) from .dialogs import ( create_assign_role_dialog, create_engage_oncall_dialog, create_executive_report_dialog, create_tactical_report_dialog, ) from .messaging import ( INCIDENT_CONVERSATION_COMMAND_MESSAGE, create_command_run_in_conversation_where_bot_not_present_message, create_command_run_in_nonincident_conversation_message, create_command_run_by_non_privileged_user_message, ) from .modals.incident.handlers import ( create_add_timeline_event_modal, create_report_incident_modal, create_update_incident_modal, create_update_notifications_group_modal, create_update_participant_modal, ) from .modals.workflow.handlers import create_run_workflow_modal log = logging.getLogger(__name__) def base64_encode(input: str): """Returns a b64 encoded string.""" return base64.b64encode(input.encode("ascii")).decode("ascii") def check_command_restrictions( command: str, user_email: str, incident_id: int, db_session: Session ) -> bool: """Checks the current user's role to determine what commands they are allowed to run.""" # some commands are sensitive and we only let non-participants execute them command_permissons = { SLACK_COMMAND_UPDATE_INCIDENT_SLUG: [ ParticipantRoleType.incident_commander, ParticipantRoleType.scribe, ], SLACK_COMMAND_ASSIGN_ROLE_SLUG: [ ParticipantRoleType.incident_commander, ParticipantRoleType.reporter, ParticipantRoleType.liaison, ParticipantRoleType.scribe, ], SLACK_COMMAND_REPORT_EXECUTIVE_SLUG: [ ParticipantRoleType.incident_commander, ParticipantRoleType.scribe, ], SLACK_COMMAND_REPORT_TACTICAL_SLUG: [ ParticipantRoleType.incident_commander, ParticipantRoleType.scribe, ], } # no permissions have been defined if command not in command_permissons.keys(): return True participant = participant_service.get_by_incident_id_and_email( db_session=db_session, incident_id=incident_id, email=user_email ) # if any required role is active, allow command for active_role in participant.active_roles: for allowed_role in command_permissons[command]: if active_role.role == allowed_role: return True def command_functions(command: str): """Interprets the command and routes it the appropriate function.""" command_mappings = { SLACK_COMMAND_ADD_TIMELINE_EVENT_SLUG: [create_add_timeline_event_modal], SLACK_COMMAND_ASSIGN_ROLE_SLUG: [create_assign_role_dialog], SLACK_COMMAND_ENGAGE_ONCALL_SLUG: [create_engage_oncall_dialog], SLACK_COMMAND_LIST_INCIDENTS_SLUG: [list_incidents], SLACK_COMMAND_LIST_MY_TASKS_SLUG: [list_my_tasks], SLACK_COMMAND_LIST_PARTICIPANTS_SLUG: [list_participants], SLACK_COMMAND_LIST_RESOURCES_SLUG: [list_resources], SLACK_COMMAND_LIST_TASKS_SLUG: [list_tasks], SLACK_COMMAND_REPORT_EXECUTIVE_SLUG: [create_executive_report_dialog], SLACK_COMMAND_REPORT_INCIDENT_SLUG: [create_report_incident_modal], SLACK_COMMAND_REPORT_TACTICAL_SLUG: [create_tactical_report_dialog], SLACK_COMMAND_UPDATE_NOTIFICATIONS_GROUP_SLUG: [create_update_notifications_group_modal], SLACK_COMMAND_UPDATE_PARTICIPANT_SLUG: [create_update_participant_modal], SLACK_COMMAND_UPDATE_INCIDENT_SLUG: [create_update_incident_modal], SLACK_COMMAND_RUN_WORKFLOW_SLUG: [create_run_workflow_modal], SLACK_COMMAND_LIST_WORKFLOWS_SLUG: [list_workflows], } return command_mappings.get(command, []) def filter_tasks_by_assignee_and_creator(tasks: List[Task], by_assignee: str, by_creator: str): """Filters a list of tasks looking for a given creator or assignee.""" filtered_tasks = [] for t in tasks: if by_creator: creator_email = t.creator.individual.email if creator_email == by_creator: filtered_tasks.append(t) # lets avoid duplication if creator is also assignee continue if by_assignee: assignee_emails = [a.individual.email for a in t.assignees] if by_assignee in assignee_emails: filtered_tasks.append(t) return filtered_tasks async def handle_non_incident_conversation_commands(client, request, background_tasks): """Handles all commands that do not have a specific incident conversation.""" command = request.get("command") channel_id = request.get("channel_id") command_args = request.get("text", "").split(" ") if command_args: organization_slug = command_args[0] # We get the list of public and private conversations the Dispatch bot is a member of ( public_conversations, private_conversations, ) = await dispatch_slack_service.get_conversations_by_user_id_async(client, SLACK_APP_USER_SLUG) # We get the name of conversation where the command was run conversation_name = await dispatch_slack_service.get_conversation_name_by_id_async( client, channel_id ) if ( not conversation_name or conversation_name not in public_conversations + private_conversations ): # We let the user know in which public conversations they can run the command return create_command_run_in_conversation_where_bot_not_present_message( command, public_conversations ) user_id = request.get("user_id") user_email = await dispatch_slack_service.get_user_email_async(client, user_id) for f in command_functions(command): background_tasks.add_task( f, user_id, user_email, channel_id, None, organization_slug=organization_slug, command=request, ) return INCIDENT_CONVERSATION_COMMAND_MESSAGE.get(command, f"Running... Command: {command}") async def handle_incident_conversation_commands(client, request, background_tasks): """Handles all commands that are issued from an incident conversation.""" channel_id = request.get("channel_id") command = request.get("command") db_session = get_organization_scope_from_channel_id(channel_id=channel_id) if not db_session: # We let the user know that incident-specific commands # can only be run in incident conversations return create_command_run_in_nonincident_conversation_message(command) conversation = conversation_service.get_by_channel_id_ignoring_channel_type( db_session=db_session, channel_id=channel_id ) user_id = request.get("user_id") user_email = await dispatch_slack_service.get_user_email_async(client, user_id) # some commands are sensitive and we only let non-participants execute them allowed = check_command_restrictions( command=command, user_email=user_email, incident_id=conversation.incident.id, db_session=db_session, ) if not allowed: return create_command_run_by_non_privileged_user_message(command) for f in command_functions(command): background_tasks.add_task( f, user_id, user_email, channel_id, conversation.incident.id, command=request, ) return INCIDENT_CONVERSATION_COMMAND_MESSAGE.get(command, f"Running... Command: {command}") async def handle_slack_command(*, client, request, background_tasks): """Handles slack command message.""" # We get the name of command that was run command = request.get("command") if command in [SLACK_COMMAND_REPORT_INCIDENT_SLUG, SLACK_COMMAND_LIST_INCIDENTS_SLUG]: return await handle_non_incident_conversation_commands(client, request, background_tasks) else: return await handle_incident_conversation_commands(client, request, background_tasks) @slack_background_task def list_resources( user_id: str, user_email: str, channel_id: str, incident_id: int, command: dict = None, db_session=None, slack_client=None, ): """Runs the list incident resources flow.""" # we load the incident instance incident = incident_service.get(db_session=db_session, incident_id=incident_id) # we send the list of resources to the participant send_incident_resources_ephemeral_message_to_participant( command["user_id"], incident, db_session ) @slack_background_task def list_my_tasks( user_id: str, user_email: str, channel_id: str, incident_id: int, command: dict = None, db_session=None, slack_client=None, ): """Returns the list of incident tasks to the user as an ephemeral message.""" list_tasks( user_id=user_id, user_email=user_email, channel_id=channel_id, incident_id=incident_id, command=command, by_creator=user_email, by_assignee=user_email, db_session=db_session, slack_client=slack_client, ) @slack_background_task def list_tasks( user_id: str, user_email: str, channel_id: str, incident_id: int, command: dict = None, db_session=None, slack_client=None, by_creator: str = None, by_assignee: str = None, ): """Returns the list of incident tasks to the user as an ephemeral message.""" blocks = [] for status in TaskStatus: blocks.append( { "type": "section", "text": {"type": "mrkdwn", "text": f"*{status} Incident Tasks*"}, } ) button_text = "Resolve" if status == TaskStatus.open else "Re-open" action_type = "resolve" if status == TaskStatus.open else "reopen" tasks = task_service.get_all_by_incident_id_and_status( db_session=db_session, incident_id=incident_id, status=status ) if by_creator or by_assignee: tasks = filter_tasks_by_assignee_and_creator(tasks, by_assignee, by_creator) for idx, task in enumerate(tasks): assignees = [f"<{a.individual.weblink}|{a.individual.name}>" for a in task.assignees] task_button = TaskButton( organization_slug=task.project.organization.slug, action_type=action_type, incident_id=incident_id, resource_id=task.resource_id, ) blocks.append( { "type": "section", "text": { "type": "mrkdwn", "text": ( f"*Description:* <{task.weblink}|{task.description}>\n" f"*Creator:* <{task.creator.individual.weblink}|{task.creator.individual.name}>\n" f"*Assignees:* {", ".join(assignees)}" ), }, "block_id": f"{ConversationButtonActions.update_task_status}-{task.status}-{idx}", "accessory": { "type": "button", "text": {"type": "plain_text", "text": button_text}, "value": task_button.json(), }, } ) blocks.append({"type": "divider"}) dispatch_slack_service.send_ephemeral_message( slack_client, channel_id, user_id, "Incident Task List", blocks=blocks, ) @slack_background_task def list_workflows( user_id: str, user_email: str, channel_id: str, incident_id: int, command: dict = None, db_session=None, slack_client=None, ): """Returns the list of incident workflows to the user as an ephemeral message.""" incident = incident_service.get(db_session=db_session, incident_id=incident_id) blocks = [] blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": "*Incident Workflows*"}}) for w in incident.workflow_instances: artifact_links = "" for a in w.artifacts: artifact_links += f"- <{a.weblink}|{a.name}> \n" blocks.append( { "type": "section", "text": { "type": "mrkdwn", "text": ( f"*Name:* <{w.weblink}|{w.workflow.name}>\n" f"*Workflow Description:* {w.workflow.description}\n" f"*Run Reason:* {w.run_reason}\n" f"*Creator:* {w.creator.individual.name}\n" f"*Status:* {w.status}\n" f"*Artifacts:* \n {artifact_links}" ), }, } ) blocks.append({"type": "divider"}) dispatch_slack_service.send_ephemeral_message( slack_client, channel_id, user_id, "Incident Workflow List", blocks=blocks, ) @slack_background_task def list_participants( user_id: str, user_email: str, channel_id: str, incident_id: int, command: dict = None, db_session=None, slack_client=None, ): """Returns the list of incident participants to the user as an ephemeral message.""" blocks = [] blocks.append( {"type": "section", "text": {"type": "mrkdwn", "text": "*Incident Participants*"}} ) participants = participant_service.get_all_by_incident_id( db_session=db_session, incident_id=incident_id ).all() incident = incident_service.get(db_session=db_session, incident_id=incident_id) contact_plugin = plugin_service.get_active_instance( db_session=db_session, project_id=incident.project.id, plugin_type="contact" ) for participant in participants: if participant.active_roles: participant_email = participant.individual.email participant_info = contact_plugin.instance.get(participant_email, db_session=db_session) participant_name = participant_info.get("fullname", participant.individual.email) participant_team = participant_info.get("team", "Unknown") participant_department = participant_info.get("department", "Unknown") participant_location = participant_info.get("location", "Unknown") participant_weblink = participant_info.get("weblink") participant_avatar_url = dispatch_slack_service.get_user_avatar_url( slack_client, participant_email ) participant_reason_added = participant.added_reason or "Unknown" if participant.added_by: participant_added_by = participant.added_by.individual.name else: participant_added_by = "Unknown" participant_active_roles = participant_role_service.get_all_active_roles( db_session=db_session, participant_id=participant.id ) participant_roles = [] for role in participant_active_roles: participant_roles.append(role.role) # TODO we should make this more resilient to missing data (kglisson) block = { "type": "section", "text": { "type": "mrkdwn", "text": ( f"*Name:* <{participant_weblink}|{participant_name} ({participant_email})>\n" f"*Team*: {participant_team}, {participant_department}\n" f"*Location*: {participant_location}\n" f"*Incident Role(s)*: {(", ").join(participant_roles)}\n" f"*Reason Added*: {participant_reason_added}\n" f"*Added By*: {participant_added_by}\n" ), }, } if len(participants) < 20: block.update( { "accessory": { "type": "image", "alt_text": participant_name, "image_url": participant_avatar_url, }, } ) blocks.append(block) blocks.append({"type": "divider"}) dispatch_slack_service.send_ephemeral_message( slack_client, channel_id, user_id, "Incident Participant List", blocks=blocks, ) @slack_background_task def list_incidents( user_id: str, user_email: str, channel_id: str, incident_id: int, command: dict = None, db_session=None, slack_client=None, ): """Returns the list of current active and stable incidents, and closed incidents in the last 24 hours.""" projects = [] incidents = [] args = command["text"].split(" ") # scopes reply to the current incident's project incident = incident_service.get(db_session=db_session, incident_id=incident_id) if incident: # command was run in an incident conversation projects.append(incident.project) else: # command was run in a non-incident conversation if len(args) == 2: project = project_service.get_by_name(db_session=db_session, name=args[1]) if project: projects.append() else: raise ValidationError( [ ErrorWrapper( NotFoundError( msg=f"Project name '{args[1]}' in organization '{args[0]}' not found. Check your spelling." ), loc="project", ) ], model=BaseModel, ) else: projects = project_service.get_all(db_session=db_session) for project in projects: # we fetch active incidents incidents.extend( incident_service.get_all_by_status( db_session=db_session, project_id=project.id, status=IncidentStatus.active ) ) # We fetch stable incidents incidents.extend( incident_service.get_all_by_status( db_session=db_session, project_id=project.id, status=IncidentStatus.stable, ) ) # We fetch closed incidents in the last 24 hours incidents.extend( incident_service.get_all_last_x_hours_by_status( db_session=db_session, project_id=project.id, status=IncidentStatus.closed, hours=24, ) ) blocks = [] blocks.append({"type": "header", "text": {"type": "plain_text", "text": "List of Incidents"}}) if incidents: for incident in incidents: if incident.visibility == Visibility.open: ticket_weblink = resolve_attr(incident, "ticket.weblink") try: blocks.append( { "type": "section", "text": { "type": "mrkdwn", "text": ( f"*<{ticket_weblink}|{incident.name}>*\n" f"*Title*: {incident.title}\n" f"*Type*: {incident.incident_type.name}\n" f"*Priority*: {incident.incident_priority.name}\n" f"*Status*: {incident.status}\n" f"*Incident Commander*: <{incident.commander.individual.weblink}|{incident.commander.individual.name}>\n" f"*Project*: {incident.project.name}" ), }, } ) except Exception as e: log.exception(e) dispatch_slack_service.send_ephemeral_message( slack_client, channel_id, user_id, "Incident List", blocks=blocks, )
import base64 import logging from typing import List from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.main import BaseModel from sqlalchemy.orm import Session from dispatch.exceptions import NotFoundError from dispatch.conversation import service as conversation_service from dispatch.conversation.enums import ConversationButtonActions from dispatch.database.core import resolve_attr from dispatch.enums import Visibility from dispatch.incident import service as incident_service from dispatch.incident.enums import IncidentStatus from dispatch.incident.messaging import send_incident_resources_ephemeral_message_to_participant from dispatch.participant import service as participant_service from dispatch.participant_role import service as participant_role_service from dispatch.participant_role.models import ParticipantRoleType from dispatch.plugin import service as plugin_service from dispatch.plugins.dispatch_slack import service as dispatch_slack_service from dispatch.plugins.dispatch_slack.models import TaskButton from dispatch.project import service as project_service from dispatch.task import service as task_service from dispatch.task.enums import TaskStatus from dispatch.task.models import Task from .config import ( SLACK_APP_USER_SLUG, SLACK_COMMAND_ADD_TIMELINE_EVENT_SLUG, SLACK_COMMAND_ASSIGN_ROLE_SLUG, SLACK_COMMAND_ENGAGE_ONCALL_SLUG, SLACK_COMMAND_LIST_INCIDENTS_SLUG, SLACK_COMMAND_LIST_MY_TASKS_SLUG, SLACK_COMMAND_LIST_PARTICIPANTS_SLUG, SLACK_COMMAND_LIST_RESOURCES_SLUG, SLACK_COMMAND_LIST_TASKS_SLUG, SLACK_COMMAND_REPORT_EXECUTIVE_SLUG, SLACK_COMMAND_REPORT_INCIDENT_SLUG, SLACK_COMMAND_REPORT_TACTICAL_SLUG, SLACK_COMMAND_UPDATE_INCIDENT_SLUG, SLACK_COMMAND_UPDATE_NOTIFICATIONS_GROUP_SLUG, SLACK_COMMAND_UPDATE_PARTICIPANT_SLUG, SLACK_COMMAND_RUN_WORKFLOW_SLUG, SLACK_COMMAND_LIST_WORKFLOWS_SLUG, ) from .decorators import ( get_organization_scope_from_channel_id, slack_background_task, ) from .dialogs import ( create_assign_role_dialog, create_engage_oncall_dialog, create_executive_report_dialog, create_tactical_report_dialog, ) from .messaging import ( INCIDENT_CONVERSATION_COMMAND_MESSAGE, create_command_run_in_conversation_where_bot_not_present_message, create_command_run_in_nonincident_conversation_message, create_command_run_by_non_privileged_user_message, ) from .modals.incident.handlers import ( create_add_timeline_event_modal, create_report_incident_modal, create_update_incident_modal, create_update_notifications_group_modal, create_update_participant_modal, ) from .modals.workflow.handlers import create_run_workflow_modal log = logging.getLogger(__name__) def base64_encode(input: str): """Returns a b64 encoded string.""" return base64.b64encode(input.encode("ascii")).decode("ascii") def check_command_restrictions( command: str, user_email: str, incident_id: int, db_session: Session ) -> bool: """Checks the current user's role to determine what commands they are allowed to run.""" # some commands are sensitive and we only let non-participants execute them command_permissons = { SLACK_COMMAND_UPDATE_INCIDENT_SLUG: [ ParticipantRoleType.incident_commander, ParticipantRoleType.scribe, ], SLACK_COMMAND_ASSIGN_ROLE_SLUG: [ ParticipantRoleType.incident_commander, ParticipantRoleType.reporter, ParticipantRoleType.liaison, ParticipantRoleType.scribe, ], SLACK_COMMAND_REPORT_EXECUTIVE_SLUG: [ ParticipantRoleType.incident_commander, ParticipantRoleType.scribe, ], SLACK_COMMAND_REPORT_TACTICAL_SLUG: [ ParticipantRoleType.incident_commander, ParticipantRoleType.scribe, ], } # no permissions have been defined if command not in command_permissons.keys(): return True participant = participant_service.get_by_incident_id_and_email( db_session=db_session, incident_id=incident_id, email=user_email ) # if any required role is active, allow command for active_role in participant.active_roles: for allowed_role in command_permissons[command]: if active_role.role == allowed_role: return True def command_functions(command: str): """Interprets the command and routes it the appropriate function.""" command_mappings = { SLACK_COMMAND_ADD_TIMELINE_EVENT_SLUG: [create_add_timeline_event_modal], SLACK_COMMAND_ASSIGN_ROLE_SLUG: [create_assign_role_dialog], SLACK_COMMAND_ENGAGE_ONCALL_SLUG: [create_engage_oncall_dialog], SLACK_COMMAND_LIST_INCIDENTS_SLUG: [list_incidents], SLACK_COMMAND_LIST_MY_TASKS_SLUG: [list_my_tasks], SLACK_COMMAND_LIST_PARTICIPANTS_SLUG: [list_participants], SLACK_COMMAND_LIST_RESOURCES_SLUG: [list_resources], SLACK_COMMAND_LIST_TASKS_SLUG: [list_tasks], SLACK_COMMAND_REPORT_EXECUTIVE_SLUG: [create_executive_report_dialog], SLACK_COMMAND_REPORT_INCIDENT_SLUG: [create_report_incident_modal], SLACK_COMMAND_REPORT_TACTICAL_SLUG: [create_tactical_report_dialog], SLACK_COMMAND_UPDATE_NOTIFICATIONS_GROUP_SLUG: [create_update_notifications_group_modal], SLACK_COMMAND_UPDATE_PARTICIPANT_SLUG: [create_update_participant_modal], SLACK_COMMAND_UPDATE_INCIDENT_SLUG: [create_update_incident_modal], SLACK_COMMAND_RUN_WORKFLOW_SLUG: [create_run_workflow_modal], SLACK_COMMAND_LIST_WORKFLOWS_SLUG: [list_workflows], } return command_mappings.get(command, []) def filter_tasks_by_assignee_and_creator(tasks: List[Task], by_assignee: str, by_creator: str): """Filters a list of tasks looking for a given creator or assignee.""" filtered_tasks = [] for t in tasks: if by_creator: creator_email = t.creator.individual.email if creator_email == by_creator: filtered_tasks.append(t) # lets avoid duplication if creator is also assignee continue if by_assignee: assignee_emails = [a.individual.email for a in t.assignees] if by_assignee in assignee_emails: filtered_tasks.append(t) return filtered_tasks async def handle_non_incident_conversation_commands(client, request, background_tasks): """Handles all commands that do not have a specific incident conversation.""" command = request.get("command") channel_id = request.get("channel_id") command_args = request.get("text", "").split(" ") if command_args: organization_slug = command_args[0] # We get the list of public and private conversations the Dispatch bot is a member of ( public_conversations, private_conversations, ) = await dispatch_slack_service.get_conversations_by_user_id_async(client, SLACK_APP_USER_SLUG) # We get the name of conversation where the command was run conversation_name = await dispatch_slack_service.get_conversation_name_by_id_async( client, channel_id ) if ( not conversation_name or conversation_name not in public_conversations + private_conversations ): # We let the user know in which public conversations they can run the command return create_command_run_in_conversation_where_bot_not_present_message( command, public_conversations ) user_id = request.get("user_id") user_email = await dispatch_slack_service.get_user_email_async(client, user_id) for f in command_functions(command): background_tasks.add_task( f, user_id, user_email, channel_id, None, organization_slug=organization_slug, command=request, ) return INCIDENT_CONVERSATION_COMMAND_MESSAGE.get(command, f"Running... Command: {command}") async def handle_incident_conversation_commands(client, request, background_tasks): """Handles all commands that are issued from an incident conversation.""" channel_id = request.get("channel_id") command = request.get("command") db_session = get_organization_scope_from_channel_id(channel_id=channel_id) if not db_session: # We let the user know that incident-specific commands # can only be run in incident conversations return create_command_run_in_nonincident_conversation_message(command) conversation = conversation_service.get_by_channel_id_ignoring_channel_type( db_session=db_session, channel_id=channel_id ) user_id = request.get("user_id") user_email = await dispatch_slack_service.get_user_email_async(client, user_id) # some commands are sensitive and we only let non-participants execute them allowed = check_command_restrictions( command=command, user_email=user_email, incident_id=conversation.incident.id, db_session=db_session, ) if not allowed: return create_command_run_by_non_privileged_user_message(command) for f in command_functions(command): background_tasks.add_task( f, user_id, user_email, channel_id, conversation.incident.id, command=request, ) return INCIDENT_CONVERSATION_COMMAND_MESSAGE.get(command, f"Running... Command: {command}") async def handle_slack_command(*, client, request, background_tasks): """Handles slack command message.""" # We get the name of command that was run command = request.get("command") if command in [SLACK_COMMAND_REPORT_INCIDENT_SLUG, SLACK_COMMAND_LIST_INCIDENTS_SLUG]: return await handle_non_incident_conversation_commands(client, request, background_tasks) else: return await handle_incident_conversation_commands(client, request, background_tasks) @slack_background_task def list_resources( user_id: str, user_email: str, channel_id: str, incident_id: int, command: dict = None, db_session=None, slack_client=None, ): """Runs the list incident resources flow.""" # we load the incident instance incident = incident_service.get(db_session=db_session, incident_id=incident_id) # we send the list of resources to the participant send_incident_resources_ephemeral_message_to_participant( command["user_id"], incident, db_session ) @slack_background_task def list_my_tasks( user_id: str, user_email: str, channel_id: str, incident_id: int, command: dict = None, db_session=None, slack_client=None, ): """Returns the list of incident tasks to the user as an ephemeral message.""" list_tasks( user_id=user_id, user_email=user_email, channel_id=channel_id, incident_id=incident_id, command=command, by_creator=user_email, by_assignee=user_email, db_session=db_session, slack_client=slack_client, ) @slack_background_task def list_tasks( user_id: str, user_email: str, channel_id: str, incident_id: int, command: dict = None, db_session=None, slack_client=None, by_creator: str = None, by_assignee: str = None, ): """Returns the list of incident tasks to the user as an ephemeral message.""" blocks = [] for status in TaskStatus: blocks.append( { "type": "section", "text": {"type": "mrkdwn", "text": f"*{status} Incident Tasks*"}, } ) button_text = "Resolve" if status == TaskStatus.open else "Re-open" action_type = "resolve" if status == TaskStatus.open else "reopen" tasks = task_service.get_all_by_incident_id_and_status( db_session=db_session, incident_id=incident_id, status=status ) if by_creator or by_assignee: tasks = filter_tasks_by_assignee_and_creator(tasks, by_assignee, by_creator) for idx, task in enumerate(tasks): assignees = [f"<{a.individual.weblink}|{a.individual.name}>" for a in task.assignees] task_button = TaskButton( organization_slug=task.project.organization.slug, action_type=action_type, incident_id=incident_id, resource_id=task.resource_id, ) blocks.append( { "type": "section", "text": { "type": "mrkdwn", "text": ( f"*Description:* <{task.weblink}|{task.description}>\n" f"*Creator:* <{task.creator.individual.weblink}|{task.creator.individual.name}>\n" f"*Assignees:* {', '.join(assignees)}" ), }, "block_id": f"{ConversationButtonActions.update_task_status}-{task.status}-{idx}", "accessory": { "type": "button", "text": {"type": "plain_text", "text": button_text}, "value": task_button.json(), }, } ) blocks.append({"type": "divider"}) dispatch_slack_service.send_ephemeral_message( slack_client, channel_id, user_id, "Incident Task List", blocks=blocks, ) @slack_background_task def list_workflows( user_id: str, user_email: str, channel_id: str, incident_id: int, command: dict = None, db_session=None, slack_client=None, ): """Returns the list of incident workflows to the user as an ephemeral message.""" incident = incident_service.get(db_session=db_session, incident_id=incident_id) blocks = [] blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": "*Incident Workflows*"}}) for w in incident.workflow_instances: artifact_links = "" for a in w.artifacts: artifact_links += f"- <{a.weblink}|{a.name}> \n" blocks.append( { "type": "section", "text": { "type": "mrkdwn", "text": ( f"*Name:* <{w.weblink}|{w.workflow.name}>\n" f"*Workflow Description:* {w.workflow.description}\n" f"*Run Reason:* {w.run_reason}\n" f"*Creator:* {w.creator.individual.name}\n" f"*Status:* {w.status}\n" f"*Artifacts:* \n {artifact_links}" ), }, } ) blocks.append({"type": "divider"}) dispatch_slack_service.send_ephemeral_message( slack_client, channel_id, user_id, "Incident Workflow List", blocks=blocks, ) @slack_background_task def list_participants( user_id: str, user_email: str, channel_id: str, incident_id: int, command: dict = None, db_session=None, slack_client=None, ): """Returns the list of incident participants to the user as an ephemeral message.""" blocks = [] blocks.append( {"type": "section", "text": {"type": "mrkdwn", "text": "*Incident Participants*"}} ) participants = participant_service.get_all_by_incident_id( db_session=db_session, incident_id=incident_id ).all() incident = incident_service.get(db_session=db_session, incident_id=incident_id) contact_plugin = plugin_service.get_active_instance( db_session=db_session, project_id=incident.project.id, plugin_type="contact" ) for participant in participants: if participant.active_roles: participant_email = participant.individual.email participant_info = contact_plugin.instance.get(participant_email, db_session=db_session) participant_name = participant_info.get("fullname", participant.individual.email) participant_team = participant_info.get("team", "Unknown") participant_department = participant_info.get("department", "Unknown") participant_location = participant_info.get("location", "Unknown") participant_weblink = participant_info.get("weblink") participant_avatar_url = dispatch_slack_service.get_user_avatar_url( slack_client, participant_email ) participant_reason_added = participant.added_reason or "Unknown" if participant.added_by: participant_added_by = participant.added_by.individual.name else: participant_added_by = "Unknown" participant_active_roles = participant_role_service.get_all_active_roles( db_session=db_session, participant_id=participant.id ) participant_roles = [] for role in participant_active_roles: participant_roles.append(role.role) # TODO we should make this more resilient to missing data (kglisson) block = { "type": "section", "text": { "type": "mrkdwn", "text": ( f"*Name:* <{participant_weblink}|{participant_name} ({participant_email})>\n" f"*Team*: {participant_team}, {participant_department}\n" f"*Location*: {participant_location}\n" f"*Incident Role(s)*: {(', ').join(participant_roles)}\n" f"*Reason Added*: {participant_reason_added}\n" f"*Added By*: {participant_added_by}\n" ), }, } if len(participants) < 20: block.update( { "accessory": { "type": "image", "alt_text": participant_name, "image_url": participant_avatar_url, }, } ) blocks.append(block) blocks.append({"type": "divider"}) dispatch_slack_service.send_ephemeral_message( slack_client, channel_id, user_id, "Incident Participant List", blocks=blocks, ) @slack_background_task def list_incidents( user_id: str, user_email: str, channel_id: str, incident_id: int, command: dict = None, db_session=None, slack_client=None, ): """Returns the list of current active and stable incidents, and closed incidents in the last 24 hours.""" projects = [] incidents = [] args = command["text"].split(" ") # scopes reply to the current incident's project incident = incident_service.get(db_session=db_session, incident_id=incident_id) if incident: # command was run in an incident conversation projects.append(incident.project) else: # command was run in a non-incident conversation if len(args) == 2: project = project_service.get_by_name(db_session=db_session, name=args[1]) if project: projects.append() else: raise ValidationError( [ ErrorWrapper( NotFoundError( msg=f"Project name '{args[1]}' in organization '{args[0]}' not found. Check your spelling." ), loc="project", ) ], model=BaseModel, ) else: projects = project_service.get_all(db_session=db_session) for project in projects: # we fetch active incidents incidents.extend( incident_service.get_all_by_status( db_session=db_session, project_id=project.id, status=IncidentStatus.active ) ) # We fetch stable incidents incidents.extend( incident_service.get_all_by_status( db_session=db_session, project_id=project.id, status=IncidentStatus.stable, ) ) # We fetch closed incidents in the last 24 hours incidents.extend( incident_service.get_all_last_x_hours_by_status( db_session=db_session, project_id=project.id, status=IncidentStatus.closed, hours=24, ) ) blocks = [] blocks.append({"type": "header", "text": {"type": "plain_text", "text": "List of Incidents"}}) if incidents: for incident in incidents: if incident.visibility == Visibility.open: ticket_weblink = resolve_attr(incident, "ticket.weblink") try: blocks.append( { "type": "section", "text": { "type": "mrkdwn", "text": ( f"*<{ticket_weblink}|{incident.name}>*\n" f"*Title*: {incident.title}\n" f"*Type*: {incident.incident_type.name}\n" f"*Priority*: {incident.incident_priority.name}\n" f"*Status*: {incident.status}\n" f"*Incident Commander*: <{incident.commander.individual.weblink}|{incident.commander.individual.name}>\n" f"*Project*: {incident.project.name}" ), }, } ) except Exception as e: log.exception(e) dispatch_slack_service.send_ephemeral_message( slack_client, channel_id, user_id, "Incident List", blocks=blocks, )
import multiprocessing import os import re import subprocess from concurrent.futures import ProcessPoolExecutor from enum import Enum from functools import partial from pathlib import Path import fire from tools.pykitti_eval.utils.find import find_cuda, find_cuda_device_arch class Gpp: def __init__(self, sources, target, std="c++11", includes: list = None, defines: dict = None, cflags: str = None, compiler="g++", link=False, libraries: dict = None, lflags: str = None, extra_cflags: str = None, extra_lflags: str = None, build_directory: str = None): if not isinstance(sources, (list, tuple)): sources = [sources] if build_directory is not None: build_directory = Path(build_directory) new_sources = [] for p in sources: if not Path(p).is_absolute(): new_sources.append(str(build_directory / p)) else: new_sources.append(p) sources = new_sources target = Path(target) if not target.is_absolute(): target = str(build_directory / target) self.sources = [str(p) for p in sources] self.target = str(target) self.std = std self.includes = includes or [] self.cflags = cflags or '-fPIC -O3' self.defines = defines or {} self.compiler = compiler self.link = link self.libraries = libraries or {} self.lflags = lflags or '' self.extra_cflags = extra_cflags or '' self.extra_lflags = extra_lflags or '' def shell(self, target: str = None, compiler: str = None): defines = [f"-D {n}={v}" for n, v in self.defines.items()] includes = [f"-I{inc}" for inc in self.includes] libraries = [ f"-L{n} {" ".join(["-l" + l for l in v])}" for n, v in self.libraries.items() ] compiler = compiler or self.compiler string = f"{compiler} -std={self.std} " if self.link: string += " -shared " else: string += " -c " target = target or self.target string += (f"-o {target} {" ".join(self.sources)} " f"{" ".join(defines)} " f"{" ".join(includes)} " f"{self.cflags} {self.extra_cflags}" f"{" ".join(libraries)} " f"{self.lflags} {self.extra_lflags}") return re.sub(r" +", r" ", string) class Link: def __init__(self, outs, target, compiler="ld", build_directory: str = None): if not isinstance(outs, (list, tuple)): outs = [outs] if build_directory is not None: build_directory = Path(build_directory) new_outs = [] for p in outs: if not Path(p).is_absolute(): new_outs.append(str(build_directory / p)) else: new_outs.append(p) outs = new_outs target = Path(target) if target.is_absolute(): target = str(build_directory / target) self.outs = [str(p) for p in outs] self.target = str(target) self.compiler = compiler def shell(self, target: str = None): string = f"{self.compiler} -r " if target is None: target = self.target string += (f"-o {target} {" ".join(self.outs)} ") return string class Nvcc(Gpp): def __init__(self, sources, target, arch=None, std="c++11", includes: list = None, defines: dict = None, cflags: str = None, extra_cflags: str = None, extra_lflags: str = None, build_directory: str = None): if arch is None: arch = find_cuda_device_arch() if arch is None: raise ValueError("you must specify arch if use cuda.") cflags = cflags or f"-x cu -Xcompiler -fPIC -arch={arch} --expt-relaxed-constexpr" try: cuda_home = find_cuda() except: cuda_home = None if cuda_home is not None: cuda_include = Path(cuda_home) / "include" includes = includes or [] includes += [str(cuda_include)] super().__init__( sources, target, std, includes, defines, cflags, compiler="nvcc", extra_cflags=extra_cflags, extra_lflags=extra_lflags, build_directory=build_directory) class CUDALink(Gpp): def __init__(self, sources, target, std="c++11", includes: list = None, defines: dict = None, cflags: str = None, libraries: dict = None, lflags: str = None, extra_cflags: str = None, extra_lflags: str = None, build_directory: str = None): includes = includes or [] defines = defines or {} libraries = libraries or {} cflags = cflags or "-fPIC -O3" try: cuda_home = find_cuda() except: cuda_home = None if cuda_home is not None: cuda_include = Path(cuda_home) / "include" includes += [str(cuda_include)] cuda_lib_path = Path(cuda_home) / "lib64" cuda_libs = {str(cuda_lib_path): ["cublas", "cudart"]} libraries = {**libraries, **cuda_libs} super().__init__( sources, target, std, includes, defines, cflags, link=True, libraries=libraries, lflags=lflags, extra_cflags=extra_cflags, extra_lflags=extra_lflags, build_directory=build_directory) class NodeState(Enum): Evaled = "evaled" Normal = "normal" Error = "error" class Node: def __init__(self, name=None): self.name = name self.prev = [] self.next = [] self.state = NodeState.Normal def __call__(self, *nodes): for node in nodes: self.prev.append(node) node.next.append(self) return self def _eval(self, *args, **kw): return True def eval(self, *args, **kw): for p in self.prev: if not p.eval(*args, **kw): self.state = NodeState.Error return False if self.state == NodeState.Normal: if self._eval(*args, **kw): self.state = NodeState.Evaled else: self.state = NodeState.Error return True return True def reset(self): self.state = NodeState.Normal self.prev = [] self.next = [] for node in self.prev: node.reset() class TargetNode(Node): def __init__(self, srcs, hdrs, deps, copts, name=None): super().__init__(name) self.srcs = srcs self.hdrs = hdrs self.deps = deps self.copts = copts def _eval(self, executor): pass def compile_func(cmd, code_folder, compiler): if not isinstance(cmd, (Link, Nvcc)): shell = cmd.shell(compiler=compiler) else: shell = cmd.shell() print(shell) cwd = None if code_folder is not None: cwd = str(code_folder) ret = subprocess.run(shell, shell=True, cwd=cwd) if ret.returncode != 0: raise RuntimeError("compile failed with retcode", ret.returncode) return ret def compile_libraries(cmds, code_folder=None, compiler: str = None, num_workers=-1): if num_workers == -1: num_workers = min(len(cmds), multiprocessing.cpu_count()) # for cmd in cmds: # print(cmd.shell()) if num_workers == 0: rets = map( partial(compile_func, code_folder=code_folder, compiler=compiler), cmds) else: with ProcessPoolExecutor(num_workers) as pool: func = partial( compile_func, code_folder=code_folder, compiler=compiler) rets = pool.map(func, cmds) if any([r.returncode != 0 for r in rets]): cmds.clear() return False cmds.clear() return True def out(path): return Path(path).parent / (Path(path).stem + ".o")
import multiprocessing import os import re import subprocess from concurrent.futures import ProcessPoolExecutor from enum import Enum from functools import partial from pathlib import Path import fire from tools.pykitti_eval.utils.find import find_cuda, find_cuda_device_arch class Gpp: def __init__(self, sources, target, std="c++11", includes: list = None, defines: dict = None, cflags: str = None, compiler="g++", link=False, libraries: dict = None, lflags: str = None, extra_cflags: str = None, extra_lflags: str = None, build_directory: str = None): if not isinstance(sources, (list, tuple)): sources = [sources] if build_directory is not None: build_directory = Path(build_directory) new_sources = [] for p in sources: if not Path(p).is_absolute(): new_sources.append(str(build_directory / p)) else: new_sources.append(p) sources = new_sources target = Path(target) if not target.is_absolute(): target = str(build_directory / target) self.sources = [str(p) for p in sources] self.target = str(target) self.std = std self.includes = includes or [] self.cflags = cflags or '-fPIC -O3' self.defines = defines or {} self.compiler = compiler self.link = link self.libraries = libraries or {} self.lflags = lflags or '' self.extra_cflags = extra_cflags or '' self.extra_lflags = extra_lflags or '' def shell(self, target: str = None, compiler: str = None): defines = [f"-D {n}={v}" for n, v in self.defines.items()] includes = [f"-I{inc}" for inc in self.includes] libraries = [ f"-L{n} {' '.join(['-l' + l for l in v])}" for n, v in self.libraries.items() ] compiler = compiler or self.compiler string = f"{compiler} -std={self.std} " if self.link: string += " -shared " else: string += " -c " target = target or self.target string += (f"-o {target} {' '.join(self.sources)} " f"{' '.join(defines)} " f"{' '.join(includes)} " f"{self.cflags} {self.extra_cflags}" f"{' '.join(libraries)} " f"{self.lflags} {self.extra_lflags}") return re.sub(r" +", r" ", string) class Link: def __init__(self, outs, target, compiler="ld", build_directory: str = None): if not isinstance(outs, (list, tuple)): outs = [outs] if build_directory is not None: build_directory = Path(build_directory) new_outs = [] for p in outs: if not Path(p).is_absolute(): new_outs.append(str(build_directory / p)) else: new_outs.append(p) outs = new_outs target = Path(target) if target.is_absolute(): target = str(build_directory / target) self.outs = [str(p) for p in outs] self.target = str(target) self.compiler = compiler def shell(self, target: str = None): string = f"{self.compiler} -r " if target is None: target = self.target string += (f"-o {target} {' '.join(self.outs)} ") return string class Nvcc(Gpp): def __init__(self, sources, target, arch=None, std="c++11", includes: list = None, defines: dict = None, cflags: str = None, extra_cflags: str = None, extra_lflags: str = None, build_directory: str = None): if arch is None: arch = find_cuda_device_arch() if arch is None: raise ValueError("you must specify arch if use cuda.") cflags = cflags or f"-x cu -Xcompiler -fPIC -arch={arch} --expt-relaxed-constexpr" try: cuda_home = find_cuda() except: cuda_home = None if cuda_home is not None: cuda_include = Path(cuda_home) / "include" includes = includes or [] includes += [str(cuda_include)] super().__init__( sources, target, std, includes, defines, cflags, compiler="nvcc", extra_cflags=extra_cflags, extra_lflags=extra_lflags, build_directory=build_directory) class CUDALink(Gpp): def __init__(self, sources, target, std="c++11", includes: list = None, defines: dict = None, cflags: str = None, libraries: dict = None, lflags: str = None, extra_cflags: str = None, extra_lflags: str = None, build_directory: str = None): includes = includes or [] defines = defines or {} libraries = libraries or {} cflags = cflags or "-fPIC -O3" try: cuda_home = find_cuda() except: cuda_home = None if cuda_home is not None: cuda_include = Path(cuda_home) / "include" includes += [str(cuda_include)] cuda_lib_path = Path(cuda_home) / "lib64" cuda_libs = {str(cuda_lib_path): ["cublas", "cudart"]} libraries = {**libraries, **cuda_libs} super().__init__( sources, target, std, includes, defines, cflags, link=True, libraries=libraries, lflags=lflags, extra_cflags=extra_cflags, extra_lflags=extra_lflags, build_directory=build_directory) class NodeState(Enum): Evaled = "evaled" Normal = "normal" Error = "error" class Node: def __init__(self, name=None): self.name = name self.prev = [] self.next = [] self.state = NodeState.Normal def __call__(self, *nodes): for node in nodes: self.prev.append(node) node.next.append(self) return self def _eval(self, *args, **kw): return True def eval(self, *args, **kw): for p in self.prev: if not p.eval(*args, **kw): self.state = NodeState.Error return False if self.state == NodeState.Normal: if self._eval(*args, **kw): self.state = NodeState.Evaled else: self.state = NodeState.Error return True return True def reset(self): self.state = NodeState.Normal self.prev = [] self.next = [] for node in self.prev: node.reset() class TargetNode(Node): def __init__(self, srcs, hdrs, deps, copts, name=None): super().__init__(name) self.srcs = srcs self.hdrs = hdrs self.deps = deps self.copts = copts def _eval(self, executor): pass def compile_func(cmd, code_folder, compiler): if not isinstance(cmd, (Link, Nvcc)): shell = cmd.shell(compiler=compiler) else: shell = cmd.shell() print(shell) cwd = None if code_folder is not None: cwd = str(code_folder) ret = subprocess.run(shell, shell=True, cwd=cwd) if ret.returncode != 0: raise RuntimeError("compile failed with retcode", ret.returncode) return ret def compile_libraries(cmds, code_folder=None, compiler: str = None, num_workers=-1): if num_workers == -1: num_workers = min(len(cmds), multiprocessing.cpu_count()) # for cmd in cmds: # print(cmd.shell()) if num_workers == 0: rets = map( partial(compile_func, code_folder=code_folder, compiler=compiler), cmds) else: with ProcessPoolExecutor(num_workers) as pool: func = partial( compile_func, code_folder=code_folder, compiler=compiler) rets = pool.map(func, cmds) if any([r.returncode != 0 for r in rets]): cmds.clear() return False cmds.clear() return True def out(path): return Path(path).parent / (Path(path).stem + ".o")
#!/usr/bin/env python3 from numpy.random import default_rng import argparse import csv if __name__ == '__main__': parser = argparse.ArgumentParser(description='Create reviewing assignments') parser.add_argument('--n', dest='n', type=int, default=3, required=False, help='number of reviews per submission') args = parser.parse_args() with open('reviewers.txt') as f: all_reviewers = f.read().splitlines() reviewer_counts = {} for r in all_reviewers: reviewer_counts[r] = 0 submissions = [] submitters = {} with open('submissions.csv') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: submission = row[0] submitter = row[1] submissions.append(submission) submitters[submission] = submitter rng = default_rng() assignments = {} # print CSV header print("--- Assignments ---") header = ['Submission'] + [f'R{i}' for i in range(1,args.n+1)] print(','.join(header)) for s in submissions: # reviewer probabilities m = max(reviewer_counts.values()) p = [m - v + 1 for v in reviewer_counts.values()] # if there's a conflict, set the prob to 0 so it's not assigned try: i = list(reviewer_counts.keys()).index(submitters[s]) p[i] = 0 except ValueError: pass # normalize to 1 probs = [v / sum(p) for v in p] # pick reviewers reviewers = rng.choice(list(reviewer_counts.keys()), size=args.n, replace=False, p=probs) assignments[s] = reviewers print(f'{s},{','.join(assignments[s])}') for r in reviewers: reviewer_counts[r] = reviewer_counts.get(r) + 1 print("--- Assignment Counts ---") print("Reviewer,Count") for r in all_reviewers: print(f'{r},{reviewer_counts[r]}')
#!/usr/bin/env python3 from numpy.random import default_rng import argparse import csv if __name__ == '__main__': parser = argparse.ArgumentParser(description='Create reviewing assignments') parser.add_argument('--n', dest='n', type=int, default=3, required=False, help='number of reviews per submission') args = parser.parse_args() with open('reviewers.txt') as f: all_reviewers = f.read().splitlines() reviewer_counts = {} for r in all_reviewers: reviewer_counts[r] = 0 submissions = [] submitters = {} with open('submissions.csv') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: submission = row[0] submitter = row[1] submissions.append(submission) submitters[submission] = submitter rng = default_rng() assignments = {} # print CSV header print("--- Assignments ---") header = ['Submission'] + [f'R{i}' for i in range(1,args.n+1)] print(','.join(header)) for s in submissions: # reviewer probabilities m = max(reviewer_counts.values()) p = [m - v + 1 for v in reviewer_counts.values()] # if there's a conflict, set the prob to 0 so it's not assigned try: i = list(reviewer_counts.keys()).index(submitters[s]) p[i] = 0 except ValueError: pass # normalize to 1 probs = [v / sum(p) for v in p] # pick reviewers reviewers = rng.choice(list(reviewer_counts.keys()), size=args.n, replace=False, p=probs) assignments[s] = reviewers print(f'{s},{",".join(assignments[s])}') for r in reviewers: reviewer_counts[r] = reviewer_counts.get(r) + 1 print("--- Assignment Counts ---") print("Reviewer,Count") for r in all_reviewers: print(f'{r},{reviewer_counts[r]}')
from multiprocessing import Pool import cv2 import glob import os.path as osp import os class DOTAImageSplitTool(object): def __init__(self, in_root, out_root, tile_overlap, tile_shape, num_process=8, ): self.in_images_dir = osp.join(in_root, 'images/images/') self.in_labels_dir = osp.join(in_root, 'labelTxt-v1.0/') self.out_images_dir = osp.join(out_root, 'images/') self.out_labels_dir = osp.join(out_root, 'labelTxt/') assert isinstance(tile_shape, tuple), f'argument "tile_shape" must be tuple but got {type(tile_shape)} instead!' assert isinstance(tile_overlap, tuple), f'argument "tile_overlap" must be tuple but got {type(tile_overlap)} instead!' self.tile_overlap = tile_overlap self.tile_shape = tile_shape images = glob.glob(self.in_images_dir + '*.png') labels = glob.glob(self.in_labels_dir + '*.txt') image_ids = [*map(lambda x: osp.splitext(osp.split(x)[-1])[0], images)] label_ids = [*map(lambda x: osp.splitext(osp.split(x)[-1])[0], labels)] assert set(image_ids) == set(label_ids) self.image_ids = image_ids if not osp.isdir(out_root): os.mkdir(out_root) if not osp.isdir(self.out_images_dir): os.mkdir(self.out_images_dir) if not osp.isdir(self.out_labels_dir): os.mkdir(self.out_labels_dir) self.num_process = num_process def _parse_annotation_single(self, image_id): label_dir = osp.join(self.in_labels_dir, image_id + '.txt') with open(label_dir, 'r') as f: s = f.readlines() header = s[:2] objects = [] s = s[2:] for si in s: bbox_info = si.split() assert len(bbox_info) == 10 bbox = [*map(lambda x: int(x), bbox_info[:8])] center = sum(bbox[0::2]) / 4.0, sum(bbox[1::2]) / 4.0 objects.append({'bbox': bbox, 'label': bbox_info[8], 'difficulty': int(bbox_info[9]), 'center': center}) return header, objects def _split_single(self, image_id): hdr, objs = self._parse_annotation_single(image_id) image_dir = osp.join(self.in_images_dir, image_id + '.png') img = cv2.imread(image_dir) h, w, _ = img.shape w_ovr, h_ovr = self.tile_overlap w_s, h_s = self.tile_shape for h_off in range(0, max(1, h - h_ovr), h_s - h_ovr): if h_off > 0: h_off = min(h - h_s, h_off) # h_off + hs <= h if h_off > 0 for w_off in range(0, max(1, w - w_ovr), w_s - w_ovr): if w_off > 0: w_off = min(w - w_s, w_off) # w_off + ws <= w if w_off > 0 objs_tile = [] for obj in objs: if w_off <= obj['center'][0] <= w_off + w_s - 1: if h_off <= obj['center'][1] <= h_off + h_s - 1: objs_tile.append(obj) if len(objs_tile) > 0: img_tile = img[h_off:h_off + h_s, w_off:w_off + w_s, :] save_image_dir = osp.join(self.out_images_dir, f'{image_id}_{w_off}_{h_off}.png') save_label_dir = osp.join(self.out_labels_dir, f'{image_id}_{w_off}_{h_off}.txt') cv2.imwrite(save_image_dir, img_tile) label_tile = hdr[:] for obj in objs_tile: px, py = obj["bbox"][0::2], obj["bbox"][1::2] px = map(lambda x: str(x - w_off), px) py = map(lambda x: str(x - h_off), py) bbox_tile = sum([*zip(px, py)], ()) obj_s = f'{' '.join(bbox_tile)} {obj['label']} {obj['difficulty']}\n' label_tile.append(obj_s) with open(save_label_dir, 'w') as f: f.writelines(label_tile) def split(self): with Pool(self.num_process) as p: p.map(self._split_single, self.image_ids) if __name__ == '__main__': trainsplit = DOTAImageSplitTool('/home/YangLin/pycharm_project/r3det-on-mmdetection/data/dataset/DOTA/train', '/home/YangLin/pycharm_project/r3det-on-mmdetection/data/dataset/DOTA/trainsplit', tile_overlap=(150, 150), tile_shape=(600, 600)) trainsplit.split() valsplit = DOTAImageSplitTool('/home/YangLin/pycharm_project/r3det-on-mmdetection/data/dataset/DOTA/val', '/home/YangLin/pycharm_project/r3det-on-mmdetection/data/dataset/DOTA/valsplit', tile_overlap=(150, 150), tile_shape=(600, 600)) valsplit.split()
from multiprocessing import Pool import cv2 import glob import os.path as osp import os class DOTAImageSplitTool(object): def __init__(self, in_root, out_root, tile_overlap, tile_shape, num_process=8, ): self.in_images_dir = osp.join(in_root, 'images/images/') self.in_labels_dir = osp.join(in_root, 'labelTxt-v1.0/') self.out_images_dir = osp.join(out_root, 'images/') self.out_labels_dir = osp.join(out_root, 'labelTxt/') assert isinstance(tile_shape, tuple), f'argument "tile_shape" must be tuple but got {type(tile_shape)} instead!' assert isinstance(tile_overlap, tuple), f'argument "tile_overlap" must be tuple but got {type(tile_overlap)} instead!' self.tile_overlap = tile_overlap self.tile_shape = tile_shape images = glob.glob(self.in_images_dir + '*.png') labels = glob.glob(self.in_labels_dir + '*.txt') image_ids = [*map(lambda x: osp.splitext(osp.split(x)[-1])[0], images)] label_ids = [*map(lambda x: osp.splitext(osp.split(x)[-1])[0], labels)] assert set(image_ids) == set(label_ids) self.image_ids = image_ids if not osp.isdir(out_root): os.mkdir(out_root) if not osp.isdir(self.out_images_dir): os.mkdir(self.out_images_dir) if not osp.isdir(self.out_labels_dir): os.mkdir(self.out_labels_dir) self.num_process = num_process def _parse_annotation_single(self, image_id): label_dir = osp.join(self.in_labels_dir, image_id + '.txt') with open(label_dir, 'r') as f: s = f.readlines() header = s[:2] objects = [] s = s[2:] for si in s: bbox_info = si.split() assert len(bbox_info) == 10 bbox = [*map(lambda x: int(x), bbox_info[:8])] center = sum(bbox[0::2]) / 4.0, sum(bbox[1::2]) / 4.0 objects.append({'bbox': bbox, 'label': bbox_info[8], 'difficulty': int(bbox_info[9]), 'center': center}) return header, objects def _split_single(self, image_id): hdr, objs = self._parse_annotation_single(image_id) image_dir = osp.join(self.in_images_dir, image_id + '.png') img = cv2.imread(image_dir) h, w, _ = img.shape w_ovr, h_ovr = self.tile_overlap w_s, h_s = self.tile_shape for h_off in range(0, max(1, h - h_ovr), h_s - h_ovr): if h_off > 0: h_off = min(h - h_s, h_off) # h_off + hs <= h if h_off > 0 for w_off in range(0, max(1, w - w_ovr), w_s - w_ovr): if w_off > 0: w_off = min(w - w_s, w_off) # w_off + ws <= w if w_off > 0 objs_tile = [] for obj in objs: if w_off <= obj['center'][0] <= w_off + w_s - 1: if h_off <= obj['center'][1] <= h_off + h_s - 1: objs_tile.append(obj) if len(objs_tile) > 0: img_tile = img[h_off:h_off + h_s, w_off:w_off + w_s, :] save_image_dir = osp.join(self.out_images_dir, f'{image_id}_{w_off}_{h_off}.png') save_label_dir = osp.join(self.out_labels_dir, f'{image_id}_{w_off}_{h_off}.txt') cv2.imwrite(save_image_dir, img_tile) label_tile = hdr[:] for obj in objs_tile: px, py = obj["bbox"][0::2], obj["bbox"][1::2] px = map(lambda x: str(x - w_off), px) py = map(lambda x: str(x - h_off), py) bbox_tile = sum([*zip(px, py)], ()) obj_s = f'{" ".join(bbox_tile)} {obj["label"]} {obj["difficulty"]}\n' label_tile.append(obj_s) with open(save_label_dir, 'w') as f: f.writelines(label_tile) def split(self): with Pool(self.num_process) as p: p.map(self._split_single, self.image_ids) if __name__ == '__main__': trainsplit = DOTAImageSplitTool('/home/YangLin/pycharm_project/r3det-on-mmdetection/data/dataset/DOTA/train', '/home/YangLin/pycharm_project/r3det-on-mmdetection/data/dataset/DOTA/trainsplit', tile_overlap=(150, 150), tile_shape=(600, 600)) trainsplit.split() valsplit = DOTAImageSplitTool('/home/YangLin/pycharm_project/r3det-on-mmdetection/data/dataset/DOTA/val', '/home/YangLin/pycharm_project/r3det-on-mmdetection/data/dataset/DOTA/valsplit', tile_overlap=(150, 150), tile_shape=(600, 600)) valsplit.split()
import os import shutil import subprocess import zipfile from pathlib import Path from typing import Tuple, List, Optional from version import update_version_txt # Files or folders common to all bots. common_sharpy = [ ("jsonpickle", None), ("sharpy", None), (os.path.join("python-sc2", "sc2"), "sc2"), ("sc2pathlibp", None), ("config.py", None), ("ladder.py", None), ] common = [ ("requirements.txt", None), ("version.txt", None), ("config.ini", None), ("ladderbots.json", None), ] json = """{ "Bots": { "[NAME]": { "Race": "[RACE]", "Type": "Python", "RootPath": "./", "FileName": "run.py", "Debug": false } } }""" json_exe = """{ "Bots": { "[NAME]": { "Race": "[RACE]", "Type": "cppwin32", "RootPath": "./", "FileName": "[NAME].exe", "Debug": false } } }""" class LadderZip: archive: str files: List[Tuple[str, Optional[str]]] def __init__( self, archive_name: str, race: str, files: List[Tuple[str, Optional[str]]], common_files: List[Tuple[str, Optional[str]]] = None, ): self.name = archive_name self.race = race self.archive = archive_name + ".zip" self.files = files if common_files: self.files.extend(common_files) else: self.files.extend(common) self.files.extend(common_sharpy) # Executable # --specpath /opt/bk/spec --distpath /opt/bk/dist --workpath /opt/bk/build self.pyinstaller = ( 'pyinstaller -y --add-data "[FOLDER]/sc2pathlibp' '";"sc2pathlibp/" --add-data "[FOLDER]/sc2";"sc2/" ' '--add-data "[FOLDER]/config.ini";"." --add-data ' '"[FOLDER]/version.txt";"." ' '"[FOLDER]/run.py" ' '--add-binary="C:\\Windows\\System32\\vcomp140.dll";"." ' '-n "[NAME]" ' '--distpath "[OUTPUTFOLDER]"' ) def create_json(self): return json.replace("[NAME]", self.name).replace("[RACE]", self.race) def create_bin_json(self): return json_exe.replace("[NAME]", self.name).replace("[RACE]", self.race) def pre_zip(self): """ Override this as needed, actions to do before creating the zip""" pass def post_zip(self): """ Override this as needed, actions to do after creating the zip""" pass def package_executable(self, output_dir: str): zip_name = f"{self.name}_bin.zip" print() print("unzip") zip_path = os.path.join(output_dir, self.archive) source_path = os.path.join(output_dir, self.name + "_source") bin_path = os.path.join(output_dir, self.name) with zipfile.ZipFile(zip_path, "r") as zip_ref: zip_ref.extractall(source_path) print("run pyinstaller") self.pyinstaller = ( self.pyinstaller.replace("[FOLDER]", source_path) .replace("[OUTPUTFOLDER]", bin_path) .replace("[NAME]", self.name) ) print(self.pyinstaller) subprocess.run(self.pyinstaller) # Reset bin path as pyinstaller likes to make a new run folder run_path = os.path.join(bin_path, self.name) # TODO: Detect Windows and do this only on Windows icuuc52zip_path = None if os.path.exists("libs"): icuuc52zip_path = os.path.join("libs", "ic52.zip") elif os.path.exists("sharpy-sc2"): icuuc52zip_path = os.path.join("sharpy-sc2", "libs", "ic52.zip") if icuuc52zip_path: with zipfile.ZipFile(icuuc52zip_path, "r") as zip_ref: # Unzip the icudt52.dll, icuin52.dll and icuuc52.dll files zip_ref.extractall(run_path) else: print("WARNING: ic52.zip not found. Standalone mode might not work.") # remove PIL and cv2 print("removing PIL and cv2") shutil.rmtree(os.path.join(run_path, "cv2")) shutil.rmtree(os.path.join(run_path, "PIL")) # Create new ladderbots.json f = open(os.path.join(run_path, "ladderbots.json"), "w+") f.write(self.create_bin_json()) f.close() # Move data folder if that exists if os.path.exists(os.path.join(source_path, "data")): shutil.copytree(os.path.join(source_path, "data"), os.path.join(run_path, "data")) print("Zip executable version") zipf = zipfile.ZipFile(os.path.join(output_dir, zip_name), "w", zipfile.ZIP_DEFLATED) LadderZip.zipdir(run_path, zipf, run_path) zipf.close() shutil.rmtree(bin_path) shutil.rmtree(source_path) def create_ladder_zip(self, exe: bool): print() archive_name = self.archive bot_specific_paths = self.files # Remove previous archive if os.path.isfile(archive_name): print(f"Deleting {archive_name}") os.remove(archive_name) files_to_zip = [] directories_to_zip = [] files_to_delete = [] f = open("ladderbots.json", "w+") f.write(self.create_json()) f.close() self.pre_zip() for src, dest in bot_specific_paths: if not os.path.exists(src): raise ValueError(f"'{src}' does not exist.") if dest is None: # the file or folder can be used as is. if os.path.isdir(src): directories_to_zip.append(src) else: files_to_zip.append(src) else: # need to move the file or folder. if os.path.isdir(src): shutil.copytree(src, dest) directories_to_zip.append(dest) files_to_delete.append(dest) else: # src is a file. src_file = os.path.basename(src) if os.path.isdir(dest): # Join directory with filename dest_path = os.path.join(dest, src_file) else: # Rename into another file dest_path = dest files_to_zip.append(dest_path) print(f"Copying {src} ... {dest_path}") files_to_delete.append(dest_path) shutil.copy(src, dest_path) print() print(f"Zipping {archive_name}") zipf = zipfile.ZipFile(archive_name, "w", zipfile.ZIP_DEFLATED) for file in files_to_zip: zipf.write(file) for directory in directories_to_zip: LadderZip.zipdir(directory, zipf) zipf.close() print() for file in files_to_delete: if os.path.isdir(file): print(f"Deleting directory {file}") # os.rmdir(file) shutil.rmtree(file) else: print(f"Deleting file {file}") os.remove(file) os.remove("ladderbots.json") if not os.path.exists("publish"): os.mkdir("publish") shutil.move(archive_name, os.path.join("publish", archive_name)) self.post_zip() print(f"\nSuccessfully created {os.path.join("publish", archive_name)}") if exe: self.package_executable("publish") @staticmethod def zipdir(path: str, ziph: zipfile.ZipFile, remove_path: Optional[str] = None): # ziph is zipfile handle for root, dirs, files in os.walk(path): for file in files: if "__pycache__" not in root: path_to_file = os.path.join(root, file) if remove_path: ziph.write(path_to_file, path_to_file.replace(remove_path, "")) else: ziph.write(path_to_file)
import os import shutil import subprocess import zipfile from pathlib import Path from typing import Tuple, List, Optional from version import update_version_txt # Files or folders common to all bots. common_sharpy = [ ("jsonpickle", None), ("sharpy", None), (os.path.join("python-sc2", "sc2"), "sc2"), ("sc2pathlibp", None), ("config.py", None), ("ladder.py", None), ] common = [ ("requirements.txt", None), ("version.txt", None), ("config.ini", None), ("ladderbots.json", None), ] json = """{ "Bots": { "[NAME]": { "Race": "[RACE]", "Type": "Python", "RootPath": "./", "FileName": "run.py", "Debug": false } } }""" json_exe = """{ "Bots": { "[NAME]": { "Race": "[RACE]", "Type": "cppwin32", "RootPath": "./", "FileName": "[NAME].exe", "Debug": false } } }""" class LadderZip: archive: str files: List[Tuple[str, Optional[str]]] def __init__( self, archive_name: str, race: str, files: List[Tuple[str, Optional[str]]], common_files: List[Tuple[str, Optional[str]]] = None, ): self.name = archive_name self.race = race self.archive = archive_name + ".zip" self.files = files if common_files: self.files.extend(common_files) else: self.files.extend(common) self.files.extend(common_sharpy) # Executable # --specpath /opt/bk/spec --distpath /opt/bk/dist --workpath /opt/bk/build self.pyinstaller = ( 'pyinstaller -y --add-data "[FOLDER]/sc2pathlibp' '";"sc2pathlibp/" --add-data "[FOLDER]/sc2";"sc2/" ' '--add-data "[FOLDER]/config.ini";"." --add-data ' '"[FOLDER]/version.txt";"." ' '"[FOLDER]/run.py" ' '--add-binary="C:\\Windows\\System32\\vcomp140.dll";"." ' '-n "[NAME]" ' '--distpath "[OUTPUTFOLDER]"' ) def create_json(self): return json.replace("[NAME]", self.name).replace("[RACE]", self.race) def create_bin_json(self): return json_exe.replace("[NAME]", self.name).replace("[RACE]", self.race) def pre_zip(self): """ Override this as needed, actions to do before creating the zip""" pass def post_zip(self): """ Override this as needed, actions to do after creating the zip""" pass def package_executable(self, output_dir: str): zip_name = f"{self.name}_bin.zip" print() print("unzip") zip_path = os.path.join(output_dir, self.archive) source_path = os.path.join(output_dir, self.name + "_source") bin_path = os.path.join(output_dir, self.name) with zipfile.ZipFile(zip_path, "r") as zip_ref: zip_ref.extractall(source_path) print("run pyinstaller") self.pyinstaller = ( self.pyinstaller.replace("[FOLDER]", source_path) .replace("[OUTPUTFOLDER]", bin_path) .replace("[NAME]", self.name) ) print(self.pyinstaller) subprocess.run(self.pyinstaller) # Reset bin path as pyinstaller likes to make a new run folder run_path = os.path.join(bin_path, self.name) # TODO: Detect Windows and do this only on Windows icuuc52zip_path = None if os.path.exists("libs"): icuuc52zip_path = os.path.join("libs", "ic52.zip") elif os.path.exists("sharpy-sc2"): icuuc52zip_path = os.path.join("sharpy-sc2", "libs", "ic52.zip") if icuuc52zip_path: with zipfile.ZipFile(icuuc52zip_path, "r") as zip_ref: # Unzip the icudt52.dll, icuin52.dll and icuuc52.dll files zip_ref.extractall(run_path) else: print("WARNING: ic52.zip not found. Standalone mode might not work.") # remove PIL and cv2 print("removing PIL and cv2") shutil.rmtree(os.path.join(run_path, "cv2")) shutil.rmtree(os.path.join(run_path, "PIL")) # Create new ladderbots.json f = open(os.path.join(run_path, "ladderbots.json"), "w+") f.write(self.create_bin_json()) f.close() # Move data folder if that exists if os.path.exists(os.path.join(source_path, "data")): shutil.copytree(os.path.join(source_path, "data"), os.path.join(run_path, "data")) print("Zip executable version") zipf = zipfile.ZipFile(os.path.join(output_dir, zip_name), "w", zipfile.ZIP_DEFLATED) LadderZip.zipdir(run_path, zipf, run_path) zipf.close() shutil.rmtree(bin_path) shutil.rmtree(source_path) def create_ladder_zip(self, exe: bool): print() archive_name = self.archive bot_specific_paths = self.files # Remove previous archive if os.path.isfile(archive_name): print(f"Deleting {archive_name}") os.remove(archive_name) files_to_zip = [] directories_to_zip = [] files_to_delete = [] f = open("ladderbots.json", "w+") f.write(self.create_json()) f.close() self.pre_zip() for src, dest in bot_specific_paths: if not os.path.exists(src): raise ValueError(f"'{src}' does not exist.") if dest is None: # the file or folder can be used as is. if os.path.isdir(src): directories_to_zip.append(src) else: files_to_zip.append(src) else: # need to move the file or folder. if os.path.isdir(src): shutil.copytree(src, dest) directories_to_zip.append(dest) files_to_delete.append(dest) else: # src is a file. src_file = os.path.basename(src) if os.path.isdir(dest): # Join directory with filename dest_path = os.path.join(dest, src_file) else: # Rename into another file dest_path = dest files_to_zip.append(dest_path) print(f"Copying {src} ... {dest_path}") files_to_delete.append(dest_path) shutil.copy(src, dest_path) print() print(f"Zipping {archive_name}") zipf = zipfile.ZipFile(archive_name, "w", zipfile.ZIP_DEFLATED) for file in files_to_zip: zipf.write(file) for directory in directories_to_zip: LadderZip.zipdir(directory, zipf) zipf.close() print() for file in files_to_delete: if os.path.isdir(file): print(f"Deleting directory {file}") # os.rmdir(file) shutil.rmtree(file) else: print(f"Deleting file {file}") os.remove(file) os.remove("ladderbots.json") if not os.path.exists("publish"): os.mkdir("publish") shutil.move(archive_name, os.path.join("publish", archive_name)) self.post_zip() print(f"\nSuccessfully created {os.path.join('publish', archive_name)}") if exe: self.package_executable("publish") @staticmethod def zipdir(path: str, ziph: zipfile.ZipFile, remove_path: Optional[str] = None): # ziph is zipfile handle for root, dirs, files in os.walk(path): for file in files: if "__pycache__" not in root: path_to_file = os.path.join(root, file) if remove_path: ziph.write(path_to_file, path_to_file.replace(remove_path, "")) else: ziph.write(path_to_file)
import errno import glob import json import os import random import numpy import tracery from tracery.modifiers import base_english from PIL import Image from extended_english import extended_english def calculate_image_possibilities(): """Computes the total possible combinations for sword pieces Returns: The total number of unique combinations of sword pieces """ # Reordering the color ramps in the palette yields 3! combinations palette_reorder_possibilities = 6 return len(palettes) * palette_reorder_possibilities * len(grips) * len(pommels) * len(crossguards) * len(blades) def print_possibility_space(): """Displays the total combinations of various proc gen items.""" print("Possibility space:") print(" {} unique sword images".format(calculate_image_possibilities())) def generate_sword_image(): """Generates a sword image from pieces Returns: A PIL Image object. """ # Chose a random set of pieces palette = Image.open(random.choice(palettes), 'r') grip = Image.open(random.choice(grips), 'r') pommel = Image.open(random.choice(pommels), 'r') crossguard = Image.open(random.choice(crossguards), 'r') blade = Image.open(random.choice(blades), 'r') # Small chance to reorder palette primary_palette = palette.palette.palette[0:15] secondary_palette = palette.palette.palette[15:30] accent_palette = palette.palette.palette[30:45] transparency = palette.palette.palette[45:] p = primary_palette + secondary_palette + accent_palette + transparency if random.random() > 0.95: reordered_palettes = [ primary_palette + accent_palette + secondary_palette + transparency, secondary_palette + primary_palette + accent_palette + transparency, secondary_palette + accent_palette + primary_palette + transparency, accent_palette + primary_palette + secondary_palette + transparency, accent_palette + secondary_palette + primary_palette + transparency ] p = random.choice(reordered_palettes) # Apply palette for image in (grip, pommel, crossguard, blade): image.putpalette(p) composite = Image.new('RGBA', (32, 32)) # Paste with mask needs to be RGBA data. Convert() is used to accomplish this. composite.paste(grip) composite.paste(pommel, (0, 0), pommel.convert()) composite.paste(blade, (0, 0), blade.convert()) composite.paste(crossguard, (0, 0), crossguard.convert()) return composite damage_type_color = { 'MAGIC': {"x": 0.6172, "y": 0.0937, "z": 0.7695}, 'FIRE': {"x": 1.0, "y": 0.0, "z": 0.0}, 'ICE': {"x": 0.0, "y": 0.0, "z": 1.0}, 'LIGHTNING': {"x": 1.0, "y": 1.0, "z": 1.0}, 'POISON': {"x": 0.1529, "y": 1.0, "z": 0.3333}, 'HEALING': {"x": 0.0, "y": 1.0, "z": 1.0}, 'PARALYZE': {"x": 0.9294, "y": 0.7882, "z": 0.1921}, 'VAMPIRE': {"x": 0.13, "y": 0.1, "z": 0.15} } def generate_sword_data(index): """Generates sword JSON data Returns: Sword data as dict """ with open('./json/sword.json') as file: sword_data = json.loads(file.read()) with open('./json/names.json') as file: name_rules = json.loads(file.read()) name_grammar = tracery.Grammar(name_rules) name_grammar.add_modifiers(base_english) name_grammar.add_modifiers(extended_english) sword_data['name'] = f'Blade {index + 1}:\n{name_grammar.flatten('#root#')}' sword_data['tex'] = index sword_data['brokenTex'] = index sword_data['spriteAtlas'] = 'blades' sword_data['baseDamage'] = int(numpy.random.normal(10, 4)) sword_data['randDamage'] = int(numpy.random.normal(10, 4)) sword_data['durability'] = int(numpy.random.normal(100, 40)) sword_data['knockback'] = numpy.random.normal(0.15, 0.025) sword_data['reach'] = numpy.random.normal(0.5, 0.125) + 0.25 sword_data['speed'] = ((1 - (sword_data['baseDamage'] + sword_data['randDamage']) / 44) * 2.0) + 0.25 sword_data['damageType'] = numpy.random.choice( [ 'PHYSICAL', 'MAGIC', 'FIRE', 'ICE', 'LIGHTNING', 'POISON', 'HEALING', 'PARALYZE', 'VAMPIRE' ], p=[ 0.5, 0.1, 0.1, 0.1, 0.1, 0.04, 0.0, 0.03, 0.03 ] ) sword_data['shader'] = { 'PHYSICAL': None, 'MAGIC': 'magic-item-purple', 'FIRE': 'magic-item-red', 'ICE': 'magic-item', 'LIGHTNING': 'magic-item-white', 'POISON': 'magic-item-green', 'HEALING': 'magic-item', 'PARALYZE': 'magic-item', 'VAMPIRE': 'magic-item-red' }[sword_data['damageType']] sword_data['attackAnimation'] = numpy.random.choice( [ 'swordAttack', 'swordAttackSlow', 'daggerAttack', 'maceAttack' ], p=[ 0.4, 0.2, 0.35, 0.05 ] ) sword_data['attackStrongAnimation'] = numpy.random.choice( [ 'swordAttackStrong', 'thrustAttack', 'daggerAttackStrong', 'maceAttackStrong' ], p=[ 0.4, 0.2, 0.35, 0.05 ] ) sword_data['chargeAnimation'] = numpy.random.choice( [ 'swordCharge', 'thrustCharge', 'daggerCharge', 'maceCharge' ], p=[ 0.35, 0.2, 0.35, 0.1 ] ) # Add a light? if (sword_data['damageType'] != 'PHYSICAL' and random.random() < 0.125): with open('./json/light.json') as file: light_data = json.loads(file.read()) light_data['lightColor'] = damage_type_color[sword_data['damageType']] sword_data['attached'].append(light_data) return sword_data def create_directory_structure(): """Generates the output mod directory structure Raises: If fails to create directory """ def ensure_directory(path): try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: raise ensure_directory('./out/textures') ensure_directory('./out/data') if __name__ == "__main__": print("Generating blades...") # Create mod directory structure create_directory_structure() # Set the random seed to have deterministic results. random.seed('teddybear') numpy.random.seed(8888888) # Load up individual pieces palettes = [os.path.normpath(g) for g in glob.glob('./images/palettes/*.png')] grips = [os.path.normpath(g) for g in glob.glob('./images/grips/*.png')] pommels = [os.path.normpath(g) for g in glob.glob('./images/pommels/*.png')] crossguards = [os.path.normpath(g) for g in glob.glob('./images/crossguards/*.png')] blades = [os.path.normpath(g) for g in glob.glob('./images/blades/*.png')] print_possibility_space() sheet_size = 32 * 16, 32 * 64 sprite_sheet = Image.new('RGBA', sheet_size) with open('./json/items.json') as file: sword_definitions = json.loads(file.read()) # Build the sprite sheet for y in range(0, sheet_size[1], 32): for x in range(0, sheet_size[0], 32): index = y // 32 * sheet_size[0] // 32 + x // 32 image = generate_sword_image() sprite_sheet.paste(image, (x, y)) s = generate_sword_data(index) sword_definitions['unique'].append(s) # Save the sprite sheet to file sprite_sheet.save('./out/textures/blades.png') # Save the item definitions to file with open('./out/data/items.dat', 'w') as file: file.write(json.dumps(sword_definitions, indent=4)) # Save the sprite sheet definition with open('./out/data/spritesheets.dat', 'w') as file, open('./json/spritesheets.json') as json_data: data = json.loads(json_data.read()) data[0]['columns'] = sheet_size[0] / 32 file.write(json.dumps(data, indent=4)) print("Done!")
import errno import glob import json import os import random import numpy import tracery from tracery.modifiers import base_english from PIL import Image from extended_english import extended_english def calculate_image_possibilities(): """Computes the total possible combinations for sword pieces Returns: The total number of unique combinations of sword pieces """ # Reordering the color ramps in the palette yields 3! combinations palette_reorder_possibilities = 6 return len(palettes) * palette_reorder_possibilities * len(grips) * len(pommels) * len(crossguards) * len(blades) def print_possibility_space(): """Displays the total combinations of various proc gen items.""" print("Possibility space:") print(" {} unique sword images".format(calculate_image_possibilities())) def generate_sword_image(): """Generates a sword image from pieces Returns: A PIL Image object. """ # Chose a random set of pieces palette = Image.open(random.choice(palettes), 'r') grip = Image.open(random.choice(grips), 'r') pommel = Image.open(random.choice(pommels), 'r') crossguard = Image.open(random.choice(crossguards), 'r') blade = Image.open(random.choice(blades), 'r') # Small chance to reorder palette primary_palette = palette.palette.palette[0:15] secondary_palette = palette.palette.palette[15:30] accent_palette = palette.palette.palette[30:45] transparency = palette.palette.palette[45:] p = primary_palette + secondary_palette + accent_palette + transparency if random.random() > 0.95: reordered_palettes = [ primary_palette + accent_palette + secondary_palette + transparency, secondary_palette + primary_palette + accent_palette + transparency, secondary_palette + accent_palette + primary_palette + transparency, accent_palette + primary_palette + secondary_palette + transparency, accent_palette + secondary_palette + primary_palette + transparency ] p = random.choice(reordered_palettes) # Apply palette for image in (grip, pommel, crossguard, blade): image.putpalette(p) composite = Image.new('RGBA', (32, 32)) # Paste with mask needs to be RGBA data. Convert() is used to accomplish this. composite.paste(grip) composite.paste(pommel, (0, 0), pommel.convert()) composite.paste(blade, (0, 0), blade.convert()) composite.paste(crossguard, (0, 0), crossguard.convert()) return composite damage_type_color = { 'MAGIC': {"x": 0.6172, "y": 0.0937, "z": 0.7695}, 'FIRE': {"x": 1.0, "y": 0.0, "z": 0.0}, 'ICE': {"x": 0.0, "y": 0.0, "z": 1.0}, 'LIGHTNING': {"x": 1.0, "y": 1.0, "z": 1.0}, 'POISON': {"x": 0.1529, "y": 1.0, "z": 0.3333}, 'HEALING': {"x": 0.0, "y": 1.0, "z": 1.0}, 'PARALYZE': {"x": 0.9294, "y": 0.7882, "z": 0.1921}, 'VAMPIRE': {"x": 0.13, "y": 0.1, "z": 0.15} } def generate_sword_data(index): """Generates sword JSON data Returns: Sword data as dict """ with open('./json/sword.json') as file: sword_data = json.loads(file.read()) with open('./json/names.json') as file: name_rules = json.loads(file.read()) name_grammar = tracery.Grammar(name_rules) name_grammar.add_modifiers(base_english) name_grammar.add_modifiers(extended_english) sword_data['name'] = f'Blade {index + 1}:\n{name_grammar.flatten("#root#")}' sword_data['tex'] = index sword_data['brokenTex'] = index sword_data['spriteAtlas'] = 'blades' sword_data['baseDamage'] = int(numpy.random.normal(10, 4)) sword_data['randDamage'] = int(numpy.random.normal(10, 4)) sword_data['durability'] = int(numpy.random.normal(100, 40)) sword_data['knockback'] = numpy.random.normal(0.15, 0.025) sword_data['reach'] = numpy.random.normal(0.5, 0.125) + 0.25 sword_data['speed'] = ((1 - (sword_data['baseDamage'] + sword_data['randDamage']) / 44) * 2.0) + 0.25 sword_data['damageType'] = numpy.random.choice( [ 'PHYSICAL', 'MAGIC', 'FIRE', 'ICE', 'LIGHTNING', 'POISON', 'HEALING', 'PARALYZE', 'VAMPIRE' ], p=[ 0.5, 0.1, 0.1, 0.1, 0.1, 0.04, 0.0, 0.03, 0.03 ] ) sword_data['shader'] = { 'PHYSICAL': None, 'MAGIC': 'magic-item-purple', 'FIRE': 'magic-item-red', 'ICE': 'magic-item', 'LIGHTNING': 'magic-item-white', 'POISON': 'magic-item-green', 'HEALING': 'magic-item', 'PARALYZE': 'magic-item', 'VAMPIRE': 'magic-item-red' }[sword_data['damageType']] sword_data['attackAnimation'] = numpy.random.choice( [ 'swordAttack', 'swordAttackSlow', 'daggerAttack', 'maceAttack' ], p=[ 0.4, 0.2, 0.35, 0.05 ] ) sword_data['attackStrongAnimation'] = numpy.random.choice( [ 'swordAttackStrong', 'thrustAttack', 'daggerAttackStrong', 'maceAttackStrong' ], p=[ 0.4, 0.2, 0.35, 0.05 ] ) sword_data['chargeAnimation'] = numpy.random.choice( [ 'swordCharge', 'thrustCharge', 'daggerCharge', 'maceCharge' ], p=[ 0.35, 0.2, 0.35, 0.1 ] ) # Add a light? if (sword_data['damageType'] != 'PHYSICAL' and random.random() < 0.125): with open('./json/light.json') as file: light_data = json.loads(file.read()) light_data['lightColor'] = damage_type_color[sword_data['damageType']] sword_data['attached'].append(light_data) return sword_data def create_directory_structure(): """Generates the output mod directory structure Raises: If fails to create directory """ def ensure_directory(path): try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: raise ensure_directory('./out/textures') ensure_directory('./out/data') if __name__ == "__main__": print("Generating blades...") # Create mod directory structure create_directory_structure() # Set the random seed to have deterministic results. random.seed('teddybear') numpy.random.seed(8888888) # Load up individual pieces palettes = [os.path.normpath(g) for g in glob.glob('./images/palettes/*.png')] grips = [os.path.normpath(g) for g in glob.glob('./images/grips/*.png')] pommels = [os.path.normpath(g) for g in glob.glob('./images/pommels/*.png')] crossguards = [os.path.normpath(g) for g in glob.glob('./images/crossguards/*.png')] blades = [os.path.normpath(g) for g in glob.glob('./images/blades/*.png')] print_possibility_space() sheet_size = 32 * 16, 32 * 64 sprite_sheet = Image.new('RGBA', sheet_size) with open('./json/items.json') as file: sword_definitions = json.loads(file.read()) # Build the sprite sheet for y in range(0, sheet_size[1], 32): for x in range(0, sheet_size[0], 32): index = y // 32 * sheet_size[0] // 32 + x // 32 image = generate_sword_image() sprite_sheet.paste(image, (x, y)) s = generate_sword_data(index) sword_definitions['unique'].append(s) # Save the sprite sheet to file sprite_sheet.save('./out/textures/blades.png') # Save the item definitions to file with open('./out/data/items.dat', 'w') as file: file.write(json.dumps(sword_definitions, indent=4)) # Save the sprite sheet definition with open('./out/data/spritesheets.dat', 'w') as file, open('./json/spritesheets.json') as json_data: data = json.loads(json_data.read()) data[0]['columns'] = sheet_size[0] / 32 file.write(json.dumps(data, indent=4)) print("Done!")
import os import random import json import logging from datetime import datetime from eval import eval_wrapper from train import train_wrapper from strips_hgn.utils.helpers import mode_to_str from strips_hgn.utils.logging_setup import setup_full_logging from default_args import get_training_args, DomainAndProblemConfiguration, get_eval_args _log = logging.getLogger(__name__) if __name__ == "__main__": _log.info(f'Starting experiments: {datetime.now().strftime('%m-%d-%H-%M-%S')}.') repeats = 3 modes=[ {'domain':'mbw', 'mode':'train', 'search':'astar', 'all':False, 'novel':0, 'lifted':0, 'distance': 0, 'bound': 600, 'auto_bslr': False}, {'domain':'mbw', 'mode':'train', 'search':'astar', 'all':False, 'novel':2, 'lifted':0, 'distance': 0, 'bound': 600, 'auto_bslr': False}, {'domain':'mbw', 'mode':'train', 'search':'astar', 'all':False, 'novel':2, 'lifted':1, 'distance': 0, 'bound': 600, 'auto_bslr': False}, {'domain':'mbw', 'mode':'train', 'search':'astar', 'all':True, 'novel':0, 'lifted':0, 'distance': 0, 'bound': 600, 'auto_bslr': False}, {'domain':'mbw', 'mode':'train', 'search':'bfs', 'all':False, 'novel':2, 'lifted':0, 'distance': 0, 'bound': 600, 'auto_bslr': False}, {'domain':'mbw', 'mode':'train', 'search':'bfs', 'all':False, 'novel':2, 'lifted':1, 'distance': 0, 'bound': 600, 'auto_bslr': False}, {'domain':'mbw', 'mode':'train', 'search':'bfs', 'all':True, 'novel':0, 'lifted':0, 'distance': 0, 'bound': 600, 'auto_bslr': False}, {'domain':'mbw', 'mode':'train', 'search':'novelty', 'all':True, 'novel':2, 'lifted':0, 'distance': 0, 'bound': 600, 'auto_bslr': False}, {'domain':'mbw', 'mode':'train', 'search':'novelty', 'all':True, 'novel':2, 'lifted':1, 'distance': 0, 'bound': 600, 'auto_bslr': False}, ] passes = {mode_to_str(mode): False for mode in modes} report = {} used_problems = set() # best_models = [] train_problem_pddls = sorted(['3/'+ p for p in os.listdir("../benchmarks/mbw/3")])[:10]+ \ sorted(['4/'+p for p in os.listdir("../benchmarks/mbw/4")])[:10]+ \ sorted(['5/'+p for p in os.listdir("../benchmarks/mbw/5")])[:10] for pddl in train_problem_pddls: used_problems.add(pddl) _CONFIGURATION = DomainAndProblemConfiguration( base_directory="../benchmarks/mbw", domain_pddl="matching-bw-typed.pddl", # {3, 4, 5 blocks} x 10 problems = 30 problems problem_pddls=train_problem_pddls ) for i in range(repeats): _log.info(f"Repeat: {i}.") valid_problem_pddls = [] for i in range(5, 9): valid_problem_pddls += sorted(random.sample([str(i)+'/'+ p for p in os.listdir("../benchmarks/mbw/"+str(i))], k=2)) _log.info(f"Validation problems are: {valid_problem_pddls}.") for pddl in valid_problem_pddls: used_problems.add(pddl) for mode in modes: if not passes[mode_to_str(mode)]: # training phase _log.info(f"Training: {mode_to_str(mode)}") train_wrapper( args=get_training_args( configurations=[_CONFIGURATION], # 10 minutes max_training_time=45*60, # num_folds=2, # batch_size=32, # learning_rate=0.005, ), experiment_type=mode_to_str(mode), mode=mode, ) # validation phase for dirname in os.listdir("../results"): if mode_to_str(mode) in dirname and not dirname.replace("train", "eval") in "_".join(os.listdir("../results")): train_dirname = dirname break _VALID_CONFIGURATION = DomainAndProblemConfiguration( base_directory="../benchmarks/mbw", domain_pddl="matching-bw-typed.pddl", problem_pddls=valid_problem_pddls, ) _log.info("Validating: {}.".format(train_dirname.replace("train", "eval"))) eval_wrapper( args=get_eval_args( configurations=[_VALID_CONFIGURATION], max_search_time=10*60, checkpoint= "../results/{}/model-best.ckpt".format(train_dirname), ), experiment_type=train_dirname.replace("train", "eval"), mode={'mode':'eval'}, ) for dirname in os.listdir("../results"): if train_dirname.replace("train", "eval") in dirname: valid_dirname = dirname break # parse json and save report total_count = len(valid_problem_pddls) solved_count = 0 with open(os.path.join('../results', valid_dirname, "test_results.json"), 'r') as file: res = json.load(file) for name, result in res['results'].items(): if result['strips-hgn']['search_state']=='success': solved_count+=1 if solved_count/total_count >=0.8: passes[mode_to_str(mode)] = True best_loss=float('inf') with open(os.path.join("../results", train_dirname, "strips_hgn.log"), 'r') as file: lines = file.readlines() for l in lines: if '(best ' in l: if best_loss > float(l[(l.find('(best ')+6): (l.find('(best ')+10)]): best_loss = float(l[(l.find('(best ')+6): (l.find('(best ')+10)]) report[train_dirname] = {'best_loss': best_loss, 'coverage': solved_count/total_count, 'pass': (solved_count/total_count)>=0.8} json.dump( report, open(os.path.join('../results', 'report.json'), "w"), indent=2, ) _log.info('Reporting {}: {}'.format(train_dirname, report[train_dirname])) # prepare test problems test_problem_pddls = [] for i in range(5, 9): problem_set = set([str(i)+'/'+ p for p in os.listdir("../benchmarks/mbw/"+str(i))])-used_problems test_problem_pddls += sorted(random.sample(list(problem_set), k=10)) for mode in modes: mode_name = mode_to_str(mode) best_model = None best_loss = float('inf') coverage = 0 for model_name, metrics in report.items(): if mode_name in model_name: if metrics['pass']: best_model = model_name break elif metrics['coverage'] > coverage: best_model = model_name coverage = metrics['coverage'] best_loss = metrics['best_loss'] elif metrics['coverage'] == coverage and metrics['best_loss'] < best_loss: best_model = model_name best_loss = metrics['best_loss'] _log.info(f"Testing: {best_model}.") # best_models.append(best_model) # test phase _TEST_CONFIGURATION = DomainAndProblemConfiguration( base_directory="../benchmarks/mbw", domain_pddl="matching-bw-typed.pddl", problem_pddls=test_problem_pddls, ) eval_wrapper( args=get_eval_args( configurations=[_TEST_CONFIGURATION], max_search_time=10*60, checkpoint= "../results/{}/model-best.ckpt".format(best_model), ), experiment_type=best_model.replace('train', 'eval'), mode={'mode':'eval'}, ) _log.info("EXPERIEMENTS COMPLETE!")
import os import random import json import logging from datetime import datetime from eval import eval_wrapper from train import train_wrapper from strips_hgn.utils.helpers import mode_to_str from strips_hgn.utils.logging_setup import setup_full_logging from default_args import get_training_args, DomainAndProblemConfiguration, get_eval_args _log = logging.getLogger(__name__) if __name__ == "__main__": _log.info(f'Starting experiments: {datetime.now().strftime("%m-%d-%H-%M-%S")}.') repeats = 3 modes=[ {'domain':'mbw', 'mode':'train', 'search':'astar', 'all':False, 'novel':0, 'lifted':0, 'distance': 0, 'bound': 600, 'auto_bslr': False}, {'domain':'mbw', 'mode':'train', 'search':'astar', 'all':False, 'novel':2, 'lifted':0, 'distance': 0, 'bound': 600, 'auto_bslr': False}, {'domain':'mbw', 'mode':'train', 'search':'astar', 'all':False, 'novel':2, 'lifted':1, 'distance': 0, 'bound': 600, 'auto_bslr': False}, {'domain':'mbw', 'mode':'train', 'search':'astar', 'all':True, 'novel':0, 'lifted':0, 'distance': 0, 'bound': 600, 'auto_bslr': False}, {'domain':'mbw', 'mode':'train', 'search':'bfs', 'all':False, 'novel':2, 'lifted':0, 'distance': 0, 'bound': 600, 'auto_bslr': False}, {'domain':'mbw', 'mode':'train', 'search':'bfs', 'all':False, 'novel':2, 'lifted':1, 'distance': 0, 'bound': 600, 'auto_bslr': False}, {'domain':'mbw', 'mode':'train', 'search':'bfs', 'all':True, 'novel':0, 'lifted':0, 'distance': 0, 'bound': 600, 'auto_bslr': False}, {'domain':'mbw', 'mode':'train', 'search':'novelty', 'all':True, 'novel':2, 'lifted':0, 'distance': 0, 'bound': 600, 'auto_bslr': False}, {'domain':'mbw', 'mode':'train', 'search':'novelty', 'all':True, 'novel':2, 'lifted':1, 'distance': 0, 'bound': 600, 'auto_bslr': False}, ] passes = {mode_to_str(mode): False for mode in modes} report = {} used_problems = set() # best_models = [] train_problem_pddls = sorted(['3/'+ p for p in os.listdir("../benchmarks/mbw/3")])[:10]+ \ sorted(['4/'+p for p in os.listdir("../benchmarks/mbw/4")])[:10]+ \ sorted(['5/'+p for p in os.listdir("../benchmarks/mbw/5")])[:10] for pddl in train_problem_pddls: used_problems.add(pddl) _CONFIGURATION = DomainAndProblemConfiguration( base_directory="../benchmarks/mbw", domain_pddl="matching-bw-typed.pddl", # {3, 4, 5 blocks} x 10 problems = 30 problems problem_pddls=train_problem_pddls ) for i in range(repeats): _log.info(f"Repeat: {i}.") valid_problem_pddls = [] for i in range(5, 9): valid_problem_pddls += sorted(random.sample([str(i)+'/'+ p for p in os.listdir("../benchmarks/mbw/"+str(i))], k=2)) _log.info(f"Validation problems are: {valid_problem_pddls}.") for pddl in valid_problem_pddls: used_problems.add(pddl) for mode in modes: if not passes[mode_to_str(mode)]: # training phase _log.info(f"Training: {mode_to_str(mode)}") train_wrapper( args=get_training_args( configurations=[_CONFIGURATION], # 10 minutes max_training_time=45*60, # num_folds=2, # batch_size=32, # learning_rate=0.005, ), experiment_type=mode_to_str(mode), mode=mode, ) # validation phase for dirname in os.listdir("../results"): if mode_to_str(mode) in dirname and not dirname.replace("train", "eval") in "_".join(os.listdir("../results")): train_dirname = dirname break _VALID_CONFIGURATION = DomainAndProblemConfiguration( base_directory="../benchmarks/mbw", domain_pddl="matching-bw-typed.pddl", problem_pddls=valid_problem_pddls, ) _log.info("Validating: {}.".format(train_dirname.replace("train", "eval"))) eval_wrapper( args=get_eval_args( configurations=[_VALID_CONFIGURATION], max_search_time=10*60, checkpoint= "../results/{}/model-best.ckpt".format(train_dirname), ), experiment_type=train_dirname.replace("train", "eval"), mode={'mode':'eval'}, ) for dirname in os.listdir("../results"): if train_dirname.replace("train", "eval") in dirname: valid_dirname = dirname break # parse json and save report total_count = len(valid_problem_pddls) solved_count = 0 with open(os.path.join('../results', valid_dirname, "test_results.json"), 'r') as file: res = json.load(file) for name, result in res['results'].items(): if result['strips-hgn']['search_state']=='success': solved_count+=1 if solved_count/total_count >=0.8: passes[mode_to_str(mode)] = True best_loss=float('inf') with open(os.path.join("../results", train_dirname, "strips_hgn.log"), 'r') as file: lines = file.readlines() for l in lines: if '(best ' in l: if best_loss > float(l[(l.find('(best ')+6): (l.find('(best ')+10)]): best_loss = float(l[(l.find('(best ')+6): (l.find('(best ')+10)]) report[train_dirname] = {'best_loss': best_loss, 'coverage': solved_count/total_count, 'pass': (solved_count/total_count)>=0.8} json.dump( report, open(os.path.join('../results', 'report.json'), "w"), indent=2, ) _log.info('Reporting {}: {}'.format(train_dirname, report[train_dirname])) # prepare test problems test_problem_pddls = [] for i in range(5, 9): problem_set = set([str(i)+'/'+ p for p in os.listdir("../benchmarks/mbw/"+str(i))])-used_problems test_problem_pddls += sorted(random.sample(list(problem_set), k=10)) for mode in modes: mode_name = mode_to_str(mode) best_model = None best_loss = float('inf') coverage = 0 for model_name, metrics in report.items(): if mode_name in model_name: if metrics['pass']: best_model = model_name break elif metrics['coverage'] > coverage: best_model = model_name coverage = metrics['coverage'] best_loss = metrics['best_loss'] elif metrics['coverage'] == coverage and metrics['best_loss'] < best_loss: best_model = model_name best_loss = metrics['best_loss'] _log.info(f"Testing: {best_model}.") # best_models.append(best_model) # test phase _TEST_CONFIGURATION = DomainAndProblemConfiguration( base_directory="../benchmarks/mbw", domain_pddl="matching-bw-typed.pddl", problem_pddls=test_problem_pddls, ) eval_wrapper( args=get_eval_args( configurations=[_TEST_CONFIGURATION], max_search_time=10*60, checkpoint= "../results/{}/model-best.ckpt".format(best_model), ), experiment_type=best_model.replace('train', 'eval'), mode={'mode':'eval'}, ) _log.info("EXPERIEMENTS COMPLETE!")
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu> """MneExperiment class to manage data from a experiment For testing purposed, set up an experiment class without checking for data: MneExperiment.auto_delete_cache = 'disable' MneExperiment.sessions = ('session',) e = MneExperiment('.', find_subjects=False) """ from collections import defaultdict, Sequence from copy import deepcopy from datetime import datetime from glob import glob import inspect from itertools import chain, product import logging import os from os.path import basename, exists, getmtime, isdir, join, relpath from pathlib import Path import re import shutil import time from typing import Union import warnings import numpy as np from tqdm import tqdm import mne from mne.baseline import rescale from mne.minimum_norm import make_inverse_operator, apply_inverse, apply_inverse_epochs from .. import _report from .. import fmtxt from .. import gui from .. import load from .. import plot from .. import save from .. import table from .. import testnd from .._data_obj import ( Datalist, Dataset, Factor, Var, SourceSpace, VolumeSourceSpace, align1, all_equal, assert_is_legal_dataset_key, combine) from .._exceptions import DefinitionError, DimensionMismatchError, OldVersionError from .._info import BAD_CHANNELS from .._io.pickle import update_subjects_dir from .._names import INTERPOLATE_CHANNELS from .._meeg import new_rejection_ds from .._mne import ( dissolve_label, labels_from_mni_coords, rename_label, combination_label, morph_source_space, shift_mne_epoch_trigger, find_source_subject, label_from_annot, ) from ..mne_fixes import ( write_labels_to_annot, _interpolate_bads_eeg, _interpolate_bads_meg) from ..mne_fixes._trans import hsp_equal, mrk_equal from ..mne_fixes._source_space import merge_volume_source_space, prune_volume_source_space from .._ndvar import concatenate, cwt_morlet, neighbor_correlation from ..fmtxt import List, Report, Image, read_meta from .._stats.stats import ttest_t from .._stats.testnd import _MergedTemporalClusterDist from .._text import enumeration, plural from .._utils import IS_WINDOWS, ask, subp, keydefaultdict, log_level, ScreenHandler from .._utils.mne_utils import fix_annot_names, is_fake_mri from .definitions import FieldCode, find_dependent_epochs, find_epochs_vars, log_dict_change, log_list_change from .epochs import PrimaryEpoch, SecondaryEpoch, SuperEpoch, EpochCollection, assemble_epochs, decim_param from .exceptions import FileDeficient, FileMissing from .experiment import FileTree from .groups import assemble_groups from .parc import ( assemble_parcs, FS_PARC, FSA_PARC, SEEDED_PARC_RE, CombinationParc, EelbrainParc, FreeSurferParc, FSAverageParc, SeededParc, IndividualSeededParc, LabelParc ) from .preprocessing import ( assemble_pipeline, RawSource, RawFilter, RawICA, compare_pipelines, ask_to_delete_ica_files) from .test_def import ( Test, EvokedTest, ROITestResult, ROI2StageResult, TestDims, TwoStageTest, assemble_tests, find_test_vars, ) from .variable_def import Variables # current cache state version CACHE_STATE_VERSION = 12 # History: # 10: input_state: share forward-solutions between sessions # 11: add samplingrate to epochs # 12: store test-vars as Variables object # paths LOG_FILE = join('{root}', 'eelbrain {name}.log') LOG_FILE_OLD = join('{root}', '.eelbrain.log') # Allowable parameters COV_PARAMS = {'epoch', 'session', 'method', 'reg', 'keep_sample_mean', 'reg_eval_win_pad'} INV_METHODS = ('MNE', 'dSPM', 'sLORETA', 'eLORETA') SRC_RE = re.compile(r'^(ico|vol)-(\d+)(?:-(cortex|brainstem))?$') inv_re = re.compile(r"^" r"(free|fixed|loose\.\d+|vec)-" # orientation constraint r"(\d*\.?\d+)-" # SNR rf"({"|".join(INV_METHODS)})" # method r"(?:-((?:0\.)?\d+))?" # depth weighting r"(?:-(pick_normal))?" r"$") # pick normal # Eelbrain 0.24 raw/preprocessing pipeline LEGACY_RAW = { '0-40': RawFilter('raw', None, 40, method='iir'), '0.1-40': RawFilter('raw', 0.1, 40, l_trans_bandwidth=0.08, filter_length='60s'), '0.2-40': RawFilter('raw', 0.2, 40, l_trans_bandwidth=0.08, filter_length='60s'), '1-40': RawFilter('raw', 1, 40, method='iir'), } CACHE_HELP = "A change in the {experiment} class definition (or the input files) means that some {filetype} files no longer reflect the current definition. In order to keep local results consistent with the definition, these files should be deleted. If you want to keep a copy of the results, be sure to move them to a different location before proceding. If you think the change in the definition was a mistake, you can select 'abort', revert the change and try again." ################################################################################ def _mask_ndvar(ds, name): y = ds[name] if y.source.parc is None: raise RuntimeError('%r has no parcellation' % (y,)) mask = y.source.parc.startswith('unknown') if mask.any(): ds[name] = y.sub(source=np.invert(mask)) def _time_str(t): "String for representing a time value" if t is None: return '' else: return '%i' % round(t * 1000) def _time_window_str(window, delim='-'): "String for representing a time window" return delim.join(map(_time_str, window)) def guess_y(ds, default=None): "Given a dataset, guess the dependent variable" for y in ('srcm', 'src', 'meg', 'eeg'): if y in ds: return y if default is not None: return default raise RuntimeError(r"Could not find data in {ds}") class DictSet: """Helper class for list of dicts without duplicates""" def __init__(self): self._list = [] def __repr__(self): return "DictSet(%s)" % self._list def __iter__(self): return self._list.__iter__() def add(self, item): if item not in self._list: self._list.append(item) def update(self, items): for item in items: self.add(item) class CacheDict(dict): def __init__(self, func, key_vars, *args): super(CacheDict, self).__init__() self._func = func self._key_vars = key_vars self._args = args def __getitem__(self, key): if key in self: return dict.__getitem__(self, key) if isinstance(key, str): out = self._func(*self._args, **{self._key_vars: key}) else: out = self._func(*self._args, **dict(zip(self._key_vars, key))) self[key] = out return out def cache_valid(mtime, *source_mtimes): "Determine whether mtime is up-to-date" return ( mtime is not None and all(t is not None for t in source_mtimes) and mtime > max(source_mtimes)) temp = { # MEG 'equalize_evoked_count': ('', 'eq'), # locations 'raw-sdir': join('{root}', 'meg'), 'raw-dir': join('{raw-sdir}', '{subject}'), # raw input files 'trans-file': join('{raw-dir}', '{mrisubject_visit}-trans.fif'), # log-files (eye-tracker etc.) 'log-dir': join('{raw-dir}', 'logs'), 'edf-file': join('{log-dir}', '*.edf'), # created input files 'ica-file': join('{raw-dir}', '{subject_visit} {raw}-ica.fif'), # hard-coded in RawICA 'rej-dir': join('{raw-dir}', 'epoch selection'), 'rej-file': join('{rej-dir}', '{session}_{sns_kind}_{epoch_visit}-{rej}.pickled'), # cache 'cache-dir': join('{root}', 'eelbrain-cache'), # raw 'raw-cache-dir': join('{cache-dir}', 'raw', '{subject}'), 'raw-cache-base': join('{raw-cache-dir}', '{recording} {raw}'), 'cached-raw-file': '{raw-cache-base}-raw.fif', 'event-file': '{raw-cache-base}-evts.pickled', 'interp-file': '{raw-cache-base}-interp.pickled', 'cached-raw-log-file': '{raw-cache-base}-raw.log', # forward modeling: 'fwd-file': join('{raw-cache-dir}', '{recording}-{mrisubject}-{src}-fwd.fif'), # sensor covariance 'cov-dir': join('{cache-dir}', 'cov'), 'cov-base': join('{cov-dir}', '{subject_visit}', '{sns_kind} {cov}-{rej}'), 'cov-file': '{cov-base}-cov.fif', 'cov-info-file': '{cov-base}-info.txt', # inverse solution 'inv-file': join('{raw-cache-dir}', 'inv', '{mrisubject} {src} {recording} {sns_kind} {cov} {rej} {inv-cache}-inv.fif'), # evoked 'evoked-dir': join('{cache-dir}', 'evoked'), 'evoked-file': join('{evoked-dir}', '{subject}', '{sns_kind} {epoch_visit} {model} {evoked_kind}-ave.fif'), # test files 'test-dir': join('{cache-dir}', 'test'), 'test-file': join('{test-dir}', '{analysis} {group}', '{test_desc} {test_dims}.pickled'), # MRIs 'common_brain': 'fsaverage', # MRI base files 'mri-sdir': join('{root}', 'mri'), 'mri-dir': join('{mri-sdir}', '{mrisubject}'), 'bem-dir': join('{mri-dir}', 'bem'), 'mri-cfg-file': join('{mri-dir}', 'MRI scaling parameters.cfg'), 'mri-file': join('{mri-dir}', 'mri', 'orig.mgz'), 'bem-file': join('{bem-dir}', '{mrisubject}-inner_skull-bem.fif'), 'bem-sol-file': join('{bem-dir}', '{mrisubject}-*-bem-sol.fif'), # removed for 0.24 'head-bem-file': join('{bem-dir}', '{mrisubject}-head.fif'), 'src-file': join('{bem-dir}', '{mrisubject}-{src}-src.fif'), 'fiducials-file': join('{bem-dir}', '{mrisubject}-fiducials.fif'), # Labels 'hemi': ('lh', 'rh'), 'label-dir': join('{mri-dir}', 'label'), 'annot-file': join('{label-dir}', '{hemi}.{parc}.annot'), # (method) plots 'methods-dir': join('{root}', 'methods'), # result output files # data processing parameters # > group # > kind of test # > single-subject # > kind of test # > subject 'res-dir': join('{root}', 'results'), 'res-file': join('{res-dir}', '{analysis}', '{resname}.{ext}'), 'res-deep-file': join('{res-dir}', '{analysis}', '{folder}', '{resname}.{ext}'), 'report-file': join('{res-dir}', '{analysis} {group}', '{folder}', '{test_desc}.html'), 'group-mov-file': join('{res-dir}', '{analysis} {group}', '{epoch_visit} {test_options} {resname}.mov'), 'subject-res-dir': join('{res-dir}', '{analysis} subjects'), 'subject-spm-report': join('{subject-res-dir}', '{test} {epoch_visit} {test_options}', '{subject}.html'), 'subject-mov-file': join('{subject-res-dir}', '{epoch_visit} {test_options} {resname}', '{subject}.mov'), # plots # plot corresponding to a report (and using same folder structure) 'res-plot-root': join('{root}', 'result plots'), 'res-plot-dir': join('{res-plot-root}', '{analysis} {group}', '{folder}', '{test_desc}'), # besa 'besa-root': join('{root}', 'besa'), 'besa-trig': join('{besa-root}', '{subject}', '{subject}_{recording}_{epoch_visit}_triggers.txt'), 'besa-evt': join('{besa-root}', '{subject}', '{subject}_{recording}_{epoch_visit}[{rej}].evt'), # MRAT 'mrat_condition': '', 'mrat-root': join('{root}', 'mrat'), 'mrat-sns-root': join('{mrat-root}', '{sns_kind}', '{epoch_visit} {model} {evoked_kind}'), 'mrat-src-root': join('{mrat-root}', '{src_kind}', '{epoch_visit} {model} {evoked_kind}'), 'mrat-sns-file': join('{mrat-sns-root}', '{mrat_condition}', '{mrat_condition}_{subject}-ave.fif'), 'mrat_info-file': join('{mrat-root}', '{subject} info.txt'), 'mrat-src-file': join('{mrat-src-root}', '{mrat_condition}', '{mrat_condition}_{subject}'), } class MneExperiment(FileTree): """Analyze an MEG experiment (gradiometer only) with MNE Parameters ---------- root : str | None the root directory for the experiment (usually the directory containing the 'meg' and 'mri' directories). The experiment can be initialized without the root for testing purposes. find_subjects : bool Automatically look for subjects in the MEG-directory (default True). Set ``find_subjects=False`` to initialize the experiment without any files. ... Initial state parameters. Notes ----- .. seealso:: Guide on using :ref:`experiment-class-guide`. """ _safe_delete = 'cache-dir' path_version = 2 screen_log_level = logging.INFO auto_delete_results = False auto_delete_cache = True # what to do when the experiment class definition changed: # True: delete outdated files # False: raise an error # 'disable': ignore it # 'debug': prompt with debug options cache_inv = True # Whether to cache inverse solution # moderate speed gain for loading source estimates (34 subjects: 20 vs 70 s) # hard drive space ~ 100 mb/file # tuple (if the experiment has multiple sessions) sessions = None visits = ('',) # Raw preprocessing pipeline raw = {} # add this value to all trigger times trigger_shift = 0 # variables for automatic labeling {name: {trigger: label, triggers: label}} variables = {} # Default values for epoch definitions epoch_default = {'decim': 5} # named epochs epochs = {} # Rejection # ========= # eog_sns: The sensors to plot separately in the rejection GUI. The default # is the two MEG sensors closest to the eyes. _eog_sns = {None: (), 'KIT-157': ('MEG 143', 'MEG 151'), 'KIT-208': ('MEG 087', 'MEG 130'), 'KIT-UMD-1': ('MEG 042', 'MEG 025'), 'KIT-UMD-2': ('MEG 042', 'MEG 025'), 'KIT-UMD-3': ('MEG 042', 'MEG 025'), 'KIT-BRAINVISION': ('HEOGL', 'HEOGR', 'VEOGb'), 'neuromag306mag': ('MEG 0121', 'MEG 1411')} # # artifact_rejection dict: # # kind : 'manual' | 'make' # How the rejection is derived: # 'manual': manually create a rejection file (use the selection GUI # through .make_epoch_selection()) # 'make' a rejection file is created by the user # interpolation : bool # enable by-epoch channel interpolation # # For manual rejection # ^^^^^^^^^^^^^^^^^^^^ _artifact_rejection = { '': {'kind': None}, 'man': {'kind': 'manual', 'interpolation': True}, } artifact_rejection = {} exclude = {} # field_values to exclude (e.g. subjects) # groups can be defined as subject lists: {'group': ('member1', 'member2', ...)} # or by exclusion: {'group': {'base': 'all', 'exclude': ('member1', 'member2')}} groups = {} # whether to look for and load eye tracker data when loading raw files has_edf = defaultdict(lambda: False) # Pattern for subject names. The first group is used to determine what # MEG-system the data was recorded from subject_re = r'(R|S|A|Y|AD|QP)(\d{3,})$' # MEG-system (legacy variable). meg_system = None # kwargs for regularization of the covariance matrix (see .make_cov()) _covs = {'auto': {'epoch': 'cov', 'method': 'auto'}, 'bestreg': {'epoch': 'cov', 'reg': 'best'}, 'reg': {'epoch': 'cov', 'reg': True}, 'noreg': {'epoch': 'cov', 'reg': None}, 'emptyroom': {'session': 'emptyroom', 'reg': None}} # MRI subject names: {subject: mrisubject} mappings # selected with e.set(mri=dict_name) # default is identity (mrisubject = subject) _mri_subjects = {'': keydefaultdict(lambda s: s)} # Where to search for subjects (defined as a template name). If the # experiment searches for subjects automatically, it scans this directory # for subfolders matching subject_re. _subject_loc = 'raw-sdir' # Parcellations __parcs = { 'aparc.a2005s': FS_PARC, 'aparc.a2009s': FS_PARC, 'aparc': FS_PARC, 'aparc.DKTatlas': FS_PARC, 'cortex': LabelParc(('cortex',), ('lateral', 'medial')), 'PALS_B12_Brodmann': FSA_PARC, 'PALS_B12_Lobes': FSA_PARC, 'PALS_B12_OrbitoFrontal': FSA_PARC, 'PALS_B12_Visuotopic': FSA_PARC, 'lobes': EelbrainParc(True, ('lateral', 'medial')), 'lobes-op': CombinationParc('lobes', {'occipitoparietal': "occipital + parietal"}, ('lateral', 'medial')), 'lobes-ot': CombinationParc('lobes', {'occipitotemporal': "occipital + temporal"}, ('lateral', 'medial')), } parcs = {} # Frequencies: lowbound, highbound, step _freqs = {'gamma': {'frequencies': np.arange(25, 50, 2), 'n_cycles': 5}} freqs = {} # basic templates to use. Can be a string referring to a templates # dictionary in the module level _temp dictionary, or a templates # dictionary _templates = temp # specify additional templates _values = {} # specify defaults for specific fields (e.g. specify the initial subject # name) defaults = {} # model order: list of factors in the order in which models should be built # (default for factors not in this list is alphabetic) _model_order = [] # Backup # ------ # basic state for a backup _backup_state = {'subject': '*', 'mrisubject': '*', 'session': '*', 'raw': 'raw'} # files to back up, together with state modifications on the basic state _backup_files = (('rej-file', {'raw': '*', 'epoch': '*', 'rej': '*'}), ('trans-file', {}), ('mri-cfg-file', {}), ('log-dir', {}),) # Tests # ----- # specify tests as (test_type, model, test_parameter) tuple. For example, # ("anova", "condition", "condition*subject") # ("t_contrast_rel", "ref%loc", "+min(ref|left>nref|*, ref|right>nref|*)") # Make sure dictionary keys (test names) are appropriate for filenames. # tests imply a model which is set automatically tests = {} _empty_test = False # for TRFExperiment _cluster_criteria = { '': {'time': 0.025, 'sensor': 4, 'source': 10}, 'all': {}, '10ms': {'time': 0.01, 'sensor': 4, 'source': 10}, 'large': {'time': 0.025, 'sensor': 8, 'source': 20}, } # plotting # -------- _brain_plot_defaults = {'surf': 'inflated'} brain_plot_defaults = {} def __init__(self, root=None, find_subjects=True, **state): # checks if hasattr(self, 'cluster_criteria'): raise AttributeError("MneExperiment subclasses can not have a .cluster_criteria attribute anymore. Please remove the attribute, delete the eelbrain-cache folder and use the select_clusters analysis parameter.") # create attributes (overwrite class attributes) self._mri_subjects = self._mri_subjects.copy() self._templates = self._templates.copy() # templates version if self.path_version == 0: self._templates['raw-dir'] = join('{raw-sdir}', 'meg', 'raw') raw_def = {**LEGACY_RAW, 'raw': RawSource('{subject}_{recording}_clm-raw.fif'), **self.raw} elif self.path_version == 1: raw_def = {**LEGACY_RAW, 'raw': RawSource(), **self.raw} elif self.path_version == 2: raw_def = {'raw': RawSource(), **self.raw} else: raise ValueError(f"MneExperiment.path_version={self.path_version}; needs to be 0, 1 or 2") # update templates with _values for cls in reversed(inspect.getmro(self.__class__)): if hasattr(cls, '_values'): self._templates.update(cls._values) FileTree.__init__(self) self._log = log = logging.Logger(self.__class__.__name__, logging.DEBUG) ######################################################################## # sessions if not self.sessions: raise TypeError("The MneExperiment.sessions parameter needs to be specified. The session name is contained in your raw data files. For example if your file is named `R0026_mysession-raw.fif` your session name is 'mysession' and you should set MneExperiment.sessions to 'mysession'.") elif isinstance(self.sessions, str): self._sessions = (self.sessions,) elif isinstance(self.sessions, Sequence): self._sessions = tuple(self.sessions) else: raise TypeError(f"MneExperiment.sessions={self.sessions!r}; needs to be a string or a tuple") self._visits = (self._visits,) if isinstance(self.visits, str) else tuple(self.visits) ######################################################################## # subjects if root is None: find_subjects = False else: root = self.get('root', root=root) if find_subjects: subject_re = re.compile(self.subject_re) sub_dir = self.get(self._subject_loc) if not exists(sub_dir): raise IOError(f"Subjects directory {sub_dir}: does notexist. To initialize {self.__class__.__name__} without data, initialize with root=None or find_subjects=False") subjects = [s for s in os.listdir(sub_dir) if subject_re.match(s) and isdir(join(sub_dir, s))] if len(subjects) == 0: log.warning(f"No subjects found in {sub_dir}") subjects.sort() subjects = tuple(subjects) else: subjects = () ######################################################################## # groups self._groups = assemble_groups(self.groups, set(subjects)) ######################################################################## # Preprocessing skip = {'root', 'subject', 'recording', 'raw'} raw_dir = self._partial('raw-dir', skip) cache_path = self._partial('cached-raw-file', skip) self._raw = assemble_pipeline(raw_def, raw_dir, cache_path, root, self._sessions, log) raw_pipe = self._raw['raw'] # legacy connectivity determination if raw_pipe.sysname is None: if self.meg_system is not None: raw_pipe.sysname = self.meg_system # update templates self._register_constant('raw-file', raw_pipe.path) ######################################################################## # variables self._variables = Variables(self.variables) self._variables._check_trigger_vars() ######################################################################## # epochs epoch_default = {'session': self._sessions[0], **self.epoch_default} self._epochs = assemble_epochs(self.epochs, epoch_default) ######################################################################## # epoch rejection artifact_rejection = {} for name, params in chain(self._artifact_rejection.items(), self.artifact_rejection.items()): if params['kind'] in ('manual', 'make', None): artifact_rejection[name] = params.copy() elif params['kind'] == 'ica': raise ValueError(f"kind={params["kind"]!r} in artifact_rejection {name!r}; The ICA option has been removed, use the RawICA raw pipe instead.") else: raise ValueError(f"kind={params["kind"]!r} in artifact_rejection {name!r}") self._artifact_rejection = artifact_rejection ######################################################################## # noise covariance for k, params in self._covs.items(): params = set(params) n_datasource = ('epoch' in params) + ('session' in params) if n_datasource != 1: if n_datasource == 0: raise ValueError("Cov %s has neither epoch nor session " "entry" % k) raise ValueError("Cov %s has both epoch and session entry" % k) if params.difference(COV_PARAMS): raise ValueError("Cov %s has unused entries: %s" % (k, ', '.join(params.difference(COV_PARAMS)))) ######################################################################## # parcellations ############### # make : can be made if non-existent # morph_from_fraverage : can be morphed from fsaverage to other subjects self._parcs = assemble_parcs(chain(self.__parcs.items(), self.parcs.items())) parc_values = list(self._parcs.keys()) parc_values.append('') ######################################################################## # frequency freqs = {} for name, f in chain(self._freqs.items(), self.freqs.items()): if name in freqs: raise ValueError("Frequency %s defined twice" % name) elif 'frequencies' not in f: raise KeyError("Frequency values missing for %s" % name) elif 'n_cycles' not in f: raise KeyError("Number of cycles not defined for %s" % name) freqs[name] = f self._freqs = freqs ######################################################################## # tests self._tests = assemble_tests(self.tests) test_values = sorted(self._tests) if self._empty_test: test_values.insert(0, '') ######################################################################## # Experiment class setup ######################## self._register_field('mri', sorted(self._mri_subjects), allow_empty=True) self._register_field('subject', subjects or None, repr=True) self._register_field('group', self._groups.keys(), 'all', post_set_handler=self._post_set_group) raw_default = sorted(self.raw)[0] if self.raw else None self._register_field('raw', sorted(self._raw), default=raw_default, repr=True) self._register_field('rej', self._artifact_rejection.keys(), 'man', allow_empty=True) # epoch epoch_keys = sorted(self._epochs) for default_epoch in epoch_keys: if isinstance(self._epochs[default_epoch], PrimaryEpoch): break else: default_epoch = None self._register_field('epoch', epoch_keys, default_epoch, repr=True) self._register_field('session', self._sessions, depends_on=('epoch',), slave_handler=self._update_session, repr=True) self._register_field('visit', self._visits, allow_empty=True, repr=True) # cov if 'bestreg' in self._covs: default_cov = 'bestreg' else: default_cov = None self._register_field('cov', sorted(self._covs), default_cov) self._register_field('inv', default='free-3-dSPM', eval_handler=self._eval_inv, post_set_handler=self._post_set_inv) self._register_field('model', eval_handler=self._eval_model) self._register_field('test', test_values, post_set_handler=self._post_set_test, allow_empty=self._empty_test, repr=False) self._register_field('parc', parc_values, 'aparc', eval_handler=self._eval_parc, allow_empty=True) self._register_field('freq', self._freqs.keys()) self._register_field('src', default='ico-4', eval_handler=self._eval_src) self._register_field('connectivity', ('', 'link-midline'), allow_empty=True) self._register_field('select_clusters', self._cluster_criteria.keys(), allow_empty=True) # slave fields self._register_field('mrisubject', depends_on=('mri', 'subject'), slave_handler=self._update_mrisubject, repr=False) self._register_field('src-name', depends_on=('src',), slave_handler=self._update_src_name, repr=False) self._register_field('inv-cache', depends_on='inv', slave_handler=self._update_inv_cache, repr=False) # fields used internally self._register_field('analysis', repr=False) self._register_field('test_options', repr=False) self._register_field('name', repr=False) self._register_field('folder', repr=False) self._register_field('resname', repr=False) self._register_field('ext', repr=False) self._register_field('test_dims', repr=False) # compounds self._register_compound('sns_kind', ('raw',)) self._register_compound('src_kind', ('sns_kind', 'cov', 'mri', 'src-name', 'inv')) self._register_compound('recording', ('session', 'visit')) self._register_compound('subject_visit', ('subject', 'visit')) self._register_compound('mrisubject_visit', ('mrisubject', 'visit')) self._register_compound('epoch_visit', ('epoch', 'visit')) self._register_compound('evoked_kind', ('rej', 'equalize_evoked_count')) self._register_compound('test_desc', ('epoch', 'visit', 'test', 'test_options')) # Define make handlers self._bind_cache('cov-file', self.make_cov) self._bind_cache('src-file', self.make_src) self._bind_cache('fwd-file', self.make_fwd) # currently only used for .rm() self._secondary_cache['cached-raw-file'] = ('event-file', 'interp-file', 'cached-raw-log-file') ######################################################################## # logger ######## # log-file if root: log_file = LOG_FILE.format(root=root, name=self.__class__.__name__) log_file_old = LOG_FILE_OLD.format(root=root) if exists(log_file_old): os.rename(log_file_old, log_file) handler = logging.FileHandler(log_file) formatter = logging.Formatter("%(levelname)-8s %(asctime)s %(message)s", "%m-%d %H:%M") # %(name)-12s handler.setFormatter(formatter) handler.setLevel(logging.DEBUG) log.addHandler(handler) # Terminal log handler = ScreenHandler() self._screen_log_level = log_level(self.screen_log_level) handler.setLevel(self._screen_log_level) log.addHandler(handler) self._screen_log_handler = handler # log package versions from .. import __version__ log.info("*** %s initialized with root %s on %s ***", self.__class__.__name__, root, datetime.now().strftime('%Y-%m-%d %H:%M:%S')) msg = "Using eelbrain %s, mne %s." % (__version__, mne.__version__) if any('dev' in v for v in (__version__, mne.__version__)): log.warning(f"{msg} Development versions are more likely to contain errors.") else: log.info(msg) if self.auto_delete_cache == 'disable': log.warning("Cache-management disabled") return ######################################################################## # Finalize ########## # register experimental features self._subclass_init() # Check that the template model is complete self._find_missing_fields() # set initial values self.set(**state) self._store_state() ######################################################################## # Cache ####### if not root: return # loading events will create cache-dir cache_dir = self.get('cache-dir') cache_dir_existed = exists(cache_dir) # collect input file information # ============================== raw_missing = [] # [(subject, recording), ...] subjects_with_raw_changes = set() # {subject, ...} events = {} # {(subject, recording): event_dataset} # saved mtimes input_state_file = join(cache_dir, 'input-state.pickle') if exists(input_state_file): input_state = load.unpickle(input_state_file) if input_state['version'] < 10: input_state = None elif input_state['version'] > CACHE_STATE_VERSION: raise RuntimeError( "You are trying to initialize an experiment with an older " "version of Eelbrain than that which wrote the cache. If " "you really need this, delete the eelbrain-cache folder " "and try again.") else: input_state = None if input_state is None: input_state = { 'version': CACHE_STATE_VERSION, 'raw-mtimes': {}, 'fwd-sessions': {s: {} for s in subjects}, } # collect current events and mtime raw_mtimes = input_state['raw-mtimes'] pipe = self._raw['raw'] with self._temporary_state: for subject, visit, recording in self.iter(('subject', 'visit', 'recording'), group='all', raw='raw'): key = subject, recording mtime = pipe.mtime(subject, recording, bad_chs=False) if mtime is None: raw_missing.append(key) continue # events events[key] = self.load_events(add_bads=False, data_raw=False) if key not in raw_mtimes or mtime != raw_mtimes[key]: subjects_with_raw_changes.add((subject, visit)) raw_mtimes[key] = mtime # log missing raw files if raw_missing: log.debug("Raw files missing:") missing = defaultdict(list) for subject, recording in raw_missing: missing[subject].append(recording) for subject, recordings in missing.items(): log.debug(f" {subject}: {", ".join(recordings)}") # check for digitizer data differences # ==================================== # Coordinate frames: # MEG (markers) ==raw-file==> head shape ==trans-file==> MRI # # - raw files with identical head shapes can share trans-file (head-mri) # - raw files with identical MEG markers (and head shape) can share # forward solutions # - SuperEpochs currently need to have a single forward solution, # hence marker positions need to be the same between sub-epochs if subjects_with_raw_changes: log.info("Raw input files changed, checking digitizer data") super_epochs = [epoch for epoch in self._epochs.values() if isinstance(epoch, SuperEpoch)] for subject, visit in subjects_with_raw_changes: # find unique digitizer datasets head_shape = None markers = [] # unique MEG marker measurements marker_ids = {} # {recording: index in markers} dig_missing = [] # raw files without dig for recording in self.iter('recording', subject=subject, visit=visit): if (subject, recording) in raw_missing: continue raw = self.load_raw(False) dig = raw.info['dig'] if dig is None: dig_missing.append(recording) continue elif head_shape is None: head_shape = dig elif not hsp_equal(dig, head_shape): raise FileDeficient(f"Raw file {recording} for {subject} has head shape that is different from {enumeration(marker_ids)}; consider defining different visits.") # find if marker pos already exists for i, dig_i in enumerate(markers): if mrk_equal(dig, dig_i): marker_ids[recording] = i break else: marker_ids[recording] = len(markers) markers.append(dig) # checks for missing digitizer data if len(markers) > 1: if dig_missing: n = len(dig_missing) raise FileDeficient(f"The raw {plural("file", n)} for {subject}, {plural("recording", n)} {enumeration(dig_missing)} {plural("is", n)} missing digitizer information") for epoch in super_epochs: if len(set(marker_ids[s] for s in epoch.sessions)) > 1: groups = defaultdict(list) for s in epoch.sessions: groups[marker_ids[s]].append(s) group_desc = ' vs '.join('/'.join(group) for group in groups.values()) raise NotImplementedError(f"SuperEpoch {epoch.name} has sessions with incompatible marker positions ({group_desc}); SuperEpochs with different forward solutions are not implemented.") # determine which sessions to use for forward solutions # -> {for_session: use_session} use_for_session = input_state['fwd-sessions'].setdefault(subject, {}) # -> {marker_id: use_session}, initialize with previously used sessions use_for_id = {marker_ids[s]: s for s in use_for_session.values() if s in marker_ids} for recording in sorted(marker_ids): mrk_id = marker_ids[recording] if recording in use_for_session: assert mrk_id == marker_ids[use_for_session[recording]] continue elif mrk_id not in use_for_id: use_for_id[mrk_id] = recording use_for_session[recording] = use_for_id[mrk_id] # for files missing digitizer, use singe available fwd-recording for recording in dig_missing: if use_for_id: assert len(use_for_id) == 1 use_for_session[recording] = use_for_id[0] # save input-state if not cache_dir_existed: os.makedirs(cache_dir, exist_ok=True) save.pickle(input_state, input_state_file) self._dig_sessions = pipe._dig_sessions = input_state['fwd-sessions'] # {subject: {for_recording: use_recording}} # Check the cache, delete invalid files # ===================================== save_state = new_state = { 'version': CACHE_STATE_VERSION, 'raw': {k: v.as_dict() for k, v in self._raw.items()}, 'groups': self._groups, 'epochs': {k: v.as_dict() for k, v in self._epochs.items()}, 'tests': {k: v.as_dict() for k, v in self._tests.items()}, 'parcs': {k: v.as_dict() for k, v in self._parcs.items()}, 'events': events, } cache_state_path = join(cache_dir, 'cache-state.pickle') if exists(cache_state_path): # check time stamp # ================ state_mtime = getmtime(cache_state_path) now = time.time() + IS_WINDOWS # Windows seems to have rounding issue if state_mtime > now: raise RuntimeError(f"The cache's time stamp is in the future ({time.ctime(state_mtime)}). If the system time ({time.ctime(now)}) is wrong, adjust the system clock; if not, delete the eelbrain-cache folder.") cache_state = load.unpickle(cache_state_path) cache_state_v = cache_state.setdefault('version', 0) if cache_state_v < CACHE_STATE_VERSION: log.debug("Updating cache-state %i -> %i", cache_state_v, CACHE_STATE_VERSION) save_state = deepcopy(save_state) self._state_backwards_compat(cache_state_v, new_state, cache_state) elif cache_state_v > CACHE_STATE_VERSION: raise RuntimeError(f"The cache is from a newer version of Eelbrain than you are currently using. Either upgrade Eelbrain or delete the cache folder.") # Find modified definitions # ========================= invalid_cache = self._check_cache(new_state, cache_state, root) # Collect invalid files # ===================== if invalid_cache or cache_state_v < 2: rm = self._collect_invalid_files(invalid_cache, new_state, cache_state) # find actual files to delete log.debug("Outdated cache files:") files = set() result_files = [] for temp, arg_dicts in rm.items(): for args in arg_dicts: pattern = self._glob_pattern(temp, True, vmatch=False, **args) filenames = glob(pattern) files.update(filenames) # log rel_pattern = relpath(pattern, root) rel_filenames = sorted(' ' + relpath(f, root) for f in filenames) log.debug(' >%s', rel_pattern) for filename in rel_filenames: log.debug(filename) # message to the screen unless log is already displayed if rel_pattern.startswith('results'): result_files.extend(rel_filenames) # handle invalid files n_result_files = len(result_files) if n_result_files and self.auto_delete_cache is True and not self.auto_delete_results: if self._screen_log_level > logging.DEBUG: msg = result_files[:] msg.insert(0, "Outdated result files detected:") else: msg = [] msg.append("Delete %i outdated results?" % (n_result_files,)) command = ask( '\n'.join(msg), options=( ('delete', 'delete invalid result files'), ('abort', 'raise an error')), help=CACHE_HELP.format( experiment=self.__class__.__name__, filetype='result'), ) if command == 'abort': raise RuntimeError("User aborted invalid result deletion") elif command != 'delete': raise RuntimeError("command=%r" % (command,)) if files: if self.auto_delete_cache is False: raise RuntimeError( "Automatic cache management disabled. Either " "revert changes, or set e.auto_delete_cache=True") elif isinstance(self.auto_delete_cache, str): if self.auto_delete_cache != 'debug': raise ValueError(f"MneExperiment.auto_delete_cache={self.auto_delete_cache!r}") command = ask( "Outdated cache files. Choose 'delete' to proceed. " "WARNING: only choose 'ignore' or 'revalidate' if " "you know what you are doing.", options=( ('delete', 'delete invalid files'), ('abort', 'raise an error'), ('ignore', 'proceed without doing anything'), ('revalidate', "don't delete any cache files but write a new cache-state file")), help=CACHE_HELP.format( experiment=self.__class__.__name__, filetype='cache and/or result'), ) if command == 'delete': pass elif command == 'abort': raise RuntimeError("User aborted invalid cache deletion") elif command == 'ignore': log.warning("Ignoring invalid cache") return elif command == 'revalidate': log.warning("Revalidating invalid cache") files.clear() else: raise RuntimeError("command=%s" % repr(command)) elif self.auto_delete_cache is not True: raise TypeError(f"MneExperiment.auto_delete_cache={self.auto_delete_cache!r}") # delete invalid files n_cache_files = len(files) - n_result_files descs = [] if n_result_files: descs.append("%i invalid result files" % n_result_files) if n_cache_files: descs.append("%i invalid cache files" % n_cache_files) log.info("Deleting " + (' and '.join(descs)) + '...') for path in files: os.remove(path) else: log.debug("No existing cache files affected.") else: log.debug("Cache up to date.") elif cache_dir_existed: # cache-dir but no history if self.auto_delete_cache is True: log.info("Deleting cache-dir without history") shutil.rmtree(cache_dir) os.mkdir(cache_dir) elif self.auto_delete_cache == 'disable': log.warning("Ignoring cache-dir without history") elif self.auto_delete_cache == 'debug': command = ask("Cache directory without history", (('validate', 'write a history file treating cache as valid'), ('abort', 'raise an error'))) if command == 'abort': raise RuntimeError("User aborted") elif command == 'validate': log.warning("Validating cache-dir without history") else: raise RuntimeError("command=%r" % (command,)) else: raise IOError("Cache directory without history, but auto_delete_cache is not True") elif not exists(cache_dir): os.mkdir(cache_dir) save.pickle(save_state, cache_state_path) def _state_backwards_compat(self, cache_state_v, new_state, cache_state): "Update state dicts for backwards-compatible comparison" # epochs if cache_state_v < 3: # Epochs represented as dict up to Eelbrain 0.24 new_state['epochs'] = {k: v.as_dict_24() for k, v in self._epochs.items()} for e in cache_state['epochs'].values(): e.pop('base', None) if 'sel_epoch' in e: e.pop('n_cases', None) elif cache_state_v < 11: # remove samplingrate parameter new_state['epochs'] = {k: {ki: vi for ki, vi in v.items() if ki != 'samplingrate'} for k, v in new_state['epochs'].items()} # events did not include session if cache_state_v < 4: session = self._sessions[0] cache_state['events'] = {(subject, session): v for subject, v in cache_state['events'].items()} # raw pipeline if cache_state_v < 5: legacy_raw = assemble_pipeline(LEGACY_RAW, '', '', '', '', self._sessions, self._log) cache_state['raw'] = {k: v.as_dict() for k, v in legacy_raw.items()} # parcellations represented as dicts if cache_state_v < 6: for params in cache_state['parcs'].values(): for key in ('morph_from_fsaverage', 'make'): if key in params: del params[key] # tests represented as dicts if cache_state_v < 7: for params in cache_state['tests'].values(): if 'desc' in params: del params['desc'] cache_state['tests'] = {k: v.as_dict() for k, v in assemble_tests(cache_state['tests']).items()} elif cache_state_v == 7: # 'kind' key missing for name, params in cache_state['tests'].items(): if name in new_state['tests']: params['kind'] = new_state['tests'][name]['kind'] if cache_state_v < 12: # 'vars' entry added to all for test, params in cache_state['tests'].items(): if 'vars' in params: try: params['vars'] = Variables(params['vars']) except Exception as error: self._log.warning(" Test %s: Defective vardef %r", test, params['vars']) params['vars'] = None else: params['vars'] = None def _check_cache(self, new_state, cache_state, root): invalid_cache = defaultdict(set) # events (subject, recording): overall change in events # variables: event change restricted to certain variables # raw: preprocessing definition changed # groups: change in group members # epochs: change in epoch parameters # parcs: parc def change # tests: test def change # check events # 'events' -> number or timing of triggers (includes trigger_shift) # 'variables' -> only variable change for key, old_events in cache_state['events'].items(): new_events = new_state['events'].get(key) if new_events is None: invalid_cache['events'].add(key) self._log.warning(" raw file removed: %s", '/'.join(key)) elif new_events.n_cases != old_events.n_cases: invalid_cache['events'].add(key) self._log.warning(" event length: %s %i->%i", '/'.join(key), old_events.n_cases, new_events.n_cases) elif not np.all(new_events['i_start'] == old_events['i_start']): invalid_cache['events'].add(key) self._log.warning(" trigger times changed: %s", '/'.join(key)) else: for var in old_events: if var == 'i_start': continue elif var not in new_events: invalid_cache['variables'].add(var) self._log.warning(" var removed: %s (%s)", var, '/'.join(key)) continue old = old_events[var] new = new_events[var] if old.name != new.name: invalid_cache['variables'].add(var) self._log.warning(" var name changed: %s (%s) %s->%s", var, '/'.join(key), old.name, new.name) elif new.__class__ is not old.__class__: invalid_cache['variables'].add(var) self._log.warning(" var type changed: %s (%s) %s->%s", var, '/'.join(key), old.__class__, new.__class) elif not all_equal(old, new, True): invalid_cache['variables'].add(var) self._log.warning(" var changed: %s (%s) %i values", var, '/'.join(key), np.sum(new != old)) # groups for group, members in cache_state['groups'].items(): if group not in self._groups: invalid_cache['groups'].add(group) self._log.warning(" Group removed: %s", group) elif members != self._groups[group]: invalid_cache['groups'].add(group) log_list_change(self._log, "Group", group, members, self._groups[group]) # raw changed, changed_ica = compare_pipelines(cache_state['raw'], new_state['raw'], self._log) if changed: invalid_cache['raw'].update(changed) for raw, status in changed_ica.items(): filenames = self.glob('ica-file', raw=raw, subject='*', visit='*', match=False) if filenames: rel_paths = '\n'.join(relpath(path, root) for path in filenames) print(f"Outdated ICA files:\n{rel_paths}") ask_to_delete_ica_files(raw, status, filenames) # epochs for epoch, old_params in cache_state['epochs'].items(): new_params = new_state['epochs'].get(epoch, None) if old_params != new_params: invalid_cache['epochs'].add(epoch) log_dict_change(self._log, 'Epoch', epoch, old_params, new_params) # parcs for parc, old_params in cache_state['parcs'].items(): new_params = new_state['parcs'].get(parc, None) if old_params == new_params: continue elif new_params is None: # Don't automatically remove because they could be user-created continue new_parc = self._parcs[parc] if isinstance(new_parc, (FreeSurferParc, FSAverageParc)): # FreeSurferParc: Parcellations that are provided by the user # should not be automatically removed. # FSAverageParc: for other mrisubjects, the parcellation # should automatically update if the user changes the # fsaverage file. continue log_dict_change(self._log, "Parc", parc, old_params, new_params) invalid_cache['parcs'].add(parc) if any(p['kind'].endswith('seeded') for p in (new_params, old_params)): invalid_cache['parcs'].add(f'{parc}-?') invalid_cache['parcs'].add(f'{parc}-??') invalid_cache['parcs'].add(f'{parc}-???') # tests for test, old_params in cache_state['tests'].items(): new_params = new_state['tests'].get(test, None) if old_params != new_params: invalid_cache['tests'].add(test) log_dict_change(self._log, "Test", test, old_params, new_params) # Secondary invalidations # ======================== # changed events -> group result involving those subjects is also bad if 'events' in invalid_cache: subjects = {subject for subject, _ in invalid_cache['events']} for group, members in cache_state['groups'].items(): if subjects.intersection(members): invalid_cache['groups'].add(group) # tests/epochs based on variables if 'variables' in invalid_cache: bad_vars = invalid_cache['variables'] # tests using bad variable for test in cache_state['tests']: if test in invalid_cache['tests']: continue params = new_state['tests'][test] bad = bad_vars.intersection(find_test_vars(params)) if bad: invalid_cache['tests'].add(test) self._log.debug(" Test %s depends on changed variables %s", test, ', '.join(bad)) # epochs using bad variable epochs_vars = find_epochs_vars(cache_state['epochs']) for epoch, evars in epochs_vars.items(): bad = bad_vars.intersection(evars) if bad: invalid_cache['epochs'].add(epoch) self._log.debug(" Epoch %s depends on changed variables %s", epoch, ', '.join(bad)) # secondary epochs if 'epochs' in invalid_cache: for e in tuple(invalid_cache['epochs']): invalid_cache['epochs'].update(find_dependent_epochs(e, cache_state['epochs'])) # epochs -> cov for cov, cov_params in self._covs.items(): if cov_params.get('epoch') in invalid_cache['epochs']: invalid_cache['cov'].add(cov) return invalid_cache def _collect_invalid_files(self, invalid_cache, new_state, cache_state): rm = defaultdict(DictSet) # version if cache_state['version'] < 2: bad_parcs = [] for parc, params in self._parcs.items(): if params['kind'] == 'seeded': bad_parcs.append(parc + '-?') bad_parcs.append(parc + '-??') bad_parcs.append(parc + '-???') else: bad_parcs.append(parc) bad_tests = [] for test, params in new_state['tests'].items(): if params['kind'] == 'anova' and params['x'].count('*') > 1: bad_tests.append(test) if bad_tests and bad_parcs: self._log.warning(" Invalid ANOVA tests: %s for %s", bad_tests, bad_parcs) for test, parc in product(bad_tests, bad_parcs): rm['test-file'].add({'test': test, 'test_dims': parc}) rm['report-file'].add({'test': test, 'folder': parc}) # evoked files are based on old events for subject, recording in invalid_cache['events']: for epoch, params in self._epochs.items(): if recording not in params.sessions: continue rm['evoked-file'].add({'subject': subject, 'epoch': epoch}) # variables for var in invalid_cache['variables']: rm['evoked-file'].add({'model': f'*{var}*'}) # groups for group in invalid_cache['groups']: rm['test-file'].add({'group': group}) rm['group-mov-file'].add({'group': group}) rm['report-file'].add({'group': group}) # raw for raw in invalid_cache['raw']: rm['cached-raw-file'].add({'raw': raw}) rm['evoked-file'].add({'raw': raw}) rm['cov-file'].add({'raw': raw}) analysis = {'analysis': f'{raw} *'} rm['test-file'].add(analysis) rm['report-file'].add(analysis) rm['group-mov-file'].add(analysis) rm['subject-mov-file'].add(analysis) # epochs for epoch in invalid_cache['epochs']: rm['evoked-file'].add({'epoch': epoch}) rm['test-file'].add({'epoch': epoch}) rm['report-file'].add({'epoch': epoch}) rm['group-mov-file'].add({'epoch': epoch}) rm['subject-mov-file'].add({'epoch': epoch}) # cov for cov in invalid_cache['cov']: rm['cov-file'].add({'cov': cov}) rm['inv-file'].add({'cov': cov}) analysis = f'* {cov} *' rm['test-file'].add({'analysis': analysis}) rm['report-file'].add({'analysis': analysis}) rm['group-mov-file'].add({'analysis': analysis}) rm['subject-mov-file'].add({'analysis': analysis}) # parcs for parc in invalid_cache['parc']: rm['annot-file'].add({'parc': parc}) rm['test-file'].add({'test_dims': parc}) rm['test-file'].add({'test_dims': f'{parc}.*'}) rm['report-file'].add({'folder': parc}) rm['report-file'].add({'folder': f'{parc} *'}) rm['report-file'].add({'folder': f'{parc.capitalize()} *'}) # pre 0.26 rm['res-file'].add({'analysis': 'Source Annot', 'resname': f'{parc} * *', 'ext': 'p*'}) # tests for test in invalid_cache['tests']: rm['test-file'].add({'test': test}) rm['report-file'].add({'test': test}) if not self.cache_inv: rm['inv-file'].add({}) # secondary cache files for temp in tuple(rm): for stemp in self._secondary_cache[temp]: rm[stemp].update(rm[temp]) return rm def _subclass_init(self): "Allow subclass to register experimental features" def __iter__(self): "Iterate state through subjects and yield each subject name." for subject in self.iter(): yield subject # mtime methods # ------------- # _mtime() functions return the time at which any input files affecting the # given file changed, and None if inputs are missing. They don't check # whether the file actually exists (usually there is no need to recompute an # intermediate file if it is not needed). # _file_mtime() functions directly return the file's mtime, or None if it # does not exists or is outdated def _annot_file_mtime(self, make_for=None): """Return max mtime of annot files or None if they do not exist. Can be user input, so we need to check the actual file. """ if make_for: with self._temporary_state: self.make_annot(mrisubject=make_for) return self._annot_file_mtime() mtime = 0 for _ in self.iter('hemi'): fpath = self.get('annot-file') if exists(fpath): mtime = max(mtime, getmtime(fpath)) else: return return mtime def _cov_mtime(self): params = self._covs[self.get('cov')] with self._temporary_state: if 'epoch' in params: self.set(epoch=params['epoch']) return self._epochs_mtime() else: self.set(session=params['session']) return self._raw_mtime() def _epochs_mtime(self): raw_mtime = self._raw_mtime() if raw_mtime: epoch = self._epochs[self.get('epoch')] rej_mtime = self._rej_mtime(epoch) if rej_mtime: return max(raw_mtime, rej_mtime) def _epochs_stc_mtime(self): "Mtime affecting source estimates; does not check annot" epochs_mtime = self._epochs_mtime() if epochs_mtime: inv_mtime = self._inv_mtime() if inv_mtime: return max(epochs_mtime, inv_mtime) def _evoked_mtime(self): return self._epochs_mtime() def _evoked_stc_mtime(self): "Mtime if up-to-date, else None; do not check annot" evoked_mtime = self._evoked_mtime() if evoked_mtime: inv_mtime = self._inv_mtime() if inv_mtime: return max(evoked_mtime, inv_mtime) def _fwd_mtime(self, subject=None, recording=None, fwd_recording=None): "The last time at which input files affecting fwd-file changed" trans = self.get('trans-file') if exists(trans): src = self.get('src-file') if exists(src): if fwd_recording is None: fwd_recording = self._get_fwd_recording(subject, recording) raw_mtime = self._raw_mtime('raw', False, subject, fwd_recording) if raw_mtime: trans_mtime = getmtime(trans) src_mtime = getmtime(src) return max(raw_mtime, trans_mtime, src_mtime) def _inv_mtime(self, fwd_recording=None): fwd_mtime = self._fwd_mtime(fwd_recording=fwd_recording) if fwd_mtime: cov_mtime = self._cov_mtime() if cov_mtime: return max(cov_mtime, fwd_mtime) def _raw_mtime(self, raw=None, bad_chs=True, subject=None, recording=None): if raw is None: raw = self.get('raw') elif raw not in self._raw: raise RuntimeError(f"raw-mtime with raw={raw!r}") pipe = self._raw[raw] if subject is None: subject = self.get('subject') if recording is None: recording = self.get('recording') return pipe.mtime(subject, recording, bad_chs) def _rej_mtime(self, epoch): """rej-file mtime for secondary epoch definition Parameters ---------- epoch : dict Epoch definition. """ rej = self._artifact_rejection[self.get('rej')] if rej['kind'] is None: return 1 # no rejection with self._temporary_state: paths = [self.get('rej-file', epoch=e) for e in epoch.rej_file_epochs] if all(exists(path) for path in paths): mtime = max(getmtime(path) for path in paths) return mtime def _result_file_mtime(self, dst, data, single_subject=False): """MTime if up-to-date, else None (for reports and movies) Parameters ---------- dst : str Filename. data : TestDims Data type. single_subject : bool Whether the corresponding test is performed for a single subject (as opposed to the current group). """ if exists(dst): mtime = self._result_mtime(data, single_subject) if mtime: dst_mtime = getmtime(dst) if dst_mtime > mtime: return dst_mtime def _result_mtime(self, data, single_subject): "See ._result_file_mtime() above" if data.source: if data.parc_level: if single_subject: out = self._annot_file_mtime(self.get('mrisubject')) elif data.parc_level == 'common': out = self._annot_file_mtime(self.get('common_brain')) elif data.parc_level == 'individual': out = 0 for _ in self: mtime = self._annot_file_mtime() if mtime is None: return else: out = max(out, mtime) else: raise RuntimeError(f"data={data.string!r}, parc_level={data.parc_level!r}") else: out = 1 if not out: return mtime_func = self._epochs_stc_mtime else: out = 1 mtime_func = self._epochs_mtime if single_subject: mtime_iterator = (mtime_func(),) else: mtime_iterator = (mtime_func() for _ in self) for mtime in mtime_iterator: if not mtime: return out = max(out, mtime) return out def _process_subject_arg(self, subjects, kwargs): """Process subject arg for methods that work on groups and subjects Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). kwargs : dict Additional state parameters to set. Returns ------- subject : None | str Subject name if the value specifies a subject, None otherwise. group : None | str Group name if the value specifies a group, None otherwise. """ if subjects is None: # default: subjects = -1 if 'group' in kwargs else 1 elif subjects is True: # legacy value: subjects = -1 if isinstance(subjects, int): if subjects == 1: return self.get('subject', **kwargs), None elif subjects == -1: return None, self.get('group', **kwargs) else: raise ValueError(f"subjects={subjects}") elif isinstance(subjects, str): if subjects in self.get_field_values('group'): if 'group' in kwargs: if kwargs['group'] != subjects: raise ValueError(f"group={kwargs["group"]!r} inconsistent with subject={subjects!r}") self.set(**kwargs) else: self.set(group=subjects, **kwargs) return None, subjects else: return self.get('subject', subject=subjects, **kwargs), None else: raise TypeError(f"subjects={subjects!r}") def _cluster_criteria_kwargs(self, data): criteria = self._cluster_criteria[self.get('select_clusters')] return {'min' + dim: criteria[dim] for dim in data.dims if dim in criteria} def _add_vars(self, ds, vardef: Union[None, str, Variables], groupvars=False): """Add vars to the dataset Parameters ---------- ds : Dataset Event dataset. vardef : dict | tuple Variable definition. groupvars : bool Apply GroupVars in ``self.variables`` (when adding variables to a dataset that does not originate from events, such as TRFs). """ if groupvars: self._variables.apply(ds, self, group_only=True) if vardef is None: return elif isinstance(vardef, str): try: vardef = self._tests[vardef].vars except KeyError: raise ValueError(f"vardef={vardef!r}") elif not isinstance(vardef, Variables): vardef = Variables(vardef) vardef.apply(ds, self) def _backup(self, dst_root, v=False): """Backup all essential files to ``dst_root``. .. warning:: Method is out of data and probably does not work as expected. Parameters ---------- dst_root : str Directory to use as root for the backup. v : bool Verbose mode: list all files that will be copied and ask for confirmation. Notes ----- For repeated backups ``dst_root`` can be the same. If a file has been previously backed up, it is only copied if the local copy has been modified more recently than the previous backup. If the backup has been modified more recently than the local copy, a warning is displayed. Currently, the following files are included in the backup:: * All rejection files * The trans-file * All files in the ``meg/{subject}/logs`` directory * For scaled MRIs, the file specifying the scale parameters MRIs are currently not backed up. """ self._log.debug("Initiating backup to %s" % dst_root) root = self.get('root') root_len = len(root) + 1 dirs = [] # directories to create pairs = [] # (src, dst) pairs to copy for temp, state_mod in self._backup_files: # determine state if state_mod: state = self._backup_state.copy() state.update(state_mod) else: state = self._backup_state # find files to back up if temp.endswith('dir'): paths = [] for dirpath in self.glob(temp, **state): for root_, _, filenames in os.walk(dirpath): paths.extend(join(root_, fn) for fn in filenames) else: paths = self.glob(temp, **state) # convert to (src, dst) pairs for src in paths: if not src.startswith(root): raise ValueError("Can only backup files in root directory") tail = src[root_len:] dst = join(dst_root, tail) if exists(dst): src_m = getmtime(src) dst_m = getmtime(dst) if dst_m == src_m: continue elif dst_m > src_m: self._log.warning("Backup more recent than original: %s", tail) continue else: i = 0 while True: i = tail.find(os.sep, i + 1) if i == -1: break path = tail[:i] if path not in dirs: dirs.append(path) pairs.append((src, dst)) if len(pairs) == 0: if v: print("All files backed up.") else: self._log.info("All files backed up.") return # verbose file list if v: paths = [relpath(src, root) for src, _ in pairs] print('\n'.join(paths)) cmd = 'x' while cmd not in 'yn': cmd = input("Proceed ([y]/n)? ") if cmd == 'n': print("Abort.") return else: print("Backing up %i files ..." % len(pairs)) self._log.info("Backing up %i files ..." % len(pairs)) # create directories for dirname in dirs: dirpath = join(dst_root, dirname) if not exists(dirpath): os.mkdir(dirpath) # copy files for src, dst in pairs: shutil.copy2(src, dst) def clear_cache(self, level=1): """Remove cached files. Parameters ---------- level : int Level up to which to clear the cache (see notes below). The default is 1, which deletes all cached files. Notes ----- Each lower level subsumes the higher levels: ``1`` Delete all cached files. ``2`` Epoched files - these need to be cleared when anything about the epoch definition changes (tmin, tmax, event inclusion, ...). Note that you might also have to manually update epoch rejection files with the :meth:`MneExperiment.make_epoch_selection` method. ``5`` tests - these need to be cleared when the members of the relevant subject groups change. Examples -------- To delete only test files, after adding raw data for a new subject to the experiment:: >>> e.clear_cache(5) To delete cached data files after changing the selection criteria for a secondary epoch:: >>> e.clear_cache(2) If criteria on a primary epoch are changed, the trial rejection has to be re-done in addition to clearing the cache. To delete all cached files and clear up hard drive space:: >>> e.clear_cache(1) """ if level <= 1: self.rm('cache-dir', confirm=True) print("All cached data cleared.") else: if level <= 2: self.rm('evoked-dir', confirm=True) self.rm('cov-dir', confirm=True) print("Cached epoch data cleared") if level <= 5: self.rm('test-dir', confirm=True) print("Cached tests cleared.") def get_field_values(self, field, exclude=(), **state): """Find values for a field taking into account exclusion Parameters ---------- field : str Field for which to find values. exclude : list of str Exclude these values. ... State parameters. """ if state: self.set(**state) if isinstance(exclude, str): exclude = (exclude,) if field == 'mrisubject': subjects = FileTree.get_field_values(self, 'subject') mri_subjects = self._mri_subjects[self.get('mri')] mrisubjects = sorted(mri_subjects[s] for s in subjects) if exclude: mrisubjects = [s for s in mrisubjects if s not in exclude] common_brain = self.get('common_brain') if common_brain and (not exclude or common_brain not in exclude): mrisubjects.insert(0, common_brain) return mrisubjects else: return FileTree.get_field_values(self, field, exclude) def _get_fwd_recording(self, subject: str = None, recording: str = None) -> str: if subject is None: subject = self.get('subject') if recording is None: recording = self.get('recording') try: return self._dig_sessions[subject][recording] except KeyError: raise FileMissing(f"Raw data missing for {subject}, session {recording}") def iter(self, fields='subject', exclude=None, values=None, group=None, progress_bar=None, **kwargs): """ Cycle the experiment's state through all values on the given fields Parameters ---------- fields : sequence | str Field(s) over which should be iterated. exclude : dict {str: iterator over str} Exclude values from iteration (``{field: values_to_exclude}``). values : dict {str: iterator over str} Fields with custom values to iterate over (instead of the corresponding field values) with {name: (sequence of values)} entries. group : None | str If iterating over subjects, use this group ('all' for all except excluded subjects, 'all!' for all including excluded subjects, or a name defined in experiment.groups). progress_bar : str Message to show in the progress bar. ... Fields with constant values throughout the iteration. """ if group is not None: kwargs['group'] = group return FileTree.iter(self, fields, exclude, values, progress_bar, **kwargs) def iter_range(self, start=None, stop=None, field='subject'): """Iterate through a range on a field with ordered values. Parameters ---------- start : None | str Start value (inclusive). With ``None``, begin at the first value. stop : None | str Stop value (inclusive). With ``None``, end with the last value. field : str Name of the field. Returns ------- iterator over value : str Current field value. """ values = self.get_field_values(field) if start is not None: start = values.index(start) if stop is not None: stop = values.index(stop) + 1 values = values[start:stop] with self._temporary_state: for value in values: self._restore_state(discard_tip=False) self.set(**{field: value}) yield value def _label_events(self, ds): # add standard variables ds['T'] = ds['i_start'] / ds.info['sfreq'] ds['SOA'] = ds['T'].diff(0) ds['subject'] = Factor([ds.info['subject']], repeat=ds.n_cases, random=True) if len(self._sessions) > 1: ds[:, 'session'] = ds.info['session'] if len(self._visits) > 1: ds[:, 'visit'] = ds.info['visit'] self._variables.apply(ds, self) # subclass label_events info = ds.info ds = self.label_events(ds) if not isinstance(ds, Dataset): raise DefinitionError(f"{self.__class__.__name__}.label_events() needs to return the events Dataset. Got {ds!r}.") elif 'i_start' not in ds: raise DefinitionError(f"The Dataset returned by {self.__class__.__name__}.label_events() does not contain a variable called `i_start`. This variable is required to ascribe events to data samples.") elif 'trigger' not in ds: raise DefinitionError(f"The Dataset returned by {self.__class__.__name__}.label_events() does not contain a variable called `trigger`. This variable is required to check rejection files.") elif ds.info is not info: ds.info.update(info) return ds def label_events(self, ds): """Add event labels to events loaded from raw files Parameters ---------- ds : Dataset A Dataset containing events (with variables as returned by :func:`load.fiff.events`). Notes ----- Override this method in MneExperiment subclasses to add event labels. The session that the events are from can be determined with ``ds.info['session']``. Calling the original (super-class) method is not necessary. """ return ds def label_subjects(self, ds): """Label the subjects in ds Creates a boolean :class:`Var` in ``ds`` for each group marking group membership. Parameters ---------- ds : Dataset A Dataset with 'subject' entry. """ subject = ds['subject'] for name, subjects in self._groups.items(): ds[name] = Var(subject.isin(subjects)) def label_groups(self, subject, groups): """Generate Factor for group membership Parameters ---------- subject : Factor A Factor with subjects. groups : list of str | {str: str} dict Groups which to label (raises an error if group membership is not unique). To use labels other than the group names themselves, use a ``{group: label}`` dict. Returns ------- group : Factor A :class:`Factor` that labels the group for each subject. """ if not isinstance(groups, dict): groups = {g: g for g in groups} labels = {s: [l for g, l in groups.items() if s in self._groups[g]] for s in subject.cells} problems = [s for s, g in labels.items() if len(g) != 1] if problems: desc = (', '.join(labels[s]) if labels[s] else 'no group' for s in problems) msg = ', '.join('%s (%s)' % pair for pair in zip(problems, desc)) raise ValueError(f"Groups {groups} are not unique for subjects: {msg}") labels = {s: g[0] for s, g in labels.items()} return Factor(subject, labels=labels) def load_annot(self, **state): """Load a parcellation (from an annot file) Returns ------- labels : list of Label Labels in the parcellation (output of :func:`mne.read_labels_from_annot`). ... State parameters. """ self.make_annot(**state) return mne.read_labels_from_annot(self.get('mrisubject'), self.get('parc'), 'both', subjects_dir=self.get('mri-sdir')) def load_bad_channels(self, **kwargs): """Load bad channels Parameters ---------- ... State parameters. Returns ------- bad_chs : list of str Bad chnnels. """ pipe = self._raw[self.get('raw', **kwargs)] return pipe.load_bad_channels(self.get('subject'), self.get('recording')) def _load_bem(self): subject = self.get('mrisubject') if subject == 'fsaverage' or is_fake_mri(self.get('mri-dir')): return mne.read_bem_surfaces(self.get('bem-file')) else: bem_dir = self.get('bem-dir') surfs = ('inner_skull', 'outer_skull', 'outer_skin') paths = {s: join(bem_dir, s + '.surf') for s in surfs} missing = [s for s in surfs if not exists(paths[s])] if missing: bem_dir = self.get('bem-dir') temp = join(".*", "bem", "(.*)") for surf in missing[:]: path = paths[surf] if os.path.islink(path): # try to fix broken symlinks old_target = os.readlink(path) m = re.match(temp, old_target) if m: new_target = m.group(1) if exists(join(bem_dir, new_target)): self._log.info("Fixing broken symlink for %s " "%s surface file", subject, surf) os.unlink(path) os.symlink(new_target, path) missing.remove(surf) # continue # self._log.info("Deleting broken symlink " + path) # os.unlink(path) if missing: self._log.info("%s %s missing for %s. Running " "mne.make_watershed_bem()...", enumeration(missing).capitalize(), plural('surface', len(missing)), subject) # re-run watershed_bem # mne-python expects the environment variable os.environ['FREESURFER_HOME'] = subp.get_fs_home() mne.bem.make_watershed_bem(subject, self.get('mri-sdir'), overwrite=True) return mne.make_bem_model(subject, conductivity=(0.3,), subjects_dir=self.get('mri-sdir')) def load_cov(self, **kwargs): """Load the covariance matrix Parameters ---------- ... State parameters. """ return mne.read_cov(self.get('cov-file', make=True, **kwargs)) def load_edf(self, **kwargs): """Load the edf file ("edf-file" template) Parameters ---------- ... State parameters. """ path = self.get('edf-file', fmatch=False, **kwargs) return load.eyelink.Edf(path) def load_epochs(self, subjects=None, baseline=False, ndvar=True, add_bads=True, reject=True, cat=None, decim=None, pad=0, data_raw=False, vardef=None, data='sensor', trigger_shift=True, tmin=None, tmax=None, tstop=None, interpolate_bads=False, **kwargs): """ Load a Dataset with epochs for a given epoch definition Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). baseline : bool | tuple Apply baseline correction using this period. True to use the epoch's baseline specification. The default is to not apply baseline correction. ndvar : bool | 'both' Convert epochs to an NDVar (named 'meg' for MEG data and 'eeg' for EEG data). Use 'both' to include NDVar and MNE Epochs. add_bads : bool | list Add bad channel information to the Raw. If True, bad channel information is retrieved from the bad channels file. Alternatively, a list of bad channels can be specified. reject : bool | 'keep' Reject bad trials. If ``True`` (default), bad trials are removed from the Dataset. Set to ``False`` to ignore the trial rejection. Set ``reject='keep'`` to load the rejection (added it to the events as ``'accept'`` variable), but keep bad trails. cat : sequence of cell-names Only load data for these cells (cells of model). decim : int Data decimation factor (the default is the factor specified in the epoch definition). pad : scalar Pad the epochs with this much time (in seconds; e.g. for spectral analysis). data_raw : bool Keep the :class:`mne.io.Raw` instance in ``ds.info['raw']`` (default False). vardef : str Name of a test defining additional variables. data : str Data to load; 'sensor' to load all sensor data (default); 'sensor.rms' to return RMS over sensors. Only applies to NDVar output. trigger_shift : bool Apply post-baseline trigger-shift if it applies to the epoch (default True). tmin : scalar Override the epoch's ``tmin`` parameter. tmax : scalar Override the epoch's ``tmax`` parameter. tstop : scalar Override the epoch's ``tmax`` parameter as exclusive ``tstop``. interpolate_bads : bool Interpolate channels marked as bad for the whole recording (useful when comparing topographies across subjects; default False). ... Applicable :ref:`state-parameters`: - :ref:`state-raw`: preprocessing pipeline - :ref:`state-epoch`: which events to use and time window - :ref:`state-rej`: which trials to use """ data = TestDims.coerce(data) if not data.sensor: raise ValueError(f"data={data.string!r}; load_evoked is for loading sensor data") elif data.sensor is not True: if not ndvar: raise ValueError(f"data={data.string!r} with ndvar=False") elif interpolate_bads: raise ValueError(f"interpolate_bads={interpolate_bads!r} with data={data.string}") if ndvar: if isinstance(ndvar, str): if ndvar != 'both': raise ValueError("ndvar=%s" % repr(ndvar)) subject, group = self._process_subject_arg(subjects, kwargs) epoch_name = self.get('epoch') if group is not None: dss = [] for _ in self.iter(group=group, progress=f"Load {epoch_name}"): ds = self.load_epochs(None, baseline, ndvar, add_bads, reject, cat, decim, pad, data_raw, vardef, data, True, tmin, tmax, tstop, interpolate_bads) dss.append(ds) return combine(dss) # single subject epoch = self._epochs[epoch_name] if isinstance(epoch, EpochCollection): dss = [] with self._temporary_state: for sub_epoch in epoch.collect: ds = self.load_epochs(subject, baseline, ndvar, add_bads, reject, cat, decim, pad, data_raw, vardef, data, trigger_shift, tmin, tmax, tstop, interpolate_bads, epoch=sub_epoch) ds[:, 'epoch'] = sub_epoch dss.append(ds) return combine(dss) if isinstance(add_bads, str): if add_bads == 'info': add_bads_to_info = True add_bads = True else: raise ValueError(f"add_bads={add_bads!r}") else: add_bads_to_info = False with self._temporary_state: ds = self.load_selected_events(add_bads=add_bads, reject=reject, data_raw=True, vardef=vardef, cat=cat) if ds.n_cases == 0: err = f"No events left for epoch={epoch.name!r}, subject={subject!r}" if cat: err += f", cat={cat!r}" raise RuntimeError(err) # load sensor space data if tmin is None: tmin = epoch.tmin if tmax is None and tstop is None: tmax = epoch.tmax if baseline is True: baseline = epoch.baseline if pad: tmin -= pad tmax += pad decim = decim_param(epoch, decim, ds.info['raw'].info) with warnings.catch_warnings(): warnings.filterwarnings('ignore', 'The events passed to the Epochs constructor', RuntimeWarning) ds = load.fiff.add_mne_epochs(ds, tmin, tmax, baseline, decim=decim, drop_bad_chs=False, tstop=tstop) # post baseline-correction trigger shift if trigger_shift and epoch.post_baseline_trigger_shift: ds['epochs'] = shift_mne_epoch_trigger(ds['epochs'], ds[epoch.post_baseline_trigger_shift], epoch.post_baseline_trigger_shift_min, epoch.post_baseline_trigger_shift_max) info = ds['epochs'].info data_to_ndvar = data.data_to_ndvar(info) # determine channels to interpolate bads_all = None bads_individual = None if interpolate_bads: bads_all = info['bads'] if ds.info[INTERPOLATE_CHANNELS] and any(ds[INTERPOLATE_CHANNELS]): bads_individual = ds[INTERPOLATE_CHANNELS] if bads_all: bads_all = set(bads_all) bads_individual = [sorted(bads_all.union(bads)) for bads in bads_individual] # interpolate bad channels if bads_all: if isinstance(interpolate_bads, str): if interpolate_bads == 'keep': reset_bads = False else: raise ValueError(f"interpolate_bads={interpolate_bads}") else: reset_bads = True ds['epochs'].interpolate_bads(reset_bads=reset_bads) # interpolate channels if reject and bads_individual: if 'mag' in data_to_ndvar: interp_path = self.get('interp-file') if exists(interp_path): interp_cache = load.unpickle(interp_path) else: interp_cache = {} n_in_cache = len(interp_cache) _interpolate_bads_meg(ds['epochs'], bads_individual, interp_cache) if len(interp_cache) > n_in_cache: save.pickle(interp_cache, interp_path) if 'eeg' in data_to_ndvar: _interpolate_bads_eeg(ds['epochs'], bads_individual) if ndvar: pipe = self._raw[self.get('raw')] exclude = () if add_bads_to_info else 'bads' for data_kind in data_to_ndvar: sysname = pipe.get_sysname(info, ds.info['subject'], data_kind) connectivity = pipe.get_connectivity(data_kind) name = 'meg' if data_kind == 'mag' else data_kind ds[name] = load.fiff.epochs_ndvar(ds['epochs'], data=data_kind, sysname=sysname, connectivity=connectivity, exclude=exclude) if add_bads_to_info: ds[name].info[BAD_CHANNELS] = ds['epochs'].info['bads'] if isinstance(data.sensor, str): ds[name] = getattr(ds[name], data.sensor)('sensor') if ndvar != 'both': del ds['epochs'] if not data_raw: del ds.info['raw'] return ds def load_epochs_stc(self, subjects=None, baseline=True, src_baseline=False, cat=None, keep_epochs=False, morph=False, mask=False, data_raw=False, vardef=None, decim=None, ndvar=True, reject=True, **state): """Load a Dataset with stcs for single epochs Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). Warning: loading single trial data for multiple subjects at once uses a lot of memory, which can lead to a periodically unresponsive terminal). baseline : bool | tuple Apply baseline correction using this period in sensor space. True to use the epoch's baseline specification (default). src_baseline : bool | tuple Apply baseline correction using this period in source space. True to use the epoch's baseline specification. The default is to not apply baseline correction. cat : sequence of cell-names Only load data for these cells (cells of model). keep_epochs : bool | 'ndvar' | 'both' Keep the sensor space data in the Dataset that is returned (default False; True to keep :class:`mne.Epochs` object; ``'ndvar'`` to keep :class:`NDVar`; ``'both'`` to keep both). morph : bool Morph the source estimates to the common_brain (default False). mask : bool | str Discard data that is labelled 'unknown' by the parcellation (only applies to NDVars, default False). data_raw : bool Keep the :class:`mne.io.Raw` instance in ``ds.info['raw']`` (default False). vardef : str Name of a test defining additional variables. decim : int Override the epoch decim factor. ndvar : bool Add the source estimates as :class:`NDVar` named "src" instead of a list of :class:`mne.SourceEstimate` objects named "stc" (default True). reject : bool | 'keep' Reject bad trials. If ``True`` (default), bad trials are removed from the Dataset. Set to ``False`` to ignore the trial rejection. Set ``reject='keep'`` to load the rejection (added it to the events as ``'accept'`` variable), but keep bad trails. ... Applicable :ref:`state-parameters`: - :ref:`state-raw`: preprocessing pipeline - :ref:`state-epoch`: which events to use and time window - :ref:`state-rej`: which trials to use - :ref:`state-cov`: covariance matrix for inverse solution - :ref:`state-src`: source space - :ref:`state-inv`: inverse solution Returns ------- epochs_dataset : Dataset Dataset containing single trial data (epochs). """ epoch_name = self.get('epoch') epoch = self._epochs[epoch_name] if not baseline and src_baseline and epoch.post_baseline_trigger_shift: raise NotImplementedError("src_baseline with post_baseline_trigger_shift") subject, group = self._process_subject_arg(subjects, state) if group is not None: if data_raw: raise ValueError(f"data_raw={data_raw!r} with group: Can not combine raw data from multiple subjects.") elif keep_epochs: raise ValueError(f"keep_epochs={keep_epochs!r} with group: Can not combine Epochs objects for different subjects. Set keep_epochs=False (default).") elif not morph: raise ValueError(f"morph={morph!r} with group: Source estimates can only be combined after morphing data to common brain model. Set morph=True.") dss = [] for _ in self.iter(group=group, progress_bar=f"Load {epoch_name} STC"): ds = self.load_epochs_stc(None, baseline, src_baseline, cat, keep_epochs, morph, mask, False, vardef, decim, ndvar, reject) dss.append(ds) return combine(dss) if keep_epochs is True: sns_ndvar = False del_epochs = False elif keep_epochs is False: sns_ndvar = False del_epochs = True elif keep_epochs == 'ndvar': sns_ndvar = 'both' del_epochs = True elif keep_epochs == 'both': sns_ndvar = 'both' del_epochs = False else: raise ValueError(f'keep_epochs={keep_epochs!r}') ds = self.load_epochs(subject, baseline, sns_ndvar, reject=reject, cat=cat, decim=decim, data_raw=data_raw, vardef=vardef) # load inv if src_baseline is True: src_baseline = epoch.baseline parc = self.get('parc') or None if isinstance(mask, str) and parc != mask: parc = mask self.set(parc=mask) # make sure annotation exists if parc: self.make_annot() epochs = ds['epochs'] inv = self.load_inv(epochs) # determine whether initial source-space can be restricted mri_sdir = self.get('mri-sdir') mrisubject = self.get('mrisubject') is_scaled = find_source_subject(mrisubject, mri_sdir) if mask and (is_scaled or not morph): label = label_from_annot(inv['src'], mrisubject, mri_sdir, parc) else: label = None stc = apply_inverse_epochs(epochs, inv, label=label, **self._params['apply_inv_kw']) if ndvar: src = self.get('src') src = load.fiff.stc_ndvar( stc, mrisubject, src, mri_sdir, self._params['apply_inv_kw']['method'], self._params['make_inv_kw'].get('fixed', False), parc=parc, connectivity=self.get('connectivity')) if src_baseline: src -= src.summary(time=src_baseline) if morph: common_brain = self.get('common_brain') with self._temporary_state: self.make_annot(mrisubject=common_brain) ds['srcm'] = morph_source_space(src, common_brain) if mask and not is_scaled: _mask_ndvar(ds, 'srcm') else: ds['src'] = src else: if src_baseline: raise NotImplementedError("Baseline for SourceEstimate") if morph: raise NotImplementedError("Morphing for SourceEstimate") ds['stc'] = stc if del_epochs: del ds['epochs'] return ds def load_events(self, subject=None, add_bads=True, data_raw=True, **kwargs): """ Load events from a raw file. Loads events from the corresponding raw file, adds the raw to the info dict. Parameters ---------- subject : str Subject for which to load events (default is the current subject in the experiment's state). add_bads : False | True | list Add bad channel information to the Raw. If True, bad channel information is retrieved from the bad channels file. Alternatively, a list of bad channels can be specified. data_raw : bool Keep the :class:`mne.io.Raw` instance in ``ds.info['raw']`` (default False). ... Applicable :ref:`state-parameters`: - :ref:`state-raw`: preprocessing pipeline - :ref:`state-epoch`: which events to use and time window """ evt_file = self.get('event-file', mkdir=True, subject=subject, **kwargs) subject = self.get('subject') # search for and check cached version raw_mtime = self._raw_mtime(bad_chs=False, subject=subject) if exists(evt_file): ds = load.unpickle(evt_file) if ds.info['raw-mtime'] != raw_mtime: ds = None else: ds = None # refresh cache if ds is None: self._log.debug("Extracting events for %s %s %s", self.get('raw'), subject, self.get('recording')) raw = self.load_raw(add_bads) ds = load.fiff.events(raw) del ds.info['raw'] ds.info['sfreq'] = raw.info['sfreq'] ds.info['raw-mtime'] = raw_mtime # add edf if self.has_edf[subject]: edf = self.load_edf() edf.add_t_to(ds) ds.info['edf'] = edf save.pickle(ds, evt_file) if data_raw: ds.info['raw'] = raw elif data_raw: ds.info['raw'] = self.load_raw(add_bads) ds.info['subject'] = subject ds.info['session'] = self.get('session') if len(self._visits) > 1: ds.info['visit'] = self.get('visit') if self.trigger_shift: if isinstance(self.trigger_shift, dict): trigger_shift = self.trigger_shift[subject] else: trigger_shift = self.trigger_shift if trigger_shift: ds['i_start'] += int(round(trigger_shift * ds.info['sfreq'])) return self._label_events(ds) def load_evoked(self, subjects=None, baseline=False, ndvar=True, cat=None, decim=None, data_raw=False, vardef=None, data='sensor', **kwargs): """ Load a Dataset with the evoked responses for each subject. Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). baseline : bool | tuple Apply baseline correction using this period. True to use the epoch's baseline specification. The default is to not apply baseline correction. ndvar : bool Convert the mne Evoked objects to an NDVar (the name in the Dataset is 'meg' or 'eeg'). cat : sequence of cell-names Only load data for these cells (cells of model). decim : int Data decimation factor (the default is the factor specified in the epoch definition). data_raw : bool Keep the :class:`mne.io.Raw` instance in ``ds.info['raw']`` (default False). vardef : str Name of a test defining additional variables. data : str Data to load; 'sensor' to load all sensor data (default); 'sensor.rms' to return RMS over sensors. Only applies to NDVar output. ... Applicable :ref:`state-parameters`: - :ref:`state-raw`: preprocessing pipeline - :ref:`state-epoch`: which events to use and time window - :ref:`state-rej`: which trials to use - :ref:`state-model`: how to group trials into conditions - :ref:`state-equalize_evoked_count`: control number of trials per cell """ subject, group = self._process_subject_arg(subjects, kwargs) epoch_name = self.get('epoch') epoch = self._epochs[epoch_name] data = TestDims.coerce(data) if not data.sensor: raise ValueError(f"data={data.string!r}; load_evoked is for loading sensor data") elif data.sensor is not True and not ndvar: raise ValueError(f"data={data.string!r} with ndvar=False") if baseline is True: baseline = epoch.baseline model = self.get('model') if group is not None: # when aggregating across sensors, do it before combining subjects # to avoid losing sensors that are not shared individual_ndvar = isinstance(data.sensor, str) desc = f'by {model}' if model else 'average' dss = [self.load_evoked(None, baseline, individual_ndvar, cat, decim, data_raw, vardef, data) for _ in self.iter(group=group, progress_bar=f"Load {epoch_name} {desc}")] if individual_ndvar: ndvar = False elif ndvar: # set interpolated channels to good for ds in dss: for e in ds['evoked']: if e.info['description'] is None: continue m = re.match(r"Eelbrain (\d+)", e.info['description']) if not m: continue v = int(m.group(1)) if v >= 11: e.info['bads'] = [] ds = combine(dss, incomplete='drop') # check consistency in MNE objects' number of time points lens = [len(e.times) for e in ds['evoked']] ulens = set(lens) if len(ulens) > 1: err = ["Unequal time axis sampling (len):"] alens = np.array(lens) for l in ulens: err.append('%i: %r' % (l, ds['subject', alens == l].cells)) raise DimensionMismatchError('\n'.join(err)) else: # single subject ds = self._make_evoked(decim, data_raw) if cat: if not model: raise TypeError(f"cat={cat!r}: Can't set cat when model is ''") model = ds.eval(model) idx = model.isin(cat) ds = ds.sub(idx) if ds.n_cases == 0: raise RuntimeError(f"Selection with cat={cat!r} resulted in empty Dataset") self._add_vars(ds, vardef) # baseline correction if isinstance(baseline, str): raise NotImplementedError elif baseline and not epoch.post_baseline_trigger_shift: for e in ds['evoked']: rescale(e.data, e.times, baseline, 'mean', copy=False) # convert to NDVar if ndvar: pipe = self._raw[self.get('raw')] info = ds[0, 'evoked'].info for data_kind in data.data_to_ndvar(info): sysname = pipe.get_sysname(info, subject, data_kind) connectivity = pipe.get_connectivity(data_kind) name = 'meg' if data_kind == 'mag' else data_kind ds[name] = load.fiff.evoked_ndvar(ds['evoked'], data=data_kind, sysname=sysname, connectivity=connectivity) if data_kind != 'eog' and isinstance(data.sensor, str): ds[name] = getattr(ds[name], data.sensor)('sensor') # if ndvar != 'both': # del ds['evoked'] return ds def load_epochs_stf(self, subjects=None, baseline=True, mask=True, morph=False, keep_stc=False, **state): """Load frequency space single trial data Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). baseline : bool | tuple Apply baseline correction using this period in sensor space. True to use the epoch's baseline specification. The default is True. mask : bool | str Discard data that is labelled 'unknown' by the parcellation (only applies to NDVars, default True). morph : bool Morph the source estimates to the common_brain (default False). keep_stc : bool Keep the source timecourse data in the Dataset that is returned (default False). ... State parameters. """ ds = self.load_epochs_stc(subjects, baseline, ndvar=True, morph=morph, mask=mask, **state) name = 'srcm' if morph else 'src' # apply morlet transformation freq_params = self.freqs[self.get('freq')] freq_range = freq_params['frequencies'] ds['stf'] = cwt_morlet(ds[name], freq_range, use_fft=True, n_cycles=freq_params['n_cycles'], zero_mean=False, out='magnitude') if not keep_stc: del ds[name] return ds def load_evoked_stf(self, subjects=None, baseline=True, mask=True, morph=False, keep_stc=False, **state): """Load frequency space evoked data Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). baseline : bool | tuple Apply baseline correction using this period in sensor space. True to use the epoch's baseline specification. The default is True. mask : bool | str Whether to just load the sources from the parcellation that are not defined as "unknown". Default is True. morph : bool Morph the source estimates to the common_brain (default False). keep_stc : bool Keep the source timecourse data in the Dataset that is returned (default False). ... State parameters. """ ds = self.load_evoked_stc(subjects, baseline, morph=morph, mask=mask, **state) name = 'srcm' if morph else 'src' # apply morlet transformation freq_params = self.freqs[self.get('freq')] freq_range = freq_params['frequencies'] ds['stf'] = cwt_morlet(ds[name], freq_range, use_fft=True, n_cycles=freq_params['n_cycles'], zero_mean=False, out='magnitude') if not keep_stc: del ds[name] return ds def load_evoked_stc(self, subjects=None, baseline=True, src_baseline=False, cat=None, keep_evoked=False, morph=False, mask=False, data_raw=False, vardef=None, decim=None, ndvar=True, **state): """Load evoked source estimates. Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). baseline : bool | tuple Apply baseline correction using this period in sensor space. True to use the epoch's baseline specification. The default is True. src_baseline : bool | tuple Apply baseline correction using this period in source space. True to use the epoch's baseline specification. The default is to not apply baseline correction. cat : sequence of cell-names Only load data for these cells (cells of model). keep_evoked : bool Keep the sensor space data in the Dataset that is returned (default False). morph : bool Morph the source estimates to the common_brain (default False). mask : bool | str Discard data that is labelled 'unknown' by the parcellation (only applies to NDVars, default False). Can be set to a parcellation name or ``True`` to use the current parcellation. data_raw : bool Keep the :class:`mne.io.Raw` instance in ``ds.info['raw']`` (default False). vardef : str Name of a test defining additional variables. decim : int Override the epoch decim factor. ndvar : bool Add the source estimates as NDVar named "src" instead of a list of :class:`mne.SourceEstimate` objects named "stc" (default True). ... Applicable :ref:`state-parameters`: - :ref:`state-raw`: preprocessing pipeline - :ref:`state-epoch`: which events to use and time window - :ref:`state-rej`: which trials to use - :ref:`state-model`: how to group trials into conditions - :ref:`state-equalize_evoked_count`: control number of trials per cell - :ref:`state-cov`: covariance matrix for inverse solution - :ref:`state-src`: source space - :ref:`state-inv`: inverse solution """ if isinstance(mask, str): state['parc'] = mask # load sensor data (needs state in case it has 'group' entry) sns_ndvar = keep_evoked and ndvar ds = self.load_evoked(subjects, baseline, sns_ndvar, cat, decim, data_raw, vardef, **state) # check baseline epoch = self._epochs[self.get('epoch')] if src_baseline and epoch.post_baseline_trigger_shift: raise NotImplementedError(f"src_baseline={src_baseline!r}: post_baseline_trigger_shift is not implemented for baseline correction in source space") elif src_baseline is True: src_baseline = epoch.baseline # MRI subjects common_brain = self.get('common_brain') meg_subjects = ds['subject'].cells from_subjects = {} # for the purpose of morphing mri_subjects = {} # for representing for subject in meg_subjects: mri_subjects[subject] = self.get('mrisubject', subject=subject) if is_fake_mri(self.get('mri-dir')): from_subjects[subject] = common_brain else: from_subjects[subject] = mri_subjects[subject] # make sure annot files are available (needed only for NDVar) if ndvar: if morph: self.make_annot(mrisubject=common_brain) elif len(meg_subjects) > 1: raise ValueError(f"ndvar=True, morph=False with multiple subjects: Can't create ndvars with data from different brains") else: self.make_annot(mrisubject=mri_subjects[meg_subjects[0]]) # convert evoked objects stcs = [] invs = {} mm_cache = CacheDict(self.load_morph_matrix, 'mrisubject') for subject, evoked in tqdm(ds.zip('subject', 'evoked'), "Localize", ds.n_cases): # get inv if subject in invs: inv = invs[subject] else: inv = invs[subject] = self.load_inv(evoked, subject=subject) # apply inv stc = apply_inverse(evoked, inv, **self._params['apply_inv_kw']) # baseline correction if src_baseline: rescale(stc._data, stc.times, src_baseline, 'mean', copy=False) if morph: subject_from = from_subjects[subject] if subject_from == common_brain: stc.subject = common_brain else: mm, v_to = mm_cache[subject_from] stc = mne.morph_data_precomputed(subject_from, common_brain, stc, v_to, mm) stcs.append(stc) # add to Dataset if ndvar: if morph: key, subject = 'srcm', common_brain else: key, subject = 'src', mri_subjects[meg_subjects[0]] src = self.get('src') mri_sdir = self.get('mri-sdir') method = self._params['apply_inv_kw']['method'] fixed = self._params['make_inv_kw'].get('fixed', False) parc = self.get('parc') or None ds[key] = load.fiff.stc_ndvar(stcs, subject, src, mri_sdir, method, fixed, parc=parc, connectivity=self.get('connectivity')) if mask: _mask_ndvar(ds, key) else: key = 'stcm' if morph else 'stc' ds[key] = stcs if not keep_evoked: del ds['evoked'] return ds def load_fwd(self, surf_ori=True, ndvar=False, mask=None, **state): """Load the forward solution Parameters ---------- surf_ori : bool Force surface orientation (default True; only applies if ``ndvar=False``, :class:`NDVar` forward operators are alsways surface based). ndvar : bool Return forward solution as :class:`NDVar` (default is :class:`mne.forward.Forward`). mask : str | bool Remove source labelled "unknown". Can be parcellation name or True, in which case the current parcellation is used. ... State parameters. Returns ------- forward_operator : mne.forward.Forward | NDVar Forward operator. """ if mask and not ndvar: raise NotImplementedError("mask is only implemented for ndvar=True") elif isinstance(mask, str): state['parc'] = mask mask = True fwd_file = self.get('fwd-file', make=True, **state) src = self.get('src') if ndvar: if src.startswith('vol'): parc = None assert mask is None else: self.make_annot() parc = self.get('parc') fwd = load.fiff.forward_operator(fwd_file, src, self.get('mri-sdir'), parc) if mask: fwd = fwd.sub(source=np.invert( fwd.source.parc.startswith('unknown'))) return fwd else: fwd = mne.read_forward_solution(fwd_file) if surf_ori: mne.convert_forward_solution(fwd, surf_ori, copy=False) return fwd def load_ica(self, **state): """Load the mne-python ICA object Returns ------- ica : mne.preprocessing.ICA ICA object for the current raw/rej setting. ... State parameters. """ path = self.make_ica(**state) return mne.preprocessing.read_ica(path) def load_inv(self, fiff=None, ndvar=False, mask=None, **state): """Load the inverse operator Parameters ---------- fiff : Raw | Epochs | Evoked | ... Object which provides the mne info dictionary (default: load the raw file). ndvar : bool Return the inverse operator as NDVar (default is :class:`mne.minimum_norm.InverseOperator`). The NDVar representation does not take into account any direction selectivity (loose/free orientation) or noise normalization properties. mask : str | bool Remove source labelled "unknown". Can be parcellation name or True, in which case the current parcellation is used. ... Applicable :ref:`state-parameters`: - :ref:`state-raw`: preprocessing pipeline - :ref:`state-rej`: which trials to use - :ref:`state-cov`: covariance matrix for inverse solution - :ref:`state-src`: source space - :ref:`state-inv`: inverse solution """ if mask and not ndvar: raise NotImplementedError("mask is only implemented for ndvar=True") elif isinstance(mask, str): state['parc'] = mask mask = True if state: self.set(**state) inv = dst = None if self.cache_inv: subject = self.get('subject') fwd_recording = self._get_fwd_recording(subject) with self._temporary_state: dst = self.get('inv-file', mkdir=True, recording=fwd_recording) if exists(dst) and cache_valid(getmtime(dst), self._inv_mtime(fwd_recording)): inv = mne.minimum_norm.read_inverse_operator(dst) if inv is None: src = self.get('src') if src[:3] == 'vol': inv = self.get('inv') if not (inv.startswith('vec') or inv.startswith('free')): raise ValueError(f'inv={inv!r} with src={src!r}: volume source space requires free or vector inverse') if fiff is None: fiff = self.load_raw() inv = make_inverse_operator(fiff.info, self.load_fwd(), self.load_cov(), use_cps=True, **self._params['make_inv_kw']) if dst: mne.minimum_norm.write_inverse_operator(dst, inv) if ndvar: inv = load.fiff.inverse_operator(inv, self.get('src'), self.get('mri-sdir'), self.get('parc')) if mask: inv = inv.sub(source=~inv.source.parc.startswith('unknown')) return inv def load_label(self, label, **kwargs): """Retrieve a label as mne Label object Parameters ---------- label : str Name of the label. If the label name does not end in '-bh' or '-rh' the combination of the labels ``label + '-lh'`` and ``label + '-rh'`` is returned. ... State parameters. """ labels = self._load_labels(label, **kwargs) if label in labels: return labels[label] elif not label.endswith(('-lh', '-rh')): return labels[label + '-lh'] + labels[label + '-rh'] else: raise ValueError("Label %r could not be found in parc %r." % (label, self.get('parc'))) def _load_labels(self, regexp=None, **kwargs): """Load labels from an annotation file.""" self.make_annot(**kwargs) mri_sdir = self.get('mri-sdir') labels = mne.read_labels_from_annot(self.get('mrisubject'), self.get('parc'), regexp=regexp, subjects_dir=mri_sdir) return {l.name: l for l in labels} def load_morph_matrix(self, **state): """Load the morph matrix from mrisubject to common_brain Parameters ---------- ... State parameters. Returns ------- mm : sparse matrix Morph matrix. vertices_to : list of 2 array Vertices of the morphed data. """ subjects_dir = self.get('mri-sdir', **state) subject_to = self.get('common_brain') subject_from = self.get('mrisubject') src_to = self.load_src(mrisubject=subject_to, match=False) src_from = self.load_src(mrisubject=subject_from, match=False) vertices_to = [src_to[0]['vertno'], src_to[1]['vertno']] vertices_from = [src_from[0]['vertno'], src_from[1]['vertno']] mm = mne.compute_morph_matrix(subject_from, subject_to, vertices_from, vertices_to, None, subjects_dir) return mm, vertices_to def load_neighbor_correlation(self, subjects=None, epoch=None, **state): """Load sensor neighbor correlation Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). epoch : str Epoch to use for computing neighbor-correlation (by default, the whole session is used). Returns ------- nc : NDVar | Dataset Sensor neighbor-correlation as :class:`NDVar` for a single subject or as :class:`Dataset` for multiple subjects. """ subject, group = self._process_subject_arg(subjects, state) if group is not None: if state: self.set(**state) lines = [(subject, self.load_neighbor_correlation(1, epoch)) for subject in self] return Dataset.from_caselist(['subject', 'nc'], lines) if epoch: if epoch is True: epoch = self.get('epoch') epoch_params = self._epochs[epoch] if len(epoch_params.sessions) != 1: raise ValueError(f"epoch={epoch!r}: epoch has multiple session") ds = self.load_epochs(epoch=epoch, reject=False, decim=1, **state) data = concatenate(ds['meg']) else: data = self.load_raw(ndvar=True, **state) return neighbor_correlation(data) def load_raw(self, add_bads=True, preload=False, ndvar=False, decim=1, **kwargs): """ Load a raw file as mne Raw object. Parameters ---------- add_bads : bool | list Add bad channel information to the bad channels text file (default True). preload : bool Load raw data into memory (default False; see :func:`mne.io.read_raw_fif` parameter). ndvar : bool Load as NDVar instead of mne Raw object (default False). decim : int Decimate data (default 1, i.e. no decimation; value other than 1 implies ``preload=True``) ... Applicable :ref:`state-parameters`: - :ref:`state-session`: from which session to load raw data - :ref:`state-raw`: preprocessing pipeline Notes ----- Bad channels defined in the raw file itself are ignored in favor of the bad channels in the bad channels file. """ pipe = self._raw[self.get('raw', **kwargs)] if decim > 1: preload = True raw = pipe.load(self.get('subject'), self.get('recording'), add_bads, preload) if decim > 1: if ndvar: # avoid warning for downsampling event channel stim_picks = np.empty(0) events = np.empty((0, 3)) else: stim_picks = events = None sfreq = int(round(raw.info['sfreq'] / decim)) raw.resample(sfreq, stim_picks=stim_picks, events=events) if ndvar: data = TestDims('sensor') data_kind = data.data_to_ndvar(raw.info)[0] sysname = pipe.get_sysname(raw.info, self.get('subject'), data_kind) connectivity = pipe.get_connectivity(data_kind) raw = load.fiff.raw_ndvar(raw, sysname=sysname, connectivity=connectivity) return raw def _load_result_plotter(self, test, tstart, tstop, pmin, parc=None, mask=None, samples=10000, data='source', baseline=True, src_baseline=None, colors=None, labels=None, h=1.2, rc=None, dst=None, vec_fmt='svg', pix_fmt='png', **kwargs): """Load cluster-based test result plotter Parameters ---------- test : str Name of the test. tstart, tstop, pmin, parc, mask, samples, data, baseline, src_baseline Test parameters. colors : dict Colors for data cells as ``{cell: matplotlib_color}`` dictionary. labels : dict Labels for data in a ``{cell: label}`` dictionary (the default is to use cell names). h : scalar Plot height in inches (default 1.1). rc : dict Matplotlib rc-parameters dictionary (the default is optimized for the default plot size ``h=1.1``). dst : str Directory in which to place results (default is the ``result plots`` directory). vec_fmt : str Format for vector graphics (default 'pdf'). pix_fmt : str Format for pixel graphics (default 'png'). ... State parameters. """ if not isinstance(self._tests[test], EvokedTest): raise NotImplementedError("Result-plots for %s" % self._tests[test].__class__.__name__) elif data != 'source': raise NotImplementedError("data=%s" % repr(data)) elif not isinstance(pmin, float): raise NotImplementedError("Threshold-free tests") from .._result_plots import ClusterPlotter # calls _set_analysis_options(): ds, res = self.load_test(test, tstart, tstop, pmin, parc, mask, samples, data, baseline, src_baseline, True, **kwargs) if dst is None: dst = self.get('res-plot-dir', mkdir=True) return ClusterPlotter(ds, res, colors, dst, vec_fmt, pix_fmt, labels, h, rc) def load_selected_events(self, subjects=None, reject=True, add_bads=True, index=True, data_raw=False, vardef=None, cat=None, **kwargs): """ Load events and return a subset based on epoch and rejection Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). reject : bool | 'keep' Reject bad trials. If ``True`` (default), bad trials are removed from the Dataset. Set to ``False`` to ignore the trial rejection. Set ``reject='keep'`` to load the rejection (added it to the events as ``'accept'`` variable), but keep bad trails. add_bads : False | True | list Add bad channel information to the Raw. If True, bad channel information is retrieved from the bad channels file. Alternatively, a list of bad channels can be specified. index : bool | str Index the Dataset before rejection (provide index name as str). data_raw : bool Keep the :class:`mne.io.Raw` instance in ``ds.info['raw']`` (default False). vardef : str Name of a test defining additional variables. cat : sequence of cell-names Only load data for these cells (cells of model). ... State parameters. Notes ----- When trial rejection is set to automatic, not rejection is performed because no epochs are loaded. """ # process arguments if reject not in (True, False, 'keep'): raise ValueError(f"reject={reject!r}") if index is True: index = 'index' elif index and not isinstance(index, str): raise TypeError(f"index={index!r}") # case of loading events for a group subject, group = self._process_subject_arg(subjects, kwargs) if group is not None: if data_raw: raise ValueError(f"data_var={data_raw!r}: can't keep raw when combining subjects") dss = [self.load_selected_events(reject=reject, add_bads=add_bads, index=index, vardef=vardef) for _ in self.iter(group=group)] ds = combine(dss) return ds epoch = self._epochs[self.get('epoch')] if isinstance(epoch, EpochCollection): raise ValueError(f"epoch={self.get("epoch")!r}; can't load events for collection epoch") # rejection comes from somewhere else if isinstance(epoch, SuperEpoch): with self._temporary_state: dss = [] raw = None # find bad channels if isinstance(add_bads, Sequence): bad_channels = list(add_bads) elif add_bads: bad_channels = sorted(set.union(*( set(self.load_bad_channels(session=session)) for session in epoch.sessions))) else: bad_channels = [] # load events for session in epoch.sessions: self.set(session=session) # load events for this session session_dss = [] for sub_epoch in epoch.sub_epochs: if self._epochs[sub_epoch].session != session: continue ds = self.load_selected_events(subject, reject, add_bads, index, True, epoch=sub_epoch) ds[:, 'epoch'] = sub_epoch session_dss.append(ds) ds = combine(session_dss) dss.append(ds) # combine raw raw_ = session_dss[0].info['raw'] raw_.info['bads'] = bad_channels if raw is None: raw = raw_ else: ds['i_start'] += raw.last_samp + 1 - raw_.first_samp raw.append(raw_) # combine bad channels ds = combine(dss) if data_raw: ds.info['raw'] = raw ds.info[BAD_CHANNELS] = bad_channels elif isinstance(epoch, SecondaryEpoch): with self._temporary_state: ds = self.load_selected_events(None, 'keep' if reject else False, add_bads, index, data_raw, epoch=epoch.sel_epoch) if epoch.sel: ds = ds.sub(epoch.sel) if index: ds.index(index) if reject is True: if self._artifact_rejection[self.get('rej')]['kind'] is not None: ds = ds.sub('accept') else: rej_params = self._artifact_rejection[self.get('rej')] # load files with self._temporary_state: ds = self.load_events(add_bads=add_bads, data_raw=data_raw, session=epoch.session) if reject and rej_params['kind'] is not None: rej_file = self.get('rej-file') if exists(rej_file): ds_sel = load.unpickle(rej_file) else: rej_file = self._get_rel('rej-file', 'root') raise FileMissing(f"The rejection file at {rej_file} does not exist. Run .make_epoch_selection() first.") else: ds_sel = None # primary event selection if epoch.sel: ds = ds.sub(epoch.sel) if index: ds.index(index) if epoch.n_cases is not None and ds.n_cases != epoch.n_cases: raise RuntimeError(f"Number of epochs {ds.n_cases}, expected {epoch.n_cases}") # rejection if ds_sel is not None: # check file if not np.all(ds['trigger'] == ds_sel['trigger']): # TODO: this warning should be given in make_epoch_selection already if np.all(ds[:-1, 'trigger'] == ds_sel['trigger']): ds = ds[:-1] self._log.warning(self.format("Last epoch for {subject} is missing")) elif np.all(ds[1:, 'trigger'] == ds_sel['trigger']): ds = ds[1:] self._log.warning(self.format("First epoch for {subject} is missing")) else: raise RuntimeError(f"The epoch selection file contains different events (trigger IDs) from the epoch data loaded from the raw file. If the events included in the epoch were changed intentionally, delete the corresponding epoch rejection file and redo epoch rejection: {rej_file}") if rej_params['interpolation']: ds.info[INTERPOLATE_CHANNELS] = True if INTERPOLATE_CHANNELS in ds_sel: ds[INTERPOLATE_CHANNELS] = ds_sel[INTERPOLATE_CHANNELS] else: ds[INTERPOLATE_CHANNELS] = Datalist([[]] * ds.n_cases, INTERPOLATE_CHANNELS, 'strlist') else: ds.info[INTERPOLATE_CHANNELS] = False # subset events if reject == 'keep': ds['accept'] = ds_sel['accept'] elif reject is True: ds = ds.sub(ds_sel['accept']) else: raise RuntimeError("reject=%s" % repr(reject)) # bad channels if add_bads: if BAD_CHANNELS in ds_sel.info: ds.info[BAD_CHANNELS] = ds_sel.info[BAD_CHANNELS] else: ds.info[BAD_CHANNELS] = [] else: # no artifact rejection ds.info[INTERPOLATE_CHANNELS] = False ds.info[BAD_CHANNELS] = [] # apply trigger-shift if epoch.trigger_shift: shift = epoch.trigger_shift if isinstance(shift, str): shift = ds.eval(shift) if isinstance(shift, Var): shift = shift.x if np.isscalar(shift): ds['i_start'] += int(round(shift * ds.info['sfreq'])) else: ds['i_start'] += np.round(shift * ds.info['sfreq']).astype(int) # Additional variables self._add_vars(ds, epoch.vars) self._add_vars(ds, vardef) # apply cat subset if cat: model = ds.eval(self.get('model')) idx = model.isin(cat) ds = ds.sub(idx) return ds def _load_spm(self, baseline=True, src_baseline=False): "Load LM" subject = self.get('subject') test = self.get('test') test_obj = self._tests[test] if not isinstance(test_obj, TwoStageTest): raise NotImplementedError("Test kind %r" % test_obj.__class__.__name__) ds = self.load_epochs_stc(subject, baseline, src_baseline, mask=True, vardef=test_obj.vars) return testnd.LM('src', test_obj.stage_1, ds, subject=subject) def load_src(self, add_geom=False, ndvar=False, **state): """Load the current source space Parameters ---------- add_geom : bool Parameter for :func:`mne.read_source_spaces`. ndvar : bool Return as NDVar Dimension object (default False). ... State parameters. """ fpath = self.get('src-file', make=True, **state) if ndvar: src = self.get('src') if src.startswith('vol'): return VolumeSourceSpace.from_file( self.get('mri-sdir'), self.get('mrisubject'), src) return SourceSpace.from_file( self.get('mri-sdir'), self.get('mrisubject'), src, self.get('parc')) return mne.read_source_spaces(fpath, add_geom) def load_test(self, test, tstart=None, tstop=None, pmin=None, parc=None, mask=None, samples=10000, data='source', baseline=True, src_baseline=None, return_data=False, make=False, **state): """Create and load spatio-temporal cluster test results Parameters ---------- test : None | str Test for which to create a report (entry in MneExperiment.tests; None to use the test that was specified most recently). tstart : scalar Beginning of the time window for the test in seconds (default is the beginning of the epoch). tstop : scalar End of the time window for the test in seconds (default is the end of the epoch). pmin : float | 'tfce' | None Kind of test. parc : None | str Parcellation for which to collect distribution. mask : None | str Mask whole brain. samples : int Number of random permutations of the data used to determine cluster p values (default 10'000). data : str Data to test, for example: - ``'sensor'`` spatio-temporal test in sensor space. - ``'source'`` spatio-temporal test in source space. - ``'source.mean'`` ROI mean time course. - ``'sensor.rms'`` RMS across sensors. baseline : bool | tuple Apply baseline correction using this period in sensor space. True to use the epoch's baseline specification (default). src_baseline : bool | tuple Apply baseline correction using this period in source space. True to use the epoch's baseline specification. The default is to not apply baseline correction. return_data : bool Return the data along with the test result (see below). .. Warning:: Single trial data (i.e., two-stage tests) take up a lot of memory and it might not be possible to load all data at once. Instead, loop through subjects and collect summary statistics. make : bool If the target file does not exist, create it (could take a long time depending on the test; if False, raise an IOError). ... State parameters (Use the ``group`` state parameter to select the subject group for which to perform the test). Returns ------- ds : Dataset (if return_data==True) Data that forms the basis of the test. res : NDTest | ROITestResult Test result for the specified test (when performing tests in ROIs, an :class:`~_experiment.ROITestResult` object is returned). """ self.set(test=test, **state) data = TestDims.coerce(data, morph=True) self._set_analysis_options(data, baseline, src_baseline, pmin, tstart, tstop, parc, mask) return self._load_test(test, tstart, tstop, pmin, parc, mask, samples, data, baseline, src_baseline, return_data, make) def _load_test(self, test, tstart, tstop, pmin, parc, mask, samples, data, baseline, src_baseline, return_data, make): "Load a cached test after _set_analysis_options() has been called" test_obj = self._tests[test] dst = self.get('test-file', mkdir=True) # try to load cached test res = None desc = self._get_rel('test-file', 'test-dir') if self._result_file_mtime(dst, data): try: res = load.unpickle(dst) if data.source is True: update_subjects_dir(res, self.get('mri-sdir'), 2) except OldVersionError: res = None else: if res.samples >= samples or res.samples == -1: self._log.info("Load cached test: %s", desc) if not return_data: return res elif not make: raise IOError("The requested test %s is cached with " "samples=%i, but you request samples=%i; Set " "make=True to perform the test." % (desc, res.samples, samples)) else: res = None elif not make and exists(dst): raise IOError("The requested test is outdated: %s. Set make=True " "to perform the test." % desc) if res is None and not make: raise IOError("The requested test is not cached: %s. Set make=True " "to perform the test." % desc) # parc/mask parc_dim = None if data.source is True: if parc: mask = True parc_dim = 'source' elif mask: if pmin is None: # can as well collect dist for parc parc_dim = 'source' elif isinstance(data.source, str): if not isinstance(parc, str): raise TypeError(f"parc needs to be set for ROI test (data={data.string!r})") elif mask is not None: raise TypeError(f"mask={mask!r}: invalid for data={data.string!r}") elif parc is not None: raise TypeError(f"parc={parc!r}: invalid for data={data.string!r}") elif mask is not None: raise TypeError(f"mask={mask!r}: invalid for data={data.string!r}") do_test = res is None if do_test: test_kwargs = self._test_kwargs(samples, pmin, tstart, tstop, data, parc_dim) else: test_kwargs = None if isinstance(test_obj, TwoStageTest): if isinstance(data.source, str): res_data, res = self._make_test_rois_2stage(baseline, src_baseline, test_obj, samples, test_kwargs, res, data, return_data) elif data.source is True: res_data, res = self._make_test_2stage(baseline, src_baseline, mask, test_obj, test_kwargs, res, data, return_data) else: raise NotImplementedError(f"Two-stage test with data={data.string!r}") elif isinstance(data.source, str): res_data, res = self._make_test_rois(baseline, src_baseline, test_obj, samples, pmin, test_kwargs, res, data) else: if data.sensor: res_data = self.load_evoked(True, baseline, True, test_obj._within_cat, data=data, vardef=test_obj.vars) elif data.source: res_data = self.load_evoked_stc(True, baseline, src_baseline, morph=True, cat=test_obj._within_cat, mask=mask, vardef=test_obj.vars) else: raise ValueError(f"data={data.string!r}") if do_test: self._log.info("Make test: %s", desc) res = self._make_test(data.y_name, res_data, test_obj, test_kwargs) if do_test: save.pickle(res, dst) if return_data: return res_data, res else: return res @staticmethod def _src_to_label_tc(ds, func): src = ds.pop('src') out = {} for label in src.source.parc.cells: if label.startswith('unknown-'): continue label_ds = ds.copy() label_ds['label_tc'] = getattr(src, func)(source=label) out[label] = label_ds return out def _make_test_rois(self, baseline, src_baseline, test_obj, samples, pmin, test_kwargs, res, data): # load data dss_list = [] n_trials_dss = [] labels = set() subjects = self.get_field_values('subject') for _ in self.iter(progress_bar="Loading data"): ds = self.load_evoked_stc(1, baseline, src_baseline, vardef=test_obj.vars) dss = self._src_to_label_tc(ds, data.source) n_trials_dss.append(ds) dss_list.append(dss) labels.update(dss.keys()) label_dss = {label: [dss[label] for dss in dss_list if label in dss] for label in labels} label_data = {label: combine(dss, incomplete='drop') for label, dss in label_dss.items()} if res is not None: return label_data, res n_trials_ds = combine(n_trials_dss, incomplete='drop') # n subjects per label n_per_label = {label: len(dss) for label, dss in label_dss.items()} # compute results do_mcc = ( len(labels) > 1 and # more than one ROI pmin not in (None, 'tfce') and # not implemented len(set(n_per_label.values())) == 1 # equal n permutations ) label_results = { label: self._make_test('label_tc', ds, test_obj, test_kwargs, do_mcc) for label, ds in label_data.items() } if do_mcc: cdists = [res._cdist for res in label_results.values()] merged_dist = _MergedTemporalClusterDist(cdists) else: merged_dist = None res = ROITestResult(subjects, samples, n_trials_ds, merged_dist, label_results) return label_data, res def _make_test_rois_2stage(self, baseline, src_baseline, test_obj, samples, test_kwargs, res, data, return_data): # stage 1 lms = [] res_data = [] n_trials_dss = [] subjects = self.get_field_values('subject') for subject in self.iter(progress_bar="Loading stage 1 models"): if test_obj.model is None: ds = self.load_epochs_stc(1, baseline, src_baseline, mask=True, vardef=test_obj.vars) else: ds = self.load_evoked_stc(1, baseline, src_baseline, mask=True, vardef=test_obj.vars, model=test_obj._within_model) dss = self._src_to_label_tc(ds, data.source) if res is None: lms.append({label: test_obj.make_stage_1('label_tc', ds, subject) for label, ds in dss.items()}) n_trials_dss.append(ds) if return_data: res_data.append(dss) # stage 2 if res is None: labels = set(chain.from_iterable(lms)) ress = {} for label in sorted(labels): label_lms = [subject_lms[label] for subject_lms in lms if label in subject_lms] if len(label_lms) <= 2: continue ress[label] = test_obj.make_stage_2(label_lms, test_kwargs) n_trials_ds = combine(n_trials_dss, incomplete='drop') res = ROI2StageResult(subjects, samples, n_trials_ds, None, ress) if return_data: data_out = {} for label in res.keys(): label_data = [subject_data[label] for subject_data in res_data if label in subject_data] data_out[label] = combine(label_data) else: data_out = None return data_out, res def _make_test_2stage(self, baseline, src_baseline, mask, test_obj, test_kwargs, res, data, return_data): # stage 1 lms = [] res_data = [] for subject in self.iter(progress_bar="Loading stage 1 models"): if test_obj.model is None: ds = self.load_epochs_stc(1, baseline, src_baseline, morph=True, mask=mask, vardef=test_obj.vars) else: ds = self.load_evoked_stc(1, baseline, src_baseline, morph=True, mask=mask, vardef=test_obj.vars, model=test_obj._within_model) if res is None: lms.append(test_obj.make_stage_1(data.y_name, ds, subject)) if return_data: res_data.append(ds) # stage 2 if res is None: res = test_obj.make_stage_2(lms, test_kwargs) if return_data: res_data = combine(res_data) return res_data, res def make_annot(self, redo=False, **state): """Make sure the annot files for both hemispheres exist Parameters ---------- redo : bool Even if the file exists, recreate it (default False). ... State parameters. Returns ------- mtime : float | None Modification time of the existing files, or None if they were newly created. """ self.set(**state) # variables parc, p = self._get_parc() if p is None: return mrisubject = self.get('mrisubject') common_brain = self.get('common_brain') mtime = self._annot_file_mtime() if mrisubject != common_brain: is_fake = is_fake_mri(self.get('mri-dir')) if p.morph_from_fsaverage or is_fake: # make sure annot exists for common brain self.set(mrisubject=common_brain, match=False) common_brain_mtime = self.make_annot() self.set(mrisubject=mrisubject, match=False) if not redo and cache_valid(mtime, common_brain_mtime): return mtime elif is_fake: for _ in self.iter('hemi'): self.make_copy('annot-file', 'mrisubject', common_brain, mrisubject) else: self.get('label-dir', make=True) subjects_dir = self.get('mri-sdir') for hemi in ('lh', 'rh'): cmd = ["mri_surf2surf", "--srcsubject", common_brain, "--trgsubject", mrisubject, "--sval-annot", parc, "--tval", parc, "--hemi", hemi] subp.run_freesurfer_command(cmd, subjects_dir) fix_annot_names(mrisubject, parc, common_brain, subjects_dir=subjects_dir) return if not redo and mtime: return mtime elif not p.make: if redo and mtime: raise RuntimeError( f"The {parc} parcellation cannot be created automatically " f"for {mrisubject}. Please update the corresponding " f"*.annot files manually.") else: raise RuntimeError( f"The {parc} parcellation cannot be created automatically " f"and is missing for {mrisubject}. Please add the " f"corresponding *.annot files to the subject's label " f"directory.") # make parcs: common_brain | non-morphed labels = self._make_annot(parc, p, mrisubject) write_labels_to_annot(labels, mrisubject, parc, True, self.get('mri-sdir')) def _make_annot(self, parc, p, subject): """Return labels Notes ----- Only called to make custom annotation files for the common_brain """ subjects_dir = self.get('mri-sdir') if isinstance(p, CombinationParc): with self._temporary_state: base = {l.name: l for l in self.load_annot(parc=p.base)} labels = [] for name, exp in p.labels.items(): labels += combination_label(name, exp, base, subjects_dir) elif isinstance(p, SeededParc): if p.mask: with self._temporary_state: self.make_annot(parc=p.mask) name, extent = SEEDED_PARC_RE.match(parc).groups() labels = labels_from_mni_coords( p.seeds_for_subject(subject), float(extent), subject, p.surface, p.mask, subjects_dir, parc) elif isinstance(p, EelbrainParc) and p.name == 'lobes': if subject != 'fsaverage': raise RuntimeError("lobes parcellation can only be created for " "fsaverage, not for %s" % subject) # load source annot with self._temporary_state: labels = self.load_annot(parc='PALS_B12_Lobes') # sort labels labels = [l for l in labels if l.name[:-3] != 'MEDIAL.WALL'] # rename good labels rename_label(labels, 'LOBE.FRONTAL', 'frontal') rename_label(labels, 'LOBE.OCCIPITAL', 'occipital') rename_label(labels, 'LOBE.PARIETAL', 'parietal') rename_label(labels, 'LOBE.TEMPORAL', 'temporal') # reassign unwanted labels targets = ('frontal', 'occipital', 'parietal', 'temporal') dissolve_label(labels, 'LOBE.LIMBIC', targets, subjects_dir) dissolve_label(labels, 'GYRUS', targets, subjects_dir, 'rh') dissolve_label(labels, '???', targets, subjects_dir) dissolve_label(labels, '????', targets, subjects_dir, 'rh') dissolve_label(labels, '???????', targets, subjects_dir, 'rh') elif isinstance(p, LabelParc): labels = [] hemis = ('lh.', 'rh.') path = join(subjects_dir, subject, 'label', '%s.label') for label in p.labels: if label.startswith(hemis): labels.append(mne.read_label(path % label)) else: labels.extend(mne.read_label(path % (hemi + label)) for hemi in hemis) else: raise NotImplementedError( "At least one of the annot files for the custom parcellation " "%r is missing for %r, and a make function is not " "implemented." % (parc, subject)) return labels def make_bad_channels(self, bad_chs=(), redo=False, **kwargs): """Write the bad channel definition file for a raw file If the file already exists, new bad channels are added to the old ones. In order to replace the old file with only the new values, set ``redo=True``. Parameters ---------- bad_chs : iterator of str Names of the channels to set as bad. Numerical entries are interpreted as "MEG XXX". If bad_chs contains entries not present in the raw data, a ValueError is raised. redo : bool If the file already exists, replace it (instead of adding). ... State parameters. See Also -------- make_bad_channels_auto : find bad channels automatically load_bad_channels : load the current bad_channels file merge_bad_channels : merge bad channel definitions for all sessions """ pipe = self._raw[self.get('raw', **kwargs)] pipe.make_bad_channels(self.get('subject'), self.get('recording'), bad_chs, redo) def make_bad_channels_auto(self, flat=1e-14, redo=False, **state): """Automatically detect bad channels Works on ``raw='raw'`` Parameters ---------- flat : scalar Threshold for detecting flat channels: channels with ``std < flat`` are considered bad (default 1e-14). redo : bool If the file already exists, replace it (instead of adding). ... State parameters. """ if state: self.set(**state) pipe = self._raw['raw'] pipe.make_bad_channels_auto(self.get('subject'), self.get('recording'), flat, redo) def make_bad_channels_neighbor_correlation(self, r, epoch=None, **state): """Exclude bad channels based on low average neighbor-correlation Parameters ---------- r : scalar Minimum admissible neighbor correlation. Any channel whose average correlation with its neighbors is below this value is added to the list of bad channels (e.g., 0.3). epoch : str Epoch to use for computing neighbor-correlation (by default, the whole session is used). ... State parameters. Notes ----- Data is loaded for the currently specified ``raw`` setting, but bad channels apply to all ``raw`` settings equally. Hence, when using this method with multiple subjects, it is important to set ``raw`` to the same value. """ nc = self.load_neighbor_correlation(1, epoch, **state) bad_chs = nc.sensor.names[nc < r] if bad_chs: self.make_bad_channels(bad_chs) def make_besa_evt(self, redo=False, **state): """Make the trigger and event files needed for besa Parameters ---------- redo : bool If besa files already exist, overwrite them. ... State parameters. Notes ----- Ignores the *decim* epoch parameter. Target files are saved relative to the *besa-root* location. """ self.set(**state) rej = self.get('rej') trig_dest = self.get('besa-trig', rej='', mkdir=True) evt_dest = self.get('besa-evt', rej=rej, mkdir=True) if not redo and exists(evt_dest) and exists(trig_dest): return # load events ds = self.load_selected_events(reject='keep') # save triggers if redo or not exists(trig_dest): save.meg160_triggers(ds, trig_dest, pad=1) if not redo and exists(evt_dest): return else: ds.index('besa_index', 1) # reject bad trials ds = ds.sub('accept') # save evt epoch = self._epochs[self.get('epoch')] save.besa_evt(ds, tstart=epoch.tmin, tstop=epoch.tmax, dest=evt_dest) def make_copy(self, temp, field, src, dst, redo=False): """Make a copy of a file to a new path by substituting one field value Parameters ---------- temp : str Template of the file which to copy. field : str Field in which the source and target of the link are distinguished. src : str Value for field on the source file. dst : str Value for field on the destination filename. redo : bool If the target file already exists, overwrite it. See Also -------- copy : Copy muliple files to a different root directory """ dst_path = self.get(temp, mkdir=True, **{field: dst}) if not redo and exists(dst_path): return src_path = self.get(temp, **{field: src}) if isdir(src_path): raise ValueError("Can only copy files, not directories.") shutil.copyfile(src_path, dst_path) def make_cov(self): "Make a noise covariance (cov) file" dest = self.get('cov-file', mkdir=True) if exists(dest): mtime = self._cov_mtime() if mtime and getmtime(dest) > mtime: return self._log.debug("Make cov-file %s", dest) params = self._covs[self.get('cov')] method = params.get('method', 'empirical') keep_sample_mean = params.get('keep_sample_mean', True) reg = params.get('reg', None) if 'epoch' in params: with self._temporary_state: ds = self.load_epochs(None, True, False, decim=1, epoch=params['epoch']) epochs = ds['epochs'] cov = mne.compute_covariance(epochs, keep_sample_mean, method=method) info = epochs.info else: with self._temporary_state: raw = self.load_raw(session=params['session']) cov = mne.compute_raw_covariance(raw, method=method) info = raw.info epochs = None if reg is True: cov = mne.cov.regularize(cov, info, rank=None) elif isinstance(reg, dict): cov = mne.cov.regularize(cov, info, **reg) elif reg == 'best': if mne.pick_types(epochs.info, meg='grad', eeg=True, ref_meg=False).size: raise NotImplementedError("EEG or gradiometer sensors") elif epochs is None: raise NotImplementedError("reg='best' for raw covariance") reg_vs = np.arange(0, 0.21, 0.01) covs = [mne.cov.regularize(cov, epochs.info, mag=v, rank=None) for v in reg_vs] # compute whitened global field power evoked = epochs.average() picks = mne.pick_types(evoked.info, meg='mag', ref_meg=False) gfps = [mne.whiten_evoked(evoked, cov, picks).data.std(0) for cov in covs] # apply padding t_pad = params.get('reg_eval_win_pad', 0) if t_pad: n_pad = int(t_pad * epochs.info['sfreq']) if len(gfps[0]) <= 2 * n_pad: msg = "Covariance padding (%s) is bigger than epoch" % t_pad raise ValueError(msg) padding = slice(n_pad, -n_pad) gfps = [gfp[padding] for gfp in gfps] vs = [gfp.mean() for gfp in gfps] i = np.argmin(np.abs(1 - np.array(vs))) cov = covs[i] # save cov value with open(self.get('cov-info-file', mkdir=True), 'w') as fid: fid.write('%s\n' % reg_vs[i]) elif reg is not None: raise RuntimeError(f"reg={reg!r} in {params}") cov.save(dest) def _make_evoked(self, decim, data_raw): """Make files with evoked sensor data. Parameters ---------- decim : int Data decimation factor (the default is the factor specified in the epoch definition). """ dst = self.get('evoked-file', mkdir=True) epoch = self._epochs[self.get('epoch')] # determine whether using default decimation if decim: if epoch.decim: default_decim = decim == epoch.decim else: raw = self.load_raw(False) default_decim = decim == raw.info['sfreq'] / epoch.samplingrate else: default_decim = True use_cache = default_decim model = self.get('model') equal_count = self.get('equalize_evoked_count') == 'eq' if use_cache and exists(dst) and cache_valid(getmtime(dst), self._evoked_mtime()): ds = self.load_selected_events(data_raw=data_raw) ds = ds.aggregate(model, drop_bad=True, equal_count=equal_count, drop=('i_start', 't_edf', 'T', 'index', 'trigger')) ds['evoked'] = mne.read_evokeds(dst, proj=False) return ds self._log.debug("Make evoked %s", dst) # load the epochs (post baseline-correction trigger shift requires # baseline corrected evoked if epoch.post_baseline_trigger_shift: ds = self.load_epochs(ndvar=False, baseline=True, decim=decim, data_raw=data_raw, interpolate_bads='keep') else: ds = self.load_epochs(ndvar=False, decim=decim, data_raw=data_raw, interpolate_bads='keep') # aggregate ds_agg = ds.aggregate(model, drop_bad=True, equal_count=equal_count, drop=('i_start', 't_edf', 'T', 'index', 'trigger'), never_drop=('epochs',)) ds_agg.rename('epochs', 'evoked') # save for e in ds_agg['evoked']: e.info['description'] = f"Eelbrain {CACHE_STATE_VERSION}" if use_cache: mne.write_evokeds(dst, ds_agg['evoked']) return ds_agg def make_fwd(self): """Make the forward model""" subject = self.get('subject') fwd_recording = self._get_fwd_recording(subject) with self._temporary_state: dst = self.get('fwd-file', recording=fwd_recording) if exists(dst): if cache_valid(getmtime(dst), self._fwd_mtime(subject, fwd_recording=fwd_recording)): return dst # get trans for correct visit for fwd_session trans = self.get('trans-file') src = self.get('src-file', make=True) pipe = self._raw[self.get('raw')] raw = pipe.load(subject, fwd_recording) bem = self._load_bem() src = mne.read_source_spaces(src) self._log.debug(f"make_fwd {basename(dst)}...") bemsol = mne.make_bem_solution(bem) fwd = mne.make_forward_solution(raw.info, trans, src, bemsol, ignore_ref=True) for s, s0 in zip(fwd['src'], src): if s['nuse'] != s0['nuse']: raise RuntimeError(f"The forward solution {basename(dst)} contains fewer sources than the source space. This could be due to a corrupted bem file with sources outside of the inner skull surface.") mne.write_forward_solution(dst, fwd, True) return dst def make_ica_selection(self, epoch=None, decim=None, session=None, **state): """Select ICA components to remove through a GUI Parameters ---------- epoch : str Epoch to use for visualization in the GUI (default is to use the raw data). decim : int Downsample data for visualization (to improve GUI performance; for raw data, the default is ~100 Hz, for epochs the default is the epoch setting). session : str | list of str One or more sessions for which to plot the raw data (this parameter can not be used together with ``epoch``; default is the session in the current state). ... State parameters. Notes ----- Computing ICA decomposition can take a while. In order to precompute the decomposition for all subjects before doing the selection use :meth:`.make_ica()` in a loop as in:: >>> for subject in e: ... e.make_ica() ... """ # ICA path = self.make_ica(**state) # display data subject = self.get('subject') pipe = self._raw[self.get('raw')] bads = pipe.load_bad_channels(subject, self.get('recording')) with self._temporary_state, warnings.catch_warnings(): warnings.filterwarnings('ignore', 'The measurement information indicates a low-pass', RuntimeWarning) if epoch is None: if session is None: session = self.get('session') raw = pipe.load_concatenated_source_raw(subject, session, self.get('visit')) events = mne.make_fixed_length_events(raw) ds = Dataset() decim = int(raw.info['sfreq'] // 100) if decim is None else decim ds['epochs'] = mne.Epochs(raw, events, 1, 0, 1, baseline=None, proj=False, decim=decim, preload=True) elif session is not None: raise TypeError(f"session={session!r} with epoch={epoch!r}") else: ds = self.load_epochs(ndvar=False, epoch=epoch, reject=False, raw=pipe.source.name, decim=decim, add_bads=bads) info = ds['epochs'].info data = TestDims('sensor') data_kind = data.data_to_ndvar(info)[0] sysname = pipe.get_sysname(info, subject, data_kind) connectivity = pipe.get_connectivity(data_kind) gui.select_components(path, ds, sysname, connectivity) def make_ica(self, **state): """Compute ICA decomposition for a :class:`pipeline.RawICA` preprocessing step If a corresponding file exists, a basic check is done as to whether the bad channels have changed, and if so the ICA is recomputed. Parameters ---------- ... State parameters. Returns ------- path : str Path to the ICA file. Notes ----- ICA decomposition can take some time. This function can be used to precompute ICA decompositions for all subjects after trial pre-rejection has been completed:: >>> for subject in e: ... e.make_ica() """ if state: self.set(**state) pipe = self._raw[self.get('raw')] if not isinstance(pipe, RawICA): ica_raws = [key for key, pipe in self._raw.items() if isinstance(pipe, RawICA)] if len(ica_raws) > 1: raise ValueError(f"raw={pipe.name!r} does not involve ICA; set raw to an ICA processing step ({enumeration(ica_raws)})") elif len(ica_raws) == 1: print(f"raw: {pipe.name} -> {ica_raws[0]}") return self.make_ica(raw=ica_raws[0]) else: raise RuntimeError("Experiment has no RawICA processing step") return pipe.make_ica(self.get('subject'), self.get('visit')) def make_link(self, temp, field, src, dst, redo=False): """Make a hard link Make a hard link at the file with the ``dst`` value on ``field``, linking to the file with the ``src`` value of ``field``. Parameters ---------- temp : str Template of the file for which to make a link. field : str Field in which the source and target of the link are distinguished. src : str Value for field on the source file. dst : str Value for field on the destination filename. redo : bool If the target file already exists, overwrite it. """ dst_path = self.get(temp, **{field: dst}) if not redo and exists(dst_path): return src_path = self.get(temp, **{field: src}) os.link(src_path, dst_path) def make_mov_ga_dspm(self, subjects=None, baseline=True, src_baseline=False, fmin=2, surf=None, views=None, hemi=None, time_dilation=4., foreground=None, background=None, smoothing_steps=None, dst=None, redo=False, **state): """Make a grand average movie from dSPM values (requires PySurfer 0.6) Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). baseline : bool | tuple Apply baseline correction using this period in sensor space. True to use the epoch's baseline specification (default). src_baseline : bool | tuple Apply baseline correction using this period in source space. True to use the epoch's baseline specification. The default is to not apply baseline correction. fmin : scalar Minimum dSPM value to draw (default 2). fmax is 3 * fmin. surf : str Surface on which to plot data. views : str | tuple of str View(s) of the brain to include in the movie. hemi : 'lh' | 'rh' | 'both' | 'split' Which hemispheres to plot. time_dilation : scalar Factor by which to slow the passage of time. For example, with ``time_dilation=4`` (the default) a segment of data for 500 ms will last 2 s. foreground : mayavi color Figure foreground color (i.e., the text color). background : mayavi color Figure background color. smoothing_steps : None | int Number of smoothing steps if data is spatially undersampled (pysurfer ``Brain.add_data()`` argument). dst : str (optional) Path to save the movie. The default is a file in the results folder with a name determined based on the input data. Plotting parameters (``view`` and all subsequent parameters) are not included in the filename. "~" is expanded to the user's home folder. redo : bool Make the movie even if the target file exists already. ... State parameters. """ state['model'] = '' subject, group = self._process_subject_arg(subjects, state) data = TestDims("source", morph=bool(group)) brain_kwargs = self._surfer_plot_kwargs(surf, views, foreground, background, smoothing_steps, hemi) self._set_analysis_options(data, baseline, src_baseline, None, None, None) self.set(equalize_evoked_count='', resname="GA dSPM %s %s" % (brain_kwargs['surf'], fmin)) if dst is None: if group is None: dst = self.get('subject-mov-file', mkdir=True) else: dst = self.get('group-mov-file', mkdir=True) else: dst = os.path.expanduser(dst) if not redo and self._result_file_mtime(dst, data, group is None): return plot._brain.assert_can_save_movies() if group is None: ds = self.load_evoked_stc(subject, baseline, src_baseline) y = ds['src'] else: ds = self.load_evoked_stc(group, baseline, src_baseline, morph=True) y = ds['srcm'] brain = plot.brain.dspm(y, fmin, fmin * 3, colorbar=False, **brain_kwargs) brain.save_movie(dst, time_dilation) brain.close() def make_mov_ttest(self, subjects=None, model='', c1=None, c0=None, p=0.05, baseline=True, src_baseline=False, surf=None, views=None, hemi=None, time_dilation=4., foreground=None, background=None, smoothing_steps=None, dst=None, redo=False, **state): """Make a t-test movie (requires PySurfer 0.6) Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). model : None | str Model on which the conditions c1 and c0 are defined. The default (``''``) is the grand average. c1 : None | str | tuple Test condition (cell in model). If None, the grand average is used and c0 has to be a scalar. c0 : str | scalar Control condition (cell on model) or scalar against which to compare c1. p : 0.1 | 0.05 | 0.01 | .001 Maximum p value to draw. baseline : bool | tuple Apply baseline correction using this period in sensor space. True to use the epoch's baseline specification (default). src_baseline : bool | tuple Apply baseline correction using this period in source space. True to use the epoch's baseline specification. The default is to not apply baseline correction. surf : str Surface on which to plot data. views : str | tuple of str View(s) of the brain to include in the movie. hemi : 'lh' | 'rh' | 'both' | 'split' Which hemispheres to plot. time_dilation : scalar Factor by which to slow the passage of time. For example, with ``time_dilation=4`` (the default) a segment of data for 500 ms will last 2 s. foreground : mayavi color Figure foreground color (i.e., the text color). background : mayavi color Figure background color. smoothing_steps : None | int Number of smoothing steps if data is spatially undersampled (pysurfer ``Brain.add_data()`` argument). dst : str (optional) Path to save the movie. The default is a file in the results folder with a name determined based on the input data. Plotting parameters (``view`` and all subsequent parameters) are not included in the filename. "~" is expanded to the user's home folder. redo : bool Make the movie even if the target file exists already. ... State parameters. """ if p == 0.1: pmid = 0.05 pmin = 0.01 elif p == 0.05: pmid = 0.01 pmin = 0.001 elif p == 0.01: pmid = 0.001 pmin = 0.001 elif p == 0.001: pmid = 0.0001 pmin = 0.00001 else: raise ValueError("p=%s" % p) data = TestDims("source", morph=True) brain_kwargs = self._surfer_plot_kwargs(surf, views, foreground, background, smoothing_steps, hemi) surf = brain_kwargs['surf'] if model: if not c1: raise ValueError("If x is specified, c1 needs to be specified; " "got c1=%s" % repr(c1)) elif c0: resname = "t-test %s-%s {test_options} %s" % (c1, c0, surf) cat = (c1, c0) else: resname = "t-test %s {test_options} %s" % (c1, surf) cat = (c1,) elif c1 or c0: raise ValueError("If x is not specified, c1 and c0 should not be " "specified either; got c1=%s, c0=%s" % (repr(c1), repr(c0))) else: resname = "t-test GA {test_options} %s" % surf cat = None state.update(resname=resname, model=model) with self._temporary_state: subject, group = self._process_subject_arg(subjects, state) self._set_analysis_options(data, baseline, src_baseline, p, None, None) if dst is None: if group is None: dst = self.get('subject-mov-file', mkdir=True) else: dst = self.get('group-mov-file', mkdir=True) else: dst = os.path.expanduser(dst) if not redo and self._result_file_mtime(dst, data, group is None): return plot._brain.assert_can_save_movies() if group is None: ds = self.load_epochs_stc(subject, baseline, src_baseline, cat=cat) y = 'src' else: ds = self.load_evoked_stc(group, baseline, src_baseline, morph=True, cat=cat) y = 'srcm' # find/apply cluster criteria state = self._cluster_criteria_kwargs(data) if state: state.update(samples=0, pmin=p) # compute t-maps if c0: if group: res = testnd.ttest_rel(y, model, c1, c0, match='subject', ds=ds, **state) else: res = testnd.ttest_ind(y, model, c1, c0, ds=ds, **state) else: res = testnd.ttest_1samp(y, ds=ds, **state) # select cluster-corrected t-map if state: tmap = res.masked_parameter_map(None) else: tmap = res.t # make movie brain = plot.brain.dspm(tmap, ttest_t(p, res.df), ttest_t(pmin, res.df), ttest_t(pmid, res.df), surf=surf) brain.save_movie(dst, time_dilation) brain.close() def make_mrat_evoked(self, **kwargs): """Produce the sensor data fiff files needed for MRAT sensor analysis Parameters ---------- ... State parameters. Examples -------- To produce evoked files for all subjects in the experiment: >>> experiment.set(model='factor1%factor2') >>> for _ in experiment: >>> experiment.make_mrat_evoked() ... """ ds = self.load_evoked(ndvar=False, **kwargs) # create fiffs model = self.get('model') factors = [f.strip() for f in model.split('%')] for case in ds.itercases(): condition = '_'.join(case[f] for f in factors) path = self.get('mrat-sns-file', mkdir=True, mrat_condition=condition) evoked = case['evoked'] evoked.save(path) def make_mrat_stcs(self, **kwargs): """Produce the STC files needed for the MRAT analysis tool Parameters ---------- ... State parameters. Examples -------- To produce stc files for all subjects in the experiment: >>> experiment.set_inv('free') >>> experiment.set(model='factor1%factor2') >>> for _ in experiment: >>> experiment.make_mrat_stcs() ... """ ds = self.load_evoked_stc(morph=True, ndvar=False, **kwargs) # save condition info info_file = self.get('mrat_info-file', mkdir=True) ds.save_txt(info_file) # create stcs model = self.get('model') factors = [f.strip() for f in model.split('%')] for case in ds.itercases(): condition = '_'.join(case[f] for f in factors) path = self.get('mrat-src-file', mkdir=True, mrat_condition=condition) stc = case['stcm'] stc.save(path) def make_plot_annot(self, surf='inflated', redo=False, **state): """Create a figure for the contents of an annotation file Parameters ---------- surf : str FreeSurfer surface on which to plot the annotation. redo : bool If the target file already exists, overwrite it. ... State parameters. """ if is_fake_mri(self.get('mri-dir', **state)): mrisubject = self.get('common_brain') self.set(mrisubject=mrisubject, match=False) dst = self.get('res-file', mkdir=True, ext='png', analysis='Source Annot', resname="{parc} {mrisubject} %s" % surf) if not redo and exists(dst): return brain = self.plot_annot(surf=surf, axw=600) brain.save_image(dst, 'rgba', True) legend = brain.plot_legend(show=False) legend.save(dst[:-3] + 'pdf', transparent=True) brain.close() legend.close() def make_plot_label(self, label, surf='inflated', redo=False, **state): if is_fake_mri(self.get('mri-dir', **state)): mrisubject = self.get('common_brain') self.set(mrisubject=mrisubject, match=False) dst = self._make_plot_label_dst(surf, label) if not redo and exists(dst): return brain = self.plot_label(label, surf=surf) brain.save_image(dst, 'rgba', True) def make_plots_labels(self, surf='inflated', redo=False, **state): self.set(**state) with self._temporary_state: if is_fake_mri(self.get('mri-dir')): self.set(mrisubject=self.get('common_brain'), match=False) labels = tuple(self._load_labels().values()) dsts = [self._make_plot_label_dst(surf, label.name) for label in labels] if not redo and all(exists(dst) for dst in dsts): return brain = self.plot_brain(surf, None, 'split', ['lat', 'med'], w=1200) for label, dst in zip(labels, dsts): brain.add_label(label) brain.save_image(dst, 'rgba', True) brain.remove_labels(hemi='lh') def _make_plot_label_dst(self, surf, label): return self.get('res-deep-file', mkdir=True, analysis='Source Labels', folder="{parc} {mrisubject} %s" % surf, resname=label, ext='png') def make_raw(self, **kwargs): """Make a raw file Parameters ---------- ... State parameters. Notes ----- Due to the electronics of the KIT system sensors, signal lower than 0.16 Hz is not recorded even when recording at DC. """ if kwargs: self.set(**kwargs) pipe = self._raw[self.get('raw')] pipe.cache(self.get('subject'), self.get('recording')) def make_epoch_selection(self, decim=None, auto=None, overwrite=None, **state): """Open :func:`gui.select_epochs` for manual epoch selection The GUI is opened with the correct file name; if the corresponding file exists, it is loaded, and upon saving the correct path is the default. Parameters ---------- decim : int Decimate epochs for the purpose of faster display. Decimation is applied relative to the raw data file (i.e., if the raw data is sampled at a 1000 Hz, ``decim=10`` results in a sampling rate of 100 Hz for display purposes. The default is to use the decim parameter specified in the epoch definition. auto : scalar (optional) Perform automatic rejection instead of showing the GUI by supplying a an absolute threshold (for example, ``1e-12`` to reject any epoch in which the absolute of at least one channel exceeds 1 picotesla). If a rejection file already exists also set ``overwrite=True``. overwrite : bool If ``auto`` is specified and a rejection file already exists, overwrite the old file. The default is to raise an error if the file exists (``None``). Set to ``False`` to quietly keep the exising file. ... State parameters. """ rej = self.get('rej', **state) rej_args = self._artifact_rejection[rej] if rej_args['kind'] != 'manual': raise ValueError(f"rej={rej!r}; Epoch rejection is not manual") epoch = self._epochs[self.get('epoch')] if not isinstance(epoch, PrimaryEpoch): if isinstance(epoch, SecondaryEpoch): raise ValueError(f"The current epoch {epoch.name!r} inherits selections from {epoch.sel_epoch!r}. To access a rejection file for this epoch, call `e.set(epoch={epoch.sel_epoch!r})` and then call `e.make_epoch_selection()` again.") elif isinstance(epoch, SuperEpoch): raise ValueError(f"The current epoch {epoch.name!r} inherits selections from these other epochs: {epoch.sub_epochs!r}. To access selections for these epochs, call `e.make_epoch_selection(epoch=epoch)` for each.") else: raise ValueError(f"The current epoch {epoch.name!r} is not a primary epoch and inherits selections from other epochs. Generate trial rejection for these epochs.") path = self.get('rej-file', mkdir=True, session=epoch.session) if auto is not None and overwrite is not True and exists(path): if overwrite is False: return elif overwrite is None: raise IOError(self.format("A rejection file already exists for {subject}, epoch {epoch}, rej {rej}. Set the overwrite parameter to specify how to handle existing files.")) else: raise TypeError(f"overwrite={overwrite!r}") ds = self.load_epochs(reject=False, trigger_shift=False, decim=decim) has_meg = 'meg' in ds has_grad = 'grad' in ds has_eeg = 'eeg' in ds has_eog = 'eog' in ds if sum((has_meg, has_grad, has_eeg)) > 1: raise NotImplementedError("Rejection GUI for multiple channel types") elif has_meg: y_name = 'meg' vlim = 2e-12 elif has_grad: raise NotImplementedError("Rejection GUI for gradiometer data") elif has_eeg: y_name = 'eeg' vlim = 1.5e-4 else: raise RuntimeError("No data found") if has_eog: eog_sns = [] # TODO: use EOG else: eog_sns = self._eog_sns.get(ds[y_name].sensor.sysname) if auto is not None: # create rejection rej_ds = new_rejection_ds(ds) rej_ds[:, 'accept'] = ds[y_name].abs().max(('sensor', 'time')) <= auto # create description for info args = [f"auto={auto!r}"] if overwrite is True: args.append("overwrite=True") if decim is not None: args.append(f"decim={decim!r}") rej_ds.info['desc'] = f"Created with {self.__class__.__name__}.make_epoch_selection({", ".join(args)})" # save save.pickle(rej_ds, path) # print info n_rej = rej_ds.eval("sum(accept == False)") print(self.format(f"{n_rej} of {rej_ds.n_cases} epochs rejected with threshold {auto} for {{subject}}, epoch {{epoch}}")) return # don't mark eog sns if it is bad bad_channels = self.load_bad_channels() eog_sns = [c for c in eog_sns if c not in bad_channels] gui.select_epochs(ds, y_name, path=path, vlim=vlim, mark=eog_sns) def _need_not_recompute_report(self, dst, samples, data, redo): "Check (and log) whether the report needs to be redone" desc = self._get_rel('report-file', 'res-dir') if not exists(dst): self._log.debug("New report: %s", desc) elif redo: self._log.debug("Redoing report: %s", desc) elif not self._result_file_mtime(dst, data): self._log.debug("Report outdated: %s", desc) else: meta = read_meta(dst) if 'samples' in meta: if int(meta['samples']) >= samples: self._log.debug("Report up to date: %s", desc) return True else: self._log.debug("Report file used %s samples, recomputing " "with %i: %s", meta['samples'], samples, desc) else: self._log.debug("Report created prior to Eelbrain 0.25, can " "not check number of samples. Delete manually " "to recompute: %s", desc) return True def make_report(self, test, parc=None, mask=None, pmin=None, tstart=None, tstop=None, samples=10000, baseline=True, src_baseline=None, include=0.2, redo=False, **state): """Create an HTML report on spatio-temporal clusters Parameters ---------- test : str Test for which to create a report (entry in MneExperiment.tests). parc : None | str Find clusters in each label of parc (as opposed to the whole brain). mask : None | str Parcellation to apply as mask. Can only be specified if parc==None. pmin : None | scalar, 1 > pmin > 0 | 'tfce' Equivalent p-value for cluster threshold, or 'tfce' for threshold-free cluster enhancement. tstart : scalar Beginning of the time window for the test in seconds (default is the beginning of the epoch). tstop : scalar End of the time window for the test in seconds (default is the end of the epoch). samples : int > 0 Number of samples used to determine cluster p values for spatio- temporal clusters (default 10,000). baseline : bool | tuple Apply baseline correction using this period in sensor space. True to use the epoch's baseline specification (default). src_baseline : bool | tuple Apply baseline correction using this period in source space. True to use the epoch's baseline specification. The default is to not apply baseline correction. include : 0 < scalar <= 1 Create plots for all clusters with p-values smaller or equal this value. redo : bool If the target file already exists, delete and recreate it. This only applies to the HTML result file, not to the test. ... State parameters. See Also -------- load_test : load corresponding data and tests """ if samples < 1: raise ValueError("samples needs to be > 0") elif include <= 0 or include > 1: raise ValueError("include needs to be 0 < include <= 1, got %s" % repr(include)) self.set(**state) data = TestDims('source', morph=True) self._set_analysis_options(data, baseline, src_baseline, pmin, tstart, tstop, parc, mask) dst = self.get('report-file', mkdir=True, test=test) if self._need_not_recompute_report(dst, samples, data, redo): return # start report title = self.format('{recording} {test_desc}') report = Report(title) report.add_paragraph(self._report_methods_brief(dst)) if isinstance(self._tests[test], TwoStageTest): self._two_stage_report(report, data, test, baseline, src_baseline, pmin, samples, tstart, tstop, parc, mask, include) else: self._evoked_report(report, data, test, baseline, src_baseline, pmin, samples, tstart, tstop, parc, mask, include) # report signature report.sign(('eelbrain', 'mne', 'surfer', 'scipy', 'numpy')) report.save_html(dst, meta={'samples': samples}) def _evoked_report(self, report, data, test, baseline, src_baseline, pmin, samples, tstart, tstop, parc, mask, include): # load data ds, res = self._load_test(test, tstart, tstop, pmin, parc, mask, samples, data, baseline, src_baseline, True, True) # info surfer_kwargs = self._surfer_plot_kwargs() self._report_test_info(report.add_section("Test Info"), ds, test, res, data, include) if parc: section = report.add_section(parc) caption = "Labels in the %s parcellation." % parc self._report_parc_image(section, caption) elif mask: title = "Whole Brain Masked by %s" % mask section = report.add_section(title) caption = "Mask: %s" % mask.capitalize() self._report_parc_image(section, caption) colors = plot.colors_for_categorial(ds.eval(res._plot_model())) report.append(_report.source_time_results(res, ds, colors, include, surfer_kwargs, parc=parc)) def _two_stage_report(self, report, data, test, baseline, src_baseline, pmin, samples, tstart, tstop, parc, mask, include): test_obj = self._tests[test] return_data = test_obj._within_model is not None rlm = self._load_test(test, tstart, tstop, pmin, parc, mask, samples, data, baseline, src_baseline, return_data, True) if return_data: group_ds, rlm = rlm else: group_ds = None # start report surfer_kwargs = self._surfer_plot_kwargs() info_section = report.add_section("Test Info") if parc: section = report.add_section(parc) caption = "Labels in the %s parcellation." % parc self._report_parc_image(section, caption) elif mask: title = "Whole Brain Masked by %s" % mask section = report.add_section(title) caption = "Mask: %s" % mask.capitalize() self._report_parc_image(section, caption) # Design matrix section = report.add_section("Design Matrix") section.append(rlm.design()) # add results to report for term in rlm.column_names: res = rlm.tests[term] ds = rlm.coefficients_dataset(term) report.append( _report.source_time_results( res, ds, None, include, surfer_kwargs, term, y='coeff')) self._report_test_info(info_section, group_ds or ds, test_obj, res, data) def make_report_rois(self, test, parc=None, pmin=None, tstart=None, tstop=None, samples=10000, baseline=True, src_baseline=False, redo=False, **state): """Create an HTML report on ROI time courses Parameters ---------- test : str Test for which to create a report (entry in MneExperiment.tests). parc : str Parcellation that defines ROIs. pmin : None | scalar, 1 > pmin > 0 | 'tfce' Equivalent p-value for cluster threshold, or 'tfce' for threshold-free cluster enhancement. tstart : scalar Beginning of the time window for the test in seconds (default is the beginning of the epoch). tstop : scalar End of the time window for the test in seconds (default is the end of the epoch). samples : int > 0 Number of samples used to determine cluster p values for spatio- temporal clusters (default 1000). baseline : bool | tuple Apply baseline correction using this period in sensor space. True to use the epoch's baseline specification (default). src_baseline : bool | tuple Apply baseline correction using this period in source space. True to use the epoch's baseline specification. The default is to not apply baseline correction. redo : bool If the target file already exists, delete and recreate it. ... State parameters. See Also -------- load_test : load corresponding data and tests (use ``data="source.mean"``) """ test_obj = self._tests[test] if samples < 1: raise ValueError("Need samples > 0 to run permutation test.") elif isinstance(test_obj, TwoStageTest): raise NotImplementedError("ROI analysis not implemented for two-" "stage tests") if parc is not None: state['parc'] = parc parc = self.get('parc', **state) if not parc: raise ValueError("No parcellation specified") data = TestDims('source.mean') self._set_analysis_options(data, baseline, src_baseline, pmin, tstart, tstop, parc) dst = self.get('report-file', mkdir=True, test=test) if self._need_not_recompute_report(dst, samples, data, redo): return res_data, res = self._load_test(test, tstart, tstop, pmin, parc, None, samples, data, baseline, src_baseline, True, True) # sorted labels labels_lh = [] labels_rh = [] for label in res.res.keys(): if label.endswith('-lh'): labels_lh.append(label) elif label.endswith('-rh'): labels_rh.append(label) else: raise NotImplementedError("Label named %s" % repr(label.name)) labels_lh.sort() labels_rh.sort() # start report title = self.format('{recording} {test_desc}') report = Report(title) # method intro (compose it later when data is available) ds0 = res_data[label] res0 = res.res[label] info_section = report.add_section("Test Info") self._report_test_info(info_section, res.n_trials_ds, test_obj, res0, data) # add parc image section = report.add_section(parc) caption = "ROIs in the %s parcellation." % parc self._report_parc_image(section, caption, res.subjects) # add content body n_subjects = len(res.subjects) colors = plot.colors_for_categorial(ds0.eval(res0._plot_model())) for label in chain(labels_lh, labels_rh): res_i = res.res[label] ds = res_data[label] title = label[:-3].capitalize() caption = "Mean in label %s." % label n = len(ds['subject'].cells) if n < n_subjects: title += ' (n=%i)' % n caption += " Data from %i of %i subjects." % (n, n_subjects) section.append(_report.time_results( res_i, ds, colors, title, caption, merged_dist=res.merged_dist)) report.sign(('eelbrain', 'mne', 'surfer', 'scipy', 'numpy')) report.save_html(dst, meta={'samples': samples}) def _make_report_eeg(self, test, pmin=None, tstart=None, tstop=None, samples=10000, baseline=True, include=1, **state): # outdated (cache, load_test()) """Create an HTML report on EEG sensor space spatio-temporal clusters Parameters ---------- test : str Test for which to create a report (entry in MneExperiment.tests). pmin : None | scalar, 1 > pmin > 0 | 'tfce' Equivalent p-value for cluster threshold, or 'tfce' for threshold-free cluster enhancement. tstart : scalar Beginning of the time window for the test in seconds (default is the beginning of the epoch). tstop : scalar End of the time window for the test in seconds (default is the end of the epoch). samples : int > 0 Number of samples used to determine cluster p values for spatio- temporal clusters (default 1000). baseline : bool | tuple Apply baseline correction using this period. True to use the epoch's baseline specification (default). include : 0 < scalar <= 1 Create plots for all clusters with p-values smaller or equal this value (the default is 1, i.e. to show all clusters). ... State parameters. """ data = TestDims("sensor") self._set_analysis_options(data, baseline, None, pmin, tstart, tstop) dst = self.get('report-file', mkdir=True, fmatch=False, test=test, folder="EEG Spatio-Temporal", modality='eeg', **state) if self._need_not_recompute_report(dst, samples, data, False): return # load data ds, res = self.load_test(test, tstart, tstop, pmin, None, None, samples, 'sensor', baseline, None, True, True) # start report title = self.format('{recording} {test_desc}') report = Report(title) # info info_section = report.add_section("Test Info") self._report_test_info(info_section, ds, test, res, data, include) # add connectivity image p = plot.SensorMap(ds['eeg'], connectivity=True, show=False) image_conn = p.image("connectivity.png") info_section.add_figure("Sensor map with connectivity", image_conn) p.close() colors = plot.colors_for_categorial(ds.eval(res._plot_model())) report.append(_report.sensor_time_results(res, ds, colors, include)) report.sign(('eelbrain', 'mne', 'scipy', 'numpy')) report.save_html(dst) def _make_report_eeg_sensors(self, test, sensors=('FZ', 'CZ', 'PZ', 'O1', 'O2'), pmin=None, tstart=None, tstop=None, samples=10000, baseline=True, redo=False, **state): # outdated (cache) """Create an HTML report on individual EEG sensors Parameters ---------- test : str Test for which to create a report (entry in MneExperiment.tests). sensors : sequence of str Names of the sensors which to include. pmin : None | scalar, 1 > pmin > 0 | 'tfce' Equivalent p-value for cluster threshold, or 'tfce' for threshold-free cluster enhancement. tstart : scalar Beginning of the time window for the test in seconds (default is the beginning of the epoch). tstop : scalar End of the time window for the test in seconds (default is the end of the epoch). samples : int > 0 Number of samples used to determine cluster p values for spatio- temporal clusters (default 1000). baseline : bool | tuple Apply baseline correction using this period. True to use the epoch's baseline specification (default). redo : bool If the target file already exists, delete and recreate it. This only applies to the HTML result file, not to the test. ... State parameters. """ data = TestDims('sensor.sub') self._set_analysis_options(data, baseline, None, pmin, tstart, tstop) dst = self.get('report-file', mkdir=True, fmatch=False, test=test, folder="EEG Sensors", modality='eeg', **state) if self._need_not_recompute_report(dst, samples, data, redo): return # load data test_obj = self._tests[test] ds = self.load_evoked(self.get('group'), baseline, True, vardef=test_obj.vars) # test that sensors are in the data eeg = ds['eeg'] missing = [s for s in sensors if s not in eeg.sensor.names] if missing: raise ValueError("The following sensors are not in the data: %s" % missing) # start report title = self.format('{recording} {test_desc}') report = Report(title) # info info_section = report.add_section("Test Info") # add sensor map p = plot.SensorMap(ds['eeg'], show=False) p.mark_sensors(sensors) info_section.add_figure("Sensor map", p) p.close() # main body caption = "Signal at %s." test_kwargs = self._test_kwargs(samples, pmin, tstart, tstop, ('time', 'sensor'), None) ress = [self._make_test(eeg.sub(sensor=sensor), ds, test_obj, test_kwargs) for sensor in sensors] colors = plot.colors_for_categorial(ds.eval(ress[0]._plot_model())) for sensor, res in zip(sensors, ress): report.append(_report.time_results(res, ds, colors, sensor, caption % sensor)) self._report_test_info(info_section, ds, test, res, data) report.sign(('eelbrain', 'mne', 'scipy', 'numpy')) report.save_html(dst) @staticmethod def _report_methods_brief(path): path = Path(path) items = [*path.parts[:-1], path.stem] return List('Methods brief', items[-3:]) def _report_subject_info(self, ds, model): """Table with subject information Parameters ---------- ds : Dataset Dataset with ``subject`` and ``n`` variables, and any factors in ``model``. model : str The model used for aggregating. """ s_ds = self.show_subjects(asds=True) if 'n' in ds: if model: n_ds = table.repmeas('n', model, 'subject', ds=ds) else: n_ds = ds n_ds_aligned = align1(n_ds, s_ds['subject'], 'subject') s_ds.update(n_ds_aligned) return s_ds.as_table( midrule=True, count=True, caption="All subjects included in the analysis with trials per " "condition") def _report_test_info(self, section, ds, test, res, data, include=None, model=True): """Top-level report info function Returns ------- info : Table Table with preprocessing and test info. """ test_obj = self._tests[test] if isinstance(test, str) else test # List of preprocessing parameters info = List("Analysis:") # epoch epoch = self.format('epoch = {epoch}') evoked_kind = self.get('evoked_kind') if evoked_kind: epoch += f' {evoked_kind}' if model is True: model = self.get('model') if model: epoch += f" ~ {model}" info.add_item(epoch) # inverse solution if data.source: info.add_item(self.format("cov = {cov}")) info.add_item(self.format("inv = {inv}")) # test info.add_item("test = %s (%s)" % (test_obj.kind, test_obj.desc)) if include is not None: info.add_item(f"Separate plots of all clusters with a p-value < {include}") section.append(info) # Statistical methods (for temporal tests, res is only representative) info = res.info_list() section.append(info) # subjects and state section.append(self._report_subject_info(ds, test_obj.model)) section.append(self.show_state(hide=('hemi', 'subject', 'mrisubject'))) return info def _report_parc_image(self, section, caption, subjects=None): "Add picture of the current parcellation" parc_name, parc = self._get_parc() with self._temporary_state: if isinstance(parc, IndividualSeededParc): if subjects is None: raise RuntimeError("subjects needs to be specified for " "plotting individual parcellations") legend = None for subject in self: # make sure there is at least one label if not any(not l.name.startswith('unknown-') for l in self.load_annot()): section.add_image_figure("No labels", subject) continue brain = self.plot_annot() if legend is None: p = brain.plot_legend(show=False) legend = p.image('parc-legend') p.close() section.add_image_figure(brain.image('parc'), subject) brain.close() return # one parc for all subjects self.set(mrisubject=self.get('common_brain')) brain = self.plot_annot(axw=500) legend = brain.plot_legend(show=False) content = [brain.image('parc'), legend.image('parc-legend')] section.add_image_figure(content, caption) brain.close() legend.close() def _make_report_lm(self, pmin=0.01, baseline=True, src_baseline=False, mask='lobes'): """Report for a first level (single subject) LM Parameters ---------- pmin : scalar Threshold p-value for uncorrected SPMs. """ if not isinstance(self._tests[self.get('test')], TwoStageTest): raise NotImplementedError("Only two-stage tests") with self._temporary_state: self._set_analysis_options('source', baseline, src_baseline, pmin, None, None, mask=mask) dst = self.get('subject-spm-report', mkdir=True) lm = self._load_spm(baseline, src_baseline) title = self.format('{recording} {test_desc}') surfer_kwargs = self._surfer_plot_kwargs() report = Report(title) report.append(_report.source_time_lm(lm, pmin, surfer_kwargs)) # report signature report.sign(('eelbrain', 'mne', 'surfer', 'scipy', 'numpy')) report.save_html(dst) def make_report_coreg(self, file_name=None, **state): """Create HTML report with plots of the MEG/MRI coregistration Parameters ---------- file_name : str Where to save the report (default is in the root/methods director). ... State parameters. """ from matplotlib import pyplot from mayavi import mlab mri = self.get('mri', **state) group = self.get('group') title = 'Coregistration' if group != 'all': title += ' ' + group if mri: title += ' ' + mri if file_name is None: file_name = join(self.get('methods-dir', mkdir=True), title + '.html') report = Report(title) for subject in self: mrisubject = self.get('mrisubject') fig = self.plot_coreg() fig.scene.camera.parallel_projection = True fig.scene.camera.parallel_scale = .175 mlab.draw(fig) # front mlab.view(90, 90, 1, figure=fig) im_front = Image.from_array(mlab.screenshot(figure=fig), 'front') # left mlab.view(0, 270, 1, roll=90, figure=fig) im_left = Image.from_array(mlab.screenshot(figure=fig), 'left') mlab.close(fig) # MRI/BEM figure if is_fake_mri(self.get('mri-dir')): bem_fig = None else: bem_fig = mne.viz.plot_bem(mrisubject, self.get('mri-sdir'), brain_surfaces='white', show=False) # add to report if subject == mrisubject: title = subject caption = "Coregistration for subject %s." % subject else: title = "%s (%s)" % (subject, mrisubject) caption = ("Coregistration for subject %s (MRI-subject %s)." % (subject, mrisubject)) section = report.add_section(title) if bem_fig is None: section.add_figure(caption, (im_front, im_left)) else: section.add_figure(caption, (im_front, im_left, bem_fig)) pyplot.close(bem_fig) report.sign() report.save_html(file_name) def make_src(self, **kwargs): """Make the source space Parameters ---------- ... State parameters. """ dst = self.get('src-file', **kwargs) subject = self.get('mrisubject') common_brain = self.get('common_brain') is_scaled = (subject != common_brain) and is_fake_mri(self.get('mri-dir')) if is_scaled: # make sure the source space exists for the original with self._temporary_state: self.make_src(mrisubject=common_brain) orig = self.get('src-file') if exists(dst): if getmtime(dst) >= getmtime(orig): return os.remove(dst) src = self.get('src') self._log.info(f"Scaling {src} source space for {subject}...") subjects_dir = self.get('mri-sdir') mne.scale_source_space(subject, f'{{subject}}-{src}-src.fif', subjects_dir=subjects_dir) elif exists(dst): return else: src = self.get('src') kind, param, special = SRC_RE.match(src).groups() self._log.info(f"Generating {src} source space for {subject}...") if kind == 'vol': if subject == 'fsaverage': bem = self.get('bem-file') else: raise NotImplementedError("Volume source space for subject other than fsaverage") if special == 'brainstem': name = 'brainstem' voi = ['Brain-Stem', '3rd-Ventricle'] voi_lat = ('Thalamus-Proper', 'VentralDC') remove_midline = False elif special == 'cortex': name = 'cortex' voi = [] voi_lat = ('Cerebral-Cortex',) remove_midline = True elif special == '': name = 'cortex' voi = [] voi_lat = ('Cerebral-Cortex', 'Cerebral-White-Matter') remove_midline = True else: raise RuntimeError(f'src={src!r}') voi.extend('%s-%s' % fmt for fmt in product(('Left', 'Right'), voi_lat)) sss = mne.setup_volume_source_space( subject, pos=float(param), bem=bem, mri=join(self.get('mri-dir'), 'mri', 'aseg.mgz'), volume_label=voi, subjects_dir=self.get('mri-sdir')) sss = merge_volume_source_space(sss, name) sss = prune_volume_source_space(sss, int(param), 2, remove_midline=remove_midline) else: assert not special spacing = kind + param sss = mne.setup_source_space(subject, spacing=spacing, add_dist=True, subjects_dir=self.get('mri-sdir')) mne.write_source_spaces(dst, sss) def _test_kwargs(self, samples, pmin, tstart, tstop, data, parc_dim): "Compile kwargs for testnd tests" kwargs = {'samples': samples, 'tstart': tstart, 'tstop': tstop, 'parc': parc_dim} if pmin == 'tfce': kwargs['tfce'] = True elif pmin is not None: kwargs['pmin'] = pmin kwargs.update(self._cluster_criteria_kwargs(data)) return kwargs def _make_test(self, y, ds, test, kwargs, force_permutation=False): """Compute test results Parameters ---------- y : NDVar Dependent variable. ds : Dataset Other variables. test : Test | str Test, or name of the test to perform. kwargs : dict Test parameters (from :meth:`._test_kwargs`). force_permutation : bool Conduct permutations regardless of whether there are any clusters. """ test_obj = test if isinstance(test, Test) else self._tests[test] if not isinstance(test_obj, EvokedTest): raise RuntimeError("Test kind=%s" % test_obj.kind) return test_obj.make(y, ds, force_permutation, kwargs) def merge_bad_channels(self): """Merge bad channel definitions for different sessions Load the bad channel definitions for all sessions of the current subject and save the union for all sessions. See Also -------- make_bad_channels : set bad channels for a single session """ n_chars = max(map(len, self._sessions)) # collect bad channels bads = set() sessions = [] with self._temporary_state: # ICARaw merges bad channels dynamically, so explicit merge needs to # be performed lower in the hierarchy self.set(raw='raw') for session in self.iter('session'): if exists(self.get('raw-file')): bads.update(self.load_bad_channels()) sessions.append(session) else: print("%%-%is: skipping, raw file missing" % n_chars % session) # update bad channel files for session in sessions: print(session.ljust(n_chars), end=': ') self.make_bad_channels(bads, session=session) def next(self, field='subject'): """Change field to the next value Parameters ---------- field : str | list of str The field for which the value should be changed (default 'subject'). Can also contain multiple fields, e.g. ``['subject', 'session']``. """ if isinstance(field, str): current = self.get(field) values = self.get_field_values(field) def fmt(x): return x else: current = tuple(self.get(f) for f in field) values = list(product(*(self.get_field_values(f) for f in field))) def fmt(x): return '/'.join(x) # find the index of the next value if current in values: idx = values.index(current) + 1 if idx == len(values): idx = -1 else: for idx in range(len(values)): if values[idx] > current: break else: idx = -1 # set the next value if idx == -1: next_ = values[0] print(f"The last {fmt(field)} was reached; rewinding to {fmt(next_)}") else: next_ = values[idx] print(f"{fmt(field)}: {fmt(current)} -> {fmt(next_)}") if isinstance(field, str): self.set(**{field: next_}) else: self.set(**dict(zip(field, next_))) def plot_annot(self, parc=None, surf=None, views=None, hemi=None, borders=False, alpha=0.7, w=None, h=None, axw=None, axh=None, foreground=None, background=None, seeds=False, **state): """Plot the annot file on which the current parcellation is based Parameters ---------- parc : None | str Parcellation to plot. If None (default), use parc from the current state. surf : 'inflated' | 'pial' | 'smoothwm' | 'sphere' | 'white' Freesurfer surface to use as brain geometry. views : str | iterator of str View or views to show in the figure. hemi : 'lh' | 'rh' | 'both' | 'split' Which hemispheres to plot (default includes hemisphere with more than one label in the annot file). borders : bool | int Show only label borders (PySurfer Brain.add_annotation() argument). alpha : scalar Alpha of the annotation (1=opaque, 0=transparent, default 0.7). axw : int Figure width per hemisphere. foreground : mayavi color Figure foreground color (i.e., the text color). background : mayavi color Figure background color. seeds : bool Plot seeds as points (only applies to seeded parcellations). ... State parameters. Returns ------- brain : Brain PySurfer Brain with the parcellation plot. legend : ColorList ColorList figure with the legend. """ if parc is not None: state['parc'] = parc self.set(**state) self.make_annot() parc_name, parc = self._get_parc() if seeds: if not isinstance(parc, SeededParc): raise ValueError( "seeds=True is only valid for seeded parcellation, " "not for parc=%r" % (parc_name,)) # if seeds are defined on a scaled common-brain, we need to plot the # scaled brain: plot_on_scaled_common_brain = isinstance(parc, IndividualSeededParc) else: plot_on_scaled_common_brain = False mri_sdir = self.get('mri-sdir') if (not plot_on_scaled_common_brain) and is_fake_mri(self.get('mri-dir')): subject = self.get('common_brain') else: subject = self.get('mrisubject') kwa = self._surfer_plot_kwargs(surf, views, foreground, background, None, hemi) brain = plot.brain.annot(parc_name, subject, borders=borders, alpha=alpha, w=w, h=h, axw=axw, axh=axh, subjects_dir=mri_sdir, **kwa) if seeds: from mayavi import mlab seeds = parc.seeds_for_subject(subject) seed_points = {hemi: [np.atleast_2d(coords) for name, coords in seeds.items() if name.endswith(hemi)] for hemi in ('lh', 'rh')} plot_points = {hemi: np.vstack(points).T if len(points) else None for hemi, points in seed_points.items()} for hemisphere in brain.brains: if plot_points[hemisphere.hemi] is None: continue x, y, z = plot_points[hemisphere.hemi] mlab.points3d(x, y, z, figure=hemisphere._f, color=(1, 0, 0), scale_factor=10) brain.set_parallel_view(scale=True) return brain def plot_brain(self, common_brain=True, **brain_kwargs): """Plot the brain model Parameters ---------- common_brain : bool If the current mrisubject is a scaled MRI, use the common_brain instead. ... : :class:`~plot._brain_object.Brain` options as keyword arguments. """ from ..plot._brain_object import Brain brain_args = self._surfer_plot_kwargs() brain_args.update(brain_kwargs) brain_args['subjects_dir'] = self.get('mri-sdir') # find subject if common_brain and is_fake_mri(self.get('mri-dir')): mrisubject = self.get('common_brain') self.set(mrisubject=mrisubject, match=False) else: mrisubject = self.get('mrisubject') return Brain(mrisubject, **brain_args) def plot_coreg(self, dig=True, parallel=True, **state): """Plot the coregistration (Head shape and MEG helmet) Parameters ---------- dig : bool Plot the digitization points (default True; 'fiducials' to plot fiducial points only). parallel : bool Set parallel view. ... State parameters. Notes ----- Uses :func:`mne.viz.plot_alignment` """ self.set(**state) with self._temporary_state: raw = self.load_raw(raw='raw') fig = mne.viz.plot_alignment( raw.info, self.get('trans-file'), self.get('mrisubject'), self.get('mri-sdir'), meg=('helmet', 'sensors'), dig=dig, interaction='terrain') if parallel: fig.scene.camera.parallel_projection = True fig.scene.camera.parallel_scale = .2 fig.scene.camera.position = [0, .5, .04] fig.scene.camera.focal_point = [0, 0, .04] fig.render() return fig def plot_whitened_gfp(self, s_start=None, s_stop=None, run=None): """Plot the GFP of the whitened evoked to evaluate the the covariance matrix Parameters ---------- s_start : str Subject at which to start (default is the first subject). s_stop: str Subject at which to stop (default is the last subject). run : bool Run the GUI after plotting (default depends on environment). """ gfps = [] subjects = [] with self._temporary_state: self.set(model='') for subject in self.iter_range(s_start, s_stop): cov = self.load_cov() picks = np.arange(len(cov.ch_names)) ds = self.load_evoked(baseline=True) whitened_evoked = mne.whiten_evoked(ds[0, 'evoked'], cov, picks) gfp = whitened_evoked.data.std(0) gfps.append(gfp) subjects.append(subject) colors = plot.colors_for_oneway(subjects) title = "Whitened Global Field Power (%s)" % self.get('cov') fig = plot._base.Figure(1, title, h=7, run=run) ax = fig._axes[0] for subject, gfp in zip(subjects, gfps): ax.plot(whitened_evoked.times, gfp, label=subject, color=colors[subject]) ax.legend(loc='right') fig.show() return fig def plot_evoked(self, subjects=None, separate=False, baseline=True, ylim='same', run=None, **kwargs): """Plot evoked sensor data Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). separate : bool When plotting a group, plot all subjects separately instead or the group average (default False). baseline : bool | tuple Apply baseline correction using this period. True to use the epoch's baseline specification (default). ylim : 'same' | 'different' Use the same or different y-axis limits for different subjects (default 'same'). run : bool Run the GUI after plotting (default in accordance with plotting default). ... State parameters. """ subject, group = self._process_subject_arg(subjects, kwargs) model = self.get('model') or None epoch = self.get('epoch') if model: model_name = f"~{model}" elif subject or separate: model_name = "Average" else: model_name = "Grand Average" if subject: ds = self.load_evoked(baseline=baseline) y = guess_y(ds) title = f"{subject} {epoch} {model_name}" return plot.TopoButterfly(y, model, ds=ds, title=title, run=run) elif separate: plots = [] vlim = [] for subject in self.iter(group=group): ds = self.load_evoked(baseline=baseline) y = guess_y(ds) title = f"{subject} {epoch} {model_name}" p = plot.TopoButterfly(y, model, ds=ds, title=title, run=False) plots.append(p) vlim.append(p.get_vlim()) if ylim.startswith('s'): vlim = np.array(vlim) vmax = np.abs(vlim, out=vlim).max() for p in plots: p.set_vlim(vmax) elif not ylim.startswith('d'): raise ValueError("ylim=%s" % repr(ylim)) if run or plot._base.do_autorun(): gui.run() else: ds = self.load_evoked(group, baseline=baseline) y = guess_y(ds) title = f"{group} {epoch} {model_name}" return plot.TopoButterfly(y, model, ds=ds, title=title, run=run) def plot_label(self, label, surf=None, views=None, w=600): """Plot a label""" if isinstance(label, str): label = self.load_label(label) title = label.name hemi = 'split' if isinstance(label, mne.BiHemiLabel) else label.hemi kwargs = self._surfer_plot_kwargs(surf, views, hemi=hemi) brain = self.plot_brain(title=title, w=w, **kwargs) brain.add_label(label, alpha=0.75) return brain def plot_raw(self, decim=10, xlim=5, add_bads=True, subtract_mean=False, **state): """Plot raw sensor data Parameters ---------- decim : int Decimate data for faster plotting (default 10). xlim : scalar Number of seconds to display (default 5 s). add_bads : bool | list Add bad channel information to the bad channels text file (default True). subtract_mean : bool Subtract the mean from each channel (useful when plotting raw data recorded with DC offset). ... State parameters. """ raw = self.load_raw(add_bads, ndvar=True, decim=decim, **state) name = self.format("{subject} {recording} {raw}") if raw.info['meas'] == 'V': vmax = 1.5e-4 elif raw.info['meas'] == 'B': vmax = 2e-12 else: vmax = None if subtract_mean: raw -= raw.mean('time') return plot.TopoButterfly(raw, w=0, h=3, xlim=xlim, vmax=vmax, name=name) def run_mne_analyze(self, modal=False): """Run mne_analyze Parameters ---------- modal : bool Causes the shell to block until mne_analyze is closed. Notes ----- Sets the current directory to raw-dir, and sets the SUBJECT and SUBJECTS_DIR to current values """ subp.run_mne_analyze(self.get('raw-dir'), self.get('mrisubject'), self.get('mri-sdir'), modal) def run_mne_browse_raw(self, modal=False): """Run mne_analyze Parameters ---------- modal : bool Causes the shell to block until mne_browse_raw is closed. Notes ----- Sets the current directory to raw-dir, and sets the SUBJECT and SUBJECTS_DIR to current values """ subp.run_mne_browse_raw(self.get('raw-dir'), self.get('mrisubject'), self.get('mri-sdir'), modal) def set(self, subject=None, match=True, allow_asterisk=False, **state): """ Set variable values. Parameters ---------- subject : str Set the `subject` value. The corresponding `mrisubject` is automatically set to the corresponding mri subject. match : bool For fields with pre-defined values, only allow valid values (default ``True``). allow_asterisk : bool If a value contains ``'*'``, set the value without the normal value evaluation and checking mechanisms (default ``False``). ... State parameters. """ if subject is not None: if 'group' not in state: state['subject'] = subject subject = None FileTree.set(self, match, allow_asterisk, **state) if subject is not None: FileTree.set(self, match, allow_asterisk, subject=subject) def _post_set_group(self, _, group): if group == '*' or group not in self._groups: return group_members = self._groups[group] self._field_values['subject'] = group_members subject = self.get('subject') if subject != '*' and subject not in group_members and group_members: self.set(group_members[0]) def set_inv(self, ori='free', snr=3, method='dSPM', depth=None, pick_normal=False): """Set the type of inverse solution used for source estimation Parameters ---------- ori : 'free' | 'fixed' | 'vec' | float (0, 1) Orientation constraint (default ``'free'``; use a ``float`` to specify a loose orientation constraint). At each source point, ... - ``free``: ... estimate a current dipole with arbitrary direction. For further analysis, only the magnitude of the current is retained, while the direction is ignored. This is good for detecting changes in neural current strength when current direction is variable (for example, due to anatomical differences between subjects). - ``fixed``: ... estimate current flow orthogonal to the cortical surface. The sign of the estimates indicates current direction relative to the surface (positive for current out of the brain). - ``vec``: ... estimate a current vector with arbitrary direction, and return this current as 3 dimensional vector. - loose (``float``): ... estimate a current dipole with arbitrary direction. Then, multiple the two components parallel to the surface with this number, and retain the magnitude. snr : scalar SNR estimate used for regularization (default 3; the general recommendation is 3 for averaged responses, and 1 for raw or single trial data). method : 'MNE' | 'dSPM' | 'sLORETA' | 'eLORETA' Noise normalization method. ``MNE`` uses unnormalized current estimates. ``dSPM`` [1]_ (default) ``sLORETA`` [2]_ and eLORETA [3]_ normalize each the estimate at each source with an estimate of the noise at that source (default ``'dSPM'``). depth : None | float [0, 1] Depth weighting [4]_ (default ``None`` to use mne default 0.8; ``0`` to disable depth weighting). pick_normal : bool Estimate a free orientation current vector, then pick the component orthogonal to the cortical surface and discard the parallel components. References ---------- .. [1] Dale A, Liu A, Fischl B, Buckner R. (2000) Dynamic statistical parametric mapping: combining fMRI and MEG for high-resolution imaging of cortical activity. Neuron, 26:55-67. `10.1016/S0896-6273(00)81138-1 <https://doi.org/10.1016/S0896-6273(00)81138-1>`_ .. [2] Pascual-Marqui RD (2002), Standardized low resolution brain electromagnetic tomography (sLORETA): technical details. Methods Find. Exp. Clin. Pharmacology, 24(D):5-12. .. [3] Pascual-Marqui RD (2007). Discrete, 3D distributed, linear imaging methods of electric neuronal activity. Part 1: exact, zero error localization. `arXiv:0710.3341 <https://arxiv.org/abs/0710.3341>`_ .. [4] Lin F, Witzel T, Ahlfors S P, Stufflebeam S M, Belliveau J W, Hämäläinen M S. (2006) Assessing and improving the spatial accuracy in MEG source localization by depth-weighted minimum-norm estimates. NeuroImage, 31(1):160–171. `10.1016/j.neuroimage.2005.11.054 <https://doi.org/10.1016/j.neuroimage.2005.11.054>`_ """ self.set(inv=self._inv_str(ori, snr, method, depth, pick_normal)) @staticmethod def _inv_str(ori, snr, method, depth, pick_normal): "Construct inv str from settings" if isinstance(ori, str): if ori not in ('free', 'fixed', 'vec'): raise ValueError(f'ori={ori!r}') elif not 0 < ori < 1: raise ValueError(f"ori={ori!r}; must be in range (0, 1)") else: ori = f'loose{str(ori)[1:]}' if snr <= 0: raise ValueError(f"snr={snr!r}") if method not in INV_METHODS: raise ValueError(f"method={method!r}") items = [ori, f'{snr:g}', method] if depth is None: pass elif not 0 <= depth <= 1: raise ValueError(f"depth={depth!r}; must be in range [0, 1]") else: items.append(f'{depth:g}') if pick_normal: if ori in ('vec', 'fixed'): raise ValueError(f"ori={ori!r} and pick_normal=True are incompatible") items.append('pick_normal') return '-'.join(items) @staticmethod def _parse_inv(inv): "(ori, snr, method, depth, pick_normal)" m = inv_re.match(inv) if m is None: raise ValueError(f"inv={inv!r}: invalid inverse specification") ori, snr, method, depth, pick_normal = m.groups() if ori.startswith('loose'): ori = float(ori[5:]) if not 0 < ori < 1: raise ValueError(f"inv={inv!r}: loose parameter needs to be in range (0, 1)") elif pick_normal and ori in ('vec', 'fixed'): raise ValueError(f"inv={inv!r}: {ori} incompatible with pick_normal") snr = float(snr) if snr <= 0: raise ValueError(f"inv={inv!r}: snr={snr!r}") if method not in INV_METHODS: raise ValueError(f"inv={inv!r}: method={method!r}") if depth is not None: depth = float(depth) if not 0 <= depth <= 1: raise ValueError(f"inv={inv!r}: depth={depth!r}, needs to be in range [0, 1]") return ori, snr, method, depth, bool(pick_normal) @classmethod def _eval_inv(cls, inv): cls._parse_inv(inv) return inv def _update_inv_cache(self, fields): if fields['inv'] == '*': return '*' m = inv_re.match(fields['inv']) ori, snr, method, depth, pick_normal = m.groups() if depth: return f'{ori}-{depth}' else: return ori def _post_set_inv(self, _, inv): if '*' in inv: self._params['make_inv_kw'] = None self._params['apply_inv_kw'] = None return ori, snr, method, depth, pick_normal = self._parse_inv(inv) if ori == 'fixed': make_kw = {'fixed': True} elif ori == 'free' or ori == 'vec': make_kw = {'loose': 1} elif isinstance(ori, float): make_kw = {'loose': ori} else: raise RuntimeError("ori=%r (in inv=%r)" % (ori, inv)) if depth is None: make_kw['depth'] = 0.8 elif depth == 0: make_kw['depth'] = None else: make_kw['depth'] = depth apply_kw = {'method': method, 'lambda2': 1. / snr ** 2} if ori == 'vec': apply_kw['pick_ori'] = 'vector' elif pick_normal: apply_kw['pick_ori'] = 'normal' self._params['make_inv_kw'] = make_kw self._params['apply_inv_kw'] = apply_kw def _eval_model(self, model): if model == '': return model elif len(model) > 1 and '*' in model: raise ValueError("model=%r; To specify interactions, use '%' instead of '*'") factors = [v.strip() for v in model.split('%')] # find order value for each factor ordered_factors = {} unordered_factors = [] for factor in sorted(factors): assert_is_legal_dataset_key(factor) if factor in self._model_order: ordered_factors[self._model_order.index(factor)] = factor else: unordered_factors.append(factor) # recompose model = [ordered_factors[v] for v in sorted(ordered_factors)] if unordered_factors: model.extend(unordered_factors) return '%'.join(model) def _eval_src(self, src): m = SRC_RE.match(src) if not m: raise ValueError(f'src={src}') kind, param, special = m.groups() if special and kind != 'vol': raise ValueError(f'src={src}') return src def _update_mrisubject(self, fields): subject = fields['subject'] mri = fields['mri'] if subject == '*' or mri == '*': return '*' return self._mri_subjects[mri][subject] def _update_session(self, fields): epoch = fields['epoch'] if epoch in self._epochs: epoch = self._epochs[epoch] if isinstance(epoch, (PrimaryEpoch, SecondaryEpoch)): return epoch.session else: return # default for non-primary epoch elif not epoch or epoch == '*': return # don't force session return '*' # if a named epoch is not in _epochs it might be a removed epoch def _update_src_name(self, fields): "Because 'ico-4' is treated in filenames as ''" return '' if fields['src'] == 'ico-4' else fields['src'] def _eval_parc(self, parc): if parc in self._parcs: if isinstance(self._parcs[parc], SeededParc): raise ValueError("Seeded parc set without size, use e.g. " "parc='%s-25'" % parc) else: return parc m = SEEDED_PARC_RE.match(parc) if m: name = m.group(1) if isinstance(self._parcs.get(name), SeededParc): return parc else: raise ValueError("No seeded parc with name %r" % name) else: raise ValueError("parc=%r" % parc) def _get_parc(self): """Parc information Returns ------- parc : str The current parc setting. params : dict | None The parc definition (``None`` for ``parc=''``). """ parc = self.get('parc') if parc == '': return '', None elif parc in self._parcs: return parc, self._parcs[parc] else: return parc, self._parcs[SEEDED_PARC_RE.match(parc).group(1)] def _post_set_test(self, _, test): if test != '*' and test in self._tests: # with vmatch=False, test object might not be availale test_obj = self._tests[test] if test_obj.model is not None: self.set(model=test_obj._within_model) def _set_analysis_options(self, data, baseline, src_baseline, pmin, tstart, tstop, parc=None, mask=None, decim=None, test_options=(), folder_options=()): """Set templates for paths with test parameters analysis: preprocessing up to source estimate epochs (not parcellation) folder: parcellation (human readable) test_dims: parcellation (as used for spatio-temporal cluster test test_options: baseline, permutation test method etc. also sets `parc` Parameters ---------- data : TestDims Whether the analysis is in sensor or source space. ... src_baseline : Should be False if data=='sensor'. ... decim : int Decimation factor (default is None, i.e. based on epochs). test_options : sequence of str Additional, test-specific tags (for use by TRFExperiment only). """ data = TestDims.coerce(data) # data kind (sensor or source space) if data.sensor: analysis = '{sns_kind} {evoked_kind}' elif data.source: analysis = '{src_kind} {evoked_kind}' else: raise RuntimeError(f"data={data.string!r}") # determine report folder (reports) and test_dims (test-files) kwargs = {'test_dims': data.string} if data.source is True: if parc is None: if mask: folder = "%s masked" % mask kwargs['parc'] = mask if pmin is None: # When not doing clustering, parc does not affect # results, so we don't need to distinguish parc and mask kwargs['test_dims'] = mask else: # parc means disconnecting kwargs['test_dims'] = '%s-mask' % mask else: folder = "Whole Brain" # only compute unmasked test once (probably rare anyways) kwargs['parc'] = 'aparc' kwargs['test_dims'] = 'unmasked' elif mask: raise ValueError("Can't specify mask together with parc") elif pmin is None or pmin == 'tfce': raise NotImplementedError( "Threshold-free test (pmin=%r) is not implemented for " "parcellation (parc parameter). Use a mask instead, or do " "a cluster-based test." % pmin) else: folder = parc kwargs['parc'] = parc kwargs['test_dims'] = parc elif data.source: # source-space ROIs if not parc: raise ValueError("Need parc for ROI definition") kwargs['parc'] = parc kwargs['test_dims'] = '%s.%s' % (parc, data.source) if data.source == 'mean': folder = f'{parc} ROIs' else: folder = f'{parc} {data.source}' elif parc: raise ValueError(f"Sensor analysis (data={data.string!r}) can't have parc") elif data.sensor: folder = 'Sensor' if data.y_name == 'meg' else 'EEG' if data.sensor is not True: folder = f'{folder} {data.sensor}' else: raise RuntimeError(f"data={data.string!r}") if folder_options: folder += ' ' + ' '.join(folder_options) # test properties items = [] # baseline (default is baseline correcting in sensor space) epoch_baseline = self._epochs[self.get('epoch')].baseline if src_baseline: assert data.source if baseline is True or baseline == epoch_baseline: items.append('snsbl') elif baseline: items.append('snsbl=%s' % _time_window_str(baseline)) if src_baseline is True or src_baseline == epoch_baseline: items.append('srcbl') else: items.append('srcbl=%s' % _time_window_str(src_baseline)) else: if not baseline: items.append('nobl') elif baseline is True or baseline == epoch_baseline: pass else: items.append('bl=%s' % _time_window_str(baseline)) # pmin if pmin is not None: # source connectivity connectivity = self.get('connectivity') if connectivity and not data.source: raise NotImplementedError(f"connectivity={connectivity!r} is not implemented for data={data!r}") elif connectivity: items.append(connectivity) items.append(str(pmin)) # cluster criteria if pmin != 'tfce': select_clusters = self.get('select_clusters') if select_clusters: items.append(select_clusters) # time window if tstart is not None or tstop is not None: items.append(_time_window_str((tstart, tstop))) if decim is not None: assert isinstance(decim, int) items.append(str(decim)) items.extend(test_options) self.set(test_options=' '.join(items), analysis=analysis, folder=folder, **kwargs) @staticmethod def _parse_test_options(test_options: FieldCode): code = FieldCode.coerce(test_options) out = {} # baseline if 'bl' in code.lookahead_1: out['baseline'] = code.next() if 'srcbl' in code.lookahead_1: out['baseline'] = (out['baseline'], code.next()) # connectivity if code.lookahead_1 == 'link-midline': out['connectivity'] = code.next() # pmin if code.lookahead_1 == 'tfce' or code.lookahead_1.startswith('0.'): out['pmin'] = code.next() # time-window if '-' in code.lookahead_1: out['time_window'] = code.next() # decim if code.lookahead_1.isdigit(): out['decim'] = code.next() return out def show_bad_channels(self, sessions=None, **state): """List bad channels Parameters ---------- sessions : True | sequence of str By default, bad channels for the current session are shown. Set ``sessions`` to ``True`` to show bad channels for all sessions, or a list of session names to show bad channeles for these sessions. ... State parameters. Notes ----- ICA Raw pipes merge bad channels from different sessions (by combining the bad channels from all sessions). """ if state: self.set(**state) if sessions is True: use_sessions = self._sessions elif sessions: use_sessions = sessions else: use_sessions = None if use_sessions is None: bad_by_s = {k: self.load_bad_channels() for k in self} list_sessions = False else: bad_channels = {k: self.load_bad_channels() for k in self.iter(('subject', 'session'), values={'session': use_sessions})} # whether they are equal between sessions bad_by_s = {} for (subject, session), bads in bad_channels.items(): if subject in bad_by_s: if bad_by_s[subject] != bads: list_sessions = True break else: bad_by_s[subject] = bads else: list_sessions = False # table session_desc = ', '.join(use_sessions) if use_sessions else self.get('session') caption = f"Bad channels in {session_desc}" if list_sessions: t = fmtxt.Table('l' * (1 + len(use_sessions)), caption=caption) t.cells('Subject', *use_sessions) t.midrule() for subject in sorted(bad_by_s): t.cell(subject) for session in use_sessions: t.cell(', '.join(bad_channels[subject, session])) else: if use_sessions is not None: caption += " (all sessions equal)" t = fmtxt.Table('ll', caption=caption) t.cells('Subject', 'Bad channels') t.midrule() for subject in sorted(bad_by_s): t.cells(subject, ', '.join(bad_by_s[subject])) return t def show_file_status(self, temp, col=None, row='subject', *args, **kwargs): """Compile a table about the existence of files Parameters ---------- temp : str The name of the path template for the files to examine. col : None | str Field over which to alternate columns (default is a single column). row : str Field over which to alternate rows (default 'subject'). count : bool Add a column with a number for each line (default True). present : 'time' | 'date' | str String to display when a given file is present. 'time' to use last modification date and time (default); 'date' for date only. absent : str String to display when a given file is absent (default '-'). ... : :meth:`MneExperiment.iter` parameters. Examples -------- >>> e.show_file_status('rej-file') Subject Rej-file ------------------------------- 0 A0005 07/22/15 13:03:08 1 A0008 07/22/15 13:07:57 2 A0028 07/22/15 13:22:04 3 A0048 07/22/15 13:25:29 >>> e.show_file_status('rej-file', 'raw') Subject 0-40 0.1-40 1-40 Clm --------------------------------------------------- 0 A0005 - 07/22/15 13:03:08 - - 1 A0008 - 07/22/15 13:07:57 - - 2 A0028 - 07/22/15 13:22:04 - - 3 A0048 - 07/22/15 13:25:29 - - """ return FileTree.show_file_status(self, temp, row, col, *args, **kwargs) def show_raw_info(self, **state): "Display the selected pipeline for raw processing" raw = self.get('raw', **state) pipe = source_pipe = self._raw[raw] pipeline = [pipe] while source_pipe.name != 'raw': source_pipe = source_pipe.source pipeline.insert(0, source_pipe) print(f"Preprocessing pipeline: {" --> ".join(p.name for p in pipeline)}") # pipe-specific if isinstance(pipe, RawICA): table = fmtxt.Table('lrr') table.cells('Subject', 'n components', 'reject') table.midrule() for subject in self: table.cell(subject) filename = self.get('ica-file') if exists(filename): ica = self.load_ica() table.cells(ica.n_components_, len(ica.exclude)) else: table.cells("No ICA-file", '') print() print(table) def show_reg_params(self, asds=False, **kwargs): """Show the covariance matrix regularization parameters Parameters ---------- asds : bool Return a dataset with the parameters (default False). ... State parameters. """ if kwargs: self.set(**kwargs) subjects = [] reg = [] for subject in self: path = self.get('cov-info-file') if exists(path): with open(path, 'r') as fid: text = fid.read() reg.append(float(text.strip())) else: reg.append(float('nan')) subjects.append(subject) ds = Dataset() ds['subject'] = Factor(subjects) ds['reg'] = Var(reg) if asds: return ds else: print(ds) def show_rej_info(self, flagp=None, asds=False, bads=False, **state): """Information about artifact rejection Parameters ---------- flagp : scalar Flag entries whose percentage of good trials is lower than this number. asds : bool Return a Dataset with the information (default is to print it). bads : bool Display bad channel names (not just number of bad channels). Notes ----- To display the number of components rejected of an ICA raw pipe, use :meth:`~MneExperiment.show_raw_info`. """ # TODO: include ICA raw preprocessing pipes if state: self.set(**state) raw_name = self.get('raw') epoch_name = self.get('epoch') rej_name = self.get('rej') rej = self._artifact_rejection[rej_name] has_epoch_rejection = rej['kind'] is not None has_interp = rej.get('interpolation') subjects = [] n_events = [] n_good = [] bad_chs = [] n_interp = [] for subject in self: subjects.append(subject) bads_raw = self.load_bad_channels() try: ds = self.load_selected_events(reject='keep') except FileMissing: ds = self.load_selected_events(reject=False) bad_chs.append((bads_raw, ())) if has_epoch_rejection: n_good.append(float('nan')) if has_interp: n_interp.append(float('nan')) else: bads_rej = set(ds.info[BAD_CHANNELS]).difference(bads_raw) bad_chs.append((bads_raw, bads_rej)) if has_epoch_rejection: n_good.append(ds['accept'].sum()) if has_interp: n_interp.append(np.mean([len(chi) for chi in ds[INTERPOLATE_CHANNELS]])) n_events.append(ds.n_cases) has_interp = has_interp and any(n_interp) caption = f"Rejection info for raw={raw_name}, epoch={epoch_name}, rej={rej_name}. Percent is rounded to one decimal." # format bad channels if bads: func = ', '.join else: func = len bad_chs = [(func(bads_raw), func(bads_rej)) for bads_raw, bads_rej in bad_chs] if any(bads_rej for bads_raw, bads_rej in bad_chs): caption += " Bad channels: defined in bad_channels file and in rej-file." bad_chs = [f'{bads_raw} + {bads_rej}' for bads_raw, bads_rej in bad_chs] else: bad_chs = [f'{bads_raw}' for bads_raw, bads_rej in bad_chs] if bads: bad_chs = [s.replace('MEG ', '') for s in bad_chs] if has_interp: caption += " ch_interp: average number of channels interpolated per epoch, rounded to one decimal." out = Dataset(caption=caption) out['subject'] = Factor(subjects) out['n_events'] = Var(n_events) if has_epoch_rejection: out['n_good'] = Var(n_good) out['percent'] = Var(np.round(100 * out['n_good'] / out['n_events'], 1)) if flagp: out['flag'] = Factor(out['percent'] < flagp, labels={False: '', True: '*'}) out['bad_channels'] = Factor(bad_chs) if has_interp: out['ch_interp'] = Var(np.round(n_interp, 1)) if asds: return out else: print(out) def show_subjects(self, mri=True, mrisubject=False, caption=True, asds=False, **state): """Create a Dataset with subject information Parameters ---------- mri : bool Add a column specifying whether the subject is using a scaled MRI or whether it has its own MRI. mrisubject : bool Add a column showing the MRI subject corresponding to each subject. caption : bool | str Caption for the table (For True, use the default "Subject in group {group}". asds : bool Return the table as Dataset instead of an FMTxt Table. ... State parameters. """ if isinstance(mri, str): state['mri'] = mri mri = True if state: self.set(**state) # caption if caption is True: caption = self.format("Subjects in group {group}") subject_list = [] mri_list = [] mrisubject_list = [] for subject in self.iter(): subject_list.append(subject) mrisubject_ = self.get('mrisubject') mrisubject_list.append(mrisubject_) if mri: mri_dir = self.get('mri-dir') if not exists(mri_dir): mri_list.append('*missing') elif is_fake_mri(mri_dir): mri_sdir = self.get('mri-sdir') info = mne.coreg.read_mri_cfg(mrisubject_, mri_sdir) cell = "%s * %s" % (info['subject_from'], str(info['scale'])) mri_list.append(cell) else: mri_list.append(mrisubject_) ds = Dataset(caption=caption) ds['subject'] = Factor(subject_list) if mri: ds['mri'] = Factor(mri_list) if mrisubject: ds['mrisubject'] = Factor(mrisubject_list) if asds: return ds else: return ds.as_table(midrule=True, count=True) def show_input_tree(self): """Print a tree of the files needed as input See Also -------- show_tree: show complete tree (including secondary, optional and cache) """ return self.show_tree(fields=['raw-file', 'trans-file', 'mri-dir']) def _surfer_plot_kwargs(self, surf=None, views=None, foreground=None, background=None, smoothing_steps=None, hemi=None): out = self._brain_plot_defaults.copy() out.update(self.brain_plot_defaults) if views: out['views'] = views else: parc, p = self._get_parc() if p is not None and p.views: out['views'] = p.views if surf: out['surf'] = surf if foreground: out['foreground'] = foreground if background: out['background'] = background if smoothing_steps: out['smoothing_steps'] = smoothing_steps if hemi: out['hemi'] = hemi return out
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu> """MneExperiment class to manage data from a experiment For testing purposed, set up an experiment class without checking for data: MneExperiment.auto_delete_cache = 'disable' MneExperiment.sessions = ('session',) e = MneExperiment('.', find_subjects=False) """ from collections import defaultdict, Sequence from copy import deepcopy from datetime import datetime from glob import glob import inspect from itertools import chain, product import logging import os from os.path import basename, exists, getmtime, isdir, join, relpath from pathlib import Path import re import shutil import time from typing import Union import warnings import numpy as np from tqdm import tqdm import mne from mne.baseline import rescale from mne.minimum_norm import make_inverse_operator, apply_inverse, apply_inverse_epochs from .. import _report from .. import fmtxt from .. import gui from .. import load from .. import plot from .. import save from .. import table from .. import testnd from .._data_obj import ( Datalist, Dataset, Factor, Var, SourceSpace, VolumeSourceSpace, align1, all_equal, assert_is_legal_dataset_key, combine) from .._exceptions import DefinitionError, DimensionMismatchError, OldVersionError from .._info import BAD_CHANNELS from .._io.pickle import update_subjects_dir from .._names import INTERPOLATE_CHANNELS from .._meeg import new_rejection_ds from .._mne import ( dissolve_label, labels_from_mni_coords, rename_label, combination_label, morph_source_space, shift_mne_epoch_trigger, find_source_subject, label_from_annot, ) from ..mne_fixes import ( write_labels_to_annot, _interpolate_bads_eeg, _interpolate_bads_meg) from ..mne_fixes._trans import hsp_equal, mrk_equal from ..mne_fixes._source_space import merge_volume_source_space, prune_volume_source_space from .._ndvar import concatenate, cwt_morlet, neighbor_correlation from ..fmtxt import List, Report, Image, read_meta from .._stats.stats import ttest_t from .._stats.testnd import _MergedTemporalClusterDist from .._text import enumeration, plural from .._utils import IS_WINDOWS, ask, subp, keydefaultdict, log_level, ScreenHandler from .._utils.mne_utils import fix_annot_names, is_fake_mri from .definitions import FieldCode, find_dependent_epochs, find_epochs_vars, log_dict_change, log_list_change from .epochs import PrimaryEpoch, SecondaryEpoch, SuperEpoch, EpochCollection, assemble_epochs, decim_param from .exceptions import FileDeficient, FileMissing from .experiment import FileTree from .groups import assemble_groups from .parc import ( assemble_parcs, FS_PARC, FSA_PARC, SEEDED_PARC_RE, CombinationParc, EelbrainParc, FreeSurferParc, FSAverageParc, SeededParc, IndividualSeededParc, LabelParc ) from .preprocessing import ( assemble_pipeline, RawSource, RawFilter, RawICA, compare_pipelines, ask_to_delete_ica_files) from .test_def import ( Test, EvokedTest, ROITestResult, ROI2StageResult, TestDims, TwoStageTest, assemble_tests, find_test_vars, ) from .variable_def import Variables # current cache state version CACHE_STATE_VERSION = 12 # History: # 10: input_state: share forward-solutions between sessions # 11: add samplingrate to epochs # 12: store test-vars as Variables object # paths LOG_FILE = join('{root}', 'eelbrain {name}.log') LOG_FILE_OLD = join('{root}', '.eelbrain.log') # Allowable parameters COV_PARAMS = {'epoch', 'session', 'method', 'reg', 'keep_sample_mean', 'reg_eval_win_pad'} INV_METHODS = ('MNE', 'dSPM', 'sLORETA', 'eLORETA') SRC_RE = re.compile(r'^(ico|vol)-(\d+)(?:-(cortex|brainstem))?$') inv_re = re.compile(r"^" r"(free|fixed|loose\.\d+|vec)-" # orientation constraint r"(\d*\.?\d+)-" # SNR rf"({'|'.join(INV_METHODS)})" # method r"(?:-((?:0\.)?\d+))?" # depth weighting r"(?:-(pick_normal))?" r"$") # pick normal # Eelbrain 0.24 raw/preprocessing pipeline LEGACY_RAW = { '0-40': RawFilter('raw', None, 40, method='iir'), '0.1-40': RawFilter('raw', 0.1, 40, l_trans_bandwidth=0.08, filter_length='60s'), '0.2-40': RawFilter('raw', 0.2, 40, l_trans_bandwidth=0.08, filter_length='60s'), '1-40': RawFilter('raw', 1, 40, method='iir'), } CACHE_HELP = "A change in the {experiment} class definition (or the input files) means that some {filetype} files no longer reflect the current definition. In order to keep local results consistent with the definition, these files should be deleted. If you want to keep a copy of the results, be sure to move them to a different location before proceding. If you think the change in the definition was a mistake, you can select 'abort', revert the change and try again." ################################################################################ def _mask_ndvar(ds, name): y = ds[name] if y.source.parc is None: raise RuntimeError('%r has no parcellation' % (y,)) mask = y.source.parc.startswith('unknown') if mask.any(): ds[name] = y.sub(source=np.invert(mask)) def _time_str(t): "String for representing a time value" if t is None: return '' else: return '%i' % round(t * 1000) def _time_window_str(window, delim='-'): "String for representing a time window" return delim.join(map(_time_str, window)) def guess_y(ds, default=None): "Given a dataset, guess the dependent variable" for y in ('srcm', 'src', 'meg', 'eeg'): if y in ds: return y if default is not None: return default raise RuntimeError(r"Could not find data in {ds}") class DictSet: """Helper class for list of dicts without duplicates""" def __init__(self): self._list = [] def __repr__(self): return "DictSet(%s)" % self._list def __iter__(self): return self._list.__iter__() def add(self, item): if item not in self._list: self._list.append(item) def update(self, items): for item in items: self.add(item) class CacheDict(dict): def __init__(self, func, key_vars, *args): super(CacheDict, self).__init__() self._func = func self._key_vars = key_vars self._args = args def __getitem__(self, key): if key in self: return dict.__getitem__(self, key) if isinstance(key, str): out = self._func(*self._args, **{self._key_vars: key}) else: out = self._func(*self._args, **dict(zip(self._key_vars, key))) self[key] = out return out def cache_valid(mtime, *source_mtimes): "Determine whether mtime is up-to-date" return ( mtime is not None and all(t is not None for t in source_mtimes) and mtime > max(source_mtimes)) temp = { # MEG 'equalize_evoked_count': ('', 'eq'), # locations 'raw-sdir': join('{root}', 'meg'), 'raw-dir': join('{raw-sdir}', '{subject}'), # raw input files 'trans-file': join('{raw-dir}', '{mrisubject_visit}-trans.fif'), # log-files (eye-tracker etc.) 'log-dir': join('{raw-dir}', 'logs'), 'edf-file': join('{log-dir}', '*.edf'), # created input files 'ica-file': join('{raw-dir}', '{subject_visit} {raw}-ica.fif'), # hard-coded in RawICA 'rej-dir': join('{raw-dir}', 'epoch selection'), 'rej-file': join('{rej-dir}', '{session}_{sns_kind}_{epoch_visit}-{rej}.pickled'), # cache 'cache-dir': join('{root}', 'eelbrain-cache'), # raw 'raw-cache-dir': join('{cache-dir}', 'raw', '{subject}'), 'raw-cache-base': join('{raw-cache-dir}', '{recording} {raw}'), 'cached-raw-file': '{raw-cache-base}-raw.fif', 'event-file': '{raw-cache-base}-evts.pickled', 'interp-file': '{raw-cache-base}-interp.pickled', 'cached-raw-log-file': '{raw-cache-base}-raw.log', # forward modeling: 'fwd-file': join('{raw-cache-dir}', '{recording}-{mrisubject}-{src}-fwd.fif'), # sensor covariance 'cov-dir': join('{cache-dir}', 'cov'), 'cov-base': join('{cov-dir}', '{subject_visit}', '{sns_kind} {cov}-{rej}'), 'cov-file': '{cov-base}-cov.fif', 'cov-info-file': '{cov-base}-info.txt', # inverse solution 'inv-file': join('{raw-cache-dir}', 'inv', '{mrisubject} {src} {recording} {sns_kind} {cov} {rej} {inv-cache}-inv.fif'), # evoked 'evoked-dir': join('{cache-dir}', 'evoked'), 'evoked-file': join('{evoked-dir}', '{subject}', '{sns_kind} {epoch_visit} {model} {evoked_kind}-ave.fif'), # test files 'test-dir': join('{cache-dir}', 'test'), 'test-file': join('{test-dir}', '{analysis} {group}', '{test_desc} {test_dims}.pickled'), # MRIs 'common_brain': 'fsaverage', # MRI base files 'mri-sdir': join('{root}', 'mri'), 'mri-dir': join('{mri-sdir}', '{mrisubject}'), 'bem-dir': join('{mri-dir}', 'bem'), 'mri-cfg-file': join('{mri-dir}', 'MRI scaling parameters.cfg'), 'mri-file': join('{mri-dir}', 'mri', 'orig.mgz'), 'bem-file': join('{bem-dir}', '{mrisubject}-inner_skull-bem.fif'), 'bem-sol-file': join('{bem-dir}', '{mrisubject}-*-bem-sol.fif'), # removed for 0.24 'head-bem-file': join('{bem-dir}', '{mrisubject}-head.fif'), 'src-file': join('{bem-dir}', '{mrisubject}-{src}-src.fif'), 'fiducials-file': join('{bem-dir}', '{mrisubject}-fiducials.fif'), # Labels 'hemi': ('lh', 'rh'), 'label-dir': join('{mri-dir}', 'label'), 'annot-file': join('{label-dir}', '{hemi}.{parc}.annot'), # (method) plots 'methods-dir': join('{root}', 'methods'), # result output files # data processing parameters # > group # > kind of test # > single-subject # > kind of test # > subject 'res-dir': join('{root}', 'results'), 'res-file': join('{res-dir}', '{analysis}', '{resname}.{ext}'), 'res-deep-file': join('{res-dir}', '{analysis}', '{folder}', '{resname}.{ext}'), 'report-file': join('{res-dir}', '{analysis} {group}', '{folder}', '{test_desc}.html'), 'group-mov-file': join('{res-dir}', '{analysis} {group}', '{epoch_visit} {test_options} {resname}.mov'), 'subject-res-dir': join('{res-dir}', '{analysis} subjects'), 'subject-spm-report': join('{subject-res-dir}', '{test} {epoch_visit} {test_options}', '{subject}.html'), 'subject-mov-file': join('{subject-res-dir}', '{epoch_visit} {test_options} {resname}', '{subject}.mov'), # plots # plot corresponding to a report (and using same folder structure) 'res-plot-root': join('{root}', 'result plots'), 'res-plot-dir': join('{res-plot-root}', '{analysis} {group}', '{folder}', '{test_desc}'), # besa 'besa-root': join('{root}', 'besa'), 'besa-trig': join('{besa-root}', '{subject}', '{subject}_{recording}_{epoch_visit}_triggers.txt'), 'besa-evt': join('{besa-root}', '{subject}', '{subject}_{recording}_{epoch_visit}[{rej}].evt'), # MRAT 'mrat_condition': '', 'mrat-root': join('{root}', 'mrat'), 'mrat-sns-root': join('{mrat-root}', '{sns_kind}', '{epoch_visit} {model} {evoked_kind}'), 'mrat-src-root': join('{mrat-root}', '{src_kind}', '{epoch_visit} {model} {evoked_kind}'), 'mrat-sns-file': join('{mrat-sns-root}', '{mrat_condition}', '{mrat_condition}_{subject}-ave.fif'), 'mrat_info-file': join('{mrat-root}', '{subject} info.txt'), 'mrat-src-file': join('{mrat-src-root}', '{mrat_condition}', '{mrat_condition}_{subject}'), } class MneExperiment(FileTree): """Analyze an MEG experiment (gradiometer only) with MNE Parameters ---------- root : str | None the root directory for the experiment (usually the directory containing the 'meg' and 'mri' directories). The experiment can be initialized without the root for testing purposes. find_subjects : bool Automatically look for subjects in the MEG-directory (default True). Set ``find_subjects=False`` to initialize the experiment without any files. ... Initial state parameters. Notes ----- .. seealso:: Guide on using :ref:`experiment-class-guide`. """ _safe_delete = 'cache-dir' path_version = 2 screen_log_level = logging.INFO auto_delete_results = False auto_delete_cache = True # what to do when the experiment class definition changed: # True: delete outdated files # False: raise an error # 'disable': ignore it # 'debug': prompt with debug options cache_inv = True # Whether to cache inverse solution # moderate speed gain for loading source estimates (34 subjects: 20 vs 70 s) # hard drive space ~ 100 mb/file # tuple (if the experiment has multiple sessions) sessions = None visits = ('',) # Raw preprocessing pipeline raw = {} # add this value to all trigger times trigger_shift = 0 # variables for automatic labeling {name: {trigger: label, triggers: label}} variables = {} # Default values for epoch definitions epoch_default = {'decim': 5} # named epochs epochs = {} # Rejection # ========= # eog_sns: The sensors to plot separately in the rejection GUI. The default # is the two MEG sensors closest to the eyes. _eog_sns = {None: (), 'KIT-157': ('MEG 143', 'MEG 151'), 'KIT-208': ('MEG 087', 'MEG 130'), 'KIT-UMD-1': ('MEG 042', 'MEG 025'), 'KIT-UMD-2': ('MEG 042', 'MEG 025'), 'KIT-UMD-3': ('MEG 042', 'MEG 025'), 'KIT-BRAINVISION': ('HEOGL', 'HEOGR', 'VEOGb'), 'neuromag306mag': ('MEG 0121', 'MEG 1411')} # # artifact_rejection dict: # # kind : 'manual' | 'make' # How the rejection is derived: # 'manual': manually create a rejection file (use the selection GUI # through .make_epoch_selection()) # 'make' a rejection file is created by the user # interpolation : bool # enable by-epoch channel interpolation # # For manual rejection # ^^^^^^^^^^^^^^^^^^^^ _artifact_rejection = { '': {'kind': None}, 'man': {'kind': 'manual', 'interpolation': True}, } artifact_rejection = {} exclude = {} # field_values to exclude (e.g. subjects) # groups can be defined as subject lists: {'group': ('member1', 'member2', ...)} # or by exclusion: {'group': {'base': 'all', 'exclude': ('member1', 'member2')}} groups = {} # whether to look for and load eye tracker data when loading raw files has_edf = defaultdict(lambda: False) # Pattern for subject names. The first group is used to determine what # MEG-system the data was recorded from subject_re = r'(R|S|A|Y|AD|QP)(\d{3,})$' # MEG-system (legacy variable). meg_system = None # kwargs for regularization of the covariance matrix (see .make_cov()) _covs = {'auto': {'epoch': 'cov', 'method': 'auto'}, 'bestreg': {'epoch': 'cov', 'reg': 'best'}, 'reg': {'epoch': 'cov', 'reg': True}, 'noreg': {'epoch': 'cov', 'reg': None}, 'emptyroom': {'session': 'emptyroom', 'reg': None}} # MRI subject names: {subject: mrisubject} mappings # selected with e.set(mri=dict_name) # default is identity (mrisubject = subject) _mri_subjects = {'': keydefaultdict(lambda s: s)} # Where to search for subjects (defined as a template name). If the # experiment searches for subjects automatically, it scans this directory # for subfolders matching subject_re. _subject_loc = 'raw-sdir' # Parcellations __parcs = { 'aparc.a2005s': FS_PARC, 'aparc.a2009s': FS_PARC, 'aparc': FS_PARC, 'aparc.DKTatlas': FS_PARC, 'cortex': LabelParc(('cortex',), ('lateral', 'medial')), 'PALS_B12_Brodmann': FSA_PARC, 'PALS_B12_Lobes': FSA_PARC, 'PALS_B12_OrbitoFrontal': FSA_PARC, 'PALS_B12_Visuotopic': FSA_PARC, 'lobes': EelbrainParc(True, ('lateral', 'medial')), 'lobes-op': CombinationParc('lobes', {'occipitoparietal': "occipital + parietal"}, ('lateral', 'medial')), 'lobes-ot': CombinationParc('lobes', {'occipitotemporal': "occipital + temporal"}, ('lateral', 'medial')), } parcs = {} # Frequencies: lowbound, highbound, step _freqs = {'gamma': {'frequencies': np.arange(25, 50, 2), 'n_cycles': 5}} freqs = {} # basic templates to use. Can be a string referring to a templates # dictionary in the module level _temp dictionary, or a templates # dictionary _templates = temp # specify additional templates _values = {} # specify defaults for specific fields (e.g. specify the initial subject # name) defaults = {} # model order: list of factors in the order in which models should be built # (default for factors not in this list is alphabetic) _model_order = [] # Backup # ------ # basic state for a backup _backup_state = {'subject': '*', 'mrisubject': '*', 'session': '*', 'raw': 'raw'} # files to back up, together with state modifications on the basic state _backup_files = (('rej-file', {'raw': '*', 'epoch': '*', 'rej': '*'}), ('trans-file', {}), ('mri-cfg-file', {}), ('log-dir', {}),) # Tests # ----- # specify tests as (test_type, model, test_parameter) tuple. For example, # ("anova", "condition", "condition*subject") # ("t_contrast_rel", "ref%loc", "+min(ref|left>nref|*, ref|right>nref|*)") # Make sure dictionary keys (test names) are appropriate for filenames. # tests imply a model which is set automatically tests = {} _empty_test = False # for TRFExperiment _cluster_criteria = { '': {'time': 0.025, 'sensor': 4, 'source': 10}, 'all': {}, '10ms': {'time': 0.01, 'sensor': 4, 'source': 10}, 'large': {'time': 0.025, 'sensor': 8, 'source': 20}, } # plotting # -------- _brain_plot_defaults = {'surf': 'inflated'} brain_plot_defaults = {} def __init__(self, root=None, find_subjects=True, **state): # checks if hasattr(self, 'cluster_criteria'): raise AttributeError("MneExperiment subclasses can not have a .cluster_criteria attribute anymore. Please remove the attribute, delete the eelbrain-cache folder and use the select_clusters analysis parameter.") # create attributes (overwrite class attributes) self._mri_subjects = self._mri_subjects.copy() self._templates = self._templates.copy() # templates version if self.path_version == 0: self._templates['raw-dir'] = join('{raw-sdir}', 'meg', 'raw') raw_def = {**LEGACY_RAW, 'raw': RawSource('{subject}_{recording}_clm-raw.fif'), **self.raw} elif self.path_version == 1: raw_def = {**LEGACY_RAW, 'raw': RawSource(), **self.raw} elif self.path_version == 2: raw_def = {'raw': RawSource(), **self.raw} else: raise ValueError(f"MneExperiment.path_version={self.path_version}; needs to be 0, 1 or 2") # update templates with _values for cls in reversed(inspect.getmro(self.__class__)): if hasattr(cls, '_values'): self._templates.update(cls._values) FileTree.__init__(self) self._log = log = logging.Logger(self.__class__.__name__, logging.DEBUG) ######################################################################## # sessions if not self.sessions: raise TypeError("The MneExperiment.sessions parameter needs to be specified. The session name is contained in your raw data files. For example if your file is named `R0026_mysession-raw.fif` your session name is 'mysession' and you should set MneExperiment.sessions to 'mysession'.") elif isinstance(self.sessions, str): self._sessions = (self.sessions,) elif isinstance(self.sessions, Sequence): self._sessions = tuple(self.sessions) else: raise TypeError(f"MneExperiment.sessions={self.sessions!r}; needs to be a string or a tuple") self._visits = (self._visits,) if isinstance(self.visits, str) else tuple(self.visits) ######################################################################## # subjects if root is None: find_subjects = False else: root = self.get('root', root=root) if find_subjects: subject_re = re.compile(self.subject_re) sub_dir = self.get(self._subject_loc) if not exists(sub_dir): raise IOError(f"Subjects directory {sub_dir}: does notexist. To initialize {self.__class__.__name__} without data, initialize with root=None or find_subjects=False") subjects = [s for s in os.listdir(sub_dir) if subject_re.match(s) and isdir(join(sub_dir, s))] if len(subjects) == 0: log.warning(f"No subjects found in {sub_dir}") subjects.sort() subjects = tuple(subjects) else: subjects = () ######################################################################## # groups self._groups = assemble_groups(self.groups, set(subjects)) ######################################################################## # Preprocessing skip = {'root', 'subject', 'recording', 'raw'} raw_dir = self._partial('raw-dir', skip) cache_path = self._partial('cached-raw-file', skip) self._raw = assemble_pipeline(raw_def, raw_dir, cache_path, root, self._sessions, log) raw_pipe = self._raw['raw'] # legacy connectivity determination if raw_pipe.sysname is None: if self.meg_system is not None: raw_pipe.sysname = self.meg_system # update templates self._register_constant('raw-file', raw_pipe.path) ######################################################################## # variables self._variables = Variables(self.variables) self._variables._check_trigger_vars() ######################################################################## # epochs epoch_default = {'session': self._sessions[0], **self.epoch_default} self._epochs = assemble_epochs(self.epochs, epoch_default) ######################################################################## # epoch rejection artifact_rejection = {} for name, params in chain(self._artifact_rejection.items(), self.artifact_rejection.items()): if params['kind'] in ('manual', 'make', None): artifact_rejection[name] = params.copy() elif params['kind'] == 'ica': raise ValueError(f"kind={params['kind']!r} in artifact_rejection {name!r}; The ICA option has been removed, use the RawICA raw pipe instead.") else: raise ValueError(f"kind={params['kind']!r} in artifact_rejection {name!r}") self._artifact_rejection = artifact_rejection ######################################################################## # noise covariance for k, params in self._covs.items(): params = set(params) n_datasource = ('epoch' in params) + ('session' in params) if n_datasource != 1: if n_datasource == 0: raise ValueError("Cov %s has neither epoch nor session " "entry" % k) raise ValueError("Cov %s has both epoch and session entry" % k) if params.difference(COV_PARAMS): raise ValueError("Cov %s has unused entries: %s" % (k, ', '.join(params.difference(COV_PARAMS)))) ######################################################################## # parcellations ############### # make : can be made if non-existent # morph_from_fraverage : can be morphed from fsaverage to other subjects self._parcs = assemble_parcs(chain(self.__parcs.items(), self.parcs.items())) parc_values = list(self._parcs.keys()) parc_values.append('') ######################################################################## # frequency freqs = {} for name, f in chain(self._freqs.items(), self.freqs.items()): if name in freqs: raise ValueError("Frequency %s defined twice" % name) elif 'frequencies' not in f: raise KeyError("Frequency values missing for %s" % name) elif 'n_cycles' not in f: raise KeyError("Number of cycles not defined for %s" % name) freqs[name] = f self._freqs = freqs ######################################################################## # tests self._tests = assemble_tests(self.tests) test_values = sorted(self._tests) if self._empty_test: test_values.insert(0, '') ######################################################################## # Experiment class setup ######################## self._register_field('mri', sorted(self._mri_subjects), allow_empty=True) self._register_field('subject', subjects or None, repr=True) self._register_field('group', self._groups.keys(), 'all', post_set_handler=self._post_set_group) raw_default = sorted(self.raw)[0] if self.raw else None self._register_field('raw', sorted(self._raw), default=raw_default, repr=True) self._register_field('rej', self._artifact_rejection.keys(), 'man', allow_empty=True) # epoch epoch_keys = sorted(self._epochs) for default_epoch in epoch_keys: if isinstance(self._epochs[default_epoch], PrimaryEpoch): break else: default_epoch = None self._register_field('epoch', epoch_keys, default_epoch, repr=True) self._register_field('session', self._sessions, depends_on=('epoch',), slave_handler=self._update_session, repr=True) self._register_field('visit', self._visits, allow_empty=True, repr=True) # cov if 'bestreg' in self._covs: default_cov = 'bestreg' else: default_cov = None self._register_field('cov', sorted(self._covs), default_cov) self._register_field('inv', default='free-3-dSPM', eval_handler=self._eval_inv, post_set_handler=self._post_set_inv) self._register_field('model', eval_handler=self._eval_model) self._register_field('test', test_values, post_set_handler=self._post_set_test, allow_empty=self._empty_test, repr=False) self._register_field('parc', parc_values, 'aparc', eval_handler=self._eval_parc, allow_empty=True) self._register_field('freq', self._freqs.keys()) self._register_field('src', default='ico-4', eval_handler=self._eval_src) self._register_field('connectivity', ('', 'link-midline'), allow_empty=True) self._register_field('select_clusters', self._cluster_criteria.keys(), allow_empty=True) # slave fields self._register_field('mrisubject', depends_on=('mri', 'subject'), slave_handler=self._update_mrisubject, repr=False) self._register_field('src-name', depends_on=('src',), slave_handler=self._update_src_name, repr=False) self._register_field('inv-cache', depends_on='inv', slave_handler=self._update_inv_cache, repr=False) # fields used internally self._register_field('analysis', repr=False) self._register_field('test_options', repr=False) self._register_field('name', repr=False) self._register_field('folder', repr=False) self._register_field('resname', repr=False) self._register_field('ext', repr=False) self._register_field('test_dims', repr=False) # compounds self._register_compound('sns_kind', ('raw',)) self._register_compound('src_kind', ('sns_kind', 'cov', 'mri', 'src-name', 'inv')) self._register_compound('recording', ('session', 'visit')) self._register_compound('subject_visit', ('subject', 'visit')) self._register_compound('mrisubject_visit', ('mrisubject', 'visit')) self._register_compound('epoch_visit', ('epoch', 'visit')) self._register_compound('evoked_kind', ('rej', 'equalize_evoked_count')) self._register_compound('test_desc', ('epoch', 'visit', 'test', 'test_options')) # Define make handlers self._bind_cache('cov-file', self.make_cov) self._bind_cache('src-file', self.make_src) self._bind_cache('fwd-file', self.make_fwd) # currently only used for .rm() self._secondary_cache['cached-raw-file'] = ('event-file', 'interp-file', 'cached-raw-log-file') ######################################################################## # logger ######## # log-file if root: log_file = LOG_FILE.format(root=root, name=self.__class__.__name__) log_file_old = LOG_FILE_OLD.format(root=root) if exists(log_file_old): os.rename(log_file_old, log_file) handler = logging.FileHandler(log_file) formatter = logging.Formatter("%(levelname)-8s %(asctime)s %(message)s", "%m-%d %H:%M") # %(name)-12s handler.setFormatter(formatter) handler.setLevel(logging.DEBUG) log.addHandler(handler) # Terminal log handler = ScreenHandler() self._screen_log_level = log_level(self.screen_log_level) handler.setLevel(self._screen_log_level) log.addHandler(handler) self._screen_log_handler = handler # log package versions from .. import __version__ log.info("*** %s initialized with root %s on %s ***", self.__class__.__name__, root, datetime.now().strftime('%Y-%m-%d %H:%M:%S')) msg = "Using eelbrain %s, mne %s." % (__version__, mne.__version__) if any('dev' in v for v in (__version__, mne.__version__)): log.warning(f"{msg} Development versions are more likely to contain errors.") else: log.info(msg) if self.auto_delete_cache == 'disable': log.warning("Cache-management disabled") return ######################################################################## # Finalize ########## # register experimental features self._subclass_init() # Check that the template model is complete self._find_missing_fields() # set initial values self.set(**state) self._store_state() ######################################################################## # Cache ####### if not root: return # loading events will create cache-dir cache_dir = self.get('cache-dir') cache_dir_existed = exists(cache_dir) # collect input file information # ============================== raw_missing = [] # [(subject, recording), ...] subjects_with_raw_changes = set() # {subject, ...} events = {} # {(subject, recording): event_dataset} # saved mtimes input_state_file = join(cache_dir, 'input-state.pickle') if exists(input_state_file): input_state = load.unpickle(input_state_file) if input_state['version'] < 10: input_state = None elif input_state['version'] > CACHE_STATE_VERSION: raise RuntimeError( "You are trying to initialize an experiment with an older " "version of Eelbrain than that which wrote the cache. If " "you really need this, delete the eelbrain-cache folder " "and try again.") else: input_state = None if input_state is None: input_state = { 'version': CACHE_STATE_VERSION, 'raw-mtimes': {}, 'fwd-sessions': {s: {} for s in subjects}, } # collect current events and mtime raw_mtimes = input_state['raw-mtimes'] pipe = self._raw['raw'] with self._temporary_state: for subject, visit, recording in self.iter(('subject', 'visit', 'recording'), group='all', raw='raw'): key = subject, recording mtime = pipe.mtime(subject, recording, bad_chs=False) if mtime is None: raw_missing.append(key) continue # events events[key] = self.load_events(add_bads=False, data_raw=False) if key not in raw_mtimes or mtime != raw_mtimes[key]: subjects_with_raw_changes.add((subject, visit)) raw_mtimes[key] = mtime # log missing raw files if raw_missing: log.debug("Raw files missing:") missing = defaultdict(list) for subject, recording in raw_missing: missing[subject].append(recording) for subject, recordings in missing.items(): log.debug(f" {subject}: {', '.join(recordings)}") # check for digitizer data differences # ==================================== # Coordinate frames: # MEG (markers) ==raw-file==> head shape ==trans-file==> MRI # # - raw files with identical head shapes can share trans-file (head-mri) # - raw files with identical MEG markers (and head shape) can share # forward solutions # - SuperEpochs currently need to have a single forward solution, # hence marker positions need to be the same between sub-epochs if subjects_with_raw_changes: log.info("Raw input files changed, checking digitizer data") super_epochs = [epoch for epoch in self._epochs.values() if isinstance(epoch, SuperEpoch)] for subject, visit in subjects_with_raw_changes: # find unique digitizer datasets head_shape = None markers = [] # unique MEG marker measurements marker_ids = {} # {recording: index in markers} dig_missing = [] # raw files without dig for recording in self.iter('recording', subject=subject, visit=visit): if (subject, recording) in raw_missing: continue raw = self.load_raw(False) dig = raw.info['dig'] if dig is None: dig_missing.append(recording) continue elif head_shape is None: head_shape = dig elif not hsp_equal(dig, head_shape): raise FileDeficient(f"Raw file {recording} for {subject} has head shape that is different from {enumeration(marker_ids)}; consider defining different visits.") # find if marker pos already exists for i, dig_i in enumerate(markers): if mrk_equal(dig, dig_i): marker_ids[recording] = i break else: marker_ids[recording] = len(markers) markers.append(dig) # checks for missing digitizer data if len(markers) > 1: if dig_missing: n = len(dig_missing) raise FileDeficient(f"The raw {plural('file', n)} for {subject}, {plural('recording', n)} {enumeration(dig_missing)} {plural('is', n)} missing digitizer information") for epoch in super_epochs: if len(set(marker_ids[s] for s in epoch.sessions)) > 1: groups = defaultdict(list) for s in epoch.sessions: groups[marker_ids[s]].append(s) group_desc = ' vs '.join('/'.join(group) for group in groups.values()) raise NotImplementedError(f"SuperEpoch {epoch.name} has sessions with incompatible marker positions ({group_desc}); SuperEpochs with different forward solutions are not implemented.") # determine which sessions to use for forward solutions # -> {for_session: use_session} use_for_session = input_state['fwd-sessions'].setdefault(subject, {}) # -> {marker_id: use_session}, initialize with previously used sessions use_for_id = {marker_ids[s]: s for s in use_for_session.values() if s in marker_ids} for recording in sorted(marker_ids): mrk_id = marker_ids[recording] if recording in use_for_session: assert mrk_id == marker_ids[use_for_session[recording]] continue elif mrk_id not in use_for_id: use_for_id[mrk_id] = recording use_for_session[recording] = use_for_id[mrk_id] # for files missing digitizer, use singe available fwd-recording for recording in dig_missing: if use_for_id: assert len(use_for_id) == 1 use_for_session[recording] = use_for_id[0] # save input-state if not cache_dir_existed: os.makedirs(cache_dir, exist_ok=True) save.pickle(input_state, input_state_file) self._dig_sessions = pipe._dig_sessions = input_state['fwd-sessions'] # {subject: {for_recording: use_recording}} # Check the cache, delete invalid files # ===================================== save_state = new_state = { 'version': CACHE_STATE_VERSION, 'raw': {k: v.as_dict() for k, v in self._raw.items()}, 'groups': self._groups, 'epochs': {k: v.as_dict() for k, v in self._epochs.items()}, 'tests': {k: v.as_dict() for k, v in self._tests.items()}, 'parcs': {k: v.as_dict() for k, v in self._parcs.items()}, 'events': events, } cache_state_path = join(cache_dir, 'cache-state.pickle') if exists(cache_state_path): # check time stamp # ================ state_mtime = getmtime(cache_state_path) now = time.time() + IS_WINDOWS # Windows seems to have rounding issue if state_mtime > now: raise RuntimeError(f"The cache's time stamp is in the future ({time.ctime(state_mtime)}). If the system time ({time.ctime(now)}) is wrong, adjust the system clock; if not, delete the eelbrain-cache folder.") cache_state = load.unpickle(cache_state_path) cache_state_v = cache_state.setdefault('version', 0) if cache_state_v < CACHE_STATE_VERSION: log.debug("Updating cache-state %i -> %i", cache_state_v, CACHE_STATE_VERSION) save_state = deepcopy(save_state) self._state_backwards_compat(cache_state_v, new_state, cache_state) elif cache_state_v > CACHE_STATE_VERSION: raise RuntimeError(f"The cache is from a newer version of Eelbrain than you are currently using. Either upgrade Eelbrain or delete the cache folder.") # Find modified definitions # ========================= invalid_cache = self._check_cache(new_state, cache_state, root) # Collect invalid files # ===================== if invalid_cache or cache_state_v < 2: rm = self._collect_invalid_files(invalid_cache, new_state, cache_state) # find actual files to delete log.debug("Outdated cache files:") files = set() result_files = [] for temp, arg_dicts in rm.items(): for args in arg_dicts: pattern = self._glob_pattern(temp, True, vmatch=False, **args) filenames = glob(pattern) files.update(filenames) # log rel_pattern = relpath(pattern, root) rel_filenames = sorted(' ' + relpath(f, root) for f in filenames) log.debug(' >%s', rel_pattern) for filename in rel_filenames: log.debug(filename) # message to the screen unless log is already displayed if rel_pattern.startswith('results'): result_files.extend(rel_filenames) # handle invalid files n_result_files = len(result_files) if n_result_files and self.auto_delete_cache is True and not self.auto_delete_results: if self._screen_log_level > logging.DEBUG: msg = result_files[:] msg.insert(0, "Outdated result files detected:") else: msg = [] msg.append("Delete %i outdated results?" % (n_result_files,)) command = ask( '\n'.join(msg), options=( ('delete', 'delete invalid result files'), ('abort', 'raise an error')), help=CACHE_HELP.format( experiment=self.__class__.__name__, filetype='result'), ) if command == 'abort': raise RuntimeError("User aborted invalid result deletion") elif command != 'delete': raise RuntimeError("command=%r" % (command,)) if files: if self.auto_delete_cache is False: raise RuntimeError( "Automatic cache management disabled. Either " "revert changes, or set e.auto_delete_cache=True") elif isinstance(self.auto_delete_cache, str): if self.auto_delete_cache != 'debug': raise ValueError(f"MneExperiment.auto_delete_cache={self.auto_delete_cache!r}") command = ask( "Outdated cache files. Choose 'delete' to proceed. " "WARNING: only choose 'ignore' or 'revalidate' if " "you know what you are doing.", options=( ('delete', 'delete invalid files'), ('abort', 'raise an error'), ('ignore', 'proceed without doing anything'), ('revalidate', "don't delete any cache files but write a new cache-state file")), help=CACHE_HELP.format( experiment=self.__class__.__name__, filetype='cache and/or result'), ) if command == 'delete': pass elif command == 'abort': raise RuntimeError("User aborted invalid cache deletion") elif command == 'ignore': log.warning("Ignoring invalid cache") return elif command == 'revalidate': log.warning("Revalidating invalid cache") files.clear() else: raise RuntimeError("command=%s" % repr(command)) elif self.auto_delete_cache is not True: raise TypeError(f"MneExperiment.auto_delete_cache={self.auto_delete_cache!r}") # delete invalid files n_cache_files = len(files) - n_result_files descs = [] if n_result_files: descs.append("%i invalid result files" % n_result_files) if n_cache_files: descs.append("%i invalid cache files" % n_cache_files) log.info("Deleting " + (' and '.join(descs)) + '...') for path in files: os.remove(path) else: log.debug("No existing cache files affected.") else: log.debug("Cache up to date.") elif cache_dir_existed: # cache-dir but no history if self.auto_delete_cache is True: log.info("Deleting cache-dir without history") shutil.rmtree(cache_dir) os.mkdir(cache_dir) elif self.auto_delete_cache == 'disable': log.warning("Ignoring cache-dir without history") elif self.auto_delete_cache == 'debug': command = ask("Cache directory without history", (('validate', 'write a history file treating cache as valid'), ('abort', 'raise an error'))) if command == 'abort': raise RuntimeError("User aborted") elif command == 'validate': log.warning("Validating cache-dir without history") else: raise RuntimeError("command=%r" % (command,)) else: raise IOError("Cache directory without history, but auto_delete_cache is not True") elif not exists(cache_dir): os.mkdir(cache_dir) save.pickle(save_state, cache_state_path) def _state_backwards_compat(self, cache_state_v, new_state, cache_state): "Update state dicts for backwards-compatible comparison" # epochs if cache_state_v < 3: # Epochs represented as dict up to Eelbrain 0.24 new_state['epochs'] = {k: v.as_dict_24() for k, v in self._epochs.items()} for e in cache_state['epochs'].values(): e.pop('base', None) if 'sel_epoch' in e: e.pop('n_cases', None) elif cache_state_v < 11: # remove samplingrate parameter new_state['epochs'] = {k: {ki: vi for ki, vi in v.items() if ki != 'samplingrate'} for k, v in new_state['epochs'].items()} # events did not include session if cache_state_v < 4: session = self._sessions[0] cache_state['events'] = {(subject, session): v for subject, v in cache_state['events'].items()} # raw pipeline if cache_state_v < 5: legacy_raw = assemble_pipeline(LEGACY_RAW, '', '', '', '', self._sessions, self._log) cache_state['raw'] = {k: v.as_dict() for k, v in legacy_raw.items()} # parcellations represented as dicts if cache_state_v < 6: for params in cache_state['parcs'].values(): for key in ('morph_from_fsaverage', 'make'): if key in params: del params[key] # tests represented as dicts if cache_state_v < 7: for params in cache_state['tests'].values(): if 'desc' in params: del params['desc'] cache_state['tests'] = {k: v.as_dict() for k, v in assemble_tests(cache_state['tests']).items()} elif cache_state_v == 7: # 'kind' key missing for name, params in cache_state['tests'].items(): if name in new_state['tests']: params['kind'] = new_state['tests'][name]['kind'] if cache_state_v < 12: # 'vars' entry added to all for test, params in cache_state['tests'].items(): if 'vars' in params: try: params['vars'] = Variables(params['vars']) except Exception as error: self._log.warning(" Test %s: Defective vardef %r", test, params['vars']) params['vars'] = None else: params['vars'] = None def _check_cache(self, new_state, cache_state, root): invalid_cache = defaultdict(set) # events (subject, recording): overall change in events # variables: event change restricted to certain variables # raw: preprocessing definition changed # groups: change in group members # epochs: change in epoch parameters # parcs: parc def change # tests: test def change # check events # 'events' -> number or timing of triggers (includes trigger_shift) # 'variables' -> only variable change for key, old_events in cache_state['events'].items(): new_events = new_state['events'].get(key) if new_events is None: invalid_cache['events'].add(key) self._log.warning(" raw file removed: %s", '/'.join(key)) elif new_events.n_cases != old_events.n_cases: invalid_cache['events'].add(key) self._log.warning(" event length: %s %i->%i", '/'.join(key), old_events.n_cases, new_events.n_cases) elif not np.all(new_events['i_start'] == old_events['i_start']): invalid_cache['events'].add(key) self._log.warning(" trigger times changed: %s", '/'.join(key)) else: for var in old_events: if var == 'i_start': continue elif var not in new_events: invalid_cache['variables'].add(var) self._log.warning(" var removed: %s (%s)", var, '/'.join(key)) continue old = old_events[var] new = new_events[var] if old.name != new.name: invalid_cache['variables'].add(var) self._log.warning(" var name changed: %s (%s) %s->%s", var, '/'.join(key), old.name, new.name) elif new.__class__ is not old.__class__: invalid_cache['variables'].add(var) self._log.warning(" var type changed: %s (%s) %s->%s", var, '/'.join(key), old.__class__, new.__class) elif not all_equal(old, new, True): invalid_cache['variables'].add(var) self._log.warning(" var changed: %s (%s) %i values", var, '/'.join(key), np.sum(new != old)) # groups for group, members in cache_state['groups'].items(): if group not in self._groups: invalid_cache['groups'].add(group) self._log.warning(" Group removed: %s", group) elif members != self._groups[group]: invalid_cache['groups'].add(group) log_list_change(self._log, "Group", group, members, self._groups[group]) # raw changed, changed_ica = compare_pipelines(cache_state['raw'], new_state['raw'], self._log) if changed: invalid_cache['raw'].update(changed) for raw, status in changed_ica.items(): filenames = self.glob('ica-file', raw=raw, subject='*', visit='*', match=False) if filenames: rel_paths = '\n'.join(relpath(path, root) for path in filenames) print(f"Outdated ICA files:\n{rel_paths}") ask_to_delete_ica_files(raw, status, filenames) # epochs for epoch, old_params in cache_state['epochs'].items(): new_params = new_state['epochs'].get(epoch, None) if old_params != new_params: invalid_cache['epochs'].add(epoch) log_dict_change(self._log, 'Epoch', epoch, old_params, new_params) # parcs for parc, old_params in cache_state['parcs'].items(): new_params = new_state['parcs'].get(parc, None) if old_params == new_params: continue elif new_params is None: # Don't automatically remove because they could be user-created continue new_parc = self._parcs[parc] if isinstance(new_parc, (FreeSurferParc, FSAverageParc)): # FreeSurferParc: Parcellations that are provided by the user # should not be automatically removed. # FSAverageParc: for other mrisubjects, the parcellation # should automatically update if the user changes the # fsaverage file. continue log_dict_change(self._log, "Parc", parc, old_params, new_params) invalid_cache['parcs'].add(parc) if any(p['kind'].endswith('seeded') for p in (new_params, old_params)): invalid_cache['parcs'].add(f'{parc}-?') invalid_cache['parcs'].add(f'{parc}-??') invalid_cache['parcs'].add(f'{parc}-???') # tests for test, old_params in cache_state['tests'].items(): new_params = new_state['tests'].get(test, None) if old_params != new_params: invalid_cache['tests'].add(test) log_dict_change(self._log, "Test", test, old_params, new_params) # Secondary invalidations # ======================== # changed events -> group result involving those subjects is also bad if 'events' in invalid_cache: subjects = {subject for subject, _ in invalid_cache['events']} for group, members in cache_state['groups'].items(): if subjects.intersection(members): invalid_cache['groups'].add(group) # tests/epochs based on variables if 'variables' in invalid_cache: bad_vars = invalid_cache['variables'] # tests using bad variable for test in cache_state['tests']: if test in invalid_cache['tests']: continue params = new_state['tests'][test] bad = bad_vars.intersection(find_test_vars(params)) if bad: invalid_cache['tests'].add(test) self._log.debug(" Test %s depends on changed variables %s", test, ', '.join(bad)) # epochs using bad variable epochs_vars = find_epochs_vars(cache_state['epochs']) for epoch, evars in epochs_vars.items(): bad = bad_vars.intersection(evars) if bad: invalid_cache['epochs'].add(epoch) self._log.debug(" Epoch %s depends on changed variables %s", epoch, ', '.join(bad)) # secondary epochs if 'epochs' in invalid_cache: for e in tuple(invalid_cache['epochs']): invalid_cache['epochs'].update(find_dependent_epochs(e, cache_state['epochs'])) # epochs -> cov for cov, cov_params in self._covs.items(): if cov_params.get('epoch') in invalid_cache['epochs']: invalid_cache['cov'].add(cov) return invalid_cache def _collect_invalid_files(self, invalid_cache, new_state, cache_state): rm = defaultdict(DictSet) # version if cache_state['version'] < 2: bad_parcs = [] for parc, params in self._parcs.items(): if params['kind'] == 'seeded': bad_parcs.append(parc + '-?') bad_parcs.append(parc + '-??') bad_parcs.append(parc + '-???') else: bad_parcs.append(parc) bad_tests = [] for test, params in new_state['tests'].items(): if params['kind'] == 'anova' and params['x'].count('*') > 1: bad_tests.append(test) if bad_tests and bad_parcs: self._log.warning(" Invalid ANOVA tests: %s for %s", bad_tests, bad_parcs) for test, parc in product(bad_tests, bad_parcs): rm['test-file'].add({'test': test, 'test_dims': parc}) rm['report-file'].add({'test': test, 'folder': parc}) # evoked files are based on old events for subject, recording in invalid_cache['events']: for epoch, params in self._epochs.items(): if recording not in params.sessions: continue rm['evoked-file'].add({'subject': subject, 'epoch': epoch}) # variables for var in invalid_cache['variables']: rm['evoked-file'].add({'model': f'*{var}*'}) # groups for group in invalid_cache['groups']: rm['test-file'].add({'group': group}) rm['group-mov-file'].add({'group': group}) rm['report-file'].add({'group': group}) # raw for raw in invalid_cache['raw']: rm['cached-raw-file'].add({'raw': raw}) rm['evoked-file'].add({'raw': raw}) rm['cov-file'].add({'raw': raw}) analysis = {'analysis': f'{raw} *'} rm['test-file'].add(analysis) rm['report-file'].add(analysis) rm['group-mov-file'].add(analysis) rm['subject-mov-file'].add(analysis) # epochs for epoch in invalid_cache['epochs']: rm['evoked-file'].add({'epoch': epoch}) rm['test-file'].add({'epoch': epoch}) rm['report-file'].add({'epoch': epoch}) rm['group-mov-file'].add({'epoch': epoch}) rm['subject-mov-file'].add({'epoch': epoch}) # cov for cov in invalid_cache['cov']: rm['cov-file'].add({'cov': cov}) rm['inv-file'].add({'cov': cov}) analysis = f'* {cov} *' rm['test-file'].add({'analysis': analysis}) rm['report-file'].add({'analysis': analysis}) rm['group-mov-file'].add({'analysis': analysis}) rm['subject-mov-file'].add({'analysis': analysis}) # parcs for parc in invalid_cache['parc']: rm['annot-file'].add({'parc': parc}) rm['test-file'].add({'test_dims': parc}) rm['test-file'].add({'test_dims': f'{parc}.*'}) rm['report-file'].add({'folder': parc}) rm['report-file'].add({'folder': f'{parc} *'}) rm['report-file'].add({'folder': f'{parc.capitalize()} *'}) # pre 0.26 rm['res-file'].add({'analysis': 'Source Annot', 'resname': f'{parc} * *', 'ext': 'p*'}) # tests for test in invalid_cache['tests']: rm['test-file'].add({'test': test}) rm['report-file'].add({'test': test}) if not self.cache_inv: rm['inv-file'].add({}) # secondary cache files for temp in tuple(rm): for stemp in self._secondary_cache[temp]: rm[stemp].update(rm[temp]) return rm def _subclass_init(self): "Allow subclass to register experimental features" def __iter__(self): "Iterate state through subjects and yield each subject name." for subject in self.iter(): yield subject # mtime methods # ------------- # _mtime() functions return the time at which any input files affecting the # given file changed, and None if inputs are missing. They don't check # whether the file actually exists (usually there is no need to recompute an # intermediate file if it is not needed). # _file_mtime() functions directly return the file's mtime, or None if it # does not exists or is outdated def _annot_file_mtime(self, make_for=None): """Return max mtime of annot files or None if they do not exist. Can be user input, so we need to check the actual file. """ if make_for: with self._temporary_state: self.make_annot(mrisubject=make_for) return self._annot_file_mtime() mtime = 0 for _ in self.iter('hemi'): fpath = self.get('annot-file') if exists(fpath): mtime = max(mtime, getmtime(fpath)) else: return return mtime def _cov_mtime(self): params = self._covs[self.get('cov')] with self._temporary_state: if 'epoch' in params: self.set(epoch=params['epoch']) return self._epochs_mtime() else: self.set(session=params['session']) return self._raw_mtime() def _epochs_mtime(self): raw_mtime = self._raw_mtime() if raw_mtime: epoch = self._epochs[self.get('epoch')] rej_mtime = self._rej_mtime(epoch) if rej_mtime: return max(raw_mtime, rej_mtime) def _epochs_stc_mtime(self): "Mtime affecting source estimates; does not check annot" epochs_mtime = self._epochs_mtime() if epochs_mtime: inv_mtime = self._inv_mtime() if inv_mtime: return max(epochs_mtime, inv_mtime) def _evoked_mtime(self): return self._epochs_mtime() def _evoked_stc_mtime(self): "Mtime if up-to-date, else None; do not check annot" evoked_mtime = self._evoked_mtime() if evoked_mtime: inv_mtime = self._inv_mtime() if inv_mtime: return max(evoked_mtime, inv_mtime) def _fwd_mtime(self, subject=None, recording=None, fwd_recording=None): "The last time at which input files affecting fwd-file changed" trans = self.get('trans-file') if exists(trans): src = self.get('src-file') if exists(src): if fwd_recording is None: fwd_recording = self._get_fwd_recording(subject, recording) raw_mtime = self._raw_mtime('raw', False, subject, fwd_recording) if raw_mtime: trans_mtime = getmtime(trans) src_mtime = getmtime(src) return max(raw_mtime, trans_mtime, src_mtime) def _inv_mtime(self, fwd_recording=None): fwd_mtime = self._fwd_mtime(fwd_recording=fwd_recording) if fwd_mtime: cov_mtime = self._cov_mtime() if cov_mtime: return max(cov_mtime, fwd_mtime) def _raw_mtime(self, raw=None, bad_chs=True, subject=None, recording=None): if raw is None: raw = self.get('raw') elif raw not in self._raw: raise RuntimeError(f"raw-mtime with raw={raw!r}") pipe = self._raw[raw] if subject is None: subject = self.get('subject') if recording is None: recording = self.get('recording') return pipe.mtime(subject, recording, bad_chs) def _rej_mtime(self, epoch): """rej-file mtime for secondary epoch definition Parameters ---------- epoch : dict Epoch definition. """ rej = self._artifact_rejection[self.get('rej')] if rej['kind'] is None: return 1 # no rejection with self._temporary_state: paths = [self.get('rej-file', epoch=e) for e in epoch.rej_file_epochs] if all(exists(path) for path in paths): mtime = max(getmtime(path) for path in paths) return mtime def _result_file_mtime(self, dst, data, single_subject=False): """MTime if up-to-date, else None (for reports and movies) Parameters ---------- dst : str Filename. data : TestDims Data type. single_subject : bool Whether the corresponding test is performed for a single subject (as opposed to the current group). """ if exists(dst): mtime = self._result_mtime(data, single_subject) if mtime: dst_mtime = getmtime(dst) if dst_mtime > mtime: return dst_mtime def _result_mtime(self, data, single_subject): "See ._result_file_mtime() above" if data.source: if data.parc_level: if single_subject: out = self._annot_file_mtime(self.get('mrisubject')) elif data.parc_level == 'common': out = self._annot_file_mtime(self.get('common_brain')) elif data.parc_level == 'individual': out = 0 for _ in self: mtime = self._annot_file_mtime() if mtime is None: return else: out = max(out, mtime) else: raise RuntimeError(f"data={data.string!r}, parc_level={data.parc_level!r}") else: out = 1 if not out: return mtime_func = self._epochs_stc_mtime else: out = 1 mtime_func = self._epochs_mtime if single_subject: mtime_iterator = (mtime_func(),) else: mtime_iterator = (mtime_func() for _ in self) for mtime in mtime_iterator: if not mtime: return out = max(out, mtime) return out def _process_subject_arg(self, subjects, kwargs): """Process subject arg for methods that work on groups and subjects Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). kwargs : dict Additional state parameters to set. Returns ------- subject : None | str Subject name if the value specifies a subject, None otherwise. group : None | str Group name if the value specifies a group, None otherwise. """ if subjects is None: # default: subjects = -1 if 'group' in kwargs else 1 elif subjects is True: # legacy value: subjects = -1 if isinstance(subjects, int): if subjects == 1: return self.get('subject', **kwargs), None elif subjects == -1: return None, self.get('group', **kwargs) else: raise ValueError(f"subjects={subjects}") elif isinstance(subjects, str): if subjects in self.get_field_values('group'): if 'group' in kwargs: if kwargs['group'] != subjects: raise ValueError(f"group={kwargs['group']!r} inconsistent with subject={subjects!r}") self.set(**kwargs) else: self.set(group=subjects, **kwargs) return None, subjects else: return self.get('subject', subject=subjects, **kwargs), None else: raise TypeError(f"subjects={subjects!r}") def _cluster_criteria_kwargs(self, data): criteria = self._cluster_criteria[self.get('select_clusters')] return {'min' + dim: criteria[dim] for dim in data.dims if dim in criteria} def _add_vars(self, ds, vardef: Union[None, str, Variables], groupvars=False): """Add vars to the dataset Parameters ---------- ds : Dataset Event dataset. vardef : dict | tuple Variable definition. groupvars : bool Apply GroupVars in ``self.variables`` (when adding variables to a dataset that does not originate from events, such as TRFs). """ if groupvars: self._variables.apply(ds, self, group_only=True) if vardef is None: return elif isinstance(vardef, str): try: vardef = self._tests[vardef].vars except KeyError: raise ValueError(f"vardef={vardef!r}") elif not isinstance(vardef, Variables): vardef = Variables(vardef) vardef.apply(ds, self) def _backup(self, dst_root, v=False): """Backup all essential files to ``dst_root``. .. warning:: Method is out of data and probably does not work as expected. Parameters ---------- dst_root : str Directory to use as root for the backup. v : bool Verbose mode: list all files that will be copied and ask for confirmation. Notes ----- For repeated backups ``dst_root`` can be the same. If a file has been previously backed up, it is only copied if the local copy has been modified more recently than the previous backup. If the backup has been modified more recently than the local copy, a warning is displayed. Currently, the following files are included in the backup:: * All rejection files * The trans-file * All files in the ``meg/{subject}/logs`` directory * For scaled MRIs, the file specifying the scale parameters MRIs are currently not backed up. """ self._log.debug("Initiating backup to %s" % dst_root) root = self.get('root') root_len = len(root) + 1 dirs = [] # directories to create pairs = [] # (src, dst) pairs to copy for temp, state_mod in self._backup_files: # determine state if state_mod: state = self._backup_state.copy() state.update(state_mod) else: state = self._backup_state # find files to back up if temp.endswith('dir'): paths = [] for dirpath in self.glob(temp, **state): for root_, _, filenames in os.walk(dirpath): paths.extend(join(root_, fn) for fn in filenames) else: paths = self.glob(temp, **state) # convert to (src, dst) pairs for src in paths: if not src.startswith(root): raise ValueError("Can only backup files in root directory") tail = src[root_len:] dst = join(dst_root, tail) if exists(dst): src_m = getmtime(src) dst_m = getmtime(dst) if dst_m == src_m: continue elif dst_m > src_m: self._log.warning("Backup more recent than original: %s", tail) continue else: i = 0 while True: i = tail.find(os.sep, i + 1) if i == -1: break path = tail[:i] if path not in dirs: dirs.append(path) pairs.append((src, dst)) if len(pairs) == 0: if v: print("All files backed up.") else: self._log.info("All files backed up.") return # verbose file list if v: paths = [relpath(src, root) for src, _ in pairs] print('\n'.join(paths)) cmd = 'x' while cmd not in 'yn': cmd = input("Proceed ([y]/n)? ") if cmd == 'n': print("Abort.") return else: print("Backing up %i files ..." % len(pairs)) self._log.info("Backing up %i files ..." % len(pairs)) # create directories for dirname in dirs: dirpath = join(dst_root, dirname) if not exists(dirpath): os.mkdir(dirpath) # copy files for src, dst in pairs: shutil.copy2(src, dst) def clear_cache(self, level=1): """Remove cached files. Parameters ---------- level : int Level up to which to clear the cache (see notes below). The default is 1, which deletes all cached files. Notes ----- Each lower level subsumes the higher levels: ``1`` Delete all cached files. ``2`` Epoched files - these need to be cleared when anything about the epoch definition changes (tmin, tmax, event inclusion, ...). Note that you might also have to manually update epoch rejection files with the :meth:`MneExperiment.make_epoch_selection` method. ``5`` tests - these need to be cleared when the members of the relevant subject groups change. Examples -------- To delete only test files, after adding raw data for a new subject to the experiment:: >>> e.clear_cache(5) To delete cached data files after changing the selection criteria for a secondary epoch:: >>> e.clear_cache(2) If criteria on a primary epoch are changed, the trial rejection has to be re-done in addition to clearing the cache. To delete all cached files and clear up hard drive space:: >>> e.clear_cache(1) """ if level <= 1: self.rm('cache-dir', confirm=True) print("All cached data cleared.") else: if level <= 2: self.rm('evoked-dir', confirm=True) self.rm('cov-dir', confirm=True) print("Cached epoch data cleared") if level <= 5: self.rm('test-dir', confirm=True) print("Cached tests cleared.") def get_field_values(self, field, exclude=(), **state): """Find values for a field taking into account exclusion Parameters ---------- field : str Field for which to find values. exclude : list of str Exclude these values. ... State parameters. """ if state: self.set(**state) if isinstance(exclude, str): exclude = (exclude,) if field == 'mrisubject': subjects = FileTree.get_field_values(self, 'subject') mri_subjects = self._mri_subjects[self.get('mri')] mrisubjects = sorted(mri_subjects[s] for s in subjects) if exclude: mrisubjects = [s for s in mrisubjects if s not in exclude] common_brain = self.get('common_brain') if common_brain and (not exclude or common_brain not in exclude): mrisubjects.insert(0, common_brain) return mrisubjects else: return FileTree.get_field_values(self, field, exclude) def _get_fwd_recording(self, subject: str = None, recording: str = None) -> str: if subject is None: subject = self.get('subject') if recording is None: recording = self.get('recording') try: return self._dig_sessions[subject][recording] except KeyError: raise FileMissing(f"Raw data missing for {subject}, session {recording}") def iter(self, fields='subject', exclude=None, values=None, group=None, progress_bar=None, **kwargs): """ Cycle the experiment's state through all values on the given fields Parameters ---------- fields : sequence | str Field(s) over which should be iterated. exclude : dict {str: iterator over str} Exclude values from iteration (``{field: values_to_exclude}``). values : dict {str: iterator over str} Fields with custom values to iterate over (instead of the corresponding field values) with {name: (sequence of values)} entries. group : None | str If iterating over subjects, use this group ('all' for all except excluded subjects, 'all!' for all including excluded subjects, or a name defined in experiment.groups). progress_bar : str Message to show in the progress bar. ... Fields with constant values throughout the iteration. """ if group is not None: kwargs['group'] = group return FileTree.iter(self, fields, exclude, values, progress_bar, **kwargs) def iter_range(self, start=None, stop=None, field='subject'): """Iterate through a range on a field with ordered values. Parameters ---------- start : None | str Start value (inclusive). With ``None``, begin at the first value. stop : None | str Stop value (inclusive). With ``None``, end with the last value. field : str Name of the field. Returns ------- iterator over value : str Current field value. """ values = self.get_field_values(field) if start is not None: start = values.index(start) if stop is not None: stop = values.index(stop) + 1 values = values[start:stop] with self._temporary_state: for value in values: self._restore_state(discard_tip=False) self.set(**{field: value}) yield value def _label_events(self, ds): # add standard variables ds['T'] = ds['i_start'] / ds.info['sfreq'] ds['SOA'] = ds['T'].diff(0) ds['subject'] = Factor([ds.info['subject']], repeat=ds.n_cases, random=True) if len(self._sessions) > 1: ds[:, 'session'] = ds.info['session'] if len(self._visits) > 1: ds[:, 'visit'] = ds.info['visit'] self._variables.apply(ds, self) # subclass label_events info = ds.info ds = self.label_events(ds) if not isinstance(ds, Dataset): raise DefinitionError(f"{self.__class__.__name__}.label_events() needs to return the events Dataset. Got {ds!r}.") elif 'i_start' not in ds: raise DefinitionError(f"The Dataset returned by {self.__class__.__name__}.label_events() does not contain a variable called `i_start`. This variable is required to ascribe events to data samples.") elif 'trigger' not in ds: raise DefinitionError(f"The Dataset returned by {self.__class__.__name__}.label_events() does not contain a variable called `trigger`. This variable is required to check rejection files.") elif ds.info is not info: ds.info.update(info) return ds def label_events(self, ds): """Add event labels to events loaded from raw files Parameters ---------- ds : Dataset A Dataset containing events (with variables as returned by :func:`load.fiff.events`). Notes ----- Override this method in MneExperiment subclasses to add event labels. The session that the events are from can be determined with ``ds.info['session']``. Calling the original (super-class) method is not necessary. """ return ds def label_subjects(self, ds): """Label the subjects in ds Creates a boolean :class:`Var` in ``ds`` for each group marking group membership. Parameters ---------- ds : Dataset A Dataset with 'subject' entry. """ subject = ds['subject'] for name, subjects in self._groups.items(): ds[name] = Var(subject.isin(subjects)) def label_groups(self, subject, groups): """Generate Factor for group membership Parameters ---------- subject : Factor A Factor with subjects. groups : list of str | {str: str} dict Groups which to label (raises an error if group membership is not unique). To use labels other than the group names themselves, use a ``{group: label}`` dict. Returns ------- group : Factor A :class:`Factor` that labels the group for each subject. """ if not isinstance(groups, dict): groups = {g: g for g in groups} labels = {s: [l for g, l in groups.items() if s in self._groups[g]] for s in subject.cells} problems = [s for s, g in labels.items() if len(g) != 1] if problems: desc = (', '.join(labels[s]) if labels[s] else 'no group' for s in problems) msg = ', '.join('%s (%s)' % pair for pair in zip(problems, desc)) raise ValueError(f"Groups {groups} are not unique for subjects: {msg}") labels = {s: g[0] for s, g in labels.items()} return Factor(subject, labels=labels) def load_annot(self, **state): """Load a parcellation (from an annot file) Returns ------- labels : list of Label Labels in the parcellation (output of :func:`mne.read_labels_from_annot`). ... State parameters. """ self.make_annot(**state) return mne.read_labels_from_annot(self.get('mrisubject'), self.get('parc'), 'both', subjects_dir=self.get('mri-sdir')) def load_bad_channels(self, **kwargs): """Load bad channels Parameters ---------- ... State parameters. Returns ------- bad_chs : list of str Bad chnnels. """ pipe = self._raw[self.get('raw', **kwargs)] return pipe.load_bad_channels(self.get('subject'), self.get('recording')) def _load_bem(self): subject = self.get('mrisubject') if subject == 'fsaverage' or is_fake_mri(self.get('mri-dir')): return mne.read_bem_surfaces(self.get('bem-file')) else: bem_dir = self.get('bem-dir') surfs = ('inner_skull', 'outer_skull', 'outer_skin') paths = {s: join(bem_dir, s + '.surf') for s in surfs} missing = [s for s in surfs if not exists(paths[s])] if missing: bem_dir = self.get('bem-dir') temp = join(".*", "bem", "(.*)") for surf in missing[:]: path = paths[surf] if os.path.islink(path): # try to fix broken symlinks old_target = os.readlink(path) m = re.match(temp, old_target) if m: new_target = m.group(1) if exists(join(bem_dir, new_target)): self._log.info("Fixing broken symlink for %s " "%s surface file", subject, surf) os.unlink(path) os.symlink(new_target, path) missing.remove(surf) # continue # self._log.info("Deleting broken symlink " + path) # os.unlink(path) if missing: self._log.info("%s %s missing for %s. Running " "mne.make_watershed_bem()...", enumeration(missing).capitalize(), plural('surface', len(missing)), subject) # re-run watershed_bem # mne-python expects the environment variable os.environ['FREESURFER_HOME'] = subp.get_fs_home() mne.bem.make_watershed_bem(subject, self.get('mri-sdir'), overwrite=True) return mne.make_bem_model(subject, conductivity=(0.3,), subjects_dir=self.get('mri-sdir')) def load_cov(self, **kwargs): """Load the covariance matrix Parameters ---------- ... State parameters. """ return mne.read_cov(self.get('cov-file', make=True, **kwargs)) def load_edf(self, **kwargs): """Load the edf file ("edf-file" template) Parameters ---------- ... State parameters. """ path = self.get('edf-file', fmatch=False, **kwargs) return load.eyelink.Edf(path) def load_epochs(self, subjects=None, baseline=False, ndvar=True, add_bads=True, reject=True, cat=None, decim=None, pad=0, data_raw=False, vardef=None, data='sensor', trigger_shift=True, tmin=None, tmax=None, tstop=None, interpolate_bads=False, **kwargs): """ Load a Dataset with epochs for a given epoch definition Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). baseline : bool | tuple Apply baseline correction using this period. True to use the epoch's baseline specification. The default is to not apply baseline correction. ndvar : bool | 'both' Convert epochs to an NDVar (named 'meg' for MEG data and 'eeg' for EEG data). Use 'both' to include NDVar and MNE Epochs. add_bads : bool | list Add bad channel information to the Raw. If True, bad channel information is retrieved from the bad channels file. Alternatively, a list of bad channels can be specified. reject : bool | 'keep' Reject bad trials. If ``True`` (default), bad trials are removed from the Dataset. Set to ``False`` to ignore the trial rejection. Set ``reject='keep'`` to load the rejection (added it to the events as ``'accept'`` variable), but keep bad trails. cat : sequence of cell-names Only load data for these cells (cells of model). decim : int Data decimation factor (the default is the factor specified in the epoch definition). pad : scalar Pad the epochs with this much time (in seconds; e.g. for spectral analysis). data_raw : bool Keep the :class:`mne.io.Raw` instance in ``ds.info['raw']`` (default False). vardef : str Name of a test defining additional variables. data : str Data to load; 'sensor' to load all sensor data (default); 'sensor.rms' to return RMS over sensors. Only applies to NDVar output. trigger_shift : bool Apply post-baseline trigger-shift if it applies to the epoch (default True). tmin : scalar Override the epoch's ``tmin`` parameter. tmax : scalar Override the epoch's ``tmax`` parameter. tstop : scalar Override the epoch's ``tmax`` parameter as exclusive ``tstop``. interpolate_bads : bool Interpolate channels marked as bad for the whole recording (useful when comparing topographies across subjects; default False). ... Applicable :ref:`state-parameters`: - :ref:`state-raw`: preprocessing pipeline - :ref:`state-epoch`: which events to use and time window - :ref:`state-rej`: which trials to use """ data = TestDims.coerce(data) if not data.sensor: raise ValueError(f"data={data.string!r}; load_evoked is for loading sensor data") elif data.sensor is not True: if not ndvar: raise ValueError(f"data={data.string!r} with ndvar=False") elif interpolate_bads: raise ValueError(f"interpolate_bads={interpolate_bads!r} with data={data.string}") if ndvar: if isinstance(ndvar, str): if ndvar != 'both': raise ValueError("ndvar=%s" % repr(ndvar)) subject, group = self._process_subject_arg(subjects, kwargs) epoch_name = self.get('epoch') if group is not None: dss = [] for _ in self.iter(group=group, progress=f"Load {epoch_name}"): ds = self.load_epochs(None, baseline, ndvar, add_bads, reject, cat, decim, pad, data_raw, vardef, data, True, tmin, tmax, tstop, interpolate_bads) dss.append(ds) return combine(dss) # single subject epoch = self._epochs[epoch_name] if isinstance(epoch, EpochCollection): dss = [] with self._temporary_state: for sub_epoch in epoch.collect: ds = self.load_epochs(subject, baseline, ndvar, add_bads, reject, cat, decim, pad, data_raw, vardef, data, trigger_shift, tmin, tmax, tstop, interpolate_bads, epoch=sub_epoch) ds[:, 'epoch'] = sub_epoch dss.append(ds) return combine(dss) if isinstance(add_bads, str): if add_bads == 'info': add_bads_to_info = True add_bads = True else: raise ValueError(f"add_bads={add_bads!r}") else: add_bads_to_info = False with self._temporary_state: ds = self.load_selected_events(add_bads=add_bads, reject=reject, data_raw=True, vardef=vardef, cat=cat) if ds.n_cases == 0: err = f"No events left for epoch={epoch.name!r}, subject={subject!r}" if cat: err += f", cat={cat!r}" raise RuntimeError(err) # load sensor space data if tmin is None: tmin = epoch.tmin if tmax is None and tstop is None: tmax = epoch.tmax if baseline is True: baseline = epoch.baseline if pad: tmin -= pad tmax += pad decim = decim_param(epoch, decim, ds.info['raw'].info) with warnings.catch_warnings(): warnings.filterwarnings('ignore', 'The events passed to the Epochs constructor', RuntimeWarning) ds = load.fiff.add_mne_epochs(ds, tmin, tmax, baseline, decim=decim, drop_bad_chs=False, tstop=tstop) # post baseline-correction trigger shift if trigger_shift and epoch.post_baseline_trigger_shift: ds['epochs'] = shift_mne_epoch_trigger(ds['epochs'], ds[epoch.post_baseline_trigger_shift], epoch.post_baseline_trigger_shift_min, epoch.post_baseline_trigger_shift_max) info = ds['epochs'].info data_to_ndvar = data.data_to_ndvar(info) # determine channels to interpolate bads_all = None bads_individual = None if interpolate_bads: bads_all = info['bads'] if ds.info[INTERPOLATE_CHANNELS] and any(ds[INTERPOLATE_CHANNELS]): bads_individual = ds[INTERPOLATE_CHANNELS] if bads_all: bads_all = set(bads_all) bads_individual = [sorted(bads_all.union(bads)) for bads in bads_individual] # interpolate bad channels if bads_all: if isinstance(interpolate_bads, str): if interpolate_bads == 'keep': reset_bads = False else: raise ValueError(f"interpolate_bads={interpolate_bads}") else: reset_bads = True ds['epochs'].interpolate_bads(reset_bads=reset_bads) # interpolate channels if reject and bads_individual: if 'mag' in data_to_ndvar: interp_path = self.get('interp-file') if exists(interp_path): interp_cache = load.unpickle(interp_path) else: interp_cache = {} n_in_cache = len(interp_cache) _interpolate_bads_meg(ds['epochs'], bads_individual, interp_cache) if len(interp_cache) > n_in_cache: save.pickle(interp_cache, interp_path) if 'eeg' in data_to_ndvar: _interpolate_bads_eeg(ds['epochs'], bads_individual) if ndvar: pipe = self._raw[self.get('raw')] exclude = () if add_bads_to_info else 'bads' for data_kind in data_to_ndvar: sysname = pipe.get_sysname(info, ds.info['subject'], data_kind) connectivity = pipe.get_connectivity(data_kind) name = 'meg' if data_kind == 'mag' else data_kind ds[name] = load.fiff.epochs_ndvar(ds['epochs'], data=data_kind, sysname=sysname, connectivity=connectivity, exclude=exclude) if add_bads_to_info: ds[name].info[BAD_CHANNELS] = ds['epochs'].info['bads'] if isinstance(data.sensor, str): ds[name] = getattr(ds[name], data.sensor)('sensor') if ndvar != 'both': del ds['epochs'] if not data_raw: del ds.info['raw'] return ds def load_epochs_stc(self, subjects=None, baseline=True, src_baseline=False, cat=None, keep_epochs=False, morph=False, mask=False, data_raw=False, vardef=None, decim=None, ndvar=True, reject=True, **state): """Load a Dataset with stcs for single epochs Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). Warning: loading single trial data for multiple subjects at once uses a lot of memory, which can lead to a periodically unresponsive terminal). baseline : bool | tuple Apply baseline correction using this period in sensor space. True to use the epoch's baseline specification (default). src_baseline : bool | tuple Apply baseline correction using this period in source space. True to use the epoch's baseline specification. The default is to not apply baseline correction. cat : sequence of cell-names Only load data for these cells (cells of model). keep_epochs : bool | 'ndvar' | 'both' Keep the sensor space data in the Dataset that is returned (default False; True to keep :class:`mne.Epochs` object; ``'ndvar'`` to keep :class:`NDVar`; ``'both'`` to keep both). morph : bool Morph the source estimates to the common_brain (default False). mask : bool | str Discard data that is labelled 'unknown' by the parcellation (only applies to NDVars, default False). data_raw : bool Keep the :class:`mne.io.Raw` instance in ``ds.info['raw']`` (default False). vardef : str Name of a test defining additional variables. decim : int Override the epoch decim factor. ndvar : bool Add the source estimates as :class:`NDVar` named "src" instead of a list of :class:`mne.SourceEstimate` objects named "stc" (default True). reject : bool | 'keep' Reject bad trials. If ``True`` (default), bad trials are removed from the Dataset. Set to ``False`` to ignore the trial rejection. Set ``reject='keep'`` to load the rejection (added it to the events as ``'accept'`` variable), but keep bad trails. ... Applicable :ref:`state-parameters`: - :ref:`state-raw`: preprocessing pipeline - :ref:`state-epoch`: which events to use and time window - :ref:`state-rej`: which trials to use - :ref:`state-cov`: covariance matrix for inverse solution - :ref:`state-src`: source space - :ref:`state-inv`: inverse solution Returns ------- epochs_dataset : Dataset Dataset containing single trial data (epochs). """ epoch_name = self.get('epoch') epoch = self._epochs[epoch_name] if not baseline and src_baseline and epoch.post_baseline_trigger_shift: raise NotImplementedError("src_baseline with post_baseline_trigger_shift") subject, group = self._process_subject_arg(subjects, state) if group is not None: if data_raw: raise ValueError(f"data_raw={data_raw!r} with group: Can not combine raw data from multiple subjects.") elif keep_epochs: raise ValueError(f"keep_epochs={keep_epochs!r} with group: Can not combine Epochs objects for different subjects. Set keep_epochs=False (default).") elif not morph: raise ValueError(f"morph={morph!r} with group: Source estimates can only be combined after morphing data to common brain model. Set morph=True.") dss = [] for _ in self.iter(group=group, progress_bar=f"Load {epoch_name} STC"): ds = self.load_epochs_stc(None, baseline, src_baseline, cat, keep_epochs, morph, mask, False, vardef, decim, ndvar, reject) dss.append(ds) return combine(dss) if keep_epochs is True: sns_ndvar = False del_epochs = False elif keep_epochs is False: sns_ndvar = False del_epochs = True elif keep_epochs == 'ndvar': sns_ndvar = 'both' del_epochs = True elif keep_epochs == 'both': sns_ndvar = 'both' del_epochs = False else: raise ValueError(f'keep_epochs={keep_epochs!r}') ds = self.load_epochs(subject, baseline, sns_ndvar, reject=reject, cat=cat, decim=decim, data_raw=data_raw, vardef=vardef) # load inv if src_baseline is True: src_baseline = epoch.baseline parc = self.get('parc') or None if isinstance(mask, str) and parc != mask: parc = mask self.set(parc=mask) # make sure annotation exists if parc: self.make_annot() epochs = ds['epochs'] inv = self.load_inv(epochs) # determine whether initial source-space can be restricted mri_sdir = self.get('mri-sdir') mrisubject = self.get('mrisubject') is_scaled = find_source_subject(mrisubject, mri_sdir) if mask and (is_scaled or not morph): label = label_from_annot(inv['src'], mrisubject, mri_sdir, parc) else: label = None stc = apply_inverse_epochs(epochs, inv, label=label, **self._params['apply_inv_kw']) if ndvar: src = self.get('src') src = load.fiff.stc_ndvar( stc, mrisubject, src, mri_sdir, self._params['apply_inv_kw']['method'], self._params['make_inv_kw'].get('fixed', False), parc=parc, connectivity=self.get('connectivity')) if src_baseline: src -= src.summary(time=src_baseline) if morph: common_brain = self.get('common_brain') with self._temporary_state: self.make_annot(mrisubject=common_brain) ds['srcm'] = morph_source_space(src, common_brain) if mask and not is_scaled: _mask_ndvar(ds, 'srcm') else: ds['src'] = src else: if src_baseline: raise NotImplementedError("Baseline for SourceEstimate") if morph: raise NotImplementedError("Morphing for SourceEstimate") ds['stc'] = stc if del_epochs: del ds['epochs'] return ds def load_events(self, subject=None, add_bads=True, data_raw=True, **kwargs): """ Load events from a raw file. Loads events from the corresponding raw file, adds the raw to the info dict. Parameters ---------- subject : str Subject for which to load events (default is the current subject in the experiment's state). add_bads : False | True | list Add bad channel information to the Raw. If True, bad channel information is retrieved from the bad channels file. Alternatively, a list of bad channels can be specified. data_raw : bool Keep the :class:`mne.io.Raw` instance in ``ds.info['raw']`` (default False). ... Applicable :ref:`state-parameters`: - :ref:`state-raw`: preprocessing pipeline - :ref:`state-epoch`: which events to use and time window """ evt_file = self.get('event-file', mkdir=True, subject=subject, **kwargs) subject = self.get('subject') # search for and check cached version raw_mtime = self._raw_mtime(bad_chs=False, subject=subject) if exists(evt_file): ds = load.unpickle(evt_file) if ds.info['raw-mtime'] != raw_mtime: ds = None else: ds = None # refresh cache if ds is None: self._log.debug("Extracting events for %s %s %s", self.get('raw'), subject, self.get('recording')) raw = self.load_raw(add_bads) ds = load.fiff.events(raw) del ds.info['raw'] ds.info['sfreq'] = raw.info['sfreq'] ds.info['raw-mtime'] = raw_mtime # add edf if self.has_edf[subject]: edf = self.load_edf() edf.add_t_to(ds) ds.info['edf'] = edf save.pickle(ds, evt_file) if data_raw: ds.info['raw'] = raw elif data_raw: ds.info['raw'] = self.load_raw(add_bads) ds.info['subject'] = subject ds.info['session'] = self.get('session') if len(self._visits) > 1: ds.info['visit'] = self.get('visit') if self.trigger_shift: if isinstance(self.trigger_shift, dict): trigger_shift = self.trigger_shift[subject] else: trigger_shift = self.trigger_shift if trigger_shift: ds['i_start'] += int(round(trigger_shift * ds.info['sfreq'])) return self._label_events(ds) def load_evoked(self, subjects=None, baseline=False, ndvar=True, cat=None, decim=None, data_raw=False, vardef=None, data='sensor', **kwargs): """ Load a Dataset with the evoked responses for each subject. Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). baseline : bool | tuple Apply baseline correction using this period. True to use the epoch's baseline specification. The default is to not apply baseline correction. ndvar : bool Convert the mne Evoked objects to an NDVar (the name in the Dataset is 'meg' or 'eeg'). cat : sequence of cell-names Only load data for these cells (cells of model). decim : int Data decimation factor (the default is the factor specified in the epoch definition). data_raw : bool Keep the :class:`mne.io.Raw` instance in ``ds.info['raw']`` (default False). vardef : str Name of a test defining additional variables. data : str Data to load; 'sensor' to load all sensor data (default); 'sensor.rms' to return RMS over sensors. Only applies to NDVar output. ... Applicable :ref:`state-parameters`: - :ref:`state-raw`: preprocessing pipeline - :ref:`state-epoch`: which events to use and time window - :ref:`state-rej`: which trials to use - :ref:`state-model`: how to group trials into conditions - :ref:`state-equalize_evoked_count`: control number of trials per cell """ subject, group = self._process_subject_arg(subjects, kwargs) epoch_name = self.get('epoch') epoch = self._epochs[epoch_name] data = TestDims.coerce(data) if not data.sensor: raise ValueError(f"data={data.string!r}; load_evoked is for loading sensor data") elif data.sensor is not True and not ndvar: raise ValueError(f"data={data.string!r} with ndvar=False") if baseline is True: baseline = epoch.baseline model = self.get('model') if group is not None: # when aggregating across sensors, do it before combining subjects # to avoid losing sensors that are not shared individual_ndvar = isinstance(data.sensor, str) desc = f'by {model}' if model else 'average' dss = [self.load_evoked(None, baseline, individual_ndvar, cat, decim, data_raw, vardef, data) for _ in self.iter(group=group, progress_bar=f"Load {epoch_name} {desc}")] if individual_ndvar: ndvar = False elif ndvar: # set interpolated channels to good for ds in dss: for e in ds['evoked']: if e.info['description'] is None: continue m = re.match(r"Eelbrain (\d+)", e.info['description']) if not m: continue v = int(m.group(1)) if v >= 11: e.info['bads'] = [] ds = combine(dss, incomplete='drop') # check consistency in MNE objects' number of time points lens = [len(e.times) for e in ds['evoked']] ulens = set(lens) if len(ulens) > 1: err = ["Unequal time axis sampling (len):"] alens = np.array(lens) for l in ulens: err.append('%i: %r' % (l, ds['subject', alens == l].cells)) raise DimensionMismatchError('\n'.join(err)) else: # single subject ds = self._make_evoked(decim, data_raw) if cat: if not model: raise TypeError(f"cat={cat!r}: Can't set cat when model is ''") model = ds.eval(model) idx = model.isin(cat) ds = ds.sub(idx) if ds.n_cases == 0: raise RuntimeError(f"Selection with cat={cat!r} resulted in empty Dataset") self._add_vars(ds, vardef) # baseline correction if isinstance(baseline, str): raise NotImplementedError elif baseline and not epoch.post_baseline_trigger_shift: for e in ds['evoked']: rescale(e.data, e.times, baseline, 'mean', copy=False) # convert to NDVar if ndvar: pipe = self._raw[self.get('raw')] info = ds[0, 'evoked'].info for data_kind in data.data_to_ndvar(info): sysname = pipe.get_sysname(info, subject, data_kind) connectivity = pipe.get_connectivity(data_kind) name = 'meg' if data_kind == 'mag' else data_kind ds[name] = load.fiff.evoked_ndvar(ds['evoked'], data=data_kind, sysname=sysname, connectivity=connectivity) if data_kind != 'eog' and isinstance(data.sensor, str): ds[name] = getattr(ds[name], data.sensor)('sensor') # if ndvar != 'both': # del ds['evoked'] return ds def load_epochs_stf(self, subjects=None, baseline=True, mask=True, morph=False, keep_stc=False, **state): """Load frequency space single trial data Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). baseline : bool | tuple Apply baseline correction using this period in sensor space. True to use the epoch's baseline specification. The default is True. mask : bool | str Discard data that is labelled 'unknown' by the parcellation (only applies to NDVars, default True). morph : bool Morph the source estimates to the common_brain (default False). keep_stc : bool Keep the source timecourse data in the Dataset that is returned (default False). ... State parameters. """ ds = self.load_epochs_stc(subjects, baseline, ndvar=True, morph=morph, mask=mask, **state) name = 'srcm' if morph else 'src' # apply morlet transformation freq_params = self.freqs[self.get('freq')] freq_range = freq_params['frequencies'] ds['stf'] = cwt_morlet(ds[name], freq_range, use_fft=True, n_cycles=freq_params['n_cycles'], zero_mean=False, out='magnitude') if not keep_stc: del ds[name] return ds def load_evoked_stf(self, subjects=None, baseline=True, mask=True, morph=False, keep_stc=False, **state): """Load frequency space evoked data Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). baseline : bool | tuple Apply baseline correction using this period in sensor space. True to use the epoch's baseline specification. The default is True. mask : bool | str Whether to just load the sources from the parcellation that are not defined as "unknown". Default is True. morph : bool Morph the source estimates to the common_brain (default False). keep_stc : bool Keep the source timecourse data in the Dataset that is returned (default False). ... State parameters. """ ds = self.load_evoked_stc(subjects, baseline, morph=morph, mask=mask, **state) name = 'srcm' if morph else 'src' # apply morlet transformation freq_params = self.freqs[self.get('freq')] freq_range = freq_params['frequencies'] ds['stf'] = cwt_morlet(ds[name], freq_range, use_fft=True, n_cycles=freq_params['n_cycles'], zero_mean=False, out='magnitude') if not keep_stc: del ds[name] return ds def load_evoked_stc(self, subjects=None, baseline=True, src_baseline=False, cat=None, keep_evoked=False, morph=False, mask=False, data_raw=False, vardef=None, decim=None, ndvar=True, **state): """Load evoked source estimates. Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). baseline : bool | tuple Apply baseline correction using this period in sensor space. True to use the epoch's baseline specification. The default is True. src_baseline : bool | tuple Apply baseline correction using this period in source space. True to use the epoch's baseline specification. The default is to not apply baseline correction. cat : sequence of cell-names Only load data for these cells (cells of model). keep_evoked : bool Keep the sensor space data in the Dataset that is returned (default False). morph : bool Morph the source estimates to the common_brain (default False). mask : bool | str Discard data that is labelled 'unknown' by the parcellation (only applies to NDVars, default False). Can be set to a parcellation name or ``True`` to use the current parcellation. data_raw : bool Keep the :class:`mne.io.Raw` instance in ``ds.info['raw']`` (default False). vardef : str Name of a test defining additional variables. decim : int Override the epoch decim factor. ndvar : bool Add the source estimates as NDVar named "src" instead of a list of :class:`mne.SourceEstimate` objects named "stc" (default True). ... Applicable :ref:`state-parameters`: - :ref:`state-raw`: preprocessing pipeline - :ref:`state-epoch`: which events to use and time window - :ref:`state-rej`: which trials to use - :ref:`state-model`: how to group trials into conditions - :ref:`state-equalize_evoked_count`: control number of trials per cell - :ref:`state-cov`: covariance matrix for inverse solution - :ref:`state-src`: source space - :ref:`state-inv`: inverse solution """ if isinstance(mask, str): state['parc'] = mask # load sensor data (needs state in case it has 'group' entry) sns_ndvar = keep_evoked and ndvar ds = self.load_evoked(subjects, baseline, sns_ndvar, cat, decim, data_raw, vardef, **state) # check baseline epoch = self._epochs[self.get('epoch')] if src_baseline and epoch.post_baseline_trigger_shift: raise NotImplementedError(f"src_baseline={src_baseline!r}: post_baseline_trigger_shift is not implemented for baseline correction in source space") elif src_baseline is True: src_baseline = epoch.baseline # MRI subjects common_brain = self.get('common_brain') meg_subjects = ds['subject'].cells from_subjects = {} # for the purpose of morphing mri_subjects = {} # for representing for subject in meg_subjects: mri_subjects[subject] = self.get('mrisubject', subject=subject) if is_fake_mri(self.get('mri-dir')): from_subjects[subject] = common_brain else: from_subjects[subject] = mri_subjects[subject] # make sure annot files are available (needed only for NDVar) if ndvar: if morph: self.make_annot(mrisubject=common_brain) elif len(meg_subjects) > 1: raise ValueError(f"ndvar=True, morph=False with multiple subjects: Can't create ndvars with data from different brains") else: self.make_annot(mrisubject=mri_subjects[meg_subjects[0]]) # convert evoked objects stcs = [] invs = {} mm_cache = CacheDict(self.load_morph_matrix, 'mrisubject') for subject, evoked in tqdm(ds.zip('subject', 'evoked'), "Localize", ds.n_cases): # get inv if subject in invs: inv = invs[subject] else: inv = invs[subject] = self.load_inv(evoked, subject=subject) # apply inv stc = apply_inverse(evoked, inv, **self._params['apply_inv_kw']) # baseline correction if src_baseline: rescale(stc._data, stc.times, src_baseline, 'mean', copy=False) if morph: subject_from = from_subjects[subject] if subject_from == common_brain: stc.subject = common_brain else: mm, v_to = mm_cache[subject_from] stc = mne.morph_data_precomputed(subject_from, common_brain, stc, v_to, mm) stcs.append(stc) # add to Dataset if ndvar: if morph: key, subject = 'srcm', common_brain else: key, subject = 'src', mri_subjects[meg_subjects[0]] src = self.get('src') mri_sdir = self.get('mri-sdir') method = self._params['apply_inv_kw']['method'] fixed = self._params['make_inv_kw'].get('fixed', False) parc = self.get('parc') or None ds[key] = load.fiff.stc_ndvar(stcs, subject, src, mri_sdir, method, fixed, parc=parc, connectivity=self.get('connectivity')) if mask: _mask_ndvar(ds, key) else: key = 'stcm' if morph else 'stc' ds[key] = stcs if not keep_evoked: del ds['evoked'] return ds def load_fwd(self, surf_ori=True, ndvar=False, mask=None, **state): """Load the forward solution Parameters ---------- surf_ori : bool Force surface orientation (default True; only applies if ``ndvar=False``, :class:`NDVar` forward operators are alsways surface based). ndvar : bool Return forward solution as :class:`NDVar` (default is :class:`mne.forward.Forward`). mask : str | bool Remove source labelled "unknown". Can be parcellation name or True, in which case the current parcellation is used. ... State parameters. Returns ------- forward_operator : mne.forward.Forward | NDVar Forward operator. """ if mask and not ndvar: raise NotImplementedError("mask is only implemented for ndvar=True") elif isinstance(mask, str): state['parc'] = mask mask = True fwd_file = self.get('fwd-file', make=True, **state) src = self.get('src') if ndvar: if src.startswith('vol'): parc = None assert mask is None else: self.make_annot() parc = self.get('parc') fwd = load.fiff.forward_operator(fwd_file, src, self.get('mri-sdir'), parc) if mask: fwd = fwd.sub(source=np.invert( fwd.source.parc.startswith('unknown'))) return fwd else: fwd = mne.read_forward_solution(fwd_file) if surf_ori: mne.convert_forward_solution(fwd, surf_ori, copy=False) return fwd def load_ica(self, **state): """Load the mne-python ICA object Returns ------- ica : mne.preprocessing.ICA ICA object for the current raw/rej setting. ... State parameters. """ path = self.make_ica(**state) return mne.preprocessing.read_ica(path) def load_inv(self, fiff=None, ndvar=False, mask=None, **state): """Load the inverse operator Parameters ---------- fiff : Raw | Epochs | Evoked | ... Object which provides the mne info dictionary (default: load the raw file). ndvar : bool Return the inverse operator as NDVar (default is :class:`mne.minimum_norm.InverseOperator`). The NDVar representation does not take into account any direction selectivity (loose/free orientation) or noise normalization properties. mask : str | bool Remove source labelled "unknown". Can be parcellation name or True, in which case the current parcellation is used. ... Applicable :ref:`state-parameters`: - :ref:`state-raw`: preprocessing pipeline - :ref:`state-rej`: which trials to use - :ref:`state-cov`: covariance matrix for inverse solution - :ref:`state-src`: source space - :ref:`state-inv`: inverse solution """ if mask and not ndvar: raise NotImplementedError("mask is only implemented for ndvar=True") elif isinstance(mask, str): state['parc'] = mask mask = True if state: self.set(**state) inv = dst = None if self.cache_inv: subject = self.get('subject') fwd_recording = self._get_fwd_recording(subject) with self._temporary_state: dst = self.get('inv-file', mkdir=True, recording=fwd_recording) if exists(dst) and cache_valid(getmtime(dst), self._inv_mtime(fwd_recording)): inv = mne.minimum_norm.read_inverse_operator(dst) if inv is None: src = self.get('src') if src[:3] == 'vol': inv = self.get('inv') if not (inv.startswith('vec') or inv.startswith('free')): raise ValueError(f'inv={inv!r} with src={src!r}: volume source space requires free or vector inverse') if fiff is None: fiff = self.load_raw() inv = make_inverse_operator(fiff.info, self.load_fwd(), self.load_cov(), use_cps=True, **self._params['make_inv_kw']) if dst: mne.minimum_norm.write_inverse_operator(dst, inv) if ndvar: inv = load.fiff.inverse_operator(inv, self.get('src'), self.get('mri-sdir'), self.get('parc')) if mask: inv = inv.sub(source=~inv.source.parc.startswith('unknown')) return inv def load_label(self, label, **kwargs): """Retrieve a label as mne Label object Parameters ---------- label : str Name of the label. If the label name does not end in '-bh' or '-rh' the combination of the labels ``label + '-lh'`` and ``label + '-rh'`` is returned. ... State parameters. """ labels = self._load_labels(label, **kwargs) if label in labels: return labels[label] elif not label.endswith(('-lh', '-rh')): return labels[label + '-lh'] + labels[label + '-rh'] else: raise ValueError("Label %r could not be found in parc %r." % (label, self.get('parc'))) def _load_labels(self, regexp=None, **kwargs): """Load labels from an annotation file.""" self.make_annot(**kwargs) mri_sdir = self.get('mri-sdir') labels = mne.read_labels_from_annot(self.get('mrisubject'), self.get('parc'), regexp=regexp, subjects_dir=mri_sdir) return {l.name: l for l in labels} def load_morph_matrix(self, **state): """Load the morph matrix from mrisubject to common_brain Parameters ---------- ... State parameters. Returns ------- mm : sparse matrix Morph matrix. vertices_to : list of 2 array Vertices of the morphed data. """ subjects_dir = self.get('mri-sdir', **state) subject_to = self.get('common_brain') subject_from = self.get('mrisubject') src_to = self.load_src(mrisubject=subject_to, match=False) src_from = self.load_src(mrisubject=subject_from, match=False) vertices_to = [src_to[0]['vertno'], src_to[1]['vertno']] vertices_from = [src_from[0]['vertno'], src_from[1]['vertno']] mm = mne.compute_morph_matrix(subject_from, subject_to, vertices_from, vertices_to, None, subjects_dir) return mm, vertices_to def load_neighbor_correlation(self, subjects=None, epoch=None, **state): """Load sensor neighbor correlation Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). epoch : str Epoch to use for computing neighbor-correlation (by default, the whole session is used). Returns ------- nc : NDVar | Dataset Sensor neighbor-correlation as :class:`NDVar` for a single subject or as :class:`Dataset` for multiple subjects. """ subject, group = self._process_subject_arg(subjects, state) if group is not None: if state: self.set(**state) lines = [(subject, self.load_neighbor_correlation(1, epoch)) for subject in self] return Dataset.from_caselist(['subject', 'nc'], lines) if epoch: if epoch is True: epoch = self.get('epoch') epoch_params = self._epochs[epoch] if len(epoch_params.sessions) != 1: raise ValueError(f"epoch={epoch!r}: epoch has multiple session") ds = self.load_epochs(epoch=epoch, reject=False, decim=1, **state) data = concatenate(ds['meg']) else: data = self.load_raw(ndvar=True, **state) return neighbor_correlation(data) def load_raw(self, add_bads=True, preload=False, ndvar=False, decim=1, **kwargs): """ Load a raw file as mne Raw object. Parameters ---------- add_bads : bool | list Add bad channel information to the bad channels text file (default True). preload : bool Load raw data into memory (default False; see :func:`mne.io.read_raw_fif` parameter). ndvar : bool Load as NDVar instead of mne Raw object (default False). decim : int Decimate data (default 1, i.e. no decimation; value other than 1 implies ``preload=True``) ... Applicable :ref:`state-parameters`: - :ref:`state-session`: from which session to load raw data - :ref:`state-raw`: preprocessing pipeline Notes ----- Bad channels defined in the raw file itself are ignored in favor of the bad channels in the bad channels file. """ pipe = self._raw[self.get('raw', **kwargs)] if decim > 1: preload = True raw = pipe.load(self.get('subject'), self.get('recording'), add_bads, preload) if decim > 1: if ndvar: # avoid warning for downsampling event channel stim_picks = np.empty(0) events = np.empty((0, 3)) else: stim_picks = events = None sfreq = int(round(raw.info['sfreq'] / decim)) raw.resample(sfreq, stim_picks=stim_picks, events=events) if ndvar: data = TestDims('sensor') data_kind = data.data_to_ndvar(raw.info)[0] sysname = pipe.get_sysname(raw.info, self.get('subject'), data_kind) connectivity = pipe.get_connectivity(data_kind) raw = load.fiff.raw_ndvar(raw, sysname=sysname, connectivity=connectivity) return raw def _load_result_plotter(self, test, tstart, tstop, pmin, parc=None, mask=None, samples=10000, data='source', baseline=True, src_baseline=None, colors=None, labels=None, h=1.2, rc=None, dst=None, vec_fmt='svg', pix_fmt='png', **kwargs): """Load cluster-based test result plotter Parameters ---------- test : str Name of the test. tstart, tstop, pmin, parc, mask, samples, data, baseline, src_baseline Test parameters. colors : dict Colors for data cells as ``{cell: matplotlib_color}`` dictionary. labels : dict Labels for data in a ``{cell: label}`` dictionary (the default is to use cell names). h : scalar Plot height in inches (default 1.1). rc : dict Matplotlib rc-parameters dictionary (the default is optimized for the default plot size ``h=1.1``). dst : str Directory in which to place results (default is the ``result plots`` directory). vec_fmt : str Format for vector graphics (default 'pdf'). pix_fmt : str Format for pixel graphics (default 'png'). ... State parameters. """ if not isinstance(self._tests[test], EvokedTest): raise NotImplementedError("Result-plots for %s" % self._tests[test].__class__.__name__) elif data != 'source': raise NotImplementedError("data=%s" % repr(data)) elif not isinstance(pmin, float): raise NotImplementedError("Threshold-free tests") from .._result_plots import ClusterPlotter # calls _set_analysis_options(): ds, res = self.load_test(test, tstart, tstop, pmin, parc, mask, samples, data, baseline, src_baseline, True, **kwargs) if dst is None: dst = self.get('res-plot-dir', mkdir=True) return ClusterPlotter(ds, res, colors, dst, vec_fmt, pix_fmt, labels, h, rc) def load_selected_events(self, subjects=None, reject=True, add_bads=True, index=True, data_raw=False, vardef=None, cat=None, **kwargs): """ Load events and return a subset based on epoch and rejection Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). reject : bool | 'keep' Reject bad trials. If ``True`` (default), bad trials are removed from the Dataset. Set to ``False`` to ignore the trial rejection. Set ``reject='keep'`` to load the rejection (added it to the events as ``'accept'`` variable), but keep bad trails. add_bads : False | True | list Add bad channel information to the Raw. If True, bad channel information is retrieved from the bad channels file. Alternatively, a list of bad channels can be specified. index : bool | str Index the Dataset before rejection (provide index name as str). data_raw : bool Keep the :class:`mne.io.Raw` instance in ``ds.info['raw']`` (default False). vardef : str Name of a test defining additional variables. cat : sequence of cell-names Only load data for these cells (cells of model). ... State parameters. Notes ----- When trial rejection is set to automatic, not rejection is performed because no epochs are loaded. """ # process arguments if reject not in (True, False, 'keep'): raise ValueError(f"reject={reject!r}") if index is True: index = 'index' elif index and not isinstance(index, str): raise TypeError(f"index={index!r}") # case of loading events for a group subject, group = self._process_subject_arg(subjects, kwargs) if group is not None: if data_raw: raise ValueError(f"data_var={data_raw!r}: can't keep raw when combining subjects") dss = [self.load_selected_events(reject=reject, add_bads=add_bads, index=index, vardef=vardef) for _ in self.iter(group=group)] ds = combine(dss) return ds epoch = self._epochs[self.get('epoch')] if isinstance(epoch, EpochCollection): raise ValueError(f"epoch={self.get('epoch')!r}; can't load events for collection epoch") # rejection comes from somewhere else if isinstance(epoch, SuperEpoch): with self._temporary_state: dss = [] raw = None # find bad channels if isinstance(add_bads, Sequence): bad_channels = list(add_bads) elif add_bads: bad_channels = sorted(set.union(*( set(self.load_bad_channels(session=session)) for session in epoch.sessions))) else: bad_channels = [] # load events for session in epoch.sessions: self.set(session=session) # load events for this session session_dss = [] for sub_epoch in epoch.sub_epochs: if self._epochs[sub_epoch].session != session: continue ds = self.load_selected_events(subject, reject, add_bads, index, True, epoch=sub_epoch) ds[:, 'epoch'] = sub_epoch session_dss.append(ds) ds = combine(session_dss) dss.append(ds) # combine raw raw_ = session_dss[0].info['raw'] raw_.info['bads'] = bad_channels if raw is None: raw = raw_ else: ds['i_start'] += raw.last_samp + 1 - raw_.first_samp raw.append(raw_) # combine bad channels ds = combine(dss) if data_raw: ds.info['raw'] = raw ds.info[BAD_CHANNELS] = bad_channels elif isinstance(epoch, SecondaryEpoch): with self._temporary_state: ds = self.load_selected_events(None, 'keep' if reject else False, add_bads, index, data_raw, epoch=epoch.sel_epoch) if epoch.sel: ds = ds.sub(epoch.sel) if index: ds.index(index) if reject is True: if self._artifact_rejection[self.get('rej')]['kind'] is not None: ds = ds.sub('accept') else: rej_params = self._artifact_rejection[self.get('rej')] # load files with self._temporary_state: ds = self.load_events(add_bads=add_bads, data_raw=data_raw, session=epoch.session) if reject and rej_params['kind'] is not None: rej_file = self.get('rej-file') if exists(rej_file): ds_sel = load.unpickle(rej_file) else: rej_file = self._get_rel('rej-file', 'root') raise FileMissing(f"The rejection file at {rej_file} does not exist. Run .make_epoch_selection() first.") else: ds_sel = None # primary event selection if epoch.sel: ds = ds.sub(epoch.sel) if index: ds.index(index) if epoch.n_cases is not None and ds.n_cases != epoch.n_cases: raise RuntimeError(f"Number of epochs {ds.n_cases}, expected {epoch.n_cases}") # rejection if ds_sel is not None: # check file if not np.all(ds['trigger'] == ds_sel['trigger']): # TODO: this warning should be given in make_epoch_selection already if np.all(ds[:-1, 'trigger'] == ds_sel['trigger']): ds = ds[:-1] self._log.warning(self.format("Last epoch for {subject} is missing")) elif np.all(ds[1:, 'trigger'] == ds_sel['trigger']): ds = ds[1:] self._log.warning(self.format("First epoch for {subject} is missing")) else: raise RuntimeError(f"The epoch selection file contains different events (trigger IDs) from the epoch data loaded from the raw file. If the events included in the epoch were changed intentionally, delete the corresponding epoch rejection file and redo epoch rejection: {rej_file}") if rej_params['interpolation']: ds.info[INTERPOLATE_CHANNELS] = True if INTERPOLATE_CHANNELS in ds_sel: ds[INTERPOLATE_CHANNELS] = ds_sel[INTERPOLATE_CHANNELS] else: ds[INTERPOLATE_CHANNELS] = Datalist([[]] * ds.n_cases, INTERPOLATE_CHANNELS, 'strlist') else: ds.info[INTERPOLATE_CHANNELS] = False # subset events if reject == 'keep': ds['accept'] = ds_sel['accept'] elif reject is True: ds = ds.sub(ds_sel['accept']) else: raise RuntimeError("reject=%s" % repr(reject)) # bad channels if add_bads: if BAD_CHANNELS in ds_sel.info: ds.info[BAD_CHANNELS] = ds_sel.info[BAD_CHANNELS] else: ds.info[BAD_CHANNELS] = [] else: # no artifact rejection ds.info[INTERPOLATE_CHANNELS] = False ds.info[BAD_CHANNELS] = [] # apply trigger-shift if epoch.trigger_shift: shift = epoch.trigger_shift if isinstance(shift, str): shift = ds.eval(shift) if isinstance(shift, Var): shift = shift.x if np.isscalar(shift): ds['i_start'] += int(round(shift * ds.info['sfreq'])) else: ds['i_start'] += np.round(shift * ds.info['sfreq']).astype(int) # Additional variables self._add_vars(ds, epoch.vars) self._add_vars(ds, vardef) # apply cat subset if cat: model = ds.eval(self.get('model')) idx = model.isin(cat) ds = ds.sub(idx) return ds def _load_spm(self, baseline=True, src_baseline=False): "Load LM" subject = self.get('subject') test = self.get('test') test_obj = self._tests[test] if not isinstance(test_obj, TwoStageTest): raise NotImplementedError("Test kind %r" % test_obj.__class__.__name__) ds = self.load_epochs_stc(subject, baseline, src_baseline, mask=True, vardef=test_obj.vars) return testnd.LM('src', test_obj.stage_1, ds, subject=subject) def load_src(self, add_geom=False, ndvar=False, **state): """Load the current source space Parameters ---------- add_geom : bool Parameter for :func:`mne.read_source_spaces`. ndvar : bool Return as NDVar Dimension object (default False). ... State parameters. """ fpath = self.get('src-file', make=True, **state) if ndvar: src = self.get('src') if src.startswith('vol'): return VolumeSourceSpace.from_file( self.get('mri-sdir'), self.get('mrisubject'), src) return SourceSpace.from_file( self.get('mri-sdir'), self.get('mrisubject'), src, self.get('parc')) return mne.read_source_spaces(fpath, add_geom) def load_test(self, test, tstart=None, tstop=None, pmin=None, parc=None, mask=None, samples=10000, data='source', baseline=True, src_baseline=None, return_data=False, make=False, **state): """Create and load spatio-temporal cluster test results Parameters ---------- test : None | str Test for which to create a report (entry in MneExperiment.tests; None to use the test that was specified most recently). tstart : scalar Beginning of the time window for the test in seconds (default is the beginning of the epoch). tstop : scalar End of the time window for the test in seconds (default is the end of the epoch). pmin : float | 'tfce' | None Kind of test. parc : None | str Parcellation for which to collect distribution. mask : None | str Mask whole brain. samples : int Number of random permutations of the data used to determine cluster p values (default 10'000). data : str Data to test, for example: - ``'sensor'`` spatio-temporal test in sensor space. - ``'source'`` spatio-temporal test in source space. - ``'source.mean'`` ROI mean time course. - ``'sensor.rms'`` RMS across sensors. baseline : bool | tuple Apply baseline correction using this period in sensor space. True to use the epoch's baseline specification (default). src_baseline : bool | tuple Apply baseline correction using this period in source space. True to use the epoch's baseline specification. The default is to not apply baseline correction. return_data : bool Return the data along with the test result (see below). .. Warning:: Single trial data (i.e., two-stage tests) take up a lot of memory and it might not be possible to load all data at once. Instead, loop through subjects and collect summary statistics. make : bool If the target file does not exist, create it (could take a long time depending on the test; if False, raise an IOError). ... State parameters (Use the ``group`` state parameter to select the subject group for which to perform the test). Returns ------- ds : Dataset (if return_data==True) Data that forms the basis of the test. res : NDTest | ROITestResult Test result for the specified test (when performing tests in ROIs, an :class:`~_experiment.ROITestResult` object is returned). """ self.set(test=test, **state) data = TestDims.coerce(data, morph=True) self._set_analysis_options(data, baseline, src_baseline, pmin, tstart, tstop, parc, mask) return self._load_test(test, tstart, tstop, pmin, parc, mask, samples, data, baseline, src_baseline, return_data, make) def _load_test(self, test, tstart, tstop, pmin, parc, mask, samples, data, baseline, src_baseline, return_data, make): "Load a cached test after _set_analysis_options() has been called" test_obj = self._tests[test] dst = self.get('test-file', mkdir=True) # try to load cached test res = None desc = self._get_rel('test-file', 'test-dir') if self._result_file_mtime(dst, data): try: res = load.unpickle(dst) if data.source is True: update_subjects_dir(res, self.get('mri-sdir'), 2) except OldVersionError: res = None else: if res.samples >= samples or res.samples == -1: self._log.info("Load cached test: %s", desc) if not return_data: return res elif not make: raise IOError("The requested test %s is cached with " "samples=%i, but you request samples=%i; Set " "make=True to perform the test." % (desc, res.samples, samples)) else: res = None elif not make and exists(dst): raise IOError("The requested test is outdated: %s. Set make=True " "to perform the test." % desc) if res is None and not make: raise IOError("The requested test is not cached: %s. Set make=True " "to perform the test." % desc) # parc/mask parc_dim = None if data.source is True: if parc: mask = True parc_dim = 'source' elif mask: if pmin is None: # can as well collect dist for parc parc_dim = 'source' elif isinstance(data.source, str): if not isinstance(parc, str): raise TypeError(f"parc needs to be set for ROI test (data={data.string!r})") elif mask is not None: raise TypeError(f"mask={mask!r}: invalid for data={data.string!r}") elif parc is not None: raise TypeError(f"parc={parc!r}: invalid for data={data.string!r}") elif mask is not None: raise TypeError(f"mask={mask!r}: invalid for data={data.string!r}") do_test = res is None if do_test: test_kwargs = self._test_kwargs(samples, pmin, tstart, tstop, data, parc_dim) else: test_kwargs = None if isinstance(test_obj, TwoStageTest): if isinstance(data.source, str): res_data, res = self._make_test_rois_2stage(baseline, src_baseline, test_obj, samples, test_kwargs, res, data, return_data) elif data.source is True: res_data, res = self._make_test_2stage(baseline, src_baseline, mask, test_obj, test_kwargs, res, data, return_data) else: raise NotImplementedError(f"Two-stage test with data={data.string!r}") elif isinstance(data.source, str): res_data, res = self._make_test_rois(baseline, src_baseline, test_obj, samples, pmin, test_kwargs, res, data) else: if data.sensor: res_data = self.load_evoked(True, baseline, True, test_obj._within_cat, data=data, vardef=test_obj.vars) elif data.source: res_data = self.load_evoked_stc(True, baseline, src_baseline, morph=True, cat=test_obj._within_cat, mask=mask, vardef=test_obj.vars) else: raise ValueError(f"data={data.string!r}") if do_test: self._log.info("Make test: %s", desc) res = self._make_test(data.y_name, res_data, test_obj, test_kwargs) if do_test: save.pickle(res, dst) if return_data: return res_data, res else: return res @staticmethod def _src_to_label_tc(ds, func): src = ds.pop('src') out = {} for label in src.source.parc.cells: if label.startswith('unknown-'): continue label_ds = ds.copy() label_ds['label_tc'] = getattr(src, func)(source=label) out[label] = label_ds return out def _make_test_rois(self, baseline, src_baseline, test_obj, samples, pmin, test_kwargs, res, data): # load data dss_list = [] n_trials_dss = [] labels = set() subjects = self.get_field_values('subject') for _ in self.iter(progress_bar="Loading data"): ds = self.load_evoked_stc(1, baseline, src_baseline, vardef=test_obj.vars) dss = self._src_to_label_tc(ds, data.source) n_trials_dss.append(ds) dss_list.append(dss) labels.update(dss.keys()) label_dss = {label: [dss[label] for dss in dss_list if label in dss] for label in labels} label_data = {label: combine(dss, incomplete='drop') for label, dss in label_dss.items()} if res is not None: return label_data, res n_trials_ds = combine(n_trials_dss, incomplete='drop') # n subjects per label n_per_label = {label: len(dss) for label, dss in label_dss.items()} # compute results do_mcc = ( len(labels) > 1 and # more than one ROI pmin not in (None, 'tfce') and # not implemented len(set(n_per_label.values())) == 1 # equal n permutations ) label_results = { label: self._make_test('label_tc', ds, test_obj, test_kwargs, do_mcc) for label, ds in label_data.items() } if do_mcc: cdists = [res._cdist for res in label_results.values()] merged_dist = _MergedTemporalClusterDist(cdists) else: merged_dist = None res = ROITestResult(subjects, samples, n_trials_ds, merged_dist, label_results) return label_data, res def _make_test_rois_2stage(self, baseline, src_baseline, test_obj, samples, test_kwargs, res, data, return_data): # stage 1 lms = [] res_data = [] n_trials_dss = [] subjects = self.get_field_values('subject') for subject in self.iter(progress_bar="Loading stage 1 models"): if test_obj.model is None: ds = self.load_epochs_stc(1, baseline, src_baseline, mask=True, vardef=test_obj.vars) else: ds = self.load_evoked_stc(1, baseline, src_baseline, mask=True, vardef=test_obj.vars, model=test_obj._within_model) dss = self._src_to_label_tc(ds, data.source) if res is None: lms.append({label: test_obj.make_stage_1('label_tc', ds, subject) for label, ds in dss.items()}) n_trials_dss.append(ds) if return_data: res_data.append(dss) # stage 2 if res is None: labels = set(chain.from_iterable(lms)) ress = {} for label in sorted(labels): label_lms = [subject_lms[label] for subject_lms in lms if label in subject_lms] if len(label_lms) <= 2: continue ress[label] = test_obj.make_stage_2(label_lms, test_kwargs) n_trials_ds = combine(n_trials_dss, incomplete='drop') res = ROI2StageResult(subjects, samples, n_trials_ds, None, ress) if return_data: data_out = {} for label in res.keys(): label_data = [subject_data[label] for subject_data in res_data if label in subject_data] data_out[label] = combine(label_data) else: data_out = None return data_out, res def _make_test_2stage(self, baseline, src_baseline, mask, test_obj, test_kwargs, res, data, return_data): # stage 1 lms = [] res_data = [] for subject in self.iter(progress_bar="Loading stage 1 models"): if test_obj.model is None: ds = self.load_epochs_stc(1, baseline, src_baseline, morph=True, mask=mask, vardef=test_obj.vars) else: ds = self.load_evoked_stc(1, baseline, src_baseline, morph=True, mask=mask, vardef=test_obj.vars, model=test_obj._within_model) if res is None: lms.append(test_obj.make_stage_1(data.y_name, ds, subject)) if return_data: res_data.append(ds) # stage 2 if res is None: res = test_obj.make_stage_2(lms, test_kwargs) if return_data: res_data = combine(res_data) return res_data, res def make_annot(self, redo=False, **state): """Make sure the annot files for both hemispheres exist Parameters ---------- redo : bool Even if the file exists, recreate it (default False). ... State parameters. Returns ------- mtime : float | None Modification time of the existing files, or None if they were newly created. """ self.set(**state) # variables parc, p = self._get_parc() if p is None: return mrisubject = self.get('mrisubject') common_brain = self.get('common_brain') mtime = self._annot_file_mtime() if mrisubject != common_brain: is_fake = is_fake_mri(self.get('mri-dir')) if p.morph_from_fsaverage or is_fake: # make sure annot exists for common brain self.set(mrisubject=common_brain, match=False) common_brain_mtime = self.make_annot() self.set(mrisubject=mrisubject, match=False) if not redo and cache_valid(mtime, common_brain_mtime): return mtime elif is_fake: for _ in self.iter('hemi'): self.make_copy('annot-file', 'mrisubject', common_brain, mrisubject) else: self.get('label-dir', make=True) subjects_dir = self.get('mri-sdir') for hemi in ('lh', 'rh'): cmd = ["mri_surf2surf", "--srcsubject", common_brain, "--trgsubject", mrisubject, "--sval-annot", parc, "--tval", parc, "--hemi", hemi] subp.run_freesurfer_command(cmd, subjects_dir) fix_annot_names(mrisubject, parc, common_brain, subjects_dir=subjects_dir) return if not redo and mtime: return mtime elif not p.make: if redo and mtime: raise RuntimeError( f"The {parc} parcellation cannot be created automatically " f"for {mrisubject}. Please update the corresponding " f"*.annot files manually.") else: raise RuntimeError( f"The {parc} parcellation cannot be created automatically " f"and is missing for {mrisubject}. Please add the " f"corresponding *.annot files to the subject's label " f"directory.") # make parcs: common_brain | non-morphed labels = self._make_annot(parc, p, mrisubject) write_labels_to_annot(labels, mrisubject, parc, True, self.get('mri-sdir')) def _make_annot(self, parc, p, subject): """Return labels Notes ----- Only called to make custom annotation files for the common_brain """ subjects_dir = self.get('mri-sdir') if isinstance(p, CombinationParc): with self._temporary_state: base = {l.name: l for l in self.load_annot(parc=p.base)} labels = [] for name, exp in p.labels.items(): labels += combination_label(name, exp, base, subjects_dir) elif isinstance(p, SeededParc): if p.mask: with self._temporary_state: self.make_annot(parc=p.mask) name, extent = SEEDED_PARC_RE.match(parc).groups() labels = labels_from_mni_coords( p.seeds_for_subject(subject), float(extent), subject, p.surface, p.mask, subjects_dir, parc) elif isinstance(p, EelbrainParc) and p.name == 'lobes': if subject != 'fsaverage': raise RuntimeError("lobes parcellation can only be created for " "fsaverage, not for %s" % subject) # load source annot with self._temporary_state: labels = self.load_annot(parc='PALS_B12_Lobes') # sort labels labels = [l for l in labels if l.name[:-3] != 'MEDIAL.WALL'] # rename good labels rename_label(labels, 'LOBE.FRONTAL', 'frontal') rename_label(labels, 'LOBE.OCCIPITAL', 'occipital') rename_label(labels, 'LOBE.PARIETAL', 'parietal') rename_label(labels, 'LOBE.TEMPORAL', 'temporal') # reassign unwanted labels targets = ('frontal', 'occipital', 'parietal', 'temporal') dissolve_label(labels, 'LOBE.LIMBIC', targets, subjects_dir) dissolve_label(labels, 'GYRUS', targets, subjects_dir, 'rh') dissolve_label(labels, '???', targets, subjects_dir) dissolve_label(labels, '????', targets, subjects_dir, 'rh') dissolve_label(labels, '???????', targets, subjects_dir, 'rh') elif isinstance(p, LabelParc): labels = [] hemis = ('lh.', 'rh.') path = join(subjects_dir, subject, 'label', '%s.label') for label in p.labels: if label.startswith(hemis): labels.append(mne.read_label(path % label)) else: labels.extend(mne.read_label(path % (hemi + label)) for hemi in hemis) else: raise NotImplementedError( "At least one of the annot files for the custom parcellation " "%r is missing for %r, and a make function is not " "implemented." % (parc, subject)) return labels def make_bad_channels(self, bad_chs=(), redo=False, **kwargs): """Write the bad channel definition file for a raw file If the file already exists, new bad channels are added to the old ones. In order to replace the old file with only the new values, set ``redo=True``. Parameters ---------- bad_chs : iterator of str Names of the channels to set as bad. Numerical entries are interpreted as "MEG XXX". If bad_chs contains entries not present in the raw data, a ValueError is raised. redo : bool If the file already exists, replace it (instead of adding). ... State parameters. See Also -------- make_bad_channels_auto : find bad channels automatically load_bad_channels : load the current bad_channels file merge_bad_channels : merge bad channel definitions for all sessions """ pipe = self._raw[self.get('raw', **kwargs)] pipe.make_bad_channels(self.get('subject'), self.get('recording'), bad_chs, redo) def make_bad_channels_auto(self, flat=1e-14, redo=False, **state): """Automatically detect bad channels Works on ``raw='raw'`` Parameters ---------- flat : scalar Threshold for detecting flat channels: channels with ``std < flat`` are considered bad (default 1e-14). redo : bool If the file already exists, replace it (instead of adding). ... State parameters. """ if state: self.set(**state) pipe = self._raw['raw'] pipe.make_bad_channels_auto(self.get('subject'), self.get('recording'), flat, redo) def make_bad_channels_neighbor_correlation(self, r, epoch=None, **state): """Exclude bad channels based on low average neighbor-correlation Parameters ---------- r : scalar Minimum admissible neighbor correlation. Any channel whose average correlation with its neighbors is below this value is added to the list of bad channels (e.g., 0.3). epoch : str Epoch to use for computing neighbor-correlation (by default, the whole session is used). ... State parameters. Notes ----- Data is loaded for the currently specified ``raw`` setting, but bad channels apply to all ``raw`` settings equally. Hence, when using this method with multiple subjects, it is important to set ``raw`` to the same value. """ nc = self.load_neighbor_correlation(1, epoch, **state) bad_chs = nc.sensor.names[nc < r] if bad_chs: self.make_bad_channels(bad_chs) def make_besa_evt(self, redo=False, **state): """Make the trigger and event files needed for besa Parameters ---------- redo : bool If besa files already exist, overwrite them. ... State parameters. Notes ----- Ignores the *decim* epoch parameter. Target files are saved relative to the *besa-root* location. """ self.set(**state) rej = self.get('rej') trig_dest = self.get('besa-trig', rej='', mkdir=True) evt_dest = self.get('besa-evt', rej=rej, mkdir=True) if not redo and exists(evt_dest) and exists(trig_dest): return # load events ds = self.load_selected_events(reject='keep') # save triggers if redo or not exists(trig_dest): save.meg160_triggers(ds, trig_dest, pad=1) if not redo and exists(evt_dest): return else: ds.index('besa_index', 1) # reject bad trials ds = ds.sub('accept') # save evt epoch = self._epochs[self.get('epoch')] save.besa_evt(ds, tstart=epoch.tmin, tstop=epoch.tmax, dest=evt_dest) def make_copy(self, temp, field, src, dst, redo=False): """Make a copy of a file to a new path by substituting one field value Parameters ---------- temp : str Template of the file which to copy. field : str Field in which the source and target of the link are distinguished. src : str Value for field on the source file. dst : str Value for field on the destination filename. redo : bool If the target file already exists, overwrite it. See Also -------- copy : Copy muliple files to a different root directory """ dst_path = self.get(temp, mkdir=True, **{field: dst}) if not redo and exists(dst_path): return src_path = self.get(temp, **{field: src}) if isdir(src_path): raise ValueError("Can only copy files, not directories.") shutil.copyfile(src_path, dst_path) def make_cov(self): "Make a noise covariance (cov) file" dest = self.get('cov-file', mkdir=True) if exists(dest): mtime = self._cov_mtime() if mtime and getmtime(dest) > mtime: return self._log.debug("Make cov-file %s", dest) params = self._covs[self.get('cov')] method = params.get('method', 'empirical') keep_sample_mean = params.get('keep_sample_mean', True) reg = params.get('reg', None) if 'epoch' in params: with self._temporary_state: ds = self.load_epochs(None, True, False, decim=1, epoch=params['epoch']) epochs = ds['epochs'] cov = mne.compute_covariance(epochs, keep_sample_mean, method=method) info = epochs.info else: with self._temporary_state: raw = self.load_raw(session=params['session']) cov = mne.compute_raw_covariance(raw, method=method) info = raw.info epochs = None if reg is True: cov = mne.cov.regularize(cov, info, rank=None) elif isinstance(reg, dict): cov = mne.cov.regularize(cov, info, **reg) elif reg == 'best': if mne.pick_types(epochs.info, meg='grad', eeg=True, ref_meg=False).size: raise NotImplementedError("EEG or gradiometer sensors") elif epochs is None: raise NotImplementedError("reg='best' for raw covariance") reg_vs = np.arange(0, 0.21, 0.01) covs = [mne.cov.regularize(cov, epochs.info, mag=v, rank=None) for v in reg_vs] # compute whitened global field power evoked = epochs.average() picks = mne.pick_types(evoked.info, meg='mag', ref_meg=False) gfps = [mne.whiten_evoked(evoked, cov, picks).data.std(0) for cov in covs] # apply padding t_pad = params.get('reg_eval_win_pad', 0) if t_pad: n_pad = int(t_pad * epochs.info['sfreq']) if len(gfps[0]) <= 2 * n_pad: msg = "Covariance padding (%s) is bigger than epoch" % t_pad raise ValueError(msg) padding = slice(n_pad, -n_pad) gfps = [gfp[padding] for gfp in gfps] vs = [gfp.mean() for gfp in gfps] i = np.argmin(np.abs(1 - np.array(vs))) cov = covs[i] # save cov value with open(self.get('cov-info-file', mkdir=True), 'w') as fid: fid.write('%s\n' % reg_vs[i]) elif reg is not None: raise RuntimeError(f"reg={reg!r} in {params}") cov.save(dest) def _make_evoked(self, decim, data_raw): """Make files with evoked sensor data. Parameters ---------- decim : int Data decimation factor (the default is the factor specified in the epoch definition). """ dst = self.get('evoked-file', mkdir=True) epoch = self._epochs[self.get('epoch')] # determine whether using default decimation if decim: if epoch.decim: default_decim = decim == epoch.decim else: raw = self.load_raw(False) default_decim = decim == raw.info['sfreq'] / epoch.samplingrate else: default_decim = True use_cache = default_decim model = self.get('model') equal_count = self.get('equalize_evoked_count') == 'eq' if use_cache and exists(dst) and cache_valid(getmtime(dst), self._evoked_mtime()): ds = self.load_selected_events(data_raw=data_raw) ds = ds.aggregate(model, drop_bad=True, equal_count=equal_count, drop=('i_start', 't_edf', 'T', 'index', 'trigger')) ds['evoked'] = mne.read_evokeds(dst, proj=False) return ds self._log.debug("Make evoked %s", dst) # load the epochs (post baseline-correction trigger shift requires # baseline corrected evoked if epoch.post_baseline_trigger_shift: ds = self.load_epochs(ndvar=False, baseline=True, decim=decim, data_raw=data_raw, interpolate_bads='keep') else: ds = self.load_epochs(ndvar=False, decim=decim, data_raw=data_raw, interpolate_bads='keep') # aggregate ds_agg = ds.aggregate(model, drop_bad=True, equal_count=equal_count, drop=('i_start', 't_edf', 'T', 'index', 'trigger'), never_drop=('epochs',)) ds_agg.rename('epochs', 'evoked') # save for e in ds_agg['evoked']: e.info['description'] = f"Eelbrain {CACHE_STATE_VERSION}" if use_cache: mne.write_evokeds(dst, ds_agg['evoked']) return ds_agg def make_fwd(self): """Make the forward model""" subject = self.get('subject') fwd_recording = self._get_fwd_recording(subject) with self._temporary_state: dst = self.get('fwd-file', recording=fwd_recording) if exists(dst): if cache_valid(getmtime(dst), self._fwd_mtime(subject, fwd_recording=fwd_recording)): return dst # get trans for correct visit for fwd_session trans = self.get('trans-file') src = self.get('src-file', make=True) pipe = self._raw[self.get('raw')] raw = pipe.load(subject, fwd_recording) bem = self._load_bem() src = mne.read_source_spaces(src) self._log.debug(f"make_fwd {basename(dst)}...") bemsol = mne.make_bem_solution(bem) fwd = mne.make_forward_solution(raw.info, trans, src, bemsol, ignore_ref=True) for s, s0 in zip(fwd['src'], src): if s['nuse'] != s0['nuse']: raise RuntimeError(f"The forward solution {basename(dst)} contains fewer sources than the source space. This could be due to a corrupted bem file with sources outside of the inner skull surface.") mne.write_forward_solution(dst, fwd, True) return dst def make_ica_selection(self, epoch=None, decim=None, session=None, **state): """Select ICA components to remove through a GUI Parameters ---------- epoch : str Epoch to use for visualization in the GUI (default is to use the raw data). decim : int Downsample data for visualization (to improve GUI performance; for raw data, the default is ~100 Hz, for epochs the default is the epoch setting). session : str | list of str One or more sessions for which to plot the raw data (this parameter can not be used together with ``epoch``; default is the session in the current state). ... State parameters. Notes ----- Computing ICA decomposition can take a while. In order to precompute the decomposition for all subjects before doing the selection use :meth:`.make_ica()` in a loop as in:: >>> for subject in e: ... e.make_ica() ... """ # ICA path = self.make_ica(**state) # display data subject = self.get('subject') pipe = self._raw[self.get('raw')] bads = pipe.load_bad_channels(subject, self.get('recording')) with self._temporary_state, warnings.catch_warnings(): warnings.filterwarnings('ignore', 'The measurement information indicates a low-pass', RuntimeWarning) if epoch is None: if session is None: session = self.get('session') raw = pipe.load_concatenated_source_raw(subject, session, self.get('visit')) events = mne.make_fixed_length_events(raw) ds = Dataset() decim = int(raw.info['sfreq'] // 100) if decim is None else decim ds['epochs'] = mne.Epochs(raw, events, 1, 0, 1, baseline=None, proj=False, decim=decim, preload=True) elif session is not None: raise TypeError(f"session={session!r} with epoch={epoch!r}") else: ds = self.load_epochs(ndvar=False, epoch=epoch, reject=False, raw=pipe.source.name, decim=decim, add_bads=bads) info = ds['epochs'].info data = TestDims('sensor') data_kind = data.data_to_ndvar(info)[0] sysname = pipe.get_sysname(info, subject, data_kind) connectivity = pipe.get_connectivity(data_kind) gui.select_components(path, ds, sysname, connectivity) def make_ica(self, **state): """Compute ICA decomposition for a :class:`pipeline.RawICA` preprocessing step If a corresponding file exists, a basic check is done as to whether the bad channels have changed, and if so the ICA is recomputed. Parameters ---------- ... State parameters. Returns ------- path : str Path to the ICA file. Notes ----- ICA decomposition can take some time. This function can be used to precompute ICA decompositions for all subjects after trial pre-rejection has been completed:: >>> for subject in e: ... e.make_ica() """ if state: self.set(**state) pipe = self._raw[self.get('raw')] if not isinstance(pipe, RawICA): ica_raws = [key for key, pipe in self._raw.items() if isinstance(pipe, RawICA)] if len(ica_raws) > 1: raise ValueError(f"raw={pipe.name!r} does not involve ICA; set raw to an ICA processing step ({enumeration(ica_raws)})") elif len(ica_raws) == 1: print(f"raw: {pipe.name} -> {ica_raws[0]}") return self.make_ica(raw=ica_raws[0]) else: raise RuntimeError("Experiment has no RawICA processing step") return pipe.make_ica(self.get('subject'), self.get('visit')) def make_link(self, temp, field, src, dst, redo=False): """Make a hard link Make a hard link at the file with the ``dst`` value on ``field``, linking to the file with the ``src`` value of ``field``. Parameters ---------- temp : str Template of the file for which to make a link. field : str Field in which the source and target of the link are distinguished. src : str Value for field on the source file. dst : str Value for field on the destination filename. redo : bool If the target file already exists, overwrite it. """ dst_path = self.get(temp, **{field: dst}) if not redo and exists(dst_path): return src_path = self.get(temp, **{field: src}) os.link(src_path, dst_path) def make_mov_ga_dspm(self, subjects=None, baseline=True, src_baseline=False, fmin=2, surf=None, views=None, hemi=None, time_dilation=4., foreground=None, background=None, smoothing_steps=None, dst=None, redo=False, **state): """Make a grand average movie from dSPM values (requires PySurfer 0.6) Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). baseline : bool | tuple Apply baseline correction using this period in sensor space. True to use the epoch's baseline specification (default). src_baseline : bool | tuple Apply baseline correction using this period in source space. True to use the epoch's baseline specification. The default is to not apply baseline correction. fmin : scalar Minimum dSPM value to draw (default 2). fmax is 3 * fmin. surf : str Surface on which to plot data. views : str | tuple of str View(s) of the brain to include in the movie. hemi : 'lh' | 'rh' | 'both' | 'split' Which hemispheres to plot. time_dilation : scalar Factor by which to slow the passage of time. For example, with ``time_dilation=4`` (the default) a segment of data for 500 ms will last 2 s. foreground : mayavi color Figure foreground color (i.e., the text color). background : mayavi color Figure background color. smoothing_steps : None | int Number of smoothing steps if data is spatially undersampled (pysurfer ``Brain.add_data()`` argument). dst : str (optional) Path to save the movie. The default is a file in the results folder with a name determined based on the input data. Plotting parameters (``view`` and all subsequent parameters) are not included in the filename. "~" is expanded to the user's home folder. redo : bool Make the movie even if the target file exists already. ... State parameters. """ state['model'] = '' subject, group = self._process_subject_arg(subjects, state) data = TestDims("source", morph=bool(group)) brain_kwargs = self._surfer_plot_kwargs(surf, views, foreground, background, smoothing_steps, hemi) self._set_analysis_options(data, baseline, src_baseline, None, None, None) self.set(equalize_evoked_count='', resname="GA dSPM %s %s" % (brain_kwargs['surf'], fmin)) if dst is None: if group is None: dst = self.get('subject-mov-file', mkdir=True) else: dst = self.get('group-mov-file', mkdir=True) else: dst = os.path.expanduser(dst) if not redo and self._result_file_mtime(dst, data, group is None): return plot._brain.assert_can_save_movies() if group is None: ds = self.load_evoked_stc(subject, baseline, src_baseline) y = ds['src'] else: ds = self.load_evoked_stc(group, baseline, src_baseline, morph=True) y = ds['srcm'] brain = plot.brain.dspm(y, fmin, fmin * 3, colorbar=False, **brain_kwargs) brain.save_movie(dst, time_dilation) brain.close() def make_mov_ttest(self, subjects=None, model='', c1=None, c0=None, p=0.05, baseline=True, src_baseline=False, surf=None, views=None, hemi=None, time_dilation=4., foreground=None, background=None, smoothing_steps=None, dst=None, redo=False, **state): """Make a t-test movie (requires PySurfer 0.6) Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). model : None | str Model on which the conditions c1 and c0 are defined. The default (``''``) is the grand average. c1 : None | str | tuple Test condition (cell in model). If None, the grand average is used and c0 has to be a scalar. c0 : str | scalar Control condition (cell on model) or scalar against which to compare c1. p : 0.1 | 0.05 | 0.01 | .001 Maximum p value to draw. baseline : bool | tuple Apply baseline correction using this period in sensor space. True to use the epoch's baseline specification (default). src_baseline : bool | tuple Apply baseline correction using this period in source space. True to use the epoch's baseline specification. The default is to not apply baseline correction. surf : str Surface on which to plot data. views : str | tuple of str View(s) of the brain to include in the movie. hemi : 'lh' | 'rh' | 'both' | 'split' Which hemispheres to plot. time_dilation : scalar Factor by which to slow the passage of time. For example, with ``time_dilation=4`` (the default) a segment of data for 500 ms will last 2 s. foreground : mayavi color Figure foreground color (i.e., the text color). background : mayavi color Figure background color. smoothing_steps : None | int Number of smoothing steps if data is spatially undersampled (pysurfer ``Brain.add_data()`` argument). dst : str (optional) Path to save the movie. The default is a file in the results folder with a name determined based on the input data. Plotting parameters (``view`` and all subsequent parameters) are not included in the filename. "~" is expanded to the user's home folder. redo : bool Make the movie even if the target file exists already. ... State parameters. """ if p == 0.1: pmid = 0.05 pmin = 0.01 elif p == 0.05: pmid = 0.01 pmin = 0.001 elif p == 0.01: pmid = 0.001 pmin = 0.001 elif p == 0.001: pmid = 0.0001 pmin = 0.00001 else: raise ValueError("p=%s" % p) data = TestDims("source", morph=True) brain_kwargs = self._surfer_plot_kwargs(surf, views, foreground, background, smoothing_steps, hemi) surf = brain_kwargs['surf'] if model: if not c1: raise ValueError("If x is specified, c1 needs to be specified; " "got c1=%s" % repr(c1)) elif c0: resname = "t-test %s-%s {test_options} %s" % (c1, c0, surf) cat = (c1, c0) else: resname = "t-test %s {test_options} %s" % (c1, surf) cat = (c1,) elif c1 or c0: raise ValueError("If x is not specified, c1 and c0 should not be " "specified either; got c1=%s, c0=%s" % (repr(c1), repr(c0))) else: resname = "t-test GA {test_options} %s" % surf cat = None state.update(resname=resname, model=model) with self._temporary_state: subject, group = self._process_subject_arg(subjects, state) self._set_analysis_options(data, baseline, src_baseline, p, None, None) if dst is None: if group is None: dst = self.get('subject-mov-file', mkdir=True) else: dst = self.get('group-mov-file', mkdir=True) else: dst = os.path.expanduser(dst) if not redo and self._result_file_mtime(dst, data, group is None): return plot._brain.assert_can_save_movies() if group is None: ds = self.load_epochs_stc(subject, baseline, src_baseline, cat=cat) y = 'src' else: ds = self.load_evoked_stc(group, baseline, src_baseline, morph=True, cat=cat) y = 'srcm' # find/apply cluster criteria state = self._cluster_criteria_kwargs(data) if state: state.update(samples=0, pmin=p) # compute t-maps if c0: if group: res = testnd.ttest_rel(y, model, c1, c0, match='subject', ds=ds, **state) else: res = testnd.ttest_ind(y, model, c1, c0, ds=ds, **state) else: res = testnd.ttest_1samp(y, ds=ds, **state) # select cluster-corrected t-map if state: tmap = res.masked_parameter_map(None) else: tmap = res.t # make movie brain = plot.brain.dspm(tmap, ttest_t(p, res.df), ttest_t(pmin, res.df), ttest_t(pmid, res.df), surf=surf) brain.save_movie(dst, time_dilation) brain.close() def make_mrat_evoked(self, **kwargs): """Produce the sensor data fiff files needed for MRAT sensor analysis Parameters ---------- ... State parameters. Examples -------- To produce evoked files for all subjects in the experiment: >>> experiment.set(model='factor1%factor2') >>> for _ in experiment: >>> experiment.make_mrat_evoked() ... """ ds = self.load_evoked(ndvar=False, **kwargs) # create fiffs model = self.get('model') factors = [f.strip() for f in model.split('%')] for case in ds.itercases(): condition = '_'.join(case[f] for f in factors) path = self.get('mrat-sns-file', mkdir=True, mrat_condition=condition) evoked = case['evoked'] evoked.save(path) def make_mrat_stcs(self, **kwargs): """Produce the STC files needed for the MRAT analysis tool Parameters ---------- ... State parameters. Examples -------- To produce stc files for all subjects in the experiment: >>> experiment.set_inv('free') >>> experiment.set(model='factor1%factor2') >>> for _ in experiment: >>> experiment.make_mrat_stcs() ... """ ds = self.load_evoked_stc(morph=True, ndvar=False, **kwargs) # save condition info info_file = self.get('mrat_info-file', mkdir=True) ds.save_txt(info_file) # create stcs model = self.get('model') factors = [f.strip() for f in model.split('%')] for case in ds.itercases(): condition = '_'.join(case[f] for f in factors) path = self.get('mrat-src-file', mkdir=True, mrat_condition=condition) stc = case['stcm'] stc.save(path) def make_plot_annot(self, surf='inflated', redo=False, **state): """Create a figure for the contents of an annotation file Parameters ---------- surf : str FreeSurfer surface on which to plot the annotation. redo : bool If the target file already exists, overwrite it. ... State parameters. """ if is_fake_mri(self.get('mri-dir', **state)): mrisubject = self.get('common_brain') self.set(mrisubject=mrisubject, match=False) dst = self.get('res-file', mkdir=True, ext='png', analysis='Source Annot', resname="{parc} {mrisubject} %s" % surf) if not redo and exists(dst): return brain = self.plot_annot(surf=surf, axw=600) brain.save_image(dst, 'rgba', True) legend = brain.plot_legend(show=False) legend.save(dst[:-3] + 'pdf', transparent=True) brain.close() legend.close() def make_plot_label(self, label, surf='inflated', redo=False, **state): if is_fake_mri(self.get('mri-dir', **state)): mrisubject = self.get('common_brain') self.set(mrisubject=mrisubject, match=False) dst = self._make_plot_label_dst(surf, label) if not redo and exists(dst): return brain = self.plot_label(label, surf=surf) brain.save_image(dst, 'rgba', True) def make_plots_labels(self, surf='inflated', redo=False, **state): self.set(**state) with self._temporary_state: if is_fake_mri(self.get('mri-dir')): self.set(mrisubject=self.get('common_brain'), match=False) labels = tuple(self._load_labels().values()) dsts = [self._make_plot_label_dst(surf, label.name) for label in labels] if not redo and all(exists(dst) for dst in dsts): return brain = self.plot_brain(surf, None, 'split', ['lat', 'med'], w=1200) for label, dst in zip(labels, dsts): brain.add_label(label) brain.save_image(dst, 'rgba', True) brain.remove_labels(hemi='lh') def _make_plot_label_dst(self, surf, label): return self.get('res-deep-file', mkdir=True, analysis='Source Labels', folder="{parc} {mrisubject} %s" % surf, resname=label, ext='png') def make_raw(self, **kwargs): """Make a raw file Parameters ---------- ... State parameters. Notes ----- Due to the electronics of the KIT system sensors, signal lower than 0.16 Hz is not recorded even when recording at DC. """ if kwargs: self.set(**kwargs) pipe = self._raw[self.get('raw')] pipe.cache(self.get('subject'), self.get('recording')) def make_epoch_selection(self, decim=None, auto=None, overwrite=None, **state): """Open :func:`gui.select_epochs` for manual epoch selection The GUI is opened with the correct file name; if the corresponding file exists, it is loaded, and upon saving the correct path is the default. Parameters ---------- decim : int Decimate epochs for the purpose of faster display. Decimation is applied relative to the raw data file (i.e., if the raw data is sampled at a 1000 Hz, ``decim=10`` results in a sampling rate of 100 Hz for display purposes. The default is to use the decim parameter specified in the epoch definition. auto : scalar (optional) Perform automatic rejection instead of showing the GUI by supplying a an absolute threshold (for example, ``1e-12`` to reject any epoch in which the absolute of at least one channel exceeds 1 picotesla). If a rejection file already exists also set ``overwrite=True``. overwrite : bool If ``auto`` is specified and a rejection file already exists, overwrite the old file. The default is to raise an error if the file exists (``None``). Set to ``False`` to quietly keep the exising file. ... State parameters. """ rej = self.get('rej', **state) rej_args = self._artifact_rejection[rej] if rej_args['kind'] != 'manual': raise ValueError(f"rej={rej!r}; Epoch rejection is not manual") epoch = self._epochs[self.get('epoch')] if not isinstance(epoch, PrimaryEpoch): if isinstance(epoch, SecondaryEpoch): raise ValueError(f"The current epoch {epoch.name!r} inherits selections from {epoch.sel_epoch!r}. To access a rejection file for this epoch, call `e.set(epoch={epoch.sel_epoch!r})` and then call `e.make_epoch_selection()` again.") elif isinstance(epoch, SuperEpoch): raise ValueError(f"The current epoch {epoch.name!r} inherits selections from these other epochs: {epoch.sub_epochs!r}. To access selections for these epochs, call `e.make_epoch_selection(epoch=epoch)` for each.") else: raise ValueError(f"The current epoch {epoch.name!r} is not a primary epoch and inherits selections from other epochs. Generate trial rejection for these epochs.") path = self.get('rej-file', mkdir=True, session=epoch.session) if auto is not None and overwrite is not True and exists(path): if overwrite is False: return elif overwrite is None: raise IOError(self.format("A rejection file already exists for {subject}, epoch {epoch}, rej {rej}. Set the overwrite parameter to specify how to handle existing files.")) else: raise TypeError(f"overwrite={overwrite!r}") ds = self.load_epochs(reject=False, trigger_shift=False, decim=decim) has_meg = 'meg' in ds has_grad = 'grad' in ds has_eeg = 'eeg' in ds has_eog = 'eog' in ds if sum((has_meg, has_grad, has_eeg)) > 1: raise NotImplementedError("Rejection GUI for multiple channel types") elif has_meg: y_name = 'meg' vlim = 2e-12 elif has_grad: raise NotImplementedError("Rejection GUI for gradiometer data") elif has_eeg: y_name = 'eeg' vlim = 1.5e-4 else: raise RuntimeError("No data found") if has_eog: eog_sns = [] # TODO: use EOG else: eog_sns = self._eog_sns.get(ds[y_name].sensor.sysname) if auto is not None: # create rejection rej_ds = new_rejection_ds(ds) rej_ds[:, 'accept'] = ds[y_name].abs().max(('sensor', 'time')) <= auto # create description for info args = [f"auto={auto!r}"] if overwrite is True: args.append("overwrite=True") if decim is not None: args.append(f"decim={decim!r}") rej_ds.info['desc'] = f"Created with {self.__class__.__name__}.make_epoch_selection({', '.join(args)})" # save save.pickle(rej_ds, path) # print info n_rej = rej_ds.eval("sum(accept == False)") print(self.format(f"{n_rej} of {rej_ds.n_cases} epochs rejected with threshold {auto} for {{subject}}, epoch {{epoch}}")) return # don't mark eog sns if it is bad bad_channels = self.load_bad_channels() eog_sns = [c for c in eog_sns if c not in bad_channels] gui.select_epochs(ds, y_name, path=path, vlim=vlim, mark=eog_sns) def _need_not_recompute_report(self, dst, samples, data, redo): "Check (and log) whether the report needs to be redone" desc = self._get_rel('report-file', 'res-dir') if not exists(dst): self._log.debug("New report: %s", desc) elif redo: self._log.debug("Redoing report: %s", desc) elif not self._result_file_mtime(dst, data): self._log.debug("Report outdated: %s", desc) else: meta = read_meta(dst) if 'samples' in meta: if int(meta['samples']) >= samples: self._log.debug("Report up to date: %s", desc) return True else: self._log.debug("Report file used %s samples, recomputing " "with %i: %s", meta['samples'], samples, desc) else: self._log.debug("Report created prior to Eelbrain 0.25, can " "not check number of samples. Delete manually " "to recompute: %s", desc) return True def make_report(self, test, parc=None, mask=None, pmin=None, tstart=None, tstop=None, samples=10000, baseline=True, src_baseline=None, include=0.2, redo=False, **state): """Create an HTML report on spatio-temporal clusters Parameters ---------- test : str Test for which to create a report (entry in MneExperiment.tests). parc : None | str Find clusters in each label of parc (as opposed to the whole brain). mask : None | str Parcellation to apply as mask. Can only be specified if parc==None. pmin : None | scalar, 1 > pmin > 0 | 'tfce' Equivalent p-value for cluster threshold, or 'tfce' for threshold-free cluster enhancement. tstart : scalar Beginning of the time window for the test in seconds (default is the beginning of the epoch). tstop : scalar End of the time window for the test in seconds (default is the end of the epoch). samples : int > 0 Number of samples used to determine cluster p values for spatio- temporal clusters (default 10,000). baseline : bool | tuple Apply baseline correction using this period in sensor space. True to use the epoch's baseline specification (default). src_baseline : bool | tuple Apply baseline correction using this period in source space. True to use the epoch's baseline specification. The default is to not apply baseline correction. include : 0 < scalar <= 1 Create plots for all clusters with p-values smaller or equal this value. redo : bool If the target file already exists, delete and recreate it. This only applies to the HTML result file, not to the test. ... State parameters. See Also -------- load_test : load corresponding data and tests """ if samples < 1: raise ValueError("samples needs to be > 0") elif include <= 0 or include > 1: raise ValueError("include needs to be 0 < include <= 1, got %s" % repr(include)) self.set(**state) data = TestDims('source', morph=True) self._set_analysis_options(data, baseline, src_baseline, pmin, tstart, tstop, parc, mask) dst = self.get('report-file', mkdir=True, test=test) if self._need_not_recompute_report(dst, samples, data, redo): return # start report title = self.format('{recording} {test_desc}') report = Report(title) report.add_paragraph(self._report_methods_brief(dst)) if isinstance(self._tests[test], TwoStageTest): self._two_stage_report(report, data, test, baseline, src_baseline, pmin, samples, tstart, tstop, parc, mask, include) else: self._evoked_report(report, data, test, baseline, src_baseline, pmin, samples, tstart, tstop, parc, mask, include) # report signature report.sign(('eelbrain', 'mne', 'surfer', 'scipy', 'numpy')) report.save_html(dst, meta={'samples': samples}) def _evoked_report(self, report, data, test, baseline, src_baseline, pmin, samples, tstart, tstop, parc, mask, include): # load data ds, res = self._load_test(test, tstart, tstop, pmin, parc, mask, samples, data, baseline, src_baseline, True, True) # info surfer_kwargs = self._surfer_plot_kwargs() self._report_test_info(report.add_section("Test Info"), ds, test, res, data, include) if parc: section = report.add_section(parc) caption = "Labels in the %s parcellation." % parc self._report_parc_image(section, caption) elif mask: title = "Whole Brain Masked by %s" % mask section = report.add_section(title) caption = "Mask: %s" % mask.capitalize() self._report_parc_image(section, caption) colors = plot.colors_for_categorial(ds.eval(res._plot_model())) report.append(_report.source_time_results(res, ds, colors, include, surfer_kwargs, parc=parc)) def _two_stage_report(self, report, data, test, baseline, src_baseline, pmin, samples, tstart, tstop, parc, mask, include): test_obj = self._tests[test] return_data = test_obj._within_model is not None rlm = self._load_test(test, tstart, tstop, pmin, parc, mask, samples, data, baseline, src_baseline, return_data, True) if return_data: group_ds, rlm = rlm else: group_ds = None # start report surfer_kwargs = self._surfer_plot_kwargs() info_section = report.add_section("Test Info") if parc: section = report.add_section(parc) caption = "Labels in the %s parcellation." % parc self._report_parc_image(section, caption) elif mask: title = "Whole Brain Masked by %s" % mask section = report.add_section(title) caption = "Mask: %s" % mask.capitalize() self._report_parc_image(section, caption) # Design matrix section = report.add_section("Design Matrix") section.append(rlm.design()) # add results to report for term in rlm.column_names: res = rlm.tests[term] ds = rlm.coefficients_dataset(term) report.append( _report.source_time_results( res, ds, None, include, surfer_kwargs, term, y='coeff')) self._report_test_info(info_section, group_ds or ds, test_obj, res, data) def make_report_rois(self, test, parc=None, pmin=None, tstart=None, tstop=None, samples=10000, baseline=True, src_baseline=False, redo=False, **state): """Create an HTML report on ROI time courses Parameters ---------- test : str Test for which to create a report (entry in MneExperiment.tests). parc : str Parcellation that defines ROIs. pmin : None | scalar, 1 > pmin > 0 | 'tfce' Equivalent p-value for cluster threshold, or 'tfce' for threshold-free cluster enhancement. tstart : scalar Beginning of the time window for the test in seconds (default is the beginning of the epoch). tstop : scalar End of the time window for the test in seconds (default is the end of the epoch). samples : int > 0 Number of samples used to determine cluster p values for spatio- temporal clusters (default 1000). baseline : bool | tuple Apply baseline correction using this period in sensor space. True to use the epoch's baseline specification (default). src_baseline : bool | tuple Apply baseline correction using this period in source space. True to use the epoch's baseline specification. The default is to not apply baseline correction. redo : bool If the target file already exists, delete and recreate it. ... State parameters. See Also -------- load_test : load corresponding data and tests (use ``data="source.mean"``) """ test_obj = self._tests[test] if samples < 1: raise ValueError("Need samples > 0 to run permutation test.") elif isinstance(test_obj, TwoStageTest): raise NotImplementedError("ROI analysis not implemented for two-" "stage tests") if parc is not None: state['parc'] = parc parc = self.get('parc', **state) if not parc: raise ValueError("No parcellation specified") data = TestDims('source.mean') self._set_analysis_options(data, baseline, src_baseline, pmin, tstart, tstop, parc) dst = self.get('report-file', mkdir=True, test=test) if self._need_not_recompute_report(dst, samples, data, redo): return res_data, res = self._load_test(test, tstart, tstop, pmin, parc, None, samples, data, baseline, src_baseline, True, True) # sorted labels labels_lh = [] labels_rh = [] for label in res.res.keys(): if label.endswith('-lh'): labels_lh.append(label) elif label.endswith('-rh'): labels_rh.append(label) else: raise NotImplementedError("Label named %s" % repr(label.name)) labels_lh.sort() labels_rh.sort() # start report title = self.format('{recording} {test_desc}') report = Report(title) # method intro (compose it later when data is available) ds0 = res_data[label] res0 = res.res[label] info_section = report.add_section("Test Info") self._report_test_info(info_section, res.n_trials_ds, test_obj, res0, data) # add parc image section = report.add_section(parc) caption = "ROIs in the %s parcellation." % parc self._report_parc_image(section, caption, res.subjects) # add content body n_subjects = len(res.subjects) colors = plot.colors_for_categorial(ds0.eval(res0._plot_model())) for label in chain(labels_lh, labels_rh): res_i = res.res[label] ds = res_data[label] title = label[:-3].capitalize() caption = "Mean in label %s." % label n = len(ds['subject'].cells) if n < n_subjects: title += ' (n=%i)' % n caption += " Data from %i of %i subjects." % (n, n_subjects) section.append(_report.time_results( res_i, ds, colors, title, caption, merged_dist=res.merged_dist)) report.sign(('eelbrain', 'mne', 'surfer', 'scipy', 'numpy')) report.save_html(dst, meta={'samples': samples}) def _make_report_eeg(self, test, pmin=None, tstart=None, tstop=None, samples=10000, baseline=True, include=1, **state): # outdated (cache, load_test()) """Create an HTML report on EEG sensor space spatio-temporal clusters Parameters ---------- test : str Test for which to create a report (entry in MneExperiment.tests). pmin : None | scalar, 1 > pmin > 0 | 'tfce' Equivalent p-value for cluster threshold, or 'tfce' for threshold-free cluster enhancement. tstart : scalar Beginning of the time window for the test in seconds (default is the beginning of the epoch). tstop : scalar End of the time window for the test in seconds (default is the end of the epoch). samples : int > 0 Number of samples used to determine cluster p values for spatio- temporal clusters (default 1000). baseline : bool | tuple Apply baseline correction using this period. True to use the epoch's baseline specification (default). include : 0 < scalar <= 1 Create plots for all clusters with p-values smaller or equal this value (the default is 1, i.e. to show all clusters). ... State parameters. """ data = TestDims("sensor") self._set_analysis_options(data, baseline, None, pmin, tstart, tstop) dst = self.get('report-file', mkdir=True, fmatch=False, test=test, folder="EEG Spatio-Temporal", modality='eeg', **state) if self._need_not_recompute_report(dst, samples, data, False): return # load data ds, res = self.load_test(test, tstart, tstop, pmin, None, None, samples, 'sensor', baseline, None, True, True) # start report title = self.format('{recording} {test_desc}') report = Report(title) # info info_section = report.add_section("Test Info") self._report_test_info(info_section, ds, test, res, data, include) # add connectivity image p = plot.SensorMap(ds['eeg'], connectivity=True, show=False) image_conn = p.image("connectivity.png") info_section.add_figure("Sensor map with connectivity", image_conn) p.close() colors = plot.colors_for_categorial(ds.eval(res._plot_model())) report.append(_report.sensor_time_results(res, ds, colors, include)) report.sign(('eelbrain', 'mne', 'scipy', 'numpy')) report.save_html(dst) def _make_report_eeg_sensors(self, test, sensors=('FZ', 'CZ', 'PZ', 'O1', 'O2'), pmin=None, tstart=None, tstop=None, samples=10000, baseline=True, redo=False, **state): # outdated (cache) """Create an HTML report on individual EEG sensors Parameters ---------- test : str Test for which to create a report (entry in MneExperiment.tests). sensors : sequence of str Names of the sensors which to include. pmin : None | scalar, 1 > pmin > 0 | 'tfce' Equivalent p-value for cluster threshold, or 'tfce' for threshold-free cluster enhancement. tstart : scalar Beginning of the time window for the test in seconds (default is the beginning of the epoch). tstop : scalar End of the time window for the test in seconds (default is the end of the epoch). samples : int > 0 Number of samples used to determine cluster p values for spatio- temporal clusters (default 1000). baseline : bool | tuple Apply baseline correction using this period. True to use the epoch's baseline specification (default). redo : bool If the target file already exists, delete and recreate it. This only applies to the HTML result file, not to the test. ... State parameters. """ data = TestDims('sensor.sub') self._set_analysis_options(data, baseline, None, pmin, tstart, tstop) dst = self.get('report-file', mkdir=True, fmatch=False, test=test, folder="EEG Sensors", modality='eeg', **state) if self._need_not_recompute_report(dst, samples, data, redo): return # load data test_obj = self._tests[test] ds = self.load_evoked(self.get('group'), baseline, True, vardef=test_obj.vars) # test that sensors are in the data eeg = ds['eeg'] missing = [s for s in sensors if s not in eeg.sensor.names] if missing: raise ValueError("The following sensors are not in the data: %s" % missing) # start report title = self.format('{recording} {test_desc}') report = Report(title) # info info_section = report.add_section("Test Info") # add sensor map p = plot.SensorMap(ds['eeg'], show=False) p.mark_sensors(sensors) info_section.add_figure("Sensor map", p) p.close() # main body caption = "Signal at %s." test_kwargs = self._test_kwargs(samples, pmin, tstart, tstop, ('time', 'sensor'), None) ress = [self._make_test(eeg.sub(sensor=sensor), ds, test_obj, test_kwargs) for sensor in sensors] colors = plot.colors_for_categorial(ds.eval(ress[0]._plot_model())) for sensor, res in zip(sensors, ress): report.append(_report.time_results(res, ds, colors, sensor, caption % sensor)) self._report_test_info(info_section, ds, test, res, data) report.sign(('eelbrain', 'mne', 'scipy', 'numpy')) report.save_html(dst) @staticmethod def _report_methods_brief(path): path = Path(path) items = [*path.parts[:-1], path.stem] return List('Methods brief', items[-3:]) def _report_subject_info(self, ds, model): """Table with subject information Parameters ---------- ds : Dataset Dataset with ``subject`` and ``n`` variables, and any factors in ``model``. model : str The model used for aggregating. """ s_ds = self.show_subjects(asds=True) if 'n' in ds: if model: n_ds = table.repmeas('n', model, 'subject', ds=ds) else: n_ds = ds n_ds_aligned = align1(n_ds, s_ds['subject'], 'subject') s_ds.update(n_ds_aligned) return s_ds.as_table( midrule=True, count=True, caption="All subjects included in the analysis with trials per " "condition") def _report_test_info(self, section, ds, test, res, data, include=None, model=True): """Top-level report info function Returns ------- info : Table Table with preprocessing and test info. """ test_obj = self._tests[test] if isinstance(test, str) else test # List of preprocessing parameters info = List("Analysis:") # epoch epoch = self.format('epoch = {epoch}') evoked_kind = self.get('evoked_kind') if evoked_kind: epoch += f' {evoked_kind}' if model is True: model = self.get('model') if model: epoch += f" ~ {model}" info.add_item(epoch) # inverse solution if data.source: info.add_item(self.format("cov = {cov}")) info.add_item(self.format("inv = {inv}")) # test info.add_item("test = %s (%s)" % (test_obj.kind, test_obj.desc)) if include is not None: info.add_item(f"Separate plots of all clusters with a p-value < {include}") section.append(info) # Statistical methods (for temporal tests, res is only representative) info = res.info_list() section.append(info) # subjects and state section.append(self._report_subject_info(ds, test_obj.model)) section.append(self.show_state(hide=('hemi', 'subject', 'mrisubject'))) return info def _report_parc_image(self, section, caption, subjects=None): "Add picture of the current parcellation" parc_name, parc = self._get_parc() with self._temporary_state: if isinstance(parc, IndividualSeededParc): if subjects is None: raise RuntimeError("subjects needs to be specified for " "plotting individual parcellations") legend = None for subject in self: # make sure there is at least one label if not any(not l.name.startswith('unknown-') for l in self.load_annot()): section.add_image_figure("No labels", subject) continue brain = self.plot_annot() if legend is None: p = brain.plot_legend(show=False) legend = p.image('parc-legend') p.close() section.add_image_figure(brain.image('parc'), subject) brain.close() return # one parc for all subjects self.set(mrisubject=self.get('common_brain')) brain = self.plot_annot(axw=500) legend = brain.plot_legend(show=False) content = [brain.image('parc'), legend.image('parc-legend')] section.add_image_figure(content, caption) brain.close() legend.close() def _make_report_lm(self, pmin=0.01, baseline=True, src_baseline=False, mask='lobes'): """Report for a first level (single subject) LM Parameters ---------- pmin : scalar Threshold p-value for uncorrected SPMs. """ if not isinstance(self._tests[self.get('test')], TwoStageTest): raise NotImplementedError("Only two-stage tests") with self._temporary_state: self._set_analysis_options('source', baseline, src_baseline, pmin, None, None, mask=mask) dst = self.get('subject-spm-report', mkdir=True) lm = self._load_spm(baseline, src_baseline) title = self.format('{recording} {test_desc}') surfer_kwargs = self._surfer_plot_kwargs() report = Report(title) report.append(_report.source_time_lm(lm, pmin, surfer_kwargs)) # report signature report.sign(('eelbrain', 'mne', 'surfer', 'scipy', 'numpy')) report.save_html(dst) def make_report_coreg(self, file_name=None, **state): """Create HTML report with plots of the MEG/MRI coregistration Parameters ---------- file_name : str Where to save the report (default is in the root/methods director). ... State parameters. """ from matplotlib import pyplot from mayavi import mlab mri = self.get('mri', **state) group = self.get('group') title = 'Coregistration' if group != 'all': title += ' ' + group if mri: title += ' ' + mri if file_name is None: file_name = join(self.get('methods-dir', mkdir=True), title + '.html') report = Report(title) for subject in self: mrisubject = self.get('mrisubject') fig = self.plot_coreg() fig.scene.camera.parallel_projection = True fig.scene.camera.parallel_scale = .175 mlab.draw(fig) # front mlab.view(90, 90, 1, figure=fig) im_front = Image.from_array(mlab.screenshot(figure=fig), 'front') # left mlab.view(0, 270, 1, roll=90, figure=fig) im_left = Image.from_array(mlab.screenshot(figure=fig), 'left') mlab.close(fig) # MRI/BEM figure if is_fake_mri(self.get('mri-dir')): bem_fig = None else: bem_fig = mne.viz.plot_bem(mrisubject, self.get('mri-sdir'), brain_surfaces='white', show=False) # add to report if subject == mrisubject: title = subject caption = "Coregistration for subject %s." % subject else: title = "%s (%s)" % (subject, mrisubject) caption = ("Coregistration for subject %s (MRI-subject %s)." % (subject, mrisubject)) section = report.add_section(title) if bem_fig is None: section.add_figure(caption, (im_front, im_left)) else: section.add_figure(caption, (im_front, im_left, bem_fig)) pyplot.close(bem_fig) report.sign() report.save_html(file_name) def make_src(self, **kwargs): """Make the source space Parameters ---------- ... State parameters. """ dst = self.get('src-file', **kwargs) subject = self.get('mrisubject') common_brain = self.get('common_brain') is_scaled = (subject != common_brain) and is_fake_mri(self.get('mri-dir')) if is_scaled: # make sure the source space exists for the original with self._temporary_state: self.make_src(mrisubject=common_brain) orig = self.get('src-file') if exists(dst): if getmtime(dst) >= getmtime(orig): return os.remove(dst) src = self.get('src') self._log.info(f"Scaling {src} source space for {subject}...") subjects_dir = self.get('mri-sdir') mne.scale_source_space(subject, f'{{subject}}-{src}-src.fif', subjects_dir=subjects_dir) elif exists(dst): return else: src = self.get('src') kind, param, special = SRC_RE.match(src).groups() self._log.info(f"Generating {src} source space for {subject}...") if kind == 'vol': if subject == 'fsaverage': bem = self.get('bem-file') else: raise NotImplementedError("Volume source space for subject other than fsaverage") if special == 'brainstem': name = 'brainstem' voi = ['Brain-Stem', '3rd-Ventricle'] voi_lat = ('Thalamus-Proper', 'VentralDC') remove_midline = False elif special == 'cortex': name = 'cortex' voi = [] voi_lat = ('Cerebral-Cortex',) remove_midline = True elif special == '': name = 'cortex' voi = [] voi_lat = ('Cerebral-Cortex', 'Cerebral-White-Matter') remove_midline = True else: raise RuntimeError(f'src={src!r}') voi.extend('%s-%s' % fmt for fmt in product(('Left', 'Right'), voi_lat)) sss = mne.setup_volume_source_space( subject, pos=float(param), bem=bem, mri=join(self.get('mri-dir'), 'mri', 'aseg.mgz'), volume_label=voi, subjects_dir=self.get('mri-sdir')) sss = merge_volume_source_space(sss, name) sss = prune_volume_source_space(sss, int(param), 2, remove_midline=remove_midline) else: assert not special spacing = kind + param sss = mne.setup_source_space(subject, spacing=spacing, add_dist=True, subjects_dir=self.get('mri-sdir')) mne.write_source_spaces(dst, sss) def _test_kwargs(self, samples, pmin, tstart, tstop, data, parc_dim): "Compile kwargs for testnd tests" kwargs = {'samples': samples, 'tstart': tstart, 'tstop': tstop, 'parc': parc_dim} if pmin == 'tfce': kwargs['tfce'] = True elif pmin is not None: kwargs['pmin'] = pmin kwargs.update(self._cluster_criteria_kwargs(data)) return kwargs def _make_test(self, y, ds, test, kwargs, force_permutation=False): """Compute test results Parameters ---------- y : NDVar Dependent variable. ds : Dataset Other variables. test : Test | str Test, or name of the test to perform. kwargs : dict Test parameters (from :meth:`._test_kwargs`). force_permutation : bool Conduct permutations regardless of whether there are any clusters. """ test_obj = test if isinstance(test, Test) else self._tests[test] if not isinstance(test_obj, EvokedTest): raise RuntimeError("Test kind=%s" % test_obj.kind) return test_obj.make(y, ds, force_permutation, kwargs) def merge_bad_channels(self): """Merge bad channel definitions for different sessions Load the bad channel definitions for all sessions of the current subject and save the union for all sessions. See Also -------- make_bad_channels : set bad channels for a single session """ n_chars = max(map(len, self._sessions)) # collect bad channels bads = set() sessions = [] with self._temporary_state: # ICARaw merges bad channels dynamically, so explicit merge needs to # be performed lower in the hierarchy self.set(raw='raw') for session in self.iter('session'): if exists(self.get('raw-file')): bads.update(self.load_bad_channels()) sessions.append(session) else: print("%%-%is: skipping, raw file missing" % n_chars % session) # update bad channel files for session in sessions: print(session.ljust(n_chars), end=': ') self.make_bad_channels(bads, session=session) def next(self, field='subject'): """Change field to the next value Parameters ---------- field : str | list of str The field for which the value should be changed (default 'subject'). Can also contain multiple fields, e.g. ``['subject', 'session']``. """ if isinstance(field, str): current = self.get(field) values = self.get_field_values(field) def fmt(x): return x else: current = tuple(self.get(f) for f in field) values = list(product(*(self.get_field_values(f) for f in field))) def fmt(x): return '/'.join(x) # find the index of the next value if current in values: idx = values.index(current) + 1 if idx == len(values): idx = -1 else: for idx in range(len(values)): if values[idx] > current: break else: idx = -1 # set the next value if idx == -1: next_ = values[0] print(f"The last {fmt(field)} was reached; rewinding to {fmt(next_)}") else: next_ = values[idx] print(f"{fmt(field)}: {fmt(current)} -> {fmt(next_)}") if isinstance(field, str): self.set(**{field: next_}) else: self.set(**dict(zip(field, next_))) def plot_annot(self, parc=None, surf=None, views=None, hemi=None, borders=False, alpha=0.7, w=None, h=None, axw=None, axh=None, foreground=None, background=None, seeds=False, **state): """Plot the annot file on which the current parcellation is based Parameters ---------- parc : None | str Parcellation to plot. If None (default), use parc from the current state. surf : 'inflated' | 'pial' | 'smoothwm' | 'sphere' | 'white' Freesurfer surface to use as brain geometry. views : str | iterator of str View or views to show in the figure. hemi : 'lh' | 'rh' | 'both' | 'split' Which hemispheres to plot (default includes hemisphere with more than one label in the annot file). borders : bool | int Show only label borders (PySurfer Brain.add_annotation() argument). alpha : scalar Alpha of the annotation (1=opaque, 0=transparent, default 0.7). axw : int Figure width per hemisphere. foreground : mayavi color Figure foreground color (i.e., the text color). background : mayavi color Figure background color. seeds : bool Plot seeds as points (only applies to seeded parcellations). ... State parameters. Returns ------- brain : Brain PySurfer Brain with the parcellation plot. legend : ColorList ColorList figure with the legend. """ if parc is not None: state['parc'] = parc self.set(**state) self.make_annot() parc_name, parc = self._get_parc() if seeds: if not isinstance(parc, SeededParc): raise ValueError( "seeds=True is only valid for seeded parcellation, " "not for parc=%r" % (parc_name,)) # if seeds are defined on a scaled common-brain, we need to plot the # scaled brain: plot_on_scaled_common_brain = isinstance(parc, IndividualSeededParc) else: plot_on_scaled_common_brain = False mri_sdir = self.get('mri-sdir') if (not plot_on_scaled_common_brain) and is_fake_mri(self.get('mri-dir')): subject = self.get('common_brain') else: subject = self.get('mrisubject') kwa = self._surfer_plot_kwargs(surf, views, foreground, background, None, hemi) brain = plot.brain.annot(parc_name, subject, borders=borders, alpha=alpha, w=w, h=h, axw=axw, axh=axh, subjects_dir=mri_sdir, **kwa) if seeds: from mayavi import mlab seeds = parc.seeds_for_subject(subject) seed_points = {hemi: [np.atleast_2d(coords) for name, coords in seeds.items() if name.endswith(hemi)] for hemi in ('lh', 'rh')} plot_points = {hemi: np.vstack(points).T if len(points) else None for hemi, points in seed_points.items()} for hemisphere in brain.brains: if plot_points[hemisphere.hemi] is None: continue x, y, z = plot_points[hemisphere.hemi] mlab.points3d(x, y, z, figure=hemisphere._f, color=(1, 0, 0), scale_factor=10) brain.set_parallel_view(scale=True) return brain def plot_brain(self, common_brain=True, **brain_kwargs): """Plot the brain model Parameters ---------- common_brain : bool If the current mrisubject is a scaled MRI, use the common_brain instead. ... : :class:`~plot._brain_object.Brain` options as keyword arguments. """ from ..plot._brain_object import Brain brain_args = self._surfer_plot_kwargs() brain_args.update(brain_kwargs) brain_args['subjects_dir'] = self.get('mri-sdir') # find subject if common_brain and is_fake_mri(self.get('mri-dir')): mrisubject = self.get('common_brain') self.set(mrisubject=mrisubject, match=False) else: mrisubject = self.get('mrisubject') return Brain(mrisubject, **brain_args) def plot_coreg(self, dig=True, parallel=True, **state): """Plot the coregistration (Head shape and MEG helmet) Parameters ---------- dig : bool Plot the digitization points (default True; 'fiducials' to plot fiducial points only). parallel : bool Set parallel view. ... State parameters. Notes ----- Uses :func:`mne.viz.plot_alignment` """ self.set(**state) with self._temporary_state: raw = self.load_raw(raw='raw') fig = mne.viz.plot_alignment( raw.info, self.get('trans-file'), self.get('mrisubject'), self.get('mri-sdir'), meg=('helmet', 'sensors'), dig=dig, interaction='terrain') if parallel: fig.scene.camera.parallel_projection = True fig.scene.camera.parallel_scale = .2 fig.scene.camera.position = [0, .5, .04] fig.scene.camera.focal_point = [0, 0, .04] fig.render() return fig def plot_whitened_gfp(self, s_start=None, s_stop=None, run=None): """Plot the GFP of the whitened evoked to evaluate the the covariance matrix Parameters ---------- s_start : str Subject at which to start (default is the first subject). s_stop: str Subject at which to stop (default is the last subject). run : bool Run the GUI after plotting (default depends on environment). """ gfps = [] subjects = [] with self._temporary_state: self.set(model='') for subject in self.iter_range(s_start, s_stop): cov = self.load_cov() picks = np.arange(len(cov.ch_names)) ds = self.load_evoked(baseline=True) whitened_evoked = mne.whiten_evoked(ds[0, 'evoked'], cov, picks) gfp = whitened_evoked.data.std(0) gfps.append(gfp) subjects.append(subject) colors = plot.colors_for_oneway(subjects) title = "Whitened Global Field Power (%s)" % self.get('cov') fig = plot._base.Figure(1, title, h=7, run=run) ax = fig._axes[0] for subject, gfp in zip(subjects, gfps): ax.plot(whitened_evoked.times, gfp, label=subject, color=colors[subject]) ax.legend(loc='right') fig.show() return fig def plot_evoked(self, subjects=None, separate=False, baseline=True, ylim='same', run=None, **kwargs): """Plot evoked sensor data Parameters ---------- subjects : str | 1 | -1 Subject(s) for which to load data. Can be a single subject name or a group name such as ``'all'``. ``1`` to use the current subject; ``-1`` for the current group. Default is current subject (or group if ``group`` is specified). separate : bool When plotting a group, plot all subjects separately instead or the group average (default False). baseline : bool | tuple Apply baseline correction using this period. True to use the epoch's baseline specification (default). ylim : 'same' | 'different' Use the same or different y-axis limits for different subjects (default 'same'). run : bool Run the GUI after plotting (default in accordance with plotting default). ... State parameters. """ subject, group = self._process_subject_arg(subjects, kwargs) model = self.get('model') or None epoch = self.get('epoch') if model: model_name = f"~{model}" elif subject or separate: model_name = "Average" else: model_name = "Grand Average" if subject: ds = self.load_evoked(baseline=baseline) y = guess_y(ds) title = f"{subject} {epoch} {model_name}" return plot.TopoButterfly(y, model, ds=ds, title=title, run=run) elif separate: plots = [] vlim = [] for subject in self.iter(group=group): ds = self.load_evoked(baseline=baseline) y = guess_y(ds) title = f"{subject} {epoch} {model_name}" p = plot.TopoButterfly(y, model, ds=ds, title=title, run=False) plots.append(p) vlim.append(p.get_vlim()) if ylim.startswith('s'): vlim = np.array(vlim) vmax = np.abs(vlim, out=vlim).max() for p in plots: p.set_vlim(vmax) elif not ylim.startswith('d'): raise ValueError("ylim=%s" % repr(ylim)) if run or plot._base.do_autorun(): gui.run() else: ds = self.load_evoked(group, baseline=baseline) y = guess_y(ds) title = f"{group} {epoch} {model_name}" return plot.TopoButterfly(y, model, ds=ds, title=title, run=run) def plot_label(self, label, surf=None, views=None, w=600): """Plot a label""" if isinstance(label, str): label = self.load_label(label) title = label.name hemi = 'split' if isinstance(label, mne.BiHemiLabel) else label.hemi kwargs = self._surfer_plot_kwargs(surf, views, hemi=hemi) brain = self.plot_brain(title=title, w=w, **kwargs) brain.add_label(label, alpha=0.75) return brain def plot_raw(self, decim=10, xlim=5, add_bads=True, subtract_mean=False, **state): """Plot raw sensor data Parameters ---------- decim : int Decimate data for faster plotting (default 10). xlim : scalar Number of seconds to display (default 5 s). add_bads : bool | list Add bad channel information to the bad channels text file (default True). subtract_mean : bool Subtract the mean from each channel (useful when plotting raw data recorded with DC offset). ... State parameters. """ raw = self.load_raw(add_bads, ndvar=True, decim=decim, **state) name = self.format("{subject} {recording} {raw}") if raw.info['meas'] == 'V': vmax = 1.5e-4 elif raw.info['meas'] == 'B': vmax = 2e-12 else: vmax = None if subtract_mean: raw -= raw.mean('time') return plot.TopoButterfly(raw, w=0, h=3, xlim=xlim, vmax=vmax, name=name) def run_mne_analyze(self, modal=False): """Run mne_analyze Parameters ---------- modal : bool Causes the shell to block until mne_analyze is closed. Notes ----- Sets the current directory to raw-dir, and sets the SUBJECT and SUBJECTS_DIR to current values """ subp.run_mne_analyze(self.get('raw-dir'), self.get('mrisubject'), self.get('mri-sdir'), modal) def run_mne_browse_raw(self, modal=False): """Run mne_analyze Parameters ---------- modal : bool Causes the shell to block until mne_browse_raw is closed. Notes ----- Sets the current directory to raw-dir, and sets the SUBJECT and SUBJECTS_DIR to current values """ subp.run_mne_browse_raw(self.get('raw-dir'), self.get('mrisubject'), self.get('mri-sdir'), modal) def set(self, subject=None, match=True, allow_asterisk=False, **state): """ Set variable values. Parameters ---------- subject : str Set the `subject` value. The corresponding `mrisubject` is automatically set to the corresponding mri subject. match : bool For fields with pre-defined values, only allow valid values (default ``True``). allow_asterisk : bool If a value contains ``'*'``, set the value without the normal value evaluation and checking mechanisms (default ``False``). ... State parameters. """ if subject is not None: if 'group' not in state: state['subject'] = subject subject = None FileTree.set(self, match, allow_asterisk, **state) if subject is not None: FileTree.set(self, match, allow_asterisk, subject=subject) def _post_set_group(self, _, group): if group == '*' or group not in self._groups: return group_members = self._groups[group] self._field_values['subject'] = group_members subject = self.get('subject') if subject != '*' and subject not in group_members and group_members: self.set(group_members[0]) def set_inv(self, ori='free', snr=3, method='dSPM', depth=None, pick_normal=False): """Set the type of inverse solution used for source estimation Parameters ---------- ori : 'free' | 'fixed' | 'vec' | float (0, 1) Orientation constraint (default ``'free'``; use a ``float`` to specify a loose orientation constraint). At each source point, ... - ``free``: ... estimate a current dipole with arbitrary direction. For further analysis, only the magnitude of the current is retained, while the direction is ignored. This is good for detecting changes in neural current strength when current direction is variable (for example, due to anatomical differences between subjects). - ``fixed``: ... estimate current flow orthogonal to the cortical surface. The sign of the estimates indicates current direction relative to the surface (positive for current out of the brain). - ``vec``: ... estimate a current vector with arbitrary direction, and return this current as 3 dimensional vector. - loose (``float``): ... estimate a current dipole with arbitrary direction. Then, multiple the two components parallel to the surface with this number, and retain the magnitude. snr : scalar SNR estimate used for regularization (default 3; the general recommendation is 3 for averaged responses, and 1 for raw or single trial data). method : 'MNE' | 'dSPM' | 'sLORETA' | 'eLORETA' Noise normalization method. ``MNE`` uses unnormalized current estimates. ``dSPM`` [1]_ (default) ``sLORETA`` [2]_ and eLORETA [3]_ normalize each the estimate at each source with an estimate of the noise at that source (default ``'dSPM'``). depth : None | float [0, 1] Depth weighting [4]_ (default ``None`` to use mne default 0.8; ``0`` to disable depth weighting). pick_normal : bool Estimate a free orientation current vector, then pick the component orthogonal to the cortical surface and discard the parallel components. References ---------- .. [1] Dale A, Liu A, Fischl B, Buckner R. (2000) Dynamic statistical parametric mapping: combining fMRI and MEG for high-resolution imaging of cortical activity. Neuron, 26:55-67. `10.1016/S0896-6273(00)81138-1 <https://doi.org/10.1016/S0896-6273(00)81138-1>`_ .. [2] Pascual-Marqui RD (2002), Standardized low resolution brain electromagnetic tomography (sLORETA): technical details. Methods Find. Exp. Clin. Pharmacology, 24(D):5-12. .. [3] Pascual-Marqui RD (2007). Discrete, 3D distributed, linear imaging methods of electric neuronal activity. Part 1: exact, zero error localization. `arXiv:0710.3341 <https://arxiv.org/abs/0710.3341>`_ .. [4] Lin F, Witzel T, Ahlfors S P, Stufflebeam S M, Belliveau J W, Hämäläinen M S. (2006) Assessing and improving the spatial accuracy in MEG source localization by depth-weighted minimum-norm estimates. NeuroImage, 31(1):160–171. `10.1016/j.neuroimage.2005.11.054 <https://doi.org/10.1016/j.neuroimage.2005.11.054>`_ """ self.set(inv=self._inv_str(ori, snr, method, depth, pick_normal)) @staticmethod def _inv_str(ori, snr, method, depth, pick_normal): "Construct inv str from settings" if isinstance(ori, str): if ori not in ('free', 'fixed', 'vec'): raise ValueError(f'ori={ori!r}') elif not 0 < ori < 1: raise ValueError(f"ori={ori!r}; must be in range (0, 1)") else: ori = f'loose{str(ori)[1:]}' if snr <= 0: raise ValueError(f"snr={snr!r}") if method not in INV_METHODS: raise ValueError(f"method={method!r}") items = [ori, f'{snr:g}', method] if depth is None: pass elif not 0 <= depth <= 1: raise ValueError(f"depth={depth!r}; must be in range [0, 1]") else: items.append(f'{depth:g}') if pick_normal: if ori in ('vec', 'fixed'): raise ValueError(f"ori={ori!r} and pick_normal=True are incompatible") items.append('pick_normal') return '-'.join(items) @staticmethod def _parse_inv(inv): "(ori, snr, method, depth, pick_normal)" m = inv_re.match(inv) if m is None: raise ValueError(f"inv={inv!r}: invalid inverse specification") ori, snr, method, depth, pick_normal = m.groups() if ori.startswith('loose'): ori = float(ori[5:]) if not 0 < ori < 1: raise ValueError(f"inv={inv!r}: loose parameter needs to be in range (0, 1)") elif pick_normal and ori in ('vec', 'fixed'): raise ValueError(f"inv={inv!r}: {ori} incompatible with pick_normal") snr = float(snr) if snr <= 0: raise ValueError(f"inv={inv!r}: snr={snr!r}") if method not in INV_METHODS: raise ValueError(f"inv={inv!r}: method={method!r}") if depth is not None: depth = float(depth) if not 0 <= depth <= 1: raise ValueError(f"inv={inv!r}: depth={depth!r}, needs to be in range [0, 1]") return ori, snr, method, depth, bool(pick_normal) @classmethod def _eval_inv(cls, inv): cls._parse_inv(inv) return inv def _update_inv_cache(self, fields): if fields['inv'] == '*': return '*' m = inv_re.match(fields['inv']) ori, snr, method, depth, pick_normal = m.groups() if depth: return f'{ori}-{depth}' else: return ori def _post_set_inv(self, _, inv): if '*' in inv: self._params['make_inv_kw'] = None self._params['apply_inv_kw'] = None return ori, snr, method, depth, pick_normal = self._parse_inv(inv) if ori == 'fixed': make_kw = {'fixed': True} elif ori == 'free' or ori == 'vec': make_kw = {'loose': 1} elif isinstance(ori, float): make_kw = {'loose': ori} else: raise RuntimeError("ori=%r (in inv=%r)" % (ori, inv)) if depth is None: make_kw['depth'] = 0.8 elif depth == 0: make_kw['depth'] = None else: make_kw['depth'] = depth apply_kw = {'method': method, 'lambda2': 1. / snr ** 2} if ori == 'vec': apply_kw['pick_ori'] = 'vector' elif pick_normal: apply_kw['pick_ori'] = 'normal' self._params['make_inv_kw'] = make_kw self._params['apply_inv_kw'] = apply_kw def _eval_model(self, model): if model == '': return model elif len(model) > 1 and '*' in model: raise ValueError("model=%r; To specify interactions, use '%' instead of '*'") factors = [v.strip() for v in model.split('%')] # find order value for each factor ordered_factors = {} unordered_factors = [] for factor in sorted(factors): assert_is_legal_dataset_key(factor) if factor in self._model_order: ordered_factors[self._model_order.index(factor)] = factor else: unordered_factors.append(factor) # recompose model = [ordered_factors[v] for v in sorted(ordered_factors)] if unordered_factors: model.extend(unordered_factors) return '%'.join(model) def _eval_src(self, src): m = SRC_RE.match(src) if not m: raise ValueError(f'src={src}') kind, param, special = m.groups() if special and kind != 'vol': raise ValueError(f'src={src}') return src def _update_mrisubject(self, fields): subject = fields['subject'] mri = fields['mri'] if subject == '*' or mri == '*': return '*' return self._mri_subjects[mri][subject] def _update_session(self, fields): epoch = fields['epoch'] if epoch in self._epochs: epoch = self._epochs[epoch] if isinstance(epoch, (PrimaryEpoch, SecondaryEpoch)): return epoch.session else: return # default for non-primary epoch elif not epoch or epoch == '*': return # don't force session return '*' # if a named epoch is not in _epochs it might be a removed epoch def _update_src_name(self, fields): "Because 'ico-4' is treated in filenames as ''" return '' if fields['src'] == 'ico-4' else fields['src'] def _eval_parc(self, parc): if parc in self._parcs: if isinstance(self._parcs[parc], SeededParc): raise ValueError("Seeded parc set without size, use e.g. " "parc='%s-25'" % parc) else: return parc m = SEEDED_PARC_RE.match(parc) if m: name = m.group(1) if isinstance(self._parcs.get(name), SeededParc): return parc else: raise ValueError("No seeded parc with name %r" % name) else: raise ValueError("parc=%r" % parc) def _get_parc(self): """Parc information Returns ------- parc : str The current parc setting. params : dict | None The parc definition (``None`` for ``parc=''``). """ parc = self.get('parc') if parc == '': return '', None elif parc in self._parcs: return parc, self._parcs[parc] else: return parc, self._parcs[SEEDED_PARC_RE.match(parc).group(1)] def _post_set_test(self, _, test): if test != '*' and test in self._tests: # with vmatch=False, test object might not be availale test_obj = self._tests[test] if test_obj.model is not None: self.set(model=test_obj._within_model) def _set_analysis_options(self, data, baseline, src_baseline, pmin, tstart, tstop, parc=None, mask=None, decim=None, test_options=(), folder_options=()): """Set templates for paths with test parameters analysis: preprocessing up to source estimate epochs (not parcellation) folder: parcellation (human readable) test_dims: parcellation (as used for spatio-temporal cluster test test_options: baseline, permutation test method etc. also sets `parc` Parameters ---------- data : TestDims Whether the analysis is in sensor or source space. ... src_baseline : Should be False if data=='sensor'. ... decim : int Decimation factor (default is None, i.e. based on epochs). test_options : sequence of str Additional, test-specific tags (for use by TRFExperiment only). """ data = TestDims.coerce(data) # data kind (sensor or source space) if data.sensor: analysis = '{sns_kind} {evoked_kind}' elif data.source: analysis = '{src_kind} {evoked_kind}' else: raise RuntimeError(f"data={data.string!r}") # determine report folder (reports) and test_dims (test-files) kwargs = {'test_dims': data.string} if data.source is True: if parc is None: if mask: folder = "%s masked" % mask kwargs['parc'] = mask if pmin is None: # When not doing clustering, parc does not affect # results, so we don't need to distinguish parc and mask kwargs['test_dims'] = mask else: # parc means disconnecting kwargs['test_dims'] = '%s-mask' % mask else: folder = "Whole Brain" # only compute unmasked test once (probably rare anyways) kwargs['parc'] = 'aparc' kwargs['test_dims'] = 'unmasked' elif mask: raise ValueError("Can't specify mask together with parc") elif pmin is None or pmin == 'tfce': raise NotImplementedError( "Threshold-free test (pmin=%r) is not implemented for " "parcellation (parc parameter). Use a mask instead, or do " "a cluster-based test." % pmin) else: folder = parc kwargs['parc'] = parc kwargs['test_dims'] = parc elif data.source: # source-space ROIs if not parc: raise ValueError("Need parc for ROI definition") kwargs['parc'] = parc kwargs['test_dims'] = '%s.%s' % (parc, data.source) if data.source == 'mean': folder = f'{parc} ROIs' else: folder = f'{parc} {data.source}' elif parc: raise ValueError(f"Sensor analysis (data={data.string!r}) can't have parc") elif data.sensor: folder = 'Sensor' if data.y_name == 'meg' else 'EEG' if data.sensor is not True: folder = f'{folder} {data.sensor}' else: raise RuntimeError(f"data={data.string!r}") if folder_options: folder += ' ' + ' '.join(folder_options) # test properties items = [] # baseline (default is baseline correcting in sensor space) epoch_baseline = self._epochs[self.get('epoch')].baseline if src_baseline: assert data.source if baseline is True or baseline == epoch_baseline: items.append('snsbl') elif baseline: items.append('snsbl=%s' % _time_window_str(baseline)) if src_baseline is True or src_baseline == epoch_baseline: items.append('srcbl') else: items.append('srcbl=%s' % _time_window_str(src_baseline)) else: if not baseline: items.append('nobl') elif baseline is True or baseline == epoch_baseline: pass else: items.append('bl=%s' % _time_window_str(baseline)) # pmin if pmin is not None: # source connectivity connectivity = self.get('connectivity') if connectivity and not data.source: raise NotImplementedError(f"connectivity={connectivity!r} is not implemented for data={data!r}") elif connectivity: items.append(connectivity) items.append(str(pmin)) # cluster criteria if pmin != 'tfce': select_clusters = self.get('select_clusters') if select_clusters: items.append(select_clusters) # time window if tstart is not None or tstop is not None: items.append(_time_window_str((tstart, tstop))) if decim is not None: assert isinstance(decim, int) items.append(str(decim)) items.extend(test_options) self.set(test_options=' '.join(items), analysis=analysis, folder=folder, **kwargs) @staticmethod def _parse_test_options(test_options: FieldCode): code = FieldCode.coerce(test_options) out = {} # baseline if 'bl' in code.lookahead_1: out['baseline'] = code.next() if 'srcbl' in code.lookahead_1: out['baseline'] = (out['baseline'], code.next()) # connectivity if code.lookahead_1 == 'link-midline': out['connectivity'] = code.next() # pmin if code.lookahead_1 == 'tfce' or code.lookahead_1.startswith('0.'): out['pmin'] = code.next() # time-window if '-' in code.lookahead_1: out['time_window'] = code.next() # decim if code.lookahead_1.isdigit(): out['decim'] = code.next() return out def show_bad_channels(self, sessions=None, **state): """List bad channels Parameters ---------- sessions : True | sequence of str By default, bad channels for the current session are shown. Set ``sessions`` to ``True`` to show bad channels for all sessions, or a list of session names to show bad channeles for these sessions. ... State parameters. Notes ----- ICA Raw pipes merge bad channels from different sessions (by combining the bad channels from all sessions). """ if state: self.set(**state) if sessions is True: use_sessions = self._sessions elif sessions: use_sessions = sessions else: use_sessions = None if use_sessions is None: bad_by_s = {k: self.load_bad_channels() for k in self} list_sessions = False else: bad_channels = {k: self.load_bad_channels() for k in self.iter(('subject', 'session'), values={'session': use_sessions})} # whether they are equal between sessions bad_by_s = {} for (subject, session), bads in bad_channels.items(): if subject in bad_by_s: if bad_by_s[subject] != bads: list_sessions = True break else: bad_by_s[subject] = bads else: list_sessions = False # table session_desc = ', '.join(use_sessions) if use_sessions else self.get('session') caption = f"Bad channels in {session_desc}" if list_sessions: t = fmtxt.Table('l' * (1 + len(use_sessions)), caption=caption) t.cells('Subject', *use_sessions) t.midrule() for subject in sorted(bad_by_s): t.cell(subject) for session in use_sessions: t.cell(', '.join(bad_channels[subject, session])) else: if use_sessions is not None: caption += " (all sessions equal)" t = fmtxt.Table('ll', caption=caption) t.cells('Subject', 'Bad channels') t.midrule() for subject in sorted(bad_by_s): t.cells(subject, ', '.join(bad_by_s[subject])) return t def show_file_status(self, temp, col=None, row='subject', *args, **kwargs): """Compile a table about the existence of files Parameters ---------- temp : str The name of the path template for the files to examine. col : None | str Field over which to alternate columns (default is a single column). row : str Field over which to alternate rows (default 'subject'). count : bool Add a column with a number for each line (default True). present : 'time' | 'date' | str String to display when a given file is present. 'time' to use last modification date and time (default); 'date' for date only. absent : str String to display when a given file is absent (default '-'). ... : :meth:`MneExperiment.iter` parameters. Examples -------- >>> e.show_file_status('rej-file') Subject Rej-file ------------------------------- 0 A0005 07/22/15 13:03:08 1 A0008 07/22/15 13:07:57 2 A0028 07/22/15 13:22:04 3 A0048 07/22/15 13:25:29 >>> e.show_file_status('rej-file', 'raw') Subject 0-40 0.1-40 1-40 Clm --------------------------------------------------- 0 A0005 - 07/22/15 13:03:08 - - 1 A0008 - 07/22/15 13:07:57 - - 2 A0028 - 07/22/15 13:22:04 - - 3 A0048 - 07/22/15 13:25:29 - - """ return FileTree.show_file_status(self, temp, row, col, *args, **kwargs) def show_raw_info(self, **state): "Display the selected pipeline for raw processing" raw = self.get('raw', **state) pipe = source_pipe = self._raw[raw] pipeline = [pipe] while source_pipe.name != 'raw': source_pipe = source_pipe.source pipeline.insert(0, source_pipe) print(f"Preprocessing pipeline: {' --> '.join(p.name for p in pipeline)}") # pipe-specific if isinstance(pipe, RawICA): table = fmtxt.Table('lrr') table.cells('Subject', 'n components', 'reject') table.midrule() for subject in self: table.cell(subject) filename = self.get('ica-file') if exists(filename): ica = self.load_ica() table.cells(ica.n_components_, len(ica.exclude)) else: table.cells("No ICA-file", '') print() print(table) def show_reg_params(self, asds=False, **kwargs): """Show the covariance matrix regularization parameters Parameters ---------- asds : bool Return a dataset with the parameters (default False). ... State parameters. """ if kwargs: self.set(**kwargs) subjects = [] reg = [] for subject in self: path = self.get('cov-info-file') if exists(path): with open(path, 'r') as fid: text = fid.read() reg.append(float(text.strip())) else: reg.append(float('nan')) subjects.append(subject) ds = Dataset() ds['subject'] = Factor(subjects) ds['reg'] = Var(reg) if asds: return ds else: print(ds) def show_rej_info(self, flagp=None, asds=False, bads=False, **state): """Information about artifact rejection Parameters ---------- flagp : scalar Flag entries whose percentage of good trials is lower than this number. asds : bool Return a Dataset with the information (default is to print it). bads : bool Display bad channel names (not just number of bad channels). Notes ----- To display the number of components rejected of an ICA raw pipe, use :meth:`~MneExperiment.show_raw_info`. """ # TODO: include ICA raw preprocessing pipes if state: self.set(**state) raw_name = self.get('raw') epoch_name = self.get('epoch') rej_name = self.get('rej') rej = self._artifact_rejection[rej_name] has_epoch_rejection = rej['kind'] is not None has_interp = rej.get('interpolation') subjects = [] n_events = [] n_good = [] bad_chs = [] n_interp = [] for subject in self: subjects.append(subject) bads_raw = self.load_bad_channels() try: ds = self.load_selected_events(reject='keep') except FileMissing: ds = self.load_selected_events(reject=False) bad_chs.append((bads_raw, ())) if has_epoch_rejection: n_good.append(float('nan')) if has_interp: n_interp.append(float('nan')) else: bads_rej = set(ds.info[BAD_CHANNELS]).difference(bads_raw) bad_chs.append((bads_raw, bads_rej)) if has_epoch_rejection: n_good.append(ds['accept'].sum()) if has_interp: n_interp.append(np.mean([len(chi) for chi in ds[INTERPOLATE_CHANNELS]])) n_events.append(ds.n_cases) has_interp = has_interp and any(n_interp) caption = f"Rejection info for raw={raw_name}, epoch={epoch_name}, rej={rej_name}. Percent is rounded to one decimal." # format bad channels if bads: func = ', '.join else: func = len bad_chs = [(func(bads_raw), func(bads_rej)) for bads_raw, bads_rej in bad_chs] if any(bads_rej for bads_raw, bads_rej in bad_chs): caption += " Bad channels: defined in bad_channels file and in rej-file." bad_chs = [f'{bads_raw} + {bads_rej}' for bads_raw, bads_rej in bad_chs] else: bad_chs = [f'{bads_raw}' for bads_raw, bads_rej in bad_chs] if bads: bad_chs = [s.replace('MEG ', '') for s in bad_chs] if has_interp: caption += " ch_interp: average number of channels interpolated per epoch, rounded to one decimal." out = Dataset(caption=caption) out['subject'] = Factor(subjects) out['n_events'] = Var(n_events) if has_epoch_rejection: out['n_good'] = Var(n_good) out['percent'] = Var(np.round(100 * out['n_good'] / out['n_events'], 1)) if flagp: out['flag'] = Factor(out['percent'] < flagp, labels={False: '', True: '*'}) out['bad_channels'] = Factor(bad_chs) if has_interp: out['ch_interp'] = Var(np.round(n_interp, 1)) if asds: return out else: print(out) def show_subjects(self, mri=True, mrisubject=False, caption=True, asds=False, **state): """Create a Dataset with subject information Parameters ---------- mri : bool Add a column specifying whether the subject is using a scaled MRI or whether it has its own MRI. mrisubject : bool Add a column showing the MRI subject corresponding to each subject. caption : bool | str Caption for the table (For True, use the default "Subject in group {group}". asds : bool Return the table as Dataset instead of an FMTxt Table. ... State parameters. """ if isinstance(mri, str): state['mri'] = mri mri = True if state: self.set(**state) # caption if caption is True: caption = self.format("Subjects in group {group}") subject_list = [] mri_list = [] mrisubject_list = [] for subject in self.iter(): subject_list.append(subject) mrisubject_ = self.get('mrisubject') mrisubject_list.append(mrisubject_) if mri: mri_dir = self.get('mri-dir') if not exists(mri_dir): mri_list.append('*missing') elif is_fake_mri(mri_dir): mri_sdir = self.get('mri-sdir') info = mne.coreg.read_mri_cfg(mrisubject_, mri_sdir) cell = "%s * %s" % (info['subject_from'], str(info['scale'])) mri_list.append(cell) else: mri_list.append(mrisubject_) ds = Dataset(caption=caption) ds['subject'] = Factor(subject_list) if mri: ds['mri'] = Factor(mri_list) if mrisubject: ds['mrisubject'] = Factor(mrisubject_list) if asds: return ds else: return ds.as_table(midrule=True, count=True) def show_input_tree(self): """Print a tree of the files needed as input See Also -------- show_tree: show complete tree (including secondary, optional and cache) """ return self.show_tree(fields=['raw-file', 'trans-file', 'mri-dir']) def _surfer_plot_kwargs(self, surf=None, views=None, foreground=None, background=None, smoothing_steps=None, hemi=None): out = self._brain_plot_defaults.copy() out.update(self.brain_plot_defaults) if views: out['views'] = views else: parc, p = self._get_parc() if p is not None and p.views: out['views'] = p.views if surf: out['surf'] = surf if foreground: out['foreground'] = foreground if background: out['background'] = background if smoothing_steps: out['smoothing_steps'] = smoothing_steps if hemi: out['hemi'] = hemi return out
import logging from datetime import date from dispatch.config import INCIDENT_RESOURCE_EXECUTIVE_REPORT_DOCUMENT from dispatch.conversation.messaging import send_feedack_to_user from dispatch.decorators import background_task from dispatch.document import service as document_service from dispatch.document.models import DocumentCreate from dispatch.event import service as event_service from dispatch.incident import service as incident_service from dispatch.participant import service as participant_service from dispatch.plugin import service as plugin_service from .enums import ReportTypes from .messaging import ( send_tactical_report_to_conversation, send_executive_report_to_notifications_group, ) from .models import ReportCreate from .service import create, get_all_by_incident_id_and_type log = logging.getLogger(__name__) @background_task def create_tactical_report( user_id: str, user_email: str, incident_id: int, action: dict, db_session=None ): """Creates and sends a new tactical report to a conversation.""" conditions = action["submission"]["conditions"] actions = action["submission"]["actions"] needs = action["submission"]["needs"] # we load the incident instance incident = incident_service.get(db_session=db_session, incident_id=incident_id) # we create a new tactical report details = {"conditions": conditions, "actions": actions, "needs": needs} tactical_report_in = ReportCreate(details=details, type=ReportTypes.tactical_report) tactical_report = create(db_session=db_session, report_in=tactical_report_in) # we load the participant participant = participant_service.get_by_incident_id_and_email( db_session=db_session, incident_id=incident_id, email=user_email ) # we save the tactical report participant.reports.append(tactical_report) incident.reports.append(tactical_report) db_session.add(participant) db_session.add(incident) db_session.commit() event_service.log( db_session=db_session, source="Incident Participant", description=f"{participant.individual.name} created a new tactical report", details={"conditions": conditions, "actions": actions, "needs": needs}, incident_id=incident_id, individual_id=participant.individual.id, ) # we send the tactical report to the conversation send_tactical_report_to_conversation(incident_id, conditions, actions, needs, db_session) return tactical_report @background_task def create_executive_report( user_id: str, user_email: str, incident_id: int, action: dict, db_session=None ): """Creates an executive report.""" report_template = document_service.get_executive_report_template(db_session=db_session) current_date = date.today().strftime("%B %d, %Y") current_status = action["submission"]["current_status"] overview = action["submission"]["overview"] next_steps = action["submission"]["next_steps"] # we load the incident instance incident = incident_service.get(db_session=db_session, incident_id=incident_id) if not report_template: send_feedack_to_user( incident.conversation.channel_id, user_id, "No executive report template defined.", db_session, ) return # we fetch all previous executive reports executive_reports = get_all_by_incident_id_and_type( db_session=db_session, incident_id=incident_id, report_type=ReportTypes.executive_report ) previous_executive_reports = [] for executive_report in executive_reports: previous_executive_reports.append( f"{executive_report.document.name} - {executive_report.document.weblink}\n" ) # we create a new executive report details = {"current_status": current_status, "overview": overview, "next_steps": next_steps} executive_report_in = ReportCreate( details=details, type=ReportTypes.executive_report, ) executive_report = create(db_session=db_session, report_in=executive_report_in) # we load the participant participant = participant_service.get_by_incident_id_and_email( db_session=db_session, incident_id=incident_id, email=user_email ) # we save the executive report participant.reports.append(executive_report) incident.reports.append(executive_report) db_session.add(participant) db_session.add(incident) db_session.commit() event_service.log( db_session=db_session, source="Incident Participant", description=f"{participant.individual.name} created a new executive report", details={"current_status": current_status, "overview": overview, "next_steps": next_steps}, incident_id=incident_id, individual_id=participant.individual.id, ) # we create a new document for the executive report storage_plugin = plugin_service.get_active(db_session=db_session, plugin_type="storage") executive_report_document_name = f"{incident.name} - Executive Report - {current_date}" executive_report_document = storage_plugin.instance.copy_file( folder_id=incident.storage.resource_id, file_id=report_template.resource_id, name=executive_report_document_name, ) executive_report_document.update( { "name": executive_report_document_name, "resource_type": INCIDENT_RESOURCE_EXECUTIVE_REPORT_DOCUMENT, } ) storage_plugin.instance.move_file( new_folder_id=incident.storage.resource_id, file_id=executive_report_document["id"] ) event_service.log( db_session=db_session, source=storage_plugin.title, description="Executive report document added to storage", incident_id=incident.id, ) document_in = DocumentCreate( name=executive_report_document["name"], resource_id=executive_report_document["id"], resource_type=executive_report_document["resource_type"], weblink=executive_report_document["weblink"], ) executive_report.document = document_service.create( db_session=db_session, document_in=document_in ) incident.documents.append(executive_report.document) db_session.add(executive_report) db_session.add(incident) db_session.commit() event_service.log( db_session=db_session, source="Dispatch Core App", description="Executive report document added to incident", incident_id=incident.id, ) # we update the incident update document document_plugin = plugin_service.get_active(db_session=db_session, plugin_type="document") document_plugin.instance.update( executive_report_document["id"], name=incident.name, title=incident.title, current_date=current_date, current_status=current_status, overview=overview, next_steps=next_steps, previous_reports="\n".join(previous_executive_reports), commander_fullname=incident.commander.name, commander_weblink=incident.commander.weblink, ) # we let the user know that the report has been created send_feedack_to_user( incident.conversation.channel_id, user_id, f"The executive report document has been created and can be found in the incident storage here: {executive_report_document["weblink"]}", db_session, ) # we send the executive report to the notifications group send_executive_report_to_notifications_group(incident_id, executive_report, db_session) # we let the user know that the report has been sent to the notifications group send_feedack_to_user( incident.conversation.channel_id, user_id, f"The executive report has been emailed to the notifications distribution list ({incident.notifications_group.email}).", db_session, ) return executive_report
import logging from datetime import date from dispatch.config import INCIDENT_RESOURCE_EXECUTIVE_REPORT_DOCUMENT from dispatch.conversation.messaging import send_feedack_to_user from dispatch.decorators import background_task from dispatch.document import service as document_service from dispatch.document.models import DocumentCreate from dispatch.event import service as event_service from dispatch.incident import service as incident_service from dispatch.participant import service as participant_service from dispatch.plugin import service as plugin_service from .enums import ReportTypes from .messaging import ( send_tactical_report_to_conversation, send_executive_report_to_notifications_group, ) from .models import ReportCreate from .service import create, get_all_by_incident_id_and_type log = logging.getLogger(__name__) @background_task def create_tactical_report( user_id: str, user_email: str, incident_id: int, action: dict, db_session=None ): """Creates and sends a new tactical report to a conversation.""" conditions = action["submission"]["conditions"] actions = action["submission"]["actions"] needs = action["submission"]["needs"] # we load the incident instance incident = incident_service.get(db_session=db_session, incident_id=incident_id) # we create a new tactical report details = {"conditions": conditions, "actions": actions, "needs": needs} tactical_report_in = ReportCreate(details=details, type=ReportTypes.tactical_report) tactical_report = create(db_session=db_session, report_in=tactical_report_in) # we load the participant participant = participant_service.get_by_incident_id_and_email( db_session=db_session, incident_id=incident_id, email=user_email ) # we save the tactical report participant.reports.append(tactical_report) incident.reports.append(tactical_report) db_session.add(participant) db_session.add(incident) db_session.commit() event_service.log( db_session=db_session, source="Incident Participant", description=f"{participant.individual.name} created a new tactical report", details={"conditions": conditions, "actions": actions, "needs": needs}, incident_id=incident_id, individual_id=participant.individual.id, ) # we send the tactical report to the conversation send_tactical_report_to_conversation(incident_id, conditions, actions, needs, db_session) return tactical_report @background_task def create_executive_report( user_id: str, user_email: str, incident_id: int, action: dict, db_session=None ): """Creates an executive report.""" report_template = document_service.get_executive_report_template(db_session=db_session) current_date = date.today().strftime("%B %d, %Y") current_status = action["submission"]["current_status"] overview = action["submission"]["overview"] next_steps = action["submission"]["next_steps"] # we load the incident instance incident = incident_service.get(db_session=db_session, incident_id=incident_id) if not report_template: send_feedack_to_user( incident.conversation.channel_id, user_id, "No executive report template defined.", db_session, ) return # we fetch all previous executive reports executive_reports = get_all_by_incident_id_and_type( db_session=db_session, incident_id=incident_id, report_type=ReportTypes.executive_report ) previous_executive_reports = [] for executive_report in executive_reports: previous_executive_reports.append( f"{executive_report.document.name} - {executive_report.document.weblink}\n" ) # we create a new executive report details = {"current_status": current_status, "overview": overview, "next_steps": next_steps} executive_report_in = ReportCreate( details=details, type=ReportTypes.executive_report, ) executive_report = create(db_session=db_session, report_in=executive_report_in) # we load the participant participant = participant_service.get_by_incident_id_and_email( db_session=db_session, incident_id=incident_id, email=user_email ) # we save the executive report participant.reports.append(executive_report) incident.reports.append(executive_report) db_session.add(participant) db_session.add(incident) db_session.commit() event_service.log( db_session=db_session, source="Incident Participant", description=f"{participant.individual.name} created a new executive report", details={"current_status": current_status, "overview": overview, "next_steps": next_steps}, incident_id=incident_id, individual_id=participant.individual.id, ) # we create a new document for the executive report storage_plugin = plugin_service.get_active(db_session=db_session, plugin_type="storage") executive_report_document_name = f"{incident.name} - Executive Report - {current_date}" executive_report_document = storage_plugin.instance.copy_file( folder_id=incident.storage.resource_id, file_id=report_template.resource_id, name=executive_report_document_name, ) executive_report_document.update( { "name": executive_report_document_name, "resource_type": INCIDENT_RESOURCE_EXECUTIVE_REPORT_DOCUMENT, } ) storage_plugin.instance.move_file( new_folder_id=incident.storage.resource_id, file_id=executive_report_document["id"] ) event_service.log( db_session=db_session, source=storage_plugin.title, description="Executive report document added to storage", incident_id=incident.id, ) document_in = DocumentCreate( name=executive_report_document["name"], resource_id=executive_report_document["id"], resource_type=executive_report_document["resource_type"], weblink=executive_report_document["weblink"], ) executive_report.document = document_service.create( db_session=db_session, document_in=document_in ) incident.documents.append(executive_report.document) db_session.add(executive_report) db_session.add(incident) db_session.commit() event_service.log( db_session=db_session, source="Dispatch Core App", description="Executive report document added to incident", incident_id=incident.id, ) # we update the incident update document document_plugin = plugin_service.get_active(db_session=db_session, plugin_type="document") document_plugin.instance.update( executive_report_document["id"], name=incident.name, title=incident.title, current_date=current_date, current_status=current_status, overview=overview, next_steps=next_steps, previous_reports="\n".join(previous_executive_reports), commander_fullname=incident.commander.name, commander_weblink=incident.commander.weblink, ) # we let the user know that the report has been created send_feedack_to_user( incident.conversation.channel_id, user_id, f"The executive report document has been created and can be found in the incident storage here: {executive_report_document['weblink']}", db_session, ) # we send the executive report to the notifications group send_executive_report_to_notifications_group(incident_id, executive_report, db_session) # we let the user know that the report has been sent to the notifications group send_feedack_to_user( incident.conversation.channel_id, user_id, f"The executive report has been emailed to the notifications distribution list ({incident.notifications_group.email}).", db_session, ) return executive_report
from collections import namedtuple import enum import os.path import re from c_common.clsutil import classonly import c_common.misc as _misc import c_common.strutil as _strutil import c_common.tables as _tables from .parser._regexes import SIMPLE_TYPE, _STORAGE FIXED_TYPE = _misc.Labeled('FIXED_TYPE') STORAGE = frozenset(_STORAGE) ############################# # kinds @enum.unique class KIND(enum.Enum): # XXX Use these in the raw parser code. TYPEDEF = 'typedef' STRUCT = 'struct' UNION = 'union' ENUM = 'enum' FUNCTION = 'function' VARIABLE = 'variable' STATEMENT = 'statement' @classonly def _from_raw(cls, raw): if raw is None: return None elif isinstance(raw, cls): return raw elif type(raw) is str: # We could use cls[raw] for the upper-case form, # but there's no need to go to the trouble. return cls(raw.lower()) else: raise NotImplementedError(raw) @classonly def by_priority(cls, group=None): if group is None: return cls._ALL_BY_PRIORITY.copy() elif group == 'type': return cls._TYPE_DECLS_BY_PRIORITY.copy() elif group == 'decl': return cls._ALL_DECLS_BY_PRIORITY.copy() elif isinstance(group, str): raise NotImplementedError(group) else: # XXX Treat group as a set of kinds & return in priority order? raise NotImplementedError(group) @classonly def is_type_decl(cls, kind): if kind in cls.TYPES: return True if not isinstance(kind, cls): raise TypeError(f'expected KIND, got {kind!r}') return False @classonly def is_decl(cls, kind): if kind in cls.DECLS: return True if not isinstance(kind, cls): raise TypeError(f'expected KIND, got {kind!r}') return False @classonly def get_group(cls, kind, *, groups=None): if not isinstance(kind, cls): raise TypeError(f'expected KIND, got {kind!r}') if groups is None: groups = ['type'] elif not groups: groups = () elif isinstance(groups, str): group = groups if group not in cls._GROUPS: raise ValueError(f'unsupported group {group!r}') groups = [group] else: unsupported = [g for g in groups if g not in cls._GROUPS] if unsupported: raise ValueError(f'unsupported groups {', '.join(repr(unsupported))}') for group in groups: if kind in cls._GROUPS[group]: return group else: return kind.value @classonly def resolve_group(cls, group): if isinstance(group, cls): return {group} elif isinstance(group, str): try: return cls._GROUPS[group].copy() except KeyError: raise ValueError(f'unsupported group {group!r}') else: resolved = set() for gr in group: resolve.update(cls.resolve_group(gr)) return resolved #return {*cls.resolve_group(g) for g in group} KIND._TYPE_DECLS_BY_PRIORITY = [ # These are in preferred order. KIND.TYPEDEF, KIND.STRUCT, KIND.UNION, KIND.ENUM, ] KIND._ALL_DECLS_BY_PRIORITY = [ # These are in preferred order. *KIND._TYPE_DECLS_BY_PRIORITY, KIND.FUNCTION, KIND.VARIABLE, ] KIND._ALL_BY_PRIORITY = [ # These are in preferred order. *KIND._ALL_DECLS_BY_PRIORITY, KIND.STATEMENT, ] KIND.TYPES = frozenset(KIND._TYPE_DECLS_BY_PRIORITY) KIND.DECLS = frozenset(KIND._ALL_DECLS_BY_PRIORITY) KIND._GROUPS = { 'type': KIND.TYPES, 'decl': KIND.DECLS, } KIND._GROUPS.update((k.value, {k}) for k in KIND) def get_kind_group(item): return KIND.get_group(item.kind) ############################# # low-level class FileInfo(namedtuple('FileInfo', 'filename lno')): @classmethod def from_raw(cls, raw): if isinstance(raw, cls): return raw elif isinstance(raw, tuple): return cls(*raw) elif not raw: return None elif isinstance(raw, str): return cls(raw, -1) else: raise TypeError(f'unsupported "raw": {raw:!r}') def __str__(self): return self.filename def fix_filename(self, relroot): filename = os.path.relpath(self.filename, relroot) return self._replace(filename=filename) class SourceLine(namedtuple('Line', 'file kind data conditions')): KINDS = ( #'directive', # data is ... 'source', # "data" is the line #'comment', # "data" is the text, including comment markers ) @property def filename(self): return self.file.filename @property def lno(self): return self.file.lno class DeclID(namedtuple('DeclID', 'filename funcname name')): """The globally-unique identifier for a declaration.""" @classmethod def from_row(cls, row, **markers): row = _tables.fix_row(row, **markers) return cls(*row) def __new__(cls, filename, funcname, name): self = super().__new__( cls, filename=str(filename) if filename else None, funcname=str(funcname) if funcname else None, name=str(name) if name else None, ) self._compare = tuple(v or '' for v in self) return self def __hash__(self): return super().__hash__() def __eq__(self, other): try: other = tuple(v or '' for v in other) except TypeError: return NotImplemented return self._compare == other def __gt__(self, other): try: other = tuple(v or '' for v in other) except TypeError: return NotImplemented return self._compare > other class ParsedItem(namedtuple('ParsedItem', 'file kind parent name data')): @classmethod def from_raw(cls, raw): if isinstance(raw, cls): return raw elif isinstance(raw, tuple): return cls(*raw) else: raise TypeError(f'unsupported "raw": {raw:!r}') @classmethod def from_row(cls, row, columns=None): if not columns: colnames = 'filename funcname name kind data'.split() else: colnames = list(columns) for i, column in enumerate(colnames): if column == 'file': colnames[i] = 'filename' elif column == 'funcname': colnames[i] = 'parent' if len(row) != len(set(colnames)): raise NotImplementedError(columns, row) kwargs = {} for column, value in zip(colnames, row): if column == 'filename': kwargs['file'] = FileInfo.from_raw(value) elif column == 'kind': kwargs['kind'] = KIND(value) elif column in cls._fields: kwargs[column] = value else: raise NotImplementedError(column) return cls(**kwargs) @property def id(self): try: return self._id except AttributeError: if self.kind is KIND.STATEMENT: self._id = None else: self._id = DeclID(str(self.file), self.funcname, self.name) return self._id @property def filename(self): if not self.file: return None return self.file.filename @property def lno(self): if not self.file: return -1 return self.file.lno @property def funcname(self): if not self.parent: return None if type(self.parent) is str: return self.parent else: return self.parent.name def as_row(self, columns=None): if not columns: columns = self._fields row = [] for column in columns: if column == 'file': value = self.filename elif column == 'kind': value = self.kind.value elif column == 'data': value = self._render_data() else: value = getattr(self, column) row.append(value) return row def _render_data(self): if not self.data: return None elif isinstance(self.data, str): return self.data else: # XXX raise NotImplementedError def _get_vartype(data): try: vartype = dict(data['vartype']) except KeyError: vartype = dict(data) storage = data.get('storage') else: storage = data.get('storage') or vartype.get('storage') del vartype['storage'] return storage, vartype def get_parsed_vartype(decl): kind = getattr(decl, 'kind', None) if isinstance(decl, ParsedItem): storage, vartype = _get_vartype(decl.data) typequal = vartype['typequal'] typespec = vartype['typespec'] abstract = vartype['abstract'] elif isinstance(decl, dict): kind = decl.get('kind') storage, vartype = _get_vartype(decl) typequal = vartype['typequal'] typespec = vartype['typespec'] abstract = vartype['abstract'] elif isinstance(decl, VarType): storage = None typequal, typespec, abstract = decl elif isinstance(decl, TypeDef): storage = None typequal, typespec, abstract = decl.vartype elif isinstance(decl, Variable): storage = decl.storage typequal, typespec, abstract = decl.vartype elif isinstance(decl, Function): storage = decl.storage typequal, typespec, abstract = decl.signature.returntype elif isinstance(decl, str): vartype, storage = VarType.from_str(decl) typequal, typespec, abstract = vartype else: raise NotImplementedError(decl) return kind, storage, typequal, typespec, abstract def get_default_storage(decl): if decl.kind not in (KIND.VARIABLE, KIND.FUNCTION): return None return 'extern' if decl.parent is None else 'auto' def get_effective_storage(decl, *, default=None): # Note that "static" limits access to just that C module # and "extern" (the default for module-level) allows access # outside the C module. if default is None: default = get_default_storage(decl) if default is None: return None try: storage = decl.storage except AttributeError: storage, _ = _get_vartype(decl.data) return storage or default ############################# # high-level class HighlevelParsedItem: kind = None FIELDS = ('file', 'parent', 'name', 'data') @classmethod def from_parsed(cls, parsed): if parsed.kind is not cls.kind: raise TypeError(f'kind mismatch ({parsed.kind.value} != {cls.kind.value})') data, extra = cls._resolve_data(parsed.data) self = cls( cls._resolve_file(parsed), parsed.name, data, cls._resolve_parent(parsed) if parsed.parent else None, **extra or {} ) self._parsed = parsed return self @classmethod def _resolve_file(cls, parsed): fileinfo = FileInfo.from_raw(parsed.file) if not fileinfo: raise NotImplementedError(parsed) return fileinfo @classmethod def _resolve_data(cls, data): return data, None @classmethod def _raw_data(cls, data, extra): if isinstance(data, str): return data else: raise NotImplementedError(data) @classmethod def _data_as_row(cls, data, extra, colnames): row = {} for colname in colnames: if colname in row: continue rendered = cls._render_data_row_item(colname, data, extra) if rendered is iter(rendered): rendered, = rendered row[colname] = rendered return row @classmethod def _render_data_row_item(cls, colname, data, extra): if colname == 'data': return str(data) else: return None @classmethod def _render_data_row(cls, fmt, data, extra, colnames): if fmt != 'row': raise NotImplementedError datarow = cls._data_as_row(data, extra, colnames) unresolved = [c for c, v in datarow.items() if v is None] if unresolved: raise NotImplementedError(unresolved) for colname, value in datarow.items(): if type(value) != str: if colname == 'kind': datarow[colname] = value.value else: datarow[colname] = str(value) return datarow @classmethod def _render_data(cls, fmt, data, extra): row = cls._render_data_row(fmt, data, extra, ['data']) yield ' '.join(row.values()) @classmethod def _resolve_parent(cls, parsed, *, _kind=None): fileinfo = FileInfo(parsed.file.filename, -1) if isinstance(parsed.parent, str): if parsed.parent.isidentifier(): name = parsed.parent else: # XXX It could be something like "<kind> <name>". raise NotImplementedError(repr(parsed.parent)) parent = ParsedItem(fileinfo, _kind, None, name, None) elif type(parsed.parent) is tuple: # XXX It could be something like (kind, name). raise NotImplementedError(repr(parsed.parent)) else: return parsed.parent Parent = KIND_CLASSES.get(_kind, Declaration) return Parent.from_parsed(parent) @classmethod def _parse_columns(cls, columns): colnames = {} # {requested -> actual} columns = list(columns or cls.FIELDS) datacolumns = [] for i, colname in enumerate(columns): if colname == 'file': columns[i] = 'filename' colnames['file'] = 'filename' elif colname == 'lno': columns[i] = 'line' colnames['lno'] = 'line' elif colname in ('filename', 'line'): colnames[colname] = colname elif colname == 'data': datacolumns.append(colname) colnames[colname] = None elif colname in cls.FIELDS or colname == 'kind': colnames[colname] = colname else: datacolumns.append(colname) colnames[colname] = None return columns, datacolumns, colnames def __init__(self, file, name, data, parent=None, *, _extra=None, _shortkey=None, _key=None, ): self.file = file self.parent = parent or None self.name = name self.data = data self._extra = _extra or {} self._shortkey = _shortkey self._key = _key def __repr__(self): args = [f'{n}={getattr(self, n)!r}' for n in ['file', 'name', 'data', 'parent', *(self._extra or ())]] return f'{type(self).__name__}({', '.join(args)})' def __str__(self): try: return self._str except AttributeError: self._str = next(self.render()) return self._str def __getattr__(self, name): try: return self._extra[name] except KeyError: raise AttributeError(name) def __hash__(self): return hash(self._key) def __eq__(self, other): if isinstance(other, HighlevelParsedItem): return self._key == other._key elif type(other) is tuple: return self._key == other else: return NotImplemented def __gt__(self, other): if isinstance(other, HighlevelParsedItem): return self._key > other._key elif type(other) is tuple: return self._key > other else: return NotImplemented @property def id(self): return self.parsed.id @property def shortkey(self): return self._shortkey @property def key(self): return self._key @property def filename(self): if not self.file: return None return self.file.filename @property def parsed(self): try: return self._parsed except AttributeError: parent = self.parent if parent is not None and not isinstance(parent, str): parent = parent.name self._parsed = ParsedItem( self.file, self.kind, parent, self.name, self._raw_data(), ) return self._parsed def fix_filename(self, relroot): if self.file: self.file = self.file.fix_filename(relroot) def as_rowdata(self, columns=None): columns, datacolumns, colnames = self._parse_columns(columns) return self._as_row(colnames, datacolumns, self._data_as_row) def render_rowdata(self, columns=None): columns, datacolumns, colnames = self._parse_columns(columns) def data_as_row(data, ext, cols): return self._render_data_row('row', data, ext, cols) rowdata = self._as_row(colnames, datacolumns, data_as_row) for column, value in rowdata.items(): colname = colnames.get(column) if not colname: continue if column == 'kind': value = value.value else: if column == 'parent': if self.parent: value = f'({self.parent.kind.value} {self.parent.name})' if not value: value = '-' elif type(value) is VarType: value = repr(str(value)) else: value = str(value) rowdata[column] = value return rowdata def _as_row(self, colnames, datacolumns, data_as_row): try: data = data_as_row(self.data, self._extra, datacolumns) except NotImplementedError: data = None row = data or {} for column, colname in colnames.items(): if colname == 'filename': value = self.file.filename if self.file else None elif colname == 'line': value = self.file.lno if self.file else None elif colname is None: value = getattr(self, column, None) else: value = getattr(self, colname, None) row.setdefault(column, value) return row def render(self, fmt='line'): fmt = fmt or 'line' try: render = _FORMATS[fmt] except KeyError: raise TypeError(f'unsupported fmt {fmt!r}') try: data = self._render_data(fmt, self.data, self._extra) except NotImplementedError: data = '-' yield from render(self, data) ### formats ### def _fmt_line(parsed, data=None): parts = [ f'<{parsed.kind.value}>', ] parent = '' if parsed.parent: parent = parsed.parent if not isinstance(parent, str): if parent.kind is KIND.FUNCTION: parent = f'{parent.name}()' else: parent = parent.name name = f'<{parent}>.{parsed.name}' else: name = parsed.name if data is None: data = parsed.data elif data is iter(data): data, = data parts.extend([ name, f'<{data}>' if data else '-', f'({str(parsed.file or '<unknown file>')})', ]) yield '\t'.join(parts) def _fmt_full(parsed, data=None): if parsed.kind is KIND.VARIABLE and parsed.parent: prefix = 'local ' suffix = f' ({parsed.parent.name})' else: # XXX Show other prefixes (e.g. global, public) prefix = suffix = '' yield f'{prefix}{parsed.kind.value} {parsed.name!r}{suffix}' for column, info in parsed.render_rowdata().items(): if column == 'kind': continue if column == 'name': continue if column == 'parent' and parsed.kind is not KIND.VARIABLE: continue if column == 'data': if parsed.kind in (KIND.STRUCT, KIND.UNION): column = 'members' elif parsed.kind is KIND.ENUM: column = 'enumerators' elif parsed.kind is KIND.STATEMENT: column = 'text' data, = data else: column = 'signature' data, = data if not data: # yield f'\t{column}:\t-' continue elif isinstance(data, str): yield f'\t{column}:\t{data!r}' else: yield f'\t{column}:' for line in data: yield f'\t\t- {line}' else: yield f'\t{column}:\t{info}' _FORMATS = { 'raw': (lambda v, _d: [repr(v)]), 'brief': _fmt_line, 'line': _fmt_line, 'full': _fmt_full, } ### declarations ## class Declaration(HighlevelParsedItem): @classmethod def from_row(cls, row, **markers): fixed = tuple(_tables.fix_row(row, **markers)) if cls is Declaration: _, _, _, kind, _ = fixed sub = KIND_CLASSES.get(KIND(kind)) if not sub or not issubclass(sub, Declaration): raise TypeError(f'unsupported kind, got {row!r}') else: sub = cls return sub._from_row(fixed) @classmethod def _from_row(cls, row): filename, funcname, name, kind, data = row kind = KIND._from_raw(kind) if kind is not cls.kind: raise TypeError(f'expected kind {cls.kind.value!r}, got {row!r}') fileinfo = FileInfo.from_raw(filename) if isinstance(data, str): data, extra = cls._parse_data(data, fmt='row') if extra: return cls(fileinfo, name, data, funcname, _extra=extra) else: return cls(fileinfo, name, data, funcname) @classmethod def _resolve_parent(cls, parsed, *, _kind=None): if _kind is None: raise TypeError(f'{cls.kind.value} declarations do not have parents ({parsed})') return super()._resolve_parent(parsed, _kind=_kind) @classmethod def _render_data(cls, fmt, data, extra): if not data: # XXX There should be some! Forward? yield '???' else: yield from cls._format_data(fmt, data, extra) @classmethod def _render_data_row_item(cls, colname, data, extra): if colname == 'data': return cls._format_data('row', data, extra) else: return None @classmethod def _format_data(cls, fmt, data, extra): raise NotImplementedError(fmt) @classmethod def _parse_data(cls, datastr, fmt=None): """This is the reverse of _render_data.""" if not datastr or datastr is _tables.UNKNOWN or datastr == '???': return None, None elif datastr is _tables.EMPTY or datastr == '-': # All the kinds have *something* even it is unknown. raise TypeError('all declarations have data of some sort, got none') else: return cls._unformat_data(datastr, fmt) @classmethod def _unformat_data(cls, datastr, fmt=None): raise NotImplementedError(fmt) class VarType(namedtuple('VarType', 'typequal typespec abstract')): @classmethod def from_str(cls, text): orig = text storage, sep, text = text.strip().partition(' ') if not sep: text = storage storage = None elif storage not in ('auto', 'register', 'static', 'extern'): text = orig storage = None return cls._from_str(text), storage @classmethod def _from_str(cls, text): orig = text if text.startswith(('const ', 'volatile ')): typequal, _, text = text.partition(' ') else: typequal = None # Extract a series of identifiers/keywords. m = re.match(r"^ *'?([a-zA-Z_]\w*(?:\s+[a-zA-Z_]\w*)*)\s*(.*?)'?\s*$", text) if not m: raise ValueError(f'invalid vartype text {orig!r}') typespec, abstract = m.groups() return cls(typequal, typespec, abstract or None) def __str__(self): parts = [] if self.qualifier: parts.append(self.qualifier) parts.append(self.spec + (self.abstract or '')) return ' '.join(parts) @property def qualifier(self): return self.typequal @property def spec(self): return self.typespec class Variable(Declaration): kind = KIND.VARIABLE @classmethod def _resolve_parent(cls, parsed): return super()._resolve_parent(parsed, _kind=KIND.FUNCTION) @classmethod def _resolve_data(cls, data): if not data: return None, None storage, vartype = _get_vartype(data) return VarType(**vartype), {'storage': storage} @classmethod def _raw_data(self, data, extra): vartype = data._asdict() return { 'storage': extra['storage'], 'vartype': vartype, } @classmethod def _format_data(cls, fmt, data, extra): storage = extra.get('storage') text = f'{storage} {data}' if storage else str(data) if fmt in ('line', 'brief'): yield text #elif fmt == 'full': elif fmt == 'row': yield text else: raise NotImplementedError(fmt) @classmethod def _unformat_data(cls, datastr, fmt=None): if fmt in ('line', 'brief'): vartype, storage = VarType.from_str(datastr) return vartype, {'storage': storage} #elif fmt == 'full': elif fmt == 'row': vartype, storage = VarType.from_str(datastr) return vartype, {'storage': storage} else: raise NotImplementedError(fmt) def __init__(self, file, name, data, parent=None, storage=None): super().__init__(file, name, data, parent, _extra={'storage': storage or None}, _shortkey=f'({parent.name}).{name}' if parent else name, _key=(str(file), # Tilde comes after all other ascii characters. f'~{parent or ''}~', name, ), ) if storage: if storage not in STORAGE: # The parser must need an update. raise NotImplementedError(storage) # Otherwise we trust the compiler to have validated it. @property def vartype(self): return self.data class Signature(namedtuple('Signature', 'params returntype inline isforward')): @classmethod def from_str(cls, text): orig = text storage, sep, text = text.strip().partition(' ') if not sep: text = storage storage = None elif storage not in ('auto', 'register', 'static', 'extern'): text = orig storage = None return cls._from_str(text), storage @classmethod def _from_str(cls, text): orig = text inline, sep, text = text.partition('|') if not sep: text = inline inline = None isforward = False if text.endswith(';'): text = text[:-1] isforward = True elif text.endswith('{}'): text = text[:-2] index = text.rindex('(') if index < 0: raise ValueError(f'bad signature text {orig!r}') params = text[index:] while params.count('(') <= params.count(')'): index = text.rindex('(', 0, index) if index < 0: raise ValueError(f'bad signature text {orig!r}') params = text[index:] text = text[:index] returntype = VarType._from_str(text.rstrip()) return cls(params, returntype, inline, isforward) def __str__(self): parts = [] if self.inline: parts.extend([ self.inline, '|', ]) parts.extend([ str(self.returntype), self.params, ';' if self.isforward else '{}', ]) return ' '.join(parts) @property def returns(self): return self.returntype class Function(Declaration): kind = KIND.FUNCTION @classmethod def _resolve_data(cls, data): if not data: return None, None kwargs = dict(data) returntype = dict(data['returntype']) del returntype['storage'] kwargs['returntype'] = VarType(**returntype) storage = kwargs.pop('storage') return Signature(**kwargs), {'storage': storage} @classmethod def _raw_data(self, data): # XXX finsh! return data @classmethod def _format_data(cls, fmt, data, extra): storage = extra.get('storage') text = f'{storage} {data}' if storage else str(data) if fmt in ('line', 'brief'): yield text #elif fmt == 'full': elif fmt == 'row': yield text else: raise NotImplementedError(fmt) @classmethod def _unformat_data(cls, datastr, fmt=None): if fmt in ('line', 'brief'): sig, storage = Signature.from_str(sig) return sig, {'storage': storage} #elif fmt == 'full': elif fmt == 'row': sig, storage = Signature.from_str(sig) return sig, {'storage': storage} else: raise NotImplementedError(fmt) def __init__(self, file, name, data, parent=None, storage=None): super().__init__(file, name, data, parent, _extra={'storage': storage}) self._shortkey = f'~{name}~ {self.data}' self._key = ( str(file), self._shortkey, ) @property def signature(self): return self.data class TypeDeclaration(Declaration): def __init__(self, file, name, data, parent=None, *, _shortkey=None): if not _shortkey: _shortkey = f'{self.kind.value} {name}' super().__init__(file, name, data, parent, _shortkey=_shortkey, _key=( str(file), _shortkey, ), ) class POTSType(TypeDeclaration): def __init__(self, name): _file = _data = _parent = None super().__init__(_file, name, _data, _parent, _shortkey=name) class FuncPtr(TypeDeclaration): def __init__(self, vartype): _file = _name = _parent = None data = vartype self.vartype = vartype super().__init__(_file, _name, data, _parent, _shortkey=f'<{vartype}>') class TypeDef(TypeDeclaration): kind = KIND.TYPEDEF @classmethod def _resolve_data(cls, data): if not data: raise NotImplementedError(data) vartype = dict(data) del vartype['storage'] return VarType(**vartype), None @classmethod def _raw_data(self, data): # XXX finish! return data @classmethod def _format_data(cls, fmt, data, extra): text = str(data) if fmt in ('line', 'brief'): yield text elif fmt == 'full': yield text elif fmt == 'row': yield text else: raise NotImplementedError(fmt) @classmethod def _unformat_data(cls, datastr, fmt=None): if fmt in ('line', 'brief'): vartype, _ = VarType.from_str(datastr) return vartype, None #elif fmt == 'full': elif fmt == 'row': vartype, _ = VarType.from_str(datastr) return vartype, None else: raise NotImplementedError(fmt) def __init__(self, file, name, data, parent=None): super().__init__(file, name, data, parent, _shortkey=name) @property def vartype(self): return self.data class Member(namedtuple('Member', 'name vartype size')): @classmethod def from_data(cls, raw, index): name = raw.name if raw.name else index vartype = size = None if type(raw.data) is int: size = raw.data elif isinstance(raw.data, str): size = int(raw.data) elif raw.data: vartype = dict(raw.data) del vartype['storage'] if 'size' in vartype: size = int(vartype.pop('size')) vartype = VarType(**vartype) return cls(name, vartype, size) @classmethod def from_str(cls, text): name, _, vartype = text.partition(': ') if name.startswith('#'): name = int(name[1:]) if vartype.isdigit(): size = int(vartype) vartype = None else: vartype, _ = VarType.from_str(vartype) size = None return cls(name, vartype, size) def __str__(self): name = self.name if isinstance(self.name, str) else f'#{self.name}' return f'{name}: {self.vartype or self.size}' class _StructUnion(TypeDeclaration): @classmethod def _resolve_data(cls, data): if not data: # XXX There should be some! Forward? return None, None return [Member.from_data(v, i) for i, v in enumerate(data)], None @classmethod def _raw_data(self, data): # XXX finish! return data @classmethod def _format_data(cls, fmt, data, extra): if fmt in ('line', 'brief'): members = ', '.join(f'<{m}>' for m in data) yield f'[{members}]' elif fmt == 'full': for member in data: yield f'{member}' elif fmt == 'row': members = ', '.join(f'<{m}>' for m in data) yield f'[{members}]' else: raise NotImplementedError(fmt) @classmethod def _unformat_data(cls, datastr, fmt=None): if fmt in ('line', 'brief'): members = [Member.from_str(m[1:-1]) for m in datastr[1:-1].split(', ')] return members, None #elif fmt == 'full': elif fmt == 'row': members = [Member.from_str(m.rstrip('>').lstrip('<')) for m in datastr[1:-1].split('>, <')] return members, None else: raise NotImplementedError(fmt) def __init__(self, file, name, data, parent=None): super().__init__(file, name, data, parent) @property def members(self): return self.data class Struct(_StructUnion): kind = KIND.STRUCT class Union(_StructUnion): kind = KIND.UNION class Enum(TypeDeclaration): kind = KIND.ENUM @classmethod def _resolve_data(cls, data): if not data: # XXX There should be some! Forward? return None, None enumerators = [e if isinstance(e, str) else e.name for e in data] return enumerators, None @classmethod def _raw_data(self, data): # XXX finsih! return data @classmethod def _format_data(cls, fmt, data, extra): if fmt in ('line', 'brief'): yield repr(data) elif fmt == 'full': for enumerator in data: yield f'{enumerator}' elif fmt == 'row': # XXX This won't work with CSV... yield ','.join(data) else: raise NotImplementedError(fmt) @classmethod def _unformat_data(cls, datastr, fmt=None): if fmt in ('line', 'brief'): return _strutil.unrepr(datastr), None #elif fmt == 'full': elif fmt == 'row': return datastr.split(','), None else: raise NotImplementedError(fmt) def __init__(self, file, name, data, parent=None): super().__init__(file, name, data, parent) @property def enumerators(self): return self.data ### statements ### class Statement(HighlevelParsedItem): kind = KIND.STATEMENT @classmethod def _resolve_data(cls, data): # XXX finsih! return data, None @classmethod def _raw_data(self, data): # XXX finsih! return data @classmethod def _render_data(cls, fmt, data, extra): # XXX Handle other formats? return repr(data) @classmethod def _parse_data(self, datastr, fmt=None): # XXX Handle other formats? return _strutil.unrepr(datastr), None def __init__(self, file, name, data, parent=None): super().__init__(file, name, data, parent, _shortkey=data or '', _key=( str(file), file.lno, # XXX Only one stmt per line? ), ) @property def text(self): return self.data ### KIND_CLASSES = {cls.kind: cls for cls in [ Variable, Function, TypeDef, Struct, Union, Enum, Statement, ]} def resolve_parsed(parsed): if isinstance(parsed, HighlevelParsedItem): return parsed try: cls = KIND_CLASSES[parsed.kind] except KeyError: raise ValueError(f'unsupported kind in {parsed!r}') return cls.from_parsed(parsed) def set_flag(item, name, value): try: setattr(item, name, value) except AttributeError: object.__setattr__(item, name, value) ############################# # composite class Declarations: @classmethod def from_decls(cls, decls): return cls(decls) @classmethod def from_parsed(cls, items): decls = (resolve_parsed(item) for item in items if item.kind is not KIND.STATEMENT) return cls.from_decls(decls) @classmethod def _resolve_key(cls, raw): if isinstance(raw, str): raw = [raw] elif isinstance(raw, Declaration): raw = ( raw.filename if cls._is_public(raw) else None, # `raw.parent` is always None for types and functions. raw.parent if raw.kind is KIND.VARIABLE else None, raw.name, ) extra = None if len(raw) == 1: name, = raw if name: name = str(name) if name.endswith(('.c', '.h')): # This is only legit as a query. key = (name, None, None) else: key = (None, None, name) else: key = (None, None, None) elif len(raw) == 2: parent, name = raw name = str(name) if isinstance(parent, Declaration): key = (None, parent.name, name) elif not parent: key = (None, None, name) else: parent = str(parent) if parent.endswith(('.c', '.h')): key = (parent, None, name) else: key = (None, parent, name) else: key, extra = raw[:3], raw[3:] filename, funcname, name = key filename = str(filename) if filename else None if isinstance(funcname, Declaration): funcname = funcname.name else: funcname = str(funcname) if funcname else None name = str(name) if name else None key = (filename, funcname, name) return key, extra @classmethod def _is_public(cls, decl): # For .c files don't we need info from .h files to make this decision? # XXX Check for "extern". # For now we treat all decls a "private" (have filename set). return False def __init__(self, decls): # (file, func, name) -> decl # "public": # * (None, None, name) # "private", "global": # * (file, None, name) # "private", "local": # * (file, func, name) if hasattr(decls, 'items'): self._decls = decls else: self._decls = {} self._extend(decls) # XXX always validate? def validate(self): for key, decl in self._decls.items(): if type(key) is not tuple or len(key) != 3: raise ValueError(f'expected 3-tuple key, got {key!r} (for decl {decl!r})') filename, funcname, name = key if not name: raise ValueError(f'expected name in key, got {key!r} (for decl {decl!r})') elif type(name) is not str: raise ValueError(f'expected name in key to be str, got {key!r} (for decl {decl!r})') # XXX Check filename type? # XXX Check funcname type? if decl.kind is KIND.STATEMENT: raise ValueError(f'expected a declaration, got {decl!r}') def __repr__(self): return f'{type(self).__name__}({list(self)})' def __len__(self): return len(self._decls) def __iter__(self): yield from self._decls def __getitem__(self, key): # XXX Be more exact for the 3-tuple case? if type(key) not in (str, tuple): raise KeyError(f'unsupported key {key!r}') resolved, extra = self._resolve_key(key) if extra: raise KeyError(f'key must have at most 3 parts, got {key!r}') if not resolved[2]: raise ValueError(f'expected name in key, got {key!r}') try: return self._decls[resolved] except KeyError: if type(key) is tuple and len(key) == 3: filename, funcname, name = key else: filename, funcname, name = resolved if filename and not filename.endswith(('.c', '.h')): raise KeyError(f'invalid filename in key {key!r}') elif funcname and funcname.endswith(('.c', '.h')): raise KeyError(f'invalid funcname in key {key!r}') elif name and name.endswith(('.c', '.h')): raise KeyError(f'invalid name in key {key!r}') else: raise # re-raise @property def types(self): return self._find(kind=KIND.TYPES) @property def functions(self): return self._find(None, None, None, KIND.FUNCTION) @property def variables(self): return self._find(None, None, None, KIND.VARIABLE) def iter_all(self): yield from self._decls.values() def get(self, key, default=None): try: return self[key] except KeyError: return default #def add_decl(self, decl, key=None): # decl = _resolve_parsed(decl) # self._add_decl(decl, key) def find(self, *key, **explicit): if not key: if not explicit: return iter(self) return self._find(**explicit) resolved, extra = self._resolve_key(key) filename, funcname, name = resolved if not extra: kind = None elif len(extra) == 1: kind, = extra else: raise KeyError(f'key must have at most 4 parts, got {key!r}') implicit= {} if filename: implicit['filename'] = filename if funcname: implicit['funcname'] = funcname if name: implicit['name'] = name if kind: implicit['kind'] = kind return self._find(**implicit, **explicit) def _find(self, filename=None, funcname=None, name=None, kind=None): for decl in self._decls.values(): if filename and decl.filename != filename: continue if funcname: if decl.kind is not KIND.VARIABLE: continue if decl.parent.name != funcname: continue if name and decl.name != name: continue if kind: kinds = KIND.resolve_group(kind) if decl.kind not in kinds: continue yield decl def _add_decl(self, decl, key=None): if key: if type(key) not in (str, tuple): raise NotImplementedError((key, decl)) # Any partial key will be turned into a full key, but that # same partial key will still match a key lookup. resolved, _ = self._resolve_key(key) if not resolved[2]: raise ValueError(f'expected name in key, got {key!r}') key = resolved # XXX Also add with the decl-derived key if not the same? else: key, _ = self._resolve_key(decl) self._decls[key] = decl def _extend(self, decls): decls = iter(decls) # Check only the first item. for decl in decls: if isinstance(decl, Declaration): self._add_decl(decl) # Add the rest without checking. for decl in decls: self._add_decl(decl) elif isinstance(decl, HighlevelParsedItem): raise NotImplementedError(decl) else: try: key, decl = decl except ValueError: raise NotImplementedError(decl) if not isinstance(decl, Declaration): raise NotImplementedError(decl) self._add_decl(decl, key) # Add the rest without checking. for key, decl in decls: self._add_decl(decl, key) # The iterator will be exhausted at this point.
from collections import namedtuple import enum import os.path import re from c_common.clsutil import classonly import c_common.misc as _misc import c_common.strutil as _strutil import c_common.tables as _tables from .parser._regexes import SIMPLE_TYPE, _STORAGE FIXED_TYPE = _misc.Labeled('FIXED_TYPE') STORAGE = frozenset(_STORAGE) ############################# # kinds @enum.unique class KIND(enum.Enum): # XXX Use these in the raw parser code. TYPEDEF = 'typedef' STRUCT = 'struct' UNION = 'union' ENUM = 'enum' FUNCTION = 'function' VARIABLE = 'variable' STATEMENT = 'statement' @classonly def _from_raw(cls, raw): if raw is None: return None elif isinstance(raw, cls): return raw elif type(raw) is str: # We could use cls[raw] for the upper-case form, # but there's no need to go to the trouble. return cls(raw.lower()) else: raise NotImplementedError(raw) @classonly def by_priority(cls, group=None): if group is None: return cls._ALL_BY_PRIORITY.copy() elif group == 'type': return cls._TYPE_DECLS_BY_PRIORITY.copy() elif group == 'decl': return cls._ALL_DECLS_BY_PRIORITY.copy() elif isinstance(group, str): raise NotImplementedError(group) else: # XXX Treat group as a set of kinds & return in priority order? raise NotImplementedError(group) @classonly def is_type_decl(cls, kind): if kind in cls.TYPES: return True if not isinstance(kind, cls): raise TypeError(f'expected KIND, got {kind!r}') return False @classonly def is_decl(cls, kind): if kind in cls.DECLS: return True if not isinstance(kind, cls): raise TypeError(f'expected KIND, got {kind!r}') return False @classonly def get_group(cls, kind, *, groups=None): if not isinstance(kind, cls): raise TypeError(f'expected KIND, got {kind!r}') if groups is None: groups = ['type'] elif not groups: groups = () elif isinstance(groups, str): group = groups if group not in cls._GROUPS: raise ValueError(f'unsupported group {group!r}') groups = [group] else: unsupported = [g for g in groups if g not in cls._GROUPS] if unsupported: raise ValueError(f'unsupported groups {", ".join(repr(unsupported))}') for group in groups: if kind in cls._GROUPS[group]: return group else: return kind.value @classonly def resolve_group(cls, group): if isinstance(group, cls): return {group} elif isinstance(group, str): try: return cls._GROUPS[group].copy() except KeyError: raise ValueError(f'unsupported group {group!r}') else: resolved = set() for gr in group: resolve.update(cls.resolve_group(gr)) return resolved #return {*cls.resolve_group(g) for g in group} KIND._TYPE_DECLS_BY_PRIORITY = [ # These are in preferred order. KIND.TYPEDEF, KIND.STRUCT, KIND.UNION, KIND.ENUM, ] KIND._ALL_DECLS_BY_PRIORITY = [ # These are in preferred order. *KIND._TYPE_DECLS_BY_PRIORITY, KIND.FUNCTION, KIND.VARIABLE, ] KIND._ALL_BY_PRIORITY = [ # These are in preferred order. *KIND._ALL_DECLS_BY_PRIORITY, KIND.STATEMENT, ] KIND.TYPES = frozenset(KIND._TYPE_DECLS_BY_PRIORITY) KIND.DECLS = frozenset(KIND._ALL_DECLS_BY_PRIORITY) KIND._GROUPS = { 'type': KIND.TYPES, 'decl': KIND.DECLS, } KIND._GROUPS.update((k.value, {k}) for k in KIND) def get_kind_group(item): return KIND.get_group(item.kind) ############################# # low-level class FileInfo(namedtuple('FileInfo', 'filename lno')): @classmethod def from_raw(cls, raw): if isinstance(raw, cls): return raw elif isinstance(raw, tuple): return cls(*raw) elif not raw: return None elif isinstance(raw, str): return cls(raw, -1) else: raise TypeError(f'unsupported "raw": {raw:!r}') def __str__(self): return self.filename def fix_filename(self, relroot): filename = os.path.relpath(self.filename, relroot) return self._replace(filename=filename) class SourceLine(namedtuple('Line', 'file kind data conditions')): KINDS = ( #'directive', # data is ... 'source', # "data" is the line #'comment', # "data" is the text, including comment markers ) @property def filename(self): return self.file.filename @property def lno(self): return self.file.lno class DeclID(namedtuple('DeclID', 'filename funcname name')): """The globally-unique identifier for a declaration.""" @classmethod def from_row(cls, row, **markers): row = _tables.fix_row(row, **markers) return cls(*row) def __new__(cls, filename, funcname, name): self = super().__new__( cls, filename=str(filename) if filename else None, funcname=str(funcname) if funcname else None, name=str(name) if name else None, ) self._compare = tuple(v or '' for v in self) return self def __hash__(self): return super().__hash__() def __eq__(self, other): try: other = tuple(v or '' for v in other) except TypeError: return NotImplemented return self._compare == other def __gt__(self, other): try: other = tuple(v or '' for v in other) except TypeError: return NotImplemented return self._compare > other class ParsedItem(namedtuple('ParsedItem', 'file kind parent name data')): @classmethod def from_raw(cls, raw): if isinstance(raw, cls): return raw elif isinstance(raw, tuple): return cls(*raw) else: raise TypeError(f'unsupported "raw": {raw:!r}') @classmethod def from_row(cls, row, columns=None): if not columns: colnames = 'filename funcname name kind data'.split() else: colnames = list(columns) for i, column in enumerate(colnames): if column == 'file': colnames[i] = 'filename' elif column == 'funcname': colnames[i] = 'parent' if len(row) != len(set(colnames)): raise NotImplementedError(columns, row) kwargs = {} for column, value in zip(colnames, row): if column == 'filename': kwargs['file'] = FileInfo.from_raw(value) elif column == 'kind': kwargs['kind'] = KIND(value) elif column in cls._fields: kwargs[column] = value else: raise NotImplementedError(column) return cls(**kwargs) @property def id(self): try: return self._id except AttributeError: if self.kind is KIND.STATEMENT: self._id = None else: self._id = DeclID(str(self.file), self.funcname, self.name) return self._id @property def filename(self): if not self.file: return None return self.file.filename @property def lno(self): if not self.file: return -1 return self.file.lno @property def funcname(self): if not self.parent: return None if type(self.parent) is str: return self.parent else: return self.parent.name def as_row(self, columns=None): if not columns: columns = self._fields row = [] for column in columns: if column == 'file': value = self.filename elif column == 'kind': value = self.kind.value elif column == 'data': value = self._render_data() else: value = getattr(self, column) row.append(value) return row def _render_data(self): if not self.data: return None elif isinstance(self.data, str): return self.data else: # XXX raise NotImplementedError def _get_vartype(data): try: vartype = dict(data['vartype']) except KeyError: vartype = dict(data) storage = data.get('storage') else: storage = data.get('storage') or vartype.get('storage') del vartype['storage'] return storage, vartype def get_parsed_vartype(decl): kind = getattr(decl, 'kind', None) if isinstance(decl, ParsedItem): storage, vartype = _get_vartype(decl.data) typequal = vartype['typequal'] typespec = vartype['typespec'] abstract = vartype['abstract'] elif isinstance(decl, dict): kind = decl.get('kind') storage, vartype = _get_vartype(decl) typequal = vartype['typequal'] typespec = vartype['typespec'] abstract = vartype['abstract'] elif isinstance(decl, VarType): storage = None typequal, typespec, abstract = decl elif isinstance(decl, TypeDef): storage = None typequal, typespec, abstract = decl.vartype elif isinstance(decl, Variable): storage = decl.storage typequal, typespec, abstract = decl.vartype elif isinstance(decl, Function): storage = decl.storage typequal, typespec, abstract = decl.signature.returntype elif isinstance(decl, str): vartype, storage = VarType.from_str(decl) typequal, typespec, abstract = vartype else: raise NotImplementedError(decl) return kind, storage, typequal, typespec, abstract def get_default_storage(decl): if decl.kind not in (KIND.VARIABLE, KIND.FUNCTION): return None return 'extern' if decl.parent is None else 'auto' def get_effective_storage(decl, *, default=None): # Note that "static" limits access to just that C module # and "extern" (the default for module-level) allows access # outside the C module. if default is None: default = get_default_storage(decl) if default is None: return None try: storage = decl.storage except AttributeError: storage, _ = _get_vartype(decl.data) return storage or default ############################# # high-level class HighlevelParsedItem: kind = None FIELDS = ('file', 'parent', 'name', 'data') @classmethod def from_parsed(cls, parsed): if parsed.kind is not cls.kind: raise TypeError(f'kind mismatch ({parsed.kind.value} != {cls.kind.value})') data, extra = cls._resolve_data(parsed.data) self = cls( cls._resolve_file(parsed), parsed.name, data, cls._resolve_parent(parsed) if parsed.parent else None, **extra or {} ) self._parsed = parsed return self @classmethod def _resolve_file(cls, parsed): fileinfo = FileInfo.from_raw(parsed.file) if not fileinfo: raise NotImplementedError(parsed) return fileinfo @classmethod def _resolve_data(cls, data): return data, None @classmethod def _raw_data(cls, data, extra): if isinstance(data, str): return data else: raise NotImplementedError(data) @classmethod def _data_as_row(cls, data, extra, colnames): row = {} for colname in colnames: if colname in row: continue rendered = cls._render_data_row_item(colname, data, extra) if rendered is iter(rendered): rendered, = rendered row[colname] = rendered return row @classmethod def _render_data_row_item(cls, colname, data, extra): if colname == 'data': return str(data) else: return None @classmethod def _render_data_row(cls, fmt, data, extra, colnames): if fmt != 'row': raise NotImplementedError datarow = cls._data_as_row(data, extra, colnames) unresolved = [c for c, v in datarow.items() if v is None] if unresolved: raise NotImplementedError(unresolved) for colname, value in datarow.items(): if type(value) != str: if colname == 'kind': datarow[colname] = value.value else: datarow[colname] = str(value) return datarow @classmethod def _render_data(cls, fmt, data, extra): row = cls._render_data_row(fmt, data, extra, ['data']) yield ' '.join(row.values()) @classmethod def _resolve_parent(cls, parsed, *, _kind=None): fileinfo = FileInfo(parsed.file.filename, -1) if isinstance(parsed.parent, str): if parsed.parent.isidentifier(): name = parsed.parent else: # XXX It could be something like "<kind> <name>". raise NotImplementedError(repr(parsed.parent)) parent = ParsedItem(fileinfo, _kind, None, name, None) elif type(parsed.parent) is tuple: # XXX It could be something like (kind, name). raise NotImplementedError(repr(parsed.parent)) else: return parsed.parent Parent = KIND_CLASSES.get(_kind, Declaration) return Parent.from_parsed(parent) @classmethod def _parse_columns(cls, columns): colnames = {} # {requested -> actual} columns = list(columns or cls.FIELDS) datacolumns = [] for i, colname in enumerate(columns): if colname == 'file': columns[i] = 'filename' colnames['file'] = 'filename' elif colname == 'lno': columns[i] = 'line' colnames['lno'] = 'line' elif colname in ('filename', 'line'): colnames[colname] = colname elif colname == 'data': datacolumns.append(colname) colnames[colname] = None elif colname in cls.FIELDS or colname == 'kind': colnames[colname] = colname else: datacolumns.append(colname) colnames[colname] = None return columns, datacolumns, colnames def __init__(self, file, name, data, parent=None, *, _extra=None, _shortkey=None, _key=None, ): self.file = file self.parent = parent or None self.name = name self.data = data self._extra = _extra or {} self._shortkey = _shortkey self._key = _key def __repr__(self): args = [f'{n}={getattr(self, n)!r}' for n in ['file', 'name', 'data', 'parent', *(self._extra or ())]] return f'{type(self).__name__}({", ".join(args)})' def __str__(self): try: return self._str except AttributeError: self._str = next(self.render()) return self._str def __getattr__(self, name): try: return self._extra[name] except KeyError: raise AttributeError(name) def __hash__(self): return hash(self._key) def __eq__(self, other): if isinstance(other, HighlevelParsedItem): return self._key == other._key elif type(other) is tuple: return self._key == other else: return NotImplemented def __gt__(self, other): if isinstance(other, HighlevelParsedItem): return self._key > other._key elif type(other) is tuple: return self._key > other else: return NotImplemented @property def id(self): return self.parsed.id @property def shortkey(self): return self._shortkey @property def key(self): return self._key @property def filename(self): if not self.file: return None return self.file.filename @property def parsed(self): try: return self._parsed except AttributeError: parent = self.parent if parent is not None and not isinstance(parent, str): parent = parent.name self._parsed = ParsedItem( self.file, self.kind, parent, self.name, self._raw_data(), ) return self._parsed def fix_filename(self, relroot): if self.file: self.file = self.file.fix_filename(relroot) def as_rowdata(self, columns=None): columns, datacolumns, colnames = self._parse_columns(columns) return self._as_row(colnames, datacolumns, self._data_as_row) def render_rowdata(self, columns=None): columns, datacolumns, colnames = self._parse_columns(columns) def data_as_row(data, ext, cols): return self._render_data_row('row', data, ext, cols) rowdata = self._as_row(colnames, datacolumns, data_as_row) for column, value in rowdata.items(): colname = colnames.get(column) if not colname: continue if column == 'kind': value = value.value else: if column == 'parent': if self.parent: value = f'({self.parent.kind.value} {self.parent.name})' if not value: value = '-' elif type(value) is VarType: value = repr(str(value)) else: value = str(value) rowdata[column] = value return rowdata def _as_row(self, colnames, datacolumns, data_as_row): try: data = data_as_row(self.data, self._extra, datacolumns) except NotImplementedError: data = None row = data or {} for column, colname in colnames.items(): if colname == 'filename': value = self.file.filename if self.file else None elif colname == 'line': value = self.file.lno if self.file else None elif colname is None: value = getattr(self, column, None) else: value = getattr(self, colname, None) row.setdefault(column, value) return row def render(self, fmt='line'): fmt = fmt or 'line' try: render = _FORMATS[fmt] except KeyError: raise TypeError(f'unsupported fmt {fmt!r}') try: data = self._render_data(fmt, self.data, self._extra) except NotImplementedError: data = '-' yield from render(self, data) ### formats ### def _fmt_line(parsed, data=None): parts = [ f'<{parsed.kind.value}>', ] parent = '' if parsed.parent: parent = parsed.parent if not isinstance(parent, str): if parent.kind is KIND.FUNCTION: parent = f'{parent.name}()' else: parent = parent.name name = f'<{parent}>.{parsed.name}' else: name = parsed.name if data is None: data = parsed.data elif data is iter(data): data, = data parts.extend([ name, f'<{data}>' if data else '-', f'({str(parsed.file or "<unknown file>")})', ]) yield '\t'.join(parts) def _fmt_full(parsed, data=None): if parsed.kind is KIND.VARIABLE and parsed.parent: prefix = 'local ' suffix = f' ({parsed.parent.name})' else: # XXX Show other prefixes (e.g. global, public) prefix = suffix = '' yield f'{prefix}{parsed.kind.value} {parsed.name!r}{suffix}' for column, info in parsed.render_rowdata().items(): if column == 'kind': continue if column == 'name': continue if column == 'parent' and parsed.kind is not KIND.VARIABLE: continue if column == 'data': if parsed.kind in (KIND.STRUCT, KIND.UNION): column = 'members' elif parsed.kind is KIND.ENUM: column = 'enumerators' elif parsed.kind is KIND.STATEMENT: column = 'text' data, = data else: column = 'signature' data, = data if not data: # yield f'\t{column}:\t-' continue elif isinstance(data, str): yield f'\t{column}:\t{data!r}' else: yield f'\t{column}:' for line in data: yield f'\t\t- {line}' else: yield f'\t{column}:\t{info}' _FORMATS = { 'raw': (lambda v, _d: [repr(v)]), 'brief': _fmt_line, 'line': _fmt_line, 'full': _fmt_full, } ### declarations ## class Declaration(HighlevelParsedItem): @classmethod def from_row(cls, row, **markers): fixed = tuple(_tables.fix_row(row, **markers)) if cls is Declaration: _, _, _, kind, _ = fixed sub = KIND_CLASSES.get(KIND(kind)) if not sub or not issubclass(sub, Declaration): raise TypeError(f'unsupported kind, got {row!r}') else: sub = cls return sub._from_row(fixed) @classmethod def _from_row(cls, row): filename, funcname, name, kind, data = row kind = KIND._from_raw(kind) if kind is not cls.kind: raise TypeError(f'expected kind {cls.kind.value!r}, got {row!r}') fileinfo = FileInfo.from_raw(filename) if isinstance(data, str): data, extra = cls._parse_data(data, fmt='row') if extra: return cls(fileinfo, name, data, funcname, _extra=extra) else: return cls(fileinfo, name, data, funcname) @classmethod def _resolve_parent(cls, parsed, *, _kind=None): if _kind is None: raise TypeError(f'{cls.kind.value} declarations do not have parents ({parsed})') return super()._resolve_parent(parsed, _kind=_kind) @classmethod def _render_data(cls, fmt, data, extra): if not data: # XXX There should be some! Forward? yield '???' else: yield from cls._format_data(fmt, data, extra) @classmethod def _render_data_row_item(cls, colname, data, extra): if colname == 'data': return cls._format_data('row', data, extra) else: return None @classmethod def _format_data(cls, fmt, data, extra): raise NotImplementedError(fmt) @classmethod def _parse_data(cls, datastr, fmt=None): """This is the reverse of _render_data.""" if not datastr or datastr is _tables.UNKNOWN or datastr == '???': return None, None elif datastr is _tables.EMPTY or datastr == '-': # All the kinds have *something* even it is unknown. raise TypeError('all declarations have data of some sort, got none') else: return cls._unformat_data(datastr, fmt) @classmethod def _unformat_data(cls, datastr, fmt=None): raise NotImplementedError(fmt) class VarType(namedtuple('VarType', 'typequal typespec abstract')): @classmethod def from_str(cls, text): orig = text storage, sep, text = text.strip().partition(' ') if not sep: text = storage storage = None elif storage not in ('auto', 'register', 'static', 'extern'): text = orig storage = None return cls._from_str(text), storage @classmethod def _from_str(cls, text): orig = text if text.startswith(('const ', 'volatile ')): typequal, _, text = text.partition(' ') else: typequal = None # Extract a series of identifiers/keywords. m = re.match(r"^ *'?([a-zA-Z_]\w*(?:\s+[a-zA-Z_]\w*)*)\s*(.*?)'?\s*$", text) if not m: raise ValueError(f'invalid vartype text {orig!r}') typespec, abstract = m.groups() return cls(typequal, typespec, abstract or None) def __str__(self): parts = [] if self.qualifier: parts.append(self.qualifier) parts.append(self.spec + (self.abstract or '')) return ' '.join(parts) @property def qualifier(self): return self.typequal @property def spec(self): return self.typespec class Variable(Declaration): kind = KIND.VARIABLE @classmethod def _resolve_parent(cls, parsed): return super()._resolve_parent(parsed, _kind=KIND.FUNCTION) @classmethod def _resolve_data(cls, data): if not data: return None, None storage, vartype = _get_vartype(data) return VarType(**vartype), {'storage': storage} @classmethod def _raw_data(self, data, extra): vartype = data._asdict() return { 'storage': extra['storage'], 'vartype': vartype, } @classmethod def _format_data(cls, fmt, data, extra): storage = extra.get('storage') text = f'{storage} {data}' if storage else str(data) if fmt in ('line', 'brief'): yield text #elif fmt == 'full': elif fmt == 'row': yield text else: raise NotImplementedError(fmt) @classmethod def _unformat_data(cls, datastr, fmt=None): if fmt in ('line', 'brief'): vartype, storage = VarType.from_str(datastr) return vartype, {'storage': storage} #elif fmt == 'full': elif fmt == 'row': vartype, storage = VarType.from_str(datastr) return vartype, {'storage': storage} else: raise NotImplementedError(fmt) def __init__(self, file, name, data, parent=None, storage=None): super().__init__(file, name, data, parent, _extra={'storage': storage or None}, _shortkey=f'({parent.name}).{name}' if parent else name, _key=(str(file), # Tilde comes after all other ascii characters. f'~{parent or ""}~', name, ), ) if storage: if storage not in STORAGE: # The parser must need an update. raise NotImplementedError(storage) # Otherwise we trust the compiler to have validated it. @property def vartype(self): return self.data class Signature(namedtuple('Signature', 'params returntype inline isforward')): @classmethod def from_str(cls, text): orig = text storage, sep, text = text.strip().partition(' ') if not sep: text = storage storage = None elif storage not in ('auto', 'register', 'static', 'extern'): text = orig storage = None return cls._from_str(text), storage @classmethod def _from_str(cls, text): orig = text inline, sep, text = text.partition('|') if not sep: text = inline inline = None isforward = False if text.endswith(';'): text = text[:-1] isforward = True elif text.endswith('{}'): text = text[:-2] index = text.rindex('(') if index < 0: raise ValueError(f'bad signature text {orig!r}') params = text[index:] while params.count('(') <= params.count(')'): index = text.rindex('(', 0, index) if index < 0: raise ValueError(f'bad signature text {orig!r}') params = text[index:] text = text[:index] returntype = VarType._from_str(text.rstrip()) return cls(params, returntype, inline, isforward) def __str__(self): parts = [] if self.inline: parts.extend([ self.inline, '|', ]) parts.extend([ str(self.returntype), self.params, ';' if self.isforward else '{}', ]) return ' '.join(parts) @property def returns(self): return self.returntype class Function(Declaration): kind = KIND.FUNCTION @classmethod def _resolve_data(cls, data): if not data: return None, None kwargs = dict(data) returntype = dict(data['returntype']) del returntype['storage'] kwargs['returntype'] = VarType(**returntype) storage = kwargs.pop('storage') return Signature(**kwargs), {'storage': storage} @classmethod def _raw_data(self, data): # XXX finsh! return data @classmethod def _format_data(cls, fmt, data, extra): storage = extra.get('storage') text = f'{storage} {data}' if storage else str(data) if fmt in ('line', 'brief'): yield text #elif fmt == 'full': elif fmt == 'row': yield text else: raise NotImplementedError(fmt) @classmethod def _unformat_data(cls, datastr, fmt=None): if fmt in ('line', 'brief'): sig, storage = Signature.from_str(sig) return sig, {'storage': storage} #elif fmt == 'full': elif fmt == 'row': sig, storage = Signature.from_str(sig) return sig, {'storage': storage} else: raise NotImplementedError(fmt) def __init__(self, file, name, data, parent=None, storage=None): super().__init__(file, name, data, parent, _extra={'storage': storage}) self._shortkey = f'~{name}~ {self.data}' self._key = ( str(file), self._shortkey, ) @property def signature(self): return self.data class TypeDeclaration(Declaration): def __init__(self, file, name, data, parent=None, *, _shortkey=None): if not _shortkey: _shortkey = f'{self.kind.value} {name}' super().__init__(file, name, data, parent, _shortkey=_shortkey, _key=( str(file), _shortkey, ), ) class POTSType(TypeDeclaration): def __init__(self, name): _file = _data = _parent = None super().__init__(_file, name, _data, _parent, _shortkey=name) class FuncPtr(TypeDeclaration): def __init__(self, vartype): _file = _name = _parent = None data = vartype self.vartype = vartype super().__init__(_file, _name, data, _parent, _shortkey=f'<{vartype}>') class TypeDef(TypeDeclaration): kind = KIND.TYPEDEF @classmethod def _resolve_data(cls, data): if not data: raise NotImplementedError(data) vartype = dict(data) del vartype['storage'] return VarType(**vartype), None @classmethod def _raw_data(self, data): # XXX finish! return data @classmethod def _format_data(cls, fmt, data, extra): text = str(data) if fmt in ('line', 'brief'): yield text elif fmt == 'full': yield text elif fmt == 'row': yield text else: raise NotImplementedError(fmt) @classmethod def _unformat_data(cls, datastr, fmt=None): if fmt in ('line', 'brief'): vartype, _ = VarType.from_str(datastr) return vartype, None #elif fmt == 'full': elif fmt == 'row': vartype, _ = VarType.from_str(datastr) return vartype, None else: raise NotImplementedError(fmt) def __init__(self, file, name, data, parent=None): super().__init__(file, name, data, parent, _shortkey=name) @property def vartype(self): return self.data class Member(namedtuple('Member', 'name vartype size')): @classmethod def from_data(cls, raw, index): name = raw.name if raw.name else index vartype = size = None if type(raw.data) is int: size = raw.data elif isinstance(raw.data, str): size = int(raw.data) elif raw.data: vartype = dict(raw.data) del vartype['storage'] if 'size' in vartype: size = int(vartype.pop('size')) vartype = VarType(**vartype) return cls(name, vartype, size) @classmethod def from_str(cls, text): name, _, vartype = text.partition(': ') if name.startswith('#'): name = int(name[1:]) if vartype.isdigit(): size = int(vartype) vartype = None else: vartype, _ = VarType.from_str(vartype) size = None return cls(name, vartype, size) def __str__(self): name = self.name if isinstance(self.name, str) else f'#{self.name}' return f'{name}: {self.vartype or self.size}' class _StructUnion(TypeDeclaration): @classmethod def _resolve_data(cls, data): if not data: # XXX There should be some! Forward? return None, None return [Member.from_data(v, i) for i, v in enumerate(data)], None @classmethod def _raw_data(self, data): # XXX finish! return data @classmethod def _format_data(cls, fmt, data, extra): if fmt in ('line', 'brief'): members = ', '.join(f'<{m}>' for m in data) yield f'[{members}]' elif fmt == 'full': for member in data: yield f'{member}' elif fmt == 'row': members = ', '.join(f'<{m}>' for m in data) yield f'[{members}]' else: raise NotImplementedError(fmt) @classmethod def _unformat_data(cls, datastr, fmt=None): if fmt in ('line', 'brief'): members = [Member.from_str(m[1:-1]) for m in datastr[1:-1].split(', ')] return members, None #elif fmt == 'full': elif fmt == 'row': members = [Member.from_str(m.rstrip('>').lstrip('<')) for m in datastr[1:-1].split('>, <')] return members, None else: raise NotImplementedError(fmt) def __init__(self, file, name, data, parent=None): super().__init__(file, name, data, parent) @property def members(self): return self.data class Struct(_StructUnion): kind = KIND.STRUCT class Union(_StructUnion): kind = KIND.UNION class Enum(TypeDeclaration): kind = KIND.ENUM @classmethod def _resolve_data(cls, data): if not data: # XXX There should be some! Forward? return None, None enumerators = [e if isinstance(e, str) else e.name for e in data] return enumerators, None @classmethod def _raw_data(self, data): # XXX finsih! return data @classmethod def _format_data(cls, fmt, data, extra): if fmt in ('line', 'brief'): yield repr(data) elif fmt == 'full': for enumerator in data: yield f'{enumerator}' elif fmt == 'row': # XXX This won't work with CSV... yield ','.join(data) else: raise NotImplementedError(fmt) @classmethod def _unformat_data(cls, datastr, fmt=None): if fmt in ('line', 'brief'): return _strutil.unrepr(datastr), None #elif fmt == 'full': elif fmt == 'row': return datastr.split(','), None else: raise NotImplementedError(fmt) def __init__(self, file, name, data, parent=None): super().__init__(file, name, data, parent) @property def enumerators(self): return self.data ### statements ### class Statement(HighlevelParsedItem): kind = KIND.STATEMENT @classmethod def _resolve_data(cls, data): # XXX finsih! return data, None @classmethod def _raw_data(self, data): # XXX finsih! return data @classmethod def _render_data(cls, fmt, data, extra): # XXX Handle other formats? return repr(data) @classmethod def _parse_data(self, datastr, fmt=None): # XXX Handle other formats? return _strutil.unrepr(datastr), None def __init__(self, file, name, data, parent=None): super().__init__(file, name, data, parent, _shortkey=data or '', _key=( str(file), file.lno, # XXX Only one stmt per line? ), ) @property def text(self): return self.data ### KIND_CLASSES = {cls.kind: cls for cls in [ Variable, Function, TypeDef, Struct, Union, Enum, Statement, ]} def resolve_parsed(parsed): if isinstance(parsed, HighlevelParsedItem): return parsed try: cls = KIND_CLASSES[parsed.kind] except KeyError: raise ValueError(f'unsupported kind in {parsed!r}') return cls.from_parsed(parsed) def set_flag(item, name, value): try: setattr(item, name, value) except AttributeError: object.__setattr__(item, name, value) ############################# # composite class Declarations: @classmethod def from_decls(cls, decls): return cls(decls) @classmethod def from_parsed(cls, items): decls = (resolve_parsed(item) for item in items if item.kind is not KIND.STATEMENT) return cls.from_decls(decls) @classmethod def _resolve_key(cls, raw): if isinstance(raw, str): raw = [raw] elif isinstance(raw, Declaration): raw = ( raw.filename if cls._is_public(raw) else None, # `raw.parent` is always None for types and functions. raw.parent if raw.kind is KIND.VARIABLE else None, raw.name, ) extra = None if len(raw) == 1: name, = raw if name: name = str(name) if name.endswith(('.c', '.h')): # This is only legit as a query. key = (name, None, None) else: key = (None, None, name) else: key = (None, None, None) elif len(raw) == 2: parent, name = raw name = str(name) if isinstance(parent, Declaration): key = (None, parent.name, name) elif not parent: key = (None, None, name) else: parent = str(parent) if parent.endswith(('.c', '.h')): key = (parent, None, name) else: key = (None, parent, name) else: key, extra = raw[:3], raw[3:] filename, funcname, name = key filename = str(filename) if filename else None if isinstance(funcname, Declaration): funcname = funcname.name else: funcname = str(funcname) if funcname else None name = str(name) if name else None key = (filename, funcname, name) return key, extra @classmethod def _is_public(cls, decl): # For .c files don't we need info from .h files to make this decision? # XXX Check for "extern". # For now we treat all decls a "private" (have filename set). return False def __init__(self, decls): # (file, func, name) -> decl # "public": # * (None, None, name) # "private", "global": # * (file, None, name) # "private", "local": # * (file, func, name) if hasattr(decls, 'items'): self._decls = decls else: self._decls = {} self._extend(decls) # XXX always validate? def validate(self): for key, decl in self._decls.items(): if type(key) is not tuple or len(key) != 3: raise ValueError(f'expected 3-tuple key, got {key!r} (for decl {decl!r})') filename, funcname, name = key if not name: raise ValueError(f'expected name in key, got {key!r} (for decl {decl!r})') elif type(name) is not str: raise ValueError(f'expected name in key to be str, got {key!r} (for decl {decl!r})') # XXX Check filename type? # XXX Check funcname type? if decl.kind is KIND.STATEMENT: raise ValueError(f'expected a declaration, got {decl!r}') def __repr__(self): return f'{type(self).__name__}({list(self)})' def __len__(self): return len(self._decls) def __iter__(self): yield from self._decls def __getitem__(self, key): # XXX Be more exact for the 3-tuple case? if type(key) not in (str, tuple): raise KeyError(f'unsupported key {key!r}') resolved, extra = self._resolve_key(key) if extra: raise KeyError(f'key must have at most 3 parts, got {key!r}') if not resolved[2]: raise ValueError(f'expected name in key, got {key!r}') try: return self._decls[resolved] except KeyError: if type(key) is tuple and len(key) == 3: filename, funcname, name = key else: filename, funcname, name = resolved if filename and not filename.endswith(('.c', '.h')): raise KeyError(f'invalid filename in key {key!r}') elif funcname and funcname.endswith(('.c', '.h')): raise KeyError(f'invalid funcname in key {key!r}') elif name and name.endswith(('.c', '.h')): raise KeyError(f'invalid name in key {key!r}') else: raise # re-raise @property def types(self): return self._find(kind=KIND.TYPES) @property def functions(self): return self._find(None, None, None, KIND.FUNCTION) @property def variables(self): return self._find(None, None, None, KIND.VARIABLE) def iter_all(self): yield from self._decls.values() def get(self, key, default=None): try: return self[key] except KeyError: return default #def add_decl(self, decl, key=None): # decl = _resolve_parsed(decl) # self._add_decl(decl, key) def find(self, *key, **explicit): if not key: if not explicit: return iter(self) return self._find(**explicit) resolved, extra = self._resolve_key(key) filename, funcname, name = resolved if not extra: kind = None elif len(extra) == 1: kind, = extra else: raise KeyError(f'key must have at most 4 parts, got {key!r}') implicit= {} if filename: implicit['filename'] = filename if funcname: implicit['funcname'] = funcname if name: implicit['name'] = name if kind: implicit['kind'] = kind return self._find(**implicit, **explicit) def _find(self, filename=None, funcname=None, name=None, kind=None): for decl in self._decls.values(): if filename and decl.filename != filename: continue if funcname: if decl.kind is not KIND.VARIABLE: continue if decl.parent.name != funcname: continue if name and decl.name != name: continue if kind: kinds = KIND.resolve_group(kind) if decl.kind not in kinds: continue yield decl def _add_decl(self, decl, key=None): if key: if type(key) not in (str, tuple): raise NotImplementedError((key, decl)) # Any partial key will be turned into a full key, but that # same partial key will still match a key lookup. resolved, _ = self._resolve_key(key) if not resolved[2]: raise ValueError(f'expected name in key, got {key!r}') key = resolved # XXX Also add with the decl-derived key if not the same? else: key, _ = self._resolve_key(decl) self._decls[key] = decl def _extend(self, decls): decls = iter(decls) # Check only the first item. for decl in decls: if isinstance(decl, Declaration): self._add_decl(decl) # Add the rest without checking. for decl in decls: self._add_decl(decl) elif isinstance(decl, HighlevelParsedItem): raise NotImplementedError(decl) else: try: key, decl = decl except ValueError: raise NotImplementedError(decl) if not isinstance(decl, Declaration): raise NotImplementedError(decl) self._add_decl(decl, key) # Add the rest without checking. for key, decl in decls: self._add_decl(decl, key) # The iterator will be exhausted at this point.
# Copyright 2019 Tuomas Aura. See LICENSE.txt for the license. import json def make_table_name(network_name, direction, special=None): if special: return '_'.join((network_name, direction, special, 'v6')) else: return '_'.join((network_name, direction, 'v6')) def make_network_description(net): desc = net['name'] notes = [] if net['vlan']: notes.append('vlan ' + str(net['vlan'])) if net['note']: notes.append(net['note']) if notes: desc = desc + ' (' + ', '.join(notes) + ')' return desc def default_mod_tables(networks, default_action, log_default): tables = { 'ipv6-modify': {} } for net in networks: desc = make_network_description(net) in_table_name = make_table_name(net['name'], 'IN', 'MOD') tables['ipv6-modify'][in_table_name] = { 'description': f'Mark incoming packets from {desc}', 'rule': { 2000: { 'action': 'modify', 'modify': { 'mark': str(net['mark']) }, 'log': 'disable' } } } out_table_name = make_table_name(net['name'], 'OUT', 'MOD') tables['ipv6-modify'][out_table_name] = { 'description': f'Filter outgoing packets to {desc}', 'rule': { 2000: { 'action': 'accept', 'state': { 'established': 'enable', 'related': 'enable' }, 'log': 'disable' }, 2001: { 'action': 'accept', 'protocol': 'ipv6-icmp', 'icmpv6': { 'type': '134' } }, 2002: { 'action': 'accept', 'protocol': 'ipv6-icmp', 'icmpv6': { 'type': '135' } }, 2003: { 'action': 'accept', 'protocol': 'ipv6-icmp', 'icmpv6': { 'type': '136' } }, 2999: { 'description': 'default action', 'action': default_action, 'log': 'enable' if log_default else 'disable' } } } return tables def specific_exception(tables, src_mark, dst_name, action, log, note): out_table_name = make_table_name(dst_name, 'OUT', 'MOD') rules = tables['ipv6-modify'][out_table_name]['rule'] number = 2000 while number in rules: number = number + 1 rules[number] = { 'action': action, 'mark': str(src_mark), 'log': 'enable' if log else 'disable' } if note: rules[number]['description'] = note def src_wildcard_exception(tables, dst_name, action, log, note): out_table_name = make_table_name(dst_name, 'OUT', 'MOD') rules = tables['ipv6-modify'][out_table_name]['rule'] number = 2000 while number in rules: number = number + 1 rules[number] = { 'action': action, 'log': 'enable' if log else 'disable', 'description': 'Override default action' + ( ': '+note if note else '' ) } del rules[2999] def dst_wildcard_exception(tables, src_mark, networks, action, log, note): for net in networks: if net['mark'] != src_mark: specific_exception(tables, src_mark, net['name'], action, log, note) def attach_to_interfaces(networks): interfaces = { 'ethernet': {} } for net in networks: in_table_name = make_table_name(net['name'], 'IN', 'MOD') out_table_name = make_table_name(net['name'], 'OUT', 'MOD') if net['if'] not in interfaces['ethernet']: interfaces['ethernet'][net['if']] = {} firewall = { 'firewall': { 'in': { 'ipv6-modify': in_table_name }, 'out': { 'ipv6-modify': out_table_name } } } if net['vlan']: if 'vif' not in interfaces['ethernet'][net['if']]: interfaces['ethernet'][net['if']]['vif'] = {} interfaces['ethernet'][net['if']]['vif'][net['vlan']] = firewall else: interfaces['ethernet'][net['if']] = firewall return interfaces def make_firewall(networks, default_action, exceptions, log_default): if default_action not in ('drop', 'accept'): raise ValueError(f'Invalid default action: {default_action}. Use "drop" or "accept".') non_default_action = 'drop' if default_action == 'accept' else 'accept' for net in networks: fields = ('name', 'if', 'vlan', 'mark', 'note') for f in fields: if f not in net: raise ValueError(f'Must specify field {f} for all networks.') if not isinstance(net['vlan'], (int, type(None))): raise ValueError(f'Invalid VLAN: {net['vlan']}. Should be a number or None.') if not isinstance(net['mark'], (int, type(None))): raise ValueError(f'Invalid mark: {net['mark']}. Should be a number or None.') network_names = [ net['name'] for net in networks ] for name in network_names: if network_names.count(name) > 1: raise ValueError(f'Network name {name} repeated.') names_to_marks = { net['name']: net['mark'] for net in networks } for ex in exceptions: fields = ('src', 'dst', 'log', 'note') for f in fields: if f not in ex: raise ValueError(f'Must specify field {f} for all exceptions.') if ex['src'] == '*' and ex['dst'] == '*': raise ValueError('Exception cannot have wildcard * as both source and destination.') for name in (ex['src'], ex['dst']): if name != '*' and name not in network_names: raise ValueError(f'{name} in exceptions but not in network names.') if ex['src'] != '*' and names_to_marks[ex['src']] is None: raise ValueError(f'Source network {ex['src']} in exceptions must have numeric mark.') tables = default_mod_tables(networks, default_action, log_default) for ex in exceptions: if ex['src'] == '*': src_wildcard_exception(tables, ex['dst'], non_default_action, ex['log'], ex['note']) else: src_mark = names_to_marks[ex['src']] if ex['dst'] == '*': dst_wildcard_exception(tables, src_mark, networks, non_default_action, ex['log'], ex['note']) else: specific_exception(tables, src_mark, ex['dst'], non_default_action, ex['log'], ex['note']) interfaces = attach_to_interfaces(networks) return { 'firewall': tables, 'interfaces': interfaces } #========================================================================== # Example home network specification networks = [ { 'name': 'WAN', 'if':'eth0', 'vlan': None, 'mark': 1000, 'note': None }, { 'name': 'LAN', 'if':'eth1', 'vlan': None, 'mark': 1001, 'note': 'infra' }, { 'name': 'VLAN1002', 'if':'eth1', 'vlan': 1002, 'mark': 1002, 'note': 'users' }, { 'name': 'VLAN1004', 'if':'eth1', 'vlan': 1004, 'mark': 1004, 'note': 'iot' }, { 'name': 'VLAN1005', 'if':'eth1', 'vlan': 1005, 'mark': 1005, 'note': 'gaming' }, { 'name': 'VLAN1007', 'if':'eth1', 'vlan': 1007, 'mark': 1007, 'note': 'printer' }, { 'name': 'VLAN1009', 'if':'eth1', 'vlan': 1009, 'mark': 1009, 'note': 'guest' }, ] default_action = 'drop' # Exceptions are the opposite i.e. 'accept' log_default = True exceptions = [ { 'src': '*' , 'dst': 'WAN', 'log': False, 'note': 'WAN access from all' }, # { 'src': 'VLAN1002', 'dst': '*', 'log': False, 'note': 'Users can access all' }, { 'src': 'VLAN1002', 'dst': 'LAN', 'log': False, 'note': 'Users to network infra' }, { 'src': 'VLAN1002', 'dst': 'VLAN1004', 'log': False, 'note': 'Users to IoT devices ' }, { 'src': 'VLAN1002', 'dst': 'VLAN1005', 'log': False, 'note': 'Users to gaming PC' }, { 'src': 'VLAN1002', 'dst': 'VLAN1007', 'log': False, 'note': 'Users to printer' }, { 'src': 'VLAN1005', 'dst': 'VLAN1007', 'log': False, 'note': 'Gaming PC to printer' }, ] firewall = make_firewall(networks, default_action, exceptions, log_default) print(json.dumps(firewall, sort_keys=True, indent=4, separators=(',', ': ')))
# Copyright 2019 Tuomas Aura. See LICENSE.txt for the license. import json def make_table_name(network_name, direction, special=None): if special: return '_'.join((network_name, direction, special, 'v6')) else: return '_'.join((network_name, direction, 'v6')) def make_network_description(net): desc = net['name'] notes = [] if net['vlan']: notes.append('vlan ' + str(net['vlan'])) if net['note']: notes.append(net['note']) if notes: desc = desc + ' (' + ', '.join(notes) + ')' return desc def default_mod_tables(networks, default_action, log_default): tables = { 'ipv6-modify': {} } for net in networks: desc = make_network_description(net) in_table_name = make_table_name(net['name'], 'IN', 'MOD') tables['ipv6-modify'][in_table_name] = { 'description': f'Mark incoming packets from {desc}', 'rule': { 2000: { 'action': 'modify', 'modify': { 'mark': str(net['mark']) }, 'log': 'disable' } } } out_table_name = make_table_name(net['name'], 'OUT', 'MOD') tables['ipv6-modify'][out_table_name] = { 'description': f'Filter outgoing packets to {desc}', 'rule': { 2000: { 'action': 'accept', 'state': { 'established': 'enable', 'related': 'enable' }, 'log': 'disable' }, 2001: { 'action': 'accept', 'protocol': 'ipv6-icmp', 'icmpv6': { 'type': '134' } }, 2002: { 'action': 'accept', 'protocol': 'ipv6-icmp', 'icmpv6': { 'type': '135' } }, 2003: { 'action': 'accept', 'protocol': 'ipv6-icmp', 'icmpv6': { 'type': '136' } }, 2999: { 'description': 'default action', 'action': default_action, 'log': 'enable' if log_default else 'disable' } } } return tables def specific_exception(tables, src_mark, dst_name, action, log, note): out_table_name = make_table_name(dst_name, 'OUT', 'MOD') rules = tables['ipv6-modify'][out_table_name]['rule'] number = 2000 while number in rules: number = number + 1 rules[number] = { 'action': action, 'mark': str(src_mark), 'log': 'enable' if log else 'disable' } if note: rules[number]['description'] = note def src_wildcard_exception(tables, dst_name, action, log, note): out_table_name = make_table_name(dst_name, 'OUT', 'MOD') rules = tables['ipv6-modify'][out_table_name]['rule'] number = 2000 while number in rules: number = number + 1 rules[number] = { 'action': action, 'log': 'enable' if log else 'disable', 'description': 'Override default action' + ( ': '+note if note else '' ) } del rules[2999] def dst_wildcard_exception(tables, src_mark, networks, action, log, note): for net in networks: if net['mark'] != src_mark: specific_exception(tables, src_mark, net['name'], action, log, note) def attach_to_interfaces(networks): interfaces = { 'ethernet': {} } for net in networks: in_table_name = make_table_name(net['name'], 'IN', 'MOD') out_table_name = make_table_name(net['name'], 'OUT', 'MOD') if net['if'] not in interfaces['ethernet']: interfaces['ethernet'][net['if']] = {} firewall = { 'firewall': { 'in': { 'ipv6-modify': in_table_name }, 'out': { 'ipv6-modify': out_table_name } } } if net['vlan']: if 'vif' not in interfaces['ethernet'][net['if']]: interfaces['ethernet'][net['if']]['vif'] = {} interfaces['ethernet'][net['if']]['vif'][net['vlan']] = firewall else: interfaces['ethernet'][net['if']] = firewall return interfaces def make_firewall(networks, default_action, exceptions, log_default): if default_action not in ('drop', 'accept'): raise ValueError(f'Invalid default action: {default_action}. Use "drop" or "accept".') non_default_action = 'drop' if default_action == 'accept' else 'accept' for net in networks: fields = ('name', 'if', 'vlan', 'mark', 'note') for f in fields: if f not in net: raise ValueError(f'Must specify field {f} for all networks.') if not isinstance(net['vlan'], (int, type(None))): raise ValueError(f'Invalid VLAN: {net["vlan"]}. Should be a number or None.') if not isinstance(net['mark'], (int, type(None))): raise ValueError(f'Invalid mark: {net["mark"]}. Should be a number or None.') network_names = [ net['name'] for net in networks ] for name in network_names: if network_names.count(name) > 1: raise ValueError(f'Network name {name} repeated.') names_to_marks = { net['name']: net['mark'] for net in networks } for ex in exceptions: fields = ('src', 'dst', 'log', 'note') for f in fields: if f not in ex: raise ValueError(f'Must specify field {f} for all exceptions.') if ex['src'] == '*' and ex['dst'] == '*': raise ValueError('Exception cannot have wildcard * as both source and destination.') for name in (ex['src'], ex['dst']): if name != '*' and name not in network_names: raise ValueError(f'{name} in exceptions but not in network names.') if ex['src'] != '*' and names_to_marks[ex['src']] is None: raise ValueError(f'Source network {ex["src"]} in exceptions must have numeric mark.') tables = default_mod_tables(networks, default_action, log_default) for ex in exceptions: if ex['src'] == '*': src_wildcard_exception(tables, ex['dst'], non_default_action, ex['log'], ex['note']) else: src_mark = names_to_marks[ex['src']] if ex['dst'] == '*': dst_wildcard_exception(tables, src_mark, networks, non_default_action, ex['log'], ex['note']) else: specific_exception(tables, src_mark, ex['dst'], non_default_action, ex['log'], ex['note']) interfaces = attach_to_interfaces(networks) return { 'firewall': tables, 'interfaces': interfaces } #========================================================================== # Example home network specification networks = [ { 'name': 'WAN', 'if':'eth0', 'vlan': None, 'mark': 1000, 'note': None }, { 'name': 'LAN', 'if':'eth1', 'vlan': None, 'mark': 1001, 'note': 'infra' }, { 'name': 'VLAN1002', 'if':'eth1', 'vlan': 1002, 'mark': 1002, 'note': 'users' }, { 'name': 'VLAN1004', 'if':'eth1', 'vlan': 1004, 'mark': 1004, 'note': 'iot' }, { 'name': 'VLAN1005', 'if':'eth1', 'vlan': 1005, 'mark': 1005, 'note': 'gaming' }, { 'name': 'VLAN1007', 'if':'eth1', 'vlan': 1007, 'mark': 1007, 'note': 'printer' }, { 'name': 'VLAN1009', 'if':'eth1', 'vlan': 1009, 'mark': 1009, 'note': 'guest' }, ] default_action = 'drop' # Exceptions are the opposite i.e. 'accept' log_default = True exceptions = [ { 'src': '*' , 'dst': 'WAN', 'log': False, 'note': 'WAN access from all' }, # { 'src': 'VLAN1002', 'dst': '*', 'log': False, 'note': 'Users can access all' }, { 'src': 'VLAN1002', 'dst': 'LAN', 'log': False, 'note': 'Users to network infra' }, { 'src': 'VLAN1002', 'dst': 'VLAN1004', 'log': False, 'note': 'Users to IoT devices ' }, { 'src': 'VLAN1002', 'dst': 'VLAN1005', 'log': False, 'note': 'Users to gaming PC' }, { 'src': 'VLAN1002', 'dst': 'VLAN1007', 'log': False, 'note': 'Users to printer' }, { 'src': 'VLAN1005', 'dst': 'VLAN1007', 'log': False, 'note': 'Gaming PC to printer' }, ] firewall = make_firewall(networks, default_action, exceptions, log_default) print(json.dumps(firewall, sort_keys=True, indent=4, separators=(',', ': ')))
from rest_framework import status from care.facility.models import FacilityUser from care.users.models import User from care.utils.tests.test_base import TestBase from config.tests.helper import mock_equal class TestFacilityUserApi(TestBase): def get_base_url(self): return "/api/v1/users/add_user" def get_list_representation(self, obj) -> dict: raise NotImplementedError def get_detail_representation(self, obj: User = None) -> dict: return { "id": obj.id, "user_type": obj.get_user_type_display(), "gender": obj.get_gender_display(), "password": mock_equal, "username": obj.username, "first_name": obj.first_name, "last_name": obj.last_name, "email": obj.email, "phone_number": obj.phone_number, "age": obj.age, "local_body": getattr(obj.local_body, "id", None), "district": getattr(obj.district, "id", None), "state": getattr(obj.state, "id", None), "skill": obj.skill, } def get_new_user_data(self): return { "username": "roopak", "user_type": "Staff", "phone_number": "+917795937091", "gender": "Male", "age": 28, "first_name": "Roopak", "last_name": "A N", "email": "anroopak@gmail.com", "district": self.district.id, "verified": True, "facilities": [self.facility.id], } def test_create_facility_user__should_succeed__when_same_level(self): data = self.get_new_user_data().copy() response = self.client.post(self.get_url(), data=data, format="json") # Test Creation self.assertEquals(response.status_code, status.HTTP_201_CREATED) user_id = response.json()["id"] user = User.objects.filter(id=user_id).first() self.assertIsNotNone(user) self.assertDictEqual(response.json(), self.get_detail_representation(user)) # Test for login password = response.json()["password"] self.client.login(username=data["username"], password=password) response = self.client.post( f"/api/v1/auth/login/", data={"username": data["username"], "password": password}, format="json" ) self.assertEquals(response.status_code, status.HTTP_200_OK) # Test if user is added to the facility self.assertIn(user, self.facility.users.all()) response = self.client.get(f"/api/v1/facility/{self.facility.id}/") self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertEquals( FacilityUser.objects.filter(facility=self.facility, user=user, created_by=self.user).count(), 1 ) def test_create_facility_user__should_succeed__when_lower_level(self): data = self.get_new_user_data().copy() data.update({"user_type": "Doctor"}) response = self.client.post(self.get_url(), data=data, format="json") # Test Creation self.assertEquals(response.status_code, status.HTTP_201_CREATED) user_id = response.json()["id"] user = User.objects.filter(id=user_id).first() self.assertIsNotNone(user) self.assertDictEqual(response.json(), self.get_detail_representation(user)) # Test for login password = response.json()["password"] self.client.login(username=data["username"], password=password) response = self.client.post( f"/api/v1/auth/login/", data={"username": data["username"], "password": password}, format="json" ) self.assertEquals(response.status_code, status.HTTP_200_OK) # Test if user is added to the facility self.assertIn(user, self.facility.users.all()) response = self.client.get(f"/api/v1/facility/{self.facility.id}/") self.assertEquals(response.status_code, status.HTTP_200_OK) def test_create_facility_user__should_fail__when_higher_level(self): data = self.get_new_user_data().copy() data.update({"user_type": "DistrictAdmin"}) response = self.client.post(self.get_url(), data=data, format="json") # Test Creation self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) def test_create_facility_user__should_fail__when_different_location(self): new_district = self.clone_object(self.district) data = self.get_new_user_data().copy() data.update({"district": new_district.id}) response = self.client.post(self.get_url(), data=data, format="json") # Test Creation self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST)
from rest_framework import status from care.facility.models import FacilityUser from care.users.models import User from care.utils.tests.test_base import TestBase from config.tests.helper import mock_equal class TestFacilityUserApi(TestBase): def get_base_url(self): return "/api/v1/users/add_user" def get_list_representation(self, obj) -> dict: raise NotImplementedError def get_detail_representation(self, obj: User = None) -> dict: return { "id": obj.id, "user_type": obj.get_user_type_display(), "gender": obj.get_gender_display(), "password": mock_equal, "username": obj.username, "first_name": obj.first_name, "last_name": obj.last_name, "email": obj.email, "phone_number": obj.phone_number, "age": obj.age, "local_body": getattr(obj.local_body, "id", None), "district": getattr(obj.district, "id", None), "state": getattr(obj.state, "id", None), "skill": obj.skill, } def get_new_user_data(self): return { "username": "roopak", "user_type": "Staff", "phone_number": "+917795937091", "gender": "Male", "age": 28, "first_name": "Roopak", "last_name": "A N", "email": "anroopak@gmail.com", "district": self.district.id, "verified": True, "facilities": [self.facility.id], } def test_create_facility_user__should_succeed__when_same_level(self): data = self.get_new_user_data().copy() response = self.client.post(self.get_url(), data=data, format="json") # Test Creation self.assertEquals(response.status_code, status.HTTP_201_CREATED) user_id = response.json()["id"] user = User.objects.filter(id=user_id).first() self.assertIsNotNone(user) self.assertDictEqual(response.json(), self.get_detail_representation(user)) # Test for login password = response.json()["password"] self.client.login(username=data["username"], password=password) response = self.client.post( f"/api/v1/auth/login/", data={"username": data["username"], "password": password}, format="json" ) self.assertEquals(response.status_code, status.HTTP_200_OK) # Test if user is added to the facility self.assertIn(user, self.facility.users.all()) response = self.client.get(f"/api/v1/facility/{self.facility.id}/") self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertEquals( FacilityUser.objects.filter(facility=self.facility, user=user, created_by=self.user).count(), 1 ) def test_create_facility_user__should_succeed__when_lower_level(self): data = self.get_new_user_data().copy() data.update({"user_type": "Doctor"}) response = self.client.post(self.get_url(), data=data, format="json") # Test Creation self.assertEquals(response.status_code, status.HTTP_201_CREATED) user_id = response.json()["id"] user = User.objects.filter(id=user_id).first() self.assertIsNotNone(user) self.assertDictEqual(response.json(), self.get_detail_representation(user)) # Test for login password = response.json()["password"] self.client.login(username=data["username"], password=password) response = self.client.post( f"/api/v1/auth/login/", data={"username": data["username"], "password": password}, format="json" ) self.assertEquals(response.status_code, status.HTTP_200_OK) # Test if user is added to the facility self.assertIn(user, self.facility.users.all()) response = self.client.get(f"/api/v1/facility/{self.facility.id}/") self.assertEquals(response.status_code, status.HTTP_200_OK) def test_create_facility_user__should_fail__when_higher_level(self): data = self.get_new_user_data().copy() data.update({"user_type": "DistrictAdmin"}) response = self.client.post(self.get_url(), data=data, format="json") # Test Creation self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) def test_create_facility_user__should_fail__when_different_location(self): new_district = self.clone_object(self.district) data = self.get_new_user_data().copy() data.update({"district": new_district.id}) response = self.client.post(self.get_url(), data=data, format="json") # Test Creation self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST)
import argparse import os import socket import subprocess import sys import time import uuid import psutil from flask import Config import redis import redis.sentinel from workers.workers import AssetWorker from swm import monitors site_path = "/sites/h51" logfile_path = os.path.join(site_path, 'logs', 'workers_debug.log') spawn_command = [ '/usr/bin/nohup', '/sites/h51/venv/bin/python', '/sites/h51/asset_worker.py', '--env', 'production' ] command_signature = ' '.join(['python', 'asset_worker.py', '--env', 'production']) class ControlWorkers(object): def __init__(self, args): self.env = args.env self.action = args.action self.kill_delay = args.kill_delay self.conn = None # Load settings self.config = Config(os.path.dirname(os.path.realpath(__file__))) # There may be overiding settings specific to the server we are running on servername = socket.gethostname().split('.')[0] if servername and os.path.isfile(f'settings/workers/{self.env}_{servername}.py'): self.config.from_object(f'settings.workers.{self.env}_{servername}.Config') else: self.config.from_object(f'settings.workers.{self.env}.Config') # Redis if self.config['REDIS_USE_SENTINEL']: sentinel = redis.sentinel.Sentinel( self.config['REDIS_ADDRESS'], db=self.config['REDIS_DB'], password=self.config['REDIS_PASSWORD'], decode_responses=True ) self.conn = sentinel.master_for(self.config['REDIS_SENTINEL_MASTER']) else: self.conn = redis.StrictRedis( host=self.config['REDIS_ADDRESS'][0], port=self.config['REDIS_ADDRESS'][1], db=self.config['REDIS_DB'], password=self.config['REDIS_PASSWORD'], decode_responses=True ) def run(self): if self.action == 'status': self.status_workers() elif self.action == 'spawn': self.spawn_worker() elif self.action == 'stop': self.stop_workers() elif self.action == 'respawn': self.stop_workers() self.spawn_worker() def spawn_worker(self): """This will spawn an initial worker. More workers will be spawned as needed within limits set in config. """ # Check we don't already have workers running procs = self.get_worker_processes() if procs: sys.exit( "Not spawning new worker because running worker process(es) found " f"pids: {" ".join([p.pid for p in procs])}" ) r = subprocess.Popen( spawn_command, stdout=open(logfile_path, 'a'), stderr=open(logfile_path, 'a') ) if r.returncode: print(f'Failed to spawn worker, return code {r.returncode}') print(f'There may be more info in {logfile_path}') sys.exit(1) def stop_workers(self): monitors.shutdown_workers(self.conn, AssetWorker, uuid.getnode()) # Allow time for monitors to kill themselves while self.kill_delay > 0 and self.get_worker_processes(): time.sleep(1) self.kill_delay -= 1 # Forcibly kill any that remain as procs = [p for p in psutil.process_iter() if command_signature in ' '.join(p.cmdline())] if not procs: return for p in alive: print(f"forcibly killing {p.pid}") p.kill() sys.exit(1) def respawn_workers(self): self.stop_workers() self.spawn_worker def status_workers(self): procs = self.get_worker_processes() print(f"{len(procs)} workers running") if procs: sys.exit(0) else: sys.exit(1) def get_worker_processes(self): return [p for p in psutil.process_iter() if command_signature in ' '.join(p.cmdline())] # Main if __name__ == '__main__': # Parse command-line arguments parser = argparse.ArgumentParser(description='API application') parser.add_argument( '-e', '--env', choices=['staging', 'production'], default='', dest='env', required=False ) parser.add_argument( '-a', '--action', choices=['spawn', 'stop', 'status', 'respawn'], default='status', dest='action', required=False ) parser.add_argument( '-k', '--kill-delay', default=10, dest='kill_delay', required=False, type=int ) args = parser.parse_args() # Create the application controller = ControlWorkers(args) controller.run()
import argparse import os import socket import subprocess import sys import time import uuid import psutil from flask import Config import redis import redis.sentinel from workers.workers import AssetWorker from swm import monitors site_path = "/sites/h51" logfile_path = os.path.join(site_path, 'logs', 'workers_debug.log') spawn_command = [ '/usr/bin/nohup', '/sites/h51/venv/bin/python', '/sites/h51/asset_worker.py', '--env', 'production' ] command_signature = ' '.join(['python', 'asset_worker.py', '--env', 'production']) class ControlWorkers(object): def __init__(self, args): self.env = args.env self.action = args.action self.kill_delay = args.kill_delay self.conn = None # Load settings self.config = Config(os.path.dirname(os.path.realpath(__file__))) # There may be overiding settings specific to the server we are running on servername = socket.gethostname().split('.')[0] if servername and os.path.isfile(f'settings/workers/{self.env}_{servername}.py'): self.config.from_object(f'settings.workers.{self.env}_{servername}.Config') else: self.config.from_object(f'settings.workers.{self.env}.Config') # Redis if self.config['REDIS_USE_SENTINEL']: sentinel = redis.sentinel.Sentinel( self.config['REDIS_ADDRESS'], db=self.config['REDIS_DB'], password=self.config['REDIS_PASSWORD'], decode_responses=True ) self.conn = sentinel.master_for(self.config['REDIS_SENTINEL_MASTER']) else: self.conn = redis.StrictRedis( host=self.config['REDIS_ADDRESS'][0], port=self.config['REDIS_ADDRESS'][1], db=self.config['REDIS_DB'], password=self.config['REDIS_PASSWORD'], decode_responses=True ) def run(self): if self.action == 'status': self.status_workers() elif self.action == 'spawn': self.spawn_worker() elif self.action == 'stop': self.stop_workers() elif self.action == 'respawn': self.stop_workers() self.spawn_worker() def spawn_worker(self): """This will spawn an initial worker. More workers will be spawned as needed within limits set in config. """ # Check we don't already have workers running procs = self.get_worker_processes() if procs: sys.exit( "Not spawning new worker because running worker process(es) found " f"pids: {' '.join([p.pid for p in procs])}" ) r = subprocess.Popen( spawn_command, stdout=open(logfile_path, 'a'), stderr=open(logfile_path, 'a') ) if r.returncode: print(f'Failed to spawn worker, return code {r.returncode}') print(f'There may be more info in {logfile_path}') sys.exit(1) def stop_workers(self): monitors.shutdown_workers(self.conn, AssetWorker, uuid.getnode()) # Allow time for monitors to kill themselves while self.kill_delay > 0 and self.get_worker_processes(): time.sleep(1) self.kill_delay -= 1 # Forcibly kill any that remain as procs = [p for p in psutil.process_iter() if command_signature in ' '.join(p.cmdline())] if not procs: return for p in alive: print(f"forcibly killing {p.pid}") p.kill() sys.exit(1) def respawn_workers(self): self.stop_workers() self.spawn_worker def status_workers(self): procs = self.get_worker_processes() print(f"{len(procs)} workers running") if procs: sys.exit(0) else: sys.exit(1) def get_worker_processes(self): return [p for p in psutil.process_iter() if command_signature in ' '.join(p.cmdline())] # Main if __name__ == '__main__': # Parse command-line arguments parser = argparse.ArgumentParser(description='API application') parser.add_argument( '-e', '--env', choices=['staging', 'production'], default='', dest='env', required=False ) parser.add_argument( '-a', '--action', choices=['spawn', 'stop', 'status', 'respawn'], default='status', dest='action', required=False ) parser.add_argument( '-k', '--kill-delay', default=10, dest='kill_delay', required=False, type=int ) args = parser.parse_args() # Create the application controller = ControlWorkers(args) controller.run()
from project.room import Room class Hotel: def __init__(self, name: str): self.name = name self.rooms = [] self.guests = 0 @classmethod def from_stars(cls, stars_count: int): new_name = f"{stars_count} stars Hotel" return cls(new_name) def add_room(self, room: Room): self.rooms.append(room) def take_room(self, room_number, people): for current_room in self.rooms: if current_room.number == room_number: result = current_room.take_room(people) if not result: self.guests += people def free_room(self, room_number): for current_room in self.rooms: if current_room.number == room_number: self.guests = 0 current_room.free_room() def status(self): free_rooms = [str(current_room.number) for current_room in self.rooms if not current_room.is_taken] taken_rooms = [str(current_room.number) for current_room in self.rooms if current_room.is_taken] return f"Hotel {self.name} has {self.guests} total guests\n" +\ f"Free rooms: {", ".join(free_rooms)}\n" +\ f"Taken rooms: {", ".join(taken_rooms)}"
from project.room import Room class Hotel: def __init__(self, name: str): self.name = name self.rooms = [] self.guests = 0 @classmethod def from_stars(cls, stars_count: int): new_name = f"{stars_count} stars Hotel" return cls(new_name) def add_room(self, room: Room): self.rooms.append(room) def take_room(self, room_number, people): for current_room in self.rooms: if current_room.number == room_number: result = current_room.take_room(people) if not result: self.guests += people def free_room(self, room_number): for current_room in self.rooms: if current_room.number == room_number: self.guests = 0 current_room.free_room() def status(self): free_rooms = [str(current_room.number) for current_room in self.rooms if not current_room.is_taken] taken_rooms = [str(current_room.number) for current_room in self.rooms if current_room.is_taken] return f"Hotel {self.name} has {self.guests} total guests\n" +\ f"Free rooms: {', '.join(free_rooms)}\n" +\ f"Taken rooms: {', '.join(taken_rooms)}"
from PyBambooHR.PyBambooHR import PyBambooHR import csv import os import pandas as pd import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import random import statistics import sys import jinja2 import itertools import configparser def load_df(): EMPLOYEES_CSV = config['DEFAULT']['EMPLOYEES_CSV'] CSV_DELIMITER = config['DEFAULT']['CSV_DELIMITER'] FEATURES = config['GROUPING']['FEATURES'].split(',') BAMBOOHR_APIKEY = config['BAMBOO']['APIKEY'] BAMBOOHR_SUBDOMAIN = config['BAMBOO']['SUBDOMAIN'] if not os.path.exists(EMPLOYEES_CSV): # Load employee info from BambooHR into a Pandas data frame employees = PyBambooHR( subdomain=BAMBOOHR_SUBDOMAIN, api_key=BAMBOOHR_APIKEY, ).get_employee_directory() employees_list = [[e[v] for v in FEATURES] for e in employees] with open(EMPLOYEES_CSV, 'w', newline='', encoding='utf-8') as csv_file: writer = csv.writer(csv_file, delimiter=CSV_DELIMITER) for employee in employees_list: writer.writerow(employee) else: print("Found existing employees data. Remove it manually if you want to refresh and get the latest data.") df = pd.read_csv( EMPLOYEES_CSV, names=['name', 'email', 'department', 'city', 'title', 'firstName'], sep=CSV_DELIMITER ).dropna() return df def partition(df, group_size, feature, group_constraints, trials=100000): """Takes a dataframe and returns a list of list of indices such that we have m+n disjoint sublists with m*4+n*3=len(list) and m being as great as possible (m,n being natural numbers greater than 0) and diversity of "feature" within sublists is high: samples _trials_ partitions and takes the best one with respect to _diversity_ score """ def calculateDiversity(partition): partitions = [list(map(lambda member: member[1], group)) for group in partition] partitionsDiversity = list(map(lambda group: (len(set(group)) * 1.0) / len(group), partitions)) return statistics.mean(partitionsDiversity) def find_suitable_group_sizes(total): i = 0 while i <= total and (total - i) % group_size != 0: i += group_size_minus if i <= total: num_normal_group_size = int((total - i)/group_size) num_minus_group_size = int(i/group_size_minus) return (num_normal_group_size, num_minus_group_size, (num_normal_group_size*group_size)%total) else: raise Exception(f"Not able to find suitable group size {group_size} for the total number of {total}") num_indices = df.shape[0] if num_indices <= (group_size + 1): return [list(df.index)] else: group_size_minus = group_size - 1 num_normal_group_size, num_minus_group_size, offset = find_suitable_group_sizes(num_indices) indexed = list(zip(df.index, df[feature])) bestScore = -1 for _ in range(trials): random.shuffle(indexed) partition = [indexed[i*group_size : (i+1)*group_size] for i in range(0, num_normal_group_size)] + \ [indexed[offset+(i*group_size_minus) : offset+(i+1)*group_size_minus] for i in range(0, num_minus_group_size)] if group_constraints is not None: partition_emails = [set(map(lambda member: df.loc[member[0]]['email'], group)) for group in partition] set_group_constraints = [set(c) for c in group_constraints] group_constraint_pairs = list(itertools.product(partition_emails, set_group_constraints)) if any(group.issuperset(constraint) for group, constraint in group_constraint_pairs): continue currentScore = calculateDiversity(partition) if currentScore > bestScore: bestScore = currentScore bestPartition = partition return [list(map(lambda member: member[0], group)) for group in bestPartition] def create_group_emails(group, df, sender, title, body_template): ret_list = [] organiser_id = random.randrange(len(group)) organiser = df.loc[group[organiser_id]]['name'] for index in group: name = df.loc[index]['firstName'] email = df.loc[index]['email'] buddy_info = [] buddy_emails = [] for buddy_index in group: if index != buddy_index: buddy_info.append([ df.loc[buddy_index]['name'], df.loc[buddy_index]['department'], df.loc[buddy_index]['title'], df.loc[buddy_index]['city']]) buddy_emails.append(df.loc[buddy_index]['email']) msg = MIMEMultipart() msg['From'] = sender msg['To'] = email msg['reply-to'] = ', '.join(buddy_emails) msg['Subject'] = "{}, {}".format(name, title) body = body_template.render(name=name, buddy_info=buddy_info, group=group, index=index, organiser_id=organiser_id, organiser=organiser) msg.attach(MIMEText(body, 'plain')) ret_list.append([msg, email]) return ret_list def generate_and_send_emails(groups, df, body_template, test_recipient=None): SMTP_SENDER = config['SMTP']['SENDER'] SMTP_SUBJECT = config['SMTP']['SUBJECT'] SMTP_HOST = config['SMTP']['HOST'] SMTP_PORT = int(config['SMTP']['PORT']) SMTP_USER = config['SMTP']['USER'] SMTP_PASSWORD = config['SMTP']['PASSWORD'] with smtplib.SMTP(host=SMTP_HOST, port=SMTP_PORT) as smtp: if SMTP_USER: smtp.login(SMTP_USER, SMTP_PASSWORD) for group in groups: group_emails = create_group_emails(group, df, SMTP_SENDER, SMTP_SUBJECT, body_template) for email in group_emails: text = email[0].as_string() recipient = email[1] if test_recipient is None: smtp.sendmail(SMTP_SENDER, recipient, text) elif recipient == test_recipient: smtp.sendmail(SMTP_SENDER, test_recipient, text) def debug_send_emails(groups, df): for group in groups: print(f"{"city":>15}{"department":>45}{"title":>60}{"name":>60}") for index in group: print(f"{df.loc[index]["city"]:>15}{df.loc[index]["department"]:>45}{df.loc[index]["title"]:>60}{df.loc[index]["name"]:>60}") print("\n***************************************\n") def run(group_size, filterFunc, template_filename, diversity_feature, group_constraints=None): test_recepient = None send_emails = sys.argv[-1] == 'send' test_emails = len(sys.argv) == 3 and sys.argv[-2] == 'test' if send_emails: print('Sending real emails') elif test_emails: test_recepient = sys.argv[-1] print('Sending test emails to {}'.format(test_recepient)) else: print('Printing example emails') df = load_df() filtered_df = df.loc[filterFunc(df), :] NUMBER_OF_TRIALS = int(config['GROUPING']['NUMBER_OF_TRIALS']) groups = partition(filtered_df, group_size, diversity_feature, group_constraints, NUMBER_OF_TRIALS) if send_emails or test_emails: with open(template_filename, 'r') as f: body_template = jinja2.Template(f.read()) generate_and_send_emails(groups, filtered_df, body_template, test_recepient) else: debug_send_emails(groups, filtered_df) def filter_bamboo_coffee(df): WHITELIST_LOCATIONS = config['GROUPING']['WHITELIST_LOCATIONS'].split(',') OPT_OUT_EMPLOYEES = config['GROUPING']['OPT_OUT_EMPLOYEES'].split(',') return df['city'].isin(WHITELIST_LOCATIONS) & ~df['email'].isin(OPT_OUT_EMPLOYEES) if __name__ == '__main__': global config config = configparser.ConfigParser() config.read('config.txt') GROUP_SIZE = int(config['GROUPING']['GROUP_SIZE']) OPTIMIZED_FEATURE = config['GROUPING']['OPTIMIZED_FEATURE'] run(GROUP_SIZE, filter_bamboo_coffee, 'bamboo_coffee.j2', OPTIMIZED_FEATURE)
from PyBambooHR.PyBambooHR import PyBambooHR import csv import os import pandas as pd import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import random import statistics import sys import jinja2 import itertools import configparser def load_df(): EMPLOYEES_CSV = config['DEFAULT']['EMPLOYEES_CSV'] CSV_DELIMITER = config['DEFAULT']['CSV_DELIMITER'] FEATURES = config['GROUPING']['FEATURES'].split(',') BAMBOOHR_APIKEY = config['BAMBOO']['APIKEY'] BAMBOOHR_SUBDOMAIN = config['BAMBOO']['SUBDOMAIN'] if not os.path.exists(EMPLOYEES_CSV): # Load employee info from BambooHR into a Pandas data frame employees = PyBambooHR( subdomain=BAMBOOHR_SUBDOMAIN, api_key=BAMBOOHR_APIKEY, ).get_employee_directory() employees_list = [[e[v] for v in FEATURES] for e in employees] with open(EMPLOYEES_CSV, 'w', newline='', encoding='utf-8') as csv_file: writer = csv.writer(csv_file, delimiter=CSV_DELIMITER) for employee in employees_list: writer.writerow(employee) else: print("Found existing employees data. Remove it manually if you want to refresh and get the latest data.") df = pd.read_csv( EMPLOYEES_CSV, names=['name', 'email', 'department', 'city', 'title', 'firstName'], sep=CSV_DELIMITER ).dropna() return df def partition(df, group_size, feature, group_constraints, trials=100000): """Takes a dataframe and returns a list of list of indices such that we have m+n disjoint sublists with m*4+n*3=len(list) and m being as great as possible (m,n being natural numbers greater than 0) and diversity of "feature" within sublists is high: samples _trials_ partitions and takes the best one with respect to _diversity_ score """ def calculateDiversity(partition): partitions = [list(map(lambda member: member[1], group)) for group in partition] partitionsDiversity = list(map(lambda group: (len(set(group)) * 1.0) / len(group), partitions)) return statistics.mean(partitionsDiversity) def find_suitable_group_sizes(total): i = 0 while i <= total and (total - i) % group_size != 0: i += group_size_minus if i <= total: num_normal_group_size = int((total - i)/group_size) num_minus_group_size = int(i/group_size_minus) return (num_normal_group_size, num_minus_group_size, (num_normal_group_size*group_size)%total) else: raise Exception(f"Not able to find suitable group size {group_size} for the total number of {total}") num_indices = df.shape[0] if num_indices <= (group_size + 1): return [list(df.index)] else: group_size_minus = group_size - 1 num_normal_group_size, num_minus_group_size, offset = find_suitable_group_sizes(num_indices) indexed = list(zip(df.index, df[feature])) bestScore = -1 for _ in range(trials): random.shuffle(indexed) partition = [indexed[i*group_size : (i+1)*group_size] for i in range(0, num_normal_group_size)] + \ [indexed[offset+(i*group_size_minus) : offset+(i+1)*group_size_minus] for i in range(0, num_minus_group_size)] if group_constraints is not None: partition_emails = [set(map(lambda member: df.loc[member[0]]['email'], group)) for group in partition] set_group_constraints = [set(c) for c in group_constraints] group_constraint_pairs = list(itertools.product(partition_emails, set_group_constraints)) if any(group.issuperset(constraint) for group, constraint in group_constraint_pairs): continue currentScore = calculateDiversity(partition) if currentScore > bestScore: bestScore = currentScore bestPartition = partition return [list(map(lambda member: member[0], group)) for group in bestPartition] def create_group_emails(group, df, sender, title, body_template): ret_list = [] organiser_id = random.randrange(len(group)) organiser = df.loc[group[organiser_id]]['name'] for index in group: name = df.loc[index]['firstName'] email = df.loc[index]['email'] buddy_info = [] buddy_emails = [] for buddy_index in group: if index != buddy_index: buddy_info.append([ df.loc[buddy_index]['name'], df.loc[buddy_index]['department'], df.loc[buddy_index]['title'], df.loc[buddy_index]['city']]) buddy_emails.append(df.loc[buddy_index]['email']) msg = MIMEMultipart() msg['From'] = sender msg['To'] = email msg['reply-to'] = ', '.join(buddy_emails) msg['Subject'] = "{}, {}".format(name, title) body = body_template.render(name=name, buddy_info=buddy_info, group=group, index=index, organiser_id=organiser_id, organiser=organiser) msg.attach(MIMEText(body, 'plain')) ret_list.append([msg, email]) return ret_list def generate_and_send_emails(groups, df, body_template, test_recipient=None): SMTP_SENDER = config['SMTP']['SENDER'] SMTP_SUBJECT = config['SMTP']['SUBJECT'] SMTP_HOST = config['SMTP']['HOST'] SMTP_PORT = int(config['SMTP']['PORT']) SMTP_USER = config['SMTP']['USER'] SMTP_PASSWORD = config['SMTP']['PASSWORD'] with smtplib.SMTP(host=SMTP_HOST, port=SMTP_PORT) as smtp: if SMTP_USER: smtp.login(SMTP_USER, SMTP_PASSWORD) for group in groups: group_emails = create_group_emails(group, df, SMTP_SENDER, SMTP_SUBJECT, body_template) for email in group_emails: text = email[0].as_string() recipient = email[1] if test_recipient is None: smtp.sendmail(SMTP_SENDER, recipient, text) elif recipient == test_recipient: smtp.sendmail(SMTP_SENDER, test_recipient, text) def debug_send_emails(groups, df): for group in groups: print(f"{'city':>15}{'department':>45}{'title':>60}{'name':>60}") for index in group: print(f"{df.loc[index]['city']:>15}{df.loc[index]['department']:>45}{df.loc[index]['title']:>60}{df.loc[index]['name']:>60}") print("\n***************************************\n") def run(group_size, filterFunc, template_filename, diversity_feature, group_constraints=None): test_recepient = None send_emails = sys.argv[-1] == 'send' test_emails = len(sys.argv) == 3 and sys.argv[-2] == 'test' if send_emails: print('Sending real emails') elif test_emails: test_recepient = sys.argv[-1] print('Sending test emails to {}'.format(test_recepient)) else: print('Printing example emails') df = load_df() filtered_df = df.loc[filterFunc(df), :] NUMBER_OF_TRIALS = int(config['GROUPING']['NUMBER_OF_TRIALS']) groups = partition(filtered_df, group_size, diversity_feature, group_constraints, NUMBER_OF_TRIALS) if send_emails or test_emails: with open(template_filename, 'r') as f: body_template = jinja2.Template(f.read()) generate_and_send_emails(groups, filtered_df, body_template, test_recepient) else: debug_send_emails(groups, filtered_df) def filter_bamboo_coffee(df): WHITELIST_LOCATIONS = config['GROUPING']['WHITELIST_LOCATIONS'].split(',') OPT_OUT_EMPLOYEES = config['GROUPING']['OPT_OUT_EMPLOYEES'].split(',') return df['city'].isin(WHITELIST_LOCATIONS) & ~df['email'].isin(OPT_OUT_EMPLOYEES) if __name__ == '__main__': global config config = configparser.ConfigParser() config.read('config.txt') GROUP_SIZE = int(config['GROUPING']['GROUP_SIZE']) OPTIMIZED_FEATURE = config['GROUPING']['OPTIMIZED_FEATURE'] run(GROUP_SIZE, filter_bamboo_coffee, 'bamboo_coffee.j2', OPTIMIZED_FEATURE)
import asyncio import pytest import pickle from pathlib import Path from aionetworking.compatibility import py37 @pytest.mark.connections('sftp_oneway_all') class TestConnectionShared: @pytest.mark.asyncio async def test_00_connection_made_lost(self, connection, sftp_conn, sftp_adaptor, connections_manager, sftp_factory): assert connections_manager.total == 0 assert connection.logger assert connection.conn is None connection.connection_made(sftp_conn) await connection.wait_connected() assert connection.is_connected() await asyncio.wait_for(connection.wait_context_set(), timeout=1) assert connection._adaptor.context == sftp_adaptor.context assert connection._adaptor == sftp_adaptor assert sftp_factory.sftp_connection == connection assert sftp_conn.get_extra_info('sftp_factory') == sftp_factory assert connection.peer == f"sftp_{sftp_adaptor.context["own"]}_{sftp_adaptor.context["peer"]}" assert connection.logger is not None assert connection.conn == sftp_conn assert connections_manager.total == 1 assert connections_manager.get(connection.peer) == connection sftp_conn.close() await connection.wait_closed() assert connections_manager.total == 0 def test_01_is_child(self, connection, parent_name): assert connection.is_child(parent_name) assert not connection.is_child(f"ABC Server") @pytest.mark.skipif(not py37, reason="Pickle SFTP connection not working in python3.6") def test_02_pickle(self, connection): data = pickle.dumps(connection) protocol = pickle.loads(data) assert protocol == connection @pytest.mark.connections('sftp_oneway_server') class TestConnectionServer: @pytest.mark.asyncio async def test_00_data_received(self, sftp_connection_connected, sftp_factory, fixed_timestamp, json_rpc_login_request_encoded, json_rpc_logout_request_encoded, assert_recordings_ok, assert_buffered_file_storage_ok): sftp_connection_connected.data_received(json_rpc_login_request_encoded) await asyncio.sleep(1.2) sftp_connection_connected.data_received(json_rpc_logout_request_encoded) sftp_connection_connected.close() await asyncio.wait_for(sftp_connection_connected.wait_closed(), timeout=1) await assert_buffered_file_storage_ok await assert_recordings_ok @pytest.mark.connections('sftp_oneway_server') class TestConnectionServerOSAuth: def test_00_password_auth_supported(self, connection): assert connection.password_auth_supported() @pytest.mark.asyncio async def test_01_password_auth_successful(self, connection, sftp_username_password, patch_os_auth_ok, patch_os_call_args): result = await connection.validate_password(*sftp_username_password) assert result is True patch_os_auth_ok.assert_called_with(*patch_os_call_args) @pytest.mark.asyncio async def test_02_password_auth_failure(self, connection, sftp_username_password, patch_os_auth_failure, patch_os_call_args): result = await connection.validate_password(*sftp_username_password) assert result is False patch_os_auth_failure.assert_called_with(*patch_os_call_args) @pytest.mark.connections('sftp_oneway_client') class TestConnectionClient: @pytest.mark.asyncio async def test_00_send(self, sftp_connection_connected, sftp_factory, fixed_timestamp, tmpdir, json_rpc_login_request_encoded): sftp_factory.realpath.assert_awaited_with('/') await sftp_connection_connected.send(json_rpc_login_request_encoded) sftp_factory.put.assert_awaited_with(Path(tmpdir) / "sftp_sent/FILE201901010101000000000000", remotepath='/') @pytest.mark.asyncio async def test_01_send_data_adaptor_method(self, sftp_connection_connected, sftp_factory, fixed_timestamp, json_rpc_login_request_encoded, tmpdir): sftp_connection_connected.send_data(json_rpc_login_request_encoded) await sftp_connection_connected.wait_tasks_done() sftp_factory.put.assert_awaited_with(Path(tmpdir) / "sftp_sent/FILE201901010101000000000000", remotepath='/') @pytest.mark.connections('sftp_oneway_all') class TestSFTPProtocolFactories: @pytest.mark.asyncio async def test_00_connection_lifecycle(self, protocol_factory_started, connection, sftp_conn, sftp_factory): new_connection = protocol_factory_started() assert protocol_factory_started.logger == new_connection.logger assert new_connection == connection assert protocol_factory_started.is_owner(new_connection) new_connection.connection_made(sftp_conn) sftp_conn._owner = new_connection await asyncio.wait_for(protocol_factory_started.wait_num_connected(1), timeout=1) await asyncio.wait_for(new_connection.wait_connected(), timeout=1) sftp_conn.close() await asyncio.wait_for(protocol_factory_started.close(), timeout=2) await asyncio.wait_for(new_connection.wait_closed(), timeout=1) @pytest.mark.asyncio async def test_01_pickle_protocol_factory(self, protocol_factory): data = pickle.dumps(protocol_factory) factory = pickle.loads(data) assert factory == protocol_factory await protocol_factory.close()
import asyncio import pytest import pickle from pathlib import Path from aionetworking.compatibility import py37 @pytest.mark.connections('sftp_oneway_all') class TestConnectionShared: @pytest.mark.asyncio async def test_00_connection_made_lost(self, connection, sftp_conn, sftp_adaptor, connections_manager, sftp_factory): assert connections_manager.total == 0 assert connection.logger assert connection.conn is None connection.connection_made(sftp_conn) await connection.wait_connected() assert connection.is_connected() await asyncio.wait_for(connection.wait_context_set(), timeout=1) assert connection._adaptor.context == sftp_adaptor.context assert connection._adaptor == sftp_adaptor assert sftp_factory.sftp_connection == connection assert sftp_conn.get_extra_info('sftp_factory') == sftp_factory assert connection.peer == f"sftp_{sftp_adaptor.context['own']}_{sftp_adaptor.context['peer']}" assert connection.logger is not None assert connection.conn == sftp_conn assert connections_manager.total == 1 assert connections_manager.get(connection.peer) == connection sftp_conn.close() await connection.wait_closed() assert connections_manager.total == 0 def test_01_is_child(self, connection, parent_name): assert connection.is_child(parent_name) assert not connection.is_child(f"ABC Server") @pytest.mark.skipif(not py37, reason="Pickle SFTP connection not working in python3.6") def test_02_pickle(self, connection): data = pickle.dumps(connection) protocol = pickle.loads(data) assert protocol == connection @pytest.mark.connections('sftp_oneway_server') class TestConnectionServer: @pytest.mark.asyncio async def test_00_data_received(self, sftp_connection_connected, sftp_factory, fixed_timestamp, json_rpc_login_request_encoded, json_rpc_logout_request_encoded, assert_recordings_ok, assert_buffered_file_storage_ok): sftp_connection_connected.data_received(json_rpc_login_request_encoded) await asyncio.sleep(1.2) sftp_connection_connected.data_received(json_rpc_logout_request_encoded) sftp_connection_connected.close() await asyncio.wait_for(sftp_connection_connected.wait_closed(), timeout=1) await assert_buffered_file_storage_ok await assert_recordings_ok @pytest.mark.connections('sftp_oneway_server') class TestConnectionServerOSAuth: def test_00_password_auth_supported(self, connection): assert connection.password_auth_supported() @pytest.mark.asyncio async def test_01_password_auth_successful(self, connection, sftp_username_password, patch_os_auth_ok, patch_os_call_args): result = await connection.validate_password(*sftp_username_password) assert result is True patch_os_auth_ok.assert_called_with(*patch_os_call_args) @pytest.mark.asyncio async def test_02_password_auth_failure(self, connection, sftp_username_password, patch_os_auth_failure, patch_os_call_args): result = await connection.validate_password(*sftp_username_password) assert result is False patch_os_auth_failure.assert_called_with(*patch_os_call_args) @pytest.mark.connections('sftp_oneway_client') class TestConnectionClient: @pytest.mark.asyncio async def test_00_send(self, sftp_connection_connected, sftp_factory, fixed_timestamp, tmpdir, json_rpc_login_request_encoded): sftp_factory.realpath.assert_awaited_with('/') await sftp_connection_connected.send(json_rpc_login_request_encoded) sftp_factory.put.assert_awaited_with(Path(tmpdir) / "sftp_sent/FILE201901010101000000000000", remotepath='/') @pytest.mark.asyncio async def test_01_send_data_adaptor_method(self, sftp_connection_connected, sftp_factory, fixed_timestamp, json_rpc_login_request_encoded, tmpdir): sftp_connection_connected.send_data(json_rpc_login_request_encoded) await sftp_connection_connected.wait_tasks_done() sftp_factory.put.assert_awaited_with(Path(tmpdir) / "sftp_sent/FILE201901010101000000000000", remotepath='/') @pytest.mark.connections('sftp_oneway_all') class TestSFTPProtocolFactories: @pytest.mark.asyncio async def test_00_connection_lifecycle(self, protocol_factory_started, connection, sftp_conn, sftp_factory): new_connection = protocol_factory_started() assert protocol_factory_started.logger == new_connection.logger assert new_connection == connection assert protocol_factory_started.is_owner(new_connection) new_connection.connection_made(sftp_conn) sftp_conn._owner = new_connection await asyncio.wait_for(protocol_factory_started.wait_num_connected(1), timeout=1) await asyncio.wait_for(new_connection.wait_connected(), timeout=1) sftp_conn.close() await asyncio.wait_for(protocol_factory_started.close(), timeout=2) await asyncio.wait_for(new_connection.wait_closed(), timeout=1) @pytest.mark.asyncio async def test_01_pickle_protocol_factory(self, protocol_factory): data = pickle.dumps(protocol_factory) factory = pickle.loads(data) assert factory == protocol_factory await protocol_factory.close()
def get_yes_no(text: str="") -> bool: answer = get_limited_options(["y", "n"], text) return answer == "y" def get_limited_options(limited_options, text=""): limited_options = list(map(str, list(limited_options))) answer = input(f"{text} ({"/".join(limited_options)})") while answer.lower() not in limited_options: print("Wrong input. Please enter one of: {{', '.join(limited_options)}} (case insensitive)") answer = input(f"{text}") return answer.lower()
def get_yes_no(text: str="") -> bool: answer = get_limited_options(["y", "n"], text) return answer == "y" def get_limited_options(limited_options, text=""): limited_options = list(map(str, list(limited_options))) answer = input(f"{text} ({'/'.join(limited_options)})") while answer.lower() not in limited_options: print("Wrong input. Please enter one of: {{', '.join(limited_options)}} (case insensitive)") answer = input(f"{text}") return answer.lower()
""" Prediction Controller """ __docformat__ = "numpy" import argparse from typing import List from datetime import datetime, timedelta import pandas as pd import numpy as np from prompt_toolkit.completion import NestedCompleter from gamestonk_terminal.parent_classes import BaseController from gamestonk_terminal import feature_flags as gtff from gamestonk_terminal.helper_funcs import ( parse_known_args_and_warn, check_positive, valid_date, get_next_stock_market_days, EXPORT_ONLY_FIGURES_ALLOWED, ) from gamestonk_terminal.menu import session from gamestonk_terminal.common.prediction_techniques import ( arima_view, arima_model, ets_model, mc_model, ets_view, knn_view, neural_networks_view, regression_view, pred_helper, mc_view, ) from gamestonk_terminal.stocks import stocks_helper class PredictionTechniquesController(BaseController): """Prediction Techniques Controller class""" CHOICES_COMMANDS = [ "load", "pick", "ets", "knn", "regression", "arima", "mlp", "rnn", "lstm", "conv1d", "mc", ] def __init__( self, ticker: str, start: datetime, interval: str, stock: pd.DataFrame, queue: List[str] = None, ): """Constructor""" super().__init__("/etf/pred/", queue) stock["Returns"] = stock["Adj Close"].pct_change() stock["LogRet"] = np.log(stock["Adj Close"]) - np.log( stock["Adj Close"].shift(1) ) stock = stock.rename(columns={"Adj Close": "AdjClose"}) stock = stock.dropna() self.stock = stock self.ticker = ticker self.start = start self.interval = interval self.target = "AdjClose" if session and gtff.USE_PROMPT_TOOLKIT: choices: dict = {c: {} for c in self.controller_choices} choices["load"]["-r"] = {c: {} for c in stocks_helper.INTERVALS} choices["pick"] = {c: {} for c in self.stock.columns} choices["ets"]["-t"] = {c: {} for c in ets_model.TRENDS} choices["ets"]["-s"] = {c: {} for c in ets_model.SEASONS} choices["arima"]["-i"] = {c: {} for c in arima_model.ICS} choices["mc"]["--dist"] = {c: {} for c in mc_model.DISTRIBUTIONS} self.completer = NestedCompleter.from_nested_dict(choices) def print_help(self): """Print help""" s_intraday = (f"Intraday {self.interval}", "Daily")[self.interval == "1440min"] if self.start: stock_info = f"{s_intraday} Stock: {self.ticker} (from {self.start.strftime("%Y-%m-%d")})" else: stock_info = "{s_intraday} Stock: {self.ticker}" help_string = f""" Prediction Techniques Menu: load load new ticker pick pick new target variable Ticker Loaded: {stock_info} Target Column: {self.target} Models: ets exponential smoothing (e.g. Holt-Winters) knn k-Nearest Neighbors regression polynomial regression arima autoregressive integrated moving average mlp MultiLayer Perceptron rnn Recurrent Neural Network lstm Long-Short Term Memory conv1d 1D Convolutional Neural Network mc Monte-Carlo simulations """ print(help_string) def custom_reset(self): """Class specific component of reset command""" if self.ticker: return ["etf", f"load {self.ticker}", "pred"] return [] def call_load(self, other_args: List[str]): """Process load command""" parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="load", description="Load stock ticker to perform analysis on. When the data source is 'yf', an Indian ticker can be" " loaded by using '.NS' at the end, e.g. 'SBIN.NS'. See available market in" " https://help.yahoo.com/kb/exchanges-data-providers-yahoo-finance-sln2310.html.", ) parser.add_argument( "-t", "--ticker", action="store", dest="ticker", required="-h" not in other_args, help="Stock ticker", ) parser.add_argument( "-s", "--start", type=valid_date, default=(datetime.now() - timedelta(days=366)).strftime("%Y-%m-%d"), dest="start", help="The starting date (format YYYY-MM-DD) of the stock", ) parser.add_argument( "-e", "--end", type=valid_date, default=datetime.now().strftime("%Y-%m-%d"), dest="end", help="The ending date (format YYYY-MM-DD) of the stock", ) parser.add_argument( "-i", "--interval", action="store", dest="interval", type=int, default=1440, choices=stocks_helper.INTERVALS, help="Intraday stock minutes", ) parser.add_argument( "--source", action="store", dest="source", choices=stocks_helper.SOURCES, default="yf", help="Source of historical data.", ) parser.add_argument( "-p", "--prepost", action="store_true", default=False, dest="prepost", help="Pre/After market hours. Only works for 'yf' source, and intraday data", ) # For the case where a user uses: 'load BB' if other_args and "-t" not in other_args and "-h" not in other_args: other_args.insert(0, "-t") ns_parser = parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_FIGURES_ALLOWED ) if ns_parser: df_stock_candidate = stocks_helper.load( ns_parser.ticker, ns_parser.start, ns_parser.interval, ns_parser.end, ns_parser.prepost, ns_parser.source, ) if not df_stock_candidate.empty: self.stock = df_stock_candidate if "." in ns_parser.ticker: self.ticker = ns_parser.ticker.upper().split(".")[0] else: self.ticker = ns_parser.ticker.upper() self.start = ns_parser.start self.interval = str(ns_parser.interval) + "min" self.stock["Returns"] = self.stock["Adj Close"].pct_change() self.stock["LogRet"] = np.log(self.stock["Adj Close"]) - np.log( self.stock["Adj Close"].shift(1) ) self.stock = self.stock.rename(columns={"Adj Close": "AdjClose"}) self.stock = self.stock.dropna() def call_pick(self, other_args: List[str]): """Process pick command""" parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=False, prog="pick", description=""" Change target variable """, ) parser.add_argument( "-t", "--target", dest="target", choices=list(self.stock.columns), help="Select variable to analyze", ) if other_args and "-t" not in other_args and "-h" not in other_args: other_args.insert(0, "-t") ns_parser = parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_FIGURES_ALLOWED ) if ns_parser: self.target = ns_parser.target print("") def call_ets(self, other_args: List[str]): """Process ets command""" parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="ets", description=""" Exponential Smoothing, see https://otexts.com/fpp2/taxonomy.html Trend='N', Seasonal='N': Simple Exponential Smoothing Trend='N', Seasonal='A': Exponential Smoothing Trend='N', Seasonal='M': Exponential Smoothing Trend='A', Seasonal='N': Holt’s linear method Trend='A', Seasonal='A': Additive Holt-Winters’ method Trend='A', Seasonal='M': Multiplicative Holt-Winters’ method Trend='Ad', Seasonal='N': Additive damped trend method Trend='Ad', Seasonal='A': Exponential Smoothing Trend='Ad', Seasonal='M': Holt-Winters’ damped method Trend component: N: None, A: Additive, Ad: Additive Damped Seasonality component: N: None, A: Additive, M: Multiplicative """, ) parser.add_argument( "-d", "--days", action="store", dest="n_days", type=check_positive, default=5, help="prediction days.", ) parser.add_argument( "-t", "--trend", action="store", dest="trend", choices=ets_model.TRENDS, default="N", help="Trend component: N: None, A: Additive, Ad: Additive Damped.", ) parser.add_argument( "-s", "--seasonal", action="store", dest="seasonal", choices=ets_model.SEASONS, default="N", help="Seasonality component: N: None, A: Additive, M: Multiplicative.", ) parser.add_argument( "-p", "--periods", action="store", dest="seasonal_periods", type=check_positive, default=5, help="Seasonal periods.", ) parser.add_argument( "-e", "--end", action="store", type=valid_date, dest="s_end_date", default=None, help="The end date (format YYYY-MM-DD) to select - Backtesting", ) ns_parser = parse_known_args_and_warn( parser, other_args, export_allowed=EXPORT_ONLY_FIGURES_ALLOWED ) if ns_parser: if ns_parser.s_end_date: if ns_parser.s_end_date < self.stock.index[0]: print( "Backtesting not allowed, since End Date is older than Start Date of historical data\n" ) if ns_parser.s_end_date < get_next_stock_market_days( last_stock_day=self.stock.index[0], n_next_days=5 + ns_parser.n_days, )[-1]: print( "Backtesting not allowed, since End Date is too close to Start Date to train model\n" ) ets_view.display_exponential_smoothing( ticker=self.ticker, values=self.stock[self.target], n_predict=ns_parser.n_days, trend=ns_parser.trend, seasonal=ns_parser.seasonal, seasonal_periods=ns_parser.seasonal_periods, s_end_date=ns_parser.s_end_date, export=ns_parser.export, ) def call_knn(self, other_args: List[str]): """Process knn command""" parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="knn", description=""" K nearest neighbors is a simple algorithm that stores all available cases and predict the numerical target based on a similarity measure (e.g. distance functions). """, ) parser.add_argument( "-i", "--input", action="store", dest="n_inputs", type=check_positive, default=40, help="number of days to use as input for prediction.", ) parser.add_argument( "-d", "--days", action="store", dest="n_days", type=check_positive, default=5, help="prediction days.", ) parser.add_argument( "-j", "--jumps", action="store", dest="n_jumps", type=check_positive, default=1, help="number of jumps in training data.", ) parser.add_argument( "-n", "--neighbors", action="store", dest="n_neighbors", type=check_positive, default=20, help="number of neighbors to use on the algorithm.", ) parser.add_argument( "-e", "--end", action="store", type=valid_date, dest="s_end_date", default=None, help="The end date (format YYYY-MM-DD) to select for testing", ) parser.add_argument( "-t", "--test_size", default=0.2, dest="valid_split", type=float, help="Percentage of data to validate in sample", ) parser.add_argument( "--no_shuffle", action="store_false", dest="no_shuffle", default=True, help="Specify if shuffling validation inputs.", ) ns_parser = parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_FIGURES_ALLOWED ) if ns_parser: knn_view.display_k_nearest_neighbors( ticker=self.ticker, data=self.stock[self.target], n_neighbors=ns_parser.n_neighbors, n_input_days=ns_parser.n_inputs, n_predict_days=ns_parser.n_days, test_size=ns_parser.valid_split, end_date=ns_parser.s_end_date, no_shuffle=ns_parser.no_shuffle, ) def call_regression(self, other_args: List[str]): """Process linear command""" parser = argparse.ArgumentParser( add_help=False, prog="regression", description=""" Regression attempts to model the relationship between two variables by fitting a linear/quadratic/cubic/other equation to observed data. One variable is considered to be an explanatory variable, and the other is considered to be a dependent variable. """, ) parser.add_argument( "-i", "--input", action="store", dest="n_inputs", type=check_positive, default=40, help="number of days to use for prediction.", ) parser.add_argument( "-d", "--days", action="store", dest="n_days", type=check_positive, default=5, help="prediction days.", ) parser.add_argument( "-j", "--jumps", action="store", dest="n_jumps", type=check_positive, default=1, help="number of jumps in training data.", ) parser.add_argument( "-e", "--end", action="store", type=valid_date, dest="s_end_date", default=None, help="The end date (format YYYY-MM-DD) to select - Backtesting", ) parser.add_argument( "-p", "--polynomial", action="store", dest="n_polynomial", type=check_positive, default=1, help="polynomial associated with regression.", ) if ( other_args and "-h" not in other_args and ("-p" not in other_args or "--polynomial" not in other_args) ): other_args.insert(0, "-p") ns_parser = parse_known_args_and_warn( parser, other_args, export_allowed=EXPORT_ONLY_FIGURES_ALLOWED ) if ns_parser: # BACKTESTING CHECK if ns_parser.s_end_date: if ns_parser.s_end_date < self.stock.index[0]: print( "Backtesting not allowed, since End Date is older than Start Date of historical data\n" ) if ns_parser.s_end_date < get_next_stock_market_days( last_stock_day=self.stock.index[0], n_next_days=5 + ns_parser.n_days, )[-1]: print( "Backtesting not allowed, since End Date is too close to Start Date to train model\n" ) regression_view.display_regression( dataset=self.ticker, values=self.stock[self.target], poly_order=ns_parser.n_polynomial, n_input=ns_parser.n_inputs, n_predict=ns_parser.n_days, n_jumps=ns_parser.n_jumps, s_end_date=ns_parser.s_end_date, export=ns_parser.export, ) def call_arima(self, other_args: List[str]): """Process arima command""" parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="arima", description=""" In statistics and econometrics, and in particular in time series analysis, an autoregressive integrated moving average (ARIMA) model is a generalization of an autoregressive moving average (ARMA) model. Both of these models are fitted to time series data either to better understand the data or to predict future points in the series (forecasting). ARIMA(p,d,q) where parameters p, d, and q are non-negative integers, p is the order (number of time lags) of the autoregressive model, d is the degree of differencing (the number of times the data have had past values subtracted), and q is the order of the moving-average model. """, ) parser.add_argument( "-d", "--days", action="store", dest="n_days", type=check_positive, default=5, help="prediction days.", ) parser.add_argument( "-i", "--ic", action="store", dest="s_ic", type=str, default="aic", choices=arima_model.ICS, help="information criteria.", ) parser.add_argument( "-s", "--seasonal", action="store_true", default=False, dest="b_seasonal", help="Use weekly seasonal data.", ) parser.add_argument( "-o", "--order", action="store", dest="s_order", default="", type=str, help="arima model order (p,d,q) in format: p,d,q.", ) parser.add_argument( "-r", "--results", action="store_true", dest="b_results", default=False, help="results about ARIMA summary flag.", ) parser.add_argument( "-e", "--end", action="store", type=valid_date, dest="s_end_date", default=None, help="The end date (format YYYY-MM-DD) to select - Backtesting", ) ns_parser = parse_known_args_and_warn( parser, other_args, export_allowed=EXPORT_ONLY_FIGURES_ALLOWED ) if ns_parser: # BACKTESTING CHECK if ns_parser.s_end_date: if ns_parser.s_end_date < self.stock.index[0]: print( "Backtesting not allowed, since End Date is older than Start Date of historical data\n" ) if ns_parser.s_end_date < get_next_stock_market_days( last_stock_day=self.stock.index[0], n_next_days=5 + ns_parser.n_days, )[-1]: print( "Backtesting not allowed, since End Date is too close to Start Date to train model\n" ) arima_view.display_arima( dataset=self.ticker, values=self.stock[self.target], arima_order=ns_parser.s_order, n_predict=ns_parser.n_days, seasonal=ns_parser.b_seasonal, ic=ns_parser.s_ic, results=ns_parser.b_results, s_end_date=ns_parser.s_end_date, export=ns_parser.export, ) def call_mlp(self, other_args: List[str]): """Process mlp command""" try: ns_parser = pred_helper.parse_args( prog="mlp", description="""Multi-Layered-Perceptron. """, other_args=other_args, ) if ns_parser: neural_networks_view.display_mlp( dataset=self.ticker, data=self.stock[self.target], n_input_days=ns_parser.n_inputs, n_predict_days=ns_parser.n_days, learning_rate=ns_parser.lr, epochs=ns_parser.n_epochs, batch_size=ns_parser.n_batch_size, test_size=ns_parser.valid_split, n_loops=ns_parser.n_loops, no_shuffle=ns_parser.no_shuffle, ) except Exception as e: print(e, "\n") finally: pred_helper.restore_env() def call_rnn(self, other_args: List[str]): """Process rnn command""" try: ns_parser = pred_helper.parse_args( prog="rnn", description="""Recurrent Neural Network. """, other_args=other_args, ) if ns_parser: neural_networks_view.display_rnn( dataset=self.ticker, data=self.stock[self.target], n_input_days=ns_parser.n_inputs, n_predict_days=ns_parser.n_days, learning_rate=ns_parser.lr, epochs=ns_parser.n_epochs, batch_size=ns_parser.n_batch_size, test_size=ns_parser.valid_split, n_loops=ns_parser.n_loops, no_shuffle=ns_parser.no_shuffle, ) except Exception as e: print(e, "\n") finally: pred_helper.restore_env() def call_lstm(self, other_args: List[str]): """Process lstm command""" try: ns_parser = pred_helper.parse_args( prog="lstm", description="""Long-Short Term Memory. """, other_args=other_args, ) if ns_parser: neural_networks_view.display_lstm( dataset=self.ticker, data=self.stock[self.target], n_input_days=ns_parser.n_inputs, n_predict_days=ns_parser.n_days, learning_rate=ns_parser.lr, epochs=ns_parser.n_epochs, batch_size=ns_parser.n_batch_size, test_size=ns_parser.valid_split, n_loops=ns_parser.n_loops, no_shuffle=ns_parser.no_shuffle, ) except Exception as e: print(e, "\n") finally: pred_helper.restore_env() def call_conv1d(self, other_args: List[str]): """Process conv1d command""" try: ns_parser = pred_helper.parse_args( prog="conv1d", description="""1D CNN.""", other_args=other_args, ) if ns_parser: neural_networks_view.display_conv1d( dataset=self.ticker, data=self.stock[self.target], n_input_days=ns_parser.n_inputs, n_predict_days=ns_parser.n_days, learning_rate=ns_parser.lr, epochs=ns_parser.n_epochs, batch_size=ns_parser.n_batch_size, test_size=ns_parser.valid_split, n_loops=ns_parser.n_loops, no_shuffle=ns_parser.no_shuffle, ) except Exception as e: print(e, "\n") finally: pred_helper.restore_env() def call_mc(self, other_args: List[str]): """Process mc command""" parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=False, prog="mc", description=""" Perform Monte Carlo forecasting """, ) parser.add_argument( "-d", "--days", help="Days to predict", dest="n_days", type=check_positive, default=30, ) parser.add_argument( "-n", "--num", help="Number of simulations to perform", dest="n_sims", default=100, ) parser.add_argument( "--dist", choices=mc_model.DISTRIBUTIONS, default="lognormal", dest="dist", help="Whether to model returns or log returns", ) ns_parser = parse_known_args_and_warn( parser, other_args, export_allowed=EXPORT_ONLY_FIGURES_ALLOWED ) if ns_parser: if self.target != "AdjClose": print("MC Prediction designed for AdjClose prices\n") mc_view.display_mc_forecast( data=self.stock[self.target], n_future=ns_parser.n_days, n_sims=ns_parser.n_sims, use_log=ns_parser.dist == "lognormal", export=ns_parser.export, )
""" Prediction Controller """ __docformat__ = "numpy" import argparse from typing import List from datetime import datetime, timedelta import pandas as pd import numpy as np from prompt_toolkit.completion import NestedCompleter from gamestonk_terminal.parent_classes import BaseController from gamestonk_terminal import feature_flags as gtff from gamestonk_terminal.helper_funcs import ( parse_known_args_and_warn, check_positive, valid_date, get_next_stock_market_days, EXPORT_ONLY_FIGURES_ALLOWED, ) from gamestonk_terminal.menu import session from gamestonk_terminal.common.prediction_techniques import ( arima_view, arima_model, ets_model, mc_model, ets_view, knn_view, neural_networks_view, regression_view, pred_helper, mc_view, ) from gamestonk_terminal.stocks import stocks_helper class PredictionTechniquesController(BaseController): """Prediction Techniques Controller class""" CHOICES_COMMANDS = [ "load", "pick", "ets", "knn", "regression", "arima", "mlp", "rnn", "lstm", "conv1d", "mc", ] def __init__( self, ticker: str, start: datetime, interval: str, stock: pd.DataFrame, queue: List[str] = None, ): """Constructor""" super().__init__("/etf/pred/", queue) stock["Returns"] = stock["Adj Close"].pct_change() stock["LogRet"] = np.log(stock["Adj Close"]) - np.log( stock["Adj Close"].shift(1) ) stock = stock.rename(columns={"Adj Close": "AdjClose"}) stock = stock.dropna() self.stock = stock self.ticker = ticker self.start = start self.interval = interval self.target = "AdjClose" if session and gtff.USE_PROMPT_TOOLKIT: choices: dict = {c: {} for c in self.controller_choices} choices["load"]["-r"] = {c: {} for c in stocks_helper.INTERVALS} choices["pick"] = {c: {} for c in self.stock.columns} choices["ets"]["-t"] = {c: {} for c in ets_model.TRENDS} choices["ets"]["-s"] = {c: {} for c in ets_model.SEASONS} choices["arima"]["-i"] = {c: {} for c in arima_model.ICS} choices["mc"]["--dist"] = {c: {} for c in mc_model.DISTRIBUTIONS} self.completer = NestedCompleter.from_nested_dict(choices) def print_help(self): """Print help""" s_intraday = (f"Intraday {self.interval}", "Daily")[self.interval == "1440min"] if self.start: stock_info = f"{s_intraday} Stock: {self.ticker} (from {self.start.strftime('%Y-%m-%d')})" else: stock_info = "{s_intraday} Stock: {self.ticker}" help_string = f""" Prediction Techniques Menu: load load new ticker pick pick new target variable Ticker Loaded: {stock_info} Target Column: {self.target} Models: ets exponential smoothing (e.g. Holt-Winters) knn k-Nearest Neighbors regression polynomial regression arima autoregressive integrated moving average mlp MultiLayer Perceptron rnn Recurrent Neural Network lstm Long-Short Term Memory conv1d 1D Convolutional Neural Network mc Monte-Carlo simulations """ print(help_string) def custom_reset(self): """Class specific component of reset command""" if self.ticker: return ["etf", f"load {self.ticker}", "pred"] return [] def call_load(self, other_args: List[str]): """Process load command""" parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="load", description="Load stock ticker to perform analysis on. When the data source is 'yf', an Indian ticker can be" " loaded by using '.NS' at the end, e.g. 'SBIN.NS'. See available market in" " https://help.yahoo.com/kb/exchanges-data-providers-yahoo-finance-sln2310.html.", ) parser.add_argument( "-t", "--ticker", action="store", dest="ticker", required="-h" not in other_args, help="Stock ticker", ) parser.add_argument( "-s", "--start", type=valid_date, default=(datetime.now() - timedelta(days=366)).strftime("%Y-%m-%d"), dest="start", help="The starting date (format YYYY-MM-DD) of the stock", ) parser.add_argument( "-e", "--end", type=valid_date, default=datetime.now().strftime("%Y-%m-%d"), dest="end", help="The ending date (format YYYY-MM-DD) of the stock", ) parser.add_argument( "-i", "--interval", action="store", dest="interval", type=int, default=1440, choices=stocks_helper.INTERVALS, help="Intraday stock minutes", ) parser.add_argument( "--source", action="store", dest="source", choices=stocks_helper.SOURCES, default="yf", help="Source of historical data.", ) parser.add_argument( "-p", "--prepost", action="store_true", default=False, dest="prepost", help="Pre/After market hours. Only works for 'yf' source, and intraday data", ) # For the case where a user uses: 'load BB' if other_args and "-t" not in other_args and "-h" not in other_args: other_args.insert(0, "-t") ns_parser = parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_FIGURES_ALLOWED ) if ns_parser: df_stock_candidate = stocks_helper.load( ns_parser.ticker, ns_parser.start, ns_parser.interval, ns_parser.end, ns_parser.prepost, ns_parser.source, ) if not df_stock_candidate.empty: self.stock = df_stock_candidate if "." in ns_parser.ticker: self.ticker = ns_parser.ticker.upper().split(".")[0] else: self.ticker = ns_parser.ticker.upper() self.start = ns_parser.start self.interval = str(ns_parser.interval) + "min" self.stock["Returns"] = self.stock["Adj Close"].pct_change() self.stock["LogRet"] = np.log(self.stock["Adj Close"]) - np.log( self.stock["Adj Close"].shift(1) ) self.stock = self.stock.rename(columns={"Adj Close": "AdjClose"}) self.stock = self.stock.dropna() def call_pick(self, other_args: List[str]): """Process pick command""" parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=False, prog="pick", description=""" Change target variable """, ) parser.add_argument( "-t", "--target", dest="target", choices=list(self.stock.columns), help="Select variable to analyze", ) if other_args and "-t" not in other_args and "-h" not in other_args: other_args.insert(0, "-t") ns_parser = parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_FIGURES_ALLOWED ) if ns_parser: self.target = ns_parser.target print("") def call_ets(self, other_args: List[str]): """Process ets command""" parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="ets", description=""" Exponential Smoothing, see https://otexts.com/fpp2/taxonomy.html Trend='N', Seasonal='N': Simple Exponential Smoothing Trend='N', Seasonal='A': Exponential Smoothing Trend='N', Seasonal='M': Exponential Smoothing Trend='A', Seasonal='N': Holt’s linear method Trend='A', Seasonal='A': Additive Holt-Winters’ method Trend='A', Seasonal='M': Multiplicative Holt-Winters’ method Trend='Ad', Seasonal='N': Additive damped trend method Trend='Ad', Seasonal='A': Exponential Smoothing Trend='Ad', Seasonal='M': Holt-Winters’ damped method Trend component: N: None, A: Additive, Ad: Additive Damped Seasonality component: N: None, A: Additive, M: Multiplicative """, ) parser.add_argument( "-d", "--days", action="store", dest="n_days", type=check_positive, default=5, help="prediction days.", ) parser.add_argument( "-t", "--trend", action="store", dest="trend", choices=ets_model.TRENDS, default="N", help="Trend component: N: None, A: Additive, Ad: Additive Damped.", ) parser.add_argument( "-s", "--seasonal", action="store", dest="seasonal", choices=ets_model.SEASONS, default="N", help="Seasonality component: N: None, A: Additive, M: Multiplicative.", ) parser.add_argument( "-p", "--periods", action="store", dest="seasonal_periods", type=check_positive, default=5, help="Seasonal periods.", ) parser.add_argument( "-e", "--end", action="store", type=valid_date, dest="s_end_date", default=None, help="The end date (format YYYY-MM-DD) to select - Backtesting", ) ns_parser = parse_known_args_and_warn( parser, other_args, export_allowed=EXPORT_ONLY_FIGURES_ALLOWED ) if ns_parser: if ns_parser.s_end_date: if ns_parser.s_end_date < self.stock.index[0]: print( "Backtesting not allowed, since End Date is older than Start Date of historical data\n" ) if ns_parser.s_end_date < get_next_stock_market_days( last_stock_day=self.stock.index[0], n_next_days=5 + ns_parser.n_days, )[-1]: print( "Backtesting not allowed, since End Date is too close to Start Date to train model\n" ) ets_view.display_exponential_smoothing( ticker=self.ticker, values=self.stock[self.target], n_predict=ns_parser.n_days, trend=ns_parser.trend, seasonal=ns_parser.seasonal, seasonal_periods=ns_parser.seasonal_periods, s_end_date=ns_parser.s_end_date, export=ns_parser.export, ) def call_knn(self, other_args: List[str]): """Process knn command""" parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="knn", description=""" K nearest neighbors is a simple algorithm that stores all available cases and predict the numerical target based on a similarity measure (e.g. distance functions). """, ) parser.add_argument( "-i", "--input", action="store", dest="n_inputs", type=check_positive, default=40, help="number of days to use as input for prediction.", ) parser.add_argument( "-d", "--days", action="store", dest="n_days", type=check_positive, default=5, help="prediction days.", ) parser.add_argument( "-j", "--jumps", action="store", dest="n_jumps", type=check_positive, default=1, help="number of jumps in training data.", ) parser.add_argument( "-n", "--neighbors", action="store", dest="n_neighbors", type=check_positive, default=20, help="number of neighbors to use on the algorithm.", ) parser.add_argument( "-e", "--end", action="store", type=valid_date, dest="s_end_date", default=None, help="The end date (format YYYY-MM-DD) to select for testing", ) parser.add_argument( "-t", "--test_size", default=0.2, dest="valid_split", type=float, help="Percentage of data to validate in sample", ) parser.add_argument( "--no_shuffle", action="store_false", dest="no_shuffle", default=True, help="Specify if shuffling validation inputs.", ) ns_parser = parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_FIGURES_ALLOWED ) if ns_parser: knn_view.display_k_nearest_neighbors( ticker=self.ticker, data=self.stock[self.target], n_neighbors=ns_parser.n_neighbors, n_input_days=ns_parser.n_inputs, n_predict_days=ns_parser.n_days, test_size=ns_parser.valid_split, end_date=ns_parser.s_end_date, no_shuffle=ns_parser.no_shuffle, ) def call_regression(self, other_args: List[str]): """Process linear command""" parser = argparse.ArgumentParser( add_help=False, prog="regression", description=""" Regression attempts to model the relationship between two variables by fitting a linear/quadratic/cubic/other equation to observed data. One variable is considered to be an explanatory variable, and the other is considered to be a dependent variable. """, ) parser.add_argument( "-i", "--input", action="store", dest="n_inputs", type=check_positive, default=40, help="number of days to use for prediction.", ) parser.add_argument( "-d", "--days", action="store", dest="n_days", type=check_positive, default=5, help="prediction days.", ) parser.add_argument( "-j", "--jumps", action="store", dest="n_jumps", type=check_positive, default=1, help="number of jumps in training data.", ) parser.add_argument( "-e", "--end", action="store", type=valid_date, dest="s_end_date", default=None, help="The end date (format YYYY-MM-DD) to select - Backtesting", ) parser.add_argument( "-p", "--polynomial", action="store", dest="n_polynomial", type=check_positive, default=1, help="polynomial associated with regression.", ) if ( other_args and "-h" not in other_args and ("-p" not in other_args or "--polynomial" not in other_args) ): other_args.insert(0, "-p") ns_parser = parse_known_args_and_warn( parser, other_args, export_allowed=EXPORT_ONLY_FIGURES_ALLOWED ) if ns_parser: # BACKTESTING CHECK if ns_parser.s_end_date: if ns_parser.s_end_date < self.stock.index[0]: print( "Backtesting not allowed, since End Date is older than Start Date of historical data\n" ) if ns_parser.s_end_date < get_next_stock_market_days( last_stock_day=self.stock.index[0], n_next_days=5 + ns_parser.n_days, )[-1]: print( "Backtesting not allowed, since End Date is too close to Start Date to train model\n" ) regression_view.display_regression( dataset=self.ticker, values=self.stock[self.target], poly_order=ns_parser.n_polynomial, n_input=ns_parser.n_inputs, n_predict=ns_parser.n_days, n_jumps=ns_parser.n_jumps, s_end_date=ns_parser.s_end_date, export=ns_parser.export, ) def call_arima(self, other_args: List[str]): """Process arima command""" parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="arima", description=""" In statistics and econometrics, and in particular in time series analysis, an autoregressive integrated moving average (ARIMA) model is a generalization of an autoregressive moving average (ARMA) model. Both of these models are fitted to time series data either to better understand the data or to predict future points in the series (forecasting). ARIMA(p,d,q) where parameters p, d, and q are non-negative integers, p is the order (number of time lags) of the autoregressive model, d is the degree of differencing (the number of times the data have had past values subtracted), and q is the order of the moving-average model. """, ) parser.add_argument( "-d", "--days", action="store", dest="n_days", type=check_positive, default=5, help="prediction days.", ) parser.add_argument( "-i", "--ic", action="store", dest="s_ic", type=str, default="aic", choices=arima_model.ICS, help="information criteria.", ) parser.add_argument( "-s", "--seasonal", action="store_true", default=False, dest="b_seasonal", help="Use weekly seasonal data.", ) parser.add_argument( "-o", "--order", action="store", dest="s_order", default="", type=str, help="arima model order (p,d,q) in format: p,d,q.", ) parser.add_argument( "-r", "--results", action="store_true", dest="b_results", default=False, help="results about ARIMA summary flag.", ) parser.add_argument( "-e", "--end", action="store", type=valid_date, dest="s_end_date", default=None, help="The end date (format YYYY-MM-DD) to select - Backtesting", ) ns_parser = parse_known_args_and_warn( parser, other_args, export_allowed=EXPORT_ONLY_FIGURES_ALLOWED ) if ns_parser: # BACKTESTING CHECK if ns_parser.s_end_date: if ns_parser.s_end_date < self.stock.index[0]: print( "Backtesting not allowed, since End Date is older than Start Date of historical data\n" ) if ns_parser.s_end_date < get_next_stock_market_days( last_stock_day=self.stock.index[0], n_next_days=5 + ns_parser.n_days, )[-1]: print( "Backtesting not allowed, since End Date is too close to Start Date to train model\n" ) arima_view.display_arima( dataset=self.ticker, values=self.stock[self.target], arima_order=ns_parser.s_order, n_predict=ns_parser.n_days, seasonal=ns_parser.b_seasonal, ic=ns_parser.s_ic, results=ns_parser.b_results, s_end_date=ns_parser.s_end_date, export=ns_parser.export, ) def call_mlp(self, other_args: List[str]): """Process mlp command""" try: ns_parser = pred_helper.parse_args( prog="mlp", description="""Multi-Layered-Perceptron. """, other_args=other_args, ) if ns_parser: neural_networks_view.display_mlp( dataset=self.ticker, data=self.stock[self.target], n_input_days=ns_parser.n_inputs, n_predict_days=ns_parser.n_days, learning_rate=ns_parser.lr, epochs=ns_parser.n_epochs, batch_size=ns_parser.n_batch_size, test_size=ns_parser.valid_split, n_loops=ns_parser.n_loops, no_shuffle=ns_parser.no_shuffle, ) except Exception as e: print(e, "\n") finally: pred_helper.restore_env() def call_rnn(self, other_args: List[str]): """Process rnn command""" try: ns_parser = pred_helper.parse_args( prog="rnn", description="""Recurrent Neural Network. """, other_args=other_args, ) if ns_parser: neural_networks_view.display_rnn( dataset=self.ticker, data=self.stock[self.target], n_input_days=ns_parser.n_inputs, n_predict_days=ns_parser.n_days, learning_rate=ns_parser.lr, epochs=ns_parser.n_epochs, batch_size=ns_parser.n_batch_size, test_size=ns_parser.valid_split, n_loops=ns_parser.n_loops, no_shuffle=ns_parser.no_shuffle, ) except Exception as e: print(e, "\n") finally: pred_helper.restore_env() def call_lstm(self, other_args: List[str]): """Process lstm command""" try: ns_parser = pred_helper.parse_args( prog="lstm", description="""Long-Short Term Memory. """, other_args=other_args, ) if ns_parser: neural_networks_view.display_lstm( dataset=self.ticker, data=self.stock[self.target], n_input_days=ns_parser.n_inputs, n_predict_days=ns_parser.n_days, learning_rate=ns_parser.lr, epochs=ns_parser.n_epochs, batch_size=ns_parser.n_batch_size, test_size=ns_parser.valid_split, n_loops=ns_parser.n_loops, no_shuffle=ns_parser.no_shuffle, ) except Exception as e: print(e, "\n") finally: pred_helper.restore_env() def call_conv1d(self, other_args: List[str]): """Process conv1d command""" try: ns_parser = pred_helper.parse_args( prog="conv1d", description="""1D CNN.""", other_args=other_args, ) if ns_parser: neural_networks_view.display_conv1d( dataset=self.ticker, data=self.stock[self.target], n_input_days=ns_parser.n_inputs, n_predict_days=ns_parser.n_days, learning_rate=ns_parser.lr, epochs=ns_parser.n_epochs, batch_size=ns_parser.n_batch_size, test_size=ns_parser.valid_split, n_loops=ns_parser.n_loops, no_shuffle=ns_parser.no_shuffle, ) except Exception as e: print(e, "\n") finally: pred_helper.restore_env() def call_mc(self, other_args: List[str]): """Process mc command""" parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=False, prog="mc", description=""" Perform Monte Carlo forecasting """, ) parser.add_argument( "-d", "--days", help="Days to predict", dest="n_days", type=check_positive, default=30, ) parser.add_argument( "-n", "--num", help="Number of simulations to perform", dest="n_sims", default=100, ) parser.add_argument( "--dist", choices=mc_model.DISTRIBUTIONS, default="lognormal", dest="dist", help="Whether to model returns or log returns", ) ns_parser = parse_known_args_and_warn( parser, other_args, export_allowed=EXPORT_ONLY_FIGURES_ALLOWED ) if ns_parser: if self.target != "AdjClose": print("MC Prediction designed for AdjClose prices\n") mc_view.display_mc_forecast( data=self.stock[self.target], n_future=ns_parser.n_days, n_sims=ns_parser.n_sims, use_log=ns_parser.dist == "lognormal", export=ns_parser.export, )
#!/usr/bin/env python3 from typing import Tuple, Any, Dict, Optional, List, FrozenSet, Union, Type, Callable, Set import json import sys import zlib import re import os import argparse import codecs import hashlib import enum import shutil from os.path import splitext from datetime import date, datetime, timedelta, timezone from base64 import b64decode, b64encode, urlsafe_b64decode, urlsafe_b64encode import cbor2 # type: ignore import cose.algorithms # type: ignore import cose.keys.curves # type: ignore import cose.keys.keytype # type: ignore import requests import http.client import asn1crypto.cms # type: ignore from lxml.html import fromstring as parse_html # type: ignore from dateutil.parser import isoparse as parse_datetime from jose import jwt, jws, jwk # type: ignore from base45 import b45decode # type: ignore from requests.exceptions import BaseHTTPError # type: ignore from cose.headers import KID, Algorithm # type: ignore from cose.keys import CoseKey from cose.keys.curves import CoseCurve, P256, P384, P521 from cose.keys.keyops import VerifyOp # type: ignore from cose.keys.keyparam import KpAlg, EC2KpX, EC2KpY, EC2KpCurve, KpKty, RSAKpN, RSAKpE, KpKeyOps # type: ignore from cose.keys.keytype import KtyEC2, KtyRSA from cose.messages import CoseMessage, Sign1Message # type: ignore from cose.algorithms import Ps256, Es256 from cryptography import x509 from cryptography.x509 import load_der_x509_certificate, load_pem_x509_certificate, load_der_x509_crl, load_pem_x509_crl, Name, RelativeDistinguishedName, NameAttribute, Version, Extensions, Extension from cryptography.x509.extensions import ExtensionNotFound, ExtendedKeyUsage from cryptography.x509.name import _NAMEOID_TO_NAME from cryptography.x509.oid import NameOID, ObjectIdentifier, SignatureAlgorithmOID, ExtensionOID from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat, load_pem_public_key, load_der_public_key from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey, EllipticCurvePublicNumbers, ECDSA, SECP256R1, EllipticCurve from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey, RSAPublicNumbers from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 # based on: https://github.com/ehn-digital-green-development/ehn-sign-verify-python-trivial # Digital Green Certificate Gateway API SPEC: https://eu-digital-green-certificates.github.io/dgc-gateway/#/Trust%20Lists/downloadTrustList # But where is it hosted? # Extended Key Usage OIDs: VALID_FOR_TEST = ObjectIdentifier('1.3.6.1.4.1.1847.2021.1.1') VALID_FOR_VACCINATION = ObjectIdentifier('1.3.6.1.4.1.1847.2021.1.2') VALID_FOR_RECOVERY = ObjectIdentifier('1.3.6.1.4.1.1847.2021.1.3') EXT_KEY_USAGE_NAMES: Dict[ObjectIdentifier, str] = { VALID_FOR_TEST: 'test', VALID_FOR_VACCINATION: 'vaccination', VALID_FOR_RECOVERY: 'recovery', # these are bugs in some X.509 certificates: ObjectIdentifier('1.3.6.1.4.1.0.1847.2021.1.1'): 'test', ObjectIdentifier('1.3.6.1.4.1.0.1847.2021.1.2'): 'vaccination', ObjectIdentifier('1.3.6.1.4.1.0.1847.2021.1.3'): 'recovery', } EXT_KEY_USAGE_OIDS: Dict[str, ObjectIdentifier] = { 'test': VALID_FOR_TEST, 'vaccination': VALID_FOR_VACCINATION, 'recovery': VALID_FOR_RECOVERY, } FAIL_ON_ERROR = False WARNING_AS_ERROR = False # these would need parameters: 'blake2b', 'blake2s', 'sha512-224', 'sha512-256', 'shake256', 'shake128' HASH_ALGORITHMS: Dict[str, Type[hashes.HashAlgorithm]] = {} for attr_name in dir(hashes): attr = getattr(hashes, attr_name) if isinstance(attr, type): if isinstance(attr, type) and issubclass(attr, hashes.HashAlgorithm) and attr is not hashes.HashAlgorithm: HASH_ALGORITHMS[attr.name] = attr # type: ignore EPOCH = datetime(1970, 1, 1) CertList = Dict[bytes, x509.Certificate] JS_CERT_PATTERN = re.compile(r"'({[^-']*-----BEGIN[^']*)'") ESC = re.compile(r'\\x([0-9a-fA-F][0-9a-fA-F])') CURVE_NAME_IGNORE = re.compile(r'[-_ ]') MD_CERT_PATTERN = re.compile(r'(?P<url>https://[^()\s]+)[^-:]*(?P<cert>-----BEGIN CERTIFICATE-----[^-]*-----END CERTIFICATE-----\r?\n?)') # https://tools.ietf.org/search/rfc4492#appendix-A COSE_CURVES: Dict[str, Type[CoseCurve]] = { 'secp256r1': P256, 'prime256v1': P256, 'secp384r1': P384, 'secp521r1': P521, } NIST_CURVES: Dict[str, Type[EllipticCurve]] = { 'K-163': ec.SECT163K1, 'B-163': ec.SECT163R2, 'K-233': ec.SECT233K1, 'B-233': ec.SECT233R1, 'K-283': ec.SECT283K1, 'B-283': ec.SECT283R1, 'K-409': ec.SECT409K1, 'B-409': ec.SECT409R1, 'K-571': ec.SECT571K1, 'B-571': ec.SECT571R1, 'P-192': ec.SECP192R1, 'P-224': ec.SECP224R1, 'P-256': ec.SECP256R1, 'P-384': ec.SECP384R1, 'P-521': ec.SECP521R1, } SECG_TO_NIST_CURVES: Dict[str, str] = {curve.name: name for name, curve in NIST_CURVES.items()} # type: ignore NAME_OIDS = {name: name_oid for name_oid, name in _NAMEOID_TO_NAME.items()} NAME_OIDS_COVID_PASS_VERIFIER = dict( postalCode = NameOID.POSTAL_CODE, street = NameOID.STREET_ADDRESS, organizationIdentifier = NameOID.ORGANIZATION_NAME, serialNumber = NameOID.SERIAL_NUMBER, ) NAME_OIDS_COVID_PASS_VERIFIER.update(NAME_OIDS) for name in dir(cose.keys.curves): if not name.startswith('_'): curve = getattr(cose.keys.curves, name) if curve is not CoseCurve and isinstance(curve, type) and issubclass(curve, CoseCurve) and curve.fullname != 'RESERVED': # type: ignore name = CURVE_NAME_IGNORE.sub('', curve.fullname).lower() # type: ignore COSE_CURVES[name] = curve del name, curve PREFIX = 'HC1:' PREFIX_NO = 'NO1:' # Norway CLAIM_NAMES = { 1: "Issuer", 6: "Issued At", 4: "Expires At", -260: "Health Claims", } DATETIME_CLAIMS = {6, 4} # This is an old test trust list, not current! It includes test public keys too! OLD_CERTS_URL_AT = 'https://dgc.a-sit.at/ehn/cert/listv2' OLD_SIGNS_URL_AT = 'https://dgc.a-sit.at/ehn/cert/sigv2' # Trust List used by Austrian greencheck app: CERTS_URL_AT_GREENCHECK = 'https://greencheck.gv.at/api/masterdata' CERTS_URL_AT_PROD = 'https://dgc-trust.qr.gv.at/trustlist' SIGN_URL_AT_PROD = 'https://dgc-trust.qr.gv.at/trustlistsig' CERTS_URL_AT_TEST = 'https://dgc-trusttest.qr.gv.at/trustlist' SIGN_URL_AT_TEST = 'https://dgc-trusttest.qr.gv.at/trustlistsig' # only used for root kec extraction from greencheck JavaScript: ROOT_CERT_KEY_ID_AT = b'\xe0\x9f\xf7\x8f\x02R\x06\xb6' # See: https://github.com/Federal-Ministry-of-Health-AT/green-pass-overview # These root certs are copied from some presentation slides. # TODO: Link a proper source here once it becomes available? # # TODO: keep up to date # Not Before: Jun 2 13:46:21 2021 GMT # Not After : Jul 2 13:46:21 2022 GMT ROOT_CERT_AT_PROD = b'''\ -----BEGIN CERTIFICATE----- MIIB1DCCAXmgAwIBAgIKAXnM+Z3eG2QgVzAKBggqhkjOPQQDAjBEMQswCQYDVQQG EwJBVDEPMA0GA1UECgwGQk1TR1BLMQwwCgYDVQQFEwMwMDExFjAUBgNVBAMMDUFU IERHQyBDU0NBIDEwHhcNMjEwNjAyMTM0NjIxWhcNMjIwNzAyMTM0NjIxWjBFMQsw CQYDVQQGEwJBVDEPMA0GA1UECgwGQk1TR1BLMQ8wDQYDVQQFEwYwMDEwMDExFDAS BgNVBAMMC0FUIERHQyBUTCAxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEl2tm d16CBHXwcBN0r1Uy+CmNW/b2V0BNP85y5N3JZeo/8l9ey/jIe5mol9fFcGTk9bCk 8zphVo0SreHa5aWrQKNSMFAwDgYDVR0PAQH/BAQDAgeAMB0GA1UdDgQWBBRTwp6d cDGcPUB6IwdDja/a3ncM0TAfBgNVHSMEGDAWgBQfIqwcZRYptMGYs2Nvv90Jnbt7 ezAKBggqhkjOPQQDAgNJADBGAiEAlR0x3CRuQV/zwHTd2R9WNqZMabXv5XqwHt72 qtgnjRgCIQCZHIHbCvlgg5uL8ZJQzAxLavqF2w6uUxYVrvYDj2Cqjw== -----END CERTIFICATE----- ''' ROOT_CERT_AT_TEST = b'''\ -----BEGIN CERTIFICATE----- MIIB6zCCAZGgAwIBAgIKAXmEuohlRbR2qzAKBggqhkjOPQQDAjBQMQswCQYDVQQG EwJBVDEPMA0GA1UECgwGQk1TR1BLMQowCAYDVQQLDAFRMQwwCgYDVQQFEwMwMDEx FjAUBgNVBAMMDUFUIERHQyBDU0NBIDEwHhcNMjEwNTE5MTMwNDQ3WhcNMjIwNjE5 MTMwNDQ3WjBRMQswCQYDVQQGEwJBVDEPMA0GA1UECgwGQk1TR1BLMQowCAYDVQQL DAFRMQ8wDQYDVQQFEwYwMDEwMDExFDASBgNVBAMMC0FUIERHQyBUTCAxMFkwEwYH KoZIzj0CAQYIKoZIzj0DAQcDQgAE29KpT1eIKsy5Jx3J0xpPLW+fEBF7ma9943/j 4Z+o1TytLVok9cWjsdasWCS/zcRyAh7HBL+oyMWdFBOWENCQ76NSMFAwDgYDVR0P AQH/BAQDAgeAMB0GA1UdDgQWBBQYmsL5sXTdMCyW4UtP5BMxq+UAVzAfBgNVHSME GDAWgBR2sKi2xkUpGC1Cr5ehwL0hniIsJzAKBggqhkjOPQQDAgNIADBFAiBse17k F5F43q9mRGettRDLprASrxsDO9XxUUp3ObjcWQIhALfUWnserGEPiD7Pa25tg9lj wkrqDrMdZHZ39qb+Jf/E -----END CERTIFICATE----- ''' # Trust List used by German Digitaler-Impfnachweis app: CERTS_URL_DE = 'https://de.dscg.ubirch.com/trustList/DSC/' PUBKEY_URL_DE = 'https://github.com/Digitaler-Impfnachweis/covpass-ios/raw/main/Certificates/PROD_RKI/CA/pubkey.pem' # Netherlands public keys: # (https://www.npkd.nl/csca-health.html) # https://verifier-api.<acc/test/etc>.coronacheck.nl/v4/verifier/public_keys # json containing a CMS (rfc5652) signature and a payload. Both base64 encoded. # The payload is a json dictionary of the domestic and international keys. The # later is an dictionary with the KID as a base64 encoded key and a subkjectPK # and keyUsage array with the allowed use. Typical decode is: # curl https://verifier-api.acc.coronacheck.nl/v4/verifier/public_keys |\ # jq -r .payload |\ # base64 -d |\ # jq .eu_keys CERTS_URL_NL = 'https://verifier-api.coronacheck.nl/v4/verifier/public_keys' ROOT_CERT_URL_NL = 'http://cert.pkioverheid.nl/EVRootCA.cer' # Keys from a French validation app (nothing official, just a hobby project by someone): # https://github.com/lovasoa/sanipasse/blob/master/src/assets/Digital_Green_Certificate_Signing_Keys.json # French trust list: # This requires the environment variable FR_TOKEN to be set to a bearer token that can be found in the TousAntiCovid Verif app. CERTS_URL_FR = 'https://portail.tacv.myservices-ingroupe.com/api/client/configuration/synchronisation/tacv' # Sweden (JOSE encoded): CERTS_URL_SE = 'https://dgcg.covidbevis.se/tp/trust-list' ROOT_CERT_URL_SE = 'https://dgcg.covidbevis.se/tp/cert' # See: https://github.com/DIGGSweden/dgc-trust/blob/main/specifications/trust-list.md # United Kingdom trust list: CERTS_URL_GB = 'https://covid-status.service.nhsx.nhs.uk/pubkeys/keys.json' CERTS_URL_COVID_PASS_VERIFIER = 'https://covid-pass-verifier.com/assets/certificates.json' # Norwegian trust list: CERTS_URL_NO = 'https://koronakontroll.nhn.no/v2/publickey' # Norwegian COVID-19 certificates seem to be based on the European Health Certificate but just with an 'NO1:' prefix. # https://harrisonsand.com/posts/covid-certificates/ # Switzerland: # See: https://github.com/cn-uofbasel/ch-dcc-keys ROOT_CERT_URL_CH = 'https://www.bit.admin.ch/dam/bit/en/dokumente/pki/scanning_center/swiss_governmentrootcaii.crt.download.crt/swiss_governmentrootcaii.crt' CERTS_URL_CH = 'https://www.cc.bit.admin.ch/trust/v1/keys/list' UPDATE_URL_CH = 'https://www.cc.bit.admin.ch/trust/v1/keys/updates?certFormat=ANDROID' USER_AGENT = 'Mozilla/5.0 (Windows) Firefox/90.0' # See also this thread: # https://github.com/eu-digital-green-certificates/dgc-participating-countries/issues/10 DEFAULT_NOT_VALID_BEFORE = datetime(1970, 1, 1, tzinfo=timezone.utc) DEFAULT_NOT_VALID_AFTER = datetime(9999, 12, 31, 23, 59, 59, 999999, tzinfo=timezone.utc) class HackCertificate(x509.Certificate): _public_key: Union[EllipticCurvePublicKey, RSAPublicKey] _issuer: Name _subject: Name _extensions: Extensions _not_valid_before: datetime _not_valid_after: datetime def __init__(self, public_key: Union[EllipticCurvePublicKey, RSAPublicKey], issuer: Optional[Name] = None, subject: Optional[Name] = None, not_valid_before: datetime = DEFAULT_NOT_VALID_BEFORE, not_valid_after: datetime = DEFAULT_NOT_VALID_AFTER, extensions: Optional[Extensions] = None, ): self._public_key = public_key self._issuer = issuer if issuer is not None else Name([]) self._subject = subject if subject is not None else Name([]) self._extensions = extensions if extensions is not None else Extensions([]) self._not_valid_before = not_valid_before self._not_valid_after = not_valid_after def fingerprint(self, algorithm: hashes.HashAlgorithm) -> bytes: raise NotImplementedError @property def extensions(self) -> Extensions: return self._extensions @property def signature(self) -> bytes: return b'' @property def tbs_certificate_bytes(self) -> bytes: return b'' def __eq__(self, other: object) -> bool: if not isinstance(other, HackCertificate): return False return self.__as_tuple() == other.__as_tuple() def __ne__(self, other: object) -> bool: if not isinstance(other, HackCertificate): return True return self.__as_tuple() != other.__as_tuple() def __as_tuple(self) -> Tuple[Union[EllipticCurvePublicKey, RSAPublicKey], Name, Name, Extensions]: return (self._public_key, self._issuer, self._subject, self._extensions) def __hash__(self) -> int: return hash(self.__as_tuple()) @property def serial_number(self) -> int: return 0 @property def issuer(self) -> Name: return self._issuer @property def subject(self) -> Name: return self._subject @property def version(self) -> Version: return Version.v1 @property def signature_algorithm_oid(self) -> ObjectIdentifier: raise NotImplementedError @property def signature_hash_algorithm(self): raise NotImplementedError @property def not_valid_before(self) -> datetime: return self._not_valid_before @property def not_valid_after(self) -> datetime: return self._not_valid_after def public_key(self): return self._public_key def public_bytes(self, encoding: Encoding): raise NotImplementedError("cannot serialize certificate from public-key only") #return self._public_key.public_bytes(encoding, PublicFormat.SubjectPublicKeyInfo) def json_serial(obj: Any) -> str: """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError(f"Type {type(obj)} not serializable") def load_ehc_certs(filename: str) -> CertList: with open(filename, 'rb') as stream: certs_cbor = stream.read() return load_ehc_certs_cbor(certs_cbor, filename) def load_ehc_certs_cbor(cbor_data: bytes, source: str) -> CertList: certs_data = cbor2.loads(cbor_data) certs: CertList = {} for item in certs_data['c']: try: key_id = item['i'] cert_data = item.get('c') if cert_data: cert = load_der_x509_certificate(cert_data) fingerprint = cert.fingerprint(hashes.SHA256()) if key_id != fingerprint[0:8]: raise ValueError(f'Key ID missmatch: {key_id.hex()} != {fingerprint[0:8].hex()}') else: pubkey_data = item['k'] pubkey = load_der_public_key(pubkey_data) issuer_dict = item.get('is') issuer = parse_json_relative_distinguished_name(issuer_dict) if issuer_dict is not None else Name([]) subject_dict = item.get('su') subject = parse_json_relative_distinguished_name(subject_dict) if subject_dict is not None else Name([]) nb = item.get('nb') not_valid_before = EPOCH + timedelta(seconds=nb) if nb is not None else DEFAULT_NOT_VALID_BEFORE na = item.get('na') not_valid_after = EPOCH + timedelta(seconds=na) if na is not None else DEFAULT_NOT_VALID_AFTER if isinstance(pubkey, (EllipticCurvePublicKey, RSAPublicKey)): cert = HackCertificate(pubkey, not_valid_before = not_valid_before, not_valid_after = not_valid_after, issuer = issuer, subject = subject, ) else: pubkey_type = type(pubkey) raise NotImplementedError(f'Unsupported public key type: {pubkey_type.__module__}.{pubkey_type.__name__}') if key_id in certs: print_warn(f'doubled key ID in {source} trust list, only using last: {format_key_id(key_id)}') except Exception as error: print_err(f'decoding {source} trust list entry {format_key_id(key_id)}: {error}') else: certs[key_id] = cert return certs def make_json_relative_distinguished_name(name: Name) -> Dict[str, str]: return {_NAMEOID_TO_NAME.get(attr.oid, attr.oid.dotted_string): attr.value for attr in reversed(list(name))} def parse_json_relative_distinguished_name(name_dict: Dict[str, str]) -> Name: name_attrs: List[NameAttribute] = [] for attr_type_str, attr_value in name_dict.items(): attr_type = NAME_OIDS.get(attr_type_str) or ObjectIdentifier(attr_type_str) name_attrs.append(NameAttribute(attr_type, attr_value)) return Name(name_attrs) def load_hack_certs_json(data: bytes, source: str) -> CertList: certs_dict = json.loads(data) certs: CertList = {} for key_id_hex, cert_dict in certs_dict['trustList'].items(): not_valid_before = parse_datetime(cert_dict['notValidBefore']) not_valid_after = parse_datetime(cert_dict['notValidAfter']) issuer = parse_json_relative_distinguished_name(cert_dict['issuer']) if 'issuer' in cert_dict else Name([]) subject = parse_json_relative_distinguished_name(cert_dict['subject']) if 'subject' in cert_dict else Name([]) pubkey_dict = cert_dict['publicKey'] usage = cert_dict.get('usage') exts: List[Extension] = [] if usage is not None: usage_oids: List[ObjectIdentifier] = [] for use in usage: oid = EXT_KEY_USAGE_OIDS[use] usage_oids.append(oid) exts.append(Extension(ExtensionOID.EXTENDED_KEY_USAGE, False, ExtendedKeyUsage(usage_oids))) extensions = Extensions(exts) key_id = urlsafe_b64decode_ignore_padding(pubkey_dict['kid']) key_type = pubkey_dict['kty'] if key_type == 'EC': curve_name = pubkey_dict['crv'] curve_type = NIST_CURVES.get(curve_name) if not curve_type: raise ValueError(f'unknown elliptic curve: {curve_name!r}') curve = curve_type() x_bytes = urlsafe_b64decode_ignore_padding(pubkey_dict['x']) y_bytes = urlsafe_b64decode_ignore_padding(pubkey_dict['y']) x = int.from_bytes(x_bytes, byteorder="big", signed=False) y = int.from_bytes(y_bytes, byteorder="big", signed=False) ec_pubkey = EllipticCurvePublicNumbers(x, y, curve).public_key() cert = HackCertificate(ec_pubkey, issuer, subject, not_valid_before, not_valid_after, extensions=extensions) if key_id in certs: print_warn(f'doubled key ID in {source} trust list, only using last: {format_key_id(key_id)}') certs[key_id] = cert elif key_type == 'RSA': e_bytes = urlsafe_b64decode_ignore_padding(pubkey_dict['e']) n_bytes = urlsafe_b64decode_ignore_padding(pubkey_dict['n']) e = int.from_bytes(e_bytes, byteorder="big", signed=False) n = int.from_bytes(n_bytes, byteorder="big", signed=False) rsa_pubkey = RSAPublicNumbers(e, n).public_key() cert = HackCertificate(rsa_pubkey, issuer, subject, not_valid_before, not_valid_after, extensions=extensions) if key_id in certs: print_warn(f'doubled key ID in {source} trust list, only using last: {format_key_id(key_id)}') certs[key_id] = cert else: print_err(f'decoding {source} trust list: illegal key type: {key_type!r}') return certs def print_err(msg: str) -> None: if FAIL_ON_ERROR: raise Exception(msg) else: # so that errors and normal output is correctly interleaved: sys.stdout.flush() print(f'ERROR: {msg}', file=sys.stderr) def print_warn(msg: str) -> None: if WARNING_AS_ERROR: print_err(msg) else: # so that errors and normal output is correctly interleaved: sys.stdout.flush() print(f'WARNING: {msg}', file=sys.stderr) def load_de_trust_list(data: bytes, pubkey: Optional[EllipticCurvePublicKey] = None) -> CertList: certs: CertList = {} sign_b64, body_json = data.split(b'\n', 1) sign = b64decode(sign_b64) body = json.loads(body_json) if pubkey is not None: r = int.from_bytes(sign[:len(sign)//2], byteorder="big", signed=False) s = int.from_bytes(sign[len(sign)//2:], byteorder="big", signed=False) sign_dds = encode_dss_signature(r, s) try: pubkey.verify(sign_dds, body_json, ECDSA(hashes.SHA256())) except InvalidSignature: raise ValueError(f'Invalid signature of DE trust list: {sign.hex()}') for cert in body['certificates']: try: key_id_b64 = cert['kid'] key_id = b64decode(key_id_b64) country = cert['country'] cert_type = cert['certificateType'] if cert_type != 'DSC': raise ValueError(f'unknown certificateType {cert_type!r} (country={country}, kid={key_id.hex()}') raw_data = b64decode(cert['rawData']) cert = load_der_x509_certificate(raw_data) fingerprint = cert.fingerprint(hashes.SHA256()) if key_id != fingerprint[0:8]: raise ValueError(f'Key ID missmatch: {key_id.hex()} != {fingerprint[0:8].hex()}') if key_id in certs: print_warn(f'doubled key ID in DE trust list, only using last: {format_key_id(key_id)}') except Exception as error: print_err(f'decoding DE trust list entry {format_key_id(key_id)}: {error}') else: certs[key_id] = cert return certs def download_at_greencheck_certs() -> CertList: response = requests.get(CERTS_URL_AT_GREENCHECK, headers={'User-Agent': USER_AGENT}) response.raise_for_status() certs_json = json.loads(response.content)['trustList'] certs_cbor = b64decode(certs_json['trustListContent']) certs_sig = b64decode(certs_json['trustListSignature']) sig_msg = CoseMessage.decode(certs_sig) if not isinstance(sig_msg, Sign1Message): msg_type = type(sig_msg) raise TypeError(f'AT trust list: expected signature to be a Sign1 COSE message, but is: {msg_type.__module__}.{msg_type.__name__}') root_cert_key_id = sig_msg.phdr.get(KID) or sig_msg.uhdr[KID] root_cert: Optional[x509.Certificate] = None try: root_cert = get_at_greencheck_root_cert(root_cert_key_id) except (BaseHTTPError, ValueError, KeyError) as error: print_err(f'AT trust list error (NOT VALIDATING): {error}') if root_cert: now = datetime.utcnow() if now < root_cert.not_valid_before: raise ValueError(f'AT trust list root certificate not yet valid: {now.isoformat()} < {root_cert.not_valid_before.isoformat()}') if now > root_cert.not_valid_after: raise ValueError(f'AT trust list root certificate already expired: {now.isoformat()} > {root_cert.not_valid_after.isoformat()}') sig_msg.key = cert_to_cose_key(root_cert) if not sig_msg.verify_signature(): raise ValueError(f'Invalid signature of AT trust list: {sig_msg.signature.hex()}') sig = cbor2.loads(sig_msg.payload) digest = hashlib.sha256(certs_cbor).digest() if sig[2] != digest: raise ValueError(f'Invalid hash of AT trust list. expected: {sig[2].hex()}, actual: {digest.hex()}') created_at = EPOCH + timedelta(seconds=sig[5]) # I guess? Or "not valid before"? expires_at = EPOCH + timedelta(seconds=sig[4]) if now > expires_at: raise ValueError(f'AT trust list already expired at {expires_at.isoformat()}') else: print_err(f'root certificate for AT trust list not found!') return load_ehc_certs_cbor(certs_cbor, 'AT') def download_at_certs(test: bool = False, token: Optional[str] = None) -> CertList: # TODO: update to handle tokens once required #if token is None: # token = os.getenv('AT_TOKEN') # if token is None: # raise KeyError( # 'Required environment variable AT_TOKEN for AT trust list is not set. ' # 'Information about how to get a token will follow soon.') if test: certs_url = CERTS_URL_AT_TEST sign_url = SIGN_URL_AT_TEST root_cert = get_root_cert('AT-TEST') else: certs_url = CERTS_URL_AT_PROD sign_url = SIGN_URL_AT_PROD root_cert = get_root_cert('AT') response = requests.get(certs_url, headers={'User-Agent': USER_AGENT}) #response = requests.get(certs_url, headers={ # 'User-Agent': USER_AGENT, # 'Authorization': f'Bearer {token}', #}) response.raise_for_status() certs_cbor = response.content response = requests.get(sign_url, headers={'User-Agent': USER_AGENT}) #response = requests.get(sign_url, headers={ # 'User-Agent': USER_AGENT, # 'Authorization': f'Bearer {token}', #}) response.raise_for_status() certs_sig = response.content sig_msg = CoseMessage.decode(certs_sig) if not isinstance(sig_msg, Sign1Message): msg_type = type(sig_msg) raise TypeError(f'AT trust list: expected signature to be a Sign1 COSE message, but is: {msg_type.__module__}.{msg_type.__name__}') root_cert_key_id = sig_msg.phdr.get(KID) or sig_msg.uhdr[KID] key_id = root_cert.fingerprint(hashes.SHA256())[:8] if key_id != root_cert_key_id: raise ValueError(f'AT trust list root certificate key ID missmatch. {key_id.hex()} != {root_cert_key_id.hex()}') now = datetime.utcnow() if now < root_cert.not_valid_before: raise ValueError(f'AT trust list root certificate not yet valid: {now.isoformat()} < {root_cert.not_valid_before.isoformat()}') if now > root_cert.not_valid_after: raise ValueError(f'AT trust list root certificate already expired: {now.isoformat()} > {root_cert.not_valid_after.isoformat()}') sig_msg.key = cert_to_cose_key(root_cert) if not sig_msg.verify_signature(): raise ValueError(f'Invalid signature of AT trust list: {sig_msg.signature.hex()}') sig = cbor2.loads(sig_msg.payload) digest = hashlib.sha256(certs_cbor).digest() if sig[2] != digest: raise ValueError(f'Invalid hash of AT trust list. expected: {sig[2].hex()}, actual: {digest.hex()}') created_at = EPOCH + timedelta(seconds=sig[5]) # I guess? Or "not valid before"? expires_at = EPOCH + timedelta(seconds=sig[4]) if now > expires_at: raise ValueError(f'AT trust list already expired at {expires_at.isoformat()}') return load_ehc_certs_cbor(certs_cbor, 'AT') def download_de_certs() -> CertList: response = requests.get(CERTS_URL_DE, headers={'User-Agent': USER_AGENT}) response.raise_for_status() certs_signed_json = response.content pubkey: Optional[EllipticCurvePublicKey] = None try: pubkey = get_root_cert('DE').public_key() # type: ignore except (BaseHTTPError, ValueError) as error: print_err(f'DE trust list error (NOT VALIDATING): {error}') return load_de_trust_list(certs_signed_json, pubkey) def download_se_certs() -> CertList: certs: CertList = {} root_cert: Optional[x509.Certificate] = None try: root_cert = get_root_cert('SE') except (BaseHTTPError, ValueError) as error: print_err(f'SE trust list error (NOT VALIDATING): {error}') response = requests.get(CERTS_URL_SE, headers={'User-Agent': USER_AGENT}) response.raise_for_status() if root_cert is None: token = jwt.get_unverified_claims(response.content.decode(response.encoding or 'UTF-8')) else: token = load_jwt(response.content, root_cert, {'verify_aud': False}) for country, country_keys in token['dsc_trust_list'].items(): for entry in country_keys['keys']: key_id = b64decode(entry['kid']) for key_data in entry['x5c']: try: cert = load_der_x509_certificate(b64decode_ignore_padding(key_data)) fingerprint = cert.fingerprint(hashes.SHA256()) if key_id != fingerprint[0:8]: raise ValueError(f'Key ID missmatch: {key_id.hex()} != {fingerprint[0:8].hex()}') if key_id in certs: print_warn(f'doubled key ID in SE trust list, only using last: {format_key_id(key_id)}') except Exception as error: print_err(f'decoding SE trust list entry {key_id.hex()} / {b64encode(key_id).decode('ASCII')}: {error}') else: certs[key_id] = cert return certs def download_covid_pass_verifier_certs() -> CertList: certs: CertList = {} response = requests.get(CERTS_URL_COVID_PASS_VERIFIER, headers={'User-Agent': USER_AGENT}) response.raise_for_status() certs_json = json.loads(response.content) for entry in certs_json: key_id = bytes(entry['kid']) cert_der = bytes(entry['crt']) if cert_der: try: cert = load_der_x509_certificate(cert_der) except Exception as error: print_err(f'decoding covid-pass-verifier.com trust list entry {format_key_id(key_id)}: {error}') else: fingerprint = cert.fingerprint(hashes.SHA256()) if key_id != fingerprint[0:8]: raise ValueError(f'Key ID missmatch: {key_id.hex()} != {fingerprint[0:8].hex()}') if key_id in certs: print_warn(f'doubled key ID in covid-pass-verifier.com trust list, only using last: {format_key_id(key_id)}') certs[key_id] = cert else: iss = entry.get('iss') if iss: issuer = Name([NameAttribute(NAME_OIDS_COVID_PASS_VERIFIER.get(key) or ObjectIdentifier(key), value) for key, value in iss.items()]) else: issuer = Name([]) sub = entry.get('sub') if sub: subject = Name([NameAttribute(NAME_OIDS_COVID_PASS_VERIFIER.get(key) or ObjectIdentifier(key), value) for key, value in sub.items()]) else: subject = Name([]) pub = entry['pub'] if 'x' in pub and 'y' in pub: # EC x_bytes = bytes(pub['x']) y_bytes = bytes(pub['y']) x = int.from_bytes(x_bytes, byteorder="big", signed=False) y = int.from_bytes(y_bytes, byteorder="big", signed=False) curve = SECP256R1() ec_pubkey = EllipticCurvePublicNumbers(x, y, curve).public_key() cert = HackCertificate(ec_pubkey, issuer, subject) if key_id in certs: print_warn(f'doubled key ID in covid-pass-verifier.com trust list, only using last: {format_key_id(key_id)}') certs[key_id] = cert elif 'n' in pub and 'e' in pub: # RSA e_bytes = bytes(pub['e']) n_bytes = bytes(pub['n']) e = int.from_bytes(e_bytes, byteorder="big", signed=False) n = int.from_bytes(n_bytes, byteorder="big", signed=False) rsa_pubkey = RSAPublicNumbers(e, n).public_key() cert = HackCertificate(rsa_pubkey, issuer, subject) if key_id in certs: print_warn(f'doubled key ID in covid-pass-verifier.com trust list, only using last: {format_key_id(key_id)}') certs[key_id] = cert else: print_err(f'decoding covid-pass-verifier.com trust list entry {format_key_id(key_id)}: no supported public key data found') return certs def download_fr_certs(token: Optional[str] = None) -> CertList: certs: CertList = {} if token is None: token = os.getenv('FR_TOKEN') if token is None: raise KeyError( 'Required environment variable FR_TOKEN for FR trust list is not set. ' 'You can get the value of the token from the TousAntiCovid Verif app APK.') response = requests.get(CERTS_URL_FR, headers={ 'User-Agent': USER_AGENT, 'Authorization': f'Bearer {token}', }) response.raise_for_status() certs_json = json.loads(response.content) for key_id_b64, cert_b64 in certs_json['certificatesDCC'].items(): try: key_id = b64decode_ignore_padding(key_id_b64) cert_pem = b64decode(cert_b64) # Yes, they encode it twice! cert_der = b64decode(cert_pem) try: cert = load_der_x509_certificate(cert_der) except ValueError: cert = load_hack_certificate_from_der_public_key(cert_der) # HackCertificate.fingerprint() is not implemented else: fingerprint = cert.fingerprint(hashes.SHA256()) if key_id != fingerprint[0:8]: pubkey = cert.public_key() attrs = cert.subject.get_attributes_for_oid(NameOID.COUNTRY_NAME) if attrs and all(attr.value == 'UK' for attr in attrs) and isinstance(pubkey, (RSAPublicKey, EllipticCurvePublicKey)): # replace fake FR trust list certificate by my own fake certificate # XXX: not eintirely sure if I should do this? issuer = [attr for attr in cert.issuer if attr.oid != NameOID.COUNTRY_NAME] subject = [attr for attr in cert.subject if attr.oid != NameOID.COUNTRY_NAME] issuer.append( NameAttribute(NameOID.COUNTRY_NAME, 'GB')) subject.append(NameAttribute(NameOID.COUNTRY_NAME, 'GB')) cert = HackCertificate( pubkey, issuer = Name(issuer), subject = Name(subject), not_valid_before = cert.not_valid_before, not_valid_after = cert.not_valid_after, ) else: #print() #print_cert(key_id, cert, print_exts=True) raise ValueError(f'Key ID missmatch: {key_id.hex()} != {fingerprint[0:8].hex()}') if key_id in certs: print_warn(f'doubled key ID in FR trust list, only using last: {format_key_id(key_id)}') except Exception as error: print_err(f'decoding FR trust list entry {format_key_id(key_id)}: {error}') else: certs[key_id] = cert return certs def build_trust_chain(certs: List[x509.Certificate]) -> Dict[bytes, x509.Certificate]: trustchain: Dict[bytes, x509.Certificate] = {} for cert in certs: subject_key_id = cert.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_KEY_IDENTIFIER).value.digest trustchain[subject_key_id] = cert return trustchain def verify_trust_chain(cert: x509.Certificate, trustchain: Dict[bytes, x509.Certificate], root_cert: x509.Certificate) -> bool: signed_cert = cert rsa_padding = PKCS1v15() root_subject_key_id = root_cert.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_KEY_IDENTIFIER).value.digest visited: Set[bytes] = set() while signed_cert is not root_cert: auth_key_id = signed_cert.extensions.get_extension_for_oid(ExtensionOID.AUTHORITY_KEY_IDENTIFIER).value.key_identifier if auth_key_id in visited: raise ValueError('loop in trust chain detected') visited.add(auth_key_id) issuer_cert: Optional[x509.Certificate] if root_subject_key_id == auth_key_id: issuer_cert = root_cert else: issuer_cert = trustchain.get(auth_key_id) if issuer_cert == root_cert: # just to be sure that there is no trickery: issuer_cert = root_cert if issuer_cert is None: auth_key_id_str = ':'.join('%02X' % x for x in auth_key_id) fingerprint = signed_cert.fingerprint(hashes.SHA256()) fingerprint_str = ':'.join('%02X' % x for x in fingerprint) print_err(f'Could not verify signature of a certificate in the trust chain.\n' f'fingerprint: {fingerprint_str}\n' f'authority key ID: {auth_key_id_str}') return False pubkey = issuer_cert.public_key() try: if isinstance(pubkey, RSAPublicKey): pubkey.verify( signed_cert.signature, signed_cert.tbs_certificate_bytes, rsa_padding, signed_cert.signature_hash_algorithm, # type: ignore ) elif isinstance(pubkey, EllipticCurvePublicKey): pubkey.verify( signed_cert.signature, signed_cert.tbs_certificate_bytes, ECDSA(signed_cert.signature_hash_algorithm), ) else: pubkey_type = type(pubkey) raise NotImplementedError(f'Unsupported public key type: {pubkey_type.__module__}.{pubkey_type.__name__}') except InvalidSignature: try: subject_key_id = signed_cert.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_KEY_IDENTIFIER).value.digest except ExtensionNotFound: subject_key_id_str = 'N/A' else: subject_key_id_str = ':'.join('%02X' % x for x in subject_key_id) fingerprint = signed_cert.fingerprint(hashes.SHA256()) fingerprint_str = ':'.join('%02X' % x for x in fingerprint) print_err(f'Could not verify signature of a certificate in the trust chain.\n' f'fingerprint: {fingerprint_str}\n' f'subject key ID: {subject_key_id_str}') return False signed_cert = issuer_cert return True def verify_pkcs7_detached_signature(payload: bytes, signature: bytes, root_cert: x509.Certificate) -> bool: content_info = asn1crypto.cms.ContentInfo.load(signature) content = content_info['content'] cert_set = content['certificates'] certs: List[x509.Certificate] = [] for asn1cert in cert_set: if asn1cert.name == 'certificate': certs.append(load_der_x509_certificate(asn1cert.chosen.dump())) else: raise NotImplementedError(f'Certificate option in trust chain not supported: {asn1cert.name}') trustchain = build_trust_chain(certs) certs_by_serial: Optional[Dict[int, x509.Certificate]] = None for signer_info in content['signer_infos']: sid = signer_info['sid'] if sid.name == 'issuer_and_serial_number': if certs_by_serial is None: # lazily create this mapping only if needed certs_by_serial = {} for cert in certs: serial_number = cert.serial_number if serial_number in certs_by_serial: raise ValueError(f'Doubled serial number in trust chain: {serial_number}') certs_by_serial[serial_number] = cert serial_number = sid.chosen['serial_number'].native cert = certs_by_serial[serial_number] elif sid.name == 'subject_key_identifier': cert = trustchain[sid.chosen.native] if not verify_trust_chain(cert, trustchain, root_cert): return False pubkey = cert.public_key() digest_algo = signer_info['digest_algorithm']['algorithm'].native digest = hashlib.new(digest_algo, payload).digest() sig_algo = signer_info['signature_algorithm']['algorithm'].native signed_attrs = signer_info['signed_attrs'] # see: https://datatracker.ietf.org/doc/html/rfc5652#section-5.4 signed_data: Union[bytes, bytearray] if signed_attrs: has_message_digest = False for signed_attr in signed_attrs: if signed_attr['type'].native == 'message_digest': for msg_digest in signed_attr['values'].native: has_message_digest = True if digest != msg_digest: print_err(f'Payload digest missmatch.\n' f'expected: {msg_digest.hex()}\n' f'actual: {digest.hex()}') return False if not has_message_digest: raise ValueError(f'Message digest signed attribute is missing.') signed_attrs_bytes = bytearray(signed_attrs.dump()) #signed_attrs_bytes[0] = ASN1_SET | ASN1_CONSTRUCTED signed_attrs_bytes[0] = 0x11 | 0x20 signed_data = signed_attrs_bytes else: signed_data = payload sign = signer_info['signature'].native try: if isinstance(pubkey, RSAPublicKey): if sig_algo != 'rsassa_pkcs1v15': raise NotImplementedError(f'Unsupported signature algorithm: {sig_algo}') pubkey.verify( sign, signed_data, PKCS1v15(), HASH_ALGORITHMS[digest_algo](), # type: ignore ) elif isinstance(pubkey, EllipticCurvePublicKey): pubkey.verify( sign, signed_data, ECDSA(HASH_ALGORITHMS[digest_algo]()), ) else: pubkey_type = type(pubkey) raise NotImplementedError(f'Unsupported public key type: {pubkey_type.__module__}.{pubkey_type.__name__}') except InvalidSignature: return False return True def download_nl_certs(token: Optional[str] = None) -> CertList: # Fetch the root certificate for the Netherlands; used to secure the # trust list. Non fatal error if this fails. root_cert: Optional[x509.Certificate] = None try: root_cert = get_root_cert('NL') except (BaseHTTPError, ValueError) as error: print_err(f'NL trust list error (NOT VALIDATING): {error}') certs: CertList = {} response = requests.get(CERTS_URL_NL, headers={'User-Agent': USER_AGENT}) response.raise_for_status() certs_json = json.loads(response.content) payload = b64decode(certs_json['payload']) if root_cert is not None: # Signature is a CMS (rfc5652) detached signature of the payload. # The certificate chain in this pkcs#7 signature rolls up to the # rootkey of the Kingdom of the Netherlands (https://www.pkioverheid.nl) # signature = b64decode(certs_json['signature']) try: valid = verify_pkcs7_detached_signature(payload, signature, root_cert) except (NotImplementedError, ValueError) as error: print_err(f'NL trust list error (NOT VALIDATING): {error}') else: if not valid: raise ValueError(f'Invalid signature of NL trust list: {signature.hex()}') payload_dict = json.loads(payload) # We ignore the 'nl_keys' - these are for the domestic QR codes; which are # privacy preserving C.L. signature based to allow for unlinkability as to # prevent tracking/surveilance. # for key_id_b64, pubkeys in payload_dict['eu_keys'].items(): try: key_id = b64decode(key_id_b64) for entry in pubkeys: try: # XXX: Why is subjectPk an array? How can there be more than one key to a key ID? pubkey_der = b64decode(entry['subjectPk']) # entry['keyUsage'] is array of 't' or 'v' or 'r' cert = load_hack_certificate_from_der_public_key(pubkey_der) if key_id in certs: print_warn(f'doubled key ID in NL trust list, only using last: {format_key_id(key_id)}') except Exception as error: print_err(f'decoding NL trust list entry {format_key_id(key_id)}: {error}') else: certs[key_id] = cert except Exception as error: print_err(f'decoding NL trust list entry {format_key_id(key_id)}: {error}') return certs CH_USER_AGENT = 'ch.admin.bag.covidcertificate.wallet;2.1.1;1626211804080;Android;28' def get_ch_token() -> str: token = os.getenv('CH_TOKEN') if token is None: raise KeyError( "Required environment variable CH_TOKEN for CH trust list is not set. " "You can get the value of the token from the BIT's Android CovidCertificate app APK.") return token def download_ch_certs(token: Optional[str] = None) -> CertList: if token is None: token = get_ch_token() root_cert: Optional[x509.Certificate] = None try: root_cert = get_root_cert('CH') except (BaseHTTPError, ValueError) as error: print_err(f'CH trust list error (NOT VALIDATING): {error}') response = requests.get(CERTS_URL_CH, headers={ 'User-Agent': CH_USER_AGENT, 'Accept': 'application/json+jws', 'Accept-Encoding': 'gzip', 'Authorization': f'Bearer {token}', }) response.raise_for_status() if root_cert is None: certs_token = jwt.get_unverified_claims(response.content.decode(response.encoding or 'UTF-8')) else: certs_token = load_jwt(response.content, root_cert) active_key_ids_b64 = certs_token['activeKeyIds'] active_key_ids = frozenset(b64decode(key_id_b64) for key_id_b64 in active_key_ids_b64) response = requests.get(UPDATE_URL_CH, headers={ 'User-Agent': CH_USER_AGENT, 'Accept': 'application/json+jws', 'Accept-Encoding': 'gzip', 'Authorization': f'Bearer {token}', }) response.raise_for_status() if root_cert is None: update_token = jwt.get_unverified_claims(response.content.decode(response.encoding or 'UTF-8')) else: update_token = load_jwt(response.content, root_cert) pubkeys: List[Dict[str, Optional[str]]] = update_token['certs'] certs: CertList = {} for pub in pubkeys: try: key_id = b64decode(pub['keyId']) # type: ignore if key_id in active_key_ids: alg = pub['alg'] usage: str = pub.get('use', 'tvr') # type: ignore usages: List[ObjectIdentifier] = [] if usage != 'sig': if 't' in usage: usages.append(VALID_FOR_TEST) if 'v' in usage: usages.append(VALID_FOR_VACCINATION) if 'r' in usage: usages.append(VALID_FOR_RECOVERY) exts: List[Extension] = [] if usages: exts.append(Extension(ExtensionOID.EXTENDED_KEY_USAGE, False, ExtendedKeyUsage(usages))) extensions = Extensions(exts) if alg == 'ES256': # EC x_bytes = b64decode(pub['x']) # type: ignore y_bytes = b64decode(pub['y']) # type: ignore x = int.from_bytes(x_bytes, byteorder="big", signed=False) y = int.from_bytes(y_bytes, byteorder="big", signed=False) crv: str = pub['crv'] # type: ignore curve = NIST_CURVES[crv]() ec_pubkey = EllipticCurvePublicNumbers(x, y, curve).public_key() cert = HackCertificate(ec_pubkey, extensions=extensions) elif alg == 'RS256': # RSA e_bytes = b64decode(pub['e']) # type: ignore n_bytes = b64decode(pub['n']) # type: ignore e = int.from_bytes(e_bytes, byteorder="big", signed=False) n = int.from_bytes(n_bytes, byteorder="big", signed=False) rsa_pubkey = RSAPublicNumbers(e, n).public_key() cert = HackCertificate(rsa_pubkey, extensions=extensions) else: raise NotImplementedError(f'algorithm not supported: {alg!r}') if key_id in certs: print_warn(f'doubled key ID in CH trust list, only using last: {format_key_id(key_id)}') certs[key_id] = cert except Exception as error: print_err(f'decoding CH trust list entry {format_key_id(key_id)}: {error}') return certs def download_no_certs(token: Optional[str] = None) -> CertList: NO_USER_AGENT = 'FHICORC/38357 CFNetwork/1240.0.4 Darwin/20.5.0' if token is None: token = os.getenv('NO_TOKEN') if token is None: raise KeyError( "Required environment variable NO_TOKEN for NO trust list is not set. " "You can get the value of the token from the Kontroll av koronasertifikat app APK.") response = requests.get(CERTS_URL_NO, headers={ 'User-Agent': NO_USER_AGENT, 'Authorization': token, }) response.raise_for_status() certs: CertList = {} # TODO: find out if there is some sort of root cert to verify the trust list? certs_json = json.loads(response.content) for entry in certs_json: key_id = b64decode(entry['kid']) pubkey_der = b64decode(entry['publicKey']) cert = load_hack_certificate_from_der_public_key(pubkey_der) if key_id in certs: print_warn(f'doubled key ID in NO trust list, only using last: {format_key_id(key_id)}') certs[key_id] = cert return certs def download_gb_certs() -> CertList: response = requests.get(CERTS_URL_GB, headers={'User-Agent': USER_AGENT}) response.raise_for_status() certs: CertList = {} # TODO: find out if there is some sort of root cert to verify the trust list? md5_b64 = response.headers.get('content-md5') if md5_b64 is not None: expected_md5 = b64decode(md5_b64) actual_md5 = hashlib.md5(response.content).digest() if expected_md5 != actual_md5: raise ValueError(f'MD5 sum missmatch of GB trust list: expected: {expected_md5.hex()}, actual: {actual_md5.hex()}') certs_json = json.loads(response.content) for entry in certs_json: key_id = b64decode(entry['kid']) pubkey_der = b64decode(entry['publicKey']) cert = load_hack_certificate_from_der_public_key( pubkey_der, Name([NameAttribute(NameOID.COUNTRY_NAME, 'GB')]), Name([NameAttribute(NameOID.COUNTRY_NAME, 'GB')]), ) if key_id in certs: print_warn(f'doubled key ID in GB trust list, only using last: {format_key_id(key_id)}') certs[key_id] = cert return certs DOWNLOADERS: Dict[str, Callable[[], CertList]] = { 'AT-GREENCHECK': download_at_greencheck_certs, 'AT': download_at_certs, 'AT-TEST': lambda: download_at_certs(test=True), 'CH': download_ch_certs, 'DE': download_de_certs, 'FR': download_fr_certs, 'GB': download_gb_certs, 'NL': download_nl_certs, 'NO': download_no_certs, 'SE': download_se_certs, 'UK': download_gb_certs, # alias 'COVID-PASS-VERIFIER': download_covid_pass_verifier_certs, } def download_ehc_certs(sources: List[str], certs_table: Dict[str, CertList] = {}) -> CertList: certs: CertList = {} get_downloader = DOWNLOADERS.get for source in sources: source_certs = certs_table.get(source) if source_certs is not None: certs.update(source_certs) else: downloader = get_downloader(source) if downloader is None: raise ValueError(f'Unknown trust list source: {source}') certs.update(downloader()) return certs def get_at_greencheck_root_cert(root_cert_key_id: bytes = ROOT_CERT_KEY_ID_AT) -> x509.Certificate: # TODO: Find out another place where to get the AT root certificate from. # This gets it from the same server as the trust list itself, which is suboptimal. response = requests.get('https://greencheck.gv.at/', headers={'User-Agent': USER_AGENT}) response.raise_for_status() doc = parse_html(response.content.decode(response.encoding or 'UTF-8')) for script in doc.xpath('//script'): src = script.attrib.get('src') if src and src.startswith('/static/js/main.') and src.endswith('.chunk.js'): response = requests.get(f'https://greencheck.gv.at{src}', headers={'User-Agent': USER_AGENT}) status_code = response.status_code if status_code < 200 or status_code >= 300: print_err(f'https://greencheck.gv.at{src} {status_code} {http.client.responses.get(status_code, '')}') else: source = response.content.decode(response.encoding or 'UTF-8') match = JS_CERT_PATTERN.search(source) if match: certs_pems_js = match.group(1) certs_pems_js = ESC.sub(lambda match: chr(int(match[1], 16)), certs_pems_js) for meta_cert_key, meta_cert_src in json.loads(certs_pems_js).items(): meta_cert = load_pem_x509_certificate(meta_cert_src.encode()) key_id = meta_cert.fingerprint(hashes.SHA256())[:8] if key_id == root_cert_key_id: return meta_cert raise KeyError(f'AT certificate with key ID {format_key_id(root_cert_key_id)} not found!') def get_at_github_root_cert(test: bool = False) -> x509.Certificate: response = requests.get('https://raw.githubusercontent.com/Federal-Ministry-of-Health-AT/green-pass-overview/main/README.md', headers={'User-Agent': USER_AGENT}) response.raise_for_status() text = response.content.decode(response.encoding or 'UTF-8') certs: Dict[str, x509.Certificate] = {} for url, cert_data in MD_CERT_PATTERN.findall(text): cert = load_pem_x509_certificate(cert_data.encode('UTF-8')) certs[url] = cert if test: res_cert = certs.get('https://dgc-trusttest.qr.gv.at') or certs.get('https://dgc-trusttest.gv.at') else: res_cert = certs.get('https://dgc-trust.qr.gv.at') if res_cert is None: raise KeyError(f'AT {'testing' if test else 'production'} root certificate not found!') return res_cert def get_at_root_cert() -> x509.Certificate: return load_pem_x509_certificate(ROOT_CERT_AT_PROD) def get_at_test_root_cert() -> x509.Certificate: return load_pem_x509_certificate(ROOT_CERT_AT_TEST) def get_de_root_pubkey() -> EllipticCurvePublicKey: response = requests.get(PUBKEY_URL_DE, headers={'User-Agent': USER_AGENT}) response.raise_for_status() pubkey = load_pem_public_key(response.content) if not isinstance(pubkey, EllipticCurvePublicKey): pubkey_type = type(pubkey) raise ValueError(f'{PUBKEY_URL_DE} is expected to be an EllipticCurvePublicKey but actually is {pubkey_type.__module__}.{pubkey_type.__name__}') return pubkey def get_de_root_cert() -> x509.Certificate: return HackCertificate(get_de_root_pubkey()) def get_nl_root_cert() -> x509.Certificate: response = requests.get(ROOT_CERT_URL_NL, headers={'User-Agent': USER_AGENT}) response.raise_for_status() return load_der_x509_certificate(response.content) def get_se_root_cert() -> x509.Certificate: response = requests.get(ROOT_CERT_URL_SE, headers={'User-Agent': USER_AGENT}) response.raise_for_status() return load_pem_x509_certificate(response.content) def get_ch_root_cert(token: Optional[str] = None) -> x509.Certificate: if token is None: token = get_ch_token() response = requests.get(ROOT_CERT_URL_CH, headers={ 'User-Agent': CH_USER_AGENT, 'Accept': 'application/json+jws', 'Accept-Encoding': 'gzip', 'Authorization': f'Bearer {token}', }) response.raise_for_status() return load_pem_x509_certificate(response.content) ROOT_CERT_DOWNLOADERS: Dict[str, Callable[[], x509.Certificate]] = { 'AT-GREENCHECK': get_at_greencheck_root_cert, 'AT': get_at_root_cert, 'AT-TEST': get_at_test_root_cert, 'AT-GITHUB': get_at_github_root_cert, 'AT-TEST-GITHUB': lambda: get_at_github_root_cert(test=True), 'DE': get_de_root_cert, # actually just a public key 'NL': get_nl_root_cert, 'SE': get_se_root_cert, 'CH': get_ch_root_cert, } def get_root_cert(source: str) -> x509.Certificate: envvar = f'{source.replace('-', '_')}_ROOT_CERT' value = os.getenv(envvar) if value is None: return ROOT_CERT_DOWNLOADERS[source]() if value.startswith('-----BEGIN CERTIFICATE-----'): return load_pem_x509_certificate(value.encode()) elif value.startswith('-----BEGIN PUBLIC KEY-----'): pubkey = load_pem_public_key(value.encode()) if not isinstance(pubkey, (EllipticCurvePublicKey, RSAPublicKey)): pubkey_type = type(pubkey) raise ValueError(f'expected EllipticCurvePublicKey or RSAPublicKey but actually got {pubkey_type.__module__}.{pubkey_type.__name__}') return HackCertificate(pubkey) with open(value, "rb") as fp: data = fp.read() if data.startswith(b'-----BEGIN CERTIFICATE-----'): return load_pem_x509_certificate(data) elif data.startswith(b'-----BEGIN PUBLIC KEY-----'): pubkey = load_pem_public_key(data) if not isinstance(pubkey, (EllipticCurvePublicKey, RSAPublicKey)): pubkey_type = type(pubkey) raise ValueError(f'expected EllipticCurvePublicKey or RSAPublicKey but actually got {pubkey_type.__module__}.{pubkey_type.__name__}') return HackCertificate(pubkey) else: return load_der_x509_certificate(data) def get_default_root_cert_filename(source: str) -> str: envvar = f'{source.replace('-', '_')}_ROOT_CERT' value = os.getenv(envvar) if value is not None and \ not value.startswith('-----BEGIN CERTIFICATE-----') and \ not value.startswith('-----BEGIN PUBLIC KEY-----'): return value return f'{source}.pem' def save_cert(cert: x509.Certificate, filename: str) -> None: _, ext = splitext(filename) ext = ext.lower() if ext == '.pem': encoding = Encoding.PEM else: encoding = Encoding.DER try: data = cert.public_bytes(encoding) except NotImplementedError: data = cert.public_key().public_bytes(encoding, PublicFormat.SubjectPublicKeyInfo) with open(filename, 'wb') as fp: fp.write(data) def load_jwt(token: bytes, root_cert: x509.Certificate, options: Optional[Dict[str, bool]] = None) -> Dict[str, Any]: header = jws.get_unverified_header(token) trustchain = [x509.load_der_x509_certificate(b64decode(cert_b64)) for cert_b64 in header['x5c']] trustchain.append(root_cert) rsa_padding = PKCS1v15() for index in range(len(trustchain) - 1): signed_cert = trustchain[index] issuer_cert = trustchain[index + 1] pubkey = issuer_cert.public_key() if isinstance(pubkey, RSAPublicKey): pubkey.verify( signed_cert.signature, signed_cert.tbs_certificate_bytes, rsa_padding, signed_cert.signature_hash_algorithm # type: ignore ) elif isinstance(pubkey, EllipticCurvePublicKey): pubkey.verify( signed_cert.signature, signed_cert.tbs_certificate_bytes, ECDSA(signed_cert.signature_hash_algorithm), ) else: pubkey_type = type(pubkey) raise NotImplementedError(f'Unsupported public key type: {pubkey_type.__module__}.{pubkey_type.__name__}') pubkey = trustchain[0].public_key() sigkey: jwk.Key if isinstance(pubkey, RSAPublicKey): rsa_pn = pubkey.public_numbers() e = rsa_pn.e.to_bytes((rsa_pn.e.bit_length() + 7) // 8, byteorder='big') n = rsa_pn.n.to_bytes((rsa_pn.n.bit_length() + 7) // 8, byteorder='big') sigkey = jwk.construct({ 'kty': 'RSA', 'alg': 'RS256', 'e': b64encode(e), 'n': b64encode(n), }) elif isinstance(pubkey, EllipticCurvePublicKey): ec_pn = pubkey.public_numbers() size = pubkey.curve.key_size // 8 x = ec_pn.x.to_bytes(size, byteorder="big") y = ec_pn.y.to_bytes(size, byteorder="big") sigkey = jwk.construct({ 'kty': 'EC', 'alg': 'ES256', 'crv': SECG_TO_NIST_CURVES.get(pubkey.curve.name, pubkey.curve.name), 'x': b64encode(x), 'y': b64encode(y), }) else: pubkey_type = type(pubkey) raise NotImplementedError(f'Unsupported public key type: {pubkey_type.__module__}.{pubkey_type.__name__}') return jwt.decode(token, key=sigkey, options=options) def load_hack_certificate_from_der_public_key(data: bytes, issuer: Optional[Name] = None, subject: Optional[Name] = None, not_valid_before: datetime = DEFAULT_NOT_VALID_BEFORE, not_valid_after: datetime = DEFAULT_NOT_VALID_AFTER, ) -> HackCertificate: pubkey = load_der_public_key(data) if isinstance(pubkey, EllipticCurvePublicKey): return HackCertificate(pubkey, issuer, subject, not_valid_before, not_valid_after) elif isinstance(pubkey, RSAPublicKey): return HackCertificate(pubkey, issuer, subject, not_valid_before, not_valid_after) else: pubkey_type = type(pubkey) raise NotImplementedError(f'Unsupported public key type: {pubkey_type.__module__}.{pubkey_type.__name__}') def b64decode_ignore_padding(b64str: str) -> bytes: return b64decode(b64str + "=" * ((4 - len(b64str) % 4) % 4)) def urlsafe_b64decode_ignore_padding(b64str: str) -> bytes: return urlsafe_b64decode(b64str + "=" * ((4 - len(b64str) % 4) % 4)) def decode_ehc(b45_data: str) -> CoseMessage: if b45_data.startswith(PREFIX): b45_data = b45_data[len(PREFIX):] elif b45_data.startswith(PREFIX_NO): b45_data = b45_data[len(PREFIX_NO):] try: data = b45decode(b45_data) except ValueError: print(b45_data) raise ValueError(f'Invalid base45 string. Try with single quotes.') from None if data.startswith(b'x'): data = zlib.decompress(data) msg: CoseMessage = CoseMessage.decode(data) return msg def format_key_id(key_id: bytes) -> str: key_id_hex = key_id.hex() key_id_b64 = b64encode(key_id).decode("ASCII") if all(byte >= 0x21 and byte <= 0x7E for byte in key_id): return f'{key_id_hex} / {key_id_b64} / {key_id.decode('ASCII')}' return f'{key_id_hex} / {key_id_b64}' def verify_ehc(msg: CoseMessage, issued_at: datetime, certs: CertList, print_exts: bool = False) -> bool: cose_algo = msg.phdr.get(Algorithm) or msg.uhdr.get(Algorithm) print(f'COSE Sig. Algo.: {cose_algo.fullname if cose_algo is not None else 'N/A'}') if isinstance(msg, Sign1Message): print(f'Signature : {b64encode(msg.signature).decode('ASCII')}') # TODO: Should we allow (or warn about) key IDs from the unprotected header? # I mean, as long as the actual key it referres to is valid # (i.e. is in the trust list) it shouldn't matter, right? key_id = msg.phdr.get(KID) or msg.uhdr[KID] cert = certs.get(key_id) # XXX: is this correct? is it not two levels of signed certificates? if not cert: raise KeyError(f'Key ID not found in trust list: {key_id.hex()}') print('X.509 Certificate:') print_cert(key_id, cert, print_exts, indent=' ') cert_expired = False if cert.not_valid_before is not None and issued_at < cert.not_valid_before: cert_expired = True if cert.not_valid_after is not None and issued_at > cert.not_valid_after: cert_expired = True print(f' Cert Expired : {cert_expired}') revoked_cert = get_revoked_cert(cert) if revoked_cert: print(f'Cert Revoked At: {revoked_cert.revocation_date.isoformat()}') revoked = True else: revoked = False msg.key = cert_to_cose_key(cert) valid = msg.verify_signature() usage = get_key_usage(cert) ehc_payload = cbor2.loads(msg.payload) ehc = ehc_payload[-260][1] usage_valid = True if 'v' in ehc and 'vaccination' not in usage: usage_valid = False if 't' in ehc and 'test' not in usage: usage_valid = False if 'r' in ehc and 'recovery' not in usage: usage_valid = False print(f'Valid Key Usage: {usage_valid}') print(f'Signature Valid: {valid}') return valid and not cert_expired and not revoked and usage_valid def cert_to_cose_key(cert: x509.Certificate) -> CoseKey: pk = cert.public_key() if isinstance(pk, EllipticCurvePublicKey): ec_pn = pk.public_numbers() size = pk.curve.key_size // 8 x = ec_pn.x.to_bytes(size, byteorder="big") y = ec_pn.y.to_bytes(size, byteorder="big") curve_name = CURVE_NAME_IGNORE.sub('', pk.curve.name).lower() curve = COSE_CURVES.get(curve_name) if not curve: raise NotImplementedError(f'Unsupported curve: {pk.curve.name}') return CoseKey.from_dict( { KpKeyOps: [VerifyOp], KpKty: KtyEC2, EC2KpCurve: curve, KpAlg: Es256, EC2KpX: x, EC2KpY: y, } ) elif isinstance(pk, RSAPublicKey): rsa_pn = pk.public_numbers() e = rsa_pn.e.to_bytes((rsa_pn.e.bit_length() + 7) // 8, byteorder='big') n = rsa_pn.n.to_bytes((rsa_pn.n.bit_length() + 7) // 8, byteorder='big') return CoseKey.from_dict( { KpKeyOps: [VerifyOp], KpKty: KtyRSA, KpAlg: Ps256, RSAKpE: e, RSAKpN: n, } ) #elif isinstance(pk, DSAPublicKey): # dsa_pn = pk.public_numbers() # return CoseKey.from_dict( # { # # ??? # } # ) else: pk_type = type(pk) raise NotImplementedError(f'Unsupported public key type: {pk_type.__module__}.{pk_type.__name__}') crl_status: Dict[str, int] = {} crls: Dict[str, x509.CertificateRevocationList] = {} def get_cached_crl(uri: str) -> x509.CertificateRevocationList: crl = crls.get(uri) if crl is not None: return crl status_code = crl_status.get(uri) if status_code is not None: raise ValueError(f'{uri} {status_code} {http.client.responses.get(status_code, '')}') response = requests.get(uri, headers={'User-Agent': USER_AGENT}) status_code = response.status_code crl_status[uri] = status_code if response.status_code >= 400 and response.status_code < 600: raise ValueError(f'{uri} {status_code} {http.client.responses.get(status_code, '')}') crl_bytes = response.content if crl_bytes.startswith(b'-----BEGIN'): crl = load_pem_x509_crl(crl_bytes) else: crl = load_der_x509_crl(crl_bytes) crls[uri] = crl return crl def get_revoked_cert(cert: x509.Certificate) -> Optional[x509.RevokedCertificate]: try: crl_points_ext = cert.extensions.get_extension_for_oid(ExtensionOID.CRL_DISTRIBUTION_POINTS) except ExtensionNotFound: pass else: crl_points = crl_points_ext.value for crl_point in crl_points: uris = crl_point.full_name if uris: for uri in uris: lower_uri = uri.value.lower() if lower_uri.startswith('http:') or lower_uri.startswith('https:'): try: crl = get_cached_crl(uri.value) except Exception as error: print_err(f'loading revokation list {uri.value} {error}') else: return crl.get_revoked_certificate_by_serial_number(cert.serial_number) return None ENV_COMMENT = re.compile(r'^\s*(?:#.*)?$') ENV_VAR = re.compile(r'^\s*(?P<key>[0-9_a-zA-Z]+)\s*=\s*(?:"(?P<quoted>(?:[^"\\]|\\["nrt\\])*)"\s*|(?P<plain>[^#"]*))(?:#.*)?$') ENV_QUOTE = re.compile(r'\\(.)') ENV_ESC = { '\\': '\\', '"': '"', 'n': '\n', 'r': '\r', 't': '\t', } def parse_env(data: str) -> Dict[str, str]: env: Dict[str, str] = {} for index, line in enumerate(data.split('\n')): if not ENV_COMMENT.match(line): match = ENV_VAR.match(line) if not match: raise SyntaxError(f'in .env file: {line}') key: str = match.group('key') # type: ignore quoted: Optional[str] = match.group('quoted') value: str if quoted is not None: value = ENV_QUOTE.sub(lambda m: ENV_ESC[m.group(1)], quoted) # type: ignore else: value = match.group('plain') # type: ignore env[key] = value return env def save_certs(certs: CertList, certs_path: str, allow_public_key_only: bool = False) -> None: ext = splitext(certs_path)[1] lower_ext = ext.lower() if lower_ext == '.json': from jwcrypto.jwk import JWK # type: ignore # JSON that includes all info in a format as needed by WebCrypto, I hope certs_json = {} for key_id, cert in certs.items(): pubkey = cert.public_key() pubkey_jwk = JWK.from_pyca(pubkey) pubkey_json = pubkey_jwk.export(as_dict=True, private_key=False) pubkey_json['key_ops'] = ['verify'] # not sure about this: pubkey_json['kid'] = urlsafe_b64encode(key_id).decode('ASCII') # even less sure about this: if pubkey_json['kty'] == 'EC': algo = { 'name': 'ECDSA', 'namedCurve': pubkey_json['crv'], 'hash': {'name': "SHA-256"}, } else: algo = { 'name': 'RSASSA-PKCS1-v1_5', 'hash': {'name': "SHA-256"}, } cert_json = { 'issuer': make_json_relative_distinguished_name(cert.issuer), 'subject': make_json_relative_distinguished_name(cert.subject), 'notValidBefore': cert.not_valid_before.isoformat(), 'notValidAfter': cert.not_valid_after.isoformat(), 'publicKey': pubkey_json, 'algorithm': algo, 'usage': sorted(get_key_usage(cert)), } certs_json[key_id.hex()] = cert_json json_doc = { 'timestamp': datetime.utcnow().isoformat()+'Z', 'trustList': certs_json, } with open(certs_path, 'w') as text_stream: json.dump(json_doc, text_stream) elif lower_ext == '.cbor': # same CBOR format as AT trust list cert_list: List[dict] = [] for key_id, cert in certs.items(): if allow_public_key_only and isinstance(cert, HackCertificate): entry = { 'i': key_id, 'k': cert.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo), } issuer = cert.issuer if issuer: entry['is'] = make_json_relative_distinguished_name(issuer) subject = cert.subject if subject: entry['su'] = make_json_relative_distinguished_name(subject) not_valid_before = cert.not_valid_before if not_valid_before is not DEFAULT_NOT_VALID_BEFORE: entry['nb'] = int(not_valid_before.timestamp()) not_valid_after = cert.not_valid_before if not_valid_after is not DEFAULT_NOT_VALID_AFTER: entry['na'] = int(not_valid_after.timestamp()) cert_list.append(entry) else: try: cert_bytes = cert.public_bytes(Encoding.DER) except NotImplementedError as error: print_err(f'Cannot store entry {format_key_id(key_id)} in CBOR trust list: {error}') else: cert_list.append({ 'i': key_id, 'c': cert_bytes, }) with open(certs_path, 'wb') as fp: cbor2.dump({'c': cert_list}, fp) else: raise ValueError(f'Unsupported certificates file extension: {ext!r}') def split_lines(text: str, width: int) -> List[str]: lines: List[str] = [] for line_str in text.split('\n'): line: List[str] = [] line_len = 0 for word in line_str.split(' '): word_len = len(word) next_len = line_len + word_len if line: next_len += 1 if next_len > width: lines.append(' '.join(line)) line.clear() line_len = 0 elif line: line_len += 1 line.append(word) line_len += word_len lines.append(' '.join(line)) return lines def fill_text(text: str, width: int, indent: str) -> str: return '\n'.join(indent + line for line in split_lines(text, width - len(indent))) class SmartFormatter(argparse.HelpFormatter): def _split_lines(self, text: str, width: int) -> List[str]: return split_lines(text, width) def _fill_text(self, text: str, width: int, indent: str) -> str: return fill_text(text, width, indent) def parse_sources(sources_str: str) -> List[str]: sources_str = sources_str.strip() return [country.strip().upper() for country in sources_str.split(',')] if sources_str else [] class Align(enum.Enum): Left = 0 Right = 1 Center = 2 def align(self, text: str, width: int, fillchar: str = ' ') -> str: if self == Align.Left: return text.ljust(width, fillchar) elif self == Align.Right: return text.rjust(width, fillchar) else: return text.center(width, fillchar) def print_table(header: List[str], align: List[Align], body: List[List[str]]) -> None: widths: List[int] = [len(cell) for cell in header] for row in body: for index, cell in enumerate(row): cell_len = len(cell) while index >= len(widths): widths.append(0) if widths[index] < cell_len: widths[index] = cell_len while len(align) < len(widths): align.append(Align.Left) print(' | '.join(alignment.align(cell, width) for alignment, cell, width in zip(align, header, widths)).rstrip()) print('-+-'.join(alignment.align('', width, '-') for alignment, width in zip(align, widths))) for row in body: print(' | '.join(alignment.align(cell, width) for alignment, cell, width in zip(align, row, widths)).rstrip()) def get_key_usage(cert: x509.Certificate) -> Set[str]: usage: Set[str] = set() try: ext_key_usage = cert.extensions.get_extension_for_oid(ExtensionOID.EXTENDED_KEY_USAGE) except ExtensionNotFound: pass else: for oid in ext_key_usage.value: usage_name = EXT_KEY_USAGE_NAMES.get(oid) if usage_name is not None: usage.add(usage_name) if not usage: usage = {'test', 'vaccination', 'recovery'} return usage def print_cert(key_id: bytes, cert: x509.Certificate, print_exts: bool = False, revoked_certs: Optional[Dict[bytes, x509.RevokedCertificate]] = None, indent: Union[str, int]='') -> None: if isinstance(indent, int): indent = ' ' * indent print(f'{indent}Key ID :', format_key_id(key_id)) if not isinstance(cert, HackCertificate): print(f'{indent}Serial Nr. :', ":".join("%02x" % byte for byte in cert.serial_number.to_bytes(20, byteorder="big"))) print(f'{indent}Issuer :', cert.issuer.rfc4514_string()) print(f'{indent}Subject :', cert.subject.rfc4514_string()) print(f'{indent}Valid Date Range:', cert.not_valid_before.isoformat() if cert.not_valid_before is not None else 'N/A', '-', cert.not_valid_after.isoformat() if cert.not_valid_after is not None else 'N/A') print(f'{indent}Version :', cert.version.name) usage: Set[str] = set() try: ext_key_usage = cert.extensions.get_extension_for_oid(ExtensionOID.EXTENDED_KEY_USAGE) except ExtensionNotFound: pass else: for oid in ext_key_usage.value: usage_name = EXT_KEY_USAGE_NAMES.get(oid) if usage_name is None: print_warn(f'Unexpected extened key usage: {oid.dotted_string} ({oid._name})') else: usage.add(usage_name) if not usage: usage = {'test', 'vaccination', 'recovery'} print(f'{indent}Ext. Key Usage : {', '.join(sorted(usage))}') pk = cert.public_key() print(f'{indent}Key Type : {type(pk).__name__.strip('_')}') if isinstance(pk, EllipticCurvePublicKey): print(f'{indent}Curve :', pk.curve.name) if not isinstance(cert, HackCertificate): signature_algorithm_oid = cert.signature_algorithm_oid print(f'{indent}Signature Algo. : oid={signature_algorithm_oid.dotted_string}, name={signature_algorithm_oid._name}') print(f'{indent}Signature :', b64encode(cert.signature).decode('ASCII')) if revoked_certs is not None: revoked_cert = revoked_certs.get(key_id) if revoked_cert: print(f'{indent}Revoked At :', revoked_cert.revocation_date.isoformat()) if print_exts and cert.extensions: print(f'{indent}Extensions :') for ext in cert.extensions: print(f'{indent}- oid={ext.oid.dotted_string}, name={ext.oid._name}, value={ext.value}') def main() -> None: ap = argparse.ArgumentParser(formatter_class=SmartFormatter, add_help=False) ap.add_argument('--help', '-h', action='store_true', default=False, help= 'Show this help message and exit.') certs_ap = ap.add_mutually_exclusive_group() certs_ap.add_argument('--certs-file', metavar="FILE", help= 'Trust list in CBOR or JSON format.') certs_ap.add_argument('--certs-from', metavar="LIST", help= "Download trust list from given country's trust list service. Comma separated list, entries from later country overwrites earlier.\n" "See also environment variables.\n" "\n" "Supported countries: AT, CH, DE, FR, GB, NL, NO, SE\n" "\n" "Note that the GB trust list only contains GB public keys, so you might want to combine it with another.\n" "\n" "If neither --certs-file nor --certs-from is given then --certs-from=DE,AT is used as default.\n", default='DE,AT') certs_ap.add_argument('--certs-table', metavar='LIST', help= 'Print table of trust list certificates showing where which key ID is avaliable showing the country of the certificate as it is known to the given trust list. ' '"X" means the certificate/public key is in the trust list, but no country attribute is known for it.') ap.add_argument('--no-verify', action='store_true', default=False, help='Skip certificate verification.') ap.add_argument('--list-certs', action='store_true', help='List certificates from trust list.') ap.add_argument('--print-exts', action='store_true', help='Also print certificate extensions.') ap.add_argument('--strip-revoked', action='store_true', help= 'Strip revoked certificates. (Downloads certificate revocation list, if supported by certificate.)') ap.add_argument('--save-certs', metavar='FILE', action='append', help= 'Store downloaded trust list to FILE. The filetype is derived from the extension, which can be .json or .cbor') ap.add_argument('--download-root-cert', metavar='SOURCE[@FILENAME]', action='append', help= 'Download and store root certificate (or public key) of SOURCE as FILENAME. ' 'If FILENAME is not given SOURCE.pem is used. ' 'If FILENAME ends in ".pem" the certificate (or public key) is stored encoded as PEM, otherwise it is encoded as DER.') ap.add_argument('--download-all-root-certs', action='store_true', help= 'Download and store all root certificates (or public keys) and store them in SOURCE.pem files.') ap.add_argument('--allow-public-key-only', '--allow-pubkey-only', action='store_true', help= 'When writing the CBOR trust list format it usually rejects entries that are only public keys and not full x509 certificates. ' 'With this options it also writes entries that are only public keys.') ap.add_argument('--envfile', metavar='FILE', default='.env', help= 'Load environment variables from FILE. Default is ".env". ' 'Set this to an empty string to not load environment varibles from a file.') ap.add_argument('--fail-on-error', action='store_true', default=False, help='Turns every error into an exception.') ap.add_argument('--warning-as-error', action='store_true', default=False, help='Turns every warning into an error.') ap.add_argument('--image', action='store_true', default=False, help='ehc_code is a path to an image file containing a QR-code.') ap.add_argument('ehc_code', nargs='*', help='Scanned EHC QR-code, or when --image is passed path to an image file.') args = ap.parse_args() if args.help: width = shutil.get_terminal_size().columns extra_help: List[Tuple[str, List[Tuple[str, str]]]] = [ ( 'environment variables:', [ ( '<SOURCE>_ROOT_CERT', "Some of the trust lists are have signatures that can be checked with a certain trust list " "specific root certificate (or just public key in the case of DE). Instead of always downloading " "these certificates you can just download them once using --download-root-cert or " "--download-all-root-certs and then supply them to this script using environment variables. " "The environment variable can be a path to a PEM or DER encoded certificate, a PEM encoded " "public key, or the value of the environment variable itself can be a PEM encoded certificate " "or public key. You can use this to pin the root certificate.\n" "\n" "Example:\n" " ./verify_ehc.py --download-root-cert SE@se_root_cert.crt\n" " export SE_ROOT_CERT=se_root_cert.crt\n" " ./verify_ehc.py --certs-from SE --save-certs certs.cbor\n" "\n" "Trust list sources for which root certificates are supported:\n" " AT, CH, DE, NL, SE" ), # TODO: Write proper help text once this information becomes available. #( # 'AT_TOKEN', # "Downloading the Austrian (AT) trust list needs the nevironment variable AT_TOKEN set to " # "a token that you will be able to get from somewhere. Still waiting on the government to " # "pulicise anything about that.\n" # "<insert description and link here>" #), ( 'CH_TOKEN', "Downloading the Swiss (CH) trust list and root certificate needs the environment variable " "CH_TOKEN set to a bearer token that can be found in the BIT's Android CovidCertificate app " "APK. See also: https://github.com/cn-uofbasel/ch-dcc-keys" ), ( 'FR_TOKEN', "Downloading the French (FR) trust list needs the environment variable FR_TOKEN set to a bearer " "token that can be found in the TousAntiCovid Verif app APK." ), ( 'NO_TOKEN', "Downloading the Norwegian (NO) trust list needs the environment variable NO_TOKEN set to an " "AuthorizationHeader string that can be found in the Kontroll av koronasertifikat app APK. " "See also: https://harrisonsand.com/posts/covid-certificates/" ), ] ) ] ap.print_help() print() item_name_limit = 20 for title, help_items in extra_help: print(title) max_item_name_len = 0 for item_name, description in help_items: item_name_len = len(item_name) if item_name_len > max_item_name_len and item_name_len < item_name_limit: max_item_name_len = item_name_len if max_item_name_len == 0: max_item_name_len = item_name_limit rest_width = max(width - 4 - max_item_name_len, 1) indent = ' ' * (width - rest_width) for item_name, description in help_items: lines = split_lines(description, rest_width) if len(item_name) > item_name_limit: print(f' {item_name}') else: print(f' {item_name.ljust(max_item_name_len)} {lines[0]}') lines = lines[1:] for line in lines: print(indent + line) print() print('Report issues to: https://github.com/panzi/verify-ehc/issues') return global FAIL_ON_ERROR, WARNING_AS_ERROR FAIL_ON_ERROR = args.fail_on_error WARNING_AS_ERROR = args.warning_as_error if args.envfile: try: with open(args.envfile, 'r') as text_stream: env_str = text_stream.read() except (FileNotFoundError, IsADirectoryError): pass else: env = parse_env(env_str) os.environ.update(env) download_root_certs = args.download_root_cert or [] if args.download_all_root_certs: download_root_certs.extend(ROOT_CERT_DOWNLOADERS.keys()) for download_root_cert in download_root_certs: parts = download_root_cert.split('@', 1) source = parts[0] if len(parts) > 1: filename = parts[1] else: filename = get_default_root_cert_filename(source) source_upper = source.strip().upper() root_cert_downloader = ROOT_CERT_DOWNLOADERS.get(source_upper) if root_cert_downloader is None: if source_upper in DOWNLOADERS: raise KeyError(f'{source_upper} has no known root certificate') else: raise KeyError(f'Unknown trust list source: {source}') root_cert = root_cert_downloader() save_cert(root_cert, filename) certs_table: Dict[str, CertList] = {} if args.certs_table: sources = parse_sources(args.certs_table) all_certs: CertList = {} get_downloader = DOWNLOADERS.get header: List[str] = ['Key ID'] align: List[Align] = [Align.Left] for source in sources: header.append(source) align.append(Align.Center) downloader = get_downloader(source) if downloader is None: raise ValueError(f'Unknown trust list source: {source}') source_certs = downloader() certs_table[source] = source_certs all_certs.update(source_certs) def sort_key(key_id: bytes) -> Tuple[List[str], bytes]: countries: List[str] = [] for source in sources: cert = certs_table[source].get(key_id) if cert is not None: for attr in cert.subject.get_attributes_for_oid(NameOID.COUNTRY_NAME): countries.append(attr.value) return countries, key_id body: List[List[str]] = [] for key_id in sorted(all_certs, key=sort_key): row: List[str] = [b64encode(key_id).decode('ASCII')] for source in sources: cert = certs_table[source].get(key_id) if cert is None: cell = '' else: cell = ','.join(attr.value for attr in cert.subject.get_attributes_for_oid(NameOID.COUNTRY_NAME)) or 'X' row.append(cell) body.append(row) print_table(header, align, body) certs: Optional[CertList] = None if not args.no_verify or args.save_certs or args.list_certs: if args.certs_file: if args.certs_file.lower().endswith('.json'): with open(args.certs_file, 'rb') as fp: certs_data = fp.read() certs = load_hack_certs_json(certs_data, args.certs_file) else: certs = load_ehc_certs(args.certs_file) else: certs = download_ehc_certs(parse_sources(args.certs_from), certs_table) if not certs: print_err("empty trust list!") items: List[Tuple[bytes, x509.Certificate]] revoked_certs: Dict[bytes, x509.RevokedCertificate] = {} if args.list_certs or args.strip_revoked: items = list(certs.items()) items.sort(key=lambda item: (item[1].issuer.rfc4514_string(), item[1].subject.rfc4514_string(), item[0])) if args.strip_revoked: for key_id, cert in items: revoked_cert = get_revoked_cert(cert) if revoked_cert: revoked_certs[key_id] = revoked_cert revoked = True if args.list_certs: revoked_certs_for_print: Optional[Dict[bytes, x509.RevokedCertificate]] = revoked_certs if args.strip_revoked else None for key_id, cert in items: print_cert(key_id, cert, print_exts=args.print_exts, revoked_certs=revoked_certs_for_print) print() if args.strip_revoked: for key_id in revoked_certs: del certs[key_id] if args.save_certs: for certs_path in args.save_certs: save_certs(certs, certs_path, args.allow_public_key_only) ehc_codes: List[str] = [] if args.image: from pyzbar.pyzbar import decode as decode_qrcode # type: ignore from PIL import Image # type: ignore for filename in args.ehc_code: image = Image.open(filename, 'r') qrcodes = decode_qrcode(image) if qrcodes: for qrcode in qrcodes: ehc_codes.append(qrcode.data.decode("utf-8")) else: print_err(f'{filename}: no qr-code found') else: ehc_codes.extend(args.ehc_code) if args.no_verify: certs = None for ehc_code in ehc_codes: ehc_msg = decode_ehc(ehc_code) ehc_payload = cbor2.loads(ehc_msg.payload) for key, value in ehc_payload.items(): if key != -260: name = CLAIM_NAMES.get(key) if name is not None: if key in DATETIME_CLAIMS: dt = EPOCH + timedelta(seconds=value) value = dt.isoformat() else: name = f'Claim {key} (unknown)' print(f'{name:15}: {value}') issued_at = EPOCH + timedelta(seconds=ehc_payload[6]) expires_at_int = ehc_payload.get(4) if expires_at_int is not None: expires_at = EPOCH + timedelta(seconds=expires_at_int) print(f'Is Expired :', datetime.utcnow() > expires_at) if certs is not None: verify_ehc(ehc_msg, issued_at, certs, args.print_exts) ehc = ehc_payload[-260][1] print('Payload :') print(json.dumps(ehc, indent=4, sort_keys=True, default=json_serial)) print() if __name__ == '__main__': main()
#!/usr/bin/env python3 from typing import Tuple, Any, Dict, Optional, List, FrozenSet, Union, Type, Callable, Set import json import sys import zlib import re import os import argparse import codecs import hashlib import enum import shutil from os.path import splitext from datetime import date, datetime, timedelta, timezone from base64 import b64decode, b64encode, urlsafe_b64decode, urlsafe_b64encode import cbor2 # type: ignore import cose.algorithms # type: ignore import cose.keys.curves # type: ignore import cose.keys.keytype # type: ignore import requests import http.client import asn1crypto.cms # type: ignore from lxml.html import fromstring as parse_html # type: ignore from dateutil.parser import isoparse as parse_datetime from jose import jwt, jws, jwk # type: ignore from base45 import b45decode # type: ignore from requests.exceptions import BaseHTTPError # type: ignore from cose.headers import KID, Algorithm # type: ignore from cose.keys import CoseKey from cose.keys.curves import CoseCurve, P256, P384, P521 from cose.keys.keyops import VerifyOp # type: ignore from cose.keys.keyparam import KpAlg, EC2KpX, EC2KpY, EC2KpCurve, KpKty, RSAKpN, RSAKpE, KpKeyOps # type: ignore from cose.keys.keytype import KtyEC2, KtyRSA from cose.messages import CoseMessage, Sign1Message # type: ignore from cose.algorithms import Ps256, Es256 from cryptography import x509 from cryptography.x509 import load_der_x509_certificate, load_pem_x509_certificate, load_der_x509_crl, load_pem_x509_crl, Name, RelativeDistinguishedName, NameAttribute, Version, Extensions, Extension from cryptography.x509.extensions import ExtensionNotFound, ExtendedKeyUsage from cryptography.x509.name import _NAMEOID_TO_NAME from cryptography.x509.oid import NameOID, ObjectIdentifier, SignatureAlgorithmOID, ExtensionOID from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat, load_pem_public_key, load_der_public_key from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey, EllipticCurvePublicNumbers, ECDSA, SECP256R1, EllipticCurve from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey, RSAPublicNumbers from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 # based on: https://github.com/ehn-digital-green-development/ehn-sign-verify-python-trivial # Digital Green Certificate Gateway API SPEC: https://eu-digital-green-certificates.github.io/dgc-gateway/#/Trust%20Lists/downloadTrustList # But where is it hosted? # Extended Key Usage OIDs: VALID_FOR_TEST = ObjectIdentifier('1.3.6.1.4.1.1847.2021.1.1') VALID_FOR_VACCINATION = ObjectIdentifier('1.3.6.1.4.1.1847.2021.1.2') VALID_FOR_RECOVERY = ObjectIdentifier('1.3.6.1.4.1.1847.2021.1.3') EXT_KEY_USAGE_NAMES: Dict[ObjectIdentifier, str] = { VALID_FOR_TEST: 'test', VALID_FOR_VACCINATION: 'vaccination', VALID_FOR_RECOVERY: 'recovery', # these are bugs in some X.509 certificates: ObjectIdentifier('1.3.6.1.4.1.0.1847.2021.1.1'): 'test', ObjectIdentifier('1.3.6.1.4.1.0.1847.2021.1.2'): 'vaccination', ObjectIdentifier('1.3.6.1.4.1.0.1847.2021.1.3'): 'recovery', } EXT_KEY_USAGE_OIDS: Dict[str, ObjectIdentifier] = { 'test': VALID_FOR_TEST, 'vaccination': VALID_FOR_VACCINATION, 'recovery': VALID_FOR_RECOVERY, } FAIL_ON_ERROR = False WARNING_AS_ERROR = False # these would need parameters: 'blake2b', 'blake2s', 'sha512-224', 'sha512-256', 'shake256', 'shake128' HASH_ALGORITHMS: Dict[str, Type[hashes.HashAlgorithm]] = {} for attr_name in dir(hashes): attr = getattr(hashes, attr_name) if isinstance(attr, type): if isinstance(attr, type) and issubclass(attr, hashes.HashAlgorithm) and attr is not hashes.HashAlgorithm: HASH_ALGORITHMS[attr.name] = attr # type: ignore EPOCH = datetime(1970, 1, 1) CertList = Dict[bytes, x509.Certificate] JS_CERT_PATTERN = re.compile(r"'({[^-']*-----BEGIN[^']*)'") ESC = re.compile(r'\\x([0-9a-fA-F][0-9a-fA-F])') CURVE_NAME_IGNORE = re.compile(r'[-_ ]') MD_CERT_PATTERN = re.compile(r'(?P<url>https://[^()\s]+)[^-:]*(?P<cert>-----BEGIN CERTIFICATE-----[^-]*-----END CERTIFICATE-----\r?\n?)') # https://tools.ietf.org/search/rfc4492#appendix-A COSE_CURVES: Dict[str, Type[CoseCurve]] = { 'secp256r1': P256, 'prime256v1': P256, 'secp384r1': P384, 'secp521r1': P521, } NIST_CURVES: Dict[str, Type[EllipticCurve]] = { 'K-163': ec.SECT163K1, 'B-163': ec.SECT163R2, 'K-233': ec.SECT233K1, 'B-233': ec.SECT233R1, 'K-283': ec.SECT283K1, 'B-283': ec.SECT283R1, 'K-409': ec.SECT409K1, 'B-409': ec.SECT409R1, 'K-571': ec.SECT571K1, 'B-571': ec.SECT571R1, 'P-192': ec.SECP192R1, 'P-224': ec.SECP224R1, 'P-256': ec.SECP256R1, 'P-384': ec.SECP384R1, 'P-521': ec.SECP521R1, } SECG_TO_NIST_CURVES: Dict[str, str] = {curve.name: name for name, curve in NIST_CURVES.items()} # type: ignore NAME_OIDS = {name: name_oid for name_oid, name in _NAMEOID_TO_NAME.items()} NAME_OIDS_COVID_PASS_VERIFIER = dict( postalCode = NameOID.POSTAL_CODE, street = NameOID.STREET_ADDRESS, organizationIdentifier = NameOID.ORGANIZATION_NAME, serialNumber = NameOID.SERIAL_NUMBER, ) NAME_OIDS_COVID_PASS_VERIFIER.update(NAME_OIDS) for name in dir(cose.keys.curves): if not name.startswith('_'): curve = getattr(cose.keys.curves, name) if curve is not CoseCurve and isinstance(curve, type) and issubclass(curve, CoseCurve) and curve.fullname != 'RESERVED': # type: ignore name = CURVE_NAME_IGNORE.sub('', curve.fullname).lower() # type: ignore COSE_CURVES[name] = curve del name, curve PREFIX = 'HC1:' PREFIX_NO = 'NO1:' # Norway CLAIM_NAMES = { 1: "Issuer", 6: "Issued At", 4: "Expires At", -260: "Health Claims", } DATETIME_CLAIMS = {6, 4} # This is an old test trust list, not current! It includes test public keys too! OLD_CERTS_URL_AT = 'https://dgc.a-sit.at/ehn/cert/listv2' OLD_SIGNS_URL_AT = 'https://dgc.a-sit.at/ehn/cert/sigv2' # Trust List used by Austrian greencheck app: CERTS_URL_AT_GREENCHECK = 'https://greencheck.gv.at/api/masterdata' CERTS_URL_AT_PROD = 'https://dgc-trust.qr.gv.at/trustlist' SIGN_URL_AT_PROD = 'https://dgc-trust.qr.gv.at/trustlistsig' CERTS_URL_AT_TEST = 'https://dgc-trusttest.qr.gv.at/trustlist' SIGN_URL_AT_TEST = 'https://dgc-trusttest.qr.gv.at/trustlistsig' # only used for root kec extraction from greencheck JavaScript: ROOT_CERT_KEY_ID_AT = b'\xe0\x9f\xf7\x8f\x02R\x06\xb6' # See: https://github.com/Federal-Ministry-of-Health-AT/green-pass-overview # These root certs are copied from some presentation slides. # TODO: Link a proper source here once it becomes available? # # TODO: keep up to date # Not Before: Jun 2 13:46:21 2021 GMT # Not After : Jul 2 13:46:21 2022 GMT ROOT_CERT_AT_PROD = b'''\ -----BEGIN CERTIFICATE----- MIIB1DCCAXmgAwIBAgIKAXnM+Z3eG2QgVzAKBggqhkjOPQQDAjBEMQswCQYDVQQG EwJBVDEPMA0GA1UECgwGQk1TR1BLMQwwCgYDVQQFEwMwMDExFjAUBgNVBAMMDUFU IERHQyBDU0NBIDEwHhcNMjEwNjAyMTM0NjIxWhcNMjIwNzAyMTM0NjIxWjBFMQsw CQYDVQQGEwJBVDEPMA0GA1UECgwGQk1TR1BLMQ8wDQYDVQQFEwYwMDEwMDExFDAS BgNVBAMMC0FUIERHQyBUTCAxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEl2tm d16CBHXwcBN0r1Uy+CmNW/b2V0BNP85y5N3JZeo/8l9ey/jIe5mol9fFcGTk9bCk 8zphVo0SreHa5aWrQKNSMFAwDgYDVR0PAQH/BAQDAgeAMB0GA1UdDgQWBBRTwp6d cDGcPUB6IwdDja/a3ncM0TAfBgNVHSMEGDAWgBQfIqwcZRYptMGYs2Nvv90Jnbt7 ezAKBggqhkjOPQQDAgNJADBGAiEAlR0x3CRuQV/zwHTd2R9WNqZMabXv5XqwHt72 qtgnjRgCIQCZHIHbCvlgg5uL8ZJQzAxLavqF2w6uUxYVrvYDj2Cqjw== -----END CERTIFICATE----- ''' ROOT_CERT_AT_TEST = b'''\ -----BEGIN CERTIFICATE----- MIIB6zCCAZGgAwIBAgIKAXmEuohlRbR2qzAKBggqhkjOPQQDAjBQMQswCQYDVQQG EwJBVDEPMA0GA1UECgwGQk1TR1BLMQowCAYDVQQLDAFRMQwwCgYDVQQFEwMwMDEx FjAUBgNVBAMMDUFUIERHQyBDU0NBIDEwHhcNMjEwNTE5MTMwNDQ3WhcNMjIwNjE5 MTMwNDQ3WjBRMQswCQYDVQQGEwJBVDEPMA0GA1UECgwGQk1TR1BLMQowCAYDVQQL DAFRMQ8wDQYDVQQFEwYwMDEwMDExFDASBgNVBAMMC0FUIERHQyBUTCAxMFkwEwYH KoZIzj0CAQYIKoZIzj0DAQcDQgAE29KpT1eIKsy5Jx3J0xpPLW+fEBF7ma9943/j 4Z+o1TytLVok9cWjsdasWCS/zcRyAh7HBL+oyMWdFBOWENCQ76NSMFAwDgYDVR0P AQH/BAQDAgeAMB0GA1UdDgQWBBQYmsL5sXTdMCyW4UtP5BMxq+UAVzAfBgNVHSME GDAWgBR2sKi2xkUpGC1Cr5ehwL0hniIsJzAKBggqhkjOPQQDAgNIADBFAiBse17k F5F43q9mRGettRDLprASrxsDO9XxUUp3ObjcWQIhALfUWnserGEPiD7Pa25tg9lj wkrqDrMdZHZ39qb+Jf/E -----END CERTIFICATE----- ''' # Trust List used by German Digitaler-Impfnachweis app: CERTS_URL_DE = 'https://de.dscg.ubirch.com/trustList/DSC/' PUBKEY_URL_DE = 'https://github.com/Digitaler-Impfnachweis/covpass-ios/raw/main/Certificates/PROD_RKI/CA/pubkey.pem' # Netherlands public keys: # (https://www.npkd.nl/csca-health.html) # https://verifier-api.<acc/test/etc>.coronacheck.nl/v4/verifier/public_keys # json containing a CMS (rfc5652) signature and a payload. Both base64 encoded. # The payload is a json dictionary of the domestic and international keys. The # later is an dictionary with the KID as a base64 encoded key and a subkjectPK # and keyUsage array with the allowed use. Typical decode is: # curl https://verifier-api.acc.coronacheck.nl/v4/verifier/public_keys |\ # jq -r .payload |\ # base64 -d |\ # jq .eu_keys CERTS_URL_NL = 'https://verifier-api.coronacheck.nl/v4/verifier/public_keys' ROOT_CERT_URL_NL = 'http://cert.pkioverheid.nl/EVRootCA.cer' # Keys from a French validation app (nothing official, just a hobby project by someone): # https://github.com/lovasoa/sanipasse/blob/master/src/assets/Digital_Green_Certificate_Signing_Keys.json # French trust list: # This requires the environment variable FR_TOKEN to be set to a bearer token that can be found in the TousAntiCovid Verif app. CERTS_URL_FR = 'https://portail.tacv.myservices-ingroupe.com/api/client/configuration/synchronisation/tacv' # Sweden (JOSE encoded): CERTS_URL_SE = 'https://dgcg.covidbevis.se/tp/trust-list' ROOT_CERT_URL_SE = 'https://dgcg.covidbevis.se/tp/cert' # See: https://github.com/DIGGSweden/dgc-trust/blob/main/specifications/trust-list.md # United Kingdom trust list: CERTS_URL_GB = 'https://covid-status.service.nhsx.nhs.uk/pubkeys/keys.json' CERTS_URL_COVID_PASS_VERIFIER = 'https://covid-pass-verifier.com/assets/certificates.json' # Norwegian trust list: CERTS_URL_NO = 'https://koronakontroll.nhn.no/v2/publickey' # Norwegian COVID-19 certificates seem to be based on the European Health Certificate but just with an 'NO1:' prefix. # https://harrisonsand.com/posts/covid-certificates/ # Switzerland: # See: https://github.com/cn-uofbasel/ch-dcc-keys ROOT_CERT_URL_CH = 'https://www.bit.admin.ch/dam/bit/en/dokumente/pki/scanning_center/swiss_governmentrootcaii.crt.download.crt/swiss_governmentrootcaii.crt' CERTS_URL_CH = 'https://www.cc.bit.admin.ch/trust/v1/keys/list' UPDATE_URL_CH = 'https://www.cc.bit.admin.ch/trust/v1/keys/updates?certFormat=ANDROID' USER_AGENT = 'Mozilla/5.0 (Windows) Firefox/90.0' # See also this thread: # https://github.com/eu-digital-green-certificates/dgc-participating-countries/issues/10 DEFAULT_NOT_VALID_BEFORE = datetime(1970, 1, 1, tzinfo=timezone.utc) DEFAULT_NOT_VALID_AFTER = datetime(9999, 12, 31, 23, 59, 59, 999999, tzinfo=timezone.utc) class HackCertificate(x509.Certificate): _public_key: Union[EllipticCurvePublicKey, RSAPublicKey] _issuer: Name _subject: Name _extensions: Extensions _not_valid_before: datetime _not_valid_after: datetime def __init__(self, public_key: Union[EllipticCurvePublicKey, RSAPublicKey], issuer: Optional[Name] = None, subject: Optional[Name] = None, not_valid_before: datetime = DEFAULT_NOT_VALID_BEFORE, not_valid_after: datetime = DEFAULT_NOT_VALID_AFTER, extensions: Optional[Extensions] = None, ): self._public_key = public_key self._issuer = issuer if issuer is not None else Name([]) self._subject = subject if subject is not None else Name([]) self._extensions = extensions if extensions is not None else Extensions([]) self._not_valid_before = not_valid_before self._not_valid_after = not_valid_after def fingerprint(self, algorithm: hashes.HashAlgorithm) -> bytes: raise NotImplementedError @property def extensions(self) -> Extensions: return self._extensions @property def signature(self) -> bytes: return b'' @property def tbs_certificate_bytes(self) -> bytes: return b'' def __eq__(self, other: object) -> bool: if not isinstance(other, HackCertificate): return False return self.__as_tuple() == other.__as_tuple() def __ne__(self, other: object) -> bool: if not isinstance(other, HackCertificate): return True return self.__as_tuple() != other.__as_tuple() def __as_tuple(self) -> Tuple[Union[EllipticCurvePublicKey, RSAPublicKey], Name, Name, Extensions]: return (self._public_key, self._issuer, self._subject, self._extensions) def __hash__(self) -> int: return hash(self.__as_tuple()) @property def serial_number(self) -> int: return 0 @property def issuer(self) -> Name: return self._issuer @property def subject(self) -> Name: return self._subject @property def version(self) -> Version: return Version.v1 @property def signature_algorithm_oid(self) -> ObjectIdentifier: raise NotImplementedError @property def signature_hash_algorithm(self): raise NotImplementedError @property def not_valid_before(self) -> datetime: return self._not_valid_before @property def not_valid_after(self) -> datetime: return self._not_valid_after def public_key(self): return self._public_key def public_bytes(self, encoding: Encoding): raise NotImplementedError("cannot serialize certificate from public-key only") #return self._public_key.public_bytes(encoding, PublicFormat.SubjectPublicKeyInfo) def json_serial(obj: Any) -> str: """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError(f"Type {type(obj)} not serializable") def load_ehc_certs(filename: str) -> CertList: with open(filename, 'rb') as stream: certs_cbor = stream.read() return load_ehc_certs_cbor(certs_cbor, filename) def load_ehc_certs_cbor(cbor_data: bytes, source: str) -> CertList: certs_data = cbor2.loads(cbor_data) certs: CertList = {} for item in certs_data['c']: try: key_id = item['i'] cert_data = item.get('c') if cert_data: cert = load_der_x509_certificate(cert_data) fingerprint = cert.fingerprint(hashes.SHA256()) if key_id != fingerprint[0:8]: raise ValueError(f'Key ID missmatch: {key_id.hex()} != {fingerprint[0:8].hex()}') else: pubkey_data = item['k'] pubkey = load_der_public_key(pubkey_data) issuer_dict = item.get('is') issuer = parse_json_relative_distinguished_name(issuer_dict) if issuer_dict is not None else Name([]) subject_dict = item.get('su') subject = parse_json_relative_distinguished_name(subject_dict) if subject_dict is not None else Name([]) nb = item.get('nb') not_valid_before = EPOCH + timedelta(seconds=nb) if nb is not None else DEFAULT_NOT_VALID_BEFORE na = item.get('na') not_valid_after = EPOCH + timedelta(seconds=na) if na is not None else DEFAULT_NOT_VALID_AFTER if isinstance(pubkey, (EllipticCurvePublicKey, RSAPublicKey)): cert = HackCertificate(pubkey, not_valid_before = not_valid_before, not_valid_after = not_valid_after, issuer = issuer, subject = subject, ) else: pubkey_type = type(pubkey) raise NotImplementedError(f'Unsupported public key type: {pubkey_type.__module__}.{pubkey_type.__name__}') if key_id in certs: print_warn(f'doubled key ID in {source} trust list, only using last: {format_key_id(key_id)}') except Exception as error: print_err(f'decoding {source} trust list entry {format_key_id(key_id)}: {error}') else: certs[key_id] = cert return certs def make_json_relative_distinguished_name(name: Name) -> Dict[str, str]: return {_NAMEOID_TO_NAME.get(attr.oid, attr.oid.dotted_string): attr.value for attr in reversed(list(name))} def parse_json_relative_distinguished_name(name_dict: Dict[str, str]) -> Name: name_attrs: List[NameAttribute] = [] for attr_type_str, attr_value in name_dict.items(): attr_type = NAME_OIDS.get(attr_type_str) or ObjectIdentifier(attr_type_str) name_attrs.append(NameAttribute(attr_type, attr_value)) return Name(name_attrs) def load_hack_certs_json(data: bytes, source: str) -> CertList: certs_dict = json.loads(data) certs: CertList = {} for key_id_hex, cert_dict in certs_dict['trustList'].items(): not_valid_before = parse_datetime(cert_dict['notValidBefore']) not_valid_after = parse_datetime(cert_dict['notValidAfter']) issuer = parse_json_relative_distinguished_name(cert_dict['issuer']) if 'issuer' in cert_dict else Name([]) subject = parse_json_relative_distinguished_name(cert_dict['subject']) if 'subject' in cert_dict else Name([]) pubkey_dict = cert_dict['publicKey'] usage = cert_dict.get('usage') exts: List[Extension] = [] if usage is not None: usage_oids: List[ObjectIdentifier] = [] for use in usage: oid = EXT_KEY_USAGE_OIDS[use] usage_oids.append(oid) exts.append(Extension(ExtensionOID.EXTENDED_KEY_USAGE, False, ExtendedKeyUsage(usage_oids))) extensions = Extensions(exts) key_id = urlsafe_b64decode_ignore_padding(pubkey_dict['kid']) key_type = pubkey_dict['kty'] if key_type == 'EC': curve_name = pubkey_dict['crv'] curve_type = NIST_CURVES.get(curve_name) if not curve_type: raise ValueError(f'unknown elliptic curve: {curve_name!r}') curve = curve_type() x_bytes = urlsafe_b64decode_ignore_padding(pubkey_dict['x']) y_bytes = urlsafe_b64decode_ignore_padding(pubkey_dict['y']) x = int.from_bytes(x_bytes, byteorder="big", signed=False) y = int.from_bytes(y_bytes, byteorder="big", signed=False) ec_pubkey = EllipticCurvePublicNumbers(x, y, curve).public_key() cert = HackCertificate(ec_pubkey, issuer, subject, not_valid_before, not_valid_after, extensions=extensions) if key_id in certs: print_warn(f'doubled key ID in {source} trust list, only using last: {format_key_id(key_id)}') certs[key_id] = cert elif key_type == 'RSA': e_bytes = urlsafe_b64decode_ignore_padding(pubkey_dict['e']) n_bytes = urlsafe_b64decode_ignore_padding(pubkey_dict['n']) e = int.from_bytes(e_bytes, byteorder="big", signed=False) n = int.from_bytes(n_bytes, byteorder="big", signed=False) rsa_pubkey = RSAPublicNumbers(e, n).public_key() cert = HackCertificate(rsa_pubkey, issuer, subject, not_valid_before, not_valid_after, extensions=extensions) if key_id in certs: print_warn(f'doubled key ID in {source} trust list, only using last: {format_key_id(key_id)}') certs[key_id] = cert else: print_err(f'decoding {source} trust list: illegal key type: {key_type!r}') return certs def print_err(msg: str) -> None: if FAIL_ON_ERROR: raise Exception(msg) else: # so that errors and normal output is correctly interleaved: sys.stdout.flush() print(f'ERROR: {msg}', file=sys.stderr) def print_warn(msg: str) -> None: if WARNING_AS_ERROR: print_err(msg) else: # so that errors and normal output is correctly interleaved: sys.stdout.flush() print(f'WARNING: {msg}', file=sys.stderr) def load_de_trust_list(data: bytes, pubkey: Optional[EllipticCurvePublicKey] = None) -> CertList: certs: CertList = {} sign_b64, body_json = data.split(b'\n', 1) sign = b64decode(sign_b64) body = json.loads(body_json) if pubkey is not None: r = int.from_bytes(sign[:len(sign)//2], byteorder="big", signed=False) s = int.from_bytes(sign[len(sign)//2:], byteorder="big", signed=False) sign_dds = encode_dss_signature(r, s) try: pubkey.verify(sign_dds, body_json, ECDSA(hashes.SHA256())) except InvalidSignature: raise ValueError(f'Invalid signature of DE trust list: {sign.hex()}') for cert in body['certificates']: try: key_id_b64 = cert['kid'] key_id = b64decode(key_id_b64) country = cert['country'] cert_type = cert['certificateType'] if cert_type != 'DSC': raise ValueError(f'unknown certificateType {cert_type!r} (country={country}, kid={key_id.hex()}') raw_data = b64decode(cert['rawData']) cert = load_der_x509_certificate(raw_data) fingerprint = cert.fingerprint(hashes.SHA256()) if key_id != fingerprint[0:8]: raise ValueError(f'Key ID missmatch: {key_id.hex()} != {fingerprint[0:8].hex()}') if key_id in certs: print_warn(f'doubled key ID in DE trust list, only using last: {format_key_id(key_id)}') except Exception as error: print_err(f'decoding DE trust list entry {format_key_id(key_id)}: {error}') else: certs[key_id] = cert return certs def download_at_greencheck_certs() -> CertList: response = requests.get(CERTS_URL_AT_GREENCHECK, headers={'User-Agent': USER_AGENT}) response.raise_for_status() certs_json = json.loads(response.content)['trustList'] certs_cbor = b64decode(certs_json['trustListContent']) certs_sig = b64decode(certs_json['trustListSignature']) sig_msg = CoseMessage.decode(certs_sig) if not isinstance(sig_msg, Sign1Message): msg_type = type(sig_msg) raise TypeError(f'AT trust list: expected signature to be a Sign1 COSE message, but is: {msg_type.__module__}.{msg_type.__name__}') root_cert_key_id = sig_msg.phdr.get(KID) or sig_msg.uhdr[KID] root_cert: Optional[x509.Certificate] = None try: root_cert = get_at_greencheck_root_cert(root_cert_key_id) except (BaseHTTPError, ValueError, KeyError) as error: print_err(f'AT trust list error (NOT VALIDATING): {error}') if root_cert: now = datetime.utcnow() if now < root_cert.not_valid_before: raise ValueError(f'AT trust list root certificate not yet valid: {now.isoformat()} < {root_cert.not_valid_before.isoformat()}') if now > root_cert.not_valid_after: raise ValueError(f'AT trust list root certificate already expired: {now.isoformat()} > {root_cert.not_valid_after.isoformat()}') sig_msg.key = cert_to_cose_key(root_cert) if not sig_msg.verify_signature(): raise ValueError(f'Invalid signature of AT trust list: {sig_msg.signature.hex()}') sig = cbor2.loads(sig_msg.payload) digest = hashlib.sha256(certs_cbor).digest() if sig[2] != digest: raise ValueError(f'Invalid hash of AT trust list. expected: {sig[2].hex()}, actual: {digest.hex()}') created_at = EPOCH + timedelta(seconds=sig[5]) # I guess? Or "not valid before"? expires_at = EPOCH + timedelta(seconds=sig[4]) if now > expires_at: raise ValueError(f'AT trust list already expired at {expires_at.isoformat()}') else: print_err(f'root certificate for AT trust list not found!') return load_ehc_certs_cbor(certs_cbor, 'AT') def download_at_certs(test: bool = False, token: Optional[str] = None) -> CertList: # TODO: update to handle tokens once required #if token is None: # token = os.getenv('AT_TOKEN') # if token is None: # raise KeyError( # 'Required environment variable AT_TOKEN for AT trust list is not set. ' # 'Information about how to get a token will follow soon.') if test: certs_url = CERTS_URL_AT_TEST sign_url = SIGN_URL_AT_TEST root_cert = get_root_cert('AT-TEST') else: certs_url = CERTS_URL_AT_PROD sign_url = SIGN_URL_AT_PROD root_cert = get_root_cert('AT') response = requests.get(certs_url, headers={'User-Agent': USER_AGENT}) #response = requests.get(certs_url, headers={ # 'User-Agent': USER_AGENT, # 'Authorization': f'Bearer {token}', #}) response.raise_for_status() certs_cbor = response.content response = requests.get(sign_url, headers={'User-Agent': USER_AGENT}) #response = requests.get(sign_url, headers={ # 'User-Agent': USER_AGENT, # 'Authorization': f'Bearer {token}', #}) response.raise_for_status() certs_sig = response.content sig_msg = CoseMessage.decode(certs_sig) if not isinstance(sig_msg, Sign1Message): msg_type = type(sig_msg) raise TypeError(f'AT trust list: expected signature to be a Sign1 COSE message, but is: {msg_type.__module__}.{msg_type.__name__}') root_cert_key_id = sig_msg.phdr.get(KID) or sig_msg.uhdr[KID] key_id = root_cert.fingerprint(hashes.SHA256())[:8] if key_id != root_cert_key_id: raise ValueError(f'AT trust list root certificate key ID missmatch. {key_id.hex()} != {root_cert_key_id.hex()}') now = datetime.utcnow() if now < root_cert.not_valid_before: raise ValueError(f'AT trust list root certificate not yet valid: {now.isoformat()} < {root_cert.not_valid_before.isoformat()}') if now > root_cert.not_valid_after: raise ValueError(f'AT trust list root certificate already expired: {now.isoformat()} > {root_cert.not_valid_after.isoformat()}') sig_msg.key = cert_to_cose_key(root_cert) if not sig_msg.verify_signature(): raise ValueError(f'Invalid signature of AT trust list: {sig_msg.signature.hex()}') sig = cbor2.loads(sig_msg.payload) digest = hashlib.sha256(certs_cbor).digest() if sig[2] != digest: raise ValueError(f'Invalid hash of AT trust list. expected: {sig[2].hex()}, actual: {digest.hex()}') created_at = EPOCH + timedelta(seconds=sig[5]) # I guess? Or "not valid before"? expires_at = EPOCH + timedelta(seconds=sig[4]) if now > expires_at: raise ValueError(f'AT trust list already expired at {expires_at.isoformat()}') return load_ehc_certs_cbor(certs_cbor, 'AT') def download_de_certs() -> CertList: response = requests.get(CERTS_URL_DE, headers={'User-Agent': USER_AGENT}) response.raise_for_status() certs_signed_json = response.content pubkey: Optional[EllipticCurvePublicKey] = None try: pubkey = get_root_cert('DE').public_key() # type: ignore except (BaseHTTPError, ValueError) as error: print_err(f'DE trust list error (NOT VALIDATING): {error}') return load_de_trust_list(certs_signed_json, pubkey) def download_se_certs() -> CertList: certs: CertList = {} root_cert: Optional[x509.Certificate] = None try: root_cert = get_root_cert('SE') except (BaseHTTPError, ValueError) as error: print_err(f'SE trust list error (NOT VALIDATING): {error}') response = requests.get(CERTS_URL_SE, headers={'User-Agent': USER_AGENT}) response.raise_for_status() if root_cert is None: token = jwt.get_unverified_claims(response.content.decode(response.encoding or 'UTF-8')) else: token = load_jwt(response.content, root_cert, {'verify_aud': False}) for country, country_keys in token['dsc_trust_list'].items(): for entry in country_keys['keys']: key_id = b64decode(entry['kid']) for key_data in entry['x5c']: try: cert = load_der_x509_certificate(b64decode_ignore_padding(key_data)) fingerprint = cert.fingerprint(hashes.SHA256()) if key_id != fingerprint[0:8]: raise ValueError(f'Key ID missmatch: {key_id.hex()} != {fingerprint[0:8].hex()}') if key_id in certs: print_warn(f'doubled key ID in SE trust list, only using last: {format_key_id(key_id)}') except Exception as error: print_err(f'decoding SE trust list entry {key_id.hex()} / {b64encode(key_id).decode("ASCII")}: {error}') else: certs[key_id] = cert return certs def download_covid_pass_verifier_certs() -> CertList: certs: CertList = {} response = requests.get(CERTS_URL_COVID_PASS_VERIFIER, headers={'User-Agent': USER_AGENT}) response.raise_for_status() certs_json = json.loads(response.content) for entry in certs_json: key_id = bytes(entry['kid']) cert_der = bytes(entry['crt']) if cert_der: try: cert = load_der_x509_certificate(cert_der) except Exception as error: print_err(f'decoding covid-pass-verifier.com trust list entry {format_key_id(key_id)}: {error}') else: fingerprint = cert.fingerprint(hashes.SHA256()) if key_id != fingerprint[0:8]: raise ValueError(f'Key ID missmatch: {key_id.hex()} != {fingerprint[0:8].hex()}') if key_id in certs: print_warn(f'doubled key ID in covid-pass-verifier.com trust list, only using last: {format_key_id(key_id)}') certs[key_id] = cert else: iss = entry.get('iss') if iss: issuer = Name([NameAttribute(NAME_OIDS_COVID_PASS_VERIFIER.get(key) or ObjectIdentifier(key), value) for key, value in iss.items()]) else: issuer = Name([]) sub = entry.get('sub') if sub: subject = Name([NameAttribute(NAME_OIDS_COVID_PASS_VERIFIER.get(key) or ObjectIdentifier(key), value) for key, value in sub.items()]) else: subject = Name([]) pub = entry['pub'] if 'x' in pub and 'y' in pub: # EC x_bytes = bytes(pub['x']) y_bytes = bytes(pub['y']) x = int.from_bytes(x_bytes, byteorder="big", signed=False) y = int.from_bytes(y_bytes, byteorder="big", signed=False) curve = SECP256R1() ec_pubkey = EllipticCurvePublicNumbers(x, y, curve).public_key() cert = HackCertificate(ec_pubkey, issuer, subject) if key_id in certs: print_warn(f'doubled key ID in covid-pass-verifier.com trust list, only using last: {format_key_id(key_id)}') certs[key_id] = cert elif 'n' in pub and 'e' in pub: # RSA e_bytes = bytes(pub['e']) n_bytes = bytes(pub['n']) e = int.from_bytes(e_bytes, byteorder="big", signed=False) n = int.from_bytes(n_bytes, byteorder="big", signed=False) rsa_pubkey = RSAPublicNumbers(e, n).public_key() cert = HackCertificate(rsa_pubkey, issuer, subject) if key_id in certs: print_warn(f'doubled key ID in covid-pass-verifier.com trust list, only using last: {format_key_id(key_id)}') certs[key_id] = cert else: print_err(f'decoding covid-pass-verifier.com trust list entry {format_key_id(key_id)}: no supported public key data found') return certs def download_fr_certs(token: Optional[str] = None) -> CertList: certs: CertList = {} if token is None: token = os.getenv('FR_TOKEN') if token is None: raise KeyError( 'Required environment variable FR_TOKEN for FR trust list is not set. ' 'You can get the value of the token from the TousAntiCovid Verif app APK.') response = requests.get(CERTS_URL_FR, headers={ 'User-Agent': USER_AGENT, 'Authorization': f'Bearer {token}', }) response.raise_for_status() certs_json = json.loads(response.content) for key_id_b64, cert_b64 in certs_json['certificatesDCC'].items(): try: key_id = b64decode_ignore_padding(key_id_b64) cert_pem = b64decode(cert_b64) # Yes, they encode it twice! cert_der = b64decode(cert_pem) try: cert = load_der_x509_certificate(cert_der) except ValueError: cert = load_hack_certificate_from_der_public_key(cert_der) # HackCertificate.fingerprint() is not implemented else: fingerprint = cert.fingerprint(hashes.SHA256()) if key_id != fingerprint[0:8]: pubkey = cert.public_key() attrs = cert.subject.get_attributes_for_oid(NameOID.COUNTRY_NAME) if attrs and all(attr.value == 'UK' for attr in attrs) and isinstance(pubkey, (RSAPublicKey, EllipticCurvePublicKey)): # replace fake FR trust list certificate by my own fake certificate # XXX: not eintirely sure if I should do this? issuer = [attr for attr in cert.issuer if attr.oid != NameOID.COUNTRY_NAME] subject = [attr for attr in cert.subject if attr.oid != NameOID.COUNTRY_NAME] issuer.append( NameAttribute(NameOID.COUNTRY_NAME, 'GB')) subject.append(NameAttribute(NameOID.COUNTRY_NAME, 'GB')) cert = HackCertificate( pubkey, issuer = Name(issuer), subject = Name(subject), not_valid_before = cert.not_valid_before, not_valid_after = cert.not_valid_after, ) else: #print() #print_cert(key_id, cert, print_exts=True) raise ValueError(f'Key ID missmatch: {key_id.hex()} != {fingerprint[0:8].hex()}') if key_id in certs: print_warn(f'doubled key ID in FR trust list, only using last: {format_key_id(key_id)}') except Exception as error: print_err(f'decoding FR trust list entry {format_key_id(key_id)}: {error}') else: certs[key_id] = cert return certs def build_trust_chain(certs: List[x509.Certificate]) -> Dict[bytes, x509.Certificate]: trustchain: Dict[bytes, x509.Certificate] = {} for cert in certs: subject_key_id = cert.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_KEY_IDENTIFIER).value.digest trustchain[subject_key_id] = cert return trustchain def verify_trust_chain(cert: x509.Certificate, trustchain: Dict[bytes, x509.Certificate], root_cert: x509.Certificate) -> bool: signed_cert = cert rsa_padding = PKCS1v15() root_subject_key_id = root_cert.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_KEY_IDENTIFIER).value.digest visited: Set[bytes] = set() while signed_cert is not root_cert: auth_key_id = signed_cert.extensions.get_extension_for_oid(ExtensionOID.AUTHORITY_KEY_IDENTIFIER).value.key_identifier if auth_key_id in visited: raise ValueError('loop in trust chain detected') visited.add(auth_key_id) issuer_cert: Optional[x509.Certificate] if root_subject_key_id == auth_key_id: issuer_cert = root_cert else: issuer_cert = trustchain.get(auth_key_id) if issuer_cert == root_cert: # just to be sure that there is no trickery: issuer_cert = root_cert if issuer_cert is None: auth_key_id_str = ':'.join('%02X' % x for x in auth_key_id) fingerprint = signed_cert.fingerprint(hashes.SHA256()) fingerprint_str = ':'.join('%02X' % x for x in fingerprint) print_err(f'Could not verify signature of a certificate in the trust chain.\n' f'fingerprint: {fingerprint_str}\n' f'authority key ID: {auth_key_id_str}') return False pubkey = issuer_cert.public_key() try: if isinstance(pubkey, RSAPublicKey): pubkey.verify( signed_cert.signature, signed_cert.tbs_certificate_bytes, rsa_padding, signed_cert.signature_hash_algorithm, # type: ignore ) elif isinstance(pubkey, EllipticCurvePublicKey): pubkey.verify( signed_cert.signature, signed_cert.tbs_certificate_bytes, ECDSA(signed_cert.signature_hash_algorithm), ) else: pubkey_type = type(pubkey) raise NotImplementedError(f'Unsupported public key type: {pubkey_type.__module__}.{pubkey_type.__name__}') except InvalidSignature: try: subject_key_id = signed_cert.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_KEY_IDENTIFIER).value.digest except ExtensionNotFound: subject_key_id_str = 'N/A' else: subject_key_id_str = ':'.join('%02X' % x for x in subject_key_id) fingerprint = signed_cert.fingerprint(hashes.SHA256()) fingerprint_str = ':'.join('%02X' % x for x in fingerprint) print_err(f'Could not verify signature of a certificate in the trust chain.\n' f'fingerprint: {fingerprint_str}\n' f'subject key ID: {subject_key_id_str}') return False signed_cert = issuer_cert return True def verify_pkcs7_detached_signature(payload: bytes, signature: bytes, root_cert: x509.Certificate) -> bool: content_info = asn1crypto.cms.ContentInfo.load(signature) content = content_info['content'] cert_set = content['certificates'] certs: List[x509.Certificate] = [] for asn1cert in cert_set: if asn1cert.name == 'certificate': certs.append(load_der_x509_certificate(asn1cert.chosen.dump())) else: raise NotImplementedError(f'Certificate option in trust chain not supported: {asn1cert.name}') trustchain = build_trust_chain(certs) certs_by_serial: Optional[Dict[int, x509.Certificate]] = None for signer_info in content['signer_infos']: sid = signer_info['sid'] if sid.name == 'issuer_and_serial_number': if certs_by_serial is None: # lazily create this mapping only if needed certs_by_serial = {} for cert in certs: serial_number = cert.serial_number if serial_number in certs_by_serial: raise ValueError(f'Doubled serial number in trust chain: {serial_number}') certs_by_serial[serial_number] = cert serial_number = sid.chosen['serial_number'].native cert = certs_by_serial[serial_number] elif sid.name == 'subject_key_identifier': cert = trustchain[sid.chosen.native] if not verify_trust_chain(cert, trustchain, root_cert): return False pubkey = cert.public_key() digest_algo = signer_info['digest_algorithm']['algorithm'].native digest = hashlib.new(digest_algo, payload).digest() sig_algo = signer_info['signature_algorithm']['algorithm'].native signed_attrs = signer_info['signed_attrs'] # see: https://datatracker.ietf.org/doc/html/rfc5652#section-5.4 signed_data: Union[bytes, bytearray] if signed_attrs: has_message_digest = False for signed_attr in signed_attrs: if signed_attr['type'].native == 'message_digest': for msg_digest in signed_attr['values'].native: has_message_digest = True if digest != msg_digest: print_err(f'Payload digest missmatch.\n' f'expected: {msg_digest.hex()}\n' f'actual: {digest.hex()}') return False if not has_message_digest: raise ValueError(f'Message digest signed attribute is missing.') signed_attrs_bytes = bytearray(signed_attrs.dump()) #signed_attrs_bytes[0] = ASN1_SET | ASN1_CONSTRUCTED signed_attrs_bytes[0] = 0x11 | 0x20 signed_data = signed_attrs_bytes else: signed_data = payload sign = signer_info['signature'].native try: if isinstance(pubkey, RSAPublicKey): if sig_algo != 'rsassa_pkcs1v15': raise NotImplementedError(f'Unsupported signature algorithm: {sig_algo}') pubkey.verify( sign, signed_data, PKCS1v15(), HASH_ALGORITHMS[digest_algo](), # type: ignore ) elif isinstance(pubkey, EllipticCurvePublicKey): pubkey.verify( sign, signed_data, ECDSA(HASH_ALGORITHMS[digest_algo]()), ) else: pubkey_type = type(pubkey) raise NotImplementedError(f'Unsupported public key type: {pubkey_type.__module__}.{pubkey_type.__name__}') except InvalidSignature: return False return True def download_nl_certs(token: Optional[str] = None) -> CertList: # Fetch the root certificate for the Netherlands; used to secure the # trust list. Non fatal error if this fails. root_cert: Optional[x509.Certificate] = None try: root_cert = get_root_cert('NL') except (BaseHTTPError, ValueError) as error: print_err(f'NL trust list error (NOT VALIDATING): {error}') certs: CertList = {} response = requests.get(CERTS_URL_NL, headers={'User-Agent': USER_AGENT}) response.raise_for_status() certs_json = json.loads(response.content) payload = b64decode(certs_json['payload']) if root_cert is not None: # Signature is a CMS (rfc5652) detached signature of the payload. # The certificate chain in this pkcs#7 signature rolls up to the # rootkey of the Kingdom of the Netherlands (https://www.pkioverheid.nl) # signature = b64decode(certs_json['signature']) try: valid = verify_pkcs7_detached_signature(payload, signature, root_cert) except (NotImplementedError, ValueError) as error: print_err(f'NL trust list error (NOT VALIDATING): {error}') else: if not valid: raise ValueError(f'Invalid signature of NL trust list: {signature.hex()}') payload_dict = json.loads(payload) # We ignore the 'nl_keys' - these are for the domestic QR codes; which are # privacy preserving C.L. signature based to allow for unlinkability as to # prevent tracking/surveilance. # for key_id_b64, pubkeys in payload_dict['eu_keys'].items(): try: key_id = b64decode(key_id_b64) for entry in pubkeys: try: # XXX: Why is subjectPk an array? How can there be more than one key to a key ID? pubkey_der = b64decode(entry['subjectPk']) # entry['keyUsage'] is array of 't' or 'v' or 'r' cert = load_hack_certificate_from_der_public_key(pubkey_der) if key_id in certs: print_warn(f'doubled key ID in NL trust list, only using last: {format_key_id(key_id)}') except Exception as error: print_err(f'decoding NL trust list entry {format_key_id(key_id)}: {error}') else: certs[key_id] = cert except Exception as error: print_err(f'decoding NL trust list entry {format_key_id(key_id)}: {error}') return certs CH_USER_AGENT = 'ch.admin.bag.covidcertificate.wallet;2.1.1;1626211804080;Android;28' def get_ch_token() -> str: token = os.getenv('CH_TOKEN') if token is None: raise KeyError( "Required environment variable CH_TOKEN for CH trust list is not set. " "You can get the value of the token from the BIT's Android CovidCertificate app APK.") return token def download_ch_certs(token: Optional[str] = None) -> CertList: if token is None: token = get_ch_token() root_cert: Optional[x509.Certificate] = None try: root_cert = get_root_cert('CH') except (BaseHTTPError, ValueError) as error: print_err(f'CH trust list error (NOT VALIDATING): {error}') response = requests.get(CERTS_URL_CH, headers={ 'User-Agent': CH_USER_AGENT, 'Accept': 'application/json+jws', 'Accept-Encoding': 'gzip', 'Authorization': f'Bearer {token}', }) response.raise_for_status() if root_cert is None: certs_token = jwt.get_unverified_claims(response.content.decode(response.encoding or 'UTF-8')) else: certs_token = load_jwt(response.content, root_cert) active_key_ids_b64 = certs_token['activeKeyIds'] active_key_ids = frozenset(b64decode(key_id_b64) for key_id_b64 in active_key_ids_b64) response = requests.get(UPDATE_URL_CH, headers={ 'User-Agent': CH_USER_AGENT, 'Accept': 'application/json+jws', 'Accept-Encoding': 'gzip', 'Authorization': f'Bearer {token}', }) response.raise_for_status() if root_cert is None: update_token = jwt.get_unverified_claims(response.content.decode(response.encoding or 'UTF-8')) else: update_token = load_jwt(response.content, root_cert) pubkeys: List[Dict[str, Optional[str]]] = update_token['certs'] certs: CertList = {} for pub in pubkeys: try: key_id = b64decode(pub['keyId']) # type: ignore if key_id in active_key_ids: alg = pub['alg'] usage: str = pub.get('use', 'tvr') # type: ignore usages: List[ObjectIdentifier] = [] if usage != 'sig': if 't' in usage: usages.append(VALID_FOR_TEST) if 'v' in usage: usages.append(VALID_FOR_VACCINATION) if 'r' in usage: usages.append(VALID_FOR_RECOVERY) exts: List[Extension] = [] if usages: exts.append(Extension(ExtensionOID.EXTENDED_KEY_USAGE, False, ExtendedKeyUsage(usages))) extensions = Extensions(exts) if alg == 'ES256': # EC x_bytes = b64decode(pub['x']) # type: ignore y_bytes = b64decode(pub['y']) # type: ignore x = int.from_bytes(x_bytes, byteorder="big", signed=False) y = int.from_bytes(y_bytes, byteorder="big", signed=False) crv: str = pub['crv'] # type: ignore curve = NIST_CURVES[crv]() ec_pubkey = EllipticCurvePublicNumbers(x, y, curve).public_key() cert = HackCertificate(ec_pubkey, extensions=extensions) elif alg == 'RS256': # RSA e_bytes = b64decode(pub['e']) # type: ignore n_bytes = b64decode(pub['n']) # type: ignore e = int.from_bytes(e_bytes, byteorder="big", signed=False) n = int.from_bytes(n_bytes, byteorder="big", signed=False) rsa_pubkey = RSAPublicNumbers(e, n).public_key() cert = HackCertificate(rsa_pubkey, extensions=extensions) else: raise NotImplementedError(f'algorithm not supported: {alg!r}') if key_id in certs: print_warn(f'doubled key ID in CH trust list, only using last: {format_key_id(key_id)}') certs[key_id] = cert except Exception as error: print_err(f'decoding CH trust list entry {format_key_id(key_id)}: {error}') return certs def download_no_certs(token: Optional[str] = None) -> CertList: NO_USER_AGENT = 'FHICORC/38357 CFNetwork/1240.0.4 Darwin/20.5.0' if token is None: token = os.getenv('NO_TOKEN') if token is None: raise KeyError( "Required environment variable NO_TOKEN for NO trust list is not set. " "You can get the value of the token from the Kontroll av koronasertifikat app APK.") response = requests.get(CERTS_URL_NO, headers={ 'User-Agent': NO_USER_AGENT, 'Authorization': token, }) response.raise_for_status() certs: CertList = {} # TODO: find out if there is some sort of root cert to verify the trust list? certs_json = json.loads(response.content) for entry in certs_json: key_id = b64decode(entry['kid']) pubkey_der = b64decode(entry['publicKey']) cert = load_hack_certificate_from_der_public_key(pubkey_der) if key_id in certs: print_warn(f'doubled key ID in NO trust list, only using last: {format_key_id(key_id)}') certs[key_id] = cert return certs def download_gb_certs() -> CertList: response = requests.get(CERTS_URL_GB, headers={'User-Agent': USER_AGENT}) response.raise_for_status() certs: CertList = {} # TODO: find out if there is some sort of root cert to verify the trust list? md5_b64 = response.headers.get('content-md5') if md5_b64 is not None: expected_md5 = b64decode(md5_b64) actual_md5 = hashlib.md5(response.content).digest() if expected_md5 != actual_md5: raise ValueError(f'MD5 sum missmatch of GB trust list: expected: {expected_md5.hex()}, actual: {actual_md5.hex()}') certs_json = json.loads(response.content) for entry in certs_json: key_id = b64decode(entry['kid']) pubkey_der = b64decode(entry['publicKey']) cert = load_hack_certificate_from_der_public_key( pubkey_der, Name([NameAttribute(NameOID.COUNTRY_NAME, 'GB')]), Name([NameAttribute(NameOID.COUNTRY_NAME, 'GB')]), ) if key_id in certs: print_warn(f'doubled key ID in GB trust list, only using last: {format_key_id(key_id)}') certs[key_id] = cert return certs DOWNLOADERS: Dict[str, Callable[[], CertList]] = { 'AT-GREENCHECK': download_at_greencheck_certs, 'AT': download_at_certs, 'AT-TEST': lambda: download_at_certs(test=True), 'CH': download_ch_certs, 'DE': download_de_certs, 'FR': download_fr_certs, 'GB': download_gb_certs, 'NL': download_nl_certs, 'NO': download_no_certs, 'SE': download_se_certs, 'UK': download_gb_certs, # alias 'COVID-PASS-VERIFIER': download_covid_pass_verifier_certs, } def download_ehc_certs(sources: List[str], certs_table: Dict[str, CertList] = {}) -> CertList: certs: CertList = {} get_downloader = DOWNLOADERS.get for source in sources: source_certs = certs_table.get(source) if source_certs is not None: certs.update(source_certs) else: downloader = get_downloader(source) if downloader is None: raise ValueError(f'Unknown trust list source: {source}') certs.update(downloader()) return certs def get_at_greencheck_root_cert(root_cert_key_id: bytes = ROOT_CERT_KEY_ID_AT) -> x509.Certificate: # TODO: Find out another place where to get the AT root certificate from. # This gets it from the same server as the trust list itself, which is suboptimal. response = requests.get('https://greencheck.gv.at/', headers={'User-Agent': USER_AGENT}) response.raise_for_status() doc = parse_html(response.content.decode(response.encoding or 'UTF-8')) for script in doc.xpath('//script'): src = script.attrib.get('src') if src and src.startswith('/static/js/main.') and src.endswith('.chunk.js'): response = requests.get(f'https://greencheck.gv.at{src}', headers={'User-Agent': USER_AGENT}) status_code = response.status_code if status_code < 200 or status_code >= 300: print_err(f'https://greencheck.gv.at{src} {status_code} {http.client.responses.get(status_code, "")}') else: source = response.content.decode(response.encoding or 'UTF-8') match = JS_CERT_PATTERN.search(source) if match: certs_pems_js = match.group(1) certs_pems_js = ESC.sub(lambda match: chr(int(match[1], 16)), certs_pems_js) for meta_cert_key, meta_cert_src in json.loads(certs_pems_js).items(): meta_cert = load_pem_x509_certificate(meta_cert_src.encode()) key_id = meta_cert.fingerprint(hashes.SHA256())[:8] if key_id == root_cert_key_id: return meta_cert raise KeyError(f'AT certificate with key ID {format_key_id(root_cert_key_id)} not found!') def get_at_github_root_cert(test: bool = False) -> x509.Certificate: response = requests.get('https://raw.githubusercontent.com/Federal-Ministry-of-Health-AT/green-pass-overview/main/README.md', headers={'User-Agent': USER_AGENT}) response.raise_for_status() text = response.content.decode(response.encoding or 'UTF-8') certs: Dict[str, x509.Certificate] = {} for url, cert_data in MD_CERT_PATTERN.findall(text): cert = load_pem_x509_certificate(cert_data.encode('UTF-8')) certs[url] = cert if test: res_cert = certs.get('https://dgc-trusttest.qr.gv.at') or certs.get('https://dgc-trusttest.gv.at') else: res_cert = certs.get('https://dgc-trust.qr.gv.at') if res_cert is None: raise KeyError(f'AT {"testing" if test else "production"} root certificate not found!') return res_cert def get_at_root_cert() -> x509.Certificate: return load_pem_x509_certificate(ROOT_CERT_AT_PROD) def get_at_test_root_cert() -> x509.Certificate: return load_pem_x509_certificate(ROOT_CERT_AT_TEST) def get_de_root_pubkey() -> EllipticCurvePublicKey: response = requests.get(PUBKEY_URL_DE, headers={'User-Agent': USER_AGENT}) response.raise_for_status() pubkey = load_pem_public_key(response.content) if not isinstance(pubkey, EllipticCurvePublicKey): pubkey_type = type(pubkey) raise ValueError(f'{PUBKEY_URL_DE} is expected to be an EllipticCurvePublicKey but actually is {pubkey_type.__module__}.{pubkey_type.__name__}') return pubkey def get_de_root_cert() -> x509.Certificate: return HackCertificate(get_de_root_pubkey()) def get_nl_root_cert() -> x509.Certificate: response = requests.get(ROOT_CERT_URL_NL, headers={'User-Agent': USER_AGENT}) response.raise_for_status() return load_der_x509_certificate(response.content) def get_se_root_cert() -> x509.Certificate: response = requests.get(ROOT_CERT_URL_SE, headers={'User-Agent': USER_AGENT}) response.raise_for_status() return load_pem_x509_certificate(response.content) def get_ch_root_cert(token: Optional[str] = None) -> x509.Certificate: if token is None: token = get_ch_token() response = requests.get(ROOT_CERT_URL_CH, headers={ 'User-Agent': CH_USER_AGENT, 'Accept': 'application/json+jws', 'Accept-Encoding': 'gzip', 'Authorization': f'Bearer {token}', }) response.raise_for_status() return load_pem_x509_certificate(response.content) ROOT_CERT_DOWNLOADERS: Dict[str, Callable[[], x509.Certificate]] = { 'AT-GREENCHECK': get_at_greencheck_root_cert, 'AT': get_at_root_cert, 'AT-TEST': get_at_test_root_cert, 'AT-GITHUB': get_at_github_root_cert, 'AT-TEST-GITHUB': lambda: get_at_github_root_cert(test=True), 'DE': get_de_root_cert, # actually just a public key 'NL': get_nl_root_cert, 'SE': get_se_root_cert, 'CH': get_ch_root_cert, } def get_root_cert(source: str) -> x509.Certificate: envvar = f'{source.replace("-", "_")}_ROOT_CERT' value = os.getenv(envvar) if value is None: return ROOT_CERT_DOWNLOADERS[source]() if value.startswith('-----BEGIN CERTIFICATE-----'): return load_pem_x509_certificate(value.encode()) elif value.startswith('-----BEGIN PUBLIC KEY-----'): pubkey = load_pem_public_key(value.encode()) if not isinstance(pubkey, (EllipticCurvePublicKey, RSAPublicKey)): pubkey_type = type(pubkey) raise ValueError(f'expected EllipticCurvePublicKey or RSAPublicKey but actually got {pubkey_type.__module__}.{pubkey_type.__name__}') return HackCertificate(pubkey) with open(value, "rb") as fp: data = fp.read() if data.startswith(b'-----BEGIN CERTIFICATE-----'): return load_pem_x509_certificate(data) elif data.startswith(b'-----BEGIN PUBLIC KEY-----'): pubkey = load_pem_public_key(data) if not isinstance(pubkey, (EllipticCurvePublicKey, RSAPublicKey)): pubkey_type = type(pubkey) raise ValueError(f'expected EllipticCurvePublicKey or RSAPublicKey but actually got {pubkey_type.__module__}.{pubkey_type.__name__}') return HackCertificate(pubkey) else: return load_der_x509_certificate(data) def get_default_root_cert_filename(source: str) -> str: envvar = f'{source.replace("-", "_")}_ROOT_CERT' value = os.getenv(envvar) if value is not None and \ not value.startswith('-----BEGIN CERTIFICATE-----') and \ not value.startswith('-----BEGIN PUBLIC KEY-----'): return value return f'{source}.pem' def save_cert(cert: x509.Certificate, filename: str) -> None: _, ext = splitext(filename) ext = ext.lower() if ext == '.pem': encoding = Encoding.PEM else: encoding = Encoding.DER try: data = cert.public_bytes(encoding) except NotImplementedError: data = cert.public_key().public_bytes(encoding, PublicFormat.SubjectPublicKeyInfo) with open(filename, 'wb') as fp: fp.write(data) def load_jwt(token: bytes, root_cert: x509.Certificate, options: Optional[Dict[str, bool]] = None) -> Dict[str, Any]: header = jws.get_unverified_header(token) trustchain = [x509.load_der_x509_certificate(b64decode(cert_b64)) for cert_b64 in header['x5c']] trustchain.append(root_cert) rsa_padding = PKCS1v15() for index in range(len(trustchain) - 1): signed_cert = trustchain[index] issuer_cert = trustchain[index + 1] pubkey = issuer_cert.public_key() if isinstance(pubkey, RSAPublicKey): pubkey.verify( signed_cert.signature, signed_cert.tbs_certificate_bytes, rsa_padding, signed_cert.signature_hash_algorithm # type: ignore ) elif isinstance(pubkey, EllipticCurvePublicKey): pubkey.verify( signed_cert.signature, signed_cert.tbs_certificate_bytes, ECDSA(signed_cert.signature_hash_algorithm), ) else: pubkey_type = type(pubkey) raise NotImplementedError(f'Unsupported public key type: {pubkey_type.__module__}.{pubkey_type.__name__}') pubkey = trustchain[0].public_key() sigkey: jwk.Key if isinstance(pubkey, RSAPublicKey): rsa_pn = pubkey.public_numbers() e = rsa_pn.e.to_bytes((rsa_pn.e.bit_length() + 7) // 8, byteorder='big') n = rsa_pn.n.to_bytes((rsa_pn.n.bit_length() + 7) // 8, byteorder='big') sigkey = jwk.construct({ 'kty': 'RSA', 'alg': 'RS256', 'e': b64encode(e), 'n': b64encode(n), }) elif isinstance(pubkey, EllipticCurvePublicKey): ec_pn = pubkey.public_numbers() size = pubkey.curve.key_size // 8 x = ec_pn.x.to_bytes(size, byteorder="big") y = ec_pn.y.to_bytes(size, byteorder="big") sigkey = jwk.construct({ 'kty': 'EC', 'alg': 'ES256', 'crv': SECG_TO_NIST_CURVES.get(pubkey.curve.name, pubkey.curve.name), 'x': b64encode(x), 'y': b64encode(y), }) else: pubkey_type = type(pubkey) raise NotImplementedError(f'Unsupported public key type: {pubkey_type.__module__}.{pubkey_type.__name__}') return jwt.decode(token, key=sigkey, options=options) def load_hack_certificate_from_der_public_key(data: bytes, issuer: Optional[Name] = None, subject: Optional[Name] = None, not_valid_before: datetime = DEFAULT_NOT_VALID_BEFORE, not_valid_after: datetime = DEFAULT_NOT_VALID_AFTER, ) -> HackCertificate: pubkey = load_der_public_key(data) if isinstance(pubkey, EllipticCurvePublicKey): return HackCertificate(pubkey, issuer, subject, not_valid_before, not_valid_after) elif isinstance(pubkey, RSAPublicKey): return HackCertificate(pubkey, issuer, subject, not_valid_before, not_valid_after) else: pubkey_type = type(pubkey) raise NotImplementedError(f'Unsupported public key type: {pubkey_type.__module__}.{pubkey_type.__name__}') def b64decode_ignore_padding(b64str: str) -> bytes: return b64decode(b64str + "=" * ((4 - len(b64str) % 4) % 4)) def urlsafe_b64decode_ignore_padding(b64str: str) -> bytes: return urlsafe_b64decode(b64str + "=" * ((4 - len(b64str) % 4) % 4)) def decode_ehc(b45_data: str) -> CoseMessage: if b45_data.startswith(PREFIX): b45_data = b45_data[len(PREFIX):] elif b45_data.startswith(PREFIX_NO): b45_data = b45_data[len(PREFIX_NO):] try: data = b45decode(b45_data) except ValueError: print(b45_data) raise ValueError(f'Invalid base45 string. Try with single quotes.') from None if data.startswith(b'x'): data = zlib.decompress(data) msg: CoseMessage = CoseMessage.decode(data) return msg def format_key_id(key_id: bytes) -> str: key_id_hex = key_id.hex() key_id_b64 = b64encode(key_id).decode("ASCII") if all(byte >= 0x21 and byte <= 0x7E for byte in key_id): return f'{key_id_hex} / {key_id_b64} / {key_id.decode("ASCII")}' return f'{key_id_hex} / {key_id_b64}' def verify_ehc(msg: CoseMessage, issued_at: datetime, certs: CertList, print_exts: bool = False) -> bool: cose_algo = msg.phdr.get(Algorithm) or msg.uhdr.get(Algorithm) print(f'COSE Sig. Algo.: {cose_algo.fullname if cose_algo is not None else "N/A"}') if isinstance(msg, Sign1Message): print(f'Signature : {b64encode(msg.signature).decode("ASCII")}') # TODO: Should we allow (or warn about) key IDs from the unprotected header? # I mean, as long as the actual key it referres to is valid # (i.e. is in the trust list) it shouldn't matter, right? key_id = msg.phdr.get(KID) or msg.uhdr[KID] cert = certs.get(key_id) # XXX: is this correct? is it not two levels of signed certificates? if not cert: raise KeyError(f'Key ID not found in trust list: {key_id.hex()}') print('X.509 Certificate:') print_cert(key_id, cert, print_exts, indent=' ') cert_expired = False if cert.not_valid_before is not None and issued_at < cert.not_valid_before: cert_expired = True if cert.not_valid_after is not None and issued_at > cert.not_valid_after: cert_expired = True print(f' Cert Expired : {cert_expired}') revoked_cert = get_revoked_cert(cert) if revoked_cert: print(f'Cert Revoked At: {revoked_cert.revocation_date.isoformat()}') revoked = True else: revoked = False msg.key = cert_to_cose_key(cert) valid = msg.verify_signature() usage = get_key_usage(cert) ehc_payload = cbor2.loads(msg.payload) ehc = ehc_payload[-260][1] usage_valid = True if 'v' in ehc and 'vaccination' not in usage: usage_valid = False if 't' in ehc and 'test' not in usage: usage_valid = False if 'r' in ehc and 'recovery' not in usage: usage_valid = False print(f'Valid Key Usage: {usage_valid}') print(f'Signature Valid: {valid}') return valid and not cert_expired and not revoked and usage_valid def cert_to_cose_key(cert: x509.Certificate) -> CoseKey: pk = cert.public_key() if isinstance(pk, EllipticCurvePublicKey): ec_pn = pk.public_numbers() size = pk.curve.key_size // 8 x = ec_pn.x.to_bytes(size, byteorder="big") y = ec_pn.y.to_bytes(size, byteorder="big") curve_name = CURVE_NAME_IGNORE.sub('', pk.curve.name).lower() curve = COSE_CURVES.get(curve_name) if not curve: raise NotImplementedError(f'Unsupported curve: {pk.curve.name}') return CoseKey.from_dict( { KpKeyOps: [VerifyOp], KpKty: KtyEC2, EC2KpCurve: curve, KpAlg: Es256, EC2KpX: x, EC2KpY: y, } ) elif isinstance(pk, RSAPublicKey): rsa_pn = pk.public_numbers() e = rsa_pn.e.to_bytes((rsa_pn.e.bit_length() + 7) // 8, byteorder='big') n = rsa_pn.n.to_bytes((rsa_pn.n.bit_length() + 7) // 8, byteorder='big') return CoseKey.from_dict( { KpKeyOps: [VerifyOp], KpKty: KtyRSA, KpAlg: Ps256, RSAKpE: e, RSAKpN: n, } ) #elif isinstance(pk, DSAPublicKey): # dsa_pn = pk.public_numbers() # return CoseKey.from_dict( # { # # ??? # } # ) else: pk_type = type(pk) raise NotImplementedError(f'Unsupported public key type: {pk_type.__module__}.{pk_type.__name__}') crl_status: Dict[str, int] = {} crls: Dict[str, x509.CertificateRevocationList] = {} def get_cached_crl(uri: str) -> x509.CertificateRevocationList: crl = crls.get(uri) if crl is not None: return crl status_code = crl_status.get(uri) if status_code is not None: raise ValueError(f'{uri} {status_code} {http.client.responses.get(status_code, "")}') response = requests.get(uri, headers={'User-Agent': USER_AGENT}) status_code = response.status_code crl_status[uri] = status_code if response.status_code >= 400 and response.status_code < 600: raise ValueError(f'{uri} {status_code} {http.client.responses.get(status_code, "")}') crl_bytes = response.content if crl_bytes.startswith(b'-----BEGIN'): crl = load_pem_x509_crl(crl_bytes) else: crl = load_der_x509_crl(crl_bytes) crls[uri] = crl return crl def get_revoked_cert(cert: x509.Certificate) -> Optional[x509.RevokedCertificate]: try: crl_points_ext = cert.extensions.get_extension_for_oid(ExtensionOID.CRL_DISTRIBUTION_POINTS) except ExtensionNotFound: pass else: crl_points = crl_points_ext.value for crl_point in crl_points: uris = crl_point.full_name if uris: for uri in uris: lower_uri = uri.value.lower() if lower_uri.startswith('http:') or lower_uri.startswith('https:'): try: crl = get_cached_crl(uri.value) except Exception as error: print_err(f'loading revokation list {uri.value} {error}') else: return crl.get_revoked_certificate_by_serial_number(cert.serial_number) return None ENV_COMMENT = re.compile(r'^\s*(?:#.*)?$') ENV_VAR = re.compile(r'^\s*(?P<key>[0-9_a-zA-Z]+)\s*=\s*(?:"(?P<quoted>(?:[^"\\]|\\["nrt\\])*)"\s*|(?P<plain>[^#"]*))(?:#.*)?$') ENV_QUOTE = re.compile(r'\\(.)') ENV_ESC = { '\\': '\\', '"': '"', 'n': '\n', 'r': '\r', 't': '\t', } def parse_env(data: str) -> Dict[str, str]: env: Dict[str, str] = {} for index, line in enumerate(data.split('\n')): if not ENV_COMMENT.match(line): match = ENV_VAR.match(line) if not match: raise SyntaxError(f'in .env file: {line}') key: str = match.group('key') # type: ignore quoted: Optional[str] = match.group('quoted') value: str if quoted is not None: value = ENV_QUOTE.sub(lambda m: ENV_ESC[m.group(1)], quoted) # type: ignore else: value = match.group('plain') # type: ignore env[key] = value return env def save_certs(certs: CertList, certs_path: str, allow_public_key_only: bool = False) -> None: ext = splitext(certs_path)[1] lower_ext = ext.lower() if lower_ext == '.json': from jwcrypto.jwk import JWK # type: ignore # JSON that includes all info in a format as needed by WebCrypto, I hope certs_json = {} for key_id, cert in certs.items(): pubkey = cert.public_key() pubkey_jwk = JWK.from_pyca(pubkey) pubkey_json = pubkey_jwk.export(as_dict=True, private_key=False) pubkey_json['key_ops'] = ['verify'] # not sure about this: pubkey_json['kid'] = urlsafe_b64encode(key_id).decode('ASCII') # even less sure about this: if pubkey_json['kty'] == 'EC': algo = { 'name': 'ECDSA', 'namedCurve': pubkey_json['crv'], 'hash': {'name': "SHA-256"}, } else: algo = { 'name': 'RSASSA-PKCS1-v1_5', 'hash': {'name': "SHA-256"}, } cert_json = { 'issuer': make_json_relative_distinguished_name(cert.issuer), 'subject': make_json_relative_distinguished_name(cert.subject), 'notValidBefore': cert.not_valid_before.isoformat(), 'notValidAfter': cert.not_valid_after.isoformat(), 'publicKey': pubkey_json, 'algorithm': algo, 'usage': sorted(get_key_usage(cert)), } certs_json[key_id.hex()] = cert_json json_doc = { 'timestamp': datetime.utcnow().isoformat()+'Z', 'trustList': certs_json, } with open(certs_path, 'w') as text_stream: json.dump(json_doc, text_stream) elif lower_ext == '.cbor': # same CBOR format as AT trust list cert_list: List[dict] = [] for key_id, cert in certs.items(): if allow_public_key_only and isinstance(cert, HackCertificate): entry = { 'i': key_id, 'k': cert.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo), } issuer = cert.issuer if issuer: entry['is'] = make_json_relative_distinguished_name(issuer) subject = cert.subject if subject: entry['su'] = make_json_relative_distinguished_name(subject) not_valid_before = cert.not_valid_before if not_valid_before is not DEFAULT_NOT_VALID_BEFORE: entry['nb'] = int(not_valid_before.timestamp()) not_valid_after = cert.not_valid_before if not_valid_after is not DEFAULT_NOT_VALID_AFTER: entry['na'] = int(not_valid_after.timestamp()) cert_list.append(entry) else: try: cert_bytes = cert.public_bytes(Encoding.DER) except NotImplementedError as error: print_err(f'Cannot store entry {format_key_id(key_id)} in CBOR trust list: {error}') else: cert_list.append({ 'i': key_id, 'c': cert_bytes, }) with open(certs_path, 'wb') as fp: cbor2.dump({'c': cert_list}, fp) else: raise ValueError(f'Unsupported certificates file extension: {ext!r}') def split_lines(text: str, width: int) -> List[str]: lines: List[str] = [] for line_str in text.split('\n'): line: List[str] = [] line_len = 0 for word in line_str.split(' '): word_len = len(word) next_len = line_len + word_len if line: next_len += 1 if next_len > width: lines.append(' '.join(line)) line.clear() line_len = 0 elif line: line_len += 1 line.append(word) line_len += word_len lines.append(' '.join(line)) return lines def fill_text(text: str, width: int, indent: str) -> str: return '\n'.join(indent + line for line in split_lines(text, width - len(indent))) class SmartFormatter(argparse.HelpFormatter): def _split_lines(self, text: str, width: int) -> List[str]: return split_lines(text, width) def _fill_text(self, text: str, width: int, indent: str) -> str: return fill_text(text, width, indent) def parse_sources(sources_str: str) -> List[str]: sources_str = sources_str.strip() return [country.strip().upper() for country in sources_str.split(',')] if sources_str else [] class Align(enum.Enum): Left = 0 Right = 1 Center = 2 def align(self, text: str, width: int, fillchar: str = ' ') -> str: if self == Align.Left: return text.ljust(width, fillchar) elif self == Align.Right: return text.rjust(width, fillchar) else: return text.center(width, fillchar) def print_table(header: List[str], align: List[Align], body: List[List[str]]) -> None: widths: List[int] = [len(cell) for cell in header] for row in body: for index, cell in enumerate(row): cell_len = len(cell) while index >= len(widths): widths.append(0) if widths[index] < cell_len: widths[index] = cell_len while len(align) < len(widths): align.append(Align.Left) print(' | '.join(alignment.align(cell, width) for alignment, cell, width in zip(align, header, widths)).rstrip()) print('-+-'.join(alignment.align('', width, '-') for alignment, width in zip(align, widths))) for row in body: print(' | '.join(alignment.align(cell, width) for alignment, cell, width in zip(align, row, widths)).rstrip()) def get_key_usage(cert: x509.Certificate) -> Set[str]: usage: Set[str] = set() try: ext_key_usage = cert.extensions.get_extension_for_oid(ExtensionOID.EXTENDED_KEY_USAGE) except ExtensionNotFound: pass else: for oid in ext_key_usage.value: usage_name = EXT_KEY_USAGE_NAMES.get(oid) if usage_name is not None: usage.add(usage_name) if not usage: usage = {'test', 'vaccination', 'recovery'} return usage def print_cert(key_id: bytes, cert: x509.Certificate, print_exts: bool = False, revoked_certs: Optional[Dict[bytes, x509.RevokedCertificate]] = None, indent: Union[str, int]='') -> None: if isinstance(indent, int): indent = ' ' * indent print(f'{indent}Key ID :', format_key_id(key_id)) if not isinstance(cert, HackCertificate): print(f'{indent}Serial Nr. :', ":".join("%02x" % byte for byte in cert.serial_number.to_bytes(20, byteorder="big"))) print(f'{indent}Issuer :', cert.issuer.rfc4514_string()) print(f'{indent}Subject :', cert.subject.rfc4514_string()) print(f'{indent}Valid Date Range:', cert.not_valid_before.isoformat() if cert.not_valid_before is not None else 'N/A', '-', cert.not_valid_after.isoformat() if cert.not_valid_after is not None else 'N/A') print(f'{indent}Version :', cert.version.name) usage: Set[str] = set() try: ext_key_usage = cert.extensions.get_extension_for_oid(ExtensionOID.EXTENDED_KEY_USAGE) except ExtensionNotFound: pass else: for oid in ext_key_usage.value: usage_name = EXT_KEY_USAGE_NAMES.get(oid) if usage_name is None: print_warn(f'Unexpected extened key usage: {oid.dotted_string} ({oid._name})') else: usage.add(usage_name) if not usage: usage = {'test', 'vaccination', 'recovery'} print(f'{indent}Ext. Key Usage : {", ".join(sorted(usage))}') pk = cert.public_key() print(f'{indent}Key Type : {type(pk).__name__.strip("_")}') if isinstance(pk, EllipticCurvePublicKey): print(f'{indent}Curve :', pk.curve.name) if not isinstance(cert, HackCertificate): signature_algorithm_oid = cert.signature_algorithm_oid print(f'{indent}Signature Algo. : oid={signature_algorithm_oid.dotted_string}, name={signature_algorithm_oid._name}') print(f'{indent}Signature :', b64encode(cert.signature).decode('ASCII')) if revoked_certs is not None: revoked_cert = revoked_certs.get(key_id) if revoked_cert: print(f'{indent}Revoked At :', revoked_cert.revocation_date.isoformat()) if print_exts and cert.extensions: print(f'{indent}Extensions :') for ext in cert.extensions: print(f'{indent}- oid={ext.oid.dotted_string}, name={ext.oid._name}, value={ext.value}') def main() -> None: ap = argparse.ArgumentParser(formatter_class=SmartFormatter, add_help=False) ap.add_argument('--help', '-h', action='store_true', default=False, help= 'Show this help message and exit.') certs_ap = ap.add_mutually_exclusive_group() certs_ap.add_argument('--certs-file', metavar="FILE", help= 'Trust list in CBOR or JSON format.') certs_ap.add_argument('--certs-from', metavar="LIST", help= "Download trust list from given country's trust list service. Comma separated list, entries from later country overwrites earlier.\n" "See also environment variables.\n" "\n" "Supported countries: AT, CH, DE, FR, GB, NL, NO, SE\n" "\n" "Note that the GB trust list only contains GB public keys, so you might want to combine it with another.\n" "\n" "If neither --certs-file nor --certs-from is given then --certs-from=DE,AT is used as default.\n", default='DE,AT') certs_ap.add_argument('--certs-table', metavar='LIST', help= 'Print table of trust list certificates showing where which key ID is avaliable showing the country of the certificate as it is known to the given trust list. ' '"X" means the certificate/public key is in the trust list, but no country attribute is known for it.') ap.add_argument('--no-verify', action='store_true', default=False, help='Skip certificate verification.') ap.add_argument('--list-certs', action='store_true', help='List certificates from trust list.') ap.add_argument('--print-exts', action='store_true', help='Also print certificate extensions.') ap.add_argument('--strip-revoked', action='store_true', help= 'Strip revoked certificates. (Downloads certificate revocation list, if supported by certificate.)') ap.add_argument('--save-certs', metavar='FILE', action='append', help= 'Store downloaded trust list to FILE. The filetype is derived from the extension, which can be .json or .cbor') ap.add_argument('--download-root-cert', metavar='SOURCE[@FILENAME]', action='append', help= 'Download and store root certificate (or public key) of SOURCE as FILENAME. ' 'If FILENAME is not given SOURCE.pem is used. ' 'If FILENAME ends in ".pem" the certificate (or public key) is stored encoded as PEM, otherwise it is encoded as DER.') ap.add_argument('--download-all-root-certs', action='store_true', help= 'Download and store all root certificates (or public keys) and store them in SOURCE.pem files.') ap.add_argument('--allow-public-key-only', '--allow-pubkey-only', action='store_true', help= 'When writing the CBOR trust list format it usually rejects entries that are only public keys and not full x509 certificates. ' 'With this options it also writes entries that are only public keys.') ap.add_argument('--envfile', metavar='FILE', default='.env', help= 'Load environment variables from FILE. Default is ".env". ' 'Set this to an empty string to not load environment varibles from a file.') ap.add_argument('--fail-on-error', action='store_true', default=False, help='Turns every error into an exception.') ap.add_argument('--warning-as-error', action='store_true', default=False, help='Turns every warning into an error.') ap.add_argument('--image', action='store_true', default=False, help='ehc_code is a path to an image file containing a QR-code.') ap.add_argument('ehc_code', nargs='*', help='Scanned EHC QR-code, or when --image is passed path to an image file.') args = ap.parse_args() if args.help: width = shutil.get_terminal_size().columns extra_help: List[Tuple[str, List[Tuple[str, str]]]] = [ ( 'environment variables:', [ ( '<SOURCE>_ROOT_CERT', "Some of the trust lists are have signatures that can be checked with a certain trust list " "specific root certificate (or just public key in the case of DE). Instead of always downloading " "these certificates you can just download them once using --download-root-cert or " "--download-all-root-certs and then supply them to this script using environment variables. " "The environment variable can be a path to a PEM or DER encoded certificate, a PEM encoded " "public key, or the value of the environment variable itself can be a PEM encoded certificate " "or public key. You can use this to pin the root certificate.\n" "\n" "Example:\n" " ./verify_ehc.py --download-root-cert SE@se_root_cert.crt\n" " export SE_ROOT_CERT=se_root_cert.crt\n" " ./verify_ehc.py --certs-from SE --save-certs certs.cbor\n" "\n" "Trust list sources for which root certificates are supported:\n" " AT, CH, DE, NL, SE" ), # TODO: Write proper help text once this information becomes available. #( # 'AT_TOKEN', # "Downloading the Austrian (AT) trust list needs the nevironment variable AT_TOKEN set to " # "a token that you will be able to get from somewhere. Still waiting on the government to " # "pulicise anything about that.\n" # "<insert description and link here>" #), ( 'CH_TOKEN', "Downloading the Swiss (CH) trust list and root certificate needs the environment variable " "CH_TOKEN set to a bearer token that can be found in the BIT's Android CovidCertificate app " "APK. See also: https://github.com/cn-uofbasel/ch-dcc-keys" ), ( 'FR_TOKEN', "Downloading the French (FR) trust list needs the environment variable FR_TOKEN set to a bearer " "token that can be found in the TousAntiCovid Verif app APK." ), ( 'NO_TOKEN', "Downloading the Norwegian (NO) trust list needs the environment variable NO_TOKEN set to an " "AuthorizationHeader string that can be found in the Kontroll av koronasertifikat app APK. " "See also: https://harrisonsand.com/posts/covid-certificates/" ), ] ) ] ap.print_help() print() item_name_limit = 20 for title, help_items in extra_help: print(title) max_item_name_len = 0 for item_name, description in help_items: item_name_len = len(item_name) if item_name_len > max_item_name_len and item_name_len < item_name_limit: max_item_name_len = item_name_len if max_item_name_len == 0: max_item_name_len = item_name_limit rest_width = max(width - 4 - max_item_name_len, 1) indent = ' ' * (width - rest_width) for item_name, description in help_items: lines = split_lines(description, rest_width) if len(item_name) > item_name_limit: print(f' {item_name}') else: print(f' {item_name.ljust(max_item_name_len)} {lines[0]}') lines = lines[1:] for line in lines: print(indent + line) print() print('Report issues to: https://github.com/panzi/verify-ehc/issues') return global FAIL_ON_ERROR, WARNING_AS_ERROR FAIL_ON_ERROR = args.fail_on_error WARNING_AS_ERROR = args.warning_as_error if args.envfile: try: with open(args.envfile, 'r') as text_stream: env_str = text_stream.read() except (FileNotFoundError, IsADirectoryError): pass else: env = parse_env(env_str) os.environ.update(env) download_root_certs = args.download_root_cert or [] if args.download_all_root_certs: download_root_certs.extend(ROOT_CERT_DOWNLOADERS.keys()) for download_root_cert in download_root_certs: parts = download_root_cert.split('@', 1) source = parts[0] if len(parts) > 1: filename = parts[1] else: filename = get_default_root_cert_filename(source) source_upper = source.strip().upper() root_cert_downloader = ROOT_CERT_DOWNLOADERS.get(source_upper) if root_cert_downloader is None: if source_upper in DOWNLOADERS: raise KeyError(f'{source_upper} has no known root certificate') else: raise KeyError(f'Unknown trust list source: {source}') root_cert = root_cert_downloader() save_cert(root_cert, filename) certs_table: Dict[str, CertList] = {} if args.certs_table: sources = parse_sources(args.certs_table) all_certs: CertList = {} get_downloader = DOWNLOADERS.get header: List[str] = ['Key ID'] align: List[Align] = [Align.Left] for source in sources: header.append(source) align.append(Align.Center) downloader = get_downloader(source) if downloader is None: raise ValueError(f'Unknown trust list source: {source}') source_certs = downloader() certs_table[source] = source_certs all_certs.update(source_certs) def sort_key(key_id: bytes) -> Tuple[List[str], bytes]: countries: List[str] = [] for source in sources: cert = certs_table[source].get(key_id) if cert is not None: for attr in cert.subject.get_attributes_for_oid(NameOID.COUNTRY_NAME): countries.append(attr.value) return countries, key_id body: List[List[str]] = [] for key_id in sorted(all_certs, key=sort_key): row: List[str] = [b64encode(key_id).decode('ASCII')] for source in sources: cert = certs_table[source].get(key_id) if cert is None: cell = '' else: cell = ','.join(attr.value for attr in cert.subject.get_attributes_for_oid(NameOID.COUNTRY_NAME)) or 'X' row.append(cell) body.append(row) print_table(header, align, body) certs: Optional[CertList] = None if not args.no_verify or args.save_certs or args.list_certs: if args.certs_file: if args.certs_file.lower().endswith('.json'): with open(args.certs_file, 'rb') as fp: certs_data = fp.read() certs = load_hack_certs_json(certs_data, args.certs_file) else: certs = load_ehc_certs(args.certs_file) else: certs = download_ehc_certs(parse_sources(args.certs_from), certs_table) if not certs: print_err("empty trust list!") items: List[Tuple[bytes, x509.Certificate]] revoked_certs: Dict[bytes, x509.RevokedCertificate] = {} if args.list_certs or args.strip_revoked: items = list(certs.items()) items.sort(key=lambda item: (item[1].issuer.rfc4514_string(), item[1].subject.rfc4514_string(), item[0])) if args.strip_revoked: for key_id, cert in items: revoked_cert = get_revoked_cert(cert) if revoked_cert: revoked_certs[key_id] = revoked_cert revoked = True if args.list_certs: revoked_certs_for_print: Optional[Dict[bytes, x509.RevokedCertificate]] = revoked_certs if args.strip_revoked else None for key_id, cert in items: print_cert(key_id, cert, print_exts=args.print_exts, revoked_certs=revoked_certs_for_print) print() if args.strip_revoked: for key_id in revoked_certs: del certs[key_id] if args.save_certs: for certs_path in args.save_certs: save_certs(certs, certs_path, args.allow_public_key_only) ehc_codes: List[str] = [] if args.image: from pyzbar.pyzbar import decode as decode_qrcode # type: ignore from PIL import Image # type: ignore for filename in args.ehc_code: image = Image.open(filename, 'r') qrcodes = decode_qrcode(image) if qrcodes: for qrcode in qrcodes: ehc_codes.append(qrcode.data.decode("utf-8")) else: print_err(f'{filename}: no qr-code found') else: ehc_codes.extend(args.ehc_code) if args.no_verify: certs = None for ehc_code in ehc_codes: ehc_msg = decode_ehc(ehc_code) ehc_payload = cbor2.loads(ehc_msg.payload) for key, value in ehc_payload.items(): if key != -260: name = CLAIM_NAMES.get(key) if name is not None: if key in DATETIME_CLAIMS: dt = EPOCH + timedelta(seconds=value) value = dt.isoformat() else: name = f'Claim {key} (unknown)' print(f'{name:15}: {value}') issued_at = EPOCH + timedelta(seconds=ehc_payload[6]) expires_at_int = ehc_payload.get(4) if expires_at_int is not None: expires_at = EPOCH + timedelta(seconds=expires_at_int) print(f'Is Expired :', datetime.utcnow() > expires_at) if certs is not None: verify_ehc(ehc_msg, issued_at, certs, args.print_exts) ehc = ehc_payload[-260][1] print('Payload :') print(json.dumps(ehc, indent=4, sort_keys=True, default=json_serial)) print() if __name__ == '__main__': main()
"""Common classes and elements for Omnilogic Integration.""" from datetime import timedelta import logging from omnilogic import OmniLogic, OmniLogicException from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_IDENTIFIERS, ATTR_MANUFACTURER, ATTR_MODEL, ATTR_NAME, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, UpdateFailed, ) from .const import ALL_ITEM_KINDS, DOMAIN _LOGGER = logging.getLogger(__name__) class OmniLogicUpdateCoordinator(DataUpdateCoordinator): """Class to manage fetching update data from single endpoint.""" def __init__( self, hass: HomeAssistant, api: OmniLogic, name: str, config_entry: ConfigEntry, polling_interval: int, ) -> None: """Initialize the global Omnilogic data updater.""" self.api = api self.config_entry = config_entry super().__init__( hass=hass, logger=_LOGGER, name=name, update_interval=timedelta(seconds=polling_interval), ) async def _async_update_data(self): """Fetch data from OmniLogic.""" try: data = await self.api.get_telemetry_data() except OmniLogicException as error: raise UpdateFailed(f"Error updating from OmniLogic: {error}") from error parsed_data = {} def get_item_data(item, item_kind, current_id, data): """Get data per kind of Omnilogic API item.""" if isinstance(item, list): for single_item in item: data = get_item_data(single_item, item_kind, current_id, data) if "systemId" in item: system_id = item["systemId"] current_id = current_id + (item_kind, system_id) data[current_id] = item for kind in ALL_ITEM_KINDS: if kind in item: data = get_item_data(item[kind], kind, current_id, data) return data parsed_data = get_item_data(data, "Backyard", (), parsed_data) return parsed_data class OmniLogicEntity(CoordinatorEntity): """Defines the base OmniLogic entity.""" def __init__( self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, item_id: tuple, icon: str, ) -> None: """Initialize the OmniLogic Entity.""" super().__init__(coordinator) bow_id = None entity_data = coordinator.data[item_id] backyard_id = item_id[:2] if len(item_id) == 6: bow_id = item_id[:4] msp_system_id = coordinator.data[backyard_id]["systemId"] entity_friendly_name = f"{coordinator.data[backyard_id]["BackyardName"]} " unique_id = f"{msp_system_id}" if bow_id is not None: unique_id = f"{unique_id}_{coordinator.data[bow_id]["systemId"]}" if kind != "Heaters": entity_friendly_name = ( f"{entity_friendly_name}{coordinator.data[bow_id]["Name"]} " ) else: entity_friendly_name = f"{entity_friendly_name}{coordinator.data[bow_id]["Operation"]["VirtualHeater"]["Name"]} " unique_id = f"{unique_id}_{coordinator.data[item_id]["systemId"]}_{kind}" if entity_data.get("Name") is not None: entity_friendly_name = f"{entity_friendly_name} {entity_data["Name"]}" entity_friendly_name = f"{entity_friendly_name} {name}" unique_id = unique_id.replace(" ", "_") self._kind = kind self._name = entity_friendly_name self._unique_id = unique_id self._item_id = item_id self._icon = icon self._attrs = {} self._msp_system_id = msp_system_id self._backyard_name = coordinator.data[backyard_id]["BackyardName"] @property def unique_id(self) -> str: """Return a unique, Home Assistant friendly identifier for this entity.""" return self._unique_id @property def name(self) -> str: """Return the name of the entity.""" return self._name @property def icon(self): """Return the icon for the entity.""" return self._icon @property def extra_state_attributes(self): """Return the attributes.""" return self._attrs @property def device_info(self): """Define the device as back yard/MSP System.""" return { ATTR_IDENTIFIERS: {(DOMAIN, self._msp_system_id)}, ATTR_NAME: self._backyard_name, ATTR_MANUFACTURER: "Hayward", ATTR_MODEL: "OmniLogic", } def check_guard(state_key, item, entity_setting): """Validate that this entity passes the defined guard conditions defined at setup.""" if state_key not in item: return True for guard_condition in entity_setting["guard_condition"]: if guard_condition and all( item.get(guard_key) == guard_value for guard_key, guard_value in guard_condition.items() ): return True return False
"""Common classes and elements for Omnilogic Integration.""" from datetime import timedelta import logging from omnilogic import OmniLogic, OmniLogicException from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_IDENTIFIERS, ATTR_MANUFACTURER, ATTR_MODEL, ATTR_NAME, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, UpdateFailed, ) from .const import ALL_ITEM_KINDS, DOMAIN _LOGGER = logging.getLogger(__name__) class OmniLogicUpdateCoordinator(DataUpdateCoordinator): """Class to manage fetching update data from single endpoint.""" def __init__( self, hass: HomeAssistant, api: OmniLogic, name: str, config_entry: ConfigEntry, polling_interval: int, ) -> None: """Initialize the global Omnilogic data updater.""" self.api = api self.config_entry = config_entry super().__init__( hass=hass, logger=_LOGGER, name=name, update_interval=timedelta(seconds=polling_interval), ) async def _async_update_data(self): """Fetch data from OmniLogic.""" try: data = await self.api.get_telemetry_data() except OmniLogicException as error: raise UpdateFailed(f"Error updating from OmniLogic: {error}") from error parsed_data = {} def get_item_data(item, item_kind, current_id, data): """Get data per kind of Omnilogic API item.""" if isinstance(item, list): for single_item in item: data = get_item_data(single_item, item_kind, current_id, data) if "systemId" in item: system_id = item["systemId"] current_id = current_id + (item_kind, system_id) data[current_id] = item for kind in ALL_ITEM_KINDS: if kind in item: data = get_item_data(item[kind], kind, current_id, data) return data parsed_data = get_item_data(data, "Backyard", (), parsed_data) return parsed_data class OmniLogicEntity(CoordinatorEntity): """Defines the base OmniLogic entity.""" def __init__( self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, item_id: tuple, icon: str, ) -> None: """Initialize the OmniLogic Entity.""" super().__init__(coordinator) bow_id = None entity_data = coordinator.data[item_id] backyard_id = item_id[:2] if len(item_id) == 6: bow_id = item_id[:4] msp_system_id = coordinator.data[backyard_id]["systemId"] entity_friendly_name = f"{coordinator.data[backyard_id]['BackyardName']} " unique_id = f"{msp_system_id}" if bow_id is not None: unique_id = f"{unique_id}_{coordinator.data[bow_id]['systemId']}" if kind != "Heaters": entity_friendly_name = ( f"{entity_friendly_name}{coordinator.data[bow_id]['Name']} " ) else: entity_friendly_name = f"{entity_friendly_name}{coordinator.data[bow_id]['Operation']['VirtualHeater']['Name']} " unique_id = f"{unique_id}_{coordinator.data[item_id]['systemId']}_{kind}" if entity_data.get("Name") is not None: entity_friendly_name = f"{entity_friendly_name} {entity_data['Name']}" entity_friendly_name = f"{entity_friendly_name} {name}" unique_id = unique_id.replace(" ", "_") self._kind = kind self._name = entity_friendly_name self._unique_id = unique_id self._item_id = item_id self._icon = icon self._attrs = {} self._msp_system_id = msp_system_id self._backyard_name = coordinator.data[backyard_id]["BackyardName"] @property def unique_id(self) -> str: """Return a unique, Home Assistant friendly identifier for this entity.""" return self._unique_id @property def name(self) -> str: """Return the name of the entity.""" return self._name @property def icon(self): """Return the icon for the entity.""" return self._icon @property def extra_state_attributes(self): """Return the attributes.""" return self._attrs @property def device_info(self): """Define the device as back yard/MSP System.""" return { ATTR_IDENTIFIERS: {(DOMAIN, self._msp_system_id)}, ATTR_NAME: self._backyard_name, ATTR_MANUFACTURER: "Hayward", ATTR_MODEL: "OmniLogic", } def check_guard(state_key, item, entity_setting): """Validate that this entity passes the defined guard conditions defined at setup.""" if state_key not in item: return True for guard_condition in entity_setting["guard_condition"]: if guard_condition and all( item.get(guard_key) == guard_value for guard_key, guard_value in guard_condition.items() ): return True return False
import pytest @pytest.fixture def admin(django_user_model): return django_user_model.objects.create_superuser(username='TestUser', email='admin@yamdb.fake', password='1234567') @pytest.fixture def token(admin): from rest_framework_simplejwt.tokens import RefreshToken refresh = RefreshToken.for_user(admin) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } @pytest.fixture def user_client(token): from rest_framework.test import APIClient client = APIClient() client.credentials(HTTP_AUTHORIZATION=f'Bearer {token['access']}') return client
import pytest @pytest.fixture def admin(django_user_model): return django_user_model.objects.create_superuser(username='TestUser', email='admin@yamdb.fake', password='1234567') @pytest.fixture def token(admin): from rest_framework_simplejwt.tokens import RefreshToken refresh = RefreshToken.for_user(admin) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } @pytest.fixture def user_client(token): from rest_framework.test import APIClient client = APIClient() client.credentials(HTTP_AUTHORIZATION=f'Bearer {token["access"]}') return client
import logging import threading import time import traceback from dataclasses import dataclass from functools import reduce from pathlib import Path from typing import Dict, List, Optional, Set, Tuple, Union from concurrent.futures.thread import ThreadPoolExecutor from blspy import G1Element, PrivateKey from chiapos import DiskProver from flax.consensus.pos_quality import UI_ACTUAL_SPACE_CONSTANT_FACTOR, _expected_plot_size from flax.types.blockchain_format.proof_of_space import ProofOfSpace from flax.types.blockchain_format.sized_bytes import bytes32 from flax.util.config import load_config, save_config from flax.wallet.derive_keys import master_sk_to_local_sk log = logging.getLogger(__name__) @dataclass class PlotInfo: prover: DiskProver pool_public_key: Optional[G1Element] pool_contract_puzzle_hash: Optional[bytes32] plot_public_key: G1Element file_size: int time_modified: float def _get_filenames(directory: Path) -> List[Path]: try: if not directory.exists(): log.warning(f"Directory: {directory} does not exist.") return [] except OSError as e: log.warning(f"Error checking if directory {directory} exists: {e}") return [] all_files: List[Path] = [] try: for child in directory.iterdir(): if not child.is_dir(): # If it is a file ending in .plot, add it - work around MacOS ._ files if child.suffix == ".plot" and not child.name.startswith("._"): all_files.append(child) else: log.info(f"Not checking subdirectory {child}, subdirectories not added by default") except Exception as e: log.warning(f"Error reading directory {directory} {e}") return all_files def get_plot_filenames(config: Dict) -> Dict[Path, List[Path]]: # Returns a map from directory to a list of all plots in the directory directory_names: List[str] = config["plot_directories"] all_files: Dict[Path, List[Path]] = {} for directory_name in directory_names: directory = Path(directory_name).resolve() all_files[directory] = _get_filenames(directory) return all_files def parse_plot_info(memo: bytes) -> Tuple[Union[G1Element, bytes32], G1Element, PrivateKey]: # Parses the plot info bytes into keys if len(memo) == (48 + 48 + 32): # This is a public key memo return ( G1Element.from_bytes(memo[:48]), G1Element.from_bytes(memo[48:96]), PrivateKey.from_bytes(memo[96:]), ) elif len(memo) == (32 + 48 + 32): # This is a pool_contract_puzzle_hash memo return ( bytes32(memo[:32]), G1Element.from_bytes(memo[32:80]), PrivateKey.from_bytes(memo[80:]), ) else: raise ValueError(f"Invalid number of bytes {len(memo)}") def stream_plot_info_pk( pool_public_key: G1Element, farmer_public_key: G1Element, local_master_sk: PrivateKey, ): # There are two ways to stream plot info: with a pool public key, or with a pool contract puzzle hash. # This one streams the public key, into bytes data = bytes(pool_public_key) + bytes(farmer_public_key) + bytes(local_master_sk) assert len(data) == (48 + 48 + 32) return data def stream_plot_info_ph( pool_contract_puzzle_hash: bytes32, farmer_public_key: G1Element, local_master_sk: PrivateKey, ): # There are two ways to stream plot info: with a pool public key, or with a pool contract puzzle hash. # This one streams the pool contract puzzle hash, into bytes data = pool_contract_puzzle_hash + bytes(farmer_public_key) + bytes(local_master_sk) assert len(data) == (32 + 48 + 32) return data def add_plot_directory(str_path: str, root_path: Path) -> Dict: config = load_config(root_path, "config.yaml") if str(Path(str_path).resolve()) not in config["harvester"]["plot_directories"]: config["harvester"]["plot_directories"].append(str(Path(str_path).resolve())) save_config(root_path, "config.yaml", config) return config def get_plot_directories(root_path: Path) -> List[str]: config = load_config(root_path, "config.yaml") return [str(Path(str_path).resolve()) for str_path in config["harvester"]["plot_directories"]] def remove_plot_directory(str_path: str, root_path: Path) -> None: config = load_config(root_path, "config.yaml") str_paths: List[str] = config["harvester"]["plot_directories"] # If path str matches exactly, remove if str_path in str_paths: str_paths.remove(str_path) # If path matcehs full path, remove new_paths = [Path(sp).resolve() for sp in str_paths] if Path(str_path).resolve() in new_paths: new_paths.remove(Path(str_path).resolve()) config["harvester"]["plot_directories"] = [str(np) for np in new_paths] save_config(root_path, "config.yaml", config) def load_plots( provers: Dict[Path, PlotInfo], failed_to_open_filenames: Dict[Path, int], farmer_public_keys: Optional[List[G1Element]], pool_public_keys: Optional[List[G1Element]], match_str: Optional[str], show_memo: bool, root_path: Path, open_no_key_filenames=False, ) -> Tuple[bool, Dict[Path, PlotInfo], Dict[Path, int], Set[Path]]: start_time = time.time() config_file = load_config(root_path, "config.yaml", "harvester") changed = False no_key_filenames: Set[Path] = set() log.info(f'Searching directories {config_file['plot_directories']}') plot_filenames: Dict[Path, List[Path]] = get_plot_filenames(config_file) all_filenames: List[Path] = [] for paths in plot_filenames.values(): all_filenames += paths plot_ids: Set[bytes32] = set() plot_ids_lock = threading.Lock() if match_str is not None: log.info(f'Only loading plots that contain "{match_str}" in the file or directory name') def process_file(filename: Path) -> Tuple[int, Dict]: new_provers: Dict[Path, PlotInfo] = {} nonlocal changed filename_str = str(filename) if match_str is not None and match_str not in filename_str: return 0, new_provers if filename.exists(): if filename in failed_to_open_filenames and (time.time() - failed_to_open_filenames[filename]) < 1200: # Try once every 20 minutes to open the file return 0, new_provers if filename in provers: try: stat_info = filename.stat() except Exception as e: log.error(f"Failed to open file {filename}. {e}") return 0, new_provers if stat_info.st_mtime == provers[filename].time_modified: with plot_ids_lock: if provers[filename].prover.get_id() in plot_ids: log.warning(f"Have multiple copies of the plot {filename}, not adding it.") return 0, new_provers plot_ids.add(provers[filename].prover.get_id()) new_provers[filename] = provers[filename] return stat_info.st_size, new_provers try: prover = DiskProver(str(filename)) expected_size = _expected_plot_size(prover.get_size()) * UI_ACTUAL_SPACE_CONSTANT_FACTOR stat_info = filename.stat() # TODO: consider checking if the file was just written to (which would mean that the file is still # being copied). A segfault might happen in this edge case. if prover.get_size() >= 30 and stat_info.st_size < 0.98 * expected_size: log.warning( f"Not farming plot {filename}. Size is {stat_info.st_size / (1024**3)} GiB, but expected" f" at least: {expected_size / (1024 ** 3)} GiB. We assume the file is being copied." ) return 0, new_provers ( pool_public_key_or_puzzle_hash, farmer_public_key, local_master_sk, ) = parse_plot_info(prover.get_memo()) # Only use plots that correct keys associated with them if farmer_public_keys is not None and farmer_public_key not in farmer_public_keys: log.warning(f"Plot {filename} has a farmer public key that is not in the farmer's pk list.") no_key_filenames.add(filename) if not open_no_key_filenames: return 0, new_provers if isinstance(pool_public_key_or_puzzle_hash, G1Element): pool_public_key = pool_public_key_or_puzzle_hash pool_contract_puzzle_hash = None else: assert isinstance(pool_public_key_or_puzzle_hash, bytes32) pool_public_key = None pool_contract_puzzle_hash = pool_public_key_or_puzzle_hash if ( pool_public_keys is not None and pool_public_key is not None and pool_public_key not in pool_public_keys ): log.warning(f"Plot {filename} has a pool public key that is not in the farmer's pool pk list.") no_key_filenames.add(filename) if not open_no_key_filenames: return 0, new_provers stat_info = filename.stat() local_sk = master_sk_to_local_sk(local_master_sk) plot_public_key: G1Element = ProofOfSpace.generate_plot_public_key(local_sk.get_g1(), farmer_public_key) with plot_ids_lock: if prover.get_id() in plot_ids: log.warning(f"Have multiple copies of the plot {filename}, not adding it.") return 0, new_provers plot_ids.add(prover.get_id()) new_provers[filename] = PlotInfo( prover, pool_public_key, pool_contract_puzzle_hash, plot_public_key, stat_info.st_size, stat_info.st_mtime, ) changed = True except Exception as e: tb = traceback.format_exc() log.error(f"Failed to open file {filename}. {e} {tb}") failed_to_open_filenames[filename] = int(time.time()) return 0, new_provers log.info(f"Found plot {filename} of size {new_provers[filename].prover.get_size()}") if show_memo: plot_memo: bytes32 if pool_contract_puzzle_hash is None: plot_memo = stream_plot_info_pk(pool_public_key, farmer_public_key, local_master_sk) else: plot_memo = stream_plot_info_ph(pool_contract_puzzle_hash, farmer_public_key, local_master_sk) plot_memo_str: str = plot_memo.hex() log.info(f"Memo: {plot_memo_str}") return stat_info.st_size, new_provers return 0, new_provers def reduce_function(x: Tuple[int, Dict], y: Tuple[int, Dict]) -> Tuple[int, Dict]: (total_size1, new_provers1) = x (total_size2, new_provers2) = y return total_size1 + total_size2, {**new_provers1, **new_provers2} with ThreadPoolExecutor() as executor: initial_value: Tuple[int, Dict[Path, PlotInfo]] = (0, {}) total_size, new_provers = reduce(reduce_function, executor.map(process_file, all_filenames), initial_value) log.info( f"Loaded a total of {len(new_provers)} plots of size {total_size / (1024 ** 4)} TiB, in" f" {time.time()-start_time} seconds" ) return changed, new_provers, failed_to_open_filenames, no_key_filenames def find_duplicate_plot_IDs(all_filenames=None) -> None: if all_filenames is None: all_filenames = [] plot_ids_set = set() duplicate_plot_ids = set() all_filenames_str: List[str] = [] for filename in all_filenames: filename_str: str = str(filename) all_filenames_str.append(filename_str) filename_parts: List[str] = filename_str.split("-") plot_id: str = filename_parts[-1] # Skipped parsing and verifying plot ID for faster performance # Skipped checking K size for faster performance # Only checks end of filenames: 64 char plot ID + .plot = 69 characters if len(plot_id) == 69: if plot_id in plot_ids_set: duplicate_plot_ids.add(plot_id) else: plot_ids_set.add(plot_id) else: log.warning(f"{filename} does not end with -[64 char plot ID].plot") for plot_id in duplicate_plot_ids: log_message: str = plot_id + " found in multiple files:\n" duplicate_filenames: List[str] = [filename_str for filename_str in all_filenames_str if plot_id in filename_str] for filename_str in duplicate_filenames: log_message += "\t" + filename_str + "\n" log.warning(f"{log_message}")
import logging import threading import time import traceback from dataclasses import dataclass from functools import reduce from pathlib import Path from typing import Dict, List, Optional, Set, Tuple, Union from concurrent.futures.thread import ThreadPoolExecutor from blspy import G1Element, PrivateKey from chiapos import DiskProver from flax.consensus.pos_quality import UI_ACTUAL_SPACE_CONSTANT_FACTOR, _expected_plot_size from flax.types.blockchain_format.proof_of_space import ProofOfSpace from flax.types.blockchain_format.sized_bytes import bytes32 from flax.util.config import load_config, save_config from flax.wallet.derive_keys import master_sk_to_local_sk log = logging.getLogger(__name__) @dataclass class PlotInfo: prover: DiskProver pool_public_key: Optional[G1Element] pool_contract_puzzle_hash: Optional[bytes32] plot_public_key: G1Element file_size: int time_modified: float def _get_filenames(directory: Path) -> List[Path]: try: if not directory.exists(): log.warning(f"Directory: {directory} does not exist.") return [] except OSError as e: log.warning(f"Error checking if directory {directory} exists: {e}") return [] all_files: List[Path] = [] try: for child in directory.iterdir(): if not child.is_dir(): # If it is a file ending in .plot, add it - work around MacOS ._ files if child.suffix == ".plot" and not child.name.startswith("._"): all_files.append(child) else: log.info(f"Not checking subdirectory {child}, subdirectories not added by default") except Exception as e: log.warning(f"Error reading directory {directory} {e}") return all_files def get_plot_filenames(config: Dict) -> Dict[Path, List[Path]]: # Returns a map from directory to a list of all plots in the directory directory_names: List[str] = config["plot_directories"] all_files: Dict[Path, List[Path]] = {} for directory_name in directory_names: directory = Path(directory_name).resolve() all_files[directory] = _get_filenames(directory) return all_files def parse_plot_info(memo: bytes) -> Tuple[Union[G1Element, bytes32], G1Element, PrivateKey]: # Parses the plot info bytes into keys if len(memo) == (48 + 48 + 32): # This is a public key memo return ( G1Element.from_bytes(memo[:48]), G1Element.from_bytes(memo[48:96]), PrivateKey.from_bytes(memo[96:]), ) elif len(memo) == (32 + 48 + 32): # This is a pool_contract_puzzle_hash memo return ( bytes32(memo[:32]), G1Element.from_bytes(memo[32:80]), PrivateKey.from_bytes(memo[80:]), ) else: raise ValueError(f"Invalid number of bytes {len(memo)}") def stream_plot_info_pk( pool_public_key: G1Element, farmer_public_key: G1Element, local_master_sk: PrivateKey, ): # There are two ways to stream plot info: with a pool public key, or with a pool contract puzzle hash. # This one streams the public key, into bytes data = bytes(pool_public_key) + bytes(farmer_public_key) + bytes(local_master_sk) assert len(data) == (48 + 48 + 32) return data def stream_plot_info_ph( pool_contract_puzzle_hash: bytes32, farmer_public_key: G1Element, local_master_sk: PrivateKey, ): # There are two ways to stream plot info: with a pool public key, or with a pool contract puzzle hash. # This one streams the pool contract puzzle hash, into bytes data = pool_contract_puzzle_hash + bytes(farmer_public_key) + bytes(local_master_sk) assert len(data) == (32 + 48 + 32) return data def add_plot_directory(str_path: str, root_path: Path) -> Dict: config = load_config(root_path, "config.yaml") if str(Path(str_path).resolve()) not in config["harvester"]["plot_directories"]: config["harvester"]["plot_directories"].append(str(Path(str_path).resolve())) save_config(root_path, "config.yaml", config) return config def get_plot_directories(root_path: Path) -> List[str]: config = load_config(root_path, "config.yaml") return [str(Path(str_path).resolve()) for str_path in config["harvester"]["plot_directories"]] def remove_plot_directory(str_path: str, root_path: Path) -> None: config = load_config(root_path, "config.yaml") str_paths: List[str] = config["harvester"]["plot_directories"] # If path str matches exactly, remove if str_path in str_paths: str_paths.remove(str_path) # If path matcehs full path, remove new_paths = [Path(sp).resolve() for sp in str_paths] if Path(str_path).resolve() in new_paths: new_paths.remove(Path(str_path).resolve()) config["harvester"]["plot_directories"] = [str(np) for np in new_paths] save_config(root_path, "config.yaml", config) def load_plots( provers: Dict[Path, PlotInfo], failed_to_open_filenames: Dict[Path, int], farmer_public_keys: Optional[List[G1Element]], pool_public_keys: Optional[List[G1Element]], match_str: Optional[str], show_memo: bool, root_path: Path, open_no_key_filenames=False, ) -> Tuple[bool, Dict[Path, PlotInfo], Dict[Path, int], Set[Path]]: start_time = time.time() config_file = load_config(root_path, "config.yaml", "harvester") changed = False no_key_filenames: Set[Path] = set() log.info(f'Searching directories {config_file["plot_directories"]}') plot_filenames: Dict[Path, List[Path]] = get_plot_filenames(config_file) all_filenames: List[Path] = [] for paths in plot_filenames.values(): all_filenames += paths plot_ids: Set[bytes32] = set() plot_ids_lock = threading.Lock() if match_str is not None: log.info(f'Only loading plots that contain "{match_str}" in the file or directory name') def process_file(filename: Path) -> Tuple[int, Dict]: new_provers: Dict[Path, PlotInfo] = {} nonlocal changed filename_str = str(filename) if match_str is not None and match_str not in filename_str: return 0, new_provers if filename.exists(): if filename in failed_to_open_filenames and (time.time() - failed_to_open_filenames[filename]) < 1200: # Try once every 20 minutes to open the file return 0, new_provers if filename in provers: try: stat_info = filename.stat() except Exception as e: log.error(f"Failed to open file {filename}. {e}") return 0, new_provers if stat_info.st_mtime == provers[filename].time_modified: with plot_ids_lock: if provers[filename].prover.get_id() in plot_ids: log.warning(f"Have multiple copies of the plot {filename}, not adding it.") return 0, new_provers plot_ids.add(provers[filename].prover.get_id()) new_provers[filename] = provers[filename] return stat_info.st_size, new_provers try: prover = DiskProver(str(filename)) expected_size = _expected_plot_size(prover.get_size()) * UI_ACTUAL_SPACE_CONSTANT_FACTOR stat_info = filename.stat() # TODO: consider checking if the file was just written to (which would mean that the file is still # being copied). A segfault might happen in this edge case. if prover.get_size() >= 30 and stat_info.st_size < 0.98 * expected_size: log.warning( f"Not farming plot {filename}. Size is {stat_info.st_size / (1024**3)} GiB, but expected" f" at least: {expected_size / (1024 ** 3)} GiB. We assume the file is being copied." ) return 0, new_provers ( pool_public_key_or_puzzle_hash, farmer_public_key, local_master_sk, ) = parse_plot_info(prover.get_memo()) # Only use plots that correct keys associated with them if farmer_public_keys is not None and farmer_public_key not in farmer_public_keys: log.warning(f"Plot {filename} has a farmer public key that is not in the farmer's pk list.") no_key_filenames.add(filename) if not open_no_key_filenames: return 0, new_provers if isinstance(pool_public_key_or_puzzle_hash, G1Element): pool_public_key = pool_public_key_or_puzzle_hash pool_contract_puzzle_hash = None else: assert isinstance(pool_public_key_or_puzzle_hash, bytes32) pool_public_key = None pool_contract_puzzle_hash = pool_public_key_or_puzzle_hash if ( pool_public_keys is not None and pool_public_key is not None and pool_public_key not in pool_public_keys ): log.warning(f"Plot {filename} has a pool public key that is not in the farmer's pool pk list.") no_key_filenames.add(filename) if not open_no_key_filenames: return 0, new_provers stat_info = filename.stat() local_sk = master_sk_to_local_sk(local_master_sk) plot_public_key: G1Element = ProofOfSpace.generate_plot_public_key(local_sk.get_g1(), farmer_public_key) with plot_ids_lock: if prover.get_id() in plot_ids: log.warning(f"Have multiple copies of the plot {filename}, not adding it.") return 0, new_provers plot_ids.add(prover.get_id()) new_provers[filename] = PlotInfo( prover, pool_public_key, pool_contract_puzzle_hash, plot_public_key, stat_info.st_size, stat_info.st_mtime, ) changed = True except Exception as e: tb = traceback.format_exc() log.error(f"Failed to open file {filename}. {e} {tb}") failed_to_open_filenames[filename] = int(time.time()) return 0, new_provers log.info(f"Found plot {filename} of size {new_provers[filename].prover.get_size()}") if show_memo: plot_memo: bytes32 if pool_contract_puzzle_hash is None: plot_memo = stream_plot_info_pk(pool_public_key, farmer_public_key, local_master_sk) else: plot_memo = stream_plot_info_ph(pool_contract_puzzle_hash, farmer_public_key, local_master_sk) plot_memo_str: str = plot_memo.hex() log.info(f"Memo: {plot_memo_str}") return stat_info.st_size, new_provers return 0, new_provers def reduce_function(x: Tuple[int, Dict], y: Tuple[int, Dict]) -> Tuple[int, Dict]: (total_size1, new_provers1) = x (total_size2, new_provers2) = y return total_size1 + total_size2, {**new_provers1, **new_provers2} with ThreadPoolExecutor() as executor: initial_value: Tuple[int, Dict[Path, PlotInfo]] = (0, {}) total_size, new_provers = reduce(reduce_function, executor.map(process_file, all_filenames), initial_value) log.info( f"Loaded a total of {len(new_provers)} plots of size {total_size / (1024 ** 4)} TiB, in" f" {time.time()-start_time} seconds" ) return changed, new_provers, failed_to_open_filenames, no_key_filenames def find_duplicate_plot_IDs(all_filenames=None) -> None: if all_filenames is None: all_filenames = [] plot_ids_set = set() duplicate_plot_ids = set() all_filenames_str: List[str] = [] for filename in all_filenames: filename_str: str = str(filename) all_filenames_str.append(filename_str) filename_parts: List[str] = filename_str.split("-") plot_id: str = filename_parts[-1] # Skipped parsing and verifying plot ID for faster performance # Skipped checking K size for faster performance # Only checks end of filenames: 64 char plot ID + .plot = 69 characters if len(plot_id) == 69: if plot_id in plot_ids_set: duplicate_plot_ids.add(plot_id) else: plot_ids_set.add(plot_id) else: log.warning(f"{filename} does not end with -[64 char plot ID].plot") for plot_id in duplicate_plot_ids: log_message: str = plot_id + " found in multiple files:\n" duplicate_filenames: List[str] = [filename_str for filename_str in all_filenames_str if plot_id in filename_str] for filename_str in duplicate_filenames: log_message += "\t" + filename_str + "\n" log.warning(f"{log_message}")
import os import pickle as pkl from hashlib import md5 from urllib.parse import urlparse import requests import wikipedia as wikipedia_api from requests import utils as requests_utils from wikidata.client import Client from wikidata.entity import Entity, EntityId, EntityState from tomt.data.imdb import ImdbID WIKIDATA_CLIENT = Client() ISBN_10_PROP = "P957" ISBN_13_PROP = "P212" def read_wikiplots(path): with open(os.path.join(path, "titles")) as reader: titles = [] for title in reader: titles.append(title.strip()) with open(os.path.join(path, "plots")) as reader: plots = [] current_plot = [] for line in reader: if line.strip() == "<EOS>": plots.append("\n".join(current_plot)) current_plot = [] else: current_plot.append(line.strip()) if len(current_plot) > 0: plots.append("\n".join(current_plot)) assert len(titles) == len(plots) return {t: p for (t, p) in zip(titles, plots)} def extract_wiki_titles(urls): titles = set() for url in urls: url = urlparse(url) titles.add(url.path.split("/")[-1]) return titles class WikiApi: def __init__(self, cache_location, wiki_search_limit): self.cache_location = cache_location os.makedirs(self.cache_location, exist_ok=True) os.makedirs(os.path.join(self.cache_location, "page_failures"), exist_ok=True) self.wiki_search_limit = wiki_search_limit def get_qids_from_title(self, wiki_title): # Given a wikipedia title, this function makes # an API call to wikipedia and searches for # candidate entities. It then extracts the # wikidata-qid from each result and returns it payload = { "action": "query", "prop": "pageprops", "ppprop": "wikibase_item", "redirects": "1", "titles": wiki_title, "format": "json" } r = requests.get(f"https://en.wikipedia.org/w/api.php", payload) if r.status_code != 200: raise ValueError("Error with HTTP Request!") jj = r.json() if "query" not in jj: return None query = jj["query"] pages = query.get("pages", dict()) if len(pages) == 0: return None qids = [] for page_id, page in pages.items(): if "pageprops" not in page: continue if "wikibase_item" not in page["pageprops"]: continue rr = { "title": page["title"], # the normalized title, "id": page["pageprops"]["wikibase_item"] # WikiData Q-ID } qids.append(rr) return qids def get_entity(self, qid): # Returns the wikidata entitiy associated with # the given QID file_loc = os.path.join(self.cache_location, qid) if os.path.exists(file_loc): with open(file_loc, "rb") as reader: ent_data = pkl.load(reader) ent = Entity(EntityId(qid), WIKIDATA_CLIENT) ent.data = ent_data ent.state = EntityState.loaded else: ent = WIKIDATA_CLIENT.get(qid, load=True) with open(file_loc, "wb") as writer: pkl.dump(ent.data, writer) return ent def write_page(self, page_id, page): ppath = os.path.join(self.cache_location, page_id) if not os.path.exists(ppath): try: with open(ppath, "wb") as writer: pkl.dump(page, writer) except FileNotFoundError: # happens with weird file names with open(os.path.join(self.cache_location, md5(page_id.encode('utf-8')).hexdigest()), "wb") as writer: pkl.dump(page, writer) def read_page(self, page_id): ppath = os.path.join(self.cache_location, page_id) if os.path.exists(ppath): with open(ppath, "rb") as reader: return pkl.load(reader) ppath = os.path.join(self.cache_location, md5(page_id.encode('utf-8')).hexdigest()) if os.path.exists(ppath): with open(ppath, "rb") as reader: return pkl.load(reader) return None def write_page_failure(self, page_id, reason): ppath = os.path.join(self.cache_location, "page_failures", page_id) if not os.path.exists(ppath): try: with open(ppath, "w") as writer: writer.write(reason) except FileNotFoundError: # happens with weird file names with open(os.path.join(self.cache_location, "page_failures", md5(page_id.encode('utf-8')).hexdigest()), "w") as writer: writer.write(reason) def check_page_failure(self, page_id): ppath = os.path.join(self.cache_location, "page_failures", page_id) if os.path.exists(ppath): with open(ppath, "r") as reader: return True, reader.read() ppath = os.path.join(self.cache_location, "page_failures", md5(page_id.encode('utf-8')).hexdigest()) if os.path.exists(ppath): with open(ppath, "r") as reader: return True, reader.read() return False, "" def delete_page_or_failure(self, page_id): ppaths = [os.path.join(self.cache_location, "page_failures", page_id), os.path.join(self.cache_location, page_id)] for ppath in ppaths: if os.path.exists(ppath): os.remove(ppath) def get_plot_info_from_wikipedia(self, page_id, keys_to_try=None): if keys_to_try is None: keys_to_try = ["Plot", "Plot summary"] failed, reason = self.check_page_failure(page_id) if failed: return None, reason page = self.read_page(page_id) if not page: try: page = wikipedia_api.page(page_id) self.write_page(page_id, page) except wikipedia_api.PageError: reason = f"Page with page ID '{page_id}' not found" self.write_page_failure(page_id, reason) return None, reason except wikipedia_api.exceptions.DisambiguationError: reason = f"Page with page ID '{page_id}' not found was unable to be disambiguated" self.write_page_failure(page_id, reason) return None, reason plot = None for key in keys_to_try: try: if page.section(key) is None: continue except KeyError: self.delete_page_or_failure(page_id) return None, "Page failed, try again" plot = page.section(key) break if not plot: reason = f"no plot found for '{page_id}'" self.write_page_failure(page_id, reason) return plot, reason return plot, "" def get_isbns(self, entity): def _get_prop(item): if item["mainsnak"]["snaktype"] == "novalue": return None, "mainsnak:novalue" else: if "datavalue" not in item["mainsnak"]: print(item) return item["mainsnak"]["datavalue"]["value"], "" def _get_prop_from_claim(claims, prop_name): if prop_name not in claims: return None, f"prop {prop_name} doesn't exist" prop = claims[prop_name] if len(prop) == 1: prop_value, fail_reason = _get_prop(prop[0]) if not prop_value: return None, fail_reason return prop_value, "" elif len(prop) > 1: raise ValueError(f"Multiple prop values for {prop}") elif len(prop) == 0: return None, f"Empty prop {prop}" claims = entity.data["claims"] isbn10, fail_reason = _get_prop_from_claim(claims, ISBN_10_PROP) if not isbn10: return (None, None), fail_reason isbn13, fail_reason = _get_prop_from_claim(claims, ISBN_13_PROP) if not isbn13: return (None, None), fail_reason return (isbn10, isbn13), "" def get_imdb_id(self, entity, imdb_api): # Extracts the IMDB ID from the wikidata # entity. This is the 'P345' property # Returns <imdb id or None>, <empty string if found OR reason for not finding it> def _get_from_p345_item(item): # input - item from the p345 array if item["mainsnak"]["snaktype"] == "novalue": return None, "mainsnak:novalue" else: if "datavalue" not in item["mainsnak"]: print(item) return ImdbID(item["mainsnak"]["datavalue"]["value"]), "" ll = entity.data["claims"] if "P345" not in ll: return None, "Doesn't have ImDB property!" p345 = ll["P345"] imdb_id = None reason = "" if len(p345) > 1: # in some cases (see Q5227700), there are multiple IMDB # ids associated with a single wikidata item. imdb_ids = set() fail_reasons = [] for l in p345: i, fail = _get_from_p345_item(l) if i and i.startswith("tt"): imdb_ids.add(ImdbID(i)) else: fail_reasons.append(fail) if len(imdb_ids) == 0: return None, "No IMDB Movie Ids found" + "::".join(fail_reasons) # see if the IDs resolve to a single one imdb_ids = imdb_api.resolve_redirects(imdb_ids) if len(imdb_ids) > 1: # TODO in other cases, handle this raise ValueError( f"Too many IMDB ids for entity {entity.data["id"]}: {p345}") imdb_id = list(imdb_ids)[0] else: imdb_id, reason = _get_from_p345_item(p345[0]) return imdb_id, reason def get_wiki_entities_from_imdb(self, imdb_id, movie, imdb_api): # Given an IMDB movie entity, this function queries # wikipedia to find wikipedia entries with similar # titles. It then retrieves the corresponding entity # and checks if the entity has the same ID as the # input movie. This is a bit (probably very) roundabout, # but the alternative is to query SPARQL which is very # slow! # It returns list of ( (title, url, ent), "") OR (None, "reason") # the api returns an empty object if not found if len(movie.data) == 0: return None, f"Unable to find imdb id {imdb_id}" imdb_id = ImdbID(movie.movieID) title = movie["title"] # now query wikidata to get the wiki title wiki_search_url = "https://en.wikipedia.org/w/api.php" payload = { "action": "opensearch", "search": title, "limit": self.wiki_search_limit, "namespace": 0, "format": "json" } results = requests.get(wiki_search_url, payload) if results.status_code != 200: raise ValueError( f"Recieved a non-200 response for {imdb_id}<>{title}") wiki_json = results.json() selected_titles = [] _, res_titles, _, res_links = wiki_json for title, url in zip(res_titles, res_links): qids = self.get_qids_from_title(title) for qid in qids: entity = self.get_entity(qid["id"]) ent_imdb_id, fail_reason = self.get_imdb_id(entity, imdb_api) if not ent_imdb_id: continue if imdb_id == ent_imdb_id: selected_titles.append((title, url, entity)) if len(selected_titles) == 0: return None, f"Unable to resolve {imdb_id}<>{title}" return selected_titles, "" def get_wikipedia_url_from_wikidata_id(self, wikidata_id, lang='en'): # From https://stackoverflow.com/a/60811917 # Given a QID, this function queries wikidata # and returns a list of URLS corresponding to this # particular QID url = ( 'https://www.wikidata.org/w/api.php' '?action=wbgetentities' '&props=sitelinks/urls' f'&ids={wikidata_id}' '&format=json') json_response = requests.get(url).json() entities = json_response.get('entities') if entities: entity = entities.get(wikidata_id) if entity: sitelinks = entity.get('sitelinks') if sitelinks: if lang: # filter only the specified language sitelink = sitelinks.get(f'{lang}wiki') if sitelink: wiki_url = sitelink.get('url') if wiki_url: return requests_utils.unquote(wiki_url) else: # return all of the urls wiki_urls = {} for key, sitelink in sitelinks.items(): wiki_url = sitelink.get('url') if wiki_url: wiki_urls[key] = requests_utils.unquote( wiki_url) return wiki_urls return None
import os import pickle as pkl from hashlib import md5 from urllib.parse import urlparse import requests import wikipedia as wikipedia_api from requests import utils as requests_utils from wikidata.client import Client from wikidata.entity import Entity, EntityId, EntityState from tomt.data.imdb import ImdbID WIKIDATA_CLIENT = Client() ISBN_10_PROP = "P957" ISBN_13_PROP = "P212" def read_wikiplots(path): with open(os.path.join(path, "titles")) as reader: titles = [] for title in reader: titles.append(title.strip()) with open(os.path.join(path, "plots")) as reader: plots = [] current_plot = [] for line in reader: if line.strip() == "<EOS>": plots.append("\n".join(current_plot)) current_plot = [] else: current_plot.append(line.strip()) if len(current_plot) > 0: plots.append("\n".join(current_plot)) assert len(titles) == len(plots) return {t: p for (t, p) in zip(titles, plots)} def extract_wiki_titles(urls): titles = set() for url in urls: url = urlparse(url) titles.add(url.path.split("/")[-1]) return titles class WikiApi: def __init__(self, cache_location, wiki_search_limit): self.cache_location = cache_location os.makedirs(self.cache_location, exist_ok=True) os.makedirs(os.path.join(self.cache_location, "page_failures"), exist_ok=True) self.wiki_search_limit = wiki_search_limit def get_qids_from_title(self, wiki_title): # Given a wikipedia title, this function makes # an API call to wikipedia and searches for # candidate entities. It then extracts the # wikidata-qid from each result and returns it payload = { "action": "query", "prop": "pageprops", "ppprop": "wikibase_item", "redirects": "1", "titles": wiki_title, "format": "json" } r = requests.get(f"https://en.wikipedia.org/w/api.php", payload) if r.status_code != 200: raise ValueError("Error with HTTP Request!") jj = r.json() if "query" not in jj: return None query = jj["query"] pages = query.get("pages", dict()) if len(pages) == 0: return None qids = [] for page_id, page in pages.items(): if "pageprops" not in page: continue if "wikibase_item" not in page["pageprops"]: continue rr = { "title": page["title"], # the normalized title, "id": page["pageprops"]["wikibase_item"] # WikiData Q-ID } qids.append(rr) return qids def get_entity(self, qid): # Returns the wikidata entitiy associated with # the given QID file_loc = os.path.join(self.cache_location, qid) if os.path.exists(file_loc): with open(file_loc, "rb") as reader: ent_data = pkl.load(reader) ent = Entity(EntityId(qid), WIKIDATA_CLIENT) ent.data = ent_data ent.state = EntityState.loaded else: ent = WIKIDATA_CLIENT.get(qid, load=True) with open(file_loc, "wb") as writer: pkl.dump(ent.data, writer) return ent def write_page(self, page_id, page): ppath = os.path.join(self.cache_location, page_id) if not os.path.exists(ppath): try: with open(ppath, "wb") as writer: pkl.dump(page, writer) except FileNotFoundError: # happens with weird file names with open(os.path.join(self.cache_location, md5(page_id.encode('utf-8')).hexdigest()), "wb") as writer: pkl.dump(page, writer) def read_page(self, page_id): ppath = os.path.join(self.cache_location, page_id) if os.path.exists(ppath): with open(ppath, "rb") as reader: return pkl.load(reader) ppath = os.path.join(self.cache_location, md5(page_id.encode('utf-8')).hexdigest()) if os.path.exists(ppath): with open(ppath, "rb") as reader: return pkl.load(reader) return None def write_page_failure(self, page_id, reason): ppath = os.path.join(self.cache_location, "page_failures", page_id) if not os.path.exists(ppath): try: with open(ppath, "w") as writer: writer.write(reason) except FileNotFoundError: # happens with weird file names with open(os.path.join(self.cache_location, "page_failures", md5(page_id.encode('utf-8')).hexdigest()), "w") as writer: writer.write(reason) def check_page_failure(self, page_id): ppath = os.path.join(self.cache_location, "page_failures", page_id) if os.path.exists(ppath): with open(ppath, "r") as reader: return True, reader.read() ppath = os.path.join(self.cache_location, "page_failures", md5(page_id.encode('utf-8')).hexdigest()) if os.path.exists(ppath): with open(ppath, "r") as reader: return True, reader.read() return False, "" def delete_page_or_failure(self, page_id): ppaths = [os.path.join(self.cache_location, "page_failures", page_id), os.path.join(self.cache_location, page_id)] for ppath in ppaths: if os.path.exists(ppath): os.remove(ppath) def get_plot_info_from_wikipedia(self, page_id, keys_to_try=None): if keys_to_try is None: keys_to_try = ["Plot", "Plot summary"] failed, reason = self.check_page_failure(page_id) if failed: return None, reason page = self.read_page(page_id) if not page: try: page = wikipedia_api.page(page_id) self.write_page(page_id, page) except wikipedia_api.PageError: reason = f"Page with page ID '{page_id}' not found" self.write_page_failure(page_id, reason) return None, reason except wikipedia_api.exceptions.DisambiguationError: reason = f"Page with page ID '{page_id}' not found was unable to be disambiguated" self.write_page_failure(page_id, reason) return None, reason plot = None for key in keys_to_try: try: if page.section(key) is None: continue except KeyError: self.delete_page_or_failure(page_id) return None, "Page failed, try again" plot = page.section(key) break if not plot: reason = f"no plot found for '{page_id}'" self.write_page_failure(page_id, reason) return plot, reason return plot, "" def get_isbns(self, entity): def _get_prop(item): if item["mainsnak"]["snaktype"] == "novalue": return None, "mainsnak:novalue" else: if "datavalue" not in item["mainsnak"]: print(item) return item["mainsnak"]["datavalue"]["value"], "" def _get_prop_from_claim(claims, prop_name): if prop_name not in claims: return None, f"prop {prop_name} doesn't exist" prop = claims[prop_name] if len(prop) == 1: prop_value, fail_reason = _get_prop(prop[0]) if not prop_value: return None, fail_reason return prop_value, "" elif len(prop) > 1: raise ValueError(f"Multiple prop values for {prop}") elif len(prop) == 0: return None, f"Empty prop {prop}" claims = entity.data["claims"] isbn10, fail_reason = _get_prop_from_claim(claims, ISBN_10_PROP) if not isbn10: return (None, None), fail_reason isbn13, fail_reason = _get_prop_from_claim(claims, ISBN_13_PROP) if not isbn13: return (None, None), fail_reason return (isbn10, isbn13), "" def get_imdb_id(self, entity, imdb_api): # Extracts the IMDB ID from the wikidata # entity. This is the 'P345' property # Returns <imdb id or None>, <empty string if found OR reason for not finding it> def _get_from_p345_item(item): # input - item from the p345 array if item["mainsnak"]["snaktype"] == "novalue": return None, "mainsnak:novalue" else: if "datavalue" not in item["mainsnak"]: print(item) return ImdbID(item["mainsnak"]["datavalue"]["value"]), "" ll = entity.data["claims"] if "P345" not in ll: return None, "Doesn't have ImDB property!" p345 = ll["P345"] imdb_id = None reason = "" if len(p345) > 1: # in some cases (see Q5227700), there are multiple IMDB # ids associated with a single wikidata item. imdb_ids = set() fail_reasons = [] for l in p345: i, fail = _get_from_p345_item(l) if i and i.startswith("tt"): imdb_ids.add(ImdbID(i)) else: fail_reasons.append(fail) if len(imdb_ids) == 0: return None, "No IMDB Movie Ids found" + "::".join(fail_reasons) # see if the IDs resolve to a single one imdb_ids = imdb_api.resolve_redirects(imdb_ids) if len(imdb_ids) > 1: # TODO in other cases, handle this raise ValueError( f"Too many IMDB ids for entity {entity.data['id']}: {p345}") imdb_id = list(imdb_ids)[0] else: imdb_id, reason = _get_from_p345_item(p345[0]) return imdb_id, reason def get_wiki_entities_from_imdb(self, imdb_id, movie, imdb_api): # Given an IMDB movie entity, this function queries # wikipedia to find wikipedia entries with similar # titles. It then retrieves the corresponding entity # and checks if the entity has the same ID as the # input movie. This is a bit (probably very) roundabout, # but the alternative is to query SPARQL which is very # slow! # It returns list of ( (title, url, ent), "") OR (None, "reason") # the api returns an empty object if not found if len(movie.data) == 0: return None, f"Unable to find imdb id {imdb_id}" imdb_id = ImdbID(movie.movieID) title = movie["title"] # now query wikidata to get the wiki title wiki_search_url = "https://en.wikipedia.org/w/api.php" payload = { "action": "opensearch", "search": title, "limit": self.wiki_search_limit, "namespace": 0, "format": "json" } results = requests.get(wiki_search_url, payload) if results.status_code != 200: raise ValueError( f"Recieved a non-200 response for {imdb_id}<>{title}") wiki_json = results.json() selected_titles = [] _, res_titles, _, res_links = wiki_json for title, url in zip(res_titles, res_links): qids = self.get_qids_from_title(title) for qid in qids: entity = self.get_entity(qid["id"]) ent_imdb_id, fail_reason = self.get_imdb_id(entity, imdb_api) if not ent_imdb_id: continue if imdb_id == ent_imdb_id: selected_titles.append((title, url, entity)) if len(selected_titles) == 0: return None, f"Unable to resolve {imdb_id}<>{title}" return selected_titles, "" def get_wikipedia_url_from_wikidata_id(self, wikidata_id, lang='en'): # From https://stackoverflow.com/a/60811917 # Given a QID, this function queries wikidata # and returns a list of URLS corresponding to this # particular QID url = ( 'https://www.wikidata.org/w/api.php' '?action=wbgetentities' '&props=sitelinks/urls' f'&ids={wikidata_id}' '&format=json') json_response = requests.get(url).json() entities = json_response.get('entities') if entities: entity = entities.get(wikidata_id) if entity: sitelinks = entity.get('sitelinks') if sitelinks: if lang: # filter only the specified language sitelink = sitelinks.get(f'{lang}wiki') if sitelink: wiki_url = sitelink.get('url') if wiki_url: return requests_utils.unquote(wiki_url) else: # return all of the urls wiki_urls = {} for key, sitelink in sitelinks.items(): wiki_url = sitelink.get('url') if wiki_url: wiki_urls[key] = requests_utils.unquote( wiki_url) return wiki_urls return None
from functools import wraps import numpy as np import inspect import re from dask import array as da from .utilcls import Progress from .._cupy import xp_ndarray, asnumpy __all__ = ["record", "record_lazy", "same_dtype", "dims_to_spatial_axes", "make_history", ] def record(func=None, *, append_history=True, record_label=False, only_binary=False, need_labels=False): def f(func): @wraps(func) def _record(self, *args, **kwargs): # check requirements of the ongoing function. if only_binary and self.dtype != bool: raise TypeError(f"Cannot run {func.__name__} with non-binary image.") if need_labels and not hasattr(self, "labels"): raise AttributeError(f"Function {func.__name__} needs labels." " Add labels to the image first.") # show the dimensionality of for-loop if "dims" in kwargs.keys(): ndim = len(kwargs["dims"]) suffix = f" ({ndim}D)" else: suffix = "" # start process with Progress(func.__name__ + suffix): out = func(self, *args, **kwargs) temp = getattr(out, "temp", None) if type(out) in (np.ndarray, xp_ndarray): out = asnumpy(out).view(self.__class__) # record history and update if needed ifupdate = kwargs.pop("update", False) if append_history: history = make_history(func.__name__, args, kwargs) if record_label: out.labels._set_info(self.labels, history) else: try: out._set_info(self, history) except AttributeError: pass ifupdate and self._update(out) # if temporary item exists if temp is not None: out.temp = temp return out return _record return f if func is None else f(func) def record_lazy(func=None, *, append_history=True, only_binary=False): def f(func): @wraps(func) def _record(self, *args, **kwargs): if only_binary and self.dtype != bool: raise TypeError(f"Cannot run {func.__name__} with non-binary image.") out = func(self, *args, **kwargs) if isinstance(out, da.core.Array): out = self.__class__(out) # record history and update if needed ifupdate = kwargs.pop("update", False) if append_history: history = make_history(func.__name__, args, kwargs) try: out._set_info(self, history) except AttributeError: pass if ifupdate: self.img = out.img self.history = out.history return out return _record return f if func is None else f(func) def same_dtype(func=None, asfloat=False): """ Decorator to assure output image has the same dtype as the input image. This decorator is compatible with both ImgArray and LazyImgArray. Parameters ---------- asfloat : bool, optional If input image should be converted to float first, by default False """ def f(func): @wraps(func) def _same_dtype(self, *args, **kwargs): dtype = self.dtype if asfloat and self.dtype.kind in "ui": self = self.as_float() out = func(self, *args, **kwargs) out = out.as_img_type(dtype) return out return _same_dtype return f if func is None else f(func) def dims_to_spatial_axes(func): """ Decorator to convert input `dims` to correct spatial axes. Compatible with ImgArray and LazyImgArray e.g.) dims=None (default) -> "yx" or "zyx" depend on the input image dims=2 -> "yx" dims=3 -> "zyx" dims="ty" -> "ty" """ @wraps(func) def _dims_to_spatial_axes(self, *args, **kwargs): dims = kwargs.get("dims", inspect.signature(func).parameters["dims"].default) if dims is None or dims=="": dims = len([a for a in "zyx" if a in self._axes]) if dims not in (2, 3): raise ValueError("Image must be 2 or 3 dimensional.") if isinstance(dims, int): s_axes = "".join([a for a in "zyx" if a in self._axes])[-dims:] else: s_axes = str(dims) kwargs["dims"] = s_axes # update input return func(self, *args, **kwargs) return _dims_to_spatial_axes def _safe_str(obj): try: if isinstance(obj, float): s = f"{obj:.3g}" else: s = str(obj) s = re.sub("\n", ";", s) if len(s) > 20: return str(type(obj)) else: return s except Exception: return str(type(obj)) def make_history(funcname, args, kwargs): _args = list(map(_safe_str, args)) _kwargs = [f"{_safe_str(k)}={_safe_str(v)}" for k, v in kwargs.items()] history = f"{funcname}({",".join(_args + _kwargs)})" return history
from functools import wraps import numpy as np import inspect import re from dask import array as da from .utilcls import Progress from .._cupy import xp_ndarray, asnumpy __all__ = ["record", "record_lazy", "same_dtype", "dims_to_spatial_axes", "make_history", ] def record(func=None, *, append_history=True, record_label=False, only_binary=False, need_labels=False): def f(func): @wraps(func) def _record(self, *args, **kwargs): # check requirements of the ongoing function. if only_binary and self.dtype != bool: raise TypeError(f"Cannot run {func.__name__} with non-binary image.") if need_labels and not hasattr(self, "labels"): raise AttributeError(f"Function {func.__name__} needs labels." " Add labels to the image first.") # show the dimensionality of for-loop if "dims" in kwargs.keys(): ndim = len(kwargs["dims"]) suffix = f" ({ndim}D)" else: suffix = "" # start process with Progress(func.__name__ + suffix): out = func(self, *args, **kwargs) temp = getattr(out, "temp", None) if type(out) in (np.ndarray, xp_ndarray): out = asnumpy(out).view(self.__class__) # record history and update if needed ifupdate = kwargs.pop("update", False) if append_history: history = make_history(func.__name__, args, kwargs) if record_label: out.labels._set_info(self.labels, history) else: try: out._set_info(self, history) except AttributeError: pass ifupdate and self._update(out) # if temporary item exists if temp is not None: out.temp = temp return out return _record return f if func is None else f(func) def record_lazy(func=None, *, append_history=True, only_binary=False): def f(func): @wraps(func) def _record(self, *args, **kwargs): if only_binary and self.dtype != bool: raise TypeError(f"Cannot run {func.__name__} with non-binary image.") out = func(self, *args, **kwargs) if isinstance(out, da.core.Array): out = self.__class__(out) # record history and update if needed ifupdate = kwargs.pop("update", False) if append_history: history = make_history(func.__name__, args, kwargs) try: out._set_info(self, history) except AttributeError: pass if ifupdate: self.img = out.img self.history = out.history return out return _record return f if func is None else f(func) def same_dtype(func=None, asfloat=False): """ Decorator to assure output image has the same dtype as the input image. This decorator is compatible with both ImgArray and LazyImgArray. Parameters ---------- asfloat : bool, optional If input image should be converted to float first, by default False """ def f(func): @wraps(func) def _same_dtype(self, *args, **kwargs): dtype = self.dtype if asfloat and self.dtype.kind in "ui": self = self.as_float() out = func(self, *args, **kwargs) out = out.as_img_type(dtype) return out return _same_dtype return f if func is None else f(func) def dims_to_spatial_axes(func): """ Decorator to convert input `dims` to correct spatial axes. Compatible with ImgArray and LazyImgArray e.g.) dims=None (default) -> "yx" or "zyx" depend on the input image dims=2 -> "yx" dims=3 -> "zyx" dims="ty" -> "ty" """ @wraps(func) def _dims_to_spatial_axes(self, *args, **kwargs): dims = kwargs.get("dims", inspect.signature(func).parameters["dims"].default) if dims is None or dims=="": dims = len([a for a in "zyx" if a in self._axes]) if dims not in (2, 3): raise ValueError("Image must be 2 or 3 dimensional.") if isinstance(dims, int): s_axes = "".join([a for a in "zyx" if a in self._axes])[-dims:] else: s_axes = str(dims) kwargs["dims"] = s_axes # update input return func(self, *args, **kwargs) return _dims_to_spatial_axes def _safe_str(obj): try: if isinstance(obj, float): s = f"{obj:.3g}" else: s = str(obj) s = re.sub("\n", ";", s) if len(s) > 20: return str(type(obj)) else: return s except Exception: return str(type(obj)) def make_history(funcname, args, kwargs): _args = list(map(_safe_str, args)) _kwargs = [f"{_safe_str(k)}={_safe_str(v)}" for k, v in kwargs.items()] history = f"{funcname}({','.join(_args + _kwargs)})" return history
#MIT License #Copyright (c) 2021 slgeekshow #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 os import requests from bot import bot as app from pyrogram import Client, filters @app.on_message(filters.command(["lyrics"])) async def lirik(_, message): rep = await message.reply_text("🔎 **searching your lyrics...**") try: if len(message.command) < 2: await message.reply_text("**give a lyric name too !**") return query = message.text.split(None, 1)[1] resp = requests.get(f"https://api-tede.herokuapp.com/api/lirik?l={query}").json() result = f"🎼 **lyrics search Successfully**✅\n\n◇───────────────◇ `{resp["data"]}´\n\n◇───────────────◇\n\n🔥**Downloaded by**:@szsongbot \n🌷 **Requestor** : {message.from_user.username}\n⚡️ **Powered By** : 【SZ™】\n\©2021【SZ™】 team **All Right Reserved**⚠️️ " await message.reply_text(result, disable_web_page_preview=True) await rep.delete() except Exception as ex: print(ex) await rep.edit("**Lyrics not found.** please give a valid song name !")
#MIT License #Copyright (c) 2021 slgeekshow #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 os import requests from bot import bot as app from pyrogram import Client, filters @app.on_message(filters.command(["lyrics"])) async def lirik(_, message): rep = await message.reply_text("🔎 **searching your lyrics...**") try: if len(message.command) < 2: await message.reply_text("**give a lyric name too !**") return query = message.text.split(None, 1)[1] resp = requests.get(f"https://api-tede.herokuapp.com/api/lirik?l={query}").json() result = f"🎼 **lyrics search Successfully**✅\n\n◇───────────────◇ `{resp['data']}´\n\n◇───────────────◇\n\n🔥**Downloaded by**:@szsongbot \n🌷 **Requestor** : {message.from_user.username}\n⚡️ **Powered By** : 【SZ™】\n\©2021【SZ™】 team **All Right Reserved**⚠️️ " await message.reply_text(result, disable_web_page_preview=True) await rep.delete() except Exception as ex: print(ex) await rep.edit("**Lyrics not found.** please give a valid song name !")
import datetime import flask import inspect import jwt import jwt.exceptions import redis import user_agents as ua import user_agents.parsers as ua_parser import typing import app.common.utils as utils import app.database as db_module import app.database.user as user_module db = db_module.db redis_db: redis.StrictRedis = db_module.redis_db RedisKeyType = db_module.RedisKeyType # Refresh token will expire after 61 days refresh_token_valid_duration: datetime.timedelta = datetime.timedelta(days=61) # Access token will expire after 1 hour access_token_valid_duration: datetime.timedelta = datetime.timedelta(hours=1) # Admin token will expire after 12 hours admin_token_valid_duration: datetime.timedelta = datetime.timedelta(hours=12) allowed_claim_in_jwt: list[str] = ['api_ver', 'iss', 'exp', 'user', 'sub', 'jti', 'role'] class TokenBase: # This will raise error when env var "RESTAPI_VERSION" not set. api_ver: str = flask.current_app.config.get('RESTAPI_VERSION') # Registered Claim iss: str = flask.current_app.config.get('SERVER_NAME') # Token Issuer(Fixed) exp: datetime.datetime = None # Expiration Unix Time sub: str = '' # Token name jti: int = -1 # JWT token ID # We won't use public claim yet # domain: str = '' # Private Claim user: int = -1 # Audience, User, Token holder role: str = '' # data: dict def is_admin(self): json_result = utils.safe_json_loads(self.role) if json_result and 'admin' in json_result: return True return False def create_token(self, key: str, algorithm: str = 'HS256') -> str: if not self.sub: raise jwt.exceptions.MissingRequiredClaimError('Subject not set in JWT class') if self.user and type(self.user) == int and self.user < 0: raise jwt.exceptions.MissingRequiredClaimError('Audience not set in JWT class') if self.jti and type(self.jti) == int and self.jti < 0: raise jwt.exceptions.MissingRequiredClaimError('Token ID not set in JWT class') current_time = datetime.datetime.utcnow().replace(tzinfo=utils.UTC) if type(self.exp) == int: token_exp_time = datetime.datetime.fromtimestamp(self.exp, utils.UTC) else: if self.exp: token_exp_time = self.exp.replace(tzinfo=utils.UTC) else: token_exp_time = None if (not token_exp_time) or (token_exp_time < current_time): raise jwt.exceptions.ExpiredSignatureError('Token has reached expiration time') result_payload = dict() attrs = inspect.getmembers(self, lambda o: not callable(o)) for attr_name, attr_value in attrs: if attr_name in allowed_claim_in_jwt: result_payload[attr_name] = attr_value return jwt.encode(payload=result_payload, key=key, algorithm=algorithm) @classmethod def from_token(cls, jwt_input: str, key: str, algorithm: str = 'HS256') -> 'TokenBase': token_data = jwt.decode(jwt_input, key=key, algorithms=algorithm) current_api_ver: str = flask.current_app.config.get('RESTAPI_VERSION') if token_data.get('api_ver', '') != current_api_ver: raise jwt.exceptions.InvalidTokenError('Token api version mismatch') if token_data.get('sub', '') != cls.sub: raise jwt.exceptions.InvalidTokenError('Token sub mismatch') token_exp_time = token_data.get('exp', 0) if type(token_exp_time) == int: if not token_exp_time: raise jwt.exceptions.ExpiredSignatureError('No expiration date included') token_exp_time = datetime.datetime.fromtimestamp(token_exp_time, utils.UTC) elif type(token_exp_time) == datetime.datetime: token_exp_time = token_exp_time.replace(tzinfo=utils.UTC) else: raise jwt.exceptions.InvalidTokenError('Expiration date could not be parsed') if token_exp_time < datetime.datetime.utcnow().replace(tzinfo=utils.UTC): raise jwt.exceptions.ExpiredSignatureError('Token has reached expiration time') token_data['exp'] = token_exp_time if token_data.get('user') < 0: raise jwt.exceptions.InvalidTokenError(f'User UUID in token is {token_data.get('user')}') # Filter and rebuild token data so that only allowed claim is in token token_data = {k: token_data[k] for k in token_data if k in allowed_claim_in_jwt} new_token = cls() new_token.__dict__.update(token_data) return new_token class AccessToken(TokenBase): # Registered Claim sub: str = 'Access' _refresh_token: 'RefreshToken' = None def create_token(self, key: str, algorithm: str = 'HS256', exp_reset: bool = True) -> str: if not RefreshToken.query.filter(RefreshToken.jti == self.jti).first(): raise Exception('Access Token could not be issued') new_token = super().create_token(key, algorithm=algorithm) # If new token safely issued, then remove revoked history redis_key = RedisKeyType.TOKEN_REVOKE.as_redis_key(self.jti) redis_result = redis_db.get(redis_key) if redis_result and redis_result == b'revoked': redis_db.delete(redis_key) return new_token @classmethod def from_token(cls, jwt_input: str, key: str, algorithm: str = 'HS256') -> 'AccessToken': parsed_token = super().from_token(jwt_input, key, algorithm) # Check if token's revoked redis_key = RedisKeyType.TOKEN_REVOKE.as_redis_key(parsed_token.jti) redis_result = redis_db.get(redis_key) if redis_result and redis_result == b'revoked': raise jwt.exceptions.InvalidTokenError('This token was revoked') return parsed_token @classmethod def from_refresh_token(cls, refresh_token: 'RefreshToken'): # Check refresh token exp current_time = datetime.datetime.utcnow().replace(tzinfo=utils.UTC) if type(refresh_token.exp) == int: token_exp_time = datetime.datetime.fromtimestamp(refresh_token.exp, utils.UTC) else: if refresh_token.exp: token_exp_time = refresh_token.exp.replace(tzinfo=utils.UTC) else: token_exp_time = None if (not token_exp_time) or (token_exp_time < current_time): raise jwt.exceptions.ExpiredSignatureError('Refresh token has reached expiration time') new_token = AccessToken() new_token._refresh_token = refresh_token new_token.exp = datetime.datetime.utcnow().replace(microsecond=0) # Drop microseconds new_token.exp += access_token_valid_duration new_token.user = refresh_token.user # Access token's JTI must be same with Refresh token's. new_token.jti = refresh_token.jti # role field must be refreshed from TB_USER new_token.role = refresh_token.usertable.role return new_token class RefreshToken(TokenBase, db.Model, db_module.DefaultModelMixin): __tablename__ = 'TB_REFRESH_TOKEN' # Registered Claim sub: str = 'Refresh' # Redefine fields to define SA's column on metadata # JWT token ID jti = db.Column(db_module.PrimaryKeyType, db.Sequence('SQ_RefreshToken_UUID'), primary_key=True) # Expiration Unix Time exp = db.Column(db.DateTime, nullable=False) # Audience, User, Token holder user = db.Column(db_module.PrimaryKeyType, db.ForeignKey('TB_USER.uuid'), nullable=False) # We need to change all refresh tokens' role when user's role is changed role = db.Column(db.String, nullable=True) ip_addr = db.Column(db.String, nullable=False) # Backref usertable: user_module.User = db.relationship( 'User', primaryjoin=user == user_module.User.uuid, backref=db.backref('refresh_tokens', order_by='RefreshToken.modified_at.desc()')) user_agent = db.Column(db.String, nullable=False) # Token data for sending notification on specific client device. # Only available on mobile. client_token = db.Column(db.String, nullable=True) @classmethod def from_usertable(cls, userdata: user_module.User) -> 'RefreshToken': new_token = cls() new_token.usertable = userdata new_token.role = userdata.role new_token.exp = datetime.datetime.utcnow().replace(microsecond=0) # Drop microseconds new_token.exp += refresh_token_valid_duration return new_token @classmethod def from_token(cls, jwt_input: str, key: str, algorithm: str = 'HS256') -> 'RefreshToken': token_data = jwt.decode(jwt_input, key=key, algorithms=algorithm) current_time: datetime.datetime = datetime.datetime.utcnow().replace(tzinfo=utils.UTC) current_api_ver: str = flask.current_app.config.get('RESTAPI_VERSION') if token_data.get('api_ver', '') != current_api_ver: raise jwt.exceptions.InvalidTokenError('Token api version mismatch') if token_data.get('sub', '') != cls.sub: raise jwt.exceptions.InvalidTokenError('Token sub mismatch') # Get token using JTI, but only target_token = RefreshToken.query.filter(RefreshToken.jti == token_data.get('jti', -1))\ .filter(RefreshToken.exp > current_time)\ .first() if not target_token: raise jwt.exceptions.InvalidTokenError('RefreshToken not found on DB') if type(target_token.exp) == int: target_token.exp = datetime.datetime.fromtimestamp(target_token.exp, utils.UTC) token_exp_time = target_token.exp.replace(tzinfo=utils.UTC) if token_exp_time < current_time: raise jwt.exceptions.ExpiredSignatureError('Refresh token has reached expiration time') db_token_exp = target_token.exp.replace(tzinfo=utils.UTC) cookie_token_exp = datetime.datetime.fromtimestamp(token_data.get('exp', 0), utils.UTC) if target_token.user == int(token_data.get('user', '')) and db_token_exp == cookie_token_exp: return target_token else: raise jwt.exceptions.InvalidTokenError('RefreshToken information mismatch') def create_token(self, key: str, algorithm: str = 'HS256', exp_reset: bool = True) -> str: if exp_reset: self.exp = datetime.datetime.utcnow().replace(microsecond=0) # Drop microseconds self.exp += refresh_token_valid_duration if self.jti and self.jti <= -1: self.jti = None db.session.add(self) try: db.session.commit() except Exception: db.session.rollback() raise return super().create_token(key, algorithm) class AdminToken(TokenBase): # Registered Claim sub: str = 'Admin' _refresh_token: 'RefreshToken' = None @classmethod def from_token(cls, jwt_input: str, key: str, algorithm: str = 'HS256') -> 'AccessToken': parsed_token = super().from_token(jwt_input, key, algorithm) # Check if token's revoked redis_key = RedisKeyType.TOKEN_REVOKE.as_redis_key(parsed_token.jti) redis_result = redis_db.get(redis_key) if redis_result and redis_result == b'revoked': raise jwt.exceptions.InvalidTokenError('This token was revoked') return parsed_token @classmethod def from_refresh_token(cls, refresh_token: 'RefreshToken'): # Check refresh token exp current_time = datetime.datetime.utcnow().replace(tzinfo=utils.UTC) if type(refresh_token.exp) == int: token_exp_time = datetime.datetime.fromtimestamp(refresh_token.exp, utils.UTC) else: if refresh_token.exp: token_exp_time = refresh_token.exp.replace(tzinfo=utils.UTC) else: token_exp_time = None if (not token_exp_time) or (token_exp_time < current_time): raise jwt.exceptions.ExpiredSignatureError('Refresh token has reached expiration time') new_token = AdminToken() new_token._refresh_token = refresh_token new_token.exp = datetime.datetime.utcnow().replace(microsecond=0) # Drop microseconds new_token.exp += admin_token_valid_duration new_token.user = refresh_token.user # Admin token's JTI must be same with Refresh token's. new_token.jti = refresh_token.jti new_token.role = refresh_token.role return new_token def create_login_data(user_data: user_module.User, user_agent: str, csrf_token: str, client_token: typing.Optional[str], ip_addr: str, key: str, algorithm: str = 'HS256')\ -> tuple[list[tuple[str, str]], dict[str, str]]: restapi_version = flask.current_app.config.get('RESTAPI_VERSION') server_name = flask.current_app.config.get('SERVER_NAME') https_enable = flask.current_app.config.get('HTTPS_ENABLE', True) cookie_samesite = ('None' if https_enable else 'Lax') if restapi_version == 'dev' else 'strict' response_header: list[tuple[str, str]] = list() response_data: dict[str, dict[str, str]] = dict() refresh_token = RefreshToken.from_usertable(user_data) refresh_token.user_agent = user_agent refresh_token.client_token = client_token refresh_token.ip_addr = ip_addr refresh_token_jwt = refresh_token.create_token(key, algorithm, True) refresh_token_cookie = utils.cookie_creator( name='refresh_token', data=refresh_token_jwt, domain=server_name if restapi_version != 'dev' else None, path=f'/api/{refresh_token.api_ver}/account', expires=utils.cookie_datetime(refresh_token.exp), samesite=cookie_samesite, secure=https_enable) response_header.append(('Set-Cookie', refresh_token_cookie)) response_data['refresh_token'] = {'exp': refresh_token.exp, } access_token = AccessToken.from_refresh_token(refresh_token) access_token_jwt = access_token.create_token(key+csrf_token, algorithm, True) response_data['access_token'] = { 'exp': refresh_token.exp, 'token': access_token_jwt, } if refresh_token.role and 'admin' in refresh_token.role: # This user is admin, so we need to issue admin token and send this with cookie. admin_token = AdminToken.from_refresh_token(refresh_token) admin_token_jwt = admin_token.create_token(key) admin_token_cookie = utils.cookie_creator( name='admin_token', data=admin_token_jwt, domain=server_name if restapi_version != 'dev' else None, path=f'/api/{refresh_token.api_ver}/admin', expires=utils.cookie_datetime(refresh_token.exp), samesite=cookie_samesite, secure=https_enable) response_header.append(('Set-Cookie', admin_token_cookie)) response_data['admin_token'] = {'exp': admin_token.exp, } return response_header, response_data def refresh_login_data(refresh_token_jwt: str, user_agent: str, csrf_token: str, client_token: typing.Optional[str], ip_addr: str, key: str, algorithm: str = 'HS256')\ -> tuple[list[tuple[str, str]], dict[str, str]]: restapi_version = flask.current_app.config.get('RESTAPI_VERSION') server_name = flask.current_app.config.get('SERVER_NAME') https_enable = flask.current_app.config.get('HTTPS_ENABLE', True) cookie_samesite = ('None' if https_enable else 'Lax') if restapi_version == 'dev' else 'strict' response_header: list[tuple[str, str]] = list() response_data: dict[str, dict[str, str]] = dict() refresh_token = RefreshToken.from_token(refresh_token_jwt, key) # Check device type/OS/browser using User-Agent. # We'll refresh token only if it's same with db records try: db_ua: ua_parser.UserAgent = ua.parse(refresh_token.user_agent) req_ua: ua_parser.UserAgent = ua.parse(user_agent) check_result: bool = all(( any(( db_ua.is_mobile == req_ua.is_mobile, db_ua.is_tablet == req_ua.is_tablet, db_ua.is_pc == req_ua.is_pc, )), db_ua.os.family == req_ua.os.family, db_ua.browser.family == req_ua.browser.family, )) if not check_result: raise jwt.exceptions.InvalidTokenError('User-Agent does not compatable') except jwt.exceptions.InvalidTokenError: raise except Exception: raise jwt.exceptions.InvalidTokenError('User-Agent not parsable') # Refresh token will be re-issued only when there's 10 days left until token expires token_exp_time = refresh_token.exp.replace(tzinfo=utils.UTC) if token_exp_time < datetime.datetime.utcnow().replace(tzinfo=utils.UTC) + datetime.timedelta(days=10): try: # Re-issue refresh token refresh_token.user_agent = user_agent refresh_token.ip_addr = ip_addr refresh_token_jwt = refresh_token.create_token(key, algorithm, True) db.session.commit() refresh_token_cookie = utils.cookie_creator( name='refresh_token', data=refresh_token_jwt, domain=server_name if restapi_version != 'dev' else None, path=f'/api/{refresh_token.api_ver}/account', expires=utils.cookie_datetime(refresh_token.exp), samesite=cookie_samesite, secure=https_enable) response_header.append(('Set-Cookie', refresh_token_cookie)) except Exception: # It's OK to ignore error while re-issueing refresh token db.session.rollback() finally: # We need to send refresh token expiration date anyway response_data['refresh_token'] = {'exp': refresh_token.exp, } # If client requests token change, then we need to commit this on db elif refresh_token.client_token != client_token: refresh_token.client_token = client_token db.session.commit() # Now, re-issue Access token # Access token can always be re-issued access_token = AccessToken.from_refresh_token(refresh_token) access_token_jwt = access_token.create_token(key+csrf_token, algorithm, True) response_data['access_token'] = { 'exp': access_token.exp, 'token': access_token_jwt, } # Re-issue Admin token if user is admin if refresh_token.role and 'admin' in refresh_token.role: admin_token = AdminToken.from_refresh_token(refresh_token) admin_token_jwt = admin_token.create_token(key) admin_token_cookie = utils.cookie_creator( name='admin_token', data=admin_token_jwt, domain=server_name if restapi_version != 'dev' else None, path=f'/api/{refresh_token.api_ver}/admin', expires=utils.cookie_datetime(refresh_token.exp), samesite=cookie_samesite, secure=https_enable) response_header.append(('Set-Cookie', admin_token_cookie)) response_data['admin_token'] = {'exp': admin_token.exp, } return response_header, response_data
import datetime import flask import inspect import jwt import jwt.exceptions import redis import user_agents as ua import user_agents.parsers as ua_parser import typing import app.common.utils as utils import app.database as db_module import app.database.user as user_module db = db_module.db redis_db: redis.StrictRedis = db_module.redis_db RedisKeyType = db_module.RedisKeyType # Refresh token will expire after 61 days refresh_token_valid_duration: datetime.timedelta = datetime.timedelta(days=61) # Access token will expire after 1 hour access_token_valid_duration: datetime.timedelta = datetime.timedelta(hours=1) # Admin token will expire after 12 hours admin_token_valid_duration: datetime.timedelta = datetime.timedelta(hours=12) allowed_claim_in_jwt: list[str] = ['api_ver', 'iss', 'exp', 'user', 'sub', 'jti', 'role'] class TokenBase: # This will raise error when env var "RESTAPI_VERSION" not set. api_ver: str = flask.current_app.config.get('RESTAPI_VERSION') # Registered Claim iss: str = flask.current_app.config.get('SERVER_NAME') # Token Issuer(Fixed) exp: datetime.datetime = None # Expiration Unix Time sub: str = '' # Token name jti: int = -1 # JWT token ID # We won't use public claim yet # domain: str = '' # Private Claim user: int = -1 # Audience, User, Token holder role: str = '' # data: dict def is_admin(self): json_result = utils.safe_json_loads(self.role) if json_result and 'admin' in json_result: return True return False def create_token(self, key: str, algorithm: str = 'HS256') -> str: if not self.sub: raise jwt.exceptions.MissingRequiredClaimError('Subject not set in JWT class') if self.user and type(self.user) == int and self.user < 0: raise jwt.exceptions.MissingRequiredClaimError('Audience not set in JWT class') if self.jti and type(self.jti) == int and self.jti < 0: raise jwt.exceptions.MissingRequiredClaimError('Token ID not set in JWT class') current_time = datetime.datetime.utcnow().replace(tzinfo=utils.UTC) if type(self.exp) == int: token_exp_time = datetime.datetime.fromtimestamp(self.exp, utils.UTC) else: if self.exp: token_exp_time = self.exp.replace(tzinfo=utils.UTC) else: token_exp_time = None if (not token_exp_time) or (token_exp_time < current_time): raise jwt.exceptions.ExpiredSignatureError('Token has reached expiration time') result_payload = dict() attrs = inspect.getmembers(self, lambda o: not callable(o)) for attr_name, attr_value in attrs: if attr_name in allowed_claim_in_jwt: result_payload[attr_name] = attr_value return jwt.encode(payload=result_payload, key=key, algorithm=algorithm) @classmethod def from_token(cls, jwt_input: str, key: str, algorithm: str = 'HS256') -> 'TokenBase': token_data = jwt.decode(jwt_input, key=key, algorithms=algorithm) current_api_ver: str = flask.current_app.config.get('RESTAPI_VERSION') if token_data.get('api_ver', '') != current_api_ver: raise jwt.exceptions.InvalidTokenError('Token api version mismatch') if token_data.get('sub', '') != cls.sub: raise jwt.exceptions.InvalidTokenError('Token sub mismatch') token_exp_time = token_data.get('exp', 0) if type(token_exp_time) == int: if not token_exp_time: raise jwt.exceptions.ExpiredSignatureError('No expiration date included') token_exp_time = datetime.datetime.fromtimestamp(token_exp_time, utils.UTC) elif type(token_exp_time) == datetime.datetime: token_exp_time = token_exp_time.replace(tzinfo=utils.UTC) else: raise jwt.exceptions.InvalidTokenError('Expiration date could not be parsed') if token_exp_time < datetime.datetime.utcnow().replace(tzinfo=utils.UTC): raise jwt.exceptions.ExpiredSignatureError('Token has reached expiration time') token_data['exp'] = token_exp_time if token_data.get('user') < 0: raise jwt.exceptions.InvalidTokenError(f'User UUID in token is {token_data.get("user")}') # Filter and rebuild token data so that only allowed claim is in token token_data = {k: token_data[k] for k in token_data if k in allowed_claim_in_jwt} new_token = cls() new_token.__dict__.update(token_data) return new_token class AccessToken(TokenBase): # Registered Claim sub: str = 'Access' _refresh_token: 'RefreshToken' = None def create_token(self, key: str, algorithm: str = 'HS256', exp_reset: bool = True) -> str: if not RefreshToken.query.filter(RefreshToken.jti == self.jti).first(): raise Exception('Access Token could not be issued') new_token = super().create_token(key, algorithm=algorithm) # If new token safely issued, then remove revoked history redis_key = RedisKeyType.TOKEN_REVOKE.as_redis_key(self.jti) redis_result = redis_db.get(redis_key) if redis_result and redis_result == b'revoked': redis_db.delete(redis_key) return new_token @classmethod def from_token(cls, jwt_input: str, key: str, algorithm: str = 'HS256') -> 'AccessToken': parsed_token = super().from_token(jwt_input, key, algorithm) # Check if token's revoked redis_key = RedisKeyType.TOKEN_REVOKE.as_redis_key(parsed_token.jti) redis_result = redis_db.get(redis_key) if redis_result and redis_result == b'revoked': raise jwt.exceptions.InvalidTokenError('This token was revoked') return parsed_token @classmethod def from_refresh_token(cls, refresh_token: 'RefreshToken'): # Check refresh token exp current_time = datetime.datetime.utcnow().replace(tzinfo=utils.UTC) if type(refresh_token.exp) == int: token_exp_time = datetime.datetime.fromtimestamp(refresh_token.exp, utils.UTC) else: if refresh_token.exp: token_exp_time = refresh_token.exp.replace(tzinfo=utils.UTC) else: token_exp_time = None if (not token_exp_time) or (token_exp_time < current_time): raise jwt.exceptions.ExpiredSignatureError('Refresh token has reached expiration time') new_token = AccessToken() new_token._refresh_token = refresh_token new_token.exp = datetime.datetime.utcnow().replace(microsecond=0) # Drop microseconds new_token.exp += access_token_valid_duration new_token.user = refresh_token.user # Access token's JTI must be same with Refresh token's. new_token.jti = refresh_token.jti # role field must be refreshed from TB_USER new_token.role = refresh_token.usertable.role return new_token class RefreshToken(TokenBase, db.Model, db_module.DefaultModelMixin): __tablename__ = 'TB_REFRESH_TOKEN' # Registered Claim sub: str = 'Refresh' # Redefine fields to define SA's column on metadata # JWT token ID jti = db.Column(db_module.PrimaryKeyType, db.Sequence('SQ_RefreshToken_UUID'), primary_key=True) # Expiration Unix Time exp = db.Column(db.DateTime, nullable=False) # Audience, User, Token holder user = db.Column(db_module.PrimaryKeyType, db.ForeignKey('TB_USER.uuid'), nullable=False) # We need to change all refresh tokens' role when user's role is changed role = db.Column(db.String, nullable=True) ip_addr = db.Column(db.String, nullable=False) # Backref usertable: user_module.User = db.relationship( 'User', primaryjoin=user == user_module.User.uuid, backref=db.backref('refresh_tokens', order_by='RefreshToken.modified_at.desc()')) user_agent = db.Column(db.String, nullable=False) # Token data for sending notification on specific client device. # Only available on mobile. client_token = db.Column(db.String, nullable=True) @classmethod def from_usertable(cls, userdata: user_module.User) -> 'RefreshToken': new_token = cls() new_token.usertable = userdata new_token.role = userdata.role new_token.exp = datetime.datetime.utcnow().replace(microsecond=0) # Drop microseconds new_token.exp += refresh_token_valid_duration return new_token @classmethod def from_token(cls, jwt_input: str, key: str, algorithm: str = 'HS256') -> 'RefreshToken': token_data = jwt.decode(jwt_input, key=key, algorithms=algorithm) current_time: datetime.datetime = datetime.datetime.utcnow().replace(tzinfo=utils.UTC) current_api_ver: str = flask.current_app.config.get('RESTAPI_VERSION') if token_data.get('api_ver', '') != current_api_ver: raise jwt.exceptions.InvalidTokenError('Token api version mismatch') if token_data.get('sub', '') != cls.sub: raise jwt.exceptions.InvalidTokenError('Token sub mismatch') # Get token using JTI, but only target_token = RefreshToken.query.filter(RefreshToken.jti == token_data.get('jti', -1))\ .filter(RefreshToken.exp > current_time)\ .first() if not target_token: raise jwt.exceptions.InvalidTokenError('RefreshToken not found on DB') if type(target_token.exp) == int: target_token.exp = datetime.datetime.fromtimestamp(target_token.exp, utils.UTC) token_exp_time = target_token.exp.replace(tzinfo=utils.UTC) if token_exp_time < current_time: raise jwt.exceptions.ExpiredSignatureError('Refresh token has reached expiration time') db_token_exp = target_token.exp.replace(tzinfo=utils.UTC) cookie_token_exp = datetime.datetime.fromtimestamp(token_data.get('exp', 0), utils.UTC) if target_token.user == int(token_data.get('user', '')) and db_token_exp == cookie_token_exp: return target_token else: raise jwt.exceptions.InvalidTokenError('RefreshToken information mismatch') def create_token(self, key: str, algorithm: str = 'HS256', exp_reset: bool = True) -> str: if exp_reset: self.exp = datetime.datetime.utcnow().replace(microsecond=0) # Drop microseconds self.exp += refresh_token_valid_duration if self.jti and self.jti <= -1: self.jti = None db.session.add(self) try: db.session.commit() except Exception: db.session.rollback() raise return super().create_token(key, algorithm) class AdminToken(TokenBase): # Registered Claim sub: str = 'Admin' _refresh_token: 'RefreshToken' = None @classmethod def from_token(cls, jwt_input: str, key: str, algorithm: str = 'HS256') -> 'AccessToken': parsed_token = super().from_token(jwt_input, key, algorithm) # Check if token's revoked redis_key = RedisKeyType.TOKEN_REVOKE.as_redis_key(parsed_token.jti) redis_result = redis_db.get(redis_key) if redis_result and redis_result == b'revoked': raise jwt.exceptions.InvalidTokenError('This token was revoked') return parsed_token @classmethod def from_refresh_token(cls, refresh_token: 'RefreshToken'): # Check refresh token exp current_time = datetime.datetime.utcnow().replace(tzinfo=utils.UTC) if type(refresh_token.exp) == int: token_exp_time = datetime.datetime.fromtimestamp(refresh_token.exp, utils.UTC) else: if refresh_token.exp: token_exp_time = refresh_token.exp.replace(tzinfo=utils.UTC) else: token_exp_time = None if (not token_exp_time) or (token_exp_time < current_time): raise jwt.exceptions.ExpiredSignatureError('Refresh token has reached expiration time') new_token = AdminToken() new_token._refresh_token = refresh_token new_token.exp = datetime.datetime.utcnow().replace(microsecond=0) # Drop microseconds new_token.exp += admin_token_valid_duration new_token.user = refresh_token.user # Admin token's JTI must be same with Refresh token's. new_token.jti = refresh_token.jti new_token.role = refresh_token.role return new_token def create_login_data(user_data: user_module.User, user_agent: str, csrf_token: str, client_token: typing.Optional[str], ip_addr: str, key: str, algorithm: str = 'HS256')\ -> tuple[list[tuple[str, str]], dict[str, str]]: restapi_version = flask.current_app.config.get('RESTAPI_VERSION') server_name = flask.current_app.config.get('SERVER_NAME') https_enable = flask.current_app.config.get('HTTPS_ENABLE', True) cookie_samesite = ('None' if https_enable else 'Lax') if restapi_version == 'dev' else 'strict' response_header: list[tuple[str, str]] = list() response_data: dict[str, dict[str, str]] = dict() refresh_token = RefreshToken.from_usertable(user_data) refresh_token.user_agent = user_agent refresh_token.client_token = client_token refresh_token.ip_addr = ip_addr refresh_token_jwt = refresh_token.create_token(key, algorithm, True) refresh_token_cookie = utils.cookie_creator( name='refresh_token', data=refresh_token_jwt, domain=server_name if restapi_version != 'dev' else None, path=f'/api/{refresh_token.api_ver}/account', expires=utils.cookie_datetime(refresh_token.exp), samesite=cookie_samesite, secure=https_enable) response_header.append(('Set-Cookie', refresh_token_cookie)) response_data['refresh_token'] = {'exp': refresh_token.exp, } access_token = AccessToken.from_refresh_token(refresh_token) access_token_jwt = access_token.create_token(key+csrf_token, algorithm, True) response_data['access_token'] = { 'exp': refresh_token.exp, 'token': access_token_jwt, } if refresh_token.role and 'admin' in refresh_token.role: # This user is admin, so we need to issue admin token and send this with cookie. admin_token = AdminToken.from_refresh_token(refresh_token) admin_token_jwt = admin_token.create_token(key) admin_token_cookie = utils.cookie_creator( name='admin_token', data=admin_token_jwt, domain=server_name if restapi_version != 'dev' else None, path=f'/api/{refresh_token.api_ver}/admin', expires=utils.cookie_datetime(refresh_token.exp), samesite=cookie_samesite, secure=https_enable) response_header.append(('Set-Cookie', admin_token_cookie)) response_data['admin_token'] = {'exp': admin_token.exp, } return response_header, response_data def refresh_login_data(refresh_token_jwt: str, user_agent: str, csrf_token: str, client_token: typing.Optional[str], ip_addr: str, key: str, algorithm: str = 'HS256')\ -> tuple[list[tuple[str, str]], dict[str, str]]: restapi_version = flask.current_app.config.get('RESTAPI_VERSION') server_name = flask.current_app.config.get('SERVER_NAME') https_enable = flask.current_app.config.get('HTTPS_ENABLE', True) cookie_samesite = ('None' if https_enable else 'Lax') if restapi_version == 'dev' else 'strict' response_header: list[tuple[str, str]] = list() response_data: dict[str, dict[str, str]] = dict() refresh_token = RefreshToken.from_token(refresh_token_jwt, key) # Check device type/OS/browser using User-Agent. # We'll refresh token only if it's same with db records try: db_ua: ua_parser.UserAgent = ua.parse(refresh_token.user_agent) req_ua: ua_parser.UserAgent = ua.parse(user_agent) check_result: bool = all(( any(( db_ua.is_mobile == req_ua.is_mobile, db_ua.is_tablet == req_ua.is_tablet, db_ua.is_pc == req_ua.is_pc, )), db_ua.os.family == req_ua.os.family, db_ua.browser.family == req_ua.browser.family, )) if not check_result: raise jwt.exceptions.InvalidTokenError('User-Agent does not compatable') except jwt.exceptions.InvalidTokenError: raise except Exception: raise jwt.exceptions.InvalidTokenError('User-Agent not parsable') # Refresh token will be re-issued only when there's 10 days left until token expires token_exp_time = refresh_token.exp.replace(tzinfo=utils.UTC) if token_exp_time < datetime.datetime.utcnow().replace(tzinfo=utils.UTC) + datetime.timedelta(days=10): try: # Re-issue refresh token refresh_token.user_agent = user_agent refresh_token.ip_addr = ip_addr refresh_token_jwt = refresh_token.create_token(key, algorithm, True) db.session.commit() refresh_token_cookie = utils.cookie_creator( name='refresh_token', data=refresh_token_jwt, domain=server_name if restapi_version != 'dev' else None, path=f'/api/{refresh_token.api_ver}/account', expires=utils.cookie_datetime(refresh_token.exp), samesite=cookie_samesite, secure=https_enable) response_header.append(('Set-Cookie', refresh_token_cookie)) except Exception: # It's OK to ignore error while re-issueing refresh token db.session.rollback() finally: # We need to send refresh token expiration date anyway response_data['refresh_token'] = {'exp': refresh_token.exp, } # If client requests token change, then we need to commit this on db elif refresh_token.client_token != client_token: refresh_token.client_token = client_token db.session.commit() # Now, re-issue Access token # Access token can always be re-issued access_token = AccessToken.from_refresh_token(refresh_token) access_token_jwt = access_token.create_token(key+csrf_token, algorithm, True) response_data['access_token'] = { 'exp': access_token.exp, 'token': access_token_jwt, } # Re-issue Admin token if user is admin if refresh_token.role and 'admin' in refresh_token.role: admin_token = AdminToken.from_refresh_token(refresh_token) admin_token_jwt = admin_token.create_token(key) admin_token_cookie = utils.cookie_creator( name='admin_token', data=admin_token_jwt, domain=server_name if restapi_version != 'dev' else None, path=f'/api/{refresh_token.api_ver}/admin', expires=utils.cookie_datetime(refresh_token.exp), samesite=cookie_samesite, secure=https_enable) response_header.append(('Set-Cookie', admin_token_cookie)) response_data['admin_token'] = {'exp': admin_token.exp, } return response_header, response_data
import grpc from cli.constants import METAMAP from proto.python.uwbionlp_pb2 import MetaMapInput from proto.python.uwbionlp_pb2_grpc import MetaMapStub class MetaMapChannelManager(): def __init__(self, container): self.name = METAMAP self.host = container.host self.port = container.port self.wait_secs = 10 def open(self): self.channel = grpc.insecure_channel(f'{self.host}:{self.port}') def close(self): self.channel.close() def generate_client(self, args): return MetaMapClient(self.channel, args) class MetaMapClient(): def __init__(self, channel, args): self.name = METAMAP self.stub = MetaMapStub(channel) self.channel = channel self.args = args def process(self, doc): response = self.stub.ExtractNamedEntities(MetaMapInput(id=doc.id, sentences=doc.sentences, semantic_types=self.args.metamap_semantic_types)) return response def to_dict(self, response): output = { 'sentences': [], 'errors': [ err for err in response.errors] } for sent in response.sentences: sentence = { 'id': sent.id, 'text': sent.text, 'concepts': [], 'beginCharIndex': sent.begin_char_index, 'endCharIndex': sent.end_char_index, } for con in sent.concepts: concept = { 'beginSentenceCharIndex': con.begin_sent_char_index, 'endSentenceCharIndex': con.end_sent_char_index, 'beginDocumentCharIndex': con.begin_doc_char_index, 'endDocumentCharIndex': con.end_doc_char_index, 'cui': con.cui, 'semanticTypes': [ st for st in con.semantic_types ], 'sourcePhrase': con.source_phrase, 'conceptName': con.concept_name, 'prediction': con.prediction } sentence['concepts'].append(concept) output['sentences'].append(sentence) return output def merge(self, base_json, client_json): base_json[self.name] = { 'concepts': [], 'errors': client_json['errors'] } for sentence in client_json['sentences']: for con in sentence['concepts']: base_json[self.name]['concepts'].append(con) return base_json def to_brat(self, client_json): t = 1 brat_rows = [] for sentence in client_json['sentences']: for con in sentence['concepts']: row = f"T{t} {con["prediction"]} {con["beginDocumentCharIndex"]} {con["endDocumentCharIndex"]} {con["sourcePhrase"]}" brat_rows.append(row) t += 1 return brat_rows semantic_types = [ 'aapp', 'acab', 'acty', 'aggp', 'amas', 'amph', 'anab', 'anim', 'anst', 'antb', 'arch', 'bacs', 'bact', 'bdsu', 'bdsy', 'bhvr', 'biof', 'bird', 'blor', 'bmod', 'bodm', 'bpoc', 'bsoj', 'celc', 'celf', 'cell', 'cgab', 'chem', 'chvf', 'chvs', 'clas', 'clna', 'clnd', 'cnce', 'comd', 'crbs', 'diap', 'dora', 'drdd', 'dsyn', 'edac', 'eehu', 'elii', 'emod', 'emst', 'enty', 'enzy', 'euka', 'evnt', 'famg', 'ffas', 'fish', 'fndg', 'fngs', 'food', 'ftcn', 'genf', 'geoa', 'gngm', 'gora', 'grpa', 'grup', 'hcpp', 'hcro', 'hlca', 'hops', 'horm', 'humn', 'idcn', 'imft', 'inbe', 'inch', 'inpo', 'inpr', 'irda', 'lang', 'lbpr', 'lbtr', 'mamm', 'mbrt', 'mcha', 'medd', 'menp', 'mnob', 'mobd', 'moft', 'mosq', 'neop', 'nnon', 'npop', 'nusq', 'ocac', 'ocdi', 'orch', 'orga', 'orgf', 'orgm', 'orgt', 'ortf', 'patf', 'phob', 'phpr', 'phsf', 'phsu', 'plnt', 'podg', 'popg', 'prog', 'pros', 'qlco', 'qnco', 'rcpt', 'rept', 'resa', 'resd', 'rnlw', 'sbst', 'shro', 'socb', 'sosy', 'spco', 'tisu', 'tmco', 'topp', 'virs', 'vita', 'vtbt' ]
import grpc from cli.constants import METAMAP from proto.python.uwbionlp_pb2 import MetaMapInput from proto.python.uwbionlp_pb2_grpc import MetaMapStub class MetaMapChannelManager(): def __init__(self, container): self.name = METAMAP self.host = container.host self.port = container.port self.wait_secs = 10 def open(self): self.channel = grpc.insecure_channel(f'{self.host}:{self.port}') def close(self): self.channel.close() def generate_client(self, args): return MetaMapClient(self.channel, args) class MetaMapClient(): def __init__(self, channel, args): self.name = METAMAP self.stub = MetaMapStub(channel) self.channel = channel self.args = args def process(self, doc): response = self.stub.ExtractNamedEntities(MetaMapInput(id=doc.id, sentences=doc.sentences, semantic_types=self.args.metamap_semantic_types)) return response def to_dict(self, response): output = { 'sentences': [], 'errors': [ err for err in response.errors] } for sent in response.sentences: sentence = { 'id': sent.id, 'text': sent.text, 'concepts': [], 'beginCharIndex': sent.begin_char_index, 'endCharIndex': sent.end_char_index, } for con in sent.concepts: concept = { 'beginSentenceCharIndex': con.begin_sent_char_index, 'endSentenceCharIndex': con.end_sent_char_index, 'beginDocumentCharIndex': con.begin_doc_char_index, 'endDocumentCharIndex': con.end_doc_char_index, 'cui': con.cui, 'semanticTypes': [ st for st in con.semantic_types ], 'sourcePhrase': con.source_phrase, 'conceptName': con.concept_name, 'prediction': con.prediction } sentence['concepts'].append(concept) output['sentences'].append(sentence) return output def merge(self, base_json, client_json): base_json[self.name] = { 'concepts': [], 'errors': client_json['errors'] } for sentence in client_json['sentences']: for con in sentence['concepts']: base_json[self.name]['concepts'].append(con) return base_json def to_brat(self, client_json): t = 1 brat_rows = [] for sentence in client_json['sentences']: for con in sentence['concepts']: row = f"T{t} {con['prediction']} {con['beginDocumentCharIndex']} {con['endDocumentCharIndex']} {con['sourcePhrase']}" brat_rows.append(row) t += 1 return brat_rows semantic_types = [ 'aapp', 'acab', 'acty', 'aggp', 'amas', 'amph', 'anab', 'anim', 'anst', 'antb', 'arch', 'bacs', 'bact', 'bdsu', 'bdsy', 'bhvr', 'biof', 'bird', 'blor', 'bmod', 'bodm', 'bpoc', 'bsoj', 'celc', 'celf', 'cell', 'cgab', 'chem', 'chvf', 'chvs', 'clas', 'clna', 'clnd', 'cnce', 'comd', 'crbs', 'diap', 'dora', 'drdd', 'dsyn', 'edac', 'eehu', 'elii', 'emod', 'emst', 'enty', 'enzy', 'euka', 'evnt', 'famg', 'ffas', 'fish', 'fndg', 'fngs', 'food', 'ftcn', 'genf', 'geoa', 'gngm', 'gora', 'grpa', 'grup', 'hcpp', 'hcro', 'hlca', 'hops', 'horm', 'humn', 'idcn', 'imft', 'inbe', 'inch', 'inpo', 'inpr', 'irda', 'lang', 'lbpr', 'lbtr', 'mamm', 'mbrt', 'mcha', 'medd', 'menp', 'mnob', 'mobd', 'moft', 'mosq', 'neop', 'nnon', 'npop', 'nusq', 'ocac', 'ocdi', 'orch', 'orga', 'orgf', 'orgm', 'orgt', 'ortf', 'patf', 'phob', 'phpr', 'phsf', 'phsu', 'plnt', 'podg', 'popg', 'prog', 'pros', 'qlco', 'qnco', 'rcpt', 'rept', 'resa', 'resd', 'rnlw', 'sbst', 'shro', 'socb', 'sosy', 'spco', 'tisu', 'tmco', 'topp', 'virs', 'vita', 'vtbt' ]
"""Super class(es) that is inherited by all API objects.""" from .helper_functions import syntax_correcter import logging import json logging.debug(f"In the {__name__} module.") class APIClassTemplate(object): """The base framework for all/(most of) the objects in the FMC.""" REQUIRED_FOR_POST = ["name"] REQUIRED_FOR_PUT = ["id"] REQUIRED_FOR_DELETE = ["id"] REQUIRED_FOR_GET = [""] FILTER_BY_NAME = False URL = "" URL_SUFFIX = "" VALID_CHARACTERS_FOR_NAME = """[.\w\d_\-]""" FIRST_SUPPORTED_FMC_VERSION = "6.1" VALID_JSON_DATA = [] GLOBAL_VALID_FOR_KWARGS = ["dry_run"] VALID_FOR_KWARGS = VALID_JSON_DATA + [] @property def show_json(self): """ json.dumps of format_data() info. :return (str) """ return json.dumps(self.format_data()) def __init__(self, fmc, **kwargs): """ Initialize an instances of object being created. :param fmc: (object) FMC object :param **kwargs: Passed variables that will be added to object being instantiated. :return: None """ logging.debug("In __init__() for APIClassTemplate class.") self.VALID_FOR_KWARGS = self.VALID_FOR_KWARGS + self.GLOBAL_VALID_FOR_KWARGS self.fmc = fmc self.limit = self.fmc.limit self.description = "Created by fmcapi." self.overridable = False self.dry_run = False self.URL = f"{self.fmc.configuration_url}{self.URL_SUFFIX}" if self.fmc.serverVersion < self.FIRST_SUPPORTED_FMC_VERSION: logging.warning( f"This API feature was released in version {self.FIRST_SUPPORTED_FMC_VERSION}. " f"Your FMC version is {self.fmc.serverVersion}. Upgrade to use this feature." ) def format_data(self, filter_query=""): """ Gather all the data in preparation for sending to API in JSON format. :param filter_query: (str) 'all' or 'kwargs' :return: (dict) json_data """ logging.debug("In format_data() for APIClassTemplate class.") json_data = {} filter_list = self.VALID_JSON_DATA if filter_query == "all": filter_list = self.__dict__ elif filter_query == "kwargs": filter_list = self.VALID_FOR_KWARGS for key_value in filter_list: if key_value in self.__dict__: json_data[key_value] = self.__dict__[key_value] return json_data def parse_kwargs(self, **kwargs): """ Parse the kwargs and set self variables to match. :return: None """ logging.debug("In parse_kwargs() for APIClassTemplate class.") for key_value in self.VALID_FOR_KWARGS: if key_value in kwargs: self.__dict__[key_value] = kwargs[key_value] if "name" in kwargs: self.name = syntax_correcter( kwargs["name"], permitted_syntax=self.VALID_CHARACTERS_FOR_NAME ) if self.name != kwargs["name"]: logging.info( f"Adjusting name '{kwargs["name"]}' to '{self.name}' due to invalid characters." ) def valid_for_get(self): """ Use REQUIRED_FOR_GET to ensure all necessary variables exist prior to submitting to API. :return: (boolean) """ logging.debug("In valid_for_get() for APIClassTemplate class.") if self.REQUIRED_FOR_GET == [""]: return True for item in self.REQUIRED_FOR_GET: if item not in self.__dict__: logging.error(f'Missing value "{item}" for GET request.') return False return True def get(self, **kwargs): """ Prepare to send GET call to FMC API. If no self.name or self.id exists then return a full listing of all objects of this type otherwise return requested name/id values. Set "expanded=true" results for specific object to gather additional detail. :return: requests response """ logging.debug("In get() for APIClassTemplate class.") self.parse_kwargs(**kwargs) if self.fmc.serverVersion < self.FIRST_SUPPORTED_FMC_VERSION: logging.error( f"Your FMC version, {self.fmc.serverVersion} does not support GET of this feature." ) return {"items": []} if self.valid_for_get(): if "id" in self.__dict__: url = f"{self.URL}/{self.id}" if self.dry_run: logging.info( "Dry Run enabled. Not actually sending to FMC. Here is what would have been sent:" ) logging.info("\tMethod = GET") logging.info(f"\tURL = {self.URL}") return False response = self.fmc.send_to_api(method="get", url=url) try: self.parse_kwargs(**response) except TypeError as e: logging.error( f"Response from FMC GET with 'id', {self.id}, returned none." f"That 'id' probably was deleted. Error: {e}." ) if "name" in self.__dict__: logging.info( f'GET success. Object with name: "{self.name}" and id: "{self.id}" fetched from FMC.' ) else: logging.info( f'GET success. Object with id: "{self.id}" fetched from FMC.' ) elif "name" in self.__dict__: if self.FILTER_BY_NAME: url = f"{self.URL}?name={self.name}&expanded=true" else: url = f"{self.URL}?expanded=true" if "limit" in self.__dict__: url = f"{url}&limit={self.limit}" if "offset" in self.__dict__: url = f"{url}&offset={self.offset}" response = self.fmc.send_to_api(method="get", url=url) if "items" not in response: response["items"] = [] for item in response["items"]: if "name" in item: if item["name"] == self.name: self.id = item["id"] self.parse_kwargs(**item) logging.info( f'GET success. Object with name: "{self.name}" and id: "{self.id}" ' f"fetched from FMC." ) return item else: logging.warning( f'No "name" attribute associated with this item to check against {self.name}.' ) if "id" not in self.__dict__: logging.warning( f"\tGET query for {self.name} is not found.\n\t\tResponse: {json.dumps(response)}" ) else: logging.debug( "GET query for object with no name or id set. " "Returning full list of these object types instead." ) url = f"{self.URL}?expanded=true&limit={self.limit}" if self.dry_run: logging.info( "Dry Run enabled. Not actually sending to FMC. Here is what would have been sent:" ) logging.info("\tMethod = GET") logging.info(f"\tURL = {self.URL}") return False response = self.fmc.send_to_api(method="get", url=url) if "items" not in response: response["items"] = [] return response else: logging.warning( "get() method failed due to failure to pass valid_for_get() test." ) return False def valid_for_post(self): """ Use REQUIRED_FOR_POST to ensure all necessary variables exist prior to submitting to API. :return: (boolean) """ logging.debug("In valid_for_post() for APIClassTemplate class.") for item in self.REQUIRED_FOR_POST: if item not in self.__dict__: logging.error(f'Missing value "{item}" for POST request.') return False return True def post(self, **kwargs): """ Prepare to send POST call to FMC API. :return: requests response """ logging.debug("In post() for APIClassTemplate class.") if self.fmc.serverVersion < self.FIRST_SUPPORTED_FMC_VERSION: logging.error( f"Your FMC version, {self.fmc.serverVersion} does not support POST of this feature." ) return False if "id" in self.__dict__: logging.info( "ID value exists for this object. Redirecting to put() method." ) self.put() else: if self.valid_for_post(): if self.dry_run: logging.info( "Dry Run enabled. Not actually sending to FMC. Here is what would have been sent:" ) logging.info("\tMethod = POST") logging.info(f"\tURL = {self.URL}") logging.info(f"\tJSON = {self.show_json()}") return False response = self.fmc.send_to_api( method="post", url=self.URL, json_data=self.format_data() ) if response: self.parse_kwargs(**response) if "name" in self.__dict__ and "id" in self.__dict__: logging.info( f'POST success. Object with name: "{self.name}" and id: "{id}" created in FMC.' ) else: logging.debug( 'POST success but no "id" or "name" values in API response.' ) else: logging.warning("POST failure. No data in API response.") return response else: logging.warning( "post() method failed due to failure to pass valid_for_post() test." ) return False def valid_for_put(self): """ Use REQUIRED_FOR_PUT to ensure all necessary variables exist prior to submitting to API. :return: (boolean) """ logging.debug("In valid_for_put() for APIClassTemplate class.") for item in self.REQUIRED_FOR_PUT: if item not in self.__dict__: logging.error(f'Missing value "{item}" for PUT request.') return False return True def put(self, **kwargs): """ Prepare to send PUT call to FMC API. :return: requests response """ logging.debug("In put() for APIClassTemplate class.") self.parse_kwargs(**kwargs) if self.fmc.serverVersion < self.FIRST_SUPPORTED_FMC_VERSION: logging.error( f"Your FMC version, {self.fmc.serverVersion} does not support PUT of this feature." ) return False if self.valid_for_put(): url = f"{self.URL}/{self.id}" if self.dry_run: logging.info( "Dry Run enabled. Not actually sending to FMC. Here is what would have been sent:" ) logging.info("\tMethod = PUT") logging.info(f"\tURL = {self.URL}") logging.info(f"\tJSON = {self.show_json()}") return False response = self.fmc.send_to_api( method="put", url=url, json_data=self.format_data() ) self.parse_kwargs(**response) if "name" in self.__dict__: logging.info( f'PUT success. Object with name: "{self.name}" and id: "{self.id}" updated in FMC.' ) else: logging.info( f'PUT success. Object with id: "{self.id}" updated in FMC.' ) return response else: logging.warning( "put() method failed due to failure to pass valid_for_put() test." ) return False def valid_for_delete(self): """ Use REQUIRED_FOR_DELETE to ensure all necessary variables exist prior to submitting to API. :return: (boolean) """ logging.debug("In valid_for_delete() for APIClassTemplate class.") for item in self.REQUIRED_FOR_DELETE: if item not in self.__dict__: logging.error(f'Missing value "{item}" for DELETE request.') return False return True def delete(self, **kwargs): """ Prepare to send DELETE call to FMC API. :return: requests response """ logging.debug("In delete() for APIClassTemplate class.") self.parse_kwargs(**kwargs) if self.fmc.serverVersion < self.FIRST_SUPPORTED_FMC_VERSION: logging.error( f"Your FMC version, {self.fmc.serverVersion} does not support DELETE of this feature." ) return False if self.valid_for_delete(): url = f"{self.URL}/{self.id}" if self.dry_run: logging.info( "Dry Run enabled. Not actually sending to FMC. Here is what would have been sent:" ) logging.info("\tMethod = DELETE") logging.info(f"\tURL = {self.URL}") logging.info(f"\tJSON = {self.show_json()}") return False response = self.fmc.send_to_api( method="delete", url=url, json_data=self.format_data() ) if not response: return None self.parse_kwargs(**response) if "name" in self.name: logging.info( f'DELETE success. Object with name: "{self.name}" and id: "{self.id}" deleted in FMC.' ) else: logging.info(f'DELETE success. Object id: "{self.id}" deleted in FMC.') return response else: logging.warning( "delete() method failed due to failure to pass valid_for_delete() test." ) return False
"""Super class(es) that is inherited by all API objects.""" from .helper_functions import syntax_correcter import logging import json logging.debug(f"In the {__name__} module.") class APIClassTemplate(object): """The base framework for all/(most of) the objects in the FMC.""" REQUIRED_FOR_POST = ["name"] REQUIRED_FOR_PUT = ["id"] REQUIRED_FOR_DELETE = ["id"] REQUIRED_FOR_GET = [""] FILTER_BY_NAME = False URL = "" URL_SUFFIX = "" VALID_CHARACTERS_FOR_NAME = """[.\w\d_\-]""" FIRST_SUPPORTED_FMC_VERSION = "6.1" VALID_JSON_DATA = [] GLOBAL_VALID_FOR_KWARGS = ["dry_run"] VALID_FOR_KWARGS = VALID_JSON_DATA + [] @property def show_json(self): """ json.dumps of format_data() info. :return (str) """ return json.dumps(self.format_data()) def __init__(self, fmc, **kwargs): """ Initialize an instances of object being created. :param fmc: (object) FMC object :param **kwargs: Passed variables that will be added to object being instantiated. :return: None """ logging.debug("In __init__() for APIClassTemplate class.") self.VALID_FOR_KWARGS = self.VALID_FOR_KWARGS + self.GLOBAL_VALID_FOR_KWARGS self.fmc = fmc self.limit = self.fmc.limit self.description = "Created by fmcapi." self.overridable = False self.dry_run = False self.URL = f"{self.fmc.configuration_url}{self.URL_SUFFIX}" if self.fmc.serverVersion < self.FIRST_SUPPORTED_FMC_VERSION: logging.warning( f"This API feature was released in version {self.FIRST_SUPPORTED_FMC_VERSION}. " f"Your FMC version is {self.fmc.serverVersion}. Upgrade to use this feature." ) def format_data(self, filter_query=""): """ Gather all the data in preparation for sending to API in JSON format. :param filter_query: (str) 'all' or 'kwargs' :return: (dict) json_data """ logging.debug("In format_data() for APIClassTemplate class.") json_data = {} filter_list = self.VALID_JSON_DATA if filter_query == "all": filter_list = self.__dict__ elif filter_query == "kwargs": filter_list = self.VALID_FOR_KWARGS for key_value in filter_list: if key_value in self.__dict__: json_data[key_value] = self.__dict__[key_value] return json_data def parse_kwargs(self, **kwargs): """ Parse the kwargs and set self variables to match. :return: None """ logging.debug("In parse_kwargs() for APIClassTemplate class.") for key_value in self.VALID_FOR_KWARGS: if key_value in kwargs: self.__dict__[key_value] = kwargs[key_value] if "name" in kwargs: self.name = syntax_correcter( kwargs["name"], permitted_syntax=self.VALID_CHARACTERS_FOR_NAME ) if self.name != kwargs["name"]: logging.info( f"Adjusting name '{kwargs['name']}' to '{self.name}' due to invalid characters." ) def valid_for_get(self): """ Use REQUIRED_FOR_GET to ensure all necessary variables exist prior to submitting to API. :return: (boolean) """ logging.debug("In valid_for_get() for APIClassTemplate class.") if self.REQUIRED_FOR_GET == [""]: return True for item in self.REQUIRED_FOR_GET: if item not in self.__dict__: logging.error(f'Missing value "{item}" for GET request.') return False return True def get(self, **kwargs): """ Prepare to send GET call to FMC API. If no self.name or self.id exists then return a full listing of all objects of this type otherwise return requested name/id values. Set "expanded=true" results for specific object to gather additional detail. :return: requests response """ logging.debug("In get() for APIClassTemplate class.") self.parse_kwargs(**kwargs) if self.fmc.serverVersion < self.FIRST_SUPPORTED_FMC_VERSION: logging.error( f"Your FMC version, {self.fmc.serverVersion} does not support GET of this feature." ) return {"items": []} if self.valid_for_get(): if "id" in self.__dict__: url = f"{self.URL}/{self.id}" if self.dry_run: logging.info( "Dry Run enabled. Not actually sending to FMC. Here is what would have been sent:" ) logging.info("\tMethod = GET") logging.info(f"\tURL = {self.URL}") return False response = self.fmc.send_to_api(method="get", url=url) try: self.parse_kwargs(**response) except TypeError as e: logging.error( f"Response from FMC GET with 'id', {self.id}, returned none." f"That 'id' probably was deleted. Error: {e}." ) if "name" in self.__dict__: logging.info( f'GET success. Object with name: "{self.name}" and id: "{self.id}" fetched from FMC.' ) else: logging.info( f'GET success. Object with id: "{self.id}" fetched from FMC.' ) elif "name" in self.__dict__: if self.FILTER_BY_NAME: url = f"{self.URL}?name={self.name}&expanded=true" else: url = f"{self.URL}?expanded=true" if "limit" in self.__dict__: url = f"{url}&limit={self.limit}" if "offset" in self.__dict__: url = f"{url}&offset={self.offset}" response = self.fmc.send_to_api(method="get", url=url) if "items" not in response: response["items"] = [] for item in response["items"]: if "name" in item: if item["name"] == self.name: self.id = item["id"] self.parse_kwargs(**item) logging.info( f'GET success. Object with name: "{self.name}" and id: "{self.id}" ' f"fetched from FMC." ) return item else: logging.warning( f'No "name" attribute associated with this item to check against {self.name}.' ) if "id" not in self.__dict__: logging.warning( f"\tGET query for {self.name} is not found.\n\t\tResponse: {json.dumps(response)}" ) else: logging.debug( "GET query for object with no name or id set. " "Returning full list of these object types instead." ) url = f"{self.URL}?expanded=true&limit={self.limit}" if self.dry_run: logging.info( "Dry Run enabled. Not actually sending to FMC. Here is what would have been sent:" ) logging.info("\tMethod = GET") logging.info(f"\tURL = {self.URL}") return False response = self.fmc.send_to_api(method="get", url=url) if "items" not in response: response["items"] = [] return response else: logging.warning( "get() method failed due to failure to pass valid_for_get() test." ) return False def valid_for_post(self): """ Use REQUIRED_FOR_POST to ensure all necessary variables exist prior to submitting to API. :return: (boolean) """ logging.debug("In valid_for_post() for APIClassTemplate class.") for item in self.REQUIRED_FOR_POST: if item not in self.__dict__: logging.error(f'Missing value "{item}" for POST request.') return False return True def post(self, **kwargs): """ Prepare to send POST call to FMC API. :return: requests response """ logging.debug("In post() for APIClassTemplate class.") if self.fmc.serverVersion < self.FIRST_SUPPORTED_FMC_VERSION: logging.error( f"Your FMC version, {self.fmc.serverVersion} does not support POST of this feature." ) return False if "id" in self.__dict__: logging.info( "ID value exists for this object. Redirecting to put() method." ) self.put() else: if self.valid_for_post(): if self.dry_run: logging.info( "Dry Run enabled. Not actually sending to FMC. Here is what would have been sent:" ) logging.info("\tMethod = POST") logging.info(f"\tURL = {self.URL}") logging.info(f"\tJSON = {self.show_json()}") return False response = self.fmc.send_to_api( method="post", url=self.URL, json_data=self.format_data() ) if response: self.parse_kwargs(**response) if "name" in self.__dict__ and "id" in self.__dict__: logging.info( f'POST success. Object with name: "{self.name}" and id: "{id}" created in FMC.' ) else: logging.debug( 'POST success but no "id" or "name" values in API response.' ) else: logging.warning("POST failure. No data in API response.") return response else: logging.warning( "post() method failed due to failure to pass valid_for_post() test." ) return False def valid_for_put(self): """ Use REQUIRED_FOR_PUT to ensure all necessary variables exist prior to submitting to API. :return: (boolean) """ logging.debug("In valid_for_put() for APIClassTemplate class.") for item in self.REQUIRED_FOR_PUT: if item not in self.__dict__: logging.error(f'Missing value "{item}" for PUT request.') return False return True def put(self, **kwargs): """ Prepare to send PUT call to FMC API. :return: requests response """ logging.debug("In put() for APIClassTemplate class.") self.parse_kwargs(**kwargs) if self.fmc.serverVersion < self.FIRST_SUPPORTED_FMC_VERSION: logging.error( f"Your FMC version, {self.fmc.serverVersion} does not support PUT of this feature." ) return False if self.valid_for_put(): url = f"{self.URL}/{self.id}" if self.dry_run: logging.info( "Dry Run enabled. Not actually sending to FMC. Here is what would have been sent:" ) logging.info("\tMethod = PUT") logging.info(f"\tURL = {self.URL}") logging.info(f"\tJSON = {self.show_json()}") return False response = self.fmc.send_to_api( method="put", url=url, json_data=self.format_data() ) self.parse_kwargs(**response) if "name" in self.__dict__: logging.info( f'PUT success. Object with name: "{self.name}" and id: "{self.id}" updated in FMC.' ) else: logging.info( f'PUT success. Object with id: "{self.id}" updated in FMC.' ) return response else: logging.warning( "put() method failed due to failure to pass valid_for_put() test." ) return False def valid_for_delete(self): """ Use REQUIRED_FOR_DELETE to ensure all necessary variables exist prior to submitting to API. :return: (boolean) """ logging.debug("In valid_for_delete() for APIClassTemplate class.") for item in self.REQUIRED_FOR_DELETE: if item not in self.__dict__: logging.error(f'Missing value "{item}" for DELETE request.') return False return True def delete(self, **kwargs): """ Prepare to send DELETE call to FMC API. :return: requests response """ logging.debug("In delete() for APIClassTemplate class.") self.parse_kwargs(**kwargs) if self.fmc.serverVersion < self.FIRST_SUPPORTED_FMC_VERSION: logging.error( f"Your FMC version, {self.fmc.serverVersion} does not support DELETE of this feature." ) return False if self.valid_for_delete(): url = f"{self.URL}/{self.id}" if self.dry_run: logging.info( "Dry Run enabled. Not actually sending to FMC. Here is what would have been sent:" ) logging.info("\tMethod = DELETE") logging.info(f"\tURL = {self.URL}") logging.info(f"\tJSON = {self.show_json()}") return False response = self.fmc.send_to_api( method="delete", url=url, json_data=self.format_data() ) if not response: return None self.parse_kwargs(**response) if "name" in self.name: logging.info( f'DELETE success. Object with name: "{self.name}" and id: "{self.id}" deleted in FMC.' ) else: logging.info(f'DELETE success. Object id: "{self.id}" deleted in FMC.') return response else: logging.warning( "delete() method failed due to failure to pass valid_for_delete() test." ) return False
""" Prometheus querying and result transformation The module provides functionality to query a Prometheus server and helpers to create correct query parameters. """ from datetime import datetime, timedelta import time from typing import Union import aiohttp from thumbling.luis import group_datetimeV2_entities from thumbling.utils import str2timestamp Num = Union[int, float] class PrometheusAPI: """ Query a Prometheus server API see https://prometheus.io/docs/prometheus/latest/querying/api/ """ def __init__(self, service_config: dict): if service_config["endpoint"].endswith("/"): self.base_url = service_config["endpoint"][:-1] else: self.base_url = service_config["endpoint"] self.query_url = self.base_url + "/api/v1/query" self.query_range_url = self.base_url + "/api/v1/query_range" async def query( self, query_string: str, time: str = None, timeout: int = None ) -> dict: params = {"query": query_string} if time is not None: params["time"] = str2timestamp(time) if timeout is not None: params["timeout"] = timeout async with aiohttp.ClientSession() as session: async with session.get(self.query_url, params=params) as resp: return await resp.json() async def query_range( self, query_string: str, start: str, end: str, step: str = "1m", timeout: int = None, ) -> dict: params = {"query": query_string, "step": step} if timeout is not None: params["timeout"] = timeout params["start"] = start params["end"] = end async with aiohttp.ClientSession() as session: async with session.get(self.query_range_url, params=params) as resp: return await resp.json() def get_limited_time_range(start: Num, end: Num, safety: int = 30) -> (int, int): """ limited a time range to values in the past Prometheus does not allow timestamps in its future so cut off the end or return None if the start is before the end or in the future. """ now = time.time() start = min(start, now - safety) end = min(end, now - safety) if start >= now or start >= end: return None return int(start), int(end) def get_query_time_ranges(entities: list) -> list: """ transform intent entities datetimeV2 to timestap tuples A very incomplete and faulty implementation of datetimeV2 entities to Prometheus valid timestamp tuples for the start/end query parameters. There must be better solutions. """ time_entities = group_datetimeV2_entities(entities) time_ranges = [] for subtype in time_entities: if subtype == "time": for entity in time_entities[subtype]: for value in entity: # use a 10 minutes time window time_value = datetime.combine( datetime.today(), datetime.strptime(value["value"], "%H:%M:%S").time(), ).timestamp() time_range = get_limited_time_range( time_value - 300, time_value + 300 ) if time_range is not None: time_ranges.append(time_range) elif subtype == "date": for entity in time_entities[subtype]: for value in entity: start_time = datetime.strptime(value["value"], "%Y-%m-%d") end_time = start_time + timedelta(days=1) time_range = get_limited_time_range( start_time.timestamp(), end_time.timestamp() ) if time_range is not None: time_ranges.append(time_range) elif subtype in ["daterange", "datetimerange"]: for entity in time_entities[subtype]: for value in entity: if "end" not in value: value["end"] = int(time.time()) start_time = str2timestamp(value["start"]) end_time = str2timestamp(value["end"]) time_range = get_limited_time_range(start_time, end_time) if time_range is not None: time_ranges.append(time_range) elif subtype in "timerange": for entity in time_entities[subtype]: for value in entity: if "end" not in value: end_time = int(time.time()) else: end_time = datetime.combine( datetime.today(), datetime.strptime(value["end"], "%H:%M:%S").time(), ).timestamp() start_time = datetime.combine( datetime.today(), datetime.strptime(value["start"], "%H:%M:%S").time(), ).timestamp() time_range = get_limited_time_range(start_time, end_time) if time_range is not None: time_ranges.append(time_range) return time_ranges def get_alert_queries(entities: list) -> list: """ create the value for the Prometheus query parameter based on the entities This is also very rudimentary and must probably adapted to each ones use case. """ instance_entities = [e for e in entities if e["type"] == "instance"] if instance_entities: queries = [] for entity in instance_entities: instance = entity["entity"].replace(" ", "") queries.append(f'ALERTS{{instance='{instance}'}}') return queries # if we do not have specific search targets we use the less specific ones service_name_entities = [e for e in entities if e["type"] == "service-name"] if service_name_entities: queries = [] for entity in service_name_entities: queries.append(f'ALERTS{{service='{entity['entity']}"}}') return queries return []
""" Prometheus querying and result transformation The module provides functionality to query a Prometheus server and helpers to create correct query parameters. """ from datetime import datetime, timedelta import time from typing import Union import aiohttp from thumbling.luis import group_datetimeV2_entities from thumbling.utils import str2timestamp Num = Union[int, float] class PrometheusAPI: """ Query a Prometheus server API see https://prometheus.io/docs/prometheus/latest/querying/api/ """ def __init__(self, service_config: dict): if service_config["endpoint"].endswith("/"): self.base_url = service_config["endpoint"][:-1] else: self.base_url = service_config["endpoint"] self.query_url = self.base_url + "/api/v1/query" self.query_range_url = self.base_url + "/api/v1/query_range" async def query( self, query_string: str, time: str = None, timeout: int = None ) -> dict: params = {"query": query_string} if time is not None: params["time"] = str2timestamp(time) if timeout is not None: params["timeout"] = timeout async with aiohttp.ClientSession() as session: async with session.get(self.query_url, params=params) as resp: return await resp.json() async def query_range( self, query_string: str, start: str, end: str, step: str = "1m", timeout: int = None, ) -> dict: params = {"query": query_string, "step": step} if timeout is not None: params["timeout"] = timeout params["start"] = start params["end"] = end async with aiohttp.ClientSession() as session: async with session.get(self.query_range_url, params=params) as resp: return await resp.json() def get_limited_time_range(start: Num, end: Num, safety: int = 30) -> (int, int): """ limited a time range to values in the past Prometheus does not allow timestamps in its future so cut off the end or return None if the start is before the end or in the future. """ now = time.time() start = min(start, now - safety) end = min(end, now - safety) if start >= now or start >= end: return None return int(start), int(end) def get_query_time_ranges(entities: list) -> list: """ transform intent entities datetimeV2 to timestap tuples A very incomplete and faulty implementation of datetimeV2 entities to Prometheus valid timestamp tuples for the start/end query parameters. There must be better solutions. """ time_entities = group_datetimeV2_entities(entities) time_ranges = [] for subtype in time_entities: if subtype == "time": for entity in time_entities[subtype]: for value in entity: # use a 10 minutes time window time_value = datetime.combine( datetime.today(), datetime.strptime(value["value"], "%H:%M:%S").time(), ).timestamp() time_range = get_limited_time_range( time_value - 300, time_value + 300 ) if time_range is not None: time_ranges.append(time_range) elif subtype == "date": for entity in time_entities[subtype]: for value in entity: start_time = datetime.strptime(value["value"], "%Y-%m-%d") end_time = start_time + timedelta(days=1) time_range = get_limited_time_range( start_time.timestamp(), end_time.timestamp() ) if time_range is not None: time_ranges.append(time_range) elif subtype in ["daterange", "datetimerange"]: for entity in time_entities[subtype]: for value in entity: if "end" not in value: value["end"] = int(time.time()) start_time = str2timestamp(value["start"]) end_time = str2timestamp(value["end"]) time_range = get_limited_time_range(start_time, end_time) if time_range is not None: time_ranges.append(time_range) elif subtype in "timerange": for entity in time_entities[subtype]: for value in entity: if "end" not in value: end_time = int(time.time()) else: end_time = datetime.combine( datetime.today(), datetime.strptime(value["end"], "%H:%M:%S").time(), ).timestamp() start_time = datetime.combine( datetime.today(), datetime.strptime(value["start"], "%H:%M:%S").time(), ).timestamp() time_range = get_limited_time_range(start_time, end_time) if time_range is not None: time_ranges.append(time_range) return time_ranges def get_alert_queries(entities: list) -> list: """ create the value for the Prometheus query parameter based on the entities This is also very rudimentary and must probably adapted to each ones use case. """ instance_entities = [e for e in entities if e["type"] == "instance"] if instance_entities: queries = [] for entity in instance_entities: instance = entity["entity"].replace(" ", "") queries.append(f'ALERTS{{instance="{instance}"}}') return queries # if we do not have specific search targets we use the less specific ones service_name_entities = [e for e in entities if e["type"] == "service-name"] if service_name_entities: queries = [] for entity in service_name_entities: queries.append(f'ALERTS{{service="{entity["entity"]}"}}') return queries return []
"""HVCS """ import logging import mimetypes import os from typing import Any, Optional, Union, cast from urllib.parse import urlsplit from gitlab import exceptions, gitlab from requests import HTTPError, Session from requests.auth import AuthBase from urllib3 import Retry from .errors import ImproperConfigurationError from .helpers import LoggedFunction, build_requests_session from .settings import config from .vcs_helpers import get_formatted_tag logger = logging.getLogger(__name__) # Add a mime type for wheels mimetypes.add_type("application/octet-stream", ".whl") class Base(object): @staticmethod def domain() -> str: raise NotImplementedError @staticmethod def api_url() -> str: raise NotImplementedError @staticmethod def token() -> Optional[str]: raise NotImplementedError @staticmethod def check_build_status(owner: str, repo: str, ref: str) -> bool: raise NotImplementedError @classmethod def post_release_changelog( cls, owner: str, repo: str, version: str, changelog: str ) -> bool: raise NotImplementedError @classmethod def upload_dists(cls, owner: str, repo: str, version: str, path: str) -> bool: # Skip on unsupported HVCS instead of raising error return True def _fix_mime_types(): """Fix incorrect entries in the `mimetypes` registry. On Windows, the Python standard library's `mimetypes` reads in mappings from file extension to MIME type from the Windows registry. Other applications can and do write incorrect values to this registry, which causes `mimetypes.guess_type` to return incorrect values, which causes TensorBoard to fail to render on the frontend. This method hard-codes the correct mappings for certain MIME types that are known to be either used by python-semantic-release or problematic in general. """ mimetypes.add_type("text/markdown", ".md") class TokenAuth(AuthBase): """ requests Authentication for token based authorization """ def __init__(self, token): self.token = token def __eq__(self, other): return all( [ self.token == getattr(other, "token", None), ] ) def __ne__(self, other): return not self == other def __call__(self, r): r.headers["Authorization"] = f"token {self.token}" return r class Github(Base): """Github helper class""" DEFAULT_DOMAIN = "github.com" _fix_mime_types() @staticmethod def domain() -> str: """Github domain property :return: The Github domain """ # ref: https://docs.github.com/en/actions/reference/environment-variables#default-environment-variables hvcs_domain = config.get( "hvcs_domain", os.getenv("GITHUB_SERVER_URL", "").replace("https://", "") ) domain = hvcs_domain if hvcs_domain else Github.DEFAULT_DOMAIN return domain @staticmethod def api_url() -> str: """Github api_url property :return: The Github API URL """ # not necessarily prefixed with api in the case of a custom domain, so # can't just default DEFAULT_DOMAIN to github.com # ref: https://docs.github.com/en/actions/reference/environment-variables#default-environment-variables hvcs_api_domain = config.get( "hvcs_api_domain", os.getenv("GITHUB_API_URL", "").replace("https://", "") ) hostname = ( hvcs_api_domain if hvcs_api_domain else "api." + Github.DEFAULT_DOMAIN ) return f"https://{hostname}" @staticmethod def token() -> Optional[str]: """Github token property :return: The Github token environment variable (GH_TOKEN) value """ return os.environ.get(config.get("github_token_var")) @staticmethod def auth() -> Optional[TokenAuth]: """Github token property :return: The Github token environment variable (GH_TOKEN) value """ token = Github.token() if not token: return None return TokenAuth(token) @staticmethod def session( raise_for_status=True, retry: Union[Retry, bool, int] = True ) -> Session: session = build_requests_session(raise_for_status=raise_for_status, retry=retry) session.auth = Github.auth() return session @staticmethod @LoggedFunction(logger) def check_build_status(owner: str, repo: str, ref: str) -> bool: """Check build status https://docs.github.com/rest/reference/repos#get-the-combined-status-for-a-specific-reference :param owner: The owner namespace of the repository :param repo: The repository name :param ref: The sha1 hash of the commit ref :return: Was the build status success? """ url = "{domain}/repos/{owner}/{repo}/commits/{ref}/status" try: response = Github.session().get( url.format(domain=Github.api_url(), owner=owner, repo=repo, ref=ref) ) return response.json().get("state") == "success" except HTTPError as e: logger.warning(f"Build status check on Github has failed: {e}") return False @classmethod @LoggedFunction(logger) def create_release(cls, owner: str, repo: str, tag: str, changelog: str) -> bool: """Create a new release https://docs.github.com/rest/reference/repos#create-a-release :param owner: The owner namespace of the repository :param repo: The repository name :param tag: Tag to create release for :param changelog: The release notes for this version :return: Whether the request succeeded """ try: Github.session().post( f"{Github.api_url()}/repos/{owner}/{repo}/releases", json={ "tag_name": tag, "name": tag, "body": changelog, "draft": False, "prerelease": False, }, ) return True except HTTPError as e: logger.warning(f"Release creation on Github has failed: {e}") return False @classmethod @LoggedFunction(logger) def get_release(cls, owner: str, repo: str, tag: str) -> Optional[int]: """Get a release by its tag name https://docs.github.com/rest/reference/repos#get-a-release-by-tag-name :param owner: The owner namespace of the repository :param repo: The repository name :param tag: Tag to get release for :return: ID of found release """ try: response = Github.session().get( f"{Github.api_url()}/repos/{owner}/{repo}/releases/tags/{tag}" ) return response.json().get("id") except HTTPError as e: if e.response.status_code != 404: logger.debug(f"Get release by tag on Github has failed: {e}") return None @classmethod @LoggedFunction(logger) def edit_release(cls, owner: str, repo: str, id: int, changelog: str) -> bool: """Edit a release with updated change notes https://docs.github.com/rest/reference/repos#update-a-release :param owner: The owner namespace of the repository :param repo: The repository name :param id: ID of release to update :param changelog: The release notes for this version :return: Whether the request succeeded """ try: Github.session().post( f"{Github.api_url()}/repos/{owner}/{repo}/releases/{id}", json={"body": changelog}, ) return True except HTTPError as e: logger.warning(f"Edit release on Github has failed: {e}") return False @classmethod @LoggedFunction(logger) def post_release_changelog( cls, owner: str, repo: str, version: str, changelog: str ) -> bool: """Post release changelog :param owner: The owner namespace of the repository :param repo: The repository name :param version: The version number :param changelog: The release notes for this version :return: The status of the request """ tag = get_formatted_tag(version) logger.debug(f"Attempting to create release for {tag}") success = Github.create_release(owner, repo, tag, changelog) if not success: logger.debug("Unsuccessful, looking for an existing release to update") release_id = Github.get_release(owner, repo, tag) if release_id: logger.debug(f"Updating release {release_id}") success = Github.edit_release(owner, repo, release_id, changelog) else: logger.debug(f"Existing release not found") return success @classmethod @LoggedFunction(logger) def upload_asset( cls, owner: str, repo: str, release_id: int, file: str, label: str = None ) -> bool: """Upload an asset to an existing release https://docs.github.com/rest/reference/repos#upload-a-release-asset :param owner: The owner namespace of the repository :param repo: The repository name :param release_id: ID of the release to upload to :param file: Path of the file to upload :param label: Custom label for this file :return: The status of the request """ url = f"https://uploads.github.com/repos/{owner}/{repo}/releases/{release_id}/assets" content_type = mimetypes.guess_type(file, strict=False)[0] if not content_type: content_type = "application/octet-stream" try: response = Github.session().post( url, params={"name": os.path.basename(file), "label": label}, headers={ "Content-Type": content_type, }, data=open(file, "rb").read(), ) logger.debug( f"Asset upload on Github completed, url: {response.url}, status code: {response.status_code}" ) return True except HTTPError as e: logger.warning(f"Asset upload {file} on Github has failed: {e}") return False @classmethod def upload_dists(cls, owner: str, repo: str, version: str, path: str) -> bool: """Upload distributions to a release :param owner: The owner namespace of the repository :param repo: The repository name :param version: Version to upload for :param path: Path to the dist directory :return: The status of the request """ # Find the release corresponding to this version release_id = Github.get_release(owner, repo, get_formatted_tag(version)) if not release_id: logger.debug("No release found to upload assets to") return False # Upload assets one_or_more_failed = False for file in os.listdir(path): file_path = os.path.join(path, file) if not Github.upload_asset(owner, repo, release_id, file_path): one_or_more_failed = True return not one_or_more_failed class Gitea(Base): """Gitea helper class""" DEFAULT_DOMAIN = "gitea.com" DEFAULT_API_PATH = "/api/v1" _fix_mime_types() @staticmethod def domain() -> str: """Gitea domain property :return: The Gitea domain """ # ref: https://docs.gitea.com/en/actions/reference/environment-variables#default-environment-variables hvcs_domain = config.get( "hvcs_domain", os.getenv("GITEA_SERVER_URL", "").replace("https://", "") ) domain = hvcs_domain if hvcs_domain else Gitea.DEFAULT_DOMAIN return domain @staticmethod def api_url() -> str: """Gitea api_url property :return: The Gitea API URL """ hvcs_domain = config.get( "hvcs_domain", os.getenv("GITEA_SERVER_URL", "").replace("https://", "") ) hostname = config.get( "hvcs_api_domain", os.getenv("GITEA_API_URL", "").replace("https://", "") ) if hvcs_domain and not hostname: hostname = hvcs_domain + Gitea.DEFAULT_API_PATH elif not hostname: hostname = Gitea.DEFAULT_DOMAIN + Gitea.DEFAULT_API_PATH return f"https://{hostname}" @staticmethod def token() -> Optional[str]: """Gitea token property :return: The Gitea token environment variable (GITEA_TOKEN) value """ return os.environ.get(config.get("gitea_token_var")) @staticmethod def auth() -> Optional[TokenAuth]: """Gitea token property :return: The Gitea token environment variable (GITEA_TOKEN) value """ token = Gitea.token() if not token: return None return TokenAuth(token) @staticmethod def session( raise_for_status=True, retry: Union[Retry, bool, int] = True ) -> Session: session = build_requests_session(raise_for_status=raise_for_status, retry=retry) session.auth = Gitea.auth() return session @staticmethod @LoggedFunction(logger) def check_build_status(owner: str, repo: str, ref: str) -> bool: """Check build status https://gitea.com/api/swagger#/repository/repoCreateStatus :param owner: The owner namespace of the repository :param repo: The repository name :param ref: The sha1 hash of the commit ref :return: Was the build status success? """ url = "{domain}/repos/{owner}/{repo}/statuses/{ref}" try: response = Gitea.session().get( url.format(domain=Gitea.api_url(), owner=owner, repo=repo, ref=ref) ) data = response.json() if type(data) == list: return data[0].get("status") == "success" else: return data.get("status") == "success" except HTTPError as e: logger.warning(f"Build status check on Gitea has failed: {e}") return False @classmethod @LoggedFunction(logger) def create_release(cls, owner: str, repo: str, tag: str, changelog: str) -> bool: """Create a new release https://gitea.com/api/swagger#/repository/repoCreateRelease :param owner: The owner namespace of the repository :param repo: The repository name :param tag: Tag to create release for :param changelog: The release notes for this version :return: Whether the request succeeded """ try: Gitea.session().post( f"{Gitea.api_url()}/repos/{owner}/{repo}/releases", json={ "tag_name": tag, "name": tag, "body": changelog, "draft": False, "prerelease": False, }, ) return True except HTTPError as e: logger.warning(f"Release creation on Gitea has failed: {e}") return False @classmethod @LoggedFunction(logger) def get_release(cls, owner: str, repo: str, tag: str) -> Optional[int]: """Get a release by its tag name https://gitea.com/api/swagger#/repository/repoGetReleaseByTag :param owner: The owner namespace of the repository :param repo: The repository name :param tag: Tag to get release for :return: ID of found release """ try: response = Gitea.session().get( f"{Gitea.api_url()}/repos/{owner}/{repo}/releases/tags/{tag}" ) return response.json().get("id") except HTTPError as e: if e.response.status_code != 404: logger.debug(f"Get release by tag on Gitea has failed: {e}") return None @classmethod @LoggedFunction(logger) def edit_release(cls, owner: str, repo: str, id: int, changelog: str) -> bool: """Edit a release with updated change notes https://gitea.com/api/swagger#/repository/repoEditRelease :param owner: The owner namespace of the repository :param repo: The repository name :param id: ID of release to update :param changelog: The release notes for this version :return: Whether the request succeeded """ try: Gitea.session().post( f"{Gitea.api_url()}/repos/{owner}/{repo}/releases/{id}", json={"body": changelog}, ) return True except HTTPError as e: logger.warning(f"Edit release on Gitea has failed: {e}") return False @classmethod @LoggedFunction(logger) def post_release_changelog( cls, owner: str, repo: str, version: str, changelog: str ) -> bool: """Post release changelog :param owner: The owner namespace of the repository :param repo: The repository name :param version: The version number :param changelog: The release notes for this version :return: The status of the request """ tag = get_formatted_tag(version) logger.debug(f"Attempting to create release for {tag}") success = Gitea.create_release(owner, repo, tag, changelog) if not success: logger.debug("Unsuccessful, looking for an existing release to update") release_id = Gitea.get_release(owner, repo, tag) if release_id: logger.debug(f"Updating release {release_id}") success = Gitea.edit_release(owner, repo, release_id, changelog) else: logger.debug(f"Existing release not found") return success @classmethod @LoggedFunction(logger) def upload_asset( cls, owner: str, repo: str, release_id: int, file: str, label: str = None ) -> bool: """Upload an asset to an existing release https://gitea.com/api/swagger#/repository/repoCreateReleaseAttachment :param owner: The owner namespace of the repository :param repo: The repository name :param release_id: ID of the release to upload to :param file: Path of the file to upload :param label: Custom label for this file :return: The status of the request """ url = f"{Gitea.api_url()}/repos/{owner}/{repo}/releases/{release_id}/assets" try: name = os.path.basename(file) response = Gitea.session().post( url, params={"name": name}, data={}, files=[ ( "attachment", ( name, open(file, "rb"), "application/octet-stream", ), ) ], ) logger.debug( f"Asset upload on Gitea completed, url: {response.url}, status code: {response.status_code}" ) return True except HTTPError as e: logger.warning(f"Asset upload {file} on Gitea has failed: {e}") return False @classmethod def upload_dists(cls, owner: str, repo: str, version: str, path: str) -> bool: """Upload distributions to a release :param owner: The owner namespace of the repository :param repo: The repository name :param version: Version to upload for :param path: Path to the dist directory :return: The status of the request """ # Find the release corresponding to this version release_id = Gitea.get_release(owner, repo, get_formatted_tag(version)) if not release_id: logger.debug("No release found to upload assets to") return False # Upload assets one_or_more_failed = False for file in os.listdir(path): file_path = os.path.join(path, file) if not Gitea.upload_asset(owner, repo, release_id, file_path): one_or_more_failed = True return not one_or_more_failed class Gitlab(Base): """Gitlab helper class""" @staticmethod def domain() -> str: """Gitlab domain property :return: The Gitlab instance domain """ # Use Gitlab-CI environment vars if available if "CI_SERVER_URL" in os.environ: url = urlsplit(os.environ["CI_SERVER_URL"]) return f"{url.netloc}{url.path}".rstrip("/") domain = config.get("hvcs_domain", os.environ.get("CI_SERVER_HOST", None)) return domain if domain else "gitlab.com" @staticmethod def api_url() -> str: """Gitlab api_url property :return: The Gitlab instance API url """ # Use Gitlab-CI environment vars if available if "CI_SERVER_URL" in os.environ: return os.environ["CI_SERVER_URL"] return f"https://{Gitlab.domain()}" @staticmethod def token() -> Optional[str]: """Gitlab token property :return: The Gitlab token environment variable (GL_TOKEN) value """ return os.environ.get(config.get("gitlab_token_var")) @staticmethod @LoggedFunction(logger) def check_build_status(owner: str, repo: str, ref: str) -> bool: """Check last build status :param owner: The owner namespace of the repository. It includes all groups and subgroups. :param repo: The repository name :param ref: The sha1 hash of the commit ref :return: the status of the pipeline (False if a job failed) """ gl = gitlab.Gitlab(Gitlab.api_url(), private_token=Gitlab.token()) gl.auth() jobs = gl.projects.get(owner + "/" + repo).commits.get(ref).statuses.list() for job in jobs: if job["status"] not in ["success", "skipped"]: # type: ignore[index] if job["status"] == "pending": # type: ignore[index] logger.debug( f"check_build_status: job {job["name"]} is still in pending status" # type: ignore[index] ) return False elif job["status"] == "failed" and not job["allow_failure"]: # type: ignore[index] logger.debug(f"check_build_status: job {job["name"]} failed") # type: ignore[index] return False return True @classmethod @LoggedFunction(logger) def post_release_changelog( cls, owner: str, repo: str, version: str, changelog: str ) -> bool: """Post release changelog :param owner: The owner namespace of the repository :param repo: The repository name :param version: The version number :param changelog: The release notes for this version :return: The status of the request """ ref = get_formatted_tag(version) gl = gitlab.Gitlab(Gitlab.api_url(), private_token=Gitlab.token()) gl.auth() try: logger.debug(f"Before release create call") gl.projects.get(owner + "/" + repo).releases.create( { "name": "Release " + version, "tag_name": ref, "description": changelog, } ) except exceptions.GitlabCreateError: logger.debug( f"Release {ref} could not be created for project {owner}/{repo}" ) return False return True @LoggedFunction(logger) def get_hvcs() -> Base: """Get HVCS helper class :raises ImproperConfigurationError: if the hvcs option provided is not valid """ hvcs = config.get("hvcs") try: return globals()[hvcs.capitalize()] except KeyError: raise ImproperConfigurationError( '"{0}" is not a valid option for hvcs. Please use "github"|"gitlab"|"gitea"'.format( hvcs ) ) def check_build_status(owner: str, repository: str, ref: str) -> bool: """ Checks the build status of a commit on the api from your hosted version control provider. :param owner: The owner of the repository :param repository: The repository name :param ref: Commit or branch reference :return: A boolean with the build status """ logger.debug(f"Checking build status for {owner}/{repository}#{ref}") return get_hvcs().check_build_status(owner, repository, ref) def post_changelog(owner: str, repository: str, version: str, changelog: str) -> bool: """ Posts the changelog to the current hvcs release API :param owner: The owner of the repository :param repository: The repository name :param version: A string with the new version :param changelog: A string with the changelog in correct format :return: a tuple with success status and payload from hvcs """ logger.debug(f"Posting release changelog for {owner}/{repository} {version}") return get_hvcs().post_release_changelog(owner, repository, version, changelog) def upload_to_release(owner: str, repository: str, version: str, path: str) -> bool: """ Upload distributions to the current hvcs release API :param owner: The owner of the repository :param repository: The repository name :param version: A string with the version to upload for :param path: Path to dist directory :return: Status of the request """ return get_hvcs().upload_dists(owner, repository, version, path) def get_token() -> Optional[str]: """ Returns the token for the current VCS :return: The token in string form """ return get_hvcs().token() def get_domain() -> Optional[str]: """ Returns the domain for the current VCS :return: The domain in string form """ return get_hvcs().domain() def check_token() -> bool: """ Checks whether there exists a token or not. :return: A boolean telling if there is a token. """ return get_hvcs().token() is not None
"""HVCS """ import logging import mimetypes import os from typing import Any, Optional, Union, cast from urllib.parse import urlsplit from gitlab import exceptions, gitlab from requests import HTTPError, Session from requests.auth import AuthBase from urllib3 import Retry from .errors import ImproperConfigurationError from .helpers import LoggedFunction, build_requests_session from .settings import config from .vcs_helpers import get_formatted_tag logger = logging.getLogger(__name__) # Add a mime type for wheels mimetypes.add_type("application/octet-stream", ".whl") class Base(object): @staticmethod def domain() -> str: raise NotImplementedError @staticmethod def api_url() -> str: raise NotImplementedError @staticmethod def token() -> Optional[str]: raise NotImplementedError @staticmethod def check_build_status(owner: str, repo: str, ref: str) -> bool: raise NotImplementedError @classmethod def post_release_changelog( cls, owner: str, repo: str, version: str, changelog: str ) -> bool: raise NotImplementedError @classmethod def upload_dists(cls, owner: str, repo: str, version: str, path: str) -> bool: # Skip on unsupported HVCS instead of raising error return True def _fix_mime_types(): """Fix incorrect entries in the `mimetypes` registry. On Windows, the Python standard library's `mimetypes` reads in mappings from file extension to MIME type from the Windows registry. Other applications can and do write incorrect values to this registry, which causes `mimetypes.guess_type` to return incorrect values, which causes TensorBoard to fail to render on the frontend. This method hard-codes the correct mappings for certain MIME types that are known to be either used by python-semantic-release or problematic in general. """ mimetypes.add_type("text/markdown", ".md") class TokenAuth(AuthBase): """ requests Authentication for token based authorization """ def __init__(self, token): self.token = token def __eq__(self, other): return all( [ self.token == getattr(other, "token", None), ] ) def __ne__(self, other): return not self == other def __call__(self, r): r.headers["Authorization"] = f"token {self.token}" return r class Github(Base): """Github helper class""" DEFAULT_DOMAIN = "github.com" _fix_mime_types() @staticmethod def domain() -> str: """Github domain property :return: The Github domain """ # ref: https://docs.github.com/en/actions/reference/environment-variables#default-environment-variables hvcs_domain = config.get( "hvcs_domain", os.getenv("GITHUB_SERVER_URL", "").replace("https://", "") ) domain = hvcs_domain if hvcs_domain else Github.DEFAULT_DOMAIN return domain @staticmethod def api_url() -> str: """Github api_url property :return: The Github API URL """ # not necessarily prefixed with api in the case of a custom domain, so # can't just default DEFAULT_DOMAIN to github.com # ref: https://docs.github.com/en/actions/reference/environment-variables#default-environment-variables hvcs_api_domain = config.get( "hvcs_api_domain", os.getenv("GITHUB_API_URL", "").replace("https://", "") ) hostname = ( hvcs_api_domain if hvcs_api_domain else "api." + Github.DEFAULT_DOMAIN ) return f"https://{hostname}" @staticmethod def token() -> Optional[str]: """Github token property :return: The Github token environment variable (GH_TOKEN) value """ return os.environ.get(config.get("github_token_var")) @staticmethod def auth() -> Optional[TokenAuth]: """Github token property :return: The Github token environment variable (GH_TOKEN) value """ token = Github.token() if not token: return None return TokenAuth(token) @staticmethod def session( raise_for_status=True, retry: Union[Retry, bool, int] = True ) -> Session: session = build_requests_session(raise_for_status=raise_for_status, retry=retry) session.auth = Github.auth() return session @staticmethod @LoggedFunction(logger) def check_build_status(owner: str, repo: str, ref: str) -> bool: """Check build status https://docs.github.com/rest/reference/repos#get-the-combined-status-for-a-specific-reference :param owner: The owner namespace of the repository :param repo: The repository name :param ref: The sha1 hash of the commit ref :return: Was the build status success? """ url = "{domain}/repos/{owner}/{repo}/commits/{ref}/status" try: response = Github.session().get( url.format(domain=Github.api_url(), owner=owner, repo=repo, ref=ref) ) return response.json().get("state") == "success" except HTTPError as e: logger.warning(f"Build status check on Github has failed: {e}") return False @classmethod @LoggedFunction(logger) def create_release(cls, owner: str, repo: str, tag: str, changelog: str) -> bool: """Create a new release https://docs.github.com/rest/reference/repos#create-a-release :param owner: The owner namespace of the repository :param repo: The repository name :param tag: Tag to create release for :param changelog: The release notes for this version :return: Whether the request succeeded """ try: Github.session().post( f"{Github.api_url()}/repos/{owner}/{repo}/releases", json={ "tag_name": tag, "name": tag, "body": changelog, "draft": False, "prerelease": False, }, ) return True except HTTPError as e: logger.warning(f"Release creation on Github has failed: {e}") return False @classmethod @LoggedFunction(logger) def get_release(cls, owner: str, repo: str, tag: str) -> Optional[int]: """Get a release by its tag name https://docs.github.com/rest/reference/repos#get-a-release-by-tag-name :param owner: The owner namespace of the repository :param repo: The repository name :param tag: Tag to get release for :return: ID of found release """ try: response = Github.session().get( f"{Github.api_url()}/repos/{owner}/{repo}/releases/tags/{tag}" ) return response.json().get("id") except HTTPError as e: if e.response.status_code != 404: logger.debug(f"Get release by tag on Github has failed: {e}") return None @classmethod @LoggedFunction(logger) def edit_release(cls, owner: str, repo: str, id: int, changelog: str) -> bool: """Edit a release with updated change notes https://docs.github.com/rest/reference/repos#update-a-release :param owner: The owner namespace of the repository :param repo: The repository name :param id: ID of release to update :param changelog: The release notes for this version :return: Whether the request succeeded """ try: Github.session().post( f"{Github.api_url()}/repos/{owner}/{repo}/releases/{id}", json={"body": changelog}, ) return True except HTTPError as e: logger.warning(f"Edit release on Github has failed: {e}") return False @classmethod @LoggedFunction(logger) def post_release_changelog( cls, owner: str, repo: str, version: str, changelog: str ) -> bool: """Post release changelog :param owner: The owner namespace of the repository :param repo: The repository name :param version: The version number :param changelog: The release notes for this version :return: The status of the request """ tag = get_formatted_tag(version) logger.debug(f"Attempting to create release for {tag}") success = Github.create_release(owner, repo, tag, changelog) if not success: logger.debug("Unsuccessful, looking for an existing release to update") release_id = Github.get_release(owner, repo, tag) if release_id: logger.debug(f"Updating release {release_id}") success = Github.edit_release(owner, repo, release_id, changelog) else: logger.debug(f"Existing release not found") return success @classmethod @LoggedFunction(logger) def upload_asset( cls, owner: str, repo: str, release_id: int, file: str, label: str = None ) -> bool: """Upload an asset to an existing release https://docs.github.com/rest/reference/repos#upload-a-release-asset :param owner: The owner namespace of the repository :param repo: The repository name :param release_id: ID of the release to upload to :param file: Path of the file to upload :param label: Custom label for this file :return: The status of the request """ url = f"https://uploads.github.com/repos/{owner}/{repo}/releases/{release_id}/assets" content_type = mimetypes.guess_type(file, strict=False)[0] if not content_type: content_type = "application/octet-stream" try: response = Github.session().post( url, params={"name": os.path.basename(file), "label": label}, headers={ "Content-Type": content_type, }, data=open(file, "rb").read(), ) logger.debug( f"Asset upload on Github completed, url: {response.url}, status code: {response.status_code}" ) return True except HTTPError as e: logger.warning(f"Asset upload {file} on Github has failed: {e}") return False @classmethod def upload_dists(cls, owner: str, repo: str, version: str, path: str) -> bool: """Upload distributions to a release :param owner: The owner namespace of the repository :param repo: The repository name :param version: Version to upload for :param path: Path to the dist directory :return: The status of the request """ # Find the release corresponding to this version release_id = Github.get_release(owner, repo, get_formatted_tag(version)) if not release_id: logger.debug("No release found to upload assets to") return False # Upload assets one_or_more_failed = False for file in os.listdir(path): file_path = os.path.join(path, file) if not Github.upload_asset(owner, repo, release_id, file_path): one_or_more_failed = True return not one_or_more_failed class Gitea(Base): """Gitea helper class""" DEFAULT_DOMAIN = "gitea.com" DEFAULT_API_PATH = "/api/v1" _fix_mime_types() @staticmethod def domain() -> str: """Gitea domain property :return: The Gitea domain """ # ref: https://docs.gitea.com/en/actions/reference/environment-variables#default-environment-variables hvcs_domain = config.get( "hvcs_domain", os.getenv("GITEA_SERVER_URL", "").replace("https://", "") ) domain = hvcs_domain if hvcs_domain else Gitea.DEFAULT_DOMAIN return domain @staticmethod def api_url() -> str: """Gitea api_url property :return: The Gitea API URL """ hvcs_domain = config.get( "hvcs_domain", os.getenv("GITEA_SERVER_URL", "").replace("https://", "") ) hostname = config.get( "hvcs_api_domain", os.getenv("GITEA_API_URL", "").replace("https://", "") ) if hvcs_domain and not hostname: hostname = hvcs_domain + Gitea.DEFAULT_API_PATH elif not hostname: hostname = Gitea.DEFAULT_DOMAIN + Gitea.DEFAULT_API_PATH return f"https://{hostname}" @staticmethod def token() -> Optional[str]: """Gitea token property :return: The Gitea token environment variable (GITEA_TOKEN) value """ return os.environ.get(config.get("gitea_token_var")) @staticmethod def auth() -> Optional[TokenAuth]: """Gitea token property :return: The Gitea token environment variable (GITEA_TOKEN) value """ token = Gitea.token() if not token: return None return TokenAuth(token) @staticmethod def session( raise_for_status=True, retry: Union[Retry, bool, int] = True ) -> Session: session = build_requests_session(raise_for_status=raise_for_status, retry=retry) session.auth = Gitea.auth() return session @staticmethod @LoggedFunction(logger) def check_build_status(owner: str, repo: str, ref: str) -> bool: """Check build status https://gitea.com/api/swagger#/repository/repoCreateStatus :param owner: The owner namespace of the repository :param repo: The repository name :param ref: The sha1 hash of the commit ref :return: Was the build status success? """ url = "{domain}/repos/{owner}/{repo}/statuses/{ref}" try: response = Gitea.session().get( url.format(domain=Gitea.api_url(), owner=owner, repo=repo, ref=ref) ) data = response.json() if type(data) == list: return data[0].get("status") == "success" else: return data.get("status") == "success" except HTTPError as e: logger.warning(f"Build status check on Gitea has failed: {e}") return False @classmethod @LoggedFunction(logger) def create_release(cls, owner: str, repo: str, tag: str, changelog: str) -> bool: """Create a new release https://gitea.com/api/swagger#/repository/repoCreateRelease :param owner: The owner namespace of the repository :param repo: The repository name :param tag: Tag to create release for :param changelog: The release notes for this version :return: Whether the request succeeded """ try: Gitea.session().post( f"{Gitea.api_url()}/repos/{owner}/{repo}/releases", json={ "tag_name": tag, "name": tag, "body": changelog, "draft": False, "prerelease": False, }, ) return True except HTTPError as e: logger.warning(f"Release creation on Gitea has failed: {e}") return False @classmethod @LoggedFunction(logger) def get_release(cls, owner: str, repo: str, tag: str) -> Optional[int]: """Get a release by its tag name https://gitea.com/api/swagger#/repository/repoGetReleaseByTag :param owner: The owner namespace of the repository :param repo: The repository name :param tag: Tag to get release for :return: ID of found release """ try: response = Gitea.session().get( f"{Gitea.api_url()}/repos/{owner}/{repo}/releases/tags/{tag}" ) return response.json().get("id") except HTTPError as e: if e.response.status_code != 404: logger.debug(f"Get release by tag on Gitea has failed: {e}") return None @classmethod @LoggedFunction(logger) def edit_release(cls, owner: str, repo: str, id: int, changelog: str) -> bool: """Edit a release with updated change notes https://gitea.com/api/swagger#/repository/repoEditRelease :param owner: The owner namespace of the repository :param repo: The repository name :param id: ID of release to update :param changelog: The release notes for this version :return: Whether the request succeeded """ try: Gitea.session().post( f"{Gitea.api_url()}/repos/{owner}/{repo}/releases/{id}", json={"body": changelog}, ) return True except HTTPError as e: logger.warning(f"Edit release on Gitea has failed: {e}") return False @classmethod @LoggedFunction(logger) def post_release_changelog( cls, owner: str, repo: str, version: str, changelog: str ) -> bool: """Post release changelog :param owner: The owner namespace of the repository :param repo: The repository name :param version: The version number :param changelog: The release notes for this version :return: The status of the request """ tag = get_formatted_tag(version) logger.debug(f"Attempting to create release for {tag}") success = Gitea.create_release(owner, repo, tag, changelog) if not success: logger.debug("Unsuccessful, looking for an existing release to update") release_id = Gitea.get_release(owner, repo, tag) if release_id: logger.debug(f"Updating release {release_id}") success = Gitea.edit_release(owner, repo, release_id, changelog) else: logger.debug(f"Existing release not found") return success @classmethod @LoggedFunction(logger) def upload_asset( cls, owner: str, repo: str, release_id: int, file: str, label: str = None ) -> bool: """Upload an asset to an existing release https://gitea.com/api/swagger#/repository/repoCreateReleaseAttachment :param owner: The owner namespace of the repository :param repo: The repository name :param release_id: ID of the release to upload to :param file: Path of the file to upload :param label: Custom label for this file :return: The status of the request """ url = f"{Gitea.api_url()}/repos/{owner}/{repo}/releases/{release_id}/assets" try: name = os.path.basename(file) response = Gitea.session().post( url, params={"name": name}, data={}, files=[ ( "attachment", ( name, open(file, "rb"), "application/octet-stream", ), ) ], ) logger.debug( f"Asset upload on Gitea completed, url: {response.url}, status code: {response.status_code}" ) return True except HTTPError as e: logger.warning(f"Asset upload {file} on Gitea has failed: {e}") return False @classmethod def upload_dists(cls, owner: str, repo: str, version: str, path: str) -> bool: """Upload distributions to a release :param owner: The owner namespace of the repository :param repo: The repository name :param version: Version to upload for :param path: Path to the dist directory :return: The status of the request """ # Find the release corresponding to this version release_id = Gitea.get_release(owner, repo, get_formatted_tag(version)) if not release_id: logger.debug("No release found to upload assets to") return False # Upload assets one_or_more_failed = False for file in os.listdir(path): file_path = os.path.join(path, file) if not Gitea.upload_asset(owner, repo, release_id, file_path): one_or_more_failed = True return not one_or_more_failed class Gitlab(Base): """Gitlab helper class""" @staticmethod def domain() -> str: """Gitlab domain property :return: The Gitlab instance domain """ # Use Gitlab-CI environment vars if available if "CI_SERVER_URL" in os.environ: url = urlsplit(os.environ["CI_SERVER_URL"]) return f"{url.netloc}{url.path}".rstrip("/") domain = config.get("hvcs_domain", os.environ.get("CI_SERVER_HOST", None)) return domain if domain else "gitlab.com" @staticmethod def api_url() -> str: """Gitlab api_url property :return: The Gitlab instance API url """ # Use Gitlab-CI environment vars if available if "CI_SERVER_URL" in os.environ: return os.environ["CI_SERVER_URL"] return f"https://{Gitlab.domain()}" @staticmethod def token() -> Optional[str]: """Gitlab token property :return: The Gitlab token environment variable (GL_TOKEN) value """ return os.environ.get(config.get("gitlab_token_var")) @staticmethod @LoggedFunction(logger) def check_build_status(owner: str, repo: str, ref: str) -> bool: """Check last build status :param owner: The owner namespace of the repository. It includes all groups and subgroups. :param repo: The repository name :param ref: The sha1 hash of the commit ref :return: the status of the pipeline (False if a job failed) """ gl = gitlab.Gitlab(Gitlab.api_url(), private_token=Gitlab.token()) gl.auth() jobs = gl.projects.get(owner + "/" + repo).commits.get(ref).statuses.list() for job in jobs: if job["status"] not in ["success", "skipped"]: # type: ignore[index] if job["status"] == "pending": # type: ignore[index] logger.debug( f"check_build_status: job {job['name']} is still in pending status" # type: ignore[index] ) return False elif job["status"] == "failed" and not job["allow_failure"]: # type: ignore[index] logger.debug(f"check_build_status: job {job['name']} failed") # type: ignore[index] return False return True @classmethod @LoggedFunction(logger) def post_release_changelog( cls, owner: str, repo: str, version: str, changelog: str ) -> bool: """Post release changelog :param owner: The owner namespace of the repository :param repo: The repository name :param version: The version number :param changelog: The release notes for this version :return: The status of the request """ ref = get_formatted_tag(version) gl = gitlab.Gitlab(Gitlab.api_url(), private_token=Gitlab.token()) gl.auth() try: logger.debug(f"Before release create call") gl.projects.get(owner + "/" + repo).releases.create( { "name": "Release " + version, "tag_name": ref, "description": changelog, } ) except exceptions.GitlabCreateError: logger.debug( f"Release {ref} could not be created for project {owner}/{repo}" ) return False return True @LoggedFunction(logger) def get_hvcs() -> Base: """Get HVCS helper class :raises ImproperConfigurationError: if the hvcs option provided is not valid """ hvcs = config.get("hvcs") try: return globals()[hvcs.capitalize()] except KeyError: raise ImproperConfigurationError( '"{0}" is not a valid option for hvcs. Please use "github"|"gitlab"|"gitea"'.format( hvcs ) ) def check_build_status(owner: str, repository: str, ref: str) -> bool: """ Checks the build status of a commit on the api from your hosted version control provider. :param owner: The owner of the repository :param repository: The repository name :param ref: Commit or branch reference :return: A boolean with the build status """ logger.debug(f"Checking build status for {owner}/{repository}#{ref}") return get_hvcs().check_build_status(owner, repository, ref) def post_changelog(owner: str, repository: str, version: str, changelog: str) -> bool: """ Posts the changelog to the current hvcs release API :param owner: The owner of the repository :param repository: The repository name :param version: A string with the new version :param changelog: A string with the changelog in correct format :return: a tuple with success status and payload from hvcs """ logger.debug(f"Posting release changelog for {owner}/{repository} {version}") return get_hvcs().post_release_changelog(owner, repository, version, changelog) def upload_to_release(owner: str, repository: str, version: str, path: str) -> bool: """ Upload distributions to the current hvcs release API :param owner: The owner of the repository :param repository: The repository name :param version: A string with the version to upload for :param path: Path to dist directory :return: Status of the request """ return get_hvcs().upload_dists(owner, repository, version, path) def get_token() -> Optional[str]: """ Returns the token for the current VCS :return: The token in string form """ return get_hvcs().token() def get_domain() -> Optional[str]: """ Returns the domain for the current VCS :return: The domain in string form """ return get_hvcs().domain() def check_token() -> bool: """ Checks whether there exists a token or not. :return: A boolean telling if there is a token. """ return get_hvcs().token() is not None
#!/usr/bin/python3.6 import ast import sys import tokenize import pickle from datetime import datetime import re import argparse from functools import reduce import json from .genCode import genCode, PrintState from .mod_index_generator import get_index from .get_comments import get_comments from . import For2PyError from . import syntax from typing import List, Dict, Iterable, Optional from collections import OrderedDict from itertools import chain, product import operator import uuid import os.path # noinspection PyDefaultArgument class GrFNState: def __init__( self, lambda_strings: Optional[List[str]], last_definitions: Optional[Dict] = {}, next_definitions: Optional[Dict] = {}, last_definition_default=0, function_name=None, variable_types: Optional[Dict] = {}, start: Optional[Dict] = {}, scope_path: Optional[List] = [], arrays: Optional[Dict] = {}, array_types: Optional[Dict] = {}, array_assign_name: Optional = None, string_assign_name: Optional = None, ): self.lambda_strings = lambda_strings self.last_definitions = last_definitions self.next_definitions = next_definitions self.last_definition_default = last_definition_default self.function_name = function_name self.variable_types = variable_types self.start = start self.scope_path = scope_path self.arrays = arrays self.array_types = array_types self.array_assign_name = array_assign_name self.string_assign_name = string_assign_name def copy( self, lambda_strings: Optional[List[str]] = None, last_definitions: Optional[Dict] = None, next_definitions: Optional[Dict] = None, last_definition_default=None, function_name=None, variable_types: Optional[Dict] = None, start: Optional[Dict] = None, scope_path: Optional[List] = None, arrays: Optional[Dict] = None, array_types: Optional[Dict] = None, array_assign_name: Optional = None, string_assign_name: Optional = None, ): return GrFNState( self.lambda_strings if lambda_strings is None else lambda_strings, self.last_definitions if last_definitions is None else last_definitions, self.next_definitions if next_definitions is None else next_definitions, self.last_definition_default if last_definition_default is None else last_definition_default, self.function_name if function_name is None else function_name, self.variable_types if variable_types is None else variable_types, self.start if start is None else start, self.scope_path if scope_path is None else scope_path, self.arrays if arrays is None else arrays, self.array_types if array_types is None else array_types, self.array_assign_name if array_assign_name is None else array_assign_name, self.string_assign_name if string_assign_name is None else string_assign_name, ) # noinspection PyDefaultArgument,PyTypeChecker class GrFNGenerator(object): def __init__(self, annotated_assigned=[], function_definitions=[]): self.annotated_assigned = annotated_assigned self.function_definitions = function_definitions self.use_numpy = True self.fortran_file = None self.exclude_list = [] self.loop_input = [] self.comments = {} self.update_functions = {} self.mode_mapper = {} self.name_mapper = {} self.variable_map = {} self.function_argument_map = {} # Holds all declared arrays {symbol:domain} self.arrays = {} # Holds declared array types {symbol:type} self.array_types = {} self.array_assign_name = None # Holds a list of multi-dimensional array symbols self.md_array = [] # Holds all the string assignments along with their length self.strings = {} self.outer_count = 0 self.types = (list, ast.Module, ast.FunctionDef) self.current_scope = "global" self.loop_index = -1 self.parent_loop_state = None self.parent_if_state = None self.handling_f_args = True self.f_array_arg = [] # {symbol:index} self.updated_arrays = {} # {symbol: [_list_of_domains_]} # This mapping is required as there may be # a multiple array passes to the function # argument and we do not want to replace one # with another. We need to update all function # argument domains for arrays self.array_arg_domain = {} # Holds list of modules that program references self.module_variable_types = {} # Holds the list of declared subprograms in modules self.module_subprograms = [] # Holds module names self.module_names = [] # List of generated lambda function def. names self.generated_lambda_functions = [] # List of user-defined (derived) types self.derived_types = [] # List of derived type grfns self.derived_types_grfn = [] # List of attributes declared under user-defined types self.derived_types_attributes = {} # List of variables (objects) declared with user-defined type self.derived_type_objects = {} # Currently handling derived type object name self.current_d_object_name = None # Currently handling derived type object's accessing attributes self.current_d_object_attributes = [] self.is_d_object_array_assign = False self.elseif_flag = False self.if_index = -1 self.elif_index = 0 self.module_summary = None self.global_scope_variables = {} self.exit_candidates = [] self.global_state = None self.imported_module = [] self.imported_module_paths = [] self.original_python_src = "" self.generated_import_codes = [] self.global_grfn = { "containers": [ { "name": None, "source_refs": [], "gensym": None, "arguments": [], "updated": [], "return_value": [], "body": [], } ], "variables": [], } self.gensym_tag_map = { "container": "c", "variable": "v", "function": "f", } self.type_def_map = { "real": "float", "integer": "integer", "string": "string", "bool": "boolean", "Array": "Array", "character": "string", "String": "string", } # The binops dictionary holds operators for all the arithmetic and # comparative functions self.binops = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.Pow: operator.pow, ast.Eq: operator.eq, ast.LtE: operator.le, } # The annotate_map dictionary is used to map Python ast data types # into data types for the lambdas self.annotate_map = { "NoneType": "undefined", "real": "Real", "float": "real", "Real": "real", "integer": "int", "int": "integer", "string": "str", "str": "string", "array": "[]", "list": "array", "bool": "bool", "file_handle": "fh", "Array": "Array", "String": "string", } # Arithmetic operator dictionary # TODO: Complete the list self.arithmetic_ops = { "Add": "+", "Sub": "-", "Div": "/", "Mult": "*", "+": "+", "-": "-", "/": "/", "*": "*", } # The unnecessary_types tuple holds the ast types to ignore self.unnecessary_types = ( ast.Mult, ast.Add, ast.Sub, ast.Pow, ast.Div, ast.USub, ast.Eq, ast.LtE, ) # List of helper library types self.library_types = ["Array", "String"] # Regular expression to match python statements that need to be # bypassed in the GrFN and lambda files. Currently contains I/O # statements. self.bypass_io = ( r"^format_\d+$|^format_\d+_obj$|^file_\d+$|^file_\w+$" r"|^write_list_\d+$|^write_line$|^format_\d+_obj" r".*|^Format$|^list_output_formats$|" r"^write_list_stream$|^file_\d+\.write$|^file_\w+\.write$" r"^output_fmt$" ) self.re_bypass_io = re.compile(self.bypass_io, re.I) self.process_grfn = { "ast.FunctionDef": self.process_function_definition, "ast.arguments": self.process_arguments, "ast.arg": self.process_arg, "ast.Load": self.process_load, "ast.Store": self.process_store, "ast.Index": self.process_index, "ast.Constant": self.process_constant, "ast.Num": self.process_num, "ast.List": self.process_list_ast, "ast.Str": self.process_str, "ast.For": self.process_for, "ast.If": self.process_if, "ast.UnaryOp": self.process_unary_operation, "ast.BinOp": self.process_binary_operation, "ast.BoolOp": self.process_boolean_operation, "ast.Expr": self.process_expression, "ast.Compare": self.process_compare, "ast.Subscript": self.process_subscript, "ast.Name": self.process_name, "ast.AnnAssign": self.process_annotated_assign, "ast.Assign": self.process_assign, "ast.Tuple": self.process_tuple, "ast.Call": self.process_call, "ast.Module": self.process_module, "ast.Attribute": self.process_attribute, "ast.AST": self.process_ast, "ast.NameConstant": self._process_nameconstant, "ast.Return": self.process_return_value, "ast.While": self.process_while, "ast.Break": self.process_break, "ast.ClassDef": self.process_class_def, "ast.Try": self.process_try, } def gen_grfn(self, node, state, call_source): """ This function generates the GrFN structure by parsing through the python AST """ # Look for code that is not inside any function. if state.function_name is None and not any( isinstance(node, t) for t in self.types ): # If the node is of instance ast.Call, it is the starting point # of the system. node_name = node.__repr__().split()[0][2:] if ( isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id != "String" and node.func.id not in self.derived_types ): start_function_name = self.generate_container_id_name( self.fortran_file, ["@global"], node.func.id ) return [{"start": start_function_name}] elif isinstance(node, ast.Expr): if ( isinstance(node.value, ast.Call) and isinstance(node.value.func, ast.Attribute) and node.value.func.attr == "set_" ): return self.process_grfn[node_name]( node, state, call_source ) else: return self.gen_grfn(node.value, state, "start") elif isinstance(node, ast.If): return self.gen_grfn(node.body, state, "start") else: if node_name != "ast.Import" and node_name != "ast.ImportFrom": return self.process_grfn[node_name]( node, state, call_source ) else: # Check if this is a module that is imported if ( node_name == "ast.ImportFrom" and "m_" in node.module.split(".")[-1] ): imported_module = node.module.split(".")[-1][2:] self.imported_module.append(imported_module) self.imported_module_paths.append(node.module) self.derived_types.extend( self.module_summary[imported_module][ "derived_type_list" ] ) # Comment it out for now to avoid "import *" case. # state.lambda_strings.insert(0, f"from {node.module} # import *\n") return [] elif isinstance(node, list): return self.process_list(node, state, call_source) elif any( isinstance(node, node_type) for node_type in self.unnecessary_types ): return self.process_unnecessary_types(node, state, call_source) else: node_name = node.__repr__().split()[0][2:] if self.process_grfn.get(node_name): return self.process_grfn[node_name](node, state, call_source) else: return self.process_nomatch(node, state, call_source) def process_list(self, node, state, call_source): """ If there are one or more ast nodes inside the `body` of a node, they appear as a list. Process each node in the list and chain them together into a single list of GrFN dictionaries. """ # result = [] # for cur in node: # tmp = self.gen_grfn(cur, state, call_source) # result.append(tmp) # return list(chain.from_iterable(result)) return list( chain.from_iterable( [self.gen_grfn(cur, state, call_source) for cur in node] ) ) def process_function_definition(self, node, state, *_): """ This function processes the function definition i.e. functionDef instance. It appends GrFN dictionaries to the `functions` key in the main GrFN JSON. These dictionaries consist of the function_assign_grfn of the function body and the function_container_grfn of the function. Every call to this function adds these along with the identifier_spec_grfn to the main GrFN JSON. """ self.module_names.append(node.name) return_value = [] return_list = [] local_last_definitions = state.last_definitions.copy() local_next_definitions = state.next_definitions.copy() local_variable_types = state.variable_types.copy() scope_path = state.scope_path.copy() # If the scope_path is empty, add @global to the list to denote that # this is the outermost scope if len(scope_path) == 0: scope_path.append("@global") if node.decorator_list: # This is still a work-in-progress function since a complete # representation of SAVEd variables has not been decided for GrFN. # Currently, if the decorator function is static_vars (for # SAVEd variables), their types are loaded in the variable_types # dictionary. function_state = state.copy( last_definitions=local_last_definitions, next_definitions=local_next_definitions, function_name=node.name, variable_types=local_variable_types, ) self.process_decorators(node.decorator_list, function_state) # Check if the function contains arguments or not. This determines # whether the function is the outermost scope (does not contain # arguments) or it is not (contains arguments). For non-outermost # scopes, indexing starts from -1 (because all arguments will have # an index of -1). For outermost scopes, indexing starts from # normally from 0. # TODO: What do you do when a non-outermost scope function does not # have arguments. Current assumption is that the function without # arguments is the outermost function i.e. call to the `start` # function. But there can be functions without arguments which are not # the `start` functions but instead some inner functions. # The following is a test to make sure that there is only one # function without arguments and that is the outermost function. All # of the models that we currently handle have this structure and # we'll have to think about how to handle cases that have more than # one non-argument function. if len(node.args.args) == 0: self.outer_count += 1 assert self.outer_count == 1, ( "There is more than one function " "without arguments in this system. " "This is not currently handled." ) function_state = state.copy( last_definitions=local_last_definitions, next_definitions=local_next_definitions, function_name=node.name, variable_types=local_variable_types, last_definition_default=0, ) else: function_state = state.copy( last_definitions={}, next_definitions={}, function_name=node.name, variable_types=local_variable_types, last_definition_default=-1, ) # Copy the states of all the global variables into the global state # holder if not self.global_scope_variables and self.current_scope == "global": self.global_scope_variables = state.copy( last_definitions=local_last_definitions, next_definitions=local_next_definitions, function_name=node.name, variable_types=local_variable_types, last_definition_default=0, ) # Get the list of arguments from the function definition argument_list = self.gen_grfn(node.args, function_state, "functiondef") # Keep a map of the arguments for each function. This will be used in # `process_for` to identify arguments which are function arguments # from those that are not self.function_argument_map[node.name] = { "name": "", "updated_list": "", "updated_indices": [], "argument_list": "", "argument_indices": [], } self.function_argument_map[node.name]["argument_list"] = argument_list # Update the current scope so that for every identifier inside the # body, the scope information is updated self.current_scope = node.name # Create the variable definition for the arguments argument_variable_grfn = [] self.handling_f_args = True for argument in argument_list: argument_variable_grfn.append( self.generate_variable_definition( [argument], None, False, function_state ) ) self.handling_f_args = False # Generate the `variable_identifier_name` for each container argument. # TODO Currently only variables are handled as container arguments. # Create test cases of other containers as container arguments and # extend this functionality. argument_list = [ f"@variable::{x}::{function_state.last_definitions[x]}" for x in argument_list ] # Enter the body of the function and recursively generate the GrFN of # the function body body_grfn = self.gen_grfn(node.body, function_state, "functiondef") # Get the `return_value` from the body. We want to append it separately. # TODO There can be multiple return values. `return_value` should be # a list and you should append to it. for body in body_grfn: for function in body["functions"]: if ( function.get("function") and function["function"]["type"] == "return" ): return_value = function["value"] # Remove the return_value function body from the main # body as we don't need that anymore body["functions"].remove(function) # TODO The return value cannot always be a `variable`. It can be # literals as well. Add that functionality here. if return_value: for value in return_value: if "var" in value: return_list.append( f"@variable::{value["var"]["variable"]}" f"::{value["var"]["index"]}" ) elif "call" in value: for _ in value["call"]["inputs"]: if "var" in value: return_list.append( f"@variable::{value["var"]["variable"]}::" f"{value["var"]["index"]}" ) return_list = list(set(return_list)) else: return_list = [] # Get the function_reference_spec, function_assign_spec and # identifier_spec for the function ( function_variable_grfn, function_assign_grfn, body_container_grfn, ) = self._get_variables_and_functions(body_grfn) # Combine the variable grfn of the arguments with that of the # container body container_variables = argument_variable_grfn + function_variable_grfn # Find the list of updated identifiers if argument_list: updated_identifiers = self._find_updated( argument_variable_grfn, function_variable_grfn, self.f_array_arg, function_state, ) for array in self.f_array_arg: if array in function_state.last_definitions: self.updated_arrays[ array ] = function_state.last_definitions[array] else: updated_identifiers = [] self.function_argument_map[node.name][ "updated_list" ] = updated_identifiers # Get a list of all argument names argument_name_list = [] for item in argument_list: argument_name_list.append(item.split("::")[1]) # Now, find the indices of updated arguments for arg in updated_identifiers: updated_argument = arg.split("::")[1] argument_index = argument_name_list.index(updated_argument) self.function_argument_map[node.name]["updated_indices"].append( argument_index ) # Some arguments to a function are output variables i.e. they are not # used as inputs to a operation but are actually updated within the # function. The reason for this is that Fortran/C design pattern of # passing variables by reference to a callee subroutine so that there # values can be populated by the callee subroutine and then used by # the caller subroutine after the callee returns # We need to remove these inputs from the argument_list old_args = [x for x in argument_list] self._remove_output_variables(argument_list, body_grfn) # Update the arguments in the function map as well self.function_argument_map[node.name]["argument_list"] = argument_list # Now, find the indices of argument variables that have been included # in the final list i.e. those that are actual inputs to the function for idx in range(len(old_args)): if old_args[idx] in argument_list: self.function_argument_map[node.name][ "argument_indices" ].append(idx) # Create a gensym for the function container container_gensym = self.generate_gensym("container") container_id_name = self.generate_container_id_name( self.fortran_file, scope_path, node.name ) self.function_argument_map[node.name]["name"] = container_id_name # Add the function name to the list that stores all the functions # defined in the program self.function_definitions.append(container_id_name) function_container_grfn = { "name": container_id_name, "source_refs": [], "gensym": container_gensym, "type": "function", "arguments": argument_list, "updated": updated_identifiers, "return_value": return_list, "body": function_assign_grfn, } function_container_grfn = [ function_container_grfn ] + body_container_grfn # function_assign_grfn.append(function_container_grfn) pgm = { "containers": function_container_grfn, "variables": container_variables, } return [pgm] def process_arguments(self, node, state, call_source): """ This function returns a list of arguments defined in a function definition. `node.args` is a list of `arg` nodes which are iteratively processed to get the argument name. """ return [self.gen_grfn(arg, state, call_source) for arg in node.args] def process_arg(self, node, state, call_source): """ This function processes a function argument. """ # Variables are declared as List() objects in the intermediate Python # representation in order to mimic the pass-by-reference property of # Fortran. So, arguments have `annotations` which hold the type() of # A the variable i.e. x[Int], y[Float], etc. assert ( node.annotation ), "Found argument without annotation. This should not happen." state.variable_types[node.arg] = self.get_variable_type( node.annotation ) # Check if an argument is a string annotation_name = node.annotation.__repr__().split()[0][2:] if annotation_name == "ast.Name" and node.annotation.id == "String": self.strings[node.arg] = { "length": "Undefined", "annotation": False, "annotation_assign": True, } if state.last_definitions.get(node.arg) is None: if call_source == "functiondef": if node.arg not in self.updated_arrays: state.last_definitions[node.arg] = -1 else: state.last_definitions[node.arg] = self.updated_arrays[ node.arg ] else: assert False, ( "Call source is not ast.FunctionDef. " "Handle this by setting state.last_definitions[" "node.arg] = 0 in place of the assert False. " "But this case should not occur in general." ) else: assert False, ( "The argument variable was already defined " "resulting in state.last_definitions containing an " "entry to this argument. Resolve this by setting " "state.last_definitions[node.arg] += 1. But this " "case should not occur in general." ) return node.arg def process_index(self, node, state, *_): """ This function handles the Index node of the ast. The Index node is a `slice` value which appears when a `[]` indexing occurs. For example: x[Real], a[0], etc. So, the `value` of the index can either be an ast.Name (x[Real]) or an ast.Num (a[0]), or any other ast type. So, we forward the `value` to its respective ast handler. """ self.gen_grfn(node.value, state, "index") def process_constant(self, node, *_): data_type = self.annotate_map.get(type(node.value).__name__) if data_type: # TODO Change this format. Since the spec has changed, # this format is no longer required. Go for a simpler format. return [{"type": "literal", "dtype": data_type, "value": node.value}] else: assert False, f"Unidentified data type of variable: {node.value}" def process_num(self, node, *_): """ This function handles the ast.Num of the ast tree. This node only contains a numeric value in its body. For example: Num(n=0), Num(n=17.27), etc. So, we return the numeric value in a <function_assign_body_literal_spec> form. """ data_type = self.annotate_map.get(type(node.n).__name__) if data_type: # TODO Change this format. Since the spec has changed, # this format is no longer required. Go for a simpler format. return [{"type": "literal", "dtype": data_type, "value": node.n}] else: assert False, f"Unidentified data type of variable: {node.n}" def process_list_ast(self, node, state, *_): """ This function handles ast.List which represents Python lists. The ast.List has an `elts` element which is a list of all the elements of the list. This is most notably encountered in annotated assignment of variables to [None] (Example: day: List[int] = [ None]). This is handled by calling `gen_grfn` on every element of the list i.e. every element of `elts`. """ # Currently, this function is encountered only for annotated # assignments of the form, a: List[float] = [None], b: List[float] = # [100], c: List[float] = [(x[0]*y[0])], etc. If any further cases # arise, the following code might need to be rewritten and the # following return code will have to be added as well. # return elements if len(elements) == 1 else [{"list": elements}] element_grfn = [] for list_element in node.elts: element_grfn.append(self.gen_grfn(list_element, state, "List")) return element_grfn @staticmethod def process_str(node, *_): """ This function handles the ast.Str of the ast tree. This node only contains a string value in its body. For example: Str(s='lorem'), Str(s='Estimate: '), etc. So, we return the string value in a <function_assign_body_literal_spec> form where the dtype is a string. """ # TODO: According to new specification, the following structure # should be used: {"type": "literal, "value": {"dtype": <type>, # "value": <value>}}. Confirm with Clay. return [{"type": "literal", "dtype": "string", "value": node.s}] def process_for(self, node, state, *_): """ This function handles the ast.For node of the AST. """ # Update the scope scope_path = state.scope_path.copy() if len(scope_path) == 0: scope_path.append("@global") scope_path.append("loop") # Check: Currently For-Else on Python is not supported if self.gen_grfn(node.orelse, state, "for"): raise For2PyError("For/Else in for not supported.") # Initialize intermediate variables container_argument = [] container_return_value = [] container_updated = [] function_output = [] function_updated = [] function_input = [] loop_condition_inputs = [] loop_condition_inputs_lambda = [] loop_variables_grfn = [] loop_functions_grfn = [] # Increment the loop index universally across the program if self.loop_index > -1: self.loop_index += 1 else: self.loop_index = 0 # First, get the `container_id_name` of the loop container container_id_name = self.generate_container_id_name( self.fortran_file, self.current_scope, f"loop${self.loop_index}" ) # Update the scope of the loop container so that everything inside # the body of the loop will have the below scope self.current_scope = f"{self.current_scope}.loop${self.loop_index}" index_variable = self.gen_grfn(node.target, state, "for") # Check: Currently, only one variable is supported as a loop variable if len(index_variable) != 1 or "var" not in index_variable[0]: raise For2PyError("Only one index variable is supported.") index_name = index_variable[0]["var"]["variable"] # Define a new empty state that will be used for mapping the state of # the operations within the for-loop container loop_last_definition = {} loop_state = state.copy( last_definitions=loop_last_definition, next_definitions={}, last_definition_default=-1, ) # We want the loop_state to have state information about variables # defined one scope above its current parent scope. The below code # allows us to do that if self.parent_loop_state: for var in self.parent_loop_state.last_definitions: if var not in state.last_definitions: # state.last_definitions[var] = \ # self.parent_loop_state.last_definitions[var] state.last_definitions[var] = -1 loop_iterator = self.gen_grfn(node.iter, state, "for") # Check: Only the `range` function is supported as a loop iterator at # this moment if ( len(loop_iterator) != 1 or "call" not in loop_iterator[0] or loop_iterator[0]["call"]["function"] != "range" ): raise For2PyError("Can only iterate over a range.") range_call = loop_iterator[0]["call"] loop_condition_inputs.append(f"@variable::{index_name}::0") loop_condition_inputs_lambda.append(index_name) for ip in range_call["inputs"]: for var in ip: if "var" in var: function_input.append( f"@variable::" f"{var["var"]["variable"]}::" f"{var["var"]["index"]}" ) container_argument.append( f"@variable::" f"{var["var"]["variable"]}::-1" ) loop_condition_inputs.append( f"@variable::" f"{var["var"]["variable"]}::-1" ) loop_condition_inputs_lambda.append(var["var"]["variable"]) elif "call" in var: # TODO: Very specifically for arrays. Will probably break # for other calls self._get_call_inputs( var["call"], function_input, container_argument, loop_condition_inputs, loop_condition_inputs_lambda, state, ) function_input = self._remove_duplicate_from_list(function_input) container_argument = self._remove_duplicate_from_list( container_argument ) loop_condition_inputs = self._remove_duplicate_from_list( loop_condition_inputs ) loop_condition_inputs_lambda = self._remove_duplicate_from_list( loop_condition_inputs_lambda ) # Save the current state of the system so that it can used by a # nested loop to get information about the variables declared in its # outermost scopes. self.parent_loop_state = state # Define some condition and break variables in the loop state loop_state.last_definitions[index_name] = 0 loop_state.last_definitions["IF_0"] = 0 loop_state.last_definitions["EXIT"] = 0 loop_state.variable_types["IF_0"] = "bool" loop_state.variable_types["EXIT"] = "bool" # Now, create the `variable` spec, `function name` and `container # wiring` for the loop index, check condition and break decisions. index_variable_grfn = self.generate_variable_definition( [index_name], None, False, loop_state ) index_function_name = self.generate_function_name( "__assign__", index_variable_grfn["name"], None ) index_function = { "function": index_function_name, "input": [], "output": [f"@variable::{index_name}::0"], "updated": [], } loop_check_variable = self.generate_variable_definition( ["IF_0"], None, False, loop_state ) loop_state.next_definitions["#cond"] = 1 loop_state.last_definitions["#cond"] = 0 loop_check_function_name = self.generate_function_name( "__condition__", loop_check_variable["name"], None ) loop_condition_function = { "function": loop_check_function_name, "input": loop_condition_inputs, "output": [f"@variable::IF_0::0"], "updated": [], } # Create the lambda function for the index variable initiations and # other loop checks. This has to be done through a custom lambda # function operation since the structure of genCode does not conform # with the way this lambda function will be created. # TODO Add code to support a step other than +1 as well assert len(range_call["inputs"]) <= 3, ( f"Only two or three elements in range function supported as of " f"now - {range_call}" ) loop_start = range_call["inputs"][0] loop_end = range_call["inputs"][1] # TODO: need to decide what we'll do with step. if len(range_call["inputs"]) == 3: loop_step = range_call["inputs"][2] # TODO Add a separate function to get the variables/literals of a # more complex form. The one below is for the basic case. if "var" in loop_start[0]: loop_start_name = loop_start[0]["var"]["variable"] elif "type" in loop_start[0] and loop_start[0]["type"] == "literal": loop_start_name = loop_start[0]["value"] else: assert False, "Error in getting loop start name" if "var" in loop_end[0]: # If the loop end is tested against a variable, such as: # for p_idx[0] in range(1, n_p[0]+1): # the loop_end_name should be the variable_name plus 1 loop_end_name = f"{loop_end[0]["var"]["variable"]}+1" elif "type" in loop_end[0] and loop_end[0]["type"] == "literal": loop_end_name = loop_end[0]["value"] else: assert False, "Error in getting loop end name" # First, lambda function for loop index initiation index_initiation_lambda = self.generate_lambda_function( loop_start_name, index_function_name["name"], True, False, False, False, [], [], state, True, ) index_function["function"]["code"] = index_initiation_lambda # Second, lambda function for IF_0_0 test loop_test_string = f"0 <= {index_name} < {loop_end_name}" loop_continuation_test_lambda = self.generate_lambda_function( loop_test_string, loop_check_function_name["name"], True, False, False, False, loop_condition_inputs_lambda, [], state, True, ) loop_condition_function["function"][ "code" ] = loop_continuation_test_lambda # Parse through the body of the loop container loop = self.gen_grfn(node.body, loop_state, "for") # Separate the body grfn into `variables` and `functions` sub parts ( body_variables_grfn, body_functions_grfn, body_container_grfn, ) = self._get_variables_and_functions(loop) # Get a list of all variables that were used as inputs within the # loop body (nested as well). loop_body_inputs = [] # Get only the dictionaries body_functions_grfn = [ item for item in body_functions_grfn if isinstance(item, dict) ] for function in body_functions_grfn: if function["function"]["type"] == "lambda": for ip in function["input"]: (_, input_var, input_index) = ip.split("::") if ( _ == "@variable" and int(input_index) == -1 and input_var not in loop_body_inputs ): loop_body_inputs.append(input_var) elif function["function"]["type"] == "container": # The same code as above but separating it out just in case # some extra checks are added in the future for ip in function["input"]: (_, input_var, input_index) = ip.split("::") if _ == "@variable" and int(input_index) == -1: loop_body_inputs.append(input_var) # Remove any duplicates since variables can be used multiple times in # various assignments within the body loop_body_inputs = self._remove_duplicate_from_list(loop_body_inputs) # If the index name is a part of the loop body, remove it since it is # not an input to the container if index_name in loop_body_inputs: loop_body_inputs.remove(index_name) # TODO: Not doing this right now. Refine this code and do it then. """ # Now, we remove the variables which were defined inside the loop # body itself and not taken as an input from outside the loop body filtered_loop_body_inputs = [] for input_var in loop_body_inputs: # We filter out those variables which have -1 index in `state` ( # which means it did not have a defined value above the loop # body) and is not a function argument (since they have an index # of -1 as well but have a defined value) if not (state.last_definitions[input_var] == -1 and input_var not in self.function_argument_map[main_function_name][ "argument_list"] ): filtered_loop_body_inputs.append(input_var) """ for item in loop_body_inputs: # TODO Hack for now, this should be filtered off from the code # block above if ( "IF" not in item and state.last_definitions.get(item) is not None ): function_input.append( f"@variable::{item}::" f"{state.last_definitions[item]}" ) container_argument.append(f"@variable::{item}::-1") function_input = self._remove_duplicate_from_list(function_input) container_argument = self._remove_duplicate_from_list( container_argument ) # Creating variable specs for the inputs to the containers. start_definitions = loop_state.last_definitions.copy() container_definitions = start_definitions.copy() container_input_state = loop_state.copy( last_definitions=container_definitions ) for argument in container_argument: (_, var, index) = argument.split("::") container_input_state.last_definitions[var] = int(index) argument_variable = self.generate_variable_definition( [var], None, False, container_input_state ) body_variables_grfn.append(argument_variable) # TODO: Think about removing (or retaining) variables which even # though defined outside the loop, are defined again inside the loop # and then used by an operation after it. # E.g. x = 5 # for ___ : # x = 2 # for ___: # y = x + 2 # Here, loop$1 will have `x` as an input but will loop$0 have `x` as # an input as well? # Currently, such variables are included in the `input`/`argument` # field. # Now, we list out all variables that have been updated/defined # inside the body of the loop loop_body_outputs = {} for function in body_functions_grfn: if function["function"]["type"] == "lambda": # TODO Currently, we only deal with a single output variable. # Modify the line above to not look at only [0] but loop # through the output to incorporate multiple outputs (_, output_var, output_index) = function["output"][0].split( "::" ) loop_body_outputs[output_var] = output_index elif function["function"]["type"] == "container": for ip in function["updated"]: if isinstance(ip, dict): for x in ip["updates"]: (_, output_var, output_index) = x.split("::") loop_body_outputs[output_var] = output_index else: (_, output_var, output_index) = ip.split("::") loop_body_outputs[output_var] = output_index for item in loop_body_outputs: # TODO the indexing variables in of function block and container # block will be different. Figure about the differences and # implement them. # TODO: Hack, this IF check should not even appear in # loop_body_outputs if ( "IF" not in item and "EXIT" not in item and state.last_definitions.get(item) is not None ): if state.last_definitions[item] == -2: updated_index = 0 else: updated_index = state.last_definitions[item] + 1 function_updated.append( f"@variable::{item}::" f"{updated_index}" ) state.last_definitions[item] = updated_index state.next_definitions[item] = updated_index + 1 item_id = loop_state.last_definitions.get( item, loop_body_outputs[item] ) container_updated.append(f"@variable::{item}::" f"{item_id}") # Create variable spec for updated variables in parent scope. # So, temporarily change the current scope to its previous form tmp_scope = self.current_scope self.current_scope = ".".join( self.current_scope.split(".")[:-1] ) updated_variable = self.generate_variable_definition( [item], None, False, state ) body_variables_grfn.append(updated_variable) # Changing it back to its current form self.current_scope = tmp_scope loop_break_variable = self.generate_variable_definition( ["EXIT"], None, False, loop_state ) loop_state.next_definitions["EXIT"] = 1 loop_break_function_name = self.generate_function_name( "__decision__", loop_break_variable["name"], None ) exit_inputs = ["@variable::IF_0::0"] exit_inputs.extend( [ f"@variable::{list(x.keys())[0]}::0" for x in self.exit_candidates ] ) lambda_inputs = [ f"{x.split("::")[1]}_{x.split("::")[2]}" for x in exit_inputs ] loop_break_function = { "function": loop_break_function_name, "input": exit_inputs, "output": [f"@variable::EXIT::0"], "updated": [], } loop_exit_test_lambda = self.generate_lambda_function( ["EXIT"], loop_break_function_name["name"], True, False, False, False, lambda_inputs, [], state, True, ) loop_break_function["function"]["code"] = loop_exit_test_lambda # TODO: For the `loop_body_outputs`, all variables that were # defined/updated inside the loop body are included. Sometimes, # some variables are defined inside the loop body, used within that # body and then not used or re-assigned to another value outside the # loop body. Do we include such variables in the updated list? # Another heuristic to think about is whether to keep only those # variables in the `updated` list which are in the `input` list. loop_variables_grfn.append(index_variable_grfn) loop_variables_grfn.append(loop_check_variable) loop_variables_grfn.append(loop_break_variable) loop_functions_grfn.append(index_function) loop_functions_grfn.append(loop_condition_function) loop_functions_grfn.append(loop_break_function) loop_functions_grfn += body_functions_grfn # Finally, add the index increment variable and function grfn to the # body grfn loop_state.last_definitions[index_name] = 1 index_increment_grfn = self.generate_variable_definition( [index_name], None, False, loop_state ) index_increment_function_name = self.generate_function_name( "__assign__", index_increment_grfn["name"], None ) index_increment_function = { "function": index_increment_function_name, "input": [f"@variable::{index_name}::0"], "output": [f"@variable::{index_name}::1"], "updated": [], } # Finally, lambda function for loop index increment index_increment_lambda = self.generate_lambda_function( f"{index_name} + 1", index_increment_function_name["name"], True, False, False, False, [index_name], [], state, True, ) index_increment_function["function"]["code"] = index_increment_lambda loop_variables_grfn.append(index_increment_grfn) loop_functions_grfn.append(index_increment_function) container_gensym = self.generate_gensym("container") loop_container = { "name": container_id_name, "source_refs": [], "gensym": container_gensym, "type": "loop", "arguments": container_argument, "updated": container_updated, "return_value": container_return_value, "body": loop_functions_grfn, } loop_function = { "function": {"name": container_id_name, "type": "container"}, "input": function_input, "output": function_output, "updated": function_updated, } loop_container = [loop_container] + body_container_grfn loop_variables = body_variables_grfn + loop_variables_grfn grfn = { "containers": loop_container, "variables": loop_variables, "functions": [loop_function], } # Change the current scope back to its previous form. self.current_scope = ".".join(self.current_scope.split(".")[:-1]) return [grfn] def process_while(self, node, state, *_): """ This function handles the while loop. The functionality will be very similar to that of the for loop described in `process_for` """ # Update the scope scope_path = state.scope_path.copy() if len(scope_path) == 0: scope_path.append("@global") scope_path.append("loop") # Initialize intermediate variables container_argument = [] container_return_value = [] container_updated = [] function_output = [] function_updated = [] function_input = [] loop_condition_inputs = [] loop_condition_inputs_lambda = [] loop_variables_grfn = [] loop_functions_grfn = [] # Increment the loop index universally across the program if self.loop_index > -1: self.loop_index += 1 else: self.loop_index = 0 # First, get the `container_id_name` of the loop container container_id_name = self.generate_container_id_name( self.fortran_file, self.current_scope, f"loop${self.loop_index}" ) # Update the scope of the loop container so that everything inside # the body of the loop will have the below scope self.current_scope = f"{self.current_scope}.loop${self.loop_index}" loop_test = self.gen_grfn(node.test, state, "while") # Define a new empty state that will be used for mapping the state of # the operations within the loop container loop_last_definition = {} loop_state = state.copy( last_definitions=loop_last_definition, next_definitions={}, last_definition_default=-1, ) # We want the loop_state to have state information about variables # defined one scope above its current parent scope. The below code # allows us to do that if self.parent_loop_state: for var in self.parent_loop_state.last_definitions: if var not in state.last_definitions: # state.last_definitions[var] = \ # self.parent_loop_state.last_definitions[var] state.last_definitions[var] = -1 # Now populate the IF and EXIT functions for the loop by identifying # the loop conditionals # TODO Add a test to check for loop validity in this area. Need to # test with more types of while loops to finalize on a test condition for item in loop_test: if not isinstance(item, list): item = [item] for var in item: if "var" in var: function_input.append( f"@variable::" f"{var["var"]["variable"]}::" f"{var["var"]["index"]}" ) container_argument.append( f"@variable::" f"{var["var"]["variable"]}::-1" ) loop_condition_inputs.append( f"@variable::" f"{var["var"]["variable"]}::-1" ) loop_condition_inputs_lambda.append(var["var"]["variable"]) elif "call" in var: # TODO: Very specifically for arrays. Will probably break # for other calls self._get_call_inputs( var["call"], function_input, container_argument, loop_condition_inputs, loop_condition_inputs_lambda, state, ) function_input = self._remove_duplicate_from_list(function_input) container_argument = self._remove_duplicate_from_list( container_argument ) loop_condition_inputs = self._remove_duplicate_from_list( loop_condition_inputs ) loop_condition_inputs_lambda = self._remove_duplicate_from_list( loop_condition_inputs_lambda ) # Save the current state of the system so that it can used by a # nested loop to get information about the variables declared in its # outermost scopes. self.parent_loop_state = state # Define some condition and break variables in the loop state loop_state.last_definitions["IF_0"] = 0 loop_state.last_definitions["EXIT"] = 0 loop_state.variable_types["IF_0"] = "bool" loop_state.variable_types["EXIT"] = "bool" # Now, create the `variable` spec, `function name` and `container # wiring` for the check condition and break decisions. loop_check_variable = self.generate_variable_definition( ["IF_0"], None, False, loop_state ) loop_state.next_definitions["#cond"] = 1 loop_state.last_definitions["#cond"] = 0 loop_check_function_name = self.generate_function_name( "__condition__", loop_check_variable["name"], None ) loop_condition_function = { "function": loop_check_function_name, "input": loop_condition_inputs, "output": [f"@variable::IF_0::0"], "updated": [], } # Create the lambda function for the index variable initiations and # other loop checks. This has to be done through a custom lambda # function operation since the structure of genCode does not conform # with the way this lambda function will be created. # TODO Add a separate function to get the variables/literals of a # more complex form. The one below is for the basic case. # Second, lambda function for IF_0_0 test loop_continuation_test_lambda = self.generate_lambda_function( node.test, loop_check_function_name["name"], True, False, False, False, loop_condition_inputs_lambda, [], state, True, ) loop_condition_function["function"][ "code" ] = loop_continuation_test_lambda # Parse through the body of the loop container loop = self.gen_grfn(node.body, loop_state, "for") # Separate the body grfn into `variables` and `functions` sub parts ( body_variables_grfn, body_functions_grfn, body_container_grfn, ) = self._get_variables_and_functions(loop) # Get a list of all variables that were used as inputs within the # loop body (nested as well). loop_body_inputs = [] # Get only the dictionaries body_functions_grfn = [ item for item in body_functions_grfn if isinstance(item, dict) ] for function in body_functions_grfn: if function["function"]["type"] == "lambda": for ip in function["input"]: (_, input_var, input_index) = ip.split("::") if ( int(input_index) == -1 and input_var not in loop_body_inputs ): loop_body_inputs.append(input_var) elif function["function"]["type"] == "container": # The same code as above but separating it out just in case # some extra checks are added in the future for ip in function["input"]: (_, input_var, input_index) = ip.split("::") # TODO Hack for bypassing `boolean` types. Will be # removed once the `literal` as an input question is # answered. if int(input_index) == -1 and input_var != "boolean": loop_body_inputs.append(input_var) # Remove any duplicates since variables can be used multiple times in # various assignments within the body loop_body_inputs = self._remove_duplicate_from_list(loop_body_inputs) # TODO: Not doing this right now. Refine this code and do it then. """ # Now, we remove the variables which were defined inside the loop # body itself and not taken as an input from outside the loop body filtered_loop_body_inputs = [] for input_var in loop_body_inputs: # We filter out those variables which have -1 index in `state` ( # which means it did not have a defined value above the loop # body) and is not a function argument (since they have an index # of -1 as well but have a defined value) if not (state.last_definitions[input_var] == -1 and input_var not in self.function_argument_map[main_function_name][ "argument_list"] ): filtered_loop_body_inputs.append(input_var) """ # for item in filtered_loop_body_inputs: for item in loop_body_inputs: # TODO Hack for now, this should be filtered off from the code # block above if ( "IF" not in item and state.last_definitions.get(item) is not None ): function_input.append( f"@variable::{item}::" f"{state.last_definitions[item]}" ) container_argument.append(f"@variable::{item}::-1") function_input = self._remove_duplicate_from_list(function_input) container_argument = self._remove_duplicate_from_list( container_argument ) # Creating variable specs for the inputs to the containers. start_definitions = loop_state.last_definitions.copy() container_definitions = start_definitions.copy() container_input_state = loop_state.copy( last_definitions=container_definitions ) for argument in container_argument: (_, var, index) = argument.split("::") container_input_state.last_definitions[var] = int(index) argument_variable = self.generate_variable_definition( [var], None, False, container_input_state ) body_variables_grfn.append(argument_variable) # TODO: Think about removing (or retaining) variables which even # though defined outside the loop, are defined again inside the loop # and then used by an operation after it. # E.g. x = 5 # for ___ : # x = 2 # for ___: # y = x + 2 # Here, loop$1 will have `x` as an input but will loop$0 have `x` as # an input as well? # Currently, such variables are included in the `input`/`argument` # field. # Now, we list out all variables that have been updated/defined # inside the body of the loop loop_body_outputs = {} for function in body_functions_grfn: if function["function"]["type"] == "lambda": # TODO Currently, we only deal with a single output variable. # Modify the line above to not look at only [0] but loop # through the output to incorporate multiple outputs (_, output_var, output_index) = function["output"][0].split( "::" ) loop_body_outputs[output_var] = output_index elif function["function"]["type"] == "container": for ip in function["updated"]: if isinstance(ip, dict): for x in ip["updates"]: (_, output_var, output_index) = x.split("::") loop_body_outputs[output_var] = output_index else: (_, output_var, output_index) = ip.split("::") loop_body_outputs[output_var] = output_index for item in loop_body_outputs: # TODO the indexing variables in of function block and container # block will be different. Figure about the differences and # implement them. # TODO: Hack, this IF check should not even appear in # loop_body_outputs if ( "IF" not in item and "EXIT" not in item and state.last_definitions.get(item) is not None ): if (state.last_definitions[item] == -2) or (item == "EXIT"): updated_index = 0 else: updated_index = state.last_definitions[item] + 1 function_updated.append( f"@variable::{item}::" f"{updated_index}" ) state.last_definitions[item] = updated_index state.next_definitions[item] = updated_index + 1 item_id = loop_state.last_definitions.get( item, loop_body_outputs[item] ) container_updated.append(f"@variable::{item}::" f"{item_id}") # Create variable spec for updated variables in parent scope. # So, temporarily change the current scope to its previous form tmp_scope = self.current_scope self.current_scope = ".".join( self.current_scope.split(".")[:-1] ) updated_variable = self.generate_variable_definition( [item], None, False, state ) body_variables_grfn.append(updated_variable) # Changing it back to its current form self.current_scope = tmp_scope loop_break_variable = self.generate_variable_definition( ["EXIT"], None, False, loop_state ) loop_state.next_definitions["EXIT"] = 1 loop_break_function_name = self.generate_function_name( "__decision__", loop_break_variable["name"], None ) exit_inputs = ["@variable::IF_0::0"] exit_inputs.extend( [ f"@variable::{list(x.keys())[0]}::0" for x in self.exit_candidates ] ) lambda_inputs = [ f"{x.split("::")[1]}_{x.split("::")[2]}" for x in exit_inputs ] loop_break_function = { "function": loop_break_function_name, "input": exit_inputs, "output": [f"@variable::EXIT::0"], "updated": [], } loop_exit_test_lambda = self.generate_lambda_function( ["EXIT"], loop_break_function_name["name"], True, False, False, False, lambda_inputs, [], state, True, ) loop_break_function["function"]["code"] = loop_exit_test_lambda # TODO: For the `loop_body_outputs`, all variables that were # defined/updated inside the loop body are included. Sometimes, # some variables are defined inside the loop body, used within that # body and then not used or re-assigned to another value outside the # loop body. Do we include such variables in the updated list? # Another heuristic to think about is whether to keep only those # variables in the `updated` list which are in the `input` list. loop_variables_grfn.append(loop_check_variable) loop_variables_grfn.append(loop_break_variable) loop_functions_grfn.append(loop_condition_function) loop_functions_grfn.append(loop_break_function) loop_functions_grfn += body_functions_grfn container_gensym = self.generate_gensym("container") loop_container = { "name": container_id_name, "source_refs": [], "gensym": container_gensym, "type": "loop", "arguments": container_argument, "updated": container_updated, "return_value": container_return_value, "body": loop_functions_grfn, } loop_function = { "function": {"name": container_id_name, "type": "container"}, "input": function_input, "output": function_output, "updated": function_updated, } loop_container = [loop_container] + body_container_grfn loop_variables = body_variables_grfn + loop_variables_grfn grfn = { "containers": loop_container, "variables": loop_variables, "functions": [loop_function], } self.current_scope = ".".join(self.current_scope.split(".")[:-1]) return [grfn] def process_if(self, node, state, call_source): """ This function handles the ast.IF node of the AST. It goes through the IF body and generates the `decision` and `condition` type of the `<function_assign_def>`. """ # Update the scope path scope_path = state.scope_path.copy() if len(scope_path) == 0: scope_path.append("@global") state.scope_path = scope_path # First, check whether this is the start of an `if-block` or an # `elif` block # if call_source == "if": if self.elseif_flag: is_else_if = True self.elseif_flag = False if_index = self.elif_index else: is_else_if = False # Increment the loop index universally across the program if self.if_index > -1: self.if_index += 1 if_index = self.if_index else: self.if_index = 0 if_index = self.if_index # Define a new empty state that will be used for mapping the # state of the operations within the for-loop container loop_last_definition = {} if_state = state.copy( last_definitions=loop_last_definition, next_definitions={}, last_definition_default=-1, ) # First, get the `container_id_name` of the if container container_id_name = self.generate_container_id_name( self.fortran_file, self.current_scope, f"IF_{if_index}" ) # Update the scope to include the new `if-block` self.current_scope = f"{self.current_scope}.IF_{if_index}" # We want the if_state to have state information about variables # defined one scope above its current parent scope. The below code # allows us to do that # TODO: How relevant is this for `if-blocks`? Will need to verify if self.parent_if_state: for var in self.parent_if_state.last_definitions: if var not in state.last_definitions: state.last_definitions[var] = -1 grfn = {"functions": [], "variables": [], "containers": []} # Get the GrFN schema of the test condition of the `IF` command # Notice that we'll have two different states depending on whether # this is the main `if-block` or the `elif` block if is_else_if: condition_sources = self.gen_grfn(node.test, state, "if") condition_variables = self.get_variables(condition_sources, state) else: condition_sources = self.gen_grfn(node.test, if_state, "if") condition_variables = self.get_variables( condition_sources, if_state ) # When opening files, if a check for a pre-existing file has to be # done, this if-block is bypassed if isinstance(condition_sources[0], dict) and condition_sources[0].get( "call" ): if ( condition_sources[0]["call"].get("function") and condition_sources[0]["call"]["function"] == "path.exists" ): return [] # The index of the IF_x_x variable will start from 0 if state.last_definition_default in (-1, 0, -2): # default_if_index = state.last_definition_default + 1 default_if_index = 0 else: assert False, ( f"Invalid value of last_definition_default:" f"{state.last_definition_default}" ) # For every new `if-block`, the IF_X value will increase by one. # For every condition check within an `if-block` (i.e. if .. elif .. # elif .. else ..), the COND_X index will start from 0 for the `if` # check and increment by 1 for every `elif` check if not is_else_if: condition_number = 0 if_state.last_definitions["#cond"] = condition_number if_state.next_definitions["#cond"] = condition_number + 1 condition_name = f"COND_{if_index}_{condition_number}" condition_index = self.get_last_definition( condition_name, if_state.last_definitions, 0 ) if_state.variable_types[condition_name] = "bool" if_state.last_definitions[condition_name] = condition_index variable_spec = self.generate_variable_definition( [condition_name], None, False, if_state ) else: condition_number = self._get_next_definition( "#cond", state.last_definitions, state.next_definitions, default_if_index - 1, ) condition_name = f"COND_{if_index}_{condition_number}" condition_index = self.get_last_definition( condition_name, state.last_definitions, 0 ) state.variable_types[condition_name] = "bool" state.last_definitions[condition_name] = condition_index variable_spec = self.generate_variable_definition( [condition_name], None, False, state ) function_name = self.generate_function_name( "__condition__", variable_spec["name"], None ) # Getting the output variable output_regex = re.compile(r".*::(?P<output>.*?)::(?P<index>.*$)") output_match = output_regex.match(variable_spec["name"]) if output_match: output = output_match.group("output") index = output_match.group("index") output_variable = f"@variable::{output}::{index}" else: assert False, ( f"Could not match output variable for " f"{variable_spec["name"]}" ) # Create the function statement for the COND_X variables fn = { "function": function_name, "input": [ f"@variable::{src["var"]["variable"]}::{src["var"]["index"]}" for src in condition_variables if "var" in src ], "output": [output_variable], "updated": [], } # Save the current state of the system so that it can used by a # nested loop to get information about the variables declared in its # outermost scopes. self.parent_if_state = state # Update the variable definition with the COND_X variable spec grfn["variables"].append(variable_spec) # Generate the lambda function code of the COND_X check lambda_string = self.generate_lambda_function( node.test, function_name["name"], False, False, False, False, [ src["var"]["variable"] for src in condition_variables if "var" in src ], [], state, False, ) fn["function"]["code"] = lambda_string else_node_name = node.orelse.__repr__().split()[0][3:] if is_else_if: if_grfn = self.gen_grfn(node.body, state, "if") if else_node_name == "ast.If": self.elseif_flag = True self.elif_index = if_index else_grfn = self.gen_grfn(node.orelse, state, "if") else: if_grfn = self.gen_grfn(node.body, if_state, "if") if else_node_name == "ast.If": self.elseif_flag = True self.elif_index = if_index else_grfn = self.gen_grfn(node.orelse, if_state, "if") # Sometimes, some if-else body blocks only contain I/O operations, # the GrFN for which will be empty. Check for these and handle # accordingly if ( len(else_grfn) > 0 and len(else_grfn[0]["functions"]) == 0 and len(else_grfn[0]["variables"]) == 0 and len(else_grfn[0]["containers"]) == 0 ): else_grfn = [] # If this is an `elif` block, append the if-body GrFN and else-body # GrFN to the functions with their respective structure and simply # return if is_else_if: grfn["functions"] = [{"condition": [fn], "statements": []}] for spec in if_grfn: grfn["functions"][0]["statements"] += spec["functions"] grfn["variables"] += spec["variables"] grfn["containers"] += spec["containers"] grfn["functions"].append({"condition": None, "statements": []}) for spec in else_grfn: # Check for cases like more than one `elif` where the overall # structure has to stay consistent if "condition" in spec["functions"][0]: grfn["functions"].pop() grfn["functions"] += spec["functions"] else: grfn["functions"][1]["statements"] += spec["functions"] grfn["variables"] += spec["variables"] grfn["containers"] += spec["containers"] return [grfn] # All of the operations from this point is only for the main # `if-block` if statement for spec in if_grfn: grfn["variables"] += spec["variables"] grfn["containers"] += spec["containers"] for spec in else_grfn: grfn["variables"] += spec["variables"] grfn["containers"] += spec["containers"] container_argument = [] function_input = [] if_body_inputs = [] if_body_outputs = {} container_updated = [] container_decisions = [] function_updated = [] container_body = [{"condition": [fn], "statements": []}] for spec in if_grfn: if len(spec["functions"]) > 0: container_body[0]["statements"] += spec["functions"] container_body.append({"condition": None, "statements": []}) for spec in else_grfn: if len(spec["functions"]) > 0: if "condition" in spec["functions"][0]: container_body.pop() container_body += spec["functions"] else: container_body[1]["statements"] += spec["functions"] # If there is no else statement, remove it from the block if ( container_body[-1]["condition"] is None and len(container_body[-1]["statements"]) == 0 ): container_body.pop() current_condition = None for body_dict in container_body: for key in body_dict: if key == "statements": self._fix_input_index(body_dict[key]) if body_dict[key]: for function in body_dict[key]: if key == "condition": current_condition = function["output"][0].split( "::" )[1] if_body_outputs[current_condition] = dict() if function["function"]["type"] == "lambda": for ip in function["input"]: (_, input_var, input_index) = ip.split("::") if ( "@literal" not in ip and int(input_index) == -1 and input_var not in if_body_inputs ): if_body_inputs.append(input_var) (_, output_var, output_index) = function["output"][ 0 ].split("::") if_body_outputs[current_condition][ output_var ] = output_index elif function["function"]["type"] == "container": # The same code as above but separating it out just # in case some extra checks are added in the future for ip in function["input"]: (_, input_var, input_index) = ip.split("::") if int(input_index) == -1: if_body_inputs.append(input_var) for ip in function["updated"]: if isinstance(ip, dict): for x in ip["updates"]: ( _, output_var, output_index, ) = x.split("::") if_body_outputs[current_condition][ output_var ] = output_index else: (_, output_var, output_index) = ip.split( "::" ) if_body_outputs[current_condition][ output_var ] = output_index else: current_condition = None if_body_outputs[current_condition] = dict() # Remove any duplicates since variables can be used multiple times in # various assignments within the body if_body_inputs = self._remove_duplicate_from_list(if_body_inputs) for item in if_body_inputs: if ( "COND" not in item and state.last_definitions.get(item) is not None ): function_input.append( f"@variable::{item}::{state.last_definitions[item]}" ) container_argument.append(f"@variable::{item}::-1") function_input = self._remove_duplicate_from_list(function_input) container_argument = self._remove_duplicate_from_list( container_argument ) # Creating variable specs for the inputs to the containers. start_definitions = if_state.last_definitions.copy() container_definitions = start_definitions.copy() container_input_state = if_state.copy( last_definitions=container_definitions ) for argument in container_argument: (_, var, index) = argument.split("::") container_input_state.last_definitions[var] = int(index) argument_variable = self.generate_variable_definition( [var], None, False, container_input_state ) grfn["variables"].append(argument_variable) updated_vars = [ list(if_body_outputs[x].keys()) for x in if_body_outputs ] updated_vars = list(set([i for x in updated_vars for i in x])) # Start of code that produces the __decisions__ statements # Get the updated variables in a format that is easier for the rest # of this code to work on # Structure: # {'z': [{'COND_0_1': 0, 'COND_0_2': 1, None: 3}, [1, 2, -1]]} decision_inputs = self._get_decision_inputs( if_body_outputs, updated_vars ) # Get the maximum number of condition statements inside this `IF` # container condition_count = if_state.last_definitions.get("#cond", 0) # For every updated variables, we'll make a decision statement and a # lambda function for updated, versions in decision_inputs.items(): condition_indexes = versions[-1] condition_map = versions[0] inputs = [] # If the variable is updated in the `else` clause (i.e. -1), # all condition booleans will be an input to it if -1 in condition_indexes: for i in range(condition_count + 1): inputs.append( {"variable": f"COND_{if_index}_{i}", "index": 0} ) else: # In this case, all condition booleans up to the maximum # condition will be an input for i in range(max(condition_indexes) + 1): inputs.append( {"variable": f"COND_{if_index}_{i}", "index": 0} ) # Now add the updated variables with their respective indexes for cond, index in condition_map.items(): inputs.append({"variable": updated, "index": index}) # If some variables don't end up always getting updated during the # if-else checks, then their -1 indexed versions should be added to # the input list. For example # if cond_0: x = 3 # else: y = 4 # Here, x won't get updated if cond_0 is unmet and vice versa for y # But in cases like: # if cond_0: x = 3 # else: x = 4 # x is always updated so it's -1 index will be not added as an input if len(condition_map) <= condition_count + 1: if state.last_definitions.get(updated) is not None: ip = f"@variable::{updated}::{state.last_definitions[updated]}" if ip not in function_input: function_input.append(ip) ip = f"@variable::{updated}::-1" if ip not in container_argument: container_argument.append(ip) # Also, add the -1 index for the variable which is the # default case when no conditions will be met inputs.append({"variable": updated, "index": -1}) # The output variable is the updated variable with its index as # index = latest_index+1 output = { "variable": updated, "index": self._get_next_definition( updated, if_state.last_definitions, if_state.next_definitions, if_state.last_definition_default, ), } # Create a variable list and add it to the variable tag variable_spec = self.generate_variable_definition( [updated], None, False, if_state ) grfn["variables"].append(variable_spec) # Create a __decision__ function and add it to the `decisions` # tag of the container function_name = self.generate_function_name( "__decision__", variable_spec["name"], None ) fn = { "function": function_name, "input": [ f"@variable::{var["variable"]}::{var["index"]}" for var in inputs ], "output": [ f"@variable::{output["variable"]}:" f":{output["index"]}" ], "updated": [], } container_decisions.append(fn) # We sort the condition booleans dictionary in such a way that # the first conditions appear at the beginning # Structure: {'COND_0_1': 0, 'COND_0_2': 1, None: 3} changes to # ('COND_0_1', 0), ('COND_0_2', 1), (None, 3) versions[0] = sorted(versions[0].items(), key=lambda item: item[1]) # The inputs to the lambda function will not have the -1 index # for the variable as `var_-1` is an invalid variable name. So, # `-1` is replaces by `xx`. Default variables will be represented # as `var_xx` lambda_inputs = [] for src in inputs: if src["index"] == -1: lambda_inputs.append(f"{src["variable"]}_xx") else: lambda_inputs.append(f"{src["variable"]}_{src["index"]}") # Generate the lambda function string lambda_string = self.generate_lambda_function( node, function_name["name"], False, True, False, False, lambda_inputs, versions, if_state, False, ) fn["function"]["code"] = lambda_string for index, item in enumerate(if_body_outputs): function_updated.append({"condition": item, "updates": []}) container_updated.append({"condition": item, "updates": []}) for var in if_body_outputs[item]: if "COND" not in var: if state.last_definitions.get(var, -2) == -2: updated_index = 0 else: if var in updated_vars: updated_index = state.last_definitions[var] + 1 else: updated_index = state.last_definitions[var] function_updated[index]["updates"].append( f"@variable::{var}::" f"{updated_index}" ) if var in updated_vars: state.last_definitions[var] = updated_index state.next_definitions[var] = updated_index + 1 # Create variable spec for updated variables in parent # scope. So, temporarily change the current scope to its # previous form. tmp_scope = self.current_scope self.current_scope = ".".join( self.current_scope.split(".")[:-1] ) updated_variable = self.generate_variable_definition( [var], None, False, state ) grfn["variables"].append(updated_variable) # Changing it back to its current form self.current_scope = tmp_scope updated_vars.remove(var) item_id = if_body_outputs[item][var] container_updated[index]["updates"].append( f"@variable:" f":{var}::" f"{item_id}" ) # If there is no else statement, remove it from the block if ( container_updated[-1]["condition"] is None and len(container_updated[-1]["updates"]) == 0 ): container_updated.pop() if ( function_updated[-1]["condition"] is None and len(function_updated[-1]["updates"]) == 0 ): function_updated.pop() function_updated = [] container_updated = [] for statement in container_decisions: for output in statement["output"]: container_updated.append(output) segments = output.split("::") var = segments[1] if state.last_definitions.get(var, -2) == -2: updated_index = 0 else: updated_index = state.last_definitions[var] function_updated.append(f"@variable::{var}::{updated_index}") container_gensym = self.generate_gensym("container") if_type = "if-block" node_lineno = node.lineno for comment in self.comments: if ( self.comments[comment] == "# select-case" and node_lineno == int(comment) + 1 ): if_type = "select-block" merged_body = self._merge_container_body( container_body, container_decisions ) if_container = { "name": container_id_name, "source_refs": [], "gensym": container_gensym, "type": if_type, "arguments": container_argument, "updated": container_updated, "return_value": [], "body": merged_body, } if_function = { "function": {"name": container_id_name, "type": "container"}, "input": function_input, "updated": function_updated, "output": [], } grfn["functions"].append(if_function) grfn["containers"] = [if_container] + grfn["containers"] # Change the current scope back to its previous form. self.current_scope = ".".join(self.current_scope.split(".")[:-1]) return [grfn] def process_unary_operation(self, node, state, *_): """ This function processes unary operations in Python represented by ast.UnaryOp. This node has an `op` key which contains the operation (e.g. USub for -, UAdd for +, Not, Invert) and an `operand` key which contains the operand of the operation. This operand can in itself be any Python object (Number, Function call, Binary Operation, Unary Operation, etc. So, iteratively call the respective ast handler for the operand. """ return self.gen_grfn(node.operand, state, "unaryop") def process_binary_operation(self, node, state, *_): """ This function handles binary operations i.e. ast.BinOp """ # If both the left and right operands are numbers (ast.Num), we can # simply perform the respective operation on these two numbers and # represent this computation in a GrFN spec. if isinstance(node.left, ast.Num) and isinstance(node.right, ast.Num): for op in self.binops: if isinstance(node.op, op): val = self.binops[type(node.op)](node.left.n, node.right.n) data_type = self.annotate_map.get(type(val).__name__) if data_type: return [ { "type": "literal", "dtype": data_type, "value": val, } ] else: assert False, f"Unidentified data type of: {val}" assert False, ( "Both operands are numbers but no operator " "available to handle their computation. Either add " "a handler if possible or remove this assert and " "allow the code below to handle such cases." ) # If the operands are anything other than numbers (ast.Str, # ast.BinOp, etc), call `gen_grfn` on each side so their respective # ast handlers will process them and return a [{grfn_spec}, ..] form # for each side. Add these two sides together to give a single [{ # grfn_spec}, ...] form. operation_grfn = self.gen_grfn( node.left, state, "binop" ) + self.gen_grfn(node.right, state, "binop") return operation_grfn def process_boolean_operation(self, node, state, *_): """ This function will process the ast.BoolOp node that handles boolean operations i.e. AND, OR, etc. """ # TODO: No example of this to test on. This looks like deprecated # format. Will need to be rechecked. grfn_list = [] operation = {ast.And: "and", ast.Or: "or"} for key in operation: if isinstance(node.op, key): grfn_list.append([{"boolean_operation": operation[key]}]) for item in node.values: grfn_list.append(self.gen_grfn(item, state, "boolop")) return grfn_list @staticmethod def process_unnecessary_types(node, *_): """ This function handles various ast tags which are unnecessary and need not be handled since we do not require to parse them """ node_name = node.__repr__().split()[0][2:] assert False, f"Found {node_name}, which should be unnecessary" def process_expression(self, node, state, *_): """ This function handles the ast.Expr node i.e. the expression node. This node appears on function calls such as when calling a function, calling print(), etc. """ expressions = self.gen_grfn(node.value, state, "expr") grfn = {"functions": [], "variables": [], "containers": []} for expr in expressions: if "call" not in expr: # assert False, f"Unsupported expr: {expr}." return [] for expr in expressions: array_set = False string_set = False container_id_name = None input_index = None output_index = None arr_index = None call = expr["call"] function_name = call["function"] io_match = self.check_io_variables(function_name) if io_match: return [] # Bypassing calls to `print` for now. Need further discussion and # decisions to move forward with what we'll do with `print` # statements. if function_name == "print": return [] # A handler for array and string <.set_>/<.set_substr> function if ".set_" in function_name: split_function = function_name.split(".") is_derived_type_array_ref = False if ( len(split_function) > 2 and split_function[0] == self.current_d_object_name ): d_object = split_function[0] call_var = split_function[1] method = split_function[2] is_derived_type_array_ref = True else: call_var = split_function[0] method = split_function[1] # This is an array if len(call["inputs"]) > 1 and method != "set_substr": array_set = True function_name = function_name.replace(".set_", "") for idx in range(0, len(split_function) - 1): input_index = self.get_last_definition( split_function[idx], state.last_definitions, state.last_definition_default, ) output_index = self._get_next_definition( split_function[idx], state.last_definitions, state.next_definitions, state.last_definition_default, ) if is_derived_type_array_ref: function_name = function_name.replace(".", "_") input_index = self.get_last_definition( function_name, state.last_definitions, state.last_definition_default, ) output_index = self._get_next_definition( function_name, state.last_definitions, state.next_definitions, state.last_definition_default, ) state.variable_types[ function_name ] = state.variable_types[call_var] self.arrays[function_name] = self.arrays[call_var] arr_index = self._generate_array_index(node) str_arr_index = "" str_arr_for_varname = "" for idx in arr_index: if function_name not in self.md_array: str_arr_index += str(idx) str_arr_for_varname += str(idx) else: str_arr_index += f"[{idx}]" str_arr_for_varname += f"{idx}" # arr_index = call["inputs"][0][0]["var"]["variable"] # Create a new variable spec for indexed array. Ex. # arr(i) will be arr_i. This will be added as a new # variable in GrFN. variable_spec = self.generate_variable_definition( [function_name], str_arr_for_varname, False, state ) grfn["variables"].append(variable_spec) if function_name not in self.md_array: state.array_assign_name = ( f"{function_name}[{str_arr_index}]" ) else: state.array_assign_name = ( f"{function_name}{str_arr_index}" ) # We want to have a new variable spec for the original # array (arr(i), for example) and generate the function # name with it. variable_spec = self.generate_variable_definition( [function_name], None, False, state ) assign_function = self.generate_function_name( "__assign__", variable_spec["name"], arr_index ) container_id_name = assign_function["name"] function_type = assign_function["type"] # This is a string else: string_set = True function_name = call_var state.string_assign_name = function_name input_index = self._get_next_definition( function_name, state.last_definitions, state.next_definitions, -1, ) variable_spec = self.generate_variable_definition( [function_name], None, False, state ) grfn["variables"].append(variable_spec) assign_function = self.generate_function_name( "__assign__", variable_spec["name"], None ) container_id_name = assign_function["name"] function_type = assign_function["type"] else: if function_name in self.function_argument_map: container_id_name = self.function_argument_map[ function_name ]["name"] elif function_name in self.module_subprograms: container_id_name = function_name else: container_id_name = self.generate_container_id_name( self.fortran_file, self.current_scope, function_name ) function_type = "container" if not container_id_name: pass function = { "function": {"name": container_id_name, "type": function_type}, "input": [], "output": [], "updated": [], } # Array itself needs to be added as an input, so check that it's # and array. If yes, then add it manually. if array_set: function["input"].append( f"@variable::" f"{function_name}::{input_index}" ) function["output"] = [ f"@variable::" f"{function_name}::{output_index}" ] argument_list = [] list_index = 0 for arg in call["inputs"]: # We handle inputs to strings differently, so break out of # this loop if string_set: break generate_lambda_for_arr = False if len(arg) == 1: # TODO: Only variables are represented in function # arguments. But a function can have strings as # arguments as well. Do we add that? if "var" in arg[0]: if arg[0]["var"]["variable"] not in argument_list: function["input"].append( f"@variable::" f"{arg[0]["var"]["variable"]}::" f"{arg[0]["var"]["index"]}" ) # This is a case where a variable gets assigned to # an array. For example, arr(i) = var. if array_set: argument_list.append(arg[0]["var"]["variable"]) # If list_index is 0, it means that the current # loop is dealing with the array index (i in arr( # i)), which we do not wish to generate a lambda # function for. list_index > 0 are the RHS values # for array assignment. if list_index > 0: generate_lambda_for_arr = True list_index += 1 # This is a case where either an expression or an array # gets assigned to an array. For example, arr(i) = # __expression__ or arr(i) = arr2(i). elif "call" in arg[0]: # Check if a function argument is a string value # E.g: GET("test", "this", x) if arg[0]["call"].get("function"): if arg[0]["call"]["function"] == "String": # The value can either be a string literal or # a substring of another string. Check for this if "value" in arg[0]["call"]["inputs"][1][0]: value = arg[0]["call"]["inputs"][1][0][ "value" ] function["input"].append( f"@literal::" f"string::" f"'{value}'" ) elif "call" in arg[0]["call"]["inputs"][1][0]: string_variable = arg[0]["call"]["inputs"][ 1 ][0]["call"]["function"] if ".get_substr" in string_variable: string_variable = string_variable.split( "." )[ 0 ] string_index = state.last_definitions[ string_variable ] function["input"].append( f"@variable::{string_variable}::" f"{string_index}" ) else: assert False, ( "Unidentified " "expression in String." ) else: assert ( False ), "Unidentified expression in String." else: function = self._generate_array_setter( node, function, arg, function_name, container_id_name, arr_index, state, ) # This is a case where a literal gets assigned to an array. # For example, arr(i) = 100. elif "type" in arg[0] and array_set: generate_lambda_for_arr = True if generate_lambda_for_arr and state.array_assign_name: argument_list.append(function_name) lambda_string = self.generate_lambda_function( node, container_id_name, True, True, False, False, argument_list, [], state, False, ) function["function"]["code"] = lambda_string else: if function_name in self.arrays: # If array type is <float> the argument holder # has a different structure that it does not hold # function info. like when an array is 'int' type # [{'call': {'function': '_type_', 'inputs': [...]] # which causes an error. Thus, the code below fixes # by correctly structuring it. array_type = self.arrays[function_name]["elem_type"] fixed_arg = [ {"call": {"function": array_type, "inputs": [arg]}} ] function = self._generate_array_setter( node, function, fixed_arg, function_name, container_id_name, arr_index, state, ) else: assert ( "call" in arg[0] ), "Only 1 input per argument supported right now." # Below is a separate loop just for filling in inputs for arrays if array_set: argument_list = [] need_lambdas = False if "set_" in call["function"]: argument_list.append(call["function"].replace(".set_", "")) for arg in call["inputs"]: for ip in arg: if "var" in ip: function["input"].append( f"@variable::" f"{ip["var"]["variable"]}::" f"{ip["var"]["index"]}" ) if ip["var"]["variable"] not in argument_list: argument_list.append(ip["var"]["variable"]) elif "call" in ip: function_call = ip["call"] function_name = function_call["function"] need_lambdas = True if ".get_" in function_name: if ".get_substr" in function_name: function_name = function_name.replace( ".get_substr", "" ) else: function_name = function_name.replace( ".get_", "" ) # In some cases, the target array itself will # be an input as well. Don't add such arrays # again. if True not in [ function_name in i for i in function["input"] ]: function["input"].append( f"@variable::" f"{function_name}::" f"{state.last_definitions[function_name]}" ) if function_name not in argument_list: argument_list.append(function_name) for call_input in function_call["inputs"]: # TODO: This is of a recursive nature. Make # this a loop. Works for SIR for now. for var in call_input: if "var" in var: function["input"].append( f"@variable::" f"{var["var"]["variable"]}::" f"{var["var"]["index"]}" ) if ( var["var"]["variable"] not in argument_list ): argument_list.append( var["var"]["variable"] ) function["input"] = self._remove_duplicate_from_list( function["input"] ) argument_list = self._remove_duplicate_from_list(argument_list) if ( need_lambdas and container_id_name not in self.generated_lambda_functions ): lambda_string = self.generate_lambda_function( node, container_id_name, True, True, False, False, argument_list, [], state, False, ) function["function"]["code"] = lambda_string need_lambdas = False # Make an assign function for a string .set_ operation if string_set: target = { "var": { "variable": function_name, "index": variable_spec["name"].split("::")[-1], } } source_list = list(chain.from_iterable(call["inputs"])) # If the function is `set_substr`, the target string will # also be an input. if method == "set_substr": source_list.append( { "var": { "variable": function_name, "index": int( variable_spec["name"].split("::")[-1] ) - 1, } } ) function = self.make_fn_dict( assign_function, target, source_list, state ) argument_list = self.make_source_list_dict(source_list) lambda_string = self.generate_lambda_function( node, container_id_name, True, False, True, False, argument_list, [], state, False, ) function["function"]["code"] = lambda_string # This is sort of a hack for SIR to get the updated fields filled # in beforehand. For a generalized approach, look at # `process_module`. if function["function"]["type"] == "container": for functions in self.function_argument_map: if ( self.function_argument_map[functions]["name"] == function["function"]["name"] ): new_input = [] for idx in range(len(function["input"])): input_var = function["input"][idx].rsplit("::") index = input_var[2] if ( input_var[1] in self.f_array_arg or input_var[1] in [ x.rsplit("::")[1] for x in self.function_argument_map[ functions ]["updated_list"] ] or idx in self.function_argument_map[functions][ "updated_indices" ] ): variable_name = input_var[1] function["updated"].append( f"@variable::{variable_name}::{int(index)+1}" ) state.last_definitions[variable_name] += 1 state.next_definitions[variable_name] = ( state.last_definitions[variable_name] + 1 ) variable_spec = self.generate_variable_definition( [variable_name], None, False, state ) grfn["variables"].append(variable_spec) # The inputs might need to be updated since some # inputs to the functions are actually output # variables and are not used as inputs inside the # function if ( idx in self.function_argument_map[functions][ "argument_indices" ] ): new_input.append(function["input"][idx]) function["input"] = new_input # Keep a track of all functions whose `update` might need to be # later updated, along with their scope. if len(function["input"]) > 0: # self.update_functions.append(function_name) self.update_functions[function_name] = { "scope": self.current_scope, "state": state, } grfn["functions"].append(function) return [grfn] def process_compare(self, node, state, *_): """ This function handles ast.Compare i.e. the comparator tag which appears on logical comparison i.e. ==, <, >, <=, etc. This generally occurs within an `if` statement but can occur elsewhere as well. """ return self.gen_grfn(node.left, state, "compare") + self.gen_grfn( node.comparators, state, "compare" ) def process_subscript(self, node, state, *_): """ This function handles the ast.Subscript i.e. subscript tag of the ast. This tag appears on variable names that are indexed i.e. x[0], y[5], var[float], etc. Subscript nodes will have a `slice` tag which gives a information inside the [] of the call. """ # The value inside the [] should be a number for now. # TODO: Remove this and handle further for implementations of arrays, # reference of dictionary item, etc if not isinstance(node.slice.value, ast.Num): # raise For2PyError("can't handle arrays right now.") pass val = self.gen_grfn(node.value, state, "subscript") if val: if val[0]["var"]["variable"] in self.annotated_assigned: if isinstance(node.ctx, ast.Store): val[0]["var"]["index"] = self._get_next_definition( val[0]["var"]["variable"], state.last_definitions, state.next_definitions, state.last_definition_default, ) elif val[0]["var"]["index"] == -1: if isinstance(node.ctx, ast.Store): val[0]["var"]["index"] = self._get_next_definition( val[0]["var"]["variable"], state.last_definitions, state.next_definitions, state.last_definition_default, ) self.annotated_assigned.append(val[0]["var"]["variable"]) else: self.annotated_assigned.append(val[0]["var"]["variable"]) return val def process_name(self, node, state, call_source): """ This function handles the ast.Name node of the AST. This node represents any variable in the code. """ # Currently, bypassing any `i_g_n_o_r_e__m_e___` variables which are # used for comment extraction. if not re.match(r"i_g_n_o_r_e__m_e___.*", node.id): for mod in self.imported_module_paths: mod_name = mod.split(".")[-1][2:] import_str = f"from {mod} import {node.id}\n" if ( mod_name in self.module_summary and node.id in self.module_summary[mod_name]["exports"] and import_str not in state.lambda_strings ): state.lambda_strings.insert(0, import_str) last_definition = self.get_last_definition( node.id, state.last_definitions, state.last_definition_default ) # This is a test. Might not always work if ( call_source == "assign" and isinstance(node.ctx, ast.Store) and last_definition < 0 ): last_definition = self._get_next_definition( node.id, state.last_definitions, state.next_definitions, state.last_definition_default, ) if ( isinstance(node.ctx, ast.Store) and state.next_definitions.get(node.id) and call_source == "annassign" ): last_definition = self._get_next_definition( node.id, state.last_definitions, state.next_definitions, state.last_definition_default, ) # TODO Change this structure. This is not required for the new # spec. It made sense for the old spec but now it is not required. return [{"var": {"variable": node.id, "index": last_definition}}] else: return [] def process_annotated_assign(self, node, state, *_): """ This function handles annotated assignment operations i.e. ast.AnnAssign. This tag appears when a variable has been assigned with an annotation e.g. x: int = 5, y: List[float] = [None], etc. """ # Get the sources and targets of the annotated assignment sources = self.gen_grfn(node.value, state, "annassign") targets = self.gen_grfn(node.target, state, "annassign") # If the source i.e. assigned value is `None` (e.g. day: List[int] = # [None]), only update the data type of the targets and populate the # `annotated_assigned` map. No further processing will be done. if ( len(sources) == 1 and ("value" in sources[0][0].keys()) and sources[0][0]["value"] is None ): for target in targets: state.variable_types[ target["var"]["variable"] ] = self.get_variable_type(node.annotation) if target["var"]["variable"] not in self.annotated_assigned: self.annotated_assigned.append(target["var"]["variable"]) # Check if these variables are io variables. We don't maintain # states for io variables. So, don't add them on the # last_definitions and next_definitions dict. io_match = self.check_io_variables(target["var"]["variable"]) if io_match: self.exclude_list.append(target["var"]["variable"]) # When a variable is AnnAssigned with [None] it is being # declared but not defined. So, it should not be assigned an # index. Having the index as -2 indicates that this variable # has only been declared but never defined. The next # definition of this variable should start with an index of 0 # though. if not io_match: target["var"]["index"] = -2 state.last_definitions[target["var"]["variable"]] = -2 state.next_definitions[target["var"]["variable"]] = 0 return [] grfn = {"functions": [], "variables": [], "containers": []} # Only a single target appears in the current version. The `for` loop # seems unnecessary but will be required when multiple targets start # appearing (e.g. a = b = 5). for target in targets: target_name = target["var"]["variable"] # Because we use the `last_definition_default` to be -1 for # functions with arguments, in these functions the annotated # assigns at the top of the function will get the -1 index which # is incorrect. if target["var"]["index"] == -1: target["var"]["index"] = 0 state.last_definitions[target_name] = 0 # Preprocessing and removing certain Assigns which only pertain # to the Python code and do not relate to the FORTRAN code in any # way. io_match = self.check_io_variables(target_name) if io_match: self.exclude_list.append(target_name) return [] state.variable_types[target_name] = self.get_variable_type( node.annotation ) if target_name not in self.annotated_assigned: self.annotated_assigned.append(target_name) # Update the `next_definition` index of the target since it is # not being explicitly done by `process_name`. # TODO Change this functionality ground up by modifying # `process_name` and `process_subscript` to make it simpler. if not state.next_definitions.get(target_name): state.next_definitions[target_name] = ( target["var"]["index"] + 1 ) variable_spec = self.generate_variable_definition( [target_name], None, False, state ) function_name = self.generate_function_name( "__assign__", variable_spec["name"], None ) # If the source is a list inside of a list, remove the outer list if len(sources) == 1 and isinstance(sources[0], list): sources = sources[0] # TODO Somewhere around here, the Float32 class problem will have # to be handled. fn = self.make_fn_dict(function_name, target, sources, state) if len(sources) > 0: lambda_string = self.generate_lambda_function( node, function_name["name"], False, True, False, False, [ src["var"]["variable"] for src in sources if "var" in src ], [], state, False, ) fn["function"]["code"] = lambda_string # In the case of assignments of the form: "ud: List[float]" # an assignment function will be created with an empty input # list. Also, the function dictionary will be empty. We do # not want such assignments in the GrFN so check for an empty # <fn> dictionary and return [] if found if len(fn) == 0: return [] grfn["functions"].append(fn) grfn["variables"].append(variable_spec) return [grfn] def process_assign(self, node, state, *_): """ This function handles an assignment operation (ast.Assign). """ io_source = False is_function_call = False maybe_d_type_object_assign = False d_type_object_name = None # Get the GrFN element of the RHS side of the assignment which are # the variables involved in the assignment operations. sources = self.gen_grfn(node.value, state, "assign") node_name = node.targets[0].__repr__().split()[0][2:] if node_name == "ast.Attribute": node_value = node.targets[0].value attrib_ast = node_value.__repr__().split()[0][2:] if ( attrib_ast == "ast.Name" and node_value.id in self.derived_type_objects ): maybe_d_type_object_assign = True d_type_object_name = node_value.id object_type = self.derived_type_objects[d_type_object_name] elif ( attrib_ast == "ast.Attribute" and node_value.value.id in self.derived_type_objects ): maybe_d_type_object_assign = True d_type_object_name = node_value.value.id object_type = self.derived_type_objects[d_type_object_name] array_assignment = False is_d_type_obj_declaration = False # Detect assigns which are string initializations of the # following form: String(10). String initialization of the form # String(10, "abcdef") are valid assignments where the index of the # variables will be incremented but for the former case the index # will not be incremented and neither will its variable spec be # generated is_string_assign = False is_string_annotation = False if len(sources) > 0 and "call" in sources[0]: type_name = sources[0]["call"]["function"] if type_name == "String": is_string_assign = True # Check if it just an object initialization or initialization # with value assignment if len(sources[0]["call"]["inputs"]) == 1: # This is just an object initialization e.g. String(10) is_string_annotation = True elif type_name == "Array": array_assignment = True array_dimensions = [] inputs = sources[0]["call"]["inputs"] # If the array type is string, the structure of inputs will # be a bit different than when it is int of float if "call" in inputs[0][0]: if inputs[0][0]["call"]["function"] == "String": array_type = "string" else: array_type = inputs[0][0]["var"]["variable"] self._get_array_dimension(sources, array_dimensions, inputs) elif type_name in self.derived_types: is_d_type_obj_declaration = True if isinstance(node.targets[0], ast.Name): variable_name = node.targets[0].id if variable_name not in self.module_variable_types: for program in self.mode_mapper["public_objects"]: if ( variable_name in self.mode_mapper["public_objects"][program] ): self.module_variable_types[variable_name] = [ program, type_name, ] else: pass else: pass # This reduce function is useful when a single assignment operation # has multiple targets (E.g: a = b = 5). Currently, the translated # python code does not appear in this way and only a single target # will be present. targets = reduce( (lambda x, y: x.append(y)), [ self.gen_grfn(target, state, "assign") for target in node.targets ], ) grfn = {"functions": [], "variables": [], "containers": []} # Again as above, only a single target appears in current version. # The `for` loop seems unnecessary but will be required when multiple # targets start appearing. target_names = [] object_attr_num = 1 for target in targets: # Bypass any assigns that have multiple targets. # E.g. (i[0], x[0], j[0], y[0],) = ... if "list" in target: return [] target_names.append(target["var"]["variable"]) # Fill some data structures if this is a string # assignment/initialization if is_string_assign: state.variable_types[target_names[0]] = "string" state.string_assign_name = target_names[0] self.strings[target_names[0]] = { "length": sources[0]["call"]["inputs"][0][0]["value"] } if is_string_annotation: # If this is just a string initialization, # last_definition should not contain this string's index. # This happens only during assignments. del state.last_definitions[target_names[0]] self.strings[target_names[0]]["annotation"] = True self.strings[target_names[0]]["annotation_assign"] = False return [] else: self.strings[target_names[0]]["annotation"] = False self.strings[target_names[0]]["annotation_assign"] = True # Pre-processing and removing certain Assigns which only pertain # to the Python code and do not relate to the FORTRAN code in any # way. io_match = self.check_io_variables(target_names[0]) if io_match: self.exclude_list.append(target_names[0]) return [] # When declaring a derived type, the source will be the name of the # derived type. If so, bypass the assign if ( len(sources) == 1 and "var" in sources[0] and sources[0]["var"]["variable"] in self.derived_types ): state.last_definitions[target_names[0]] = 0 return [] # If the target is a list of variables, the grfn notation for the # target will be a list of variable names i.e. "[a, b, c]" # TODO: This does not seem right. Discuss with Clay and Paul # about what a proper notation for this would be if target.get("list"): targets = ",".join( [x["var"]["variable"] for x in target["list"]] ) target = {"var": {"variable": targets, "index": 1}} if array_assignment: var_name = target["var"]["variable"] state.array_assign_name = var_name # Just like the same reason as the variables # declared with annotation within function (not # function arguments) need to have index of zero. # Thus, these 3 lines of code fixes the index to # correct value from -1 to 0. if target["var"]["index"] == -1: target["var"]["index"] = 0 state.last_definitions[target_names[0]] = 0 is_mutable = False array_info = { "index": target["var"]["index"], "dimensions": array_dimensions, "elem_type": array_type, "mutable": is_mutable, } self.arrays[var_name] = array_info state.array_types[var_name] = array_type if array_type == "string": length = inputs[0][0]["call"]["inputs"][0][0]["value"] self.strings[var_name] = { "length": length, "annotation": False, "annotation_assign": True, } if ( maybe_d_type_object_assign and object_type and object_type in self.derived_types_attributes and target_names[0] in self.derived_types_attributes[object_type] ): self.current_d_object_name = d_type_object_name is_d_type_object_assignment = True # If targets holds more than 1 variable information and # it's greater than the object attribute number, then # the derived type object is referencing more than # 1 attribute (i.e. x.k.v). if len(targets) > 1 and len(targets) > object_attr_num: object_attr_num += 1 # Therefore, we do not want to go any further before # collecting all the information of the attribute # information, so we need to simply return back to the # beginning of loop and restart the process continue else: is_d_type_object_assignment = False variable_spec = self.generate_variable_definition( target_names, d_type_object_name, is_d_type_object_assignment, state, ) # Do not add the variable spec if this is a string annotation # since this can collide with the variable spec of the first # string assignment. if not is_string_annotation: grfn["variables"].append(variable_spec) # Since a Python class (derived type) object declaration has syntax # is __object_name__ = __class_name__, it's considered as an # assignment that will create __assign__ function GrFN, # which should not. Thus, simply return the [grfn] here to avoid # generating __assign__ function. if is_d_type_obj_declaration: return [grfn] # TODO Hack to not print lambda function for IO assigns. Need a # proper method to handle IO moving on for src in sources: if "call" in src: if self.check_io_variables(src["call"]["function"]): io_source = True function = src["call"]["function"] # Check if the source is a function call by comparing its # value with the list of functions in our program ( # obtained from the mode mapper) for program_functions in self.mode_mapper["subprograms"]: if ( function in self.mode_mapper["subprograms"][ program_functions ] ): is_function_call = True if is_function_call: container_name = self.generate_container_id_name( self.fortran_file, ["@global"], function ) function_name = {"name": container_name, "type": "container"} else: function_name = self.generate_function_name( "__assign__", variable_spec["name"], None ) # If current assignment process is for a derived type object (i.e # x.k), then if is_d_type_object_assignment: # (1) we need to add derived type object as function input. if state.last_definitions.get(d_type_object_name) is not None: index = state.last_definitions[d_type_object_name] elif ( self.global_scope_variables and self.global_scope_variables.last_definitions.get( d_type_object_name ) is not None ): index = 0 else: # Set to default 0. index = 0 # assert False, f"{d_type_object_name} not defined in the " \ # f"the current scope: {self.current_scope} " \ # f"or globally." src = [ {"var": {"variable": d_type_object_name, "index": index,}} ] sources.extend(src) # (2) Generate the object name + attributes variable name new_var_name = d_type_object_name for target_name in target_names: new_var_name += f"__{target_name}" self.current_d_object_attributes.append(target_name) # (3) we need to modify thee target to be "objectName_attribute" # For example, variable: x_k and index: __index_of_x_y__. target["var"] = { "variable": new_var_name, "index": state.last_definitions[new_var_name], } fn = self.make_fn_dict(function_name, target, sources, state) if len(fn) == 0: return [] source_list = self.make_source_list_dict(sources) if not io_source and not is_function_call: lambda_string = self.generate_lambda_function( node, function_name["name"], True, array_assignment, is_string_assign, is_d_type_object_assignment, source_list, [], state, False, ) fn["function"]["code"] = lambda_string grfn["functions"].append(fn) # We need to cleanup the object attribute tracking list. self.current_d_object_attributes = [] return [grfn] def process_tuple(self, node, state, *_): """ This function handles the ast.Tuple node of the AST. This handled in the same way `process_list_ast` is handled. """ elements = [ element[0] for element in [ self.gen_grfn(list_element, state, "ctx") for list_element in node.elts ] ] return elements if len(elements) == 1 else [{"list": elements}] def process_call(self, node, state, *_): """ This function handles the ast.Call node of the AST. This node denotes the call to a function. The body contains of the function name and its arguments. """ # Check if the call is in the form of <module>.<function> (E.g. # math.exp, math.cos, etc). The `module` part here is captured by the # attribute tag. if isinstance(node.func, ast.Attribute): # Check if there is a <sys> call. Bypass it if exists. if ( isinstance(node.func.value, ast.Attribute) and isinstance(node.func.value.value, ast.Name) and node.func.value.value.id == "sys" ): return [] function_node = node.func # The `function_node` can be a ast.Name (e.g. Format(format_10) # where `format_10` will be an ast.Name or it can have another # ast.Attribute (e.g. Format(main.file_10.readline())). # Currently, only these two nodes have been detected, so test for # these will be made. if isinstance(function_node.value, ast.Name): module = function_node.value.id function_name = function_node.attr function_name = module + "." + function_name elif isinstance(function_node.value, ast.Attribute): module = self.gen_grfn(function_node.value, state, "call") function_name = "" func_name = function_node.attr if self.is_d_object_array_assign: function_name = self.current_d_object_name + "." self.is_d_object_array_assign = False function_name += module + "." + func_name elif isinstance(function_node.value, ast.Call): return self.gen_grfn(function_node.value, state, "call") elif isinstance(function_node.value, ast.Str) and hasattr( function_node, "attr" ): module = function_node.value.s function_name = module + function_node.attr else: assert False, ( f"Invalid expression call" f" {dump_ast(function_node)}" ) else: function_name = node.func.id inputs = [] for arg in node.args: argument = self.gen_grfn(arg, state, _) inputs.append(argument) call = {"call": {"function": function_name, "inputs": inputs}} return [call] def process_module(self, node, state, *_): """ This function handles the ast.Module node in the AST. The module node is the starting point of the AST and its body consists of the entire ast of the python code. """ grfn_list = [] for cur in node.body: node_name = cur.__repr__().split()[0][2:] grfn = self.gen_grfn(cur, state, "module") if grfn and "name" in grfn[0] and "@type" in grfn[0]["name"]: self.derived_types_grfn.append(grfn[0]) elif self.current_scope == "global" and node_name in [ "ast.AnnAssign", "ast.Assign", "ast.Expr", ]: if not self.global_grfn["containers"][0]["name"]: namespace = self._get_namespace(self.fortran_file) self.global_grfn["containers"][0][ "name" ] = f"@container::{namespace}::@global" self.global_grfn["containers"][0][ "gensym" ] = self.generate_gensym("container") if len(grfn) > 0: self.global_grfn["containers"][0]["body"] += grfn[0][ "functions" ] self.global_grfn["variables"] += grfn[0]["variables"] else: grfn_list += grfn if self.global_grfn["containers"][0]["name"]: grfn_list += [self.global_grfn] merged_grfn = [self._merge_dictionary(grfn_list)] return merged_grfn # TODO Implement this. This needs to be done for generality # We fill in the `updated` field of function calls by looking at the # `updated` field of their container grfn final_grfn = self.load_updated(merged_grfn) return final_grfn @staticmethod def _process_nameconstant(node, *_): # TODO Change this format according to the new spec if isinstance(node.value, bool): dtype = "boolean" else: dtype = "string" return [{"type": "literal", "dtype": dtype, "value": node.value}] def process_attribute(self, node, state, call_source): """ Handle Attributes: This is a fix on `feature_save` branch to bypass the SAVE statement feature where a SAVEd variable is referenced as <function_name>.<variable_name>. So the code below only returns the <variable_name> which is stored under `node.attr`. The `node.id` stores the <function_name> which is being ignored. """ # If this node appears inside an ast.Call processing, then this is # the case where a function call has been saved in the case of IO # handling. E.g. format_10_obj.read_line(main.file_10.readline())). # Here, main.file_10.readline is if call_source == "call": if ( isinstance(node.value, ast.Name) and node.value.id == self.current_d_object_name ): self.is_d_object_array_assign = True module = node.attr return module # When a computations float value is extracted using the Float32 # class's _val method, an ast.Attribute will be present if node.attr == "_val": return self.gen_grfn(node.value, state, call_source) else: node_value = node.__repr__().split()[0][2:] if node_value != "ast.Attribute": # TODO: This section of the code should be the same as # `process_name`. Verify this. last_definition = self.get_last_definition( node.attr, state.last_definitions, state.last_definition_default, ) # TODO Change the format according to the new spec return [ {"var": {"variable": node.attr, "index": last_definition}} ] else: ( attributes, last_definitions, ) = self.get_derived_type_attributes(node, state) # Derived type reference variable on the RHS of assignment # needs to have a syntax like x__b (x%b in Fortran), so first # form "x_" here. # Currently, only going two levels deep. # TODO: This can be arbitrary level deep if isinstance(node.value, ast.Name): new_variable = node.value.id + "_" elif isinstance(node.value, ast.Attribute) or isinstance( node.value, ast.Subscript ): new_variable = node.value.value.id + "_" elif ( isinstance(node.value, ast.Call) and node.value.func.attr == "get_" ): new_variable = node.value.func.value.id + "_" new_variable += f"_{node.value.args[0].value.id}_" else: assert ( False ), f"Too deep levels or unhandled type. {dump_ast(node)}." new_var_index = 0 for attr in attributes: # Then, append attributes to the new variable new_variable = new_variable + f"_{attr}_" new_var_index = last_definitions[attr] new_variable = new_variable[:-1] # Since we've generated a new variable, we need to update # last_definitions dictionary. state.last_definitions[new_variable] = 0 variable_info = { "var": {"variable": new_variable, "index": new_var_index,} } # In the case of a saved variable, this node is called from # the ast.Subscript if call_source == "subscript": attribs = [] for attr in attributes: variable_info = { "var": { "variable": attr, "index": last_definitions[attr], } } attribs.append(variable_info) return attribs return [variable_info] def process_return_value(self, node, state, *_): """ This function handles the return value from a function. """ grfn = {"functions": [], "variables": [], "containers": []} if node.value: val = self.gen_grfn(node.value, state, "return_value") else: val = None namespace = self._get_namespace(self.fortran_file) function_name = f"{namespace}__{self.current_scope}__return" function_name = self.replace_multiple( function_name, ["$", "-", ":"], "_" ) function_name = function_name.replace(".", "__") return_dict = { "function": {"name": function_name, "type": "return"}, "value": val, } grfn["functions"].append(return_dict) return [grfn] def process_class_def(self, node, state, *_): """This function handles user defined type (class) by populating types grfn attribute. """ class_name = node.name src_string_list = self.original_python_src.split("\n") isClass = False class_code = "" import_code = "" # Read in the Python source string line by line for line in src_string_list: # If the current line is a start of class definition # class myClass: # , then set isClass to True and append @dataclass # to class_code string variable class_info = syntax.is_class_def(line) if class_info[0] and class_info[1] == class_name: isClass = True state.lambda_strings.append("@dataclass\n") class_code += "@dataclass\n" # If isClass is True, then it means that current line # is part of class definition. if isClass: # If a line contains "=", then it means class variables # are one of Array, String, or derived-type type. if "=" in line: splitted_line = line.split("=") var = splitted_line[0].rstrip() rhs_split = splitted_line[1].split("(") class_type = rhs_split[0].strip() if len(rhs_split) > 1: data_type = rhs_split[1].split(",")[0].strip() else: data_type = None if class_type == "Array": if data_type == "String": data_type = "str" line = f"{var}:List[{data_type}]" elif class_type == "String": line = f"{var}:str" elif class_type in self.derived_types: # If type is derived-type, we neeed to extract the module name and # form "from __filename__ import __class_name__" string. # However, we have not discussed where this will be inserted, so # if found out, please modify it. for mod in self.imported_module_paths: mod_name = mod.split(".")[-1][2:] import_str = f"from {mod} import {class_type}\n" if ( mod_name in self.module_summary and import_str not in self.generated_import_codes ): self.generated_import_codes.append(import_str) import_code += import_str state.lambda_strings.insert(0, import_str) state.lambda_strings.append(line + "\n") class_code += f"{line.strip()}\n\t" if not line.strip(): isClass = False grfn = { "name": "", "type": "type", "attributes": [], "code": class_code.strip(), } namespace = self._get_namespace(self.fortran_file) type_name = f"@type::{namespace}::@global::{class_name}" grfn["name"] = type_name # Keep a track of declared user-defined types self.derived_types.append(node.name.lower()) self.derived_types_attributes[node.name] = [] attributes = node.body # Populate class member variables into attributes array. for attrib in attributes: attrib_is_array = False attrib_ast = attrib.__repr__().split()[0][2:] if attrib_ast == "ast.AnnAssign": attrib_name = attrib.target.id if attrib.annotation.id in self.annotate_map: attrib_type = self.annotate_map[attrib.annotation.id] elif attrib.annotation.id in self.derived_types: attrib_type = attrib.annotation.id elif attrib_ast == "ast.Assign": attrib_name = attrib.targets[0].id try: attrib_type = attrib.value.func.id except AttributeError: attrib_type = attrib.value.id assert ( attrib_type in self.derived_types or attrib_type in self.library_types ), f"User-defined type [{attrib_type}] does not exist." if attrib_type == "Array": attrib_is_array = True if attrib_is_array: elem_type = attrib.value.args[0].id # TODO: Currently, derived type array attributes are assumed # to be a single dimensional array with integer type. It maybe # appropriate to handle a multi-dimensional with variable used # as a dimension size. dimension_info = attrib.value.args[1] is_literal = False is_name = False single_dimension = False dimension_list = [] if isinstance(dimension_info.elts[0], ast.Tuple): lower_bound = int(dimension_info.elts[0].elts[0].n) single_dimension = True # Retrieve upper bound of an array. if isinstance(dimension_info.elts[0].elts[1], ast.Num): upper_bound = int(dimension_info.elts[0].elts[1].n) is_literal = True elif isinstance(dimension_info.elts[0].elts[1], ast.Name): upper_bound = dimension_info.elts[0].elts[1].id is_name = True else: assert False, ( f"Currently, ast type " f"[{type(dimension_info.elts[0].elts[1])}] is not " f"supported." ) if is_literal: dimension = (upper_bound - lower_bound) + 1 elif is_name: dimension = upper_bound else: pass dimension_list.append(dimension) elif isinstance(dimension_info.elts[0], ast.Call): lower_bound = int(dimension_info.elts[0].func.elts[0].n) if isinstance( dimension_info.elts[0].func.elts[1], ast.Num ): upper_bound = int( dimension_info.elts[0].func.elts[1].n ) is_literal = True elif isinstance( dimension_info.elts[0].func.elts[1], ast.Name ): upper_bound = dimension_info.elts[0].func.elts[1].id is_name = True if is_literal: first_dimension = (upper_bound - lower_bound) + 1 elif is_name: first_dimension = upper_bound dimension_list.append(first_dimension) lower_bound = int(dimension_info.elts[0].args[0].n) if isinstance(dimension_info.elts[0].args[1], ast.Num): upper_bound = int(dimension_info.elts[0].args[1].n) is_literal = True elif isinstance(dimension_info.elts[0].args[1], ast.Name): upper_bound = dimension_info.elts[0].args[1].id is_name = True if is_literal: second_dimension = (upper_bound - lower_bound) + 1 elif is_name: second_dimension = upper_bound dimension_list.append(second_dimension) dimensions = dimension_list grfn["attributes"].append( { "name": attrib_name, "type": attrib_type, "elem_type": elem_type, "dimensions": dimensions, } ) # Here index is not needed for derived type attributes, # but simply adding it as a placeholder to make a constant # structure with other arrays. self.arrays[attrib_name] = { "index": 0, "dimensions": dimensions, "elem_type": elem_type, "mutable": True, } else: grfn["attributes"].append( {"name": attrib_name, "type": attrib_type} ) pass self.derived_types_attributes[node.name].append(attrib_name) state.variable_types[attrib_name] = attrib_type return [grfn] def process_break(self, node, state, *_): """ Process the breaks in the file, adding an EXIT node """ # Get all the IF_X identifiers and pick the one with the largest # index because that is the current one if_ids = [ int(x[-1]) for x in state.last_definitions.keys() if "IF_" in x ] current_if = f"IF_{max(if_ids)}" self.exit_candidates.append({current_if: "break"}) grfn = { "functions": ["insert_break"], "variables": [], "containers": [], } return [grfn] @staticmethod def process_ast(node, *_): sys.stderr.write( f"No handler for AST.{node.__class__.__name__} in gen_grfn, " f"fields: {node._fields}\n" ) def process_load(self, node, state, call_source): raise For2PyError( f"Found ast.Load, which should not happen. " f"From source: {call_source}" ) def process_store(self, node, state, call_source): raise For2PyError( f"Found ast.Store, which should not happen. " f"From source: {call_source}" ) @staticmethod def process_nomatch(node, *_): sys.stderr.write( f"No handler for {node.__class__.__name__} in gen_grfn, " f"value: {str(node)}\n" ) @staticmethod def _get_namespace(original_fortran_file) -> str: """ This function returns the namespace for every identifier in the system being analyzed. Currently, this function is very barebone and just returns the name of the system being evaluated. After more testing with modules and imports, the namespace will expand into more than just the system file name. """ namespace_path_list = get_path(original_fortran_file, "namespace") namespace_path = ".".join(namespace_path_list) # TODO Hack: Currently only the last element of the # `namespace_path_list` is being returned as the `namespace_path` in # order to make it consistent with the handwritten SIR-Demo GrFN # JSON. Will need a more generic path for later instances. namespace_path = namespace_path_list[-1] return namespace_path def make_source_list_dict(self, source_dictionary): source_list = [] # If the source is a list inside of a list, remove the outer list if len(source_dictionary) == 1 and isinstance( source_dictionary[0], list ): source_dictionary = source_dictionary[0] for src in source_dictionary: if "var" in src: if src["var"]["variable"] not in self.annotate_map: source_list.append(src["var"]["variable"]) elif "call" in src: for ip in src["call"]["inputs"]: source_list.extend(self.make_source_list_dict(ip)) if ( "f_index" in src["call"]["function"] or "get_substr" in src["call"]["function"] ): string_var = src["call"]["function"].split(".")[0] source_list.append(string_var) elif "list" in src: for ip in src["list"]: if "var" in ip: source_list.append(ip["var"]["variable"]) # Removing duplicates unique_source = [] [ unique_source.append(obj) for obj in source_list if obj not in unique_source ] source_list = unique_source return source_list def make_fn_dict(self, name, target, sources, state): source = [] fn = {} io_source = False target_name = target["var"]["variable"] target_string = f"@variable::{target_name}::{target["var"]["index"]}" # If the source is a list inside of a list, remove the outer list if len(sources) == 1 and isinstance(sources[0], list): sources = sources[0] for src in sources: # Check for a write to a file if re.match(r"\d+", target_name) and "list" in src: return fn if "call" in src: function_name = src["call"]["function"] method_var = function_name.split(".") if len(method_var) > 1: method_name = method_var[1] else: method_name = function_name # Remove first index of an array function as it's # really a type name not the variable for input. if function_name == "Array": del src["call"]["inputs"][0] # If a RHS of an assignment is an array getter, # for example, meani.get_((runs[0])), we only need # the array name (meani in this case) and append # to source. # if ".get_" in src["call"]["function"]: if method_name == "get_": get_array_name = src["call"]["function"].replace( ".get_", "" ) var_arr_name = f"@variable::{get_array_name}::-1" source.append(var_arr_name) # Bypassing identifiers who have I/O constructs on their source # fields too. # Example: (i[0],) = format_10_obj.read_line(file_10.readline()) # 'i' is bypassed here # TODO this is only for PETASCE02.for. Will need to include 'i' # in the long run bypass_match_source = self.check_io_variables(function_name) if bypass_match_source: if "var" in src: self.exclude_list.append(src["var"]["variable"]) # TODO This is a hack for SIR's retval to be included as # an assign function (will not have an input). But, # moving on a proper method for handling IO is required. # Uncomment the line below to revert to old form. # return fn io_source = True # TODO Finalize the spec for calls here of this form: # "@container::<namespace_path_string>::<scope_path_string>:: # <container_base_name>" and add here. if not io_source: for source_ins in self.make_call_body_dict(src): source.append(source_ins) # Check for cases of string index operations if method_name in ["f_index", "get_substr"]: string_var = src["call"]["function"].split(".")[0] index = state.last_definitions[string_var] source.append(f"@variable::{string_var}::{index}") elif "var" in src: source_string = ( f"@variable::{src["var"]["variable"]}::" f"{src["var"]["index"]}" ) source.append(source_string) # The code below is commented out to not include any `literal` # values in the input of `function` bodies. The spec does mention # including `literals` so if needed, uncomment the code block below # elif "type" in src and src["type"] == "literal": # variable_type = self.type_def_map[src["dtype"]] # source_string = f"@literal::{variable_type}::{src["value"]}" # source.append(source_string) # else: # assert False, f"Unidentified source: {src}" # Removing duplicates unique_source = [] [ unique_source.append(obj) for obj in source if obj not in unique_source ] source = unique_source fn = { "function": name, "input": source, "output": [target_string], "updated": [], } return fn @staticmethod def _remove_io_variables(variable_list): """ This function scans each variable from a list of currently defined variables and removes those which are related to I/O such as format variables, file handles, write lists and write_lines. """ io_regex = re.compile( r"(format_\d+_obj)|(file_\d+)|(write_list_\d+)|" r"(write_line)" ) io_match_list = [io_regex.match(var) for var in variable_list] return [ var for var in variable_list if io_match_list[variable_list.index(var)] is None ] def make_call_body_dict(self, source): """ We are going to remove addition of functions such as "max", "exp", "sin", etc to the source list. The following two lines when commented helps us do that. If user-defined functions come up as sources, some other approach might be required. """ # TODO Try with user defined functions and see if the below two lines # need to be reworked # name = source["call"]["function"] # source_list.append({"name": name, "type": "function"}) source_list = [] for ip in source["call"]["inputs"]: if isinstance(ip, list): for item in ip: if "var" in item: source_string = ( f"@variable::" f"{item["var"]["variable"]}::" f"{item["var"]["index"]}" ) source_list.append(source_string) # TODO Adding boolean literals as an input to an assign # function but not integer literals? elif ( "type" in item and item["type"] == "literal" and item["dtype"] == "boolean" ): source_string = ( f"@literal::" f"{item["dtype"]}::" f"{item["value"]}" ) source_list.append(source_string) elif "call" in item: source_list.extend(self.make_call_body_dict(item)) elif "list" in item: # Handles a case where array declaration size # was given with a variable value. for value in item["list"]: if "var" in value: variable = ( f"@variable:" f":{value["var"]["variable"]}::0" ) source_list.append(variable) return source_list def process_decorators(self, node, state): """ Go through each decorator and extract relevant information. Currently this function only checks for the static_vars decorator for the SAVEd variables and updates variable_types with the data type of each variable. """ for decorator in node: decorator_function_name = decorator.func.id if decorator_function_name == "static_vars": for arg in decorator.args[0].elts: variable = arg.values[0].s variable_type = arg.values[2].s if "String" in variable_type: length_regex = re.compile(r"String\((\d+)\)", re.I) match = length_regex.match(variable_type) if match: length = match.group(1) elif ( hasattr(arg.values[1], "func") and hasattr(arg.values[1], "args") and hasattr(arg.values[1].args[0], "args") ): length = arg.values[1].args[0].args[0].n else: assert ( False ), "Could not identify valid String type" self.strings[variable] = { "length": length, "annotation": False, "annotation_assign": False, } state.variable_types[variable] = self.annotate_map[ "String" ] else: state.variable_types[variable] = self.annotate_map[ variable_type ] @staticmethod def process_try(node, state, call_source): return [] @staticmethod def _merge_dictionary(dicts: Iterable[Dict]) -> Dict: """ This function merges the entire dictionary created by `gen_grfn` into another dictionary in a managed manner. The `dicts` argument is a list of form [{}, {}, {}] where each {} dictionary is the grfn specification of a function. It contains `functions` and `identifiers` as its keys. Additionally, if the python code has a starting point, that is also present in the last {} of `dicts`. The function merges the values from the `functions` key of each {} in `dicts` into a single key of the same name. Similarly, it does this for every unique key in the `dicts` dictionaries. """ fields = set(chain.from_iterable(d.keys() for d in dicts)) merged_dict = {field: [] for field in fields} # Create a cross-product between each unique key and each grfn # dictionary for field, d in product(fields, dicts): if field in d: if isinstance(d[field], list): merged_dict[field] += d[field] else: merged_dict[field].append(d[field]) return merged_dict def get_last_definition( self, var, last_definitions, last_definition_default ): """ This function returns the last (current) definition (index) of a variable. """ index = last_definition_default # Pre-processing and removing certain Assigns which only pertain to the # Python code and do not relate to the FORTRAN code in any way. bypass_match = self.re_bypass_io.match(var) if not bypass_match: if var in last_definitions: index = last_definitions[var] else: last_definitions[var] = index return index else: return 0 @staticmethod def _get_next_definition( var, last_definitions, next_definitions, last_definition_default ): """ This function returns the next definition i.e. index of a variable. """ # The dictionary `next_definitions` holds the next index of all current # variables in scope. If the variable is not found (happens when it is # assigned for the first time in a scope), its index will be one greater # than the last definition default. index = next_definitions.get(var, last_definition_default + 1) # Update the next definition index of this variable by incrementing # it by 1. This will be used the next time when this variable is # referenced on the LHS side of an assignment. next_definitions[var] = index + 1 # Also update the `last_definitions` dictionary which holds the current # index of all variables in scope. last_definitions[var] = index return index def get_variable_type(self, annotation_node): """ This function returns the data type of a variable using the annotation information used to define that variable """ # If the variable has been wrapped in a list like x: List[int], # `annotation_node` will be a Subscript node if isinstance(annotation_node, ast.Subscript): data_type = annotation_node.slice.value.id else: data_type = annotation_node.id if self.annotate_map.get(data_type): return self.annotate_map[data_type] elif data_type in self.derived_types: return data_type else: assert False, ( "Unsupported type (only float, int, list, real, " "bool and str supported as of now).\n" ) @staticmethod def _get_variables_and_functions(grfn): variables = list( chain.from_iterable(stmt["variables"] for stmt in grfn) ) fns = list(chain.from_iterable(stmt["functions"] for stmt in grfn)) containers = list( chain.from_iterable(stmt["containers"] for stmt in grfn) ) return variables, fns, containers def generate_gensym(self, tag): """ The gensym is used to uniquely identify any identifier in the program. Python's uuid library is used to generate a unique 12 digit HEX string. The uuid4() function of 'uuid' focuses on randomness. Each and every bit of a UUID v4 is generated randomly and with no inherent logic. To every gensym, we add a tag signifying the data type it represents. 'v': variables 'c': containers 'f': functions """ return f"{self.gensym_tag_map[tag]}_{uuid.uuid4().hex[:12]}" def generate_lambda_function( self, node, function_name: str, return_value: bool, array_assign: bool, string_assign: bool, d_type_assign: bool, inputs, decision_versions, state, is_custom: bool, ): self.generated_lambda_functions.append(function_name) lambda_for_var = True inline_lambda = "lambda " lambda_strings = ["\n"] argument_strings = [] # We need to remove the attribute (class member var) from # the source_list as we do not need it in the lambda function # argument. Also, form an __object.attribute__ string. if d_type_assign: d_type = state.variable_types[self.current_d_object_name] target_name = self.current_d_object_name for attr in self.current_d_object_attributes: if attr in self.derived_types_attributes[d_type]: target_name += f".{attr}" # Since the next attribute that will be seen must be # dependent on the current attribute type, here it's # updating the d_type. d_type = state.variable_types[attr] # If a custom lambda function is encountered, create its function # instead if is_custom: lambda_strings.append( f"def {function_name}({", ".join(inputs)}):\n " ) inline_lambda += f"{",".join(inputs)}:" if return_value: if isinstance(node, str): lambda_strings.append(f"return {node}") inline_lambda += node elif isinstance(node, int): lambda_strings.append(f"return {node}") inline_lambda += f"{node}" elif isinstance(node, list) and node[0] == "EXIT": exit_string = f"(not {inputs[0]})" for ip in inputs[1:]: exit_string += f" or (not {ip})" lambda_strings.append(f"return {exit_string}") inline_lambda += exit_string else: lambda_code_generator = genCode(self.use_numpy) code = lambda_code_generator.generate_code( node, PrintState("\n ") ) lambda_strings.append(f"return {code}") inline_lambda += code else: assert False, f"Should always return" lambda_strings.append("\n\n") return inline_lambda # return "".join(lambda_strings) # Sort the arguments in the function call as it is used in the operation input_list = sorted(set(inputs), key=inputs.index) if "__decision__" in function_name: argument_map = self._generate_argument_map(inputs) input_list = list(argument_map.values()) # Add type annotations to the function arguments for ip in input_list: annotation = state.variable_types.get(ip) if ip in state.array_types: lambda_for_var = False if lambda_for_var and not annotation: # `variable_types` does not contain annotations for variables # for indexing such as 'abc_1', etc. Check if the such variables # exist and assign appropriate annotations key_match = lambda var, dicn: ([i for i in dicn if i in var]) if len(key_match(ip, state.variable_types)) > 0: annotation = state.variable_types[ key_match(ip, state.variable_types)[0] ] # function argument requires annotation only when # it's dealing with simple variable (at least for now). # TODO String assignments of all kinds are class/method related # operations and will not involve annotations. Discuss this. if lambda_for_var and annotation != "string": if annotation in self.annotate_map: annotation = self.annotate_map[annotation] # else: # assert annotation in self.derived_types, ( # f"Annotation must be a regular type or user defined " # f"type. Annotation: {annotation}" # ) if annotation: if ( annotation not in self.annotate_map and annotation in self.derived_types ): for mod in self.imported_module_paths: mod_name = mod.split(".")[-1][2:] import_str = f"from {mod} import {annotation}\n" if ( mod_name in self.module_summary and annotation in self.module_summary[mod_name][ "derived_type_list" ] and import_str not in state.lambda_strings ): state.lambda_strings.insert(0, import_str) argument_strings.append(f"{ip}: {annotation}") else: argument_strings.append(f"{ip}") # Currently, this is for array specific else case. else: argument_strings.append(ip) lambda_for_var = True lambda_strings.append( f"def {function_name}({", ".join(argument_strings)}):\n " ) inline_lambda += f"{",".join(input_list)}:" # A case where calculating the sum of array. # In this case, we do not have to invoke genCode function(s). if ( isinstance(node, ast.Assign) and isinstance(node.value, ast.Call) and "attr" in node.value.func._fields and node.value.func.attr == "get_sum" ): arr_name = node.value.func.value.id # TODO: Currently, only handles 1D-list to satisfy cases # that onnly appears in the Min-SPAM files. lambda_strings.append(f"return sum({arr_name})\n") inline_lambda += f"sum({arr_name})" return inline_lambda # return "".join(lambda_strings) # If a `decision` tag comes up, override the call to genCode to manually # enter the python script for the lambda file. if "__decision__" in function_name: # Get the condition var to know the instance of IF function we're # on i.e. COND_1 or COND_0 and so on condition_var = inputs[0].rsplit("_", 2)[0] # Get the maximum number of `if COND` booleans we have for this # if container max_conditions = state.last_definitions.get("#cond", 0) code = self._generate_decision_lambda( decision_versions, condition_var, max_conditions, inputs[-1].rsplit("_", 1)[0], argument_map, ) elif not string_assign: array_name = None if state.array_assign_name: array_name = state.array_assign_name.split("[")[0] if array_name in self.strings: lambda_code_generator = genCode( self.use_numpy, self.strings[array_name]["length"] ) else: lambda_code_generator = genCode(self.use_numpy) code = lambda_code_generator.generate_code( node, PrintState("\n ") ) if return_value: if array_assign: if "_" in state.array_assign_name: names = state.array_assign_name.split("_") if names[0] == self.current_d_object_name: state.array_assign_name = state.array_assign_name.replace( "_", "." ) lambda_strings.append(f"{state.array_assign_name} = {code}\n") lambda_strings.append(f" return {array_name}") if "[" in state.array_assign_name: array_split = state.array_assign_name.split("[") array_name = array_split[0] array_index = array_split[1][:-1] code = ( f"({array_name}.__setitem__({array_index},{code})," f"{array_name})[1]" ) state.array_assign_name = None elif string_assign: lambda_code_generator = genCode( self.use_numpy, self.strings[state.string_assign_name]["length"], ) code = lambda_code_generator.generate_code( node, PrintState("\n "), ) if self.strings[state.string_assign_name]["annotation"]: self.strings[state.string_assign_name][ "annotation" ] = False if self.strings[state.string_assign_name]["annotation_assign"]: self.strings[state.string_assign_name][ "annotation_assign" ] = False lambda_strings.append(f"return {code}") state.string_assign_name = None elif d_type_assign: lambda_strings.append(f"{target_name} = {code}\n") lambda_strings.append(f" return {target_name}") else: lambda_strings.append(f"return {code}") else: lines = code.split("\n") indent = re.search("[^ ]", lines[-1]).start() lines[-1] = lines[-1][:indent] + "return " + lines[-1][indent:] lambda_strings.append("\n".join(lines)) lambda_strings.append("\n\n") inline_lambda += code return inline_lambda # return "".join(lambda_strings) def generate_container_id_name( self, namespace_file: str, scope_path, container_basename: str ) -> str: namespace = self._get_namespace(namespace_file) if isinstance(scope_path, list): scope_path_string = ".".join(scope_path) elif isinstance(scope_path, str): scope_path_string = scope_path else: assert False, f"Invalid scope_path type {scope_path}" container_id = ( f"@container::{namespace}::{scope_path_string}::" f"{container_basename}" ) return container_id def generate_variable_definition( self, variables, reference, d_type_object_assign, state ): """ This function generates the GrFN structure for a variable definition, of the form: variable: { name: source_refs: gensym: domain: domain_constraints: } Args: variables (list): List of variables. reference (str): Either array's indexing variable (i.e. i for array[i]) or derived type object's referencing class member variable (i.e. k for x.k) Returns: list : Generated GrFN. """ namespace = self._get_namespace(self.fortran_file) index = [] domains = [] for variable in variables: if variable in state.last_definitions: index.append(state.last_definitions[variable]) elif ( variable in self.strings and self.strings[variable]["annotation"] ): # If this is a string initialization without assignment, # the index will be 0 by default index.append(0) elif variable in self.arrays: index.append(0) domains.append(self.get_domain_dictionary(variable, state)) for domain in domains: # Since we need to update the domain of arrays that # were passed to a function once the program actually # finds about it, we need to temporarily hold the domain # information in the dictionary of domain list. if "name" in domain: if domain["name"] == "array": if variable in self.array_arg_domain: self.array_arg_domain[variable].append(domain) else: self.array_arg_domain[variable] = [domain] elif domain["name"] in self.derived_types: self.derived_type_objects[variable] = domain["name"] # Only array variables hold dimensions in their domain # when they get declared, we identify the array variable # declaration by simply checking the existence of the dimensions # key in the domain. Also, the array was previously passed # to functions. if "dimensions" in domain and variable in self.array_arg_domain: # Since we can't simply do "dom = domain" # as this will do a replacement of the dict element # not the actual domain object of the original function # argument, we need to clean off the existing contents # first and then add the array domain spec one-by-one. for dom in self.array_arg_domain[variable]: if "name" in dom: del dom["name"] if "type" in dom: del dom["type"] dom["index"] = domain["index"] dom["dimensions"] = domain["dimensions"] dom["elem_type"] = domain["elem_type"] dom["mutable"] = domain["mutable"] variable_gensym = self.generate_gensym("variable") if reference is not None: if d_type_object_assign: variable = reference for var in variables: variable += f"__{var}" # else: # variable = f"{variable}_{reference}" # TODO: The code above has been commented for now but not removed. # Remove this when everything works and the line below doesn't # give any issues state.last_definitions[variable] = index[0] variable_name = ( f"@variable::{namespace}::{self.current_scope}::" f"{variable}::{index[0]}" ) # TODO Change the domain constraint. How do you figure out the domain # constraint? domain_constraint = "(and (> v -infty) (< v infty))" variable_definition = { "name": variable_name, "gensym": variable_gensym, "source_refs": [], "domain": domain, "domain_constraint": domain_constraint, } return variable_definition def get_domain_dictionary(self, variable, state): if variable in self.arrays: domain_dictionary = self.arrays[variable] else: type_name = None if ( variable in state.variable_types and state.variable_types[variable] ): variable_type = state.variable_types[variable] elif variable in self.module_variable_types: variable_type = self.module_variable_types[variable][1] # Is this a derived type variable elif "__" in variable: variable_tail = variable.split("__")[-1] if ( variable_tail in state.variable_types and state.variable_types[variable_tail] ): variable_type = state.variable_types[variable_tail] else: assert False, f"unrecognized variable: {variable}" else: variable_type = None # assert False, f"unrecognized variable: {variable}" # Mark if a variable is mutable or not. if ( variable in self.variable_map and self.variable_map[variable]["parameter"] ): is_mutable = True else: is_mutable = False # Array as a function argument handler. if self.handling_f_args and variable_type == "array": self.f_array_arg.append(variable) # Retrieve variable type name (i.e. integer, float, # __derived_type__) if variable_type in self.type_def_map: type_name = self.type_def_map[variable_type] elif variable_type in self.derived_types: type_name = variable_type # Since derived type variables are not a regular type variable, # we need to needs to them manually here into variable_types # dictionary to be referenced later in the stream. state.variable_types[variable] = type_name elif variable_type == "Real": type_name = "float" elif len(self.imported_module) > 0: for mod in self.imported_module: if ( mod in self.module_summary and variable in self.module_summary[mod]["symbol_types"] ): type_name = self.module_summary[mod]["symbol_types"] else: type_found = False if len(self.module_names) > 1: for mod in self.module_names: if ( mod != "main" and mod in self.module_summary and variable_type in self.module_summary[mod]["derived_type_list"] ): type_found = True type_name = variable_type state.variable_types[variable] = type_name domain_dictionary = { "name": type_name, "type": "type", "mutable": is_mutable, } return domain_dictionary def generate_function_name(self, function_type, variable, arr_index): """ This function generates the name of the function inside the container wiring within the body of a container. """ variable_spec_regex = ( r"@.*?::(?P<namescope>.*?::.*?)::(" r"?P<variable>.*?)::(?P<index>.*)" ) variable_match = re.match(variable_spec_regex, variable) if variable_match: namespace_scope = variable_match.group("namescope") variable_name = variable_match.group("variable") if arr_index: variable_name += "_" for index in arr_index: variable_name = variable_name + f"{index}" variable_index = variable_match.group("index") name = ( namespace_scope + function_type + variable_name + "::" + variable_index ) name = self.replace_multiple(name, ["$", "-", ":"], "_") name = name.replace(".", "__") if any( [ x in function_type for x in ["assign", "condition", "decision"] ] ): spec_type = "lambda" else: spec_type = "None" else: assert False, f"Cannot match regex for variable spec: {variable}" return {"name": name, "type": spec_type} def load_updated(self, grfn_dict): """ This function parses through the GrFN once and finds the container spec of functions whose `updated` fields needs to be filled in that functions' function call spec. """ for container in self.function_argument_map: if container in self.update_functions: for container_grfn in grfn_dict[0]["containers"]: for body_function in container_grfn["body"]: function_name = body_function["function"]["name"] if ( function_name.startswith("@container") and function_name.split("::")[-1] == container ): updated_variable = [ body_function["input"][i] for i in self.function_argument_map[container][ "updated_indices" ] ] for i in range(len(updated_variable)): old_index = int( updated_variable[i].split("::")[-1] ) new_index = old_index + 1 updated_var_list = updated_variable[i].split( "::" )[:-1] updated_var_list.append(str(new_index)) updated_variable[i] = "::".join( updated_var_list ) self.current_scope = self.update_functions[ container ]["scope"] variable_name = updated_var_list[1] variable_spec = self.generate_variable_definition( variable_name, None, False, self.update_functions[container]["state"], ) variable_name_list = variable_spec[ "name" ].split("::")[:-1] variable_name_list.append(str(new_index)) variable_spec["name"] = "::".join( variable_name_list ) grfn_dict[0]["variables"].append(variable_spec) body_function["updated"] = updated_variable return grfn_dict @staticmethod def _get_array_dimension(sources, array_dimensions, inputs): """This function is for extracting bounds of an array. Args: sources (list): A list holding GrFN element of array function. For example, Array (int, [[(0, 10)]). array_dimensions (list): An empty list that will be populated by current function with the dimension info. inputs (list): A list that holds inputs dictionary extracted from sources. Returns: None. """ # A multi-dimensional array handler if len(inputs[1]) > 1: for lst in inputs[1]: low_bound = int(lst[0]["list"][0]["value"]) upper_bound = int(lst[0]["list"][1]["value"]) array_dimensions.append(upper_bound - low_bound + 1) # 1-D array handler else: bounds = inputs[1][0][0]["list"] # Get lower bound of an array if "type" in bounds[0]: # When an index is a scalar value low_bound = bounds[0]["value"] else: # When an index is a variable low_bound = bounds[0]["var"]["variable"] # Get upper bound of an array if "type" in bounds[1]: upper_bound = bounds[1]["value"] else: upper_bound = bounds[1]["var"]["variable"] if isinstance(low_bound, int) and isinstance(upper_bound, int): array_dimensions.append(upper_bound - low_bound + 1) elif isinstance(upper_bound, str): # assert ( # isinstance(low_bound, int) and low_bound == 0 # ), "low_bound must be <integer> type and 0 (zero) for now." array_dimensions.append(upper_bound) else: assert False, ( f"low_bound type: {type(low_bound)} is " f"currently not handled." ) def _generate_array_setter( self, node, function, arg, name, container_id_name, arr_index, state ): """ This function is for handling array setter (ex. means.set_(...)). Args: node: The node referring to the array function (list): A list holding the information of the function for JSON and lambda function generation. arg (list): A list holding the arguments of call['inputs']. name (str): A name of the array. container_id_name (str): A name of function container. It's an array name with other appended info. in this function. arr_index (str): Index of a target array. state: The current state of the system Returns: (list) function: A completed list of function. """ if "_" in name: names = name.split("_") if names[0] == self.current_d_object_name: argument_list = [names[0]] else: argument_list = [name] else: argument_list = [name] # Array index is always one of # the lambda function argument for idx in arr_index: if idx not in self.arithmetic_ops and isinstance(idx, str): argument_list.append(idx) # For array setter value handler for var in arg[0]["call"]["inputs"][0]: # If an input is a simple variable. if "var" in var: var_name = var["var"]["variable"] if var_name not in argument_list: input_index = self.get_last_definition( var_name, state.last_definitions, state.last_definition_default, ) function["input"].append( f"@variable::" f"{var_name}::" f"{input_index}" ) argument_list.append(var_name) else: # It's not an error, so just pass it. pass # If an input is an array. elif "call" in var: ref_call = var["call"] if ".get_" in ref_call["function"]: get_array_name = ref_call["function"].replace(".get_", "") if get_array_name not in argument_list: argument_list.append(get_array_name) if get_array_name != name: ip_index = self.get_last_definition( get_array_name, state.last_definitions, state.last_definition_default, ) function["input"].append( f"@variable::" f"{get_array_name}::" f"{ip_index}" ) else: # It's not an error, so just pass it. pass # Generate lambda function for array[index] lambda_string = self.generate_lambda_function( node, container_id_name, True, True, False, False, argument_list, [], state, False, ) function["function"]["code"] = lambda_string return function def _generate_array_index(self, node): """This function is for generating array index grfn handling both single and multi-dimensional arrays. Args: node: The node referring to the array. Returns: (list) index: Formed array index. """ args = node.value.args[0] args_name = args.__repr__().split()[0][2:] # Case 1: Single dimensional array if args_name == "ast.Subscript": if hasattr(args.value, "value"): return [args.value.value.id] else: return [args.value.id] elif args_name == "ast.Num": return [int(args.n) - 1] # Case 1.1: Single dimensional array with arithmetic # operation as setter index elif args_name == "ast.BinOp": left_ast = args.left.__repr__().split()[0][2:] right_ast = args.right.__repr__().split()[0][2:] # Get the operator's left side value if left_ast == "ast.Subscript": left = args.left.value.id elif left_ast == "ast.Num": left = args.left.n # Get the arithmetic operator op = self.arithmetic_ops[args.op.__repr__().split()[0][6:]] # Get the operator's right side value if right_ast == "ast.Subscript": right = args.right.value.id elif right_ast == "ast.Num": right = args.right.n return [left, op, right] # Case 2: Multi-dimensional array elif args_name == "ast.Tuple": if hasattr(node.value.func.value, "id"): md_array_name = node.value.func.value.id elif hasattr(node.value.func.value, "value"): md_array_name = node.value.func.value.value.id if md_array_name not in self.md_array: self.md_array.append(md_array_name) dimensions = args.elts dimension_list = [] for dimension in dimensions: ast_name = dimension.__repr__().split()[0][2:] if ast_name == "ast.Subscript": if hasattr(dimension.value, "id"): dimension_list.append(dimension.value.id) elif hasattr(dimension.value, "value"): dimension_list.append(dimension.value.value.id) elif ast_name == "ast.Call": dimension_list.append(dimension.func.value.value.id) else: assert ast_name == "ast.Num", ( f"Unable to handle {ast_name} for multi-dimensional " f"array - node: {dump_ast(node)}\n" f"dimension: {dump_ast(dimension)}" ) return dimension_list else: assert False, f"Unable to handle {args_name}" def get_derived_type_attributes(self, node, state): """ This function retrieves the derived type attributes from the ast and return the updated last definition dict and populated attribute list""" attributes = [] node_value = node.value.__repr__().split()[0][2:] if node_value == "ast.Attribute" and node.value.attr: attributes.append(node.value.attr) if node.attr: attributes.append(node.attr) last_definitions = {} for attrib in attributes: last_definitions[attrib] = self.get_last_definition( attrib, state.last_definitions, state.last_definition_default ) return attributes, last_definitions @staticmethod def replace_multiple(main_string, to_be_replaced, new_string): """ Replace a set of multiple sub strings with a new string in main string. """ # Iterate over the strings to be replaced for elem in to_be_replaced: # Check if string is in the main string if elem in main_string: # Replace the string main_string = main_string.replace(elem, new_string) return main_string @staticmethod def _find_updated(argument_list, body_variable_list, f_array_arg, state): """ This function finds and generates a list of updated identifiers in a container. """ # TODO After implementing everything, check if `argument_dict` and # `body_dict` will be the same as `function_state.last_definitions` # before and after getting `body_grfn`. If so, remove the creation # of `argument_dict` and `body_dict` and use the `last_definitions` # instead argument_dict = {} body_dict = {} updated_list = [] variable_regex = re.compile(r".*::(?P<variable>.*?)::(?P<index>.*$)") # First, get mapping of argument variables and their indexes for var in argument_list: var_match = variable_regex.match(var["name"]) if var_match: argument_dict[var_match.group("variable")] = var_match.group( "index" ) else: assert False, ( f"Error when parsing argument variable " f"{var["name"]}" ) # Now, get mapping of body variables and their latest indexes for var in body_variable_list: var_match = variable_regex.match(var["name"]) if var_match: body_dict[var_match.group("variable")] = var_match.group( "index" ) else: assert False, ( f"Error when parsing body variable " f"{var["name"]}" ) # Now loop through every argument variable over the body variable to # check if the indices mismatch which would indicate an updated variable for argument in argument_dict: if argument in body_dict and int(body_dict[argument]) > int( argument_dict[argument] ): updated_list.append( f"@variable::{argument}::" f"{body_dict[argument]}" ) # If argument is an array type, get the current index and # update it. Then, append to the function's updated list elif argument in f_array_arg: updated_idx = state.last_definitions[argument] updated_list.append( f"@variable::{argument}::" f"{updated_idx}" ) return updated_list @staticmethod def _remove_output_variables(arguments_list, body): """ Remove output variables from the argument list of function definitions """ input_list = [] arg_map = {} for arg in arguments_list: arg_map[arg.split("::")[1]] = arg for obj in body: if obj["functions"]: for statement in obj["functions"]: for ip in statement["input"]: input_list.append(ip.split("::")[1]) if statement["function"]["type"] == "lambda": check = "output" elif statement["function"]["type"] == "container": check = "updated" else: assert False, "Unknown function type detected" for op in statement[check]: op = op.split("::")[1] if op not in input_list and op in arg_map: arguments_list.remove(arg_map[op]) def check_io_variables(self, variable_name): """ This function scans the variable and checks if it is an io variable. It returns the status of this check i.e. True or False. """ io_match = self.re_bypass_io.match(variable_name) return io_match @staticmethod def _get_call_inputs( call_function, function_input, container_argument, loop_condition_inputs, loop_condition_inputs_lambda, state, ): """ This function parses a call function (such as when reading an array) and loads all respective input variables from it. """ # First check if the call is from an array call. We only update the # lists if it is an array operation (such as samples.get_((x[0])) if ".get_" in call_function["function"]: array_name = call_function["function"].replace(".get_", "") array_index = state.last_definitions.get( array_name, state.last_definition_default ) function_input.append( f"@variable::" f"{array_name}::" f"{array_index}" ) container_argument.append(f"@variable::" f"{array_name}::-1") loop_condition_inputs.append(f"@variable::" f"{array_name}::-1") loop_condition_inputs_lambda.append(array_name) for inputs in call_function["inputs"]: if not isinstance(inputs, list): inputs = [inputs] for var in inputs: if "var" in var: function_input.append( f"@variable::" f"{var["var"]["variable"]}::" f"{var["var"]["index"]}" ) container_argument.append( f"@variable::{var["var"]["variable"]}::-1" ) loop_condition_inputs.append( f"@variable::" f"{var["var"]["variable"]}::-1" ) loop_condition_inputs_lambda.append( var["var"]["variable"] ) else: pass @staticmethod def _remove_duplicate_from_list(input_list): """ This helper function removes any duplicates from a list """ # return list(set(input_list)) return list(OrderedDict.fromkeys(input_list)) def get_variables(self, condition_sources, state): variable_list = list() for item in condition_sources: if isinstance(item, dict) and "var" in item: variable_list.append(item) elif isinstance(item, dict) and "list" in item: variable_list += self.get_variables(item["list"], state) elif isinstance(item, list): variable_list += self.get_variables(item, state) elif "call" in item: function_dict = item["call"] if function_dict["function"] == "abs": for x in function_dict["inputs"]: variable_list += self.get_variables(x, state) elif "__str__" in function_dict["function"]: var_name = function_dict["function"].split(".")[0] var_node = [ { "var": { "variable": var_name, "index": state.last_definitions.get( var_name, -1 ), } } ] variable_list += var_node elif "get_" in function_dict["function"]: var_name = function_dict["function"].split(".")[0] var_node = [ { "var": { "variable": var_name, "index": state.last_definitions.get( var_name, -1 ), } } ] variable_list += var_node for x in function_dict["inputs"]: variable_list += self.get_variables(x, state) # TODO: Will have to add other if cases for other string # types here # Remove any duplicate dictionaries from the list. This is done to # preserve ordering. # Reference: https://www.geeksforgeeks.org/ # python-removing-duplicate-dicts-in-list/ variable_list = [ i for n, i in enumerate(variable_list) if i not in variable_list[n + 1 :] ] return variable_list @staticmethod def _get_decision_inputs(if_body_outputs, updated_vars): """ This is a helper function that converts the updated dictionary of variables in the if-containers into a form that is easier to process for finding the decision tags """ decision_inputs = {} condition_var_regex = re.compile(r"COND_\d+_\d+") for var in updated_vars: if not condition_var_regex.match(var): decision_inputs[var] = [] for var in decision_inputs: condition_index_list = [] condition_index_map = {} for item, value in if_body_outputs.items(): if var in value: condition_index_map[item] = int(value[var]) if item: condition_index_list.append( int(item.rsplit("_", 1)[1]) ) else: condition_index_list.append(-1) decision_inputs[var].append(condition_index_map) decision_inputs[var].append(condition_index_list) return decision_inputs def _generate_decision_lambda( self, decision_versions: list, condition_var: str, max_conditions: int, var: str, argument_map: dict, ): """ This helper function generates the lambda function code for decision statements of if clauses. """ code = "" (cond_tuples, var_indices) = decision_versions if not self.use_numpy: if cond_tuples[0][0] is None: cond_var = argument_map[f"{condition_var}_0_0"] if_var = argument_map[f"{var}_0"] else_var = argument_map[f"{var}_xx"] return f"{if_var} if not {cond_var} else {else_var}" for cond_data in cond_tuples: (cond_name, var_idx) = cond_data var_arg = argument_map[f"{var}_{var_idx}"] if cond_name is None: code += f"{var_arg}" return code cond_arg = argument_map[f"{cond_name}_0"] code += f"{var_arg} if {cond_arg} else " if f"{var}_xx" in argument_map: else_var_name = argument_map[f"{var}_xx"] else: else_var_name = "None" code += f"{else_var_name}" return code else: # Use a where statement if this conditional is a simple if ... else if len(cond_tuples) == 2 and cond_tuples[-1][0] is None: cond_name = cond_tuples[0][0] cond_arg = argument_map[f"{cond_name}_0"] var_if = argument_map[f"{var}_{cond_tuples[0][1]}"] var_else = argument_map[f"{var}_{cond_tuples[-1][1]}"] return f"np.where({cond_arg},{var_if},{var_else})" if cond_tuples[0][0] is None: cond_var = argument_map[f"{condition_var}_0_0"] if_var = argument_map[f"{var}_0"] else_var = argument_map[f"{var}_xx"] return f"np.where(~({cond_var}),{if_var},{else_var})" (cond_names, var_indices) = map(list, zip(*cond_tuples)) cond_list = ",".join( [argument_map[f"{cond_var}_0"] for cond_var in cond_names] ) var_list = ",".join( [argument_map[f"{var}_{v}"] for v in var_indices] ) if f"{var}_xx" in argument_map: var_else = argument_map[f"{var}_xx"] else: var_else = "0" return f"np.select([{cond_list}],[{var_list}],default={var_else})" def _generate_argument_map(self, inputs): """ This function generates a different mapping of the arguments to the lambda function for decision statements. For every variable, the indexing starts from 0 and increases accordingly in the inputs list """ cond_count = 0 var_count = 0 arg_map = {} for ip in inputs: (var, _) = ip.split("_", 1) if var == "COND": arg_map[ip] = f"{var}_{cond_count}" cond_count += 1 else: arg_map[ip] = f"{var}_{var_count}" var_count += 1 return arg_map @staticmethod def _merge_container_body(container_body, container_decisions): """ This function merges the container body of if containers so that every condition and assignment statement is inside a single list. This list is then suffixed with the decisions statements """ final_body = [] for item in container_body: if item["condition"]: final_body += item["condition"] final_body += item["statements"] final_body += container_decisions return final_body @staticmethod def _fix_input_index(statement_list): """ For every statement list of a condition in `if-containers`, all inputs should start from -1 and increase accordingly. This function does the work of checking if such changes need to be for every statement list """ output_list = [] for stmt in statement_list: input_list = stmt["input"] for index in range(len(input_list)): var_parts = input_list[index].split("::") if ( var_parts[1] not in output_list and int(var_parts[-1]) != -1 ): var_parts[-1] = "-1" input_list[index] = "::".join(var_parts) output_list += [x.split("::")[1] for x in stmt["output"]] def get_path(file_name: str, instance: str): """ This function returns the path of a file starting from the root of the delphi repository. The returned path varies depending on whether it is for a namespace or a source variable, which is denoted by the `instance` argument variable. It is important to note that the path refers to that of the original system being analyzed i.e. the Fortran code and not the intermediate Python file which is used to generate the AST. """ if instance == "source": source_match = re.match(r"[./]*(.*)", file_name) assert source_match, ( f"Original Fortran source file for {file_name} " f"not found." ) return source_match.group(1) elif instance == "namespace": source_match = re.match(r"[./]*(.*)\.", file_name) assert source_match, f"Namespace path for {file_name} not found." return source_match.group(1).split("/") else: assert False, f"Error when trying to get the path of file {file_name}." def dump_ast( node, annotate_fields=True, include_attributes=False, indent=" " ): """ Return a formatted dump of the tree in *node*. This is mainly useful for debugging purposes. The returned string will show the names and the values for fields. This makes the code impossible to evaluate, so if evaluation is wanted *annotate_fields* must be set to False. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, *include_attributes* can be set to True. """ def _format(ast_node, level=0): if isinstance(ast_node, ast.AST): fields = [ (a, _format(b, level)) for a, b in ast.iter_fields(ast_node) ] if include_attributes and ast_node._attributes: fields.extend( [ (a, _format(getattr(ast_node, a), level)) for a in ast_node._attributes ] ) return "".join( [ ast_node.__class__.__name__, "(", ", ".join( ("%s=%s" % field for field in fields) if annotate_fields else (b for a, b in fields) ), ")", ] ) elif isinstance(ast_node, list): lines = ["["] lines.extend( ( indent * (level + 2) + _format(x, level + 2) + "," for x in ast_node ) ) if len(lines) > 1: lines.append(indent * (level + 1) + "]") else: lines[-1] += "]" return "\n".join(lines) return repr(ast_node) if not isinstance(node, ast.AST): raise TypeError("expected AST, got %r" % node.__class__.__name__) return _format(node) def process_comments(source_comment_dict, generator_object): """ This function replaces the keys in the source comments that are function names in the source files into their container id name. """ grfn_argument_map = generator_object.function_argument_map for key in source_comment_dict: if key in grfn_argument_map: source_comment_dict[ grfn_argument_map[key]["name"] ] = source_comment_dict.pop(key) return source_comment_dict # noinspection PyDefaultArgument def create_grfn_dict( lambda_file: str, python_source_string: str, file_name: str, mode_mapper_dict: list, original_file: str, mod_log_file_path: str, comments: dict, module_file_exist=False, module_import_paths={}, ) -> Dict: """ Create a Python dict representing the GrFN, with additional metadata for JSON output. """ generator = GrFNGenerator() generator.original_python_src = python_source_string asts = [ast.parse(python_source_string)] # print(dump_ast(asts[-1])) lambda_string_list = [ "from numbers import Real\n", "from random import random\n", "import numpy as np\n", "from automates.program_analysis.for2py.strings import *\n", "from automates.program_analysis.for2py import intrinsics\n", "from automates.program_analysis.for2py.arrays import *\n", "from dataclasses import dataclass\n", "import automates.program_analysis.for2py.math_ext as math\n\n", ] state = GrFNState(lambda_string_list) generator.mode_mapper = mode_mapper_dict[0] # Populate list of modules that the program imports for mod in generator.mode_mapper["modules"]: if mod != "main": generator.module_names.append(mod) generator.fortran_file = original_file generator.comments = comments # Currently, we are specifying the module file with # a prefix "m_", this may be changed in the future. # If it requires a change, simply modify this below prefix. module_file_prefix = "m_" with open(mod_log_file_path) as json_f: module_logs = json.load(json_f) # Load module summary on memory for later use generator.module_summary = module_logs["mod_info"] try: filename_regex = re.compile(r"(?P<path>.*/)(?P<filename>.*).py") file_match = re.match(filename_regex, file_name) assert file_match, f"Can't match filename to any format: {file_name}" path = file_match.group("path") filename = file_match.group("filename") # Since we do not have separate variable pickle file # for m_*.py, we need to use the original program pickle # file that module resides. module_name = None if module_file_exist: module_file_path = file_name # Ignoring the module file prefix module_name = filename[len(module_file_prefix) :] org_file = get_original_file_name(original_file) file_name = path + org_file else: file_name = path + filename with open(f"{file_name}_variable_map.pkl", "rb") as f: variable_map = pickle.load(f) generator.variable_map = variable_map except IOError: raise For2PyError(f"Unable to read file {file_name}.") # Extract variables with type that are declared in module generator.module_variable_types = mode_mapper_dict[0]["symbol_types"] # Extract functions (and subroutines) declared in module for module in mode_mapper_dict[0]["subprograms"]: for subp in mode_mapper_dict[0]["subprograms"][module]: generator.module_subprograms.append(subp) if module in module_logs["mod_info"]: module_logs["mod_info"][module]["symbol_types"][subp] = "func" for module in mode_mapper_dict[0]["imports"]: for subm in mode_mapper_dict[0]["imports"][module]: import_module_name = list(subm.keys())[0] import_function_list = subm[import_module_name] if ( not import_function_list and import_module_name in module_logs["mod_info"] ): symbols = module_logs["mod_info"][import_module_name][ "symbol_types" ] for key, value in symbols.items(): if value == "func": generator.module_subprograms.append(key) generator.module_subprograms.extend(import_function_list) # Generate GrFN with an AST generated from Python IR. grfn = generator.gen_grfn(asts, state, "")[0] if len(generator.mode_mapper["use_mapping"]) > 0: for user, module in generator.mode_mapper["use_mapping"].items(): if (user in generator.module_names) or ( module_name and module_name == user ): module_paths = [] for import_mods in module: for mod_name, target in import_mods.items(): module_path = ( path + module_file_prefix + mod_name + "_AIR.json" ) module_paths.append(module_path) module_import_paths[user] = module_paths # If the GrFN has a `start` node, it will refer to the name of the # PROGRAM module which will be the entry point of the GrFN. if grfn.get("start"): grfn["start"] = [grfn["start"][0]] elif generator.function_definitions: # TODO: The `grfn_spec` mentions this to be null (None) but it looks # like `networks.py` requires a certain function. Finalize after # `networks.py` is completed. # grfn["start"] = None grfn["start"] = [generator.function_definitions[-1]] else: grfn["start"] = None # Add the placeholder to enter the grounding and link hypothesis information grfn["grounding"] = [] # TODO Add a placeholder for `types`. This will have to be populated when # user defined types start appearing. grfn["types"] = generator.derived_types_grfn # Get the file path of the original Fortran code being analyzed source_file = get_path(original_file, "source") # TODO Hack: Currently only the file name is being displayed as the # source in order to match the handwritten SIR model GrFN JSON. Since # the directory of the `SIR-Gillespie-SD_inline.f` file is the root, # it works for this case but will need to be generalized for other cases. file_path_list = source_file.split("/") grfn["source"] = [file_path_list[-1]] # Get the source comments from the original Fortran source file. source_file_comments = get_comments(original_file) comment_dict = process_comments(dict(source_file_comments), generator) source_comments = comment_dict grfn["source_comments"] = source_comments # dateCreated stores the date and time on which the lambda and GrFN files # were created. It is stored in the YYYMMDD format grfn["date_created"] = f"{datetime.utcnow().isoformat("T")}Z" # If some fields are not present, add an empty one if not grfn.get("containers"): grfn["containers"] = [] if not grfn.get("variables"): grfn["variables"] = [] # with open(lambda_file, "w") as lambda_fh: # lambda_fh.write("".join(lambda_string_list)) with open(mod_log_file_path, "w+") as json_f: json_f.write(json.dumps(module_logs, indent=2)) del state return grfn def generate_ast(filename: str): """ This function generates the AST of a python file using Python's ast module. """ return ast.parse(tokenize.open(filename).read()) def get_asts_from_files(file_list: List[str], printast=False) -> List: """ This function returns the AST of each python file in the python_file_list. """ ast_list = [] for file in file_list: ast_list.append(generate_ast(file)) if printast: # If the printAst flag is set, print the AST to console print(dump_ast(ast_list[-1])) return ast_list def get_system_name(pyfile_list: List[str]): """ This function returns the name of the system under analysis. Generally, the system is the one which is not prefixed by `m_` (which represents modules). """ system_name = None path = None for file in pyfile_list: if not file.startswith("m_"): system_name_match = re.match(r".*/(.*)\.py", file) assert system_name_match, f"System name for file {file} not found." system_name = system_name_match.group(1) path_match = re.match(r"(.*)/.*", file) assert path_match, "Target path not found" path = path_match.group(1) if not (system_name or path): assert False, ( f"Error when trying to find the system name of the " f"analyzed program." ) return system_name, path def generate_system_def( python_list: List[str], module_grfn_list: List[str], import_grfn_paths: List[str], module_logs: Dict, original_file_path: str, ): """ This function generates the system definition for the system under analysis and writes this to the main system file. """ (system_name, path) = get_system_name(python_list) system_filepath = f"{path}/system.json" module_name_regex = re.compile( r"(?P<path>.*/)m_(" r"?P<module_name>.*)_AIR.json" ) grfn_components = [] for module_grfn in module_grfn_list: code_sources = [] module_match = re.match(module_name_regex, module_grfn) if module_match: module_name = module_match.group("module_name") if module_name in module_logs["mod_to_file"]: for path in module_logs["mod_to_file"][module_name]: code_sources.append(path) if not code_sources: code_sources.append(original_file_path) grfn_components.append( { "grfn_source": module_grfn, "code_source": code_sources, "imports": [], } ) for grfn in import_grfn_paths: for path in import_grfn_paths[grfn]: if ( path not in grfn_components[0]["imports"] and path != module_grfn ): grfn_components[0]["imports"].append(path) system_def = {"name": system_name, "components": grfn_components} if os.path.isfile(system_filepath): with open(system_filepath, "r") as f: systems_def = json.load(f) systems_def["systems"].append(system_def) else: systems_def = {"systems": [system_def]} return system_def def process_files( python_list: List[str], grfn_tail: str, lambda_tail: str, original_file_path: str, print_ast_flag=False, ): """ This function takes in the list of python files to convert into GrFN and generates each file's AST along with starting the GrFN generation process. """ module_file_exist = False module_mapper = {} grfn_filepath_list = [] ast_list = get_asts_from_files(python_list, print_ast_flag) # Regular expression to identify the path and name of all python files filename_regex = re.compile(r"(?P<path>.*/)(?P<filename>.*).py") # First, find the main python file in order to populate the module # mapper for item in python_list: file_match = re.match(filename_regex, item) assert file_match, "Invalid filename." path = file_match.group("path") filename = file_match.group("filename") # Ignore all Python files of modules created by `pyTranslate.py` # since these module files do not contain a corresponding XML file. if not filename.startswith("m_"): xml_file = f"{path}rectified_{filename}.xml" # Calling the `get_index` function in `mod_index_generator.py` to # map all variables and objects in the various files else: module_file_exist = True file_name = get_original_file_name(original_file_path) xml_file = f"{path}rectified_{file_name}.xml" # Calling the `get_index` function in `mod_index_generator.py` to # map all variables and objects in the various files module_mapper = get_index(xml_file) module_import_paths = {} for index, ast_string in enumerate(ast_list): lambda_file = python_list[index][:-3] + "_" + lambda_tail grfn_file = python_list[index][:-3] + "_" + grfn_tail grfn_dict = create_grfn_dict( lambda_file, [ast_string], python_list[index], module_mapper, original_file_path, module_file_exist, module_import_paths, ) if module_file_exist: main_python_file = path + file_name + ".py" python_list[index] = main_python_file grfn_filepath_list.append(grfn_file) # Write each GrFN JSON into a file with open(grfn_file, "w") as file_handle: file_handle.write(json.dumps(grfn_dict, sort_keys=True, indent=2)) def get_original_file_name(original_file_path): original_file = original_file_path.split("/") return original_file[-1].split(".")[0] if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "-f", "--files", nargs="+", required=True, help="A list of python files to generate a PGM for", ) parser.add_argument( "-p", "--grfn_suffix", nargs=1, required=True, help="Filename for the output PGM", ) parser.add_argument( "-l", "--lambda_suffix", nargs=1, required=True, help="Filename for output lambda functions", ) parser.add_argument( "-o", "--out", nargs=1, required=True, help="Text file containing the list of output python files being " "generated", ) parser.add_argument( "-a", "--print_ast", action="store_true", required=False, help="Print ASTs", ) parser.add_argument( "-g", "--original_file", nargs=1, required=True, help="Filename of the original Fortran file", ) arguments = parser.parse_args(sys.argv[1:]) # Read the outputFile which contains the name of all the python files # generated by `pyTranslate.py`. Multiple files occur in the case of # modules since each module is written out into a separate python file. with open(arguments.out[0], "r") as f: python_files = f.read() # The Python file names are space separated. Append each one to a list. python_file_list = python_files.rstrip().split(" ") grfn_suffix = arguments.grfn_suffix[0] lambda_suffix = arguments.lambda_suffix[0] fortran_file = arguments.original_file[0] print_ast = arguments.print_ast process_files( python_file_list, grfn_suffix, lambda_suffix, fortran_file, print_ast )
#!/usr/bin/python3.6 import ast import sys import tokenize import pickle from datetime import datetime import re import argparse from functools import reduce import json from .genCode import genCode, PrintState from .mod_index_generator import get_index from .get_comments import get_comments from . import For2PyError from . import syntax from typing import List, Dict, Iterable, Optional from collections import OrderedDict from itertools import chain, product import operator import uuid import os.path # noinspection PyDefaultArgument class GrFNState: def __init__( self, lambda_strings: Optional[List[str]], last_definitions: Optional[Dict] = {}, next_definitions: Optional[Dict] = {}, last_definition_default=0, function_name=None, variable_types: Optional[Dict] = {}, start: Optional[Dict] = {}, scope_path: Optional[List] = [], arrays: Optional[Dict] = {}, array_types: Optional[Dict] = {}, array_assign_name: Optional = None, string_assign_name: Optional = None, ): self.lambda_strings = lambda_strings self.last_definitions = last_definitions self.next_definitions = next_definitions self.last_definition_default = last_definition_default self.function_name = function_name self.variable_types = variable_types self.start = start self.scope_path = scope_path self.arrays = arrays self.array_types = array_types self.array_assign_name = array_assign_name self.string_assign_name = string_assign_name def copy( self, lambda_strings: Optional[List[str]] = None, last_definitions: Optional[Dict] = None, next_definitions: Optional[Dict] = None, last_definition_default=None, function_name=None, variable_types: Optional[Dict] = None, start: Optional[Dict] = None, scope_path: Optional[List] = None, arrays: Optional[Dict] = None, array_types: Optional[Dict] = None, array_assign_name: Optional = None, string_assign_name: Optional = None, ): return GrFNState( self.lambda_strings if lambda_strings is None else lambda_strings, self.last_definitions if last_definitions is None else last_definitions, self.next_definitions if next_definitions is None else next_definitions, self.last_definition_default if last_definition_default is None else last_definition_default, self.function_name if function_name is None else function_name, self.variable_types if variable_types is None else variable_types, self.start if start is None else start, self.scope_path if scope_path is None else scope_path, self.arrays if arrays is None else arrays, self.array_types if array_types is None else array_types, self.array_assign_name if array_assign_name is None else array_assign_name, self.string_assign_name if string_assign_name is None else string_assign_name, ) # noinspection PyDefaultArgument,PyTypeChecker class GrFNGenerator(object): def __init__(self, annotated_assigned=[], function_definitions=[]): self.annotated_assigned = annotated_assigned self.function_definitions = function_definitions self.use_numpy = True self.fortran_file = None self.exclude_list = [] self.loop_input = [] self.comments = {} self.update_functions = {} self.mode_mapper = {} self.name_mapper = {} self.variable_map = {} self.function_argument_map = {} # Holds all declared arrays {symbol:domain} self.arrays = {} # Holds declared array types {symbol:type} self.array_types = {} self.array_assign_name = None # Holds a list of multi-dimensional array symbols self.md_array = [] # Holds all the string assignments along with their length self.strings = {} self.outer_count = 0 self.types = (list, ast.Module, ast.FunctionDef) self.current_scope = "global" self.loop_index = -1 self.parent_loop_state = None self.parent_if_state = None self.handling_f_args = True self.f_array_arg = [] # {symbol:index} self.updated_arrays = {} # {symbol: [_list_of_domains_]} # This mapping is required as there may be # a multiple array passes to the function # argument and we do not want to replace one # with another. We need to update all function # argument domains for arrays self.array_arg_domain = {} # Holds list of modules that program references self.module_variable_types = {} # Holds the list of declared subprograms in modules self.module_subprograms = [] # Holds module names self.module_names = [] # List of generated lambda function def. names self.generated_lambda_functions = [] # List of user-defined (derived) types self.derived_types = [] # List of derived type grfns self.derived_types_grfn = [] # List of attributes declared under user-defined types self.derived_types_attributes = {} # List of variables (objects) declared with user-defined type self.derived_type_objects = {} # Currently handling derived type object name self.current_d_object_name = None # Currently handling derived type object's accessing attributes self.current_d_object_attributes = [] self.is_d_object_array_assign = False self.elseif_flag = False self.if_index = -1 self.elif_index = 0 self.module_summary = None self.global_scope_variables = {} self.exit_candidates = [] self.global_state = None self.imported_module = [] self.imported_module_paths = [] self.original_python_src = "" self.generated_import_codes = [] self.global_grfn = { "containers": [ { "name": None, "source_refs": [], "gensym": None, "arguments": [], "updated": [], "return_value": [], "body": [], } ], "variables": [], } self.gensym_tag_map = { "container": "c", "variable": "v", "function": "f", } self.type_def_map = { "real": "float", "integer": "integer", "string": "string", "bool": "boolean", "Array": "Array", "character": "string", "String": "string", } # The binops dictionary holds operators for all the arithmetic and # comparative functions self.binops = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.Pow: operator.pow, ast.Eq: operator.eq, ast.LtE: operator.le, } # The annotate_map dictionary is used to map Python ast data types # into data types for the lambdas self.annotate_map = { "NoneType": "undefined", "real": "Real", "float": "real", "Real": "real", "integer": "int", "int": "integer", "string": "str", "str": "string", "array": "[]", "list": "array", "bool": "bool", "file_handle": "fh", "Array": "Array", "String": "string", } # Arithmetic operator dictionary # TODO: Complete the list self.arithmetic_ops = { "Add": "+", "Sub": "-", "Div": "/", "Mult": "*", "+": "+", "-": "-", "/": "/", "*": "*", } # The unnecessary_types tuple holds the ast types to ignore self.unnecessary_types = ( ast.Mult, ast.Add, ast.Sub, ast.Pow, ast.Div, ast.USub, ast.Eq, ast.LtE, ) # List of helper library types self.library_types = ["Array", "String"] # Regular expression to match python statements that need to be # bypassed in the GrFN and lambda files. Currently contains I/O # statements. self.bypass_io = ( r"^format_\d+$|^format_\d+_obj$|^file_\d+$|^file_\w+$" r"|^write_list_\d+$|^write_line$|^format_\d+_obj" r".*|^Format$|^list_output_formats$|" r"^write_list_stream$|^file_\d+\.write$|^file_\w+\.write$" r"^output_fmt$" ) self.re_bypass_io = re.compile(self.bypass_io, re.I) self.process_grfn = { "ast.FunctionDef": self.process_function_definition, "ast.arguments": self.process_arguments, "ast.arg": self.process_arg, "ast.Load": self.process_load, "ast.Store": self.process_store, "ast.Index": self.process_index, "ast.Constant": self.process_constant, "ast.Num": self.process_num, "ast.List": self.process_list_ast, "ast.Str": self.process_str, "ast.For": self.process_for, "ast.If": self.process_if, "ast.UnaryOp": self.process_unary_operation, "ast.BinOp": self.process_binary_operation, "ast.BoolOp": self.process_boolean_operation, "ast.Expr": self.process_expression, "ast.Compare": self.process_compare, "ast.Subscript": self.process_subscript, "ast.Name": self.process_name, "ast.AnnAssign": self.process_annotated_assign, "ast.Assign": self.process_assign, "ast.Tuple": self.process_tuple, "ast.Call": self.process_call, "ast.Module": self.process_module, "ast.Attribute": self.process_attribute, "ast.AST": self.process_ast, "ast.NameConstant": self._process_nameconstant, "ast.Return": self.process_return_value, "ast.While": self.process_while, "ast.Break": self.process_break, "ast.ClassDef": self.process_class_def, "ast.Try": self.process_try, } def gen_grfn(self, node, state, call_source): """ This function generates the GrFN structure by parsing through the python AST """ # Look for code that is not inside any function. if state.function_name is None and not any( isinstance(node, t) for t in self.types ): # If the node is of instance ast.Call, it is the starting point # of the system. node_name = node.__repr__().split()[0][2:] if ( isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id != "String" and node.func.id not in self.derived_types ): start_function_name = self.generate_container_id_name( self.fortran_file, ["@global"], node.func.id ) return [{"start": start_function_name}] elif isinstance(node, ast.Expr): if ( isinstance(node.value, ast.Call) and isinstance(node.value.func, ast.Attribute) and node.value.func.attr == "set_" ): return self.process_grfn[node_name]( node, state, call_source ) else: return self.gen_grfn(node.value, state, "start") elif isinstance(node, ast.If): return self.gen_grfn(node.body, state, "start") else: if node_name != "ast.Import" and node_name != "ast.ImportFrom": return self.process_grfn[node_name]( node, state, call_source ) else: # Check if this is a module that is imported if ( node_name == "ast.ImportFrom" and "m_" in node.module.split(".")[-1] ): imported_module = node.module.split(".")[-1][2:] self.imported_module.append(imported_module) self.imported_module_paths.append(node.module) self.derived_types.extend( self.module_summary[imported_module][ "derived_type_list" ] ) # Comment it out for now to avoid "import *" case. # state.lambda_strings.insert(0, f"from {node.module} # import *\n") return [] elif isinstance(node, list): return self.process_list(node, state, call_source) elif any( isinstance(node, node_type) for node_type in self.unnecessary_types ): return self.process_unnecessary_types(node, state, call_source) else: node_name = node.__repr__().split()[0][2:] if self.process_grfn.get(node_name): return self.process_grfn[node_name](node, state, call_source) else: return self.process_nomatch(node, state, call_source) def process_list(self, node, state, call_source): """ If there are one or more ast nodes inside the `body` of a node, they appear as a list. Process each node in the list and chain them together into a single list of GrFN dictionaries. """ # result = [] # for cur in node: # tmp = self.gen_grfn(cur, state, call_source) # result.append(tmp) # return list(chain.from_iterable(result)) return list( chain.from_iterable( [self.gen_grfn(cur, state, call_source) for cur in node] ) ) def process_function_definition(self, node, state, *_): """ This function processes the function definition i.e. functionDef instance. It appends GrFN dictionaries to the `functions` key in the main GrFN JSON. These dictionaries consist of the function_assign_grfn of the function body and the function_container_grfn of the function. Every call to this function adds these along with the identifier_spec_grfn to the main GrFN JSON. """ self.module_names.append(node.name) return_value = [] return_list = [] local_last_definitions = state.last_definitions.copy() local_next_definitions = state.next_definitions.copy() local_variable_types = state.variable_types.copy() scope_path = state.scope_path.copy() # If the scope_path is empty, add @global to the list to denote that # this is the outermost scope if len(scope_path) == 0: scope_path.append("@global") if node.decorator_list: # This is still a work-in-progress function since a complete # representation of SAVEd variables has not been decided for GrFN. # Currently, if the decorator function is static_vars (for # SAVEd variables), their types are loaded in the variable_types # dictionary. function_state = state.copy( last_definitions=local_last_definitions, next_definitions=local_next_definitions, function_name=node.name, variable_types=local_variable_types, ) self.process_decorators(node.decorator_list, function_state) # Check if the function contains arguments or not. This determines # whether the function is the outermost scope (does not contain # arguments) or it is not (contains arguments). For non-outermost # scopes, indexing starts from -1 (because all arguments will have # an index of -1). For outermost scopes, indexing starts from # normally from 0. # TODO: What do you do when a non-outermost scope function does not # have arguments. Current assumption is that the function without # arguments is the outermost function i.e. call to the `start` # function. But there can be functions without arguments which are not # the `start` functions but instead some inner functions. # The following is a test to make sure that there is only one # function without arguments and that is the outermost function. All # of the models that we currently handle have this structure and # we'll have to think about how to handle cases that have more than # one non-argument function. if len(node.args.args) == 0: self.outer_count += 1 assert self.outer_count == 1, ( "There is more than one function " "without arguments in this system. " "This is not currently handled." ) function_state = state.copy( last_definitions=local_last_definitions, next_definitions=local_next_definitions, function_name=node.name, variable_types=local_variable_types, last_definition_default=0, ) else: function_state = state.copy( last_definitions={}, next_definitions={}, function_name=node.name, variable_types=local_variable_types, last_definition_default=-1, ) # Copy the states of all the global variables into the global state # holder if not self.global_scope_variables and self.current_scope == "global": self.global_scope_variables = state.copy( last_definitions=local_last_definitions, next_definitions=local_next_definitions, function_name=node.name, variable_types=local_variable_types, last_definition_default=0, ) # Get the list of arguments from the function definition argument_list = self.gen_grfn(node.args, function_state, "functiondef") # Keep a map of the arguments for each function. This will be used in # `process_for` to identify arguments which are function arguments # from those that are not self.function_argument_map[node.name] = { "name": "", "updated_list": "", "updated_indices": [], "argument_list": "", "argument_indices": [], } self.function_argument_map[node.name]["argument_list"] = argument_list # Update the current scope so that for every identifier inside the # body, the scope information is updated self.current_scope = node.name # Create the variable definition for the arguments argument_variable_grfn = [] self.handling_f_args = True for argument in argument_list: argument_variable_grfn.append( self.generate_variable_definition( [argument], None, False, function_state ) ) self.handling_f_args = False # Generate the `variable_identifier_name` for each container argument. # TODO Currently only variables are handled as container arguments. # Create test cases of other containers as container arguments and # extend this functionality. argument_list = [ f"@variable::{x}::{function_state.last_definitions[x]}" for x in argument_list ] # Enter the body of the function and recursively generate the GrFN of # the function body body_grfn = self.gen_grfn(node.body, function_state, "functiondef") # Get the `return_value` from the body. We want to append it separately. # TODO There can be multiple return values. `return_value` should be # a list and you should append to it. for body in body_grfn: for function in body["functions"]: if ( function.get("function") and function["function"]["type"] == "return" ): return_value = function["value"] # Remove the return_value function body from the main # body as we don't need that anymore body["functions"].remove(function) # TODO The return value cannot always be a `variable`. It can be # literals as well. Add that functionality here. if return_value: for value in return_value: if "var" in value: return_list.append( f"@variable::{value['var']['variable']}" f"::{value['var']['index']}" ) elif "call" in value: for _ in value["call"]["inputs"]: if "var" in value: return_list.append( f"@variable::{value['var']['variable']}::" f"{value['var']['index']}" ) return_list = list(set(return_list)) else: return_list = [] # Get the function_reference_spec, function_assign_spec and # identifier_spec for the function ( function_variable_grfn, function_assign_grfn, body_container_grfn, ) = self._get_variables_and_functions(body_grfn) # Combine the variable grfn of the arguments with that of the # container body container_variables = argument_variable_grfn + function_variable_grfn # Find the list of updated identifiers if argument_list: updated_identifiers = self._find_updated( argument_variable_grfn, function_variable_grfn, self.f_array_arg, function_state, ) for array in self.f_array_arg: if array in function_state.last_definitions: self.updated_arrays[ array ] = function_state.last_definitions[array] else: updated_identifiers = [] self.function_argument_map[node.name][ "updated_list" ] = updated_identifiers # Get a list of all argument names argument_name_list = [] for item in argument_list: argument_name_list.append(item.split("::")[1]) # Now, find the indices of updated arguments for arg in updated_identifiers: updated_argument = arg.split("::")[1] argument_index = argument_name_list.index(updated_argument) self.function_argument_map[node.name]["updated_indices"].append( argument_index ) # Some arguments to a function are output variables i.e. they are not # used as inputs to a operation but are actually updated within the # function. The reason for this is that Fortran/C design pattern of # passing variables by reference to a callee subroutine so that there # values can be populated by the callee subroutine and then used by # the caller subroutine after the callee returns # We need to remove these inputs from the argument_list old_args = [x for x in argument_list] self._remove_output_variables(argument_list, body_grfn) # Update the arguments in the function map as well self.function_argument_map[node.name]["argument_list"] = argument_list # Now, find the indices of argument variables that have been included # in the final list i.e. those that are actual inputs to the function for idx in range(len(old_args)): if old_args[idx] in argument_list: self.function_argument_map[node.name][ "argument_indices" ].append(idx) # Create a gensym for the function container container_gensym = self.generate_gensym("container") container_id_name = self.generate_container_id_name( self.fortran_file, scope_path, node.name ) self.function_argument_map[node.name]["name"] = container_id_name # Add the function name to the list that stores all the functions # defined in the program self.function_definitions.append(container_id_name) function_container_grfn = { "name": container_id_name, "source_refs": [], "gensym": container_gensym, "type": "function", "arguments": argument_list, "updated": updated_identifiers, "return_value": return_list, "body": function_assign_grfn, } function_container_grfn = [ function_container_grfn ] + body_container_grfn # function_assign_grfn.append(function_container_grfn) pgm = { "containers": function_container_grfn, "variables": container_variables, } return [pgm] def process_arguments(self, node, state, call_source): """ This function returns a list of arguments defined in a function definition. `node.args` is a list of `arg` nodes which are iteratively processed to get the argument name. """ return [self.gen_grfn(arg, state, call_source) for arg in node.args] def process_arg(self, node, state, call_source): """ This function processes a function argument. """ # Variables are declared as List() objects in the intermediate Python # representation in order to mimic the pass-by-reference property of # Fortran. So, arguments have `annotations` which hold the type() of # A the variable i.e. x[Int], y[Float], etc. assert ( node.annotation ), "Found argument without annotation. This should not happen." state.variable_types[node.arg] = self.get_variable_type( node.annotation ) # Check if an argument is a string annotation_name = node.annotation.__repr__().split()[0][2:] if annotation_name == "ast.Name" and node.annotation.id == "String": self.strings[node.arg] = { "length": "Undefined", "annotation": False, "annotation_assign": True, } if state.last_definitions.get(node.arg) is None: if call_source == "functiondef": if node.arg not in self.updated_arrays: state.last_definitions[node.arg] = -1 else: state.last_definitions[node.arg] = self.updated_arrays[ node.arg ] else: assert False, ( "Call source is not ast.FunctionDef. " "Handle this by setting state.last_definitions[" "node.arg] = 0 in place of the assert False. " "But this case should not occur in general." ) else: assert False, ( "The argument variable was already defined " "resulting in state.last_definitions containing an " "entry to this argument. Resolve this by setting " "state.last_definitions[node.arg] += 1. But this " "case should not occur in general." ) return node.arg def process_index(self, node, state, *_): """ This function handles the Index node of the ast. The Index node is a `slice` value which appears when a `[]` indexing occurs. For example: x[Real], a[0], etc. So, the `value` of the index can either be an ast.Name (x[Real]) or an ast.Num (a[0]), or any other ast type. So, we forward the `value` to its respective ast handler. """ self.gen_grfn(node.value, state, "index") def process_constant(self, node, *_): data_type = self.annotate_map.get(type(node.value).__name__) if data_type: # TODO Change this format. Since the spec has changed, # this format is no longer required. Go for a simpler format. return [{"type": "literal", "dtype": data_type, "value": node.value}] else: assert False, f"Unidentified data type of variable: {node.value}" def process_num(self, node, *_): """ This function handles the ast.Num of the ast tree. This node only contains a numeric value in its body. For example: Num(n=0), Num(n=17.27), etc. So, we return the numeric value in a <function_assign_body_literal_spec> form. """ data_type = self.annotate_map.get(type(node.n).__name__) if data_type: # TODO Change this format. Since the spec has changed, # this format is no longer required. Go for a simpler format. return [{"type": "literal", "dtype": data_type, "value": node.n}] else: assert False, f"Unidentified data type of variable: {node.n}" def process_list_ast(self, node, state, *_): """ This function handles ast.List which represents Python lists. The ast.List has an `elts` element which is a list of all the elements of the list. This is most notably encountered in annotated assignment of variables to [None] (Example: day: List[int] = [ None]). This is handled by calling `gen_grfn` on every element of the list i.e. every element of `elts`. """ # Currently, this function is encountered only for annotated # assignments of the form, a: List[float] = [None], b: List[float] = # [100], c: List[float] = [(x[0]*y[0])], etc. If any further cases # arise, the following code might need to be rewritten and the # following return code will have to be added as well. # return elements if len(elements) == 1 else [{"list": elements}] element_grfn = [] for list_element in node.elts: element_grfn.append(self.gen_grfn(list_element, state, "List")) return element_grfn @staticmethod def process_str(node, *_): """ This function handles the ast.Str of the ast tree. This node only contains a string value in its body. For example: Str(s='lorem'), Str(s='Estimate: '), etc. So, we return the string value in a <function_assign_body_literal_spec> form where the dtype is a string. """ # TODO: According to new specification, the following structure # should be used: {"type": "literal, "value": {"dtype": <type>, # "value": <value>}}. Confirm with Clay. return [{"type": "literal", "dtype": "string", "value": node.s}] def process_for(self, node, state, *_): """ This function handles the ast.For node of the AST. """ # Update the scope scope_path = state.scope_path.copy() if len(scope_path) == 0: scope_path.append("@global") scope_path.append("loop") # Check: Currently For-Else on Python is not supported if self.gen_grfn(node.orelse, state, "for"): raise For2PyError("For/Else in for not supported.") # Initialize intermediate variables container_argument = [] container_return_value = [] container_updated = [] function_output = [] function_updated = [] function_input = [] loop_condition_inputs = [] loop_condition_inputs_lambda = [] loop_variables_grfn = [] loop_functions_grfn = [] # Increment the loop index universally across the program if self.loop_index > -1: self.loop_index += 1 else: self.loop_index = 0 # First, get the `container_id_name` of the loop container container_id_name = self.generate_container_id_name( self.fortran_file, self.current_scope, f"loop${self.loop_index}" ) # Update the scope of the loop container so that everything inside # the body of the loop will have the below scope self.current_scope = f"{self.current_scope}.loop${self.loop_index}" index_variable = self.gen_grfn(node.target, state, "for") # Check: Currently, only one variable is supported as a loop variable if len(index_variable) != 1 or "var" not in index_variable[0]: raise For2PyError("Only one index variable is supported.") index_name = index_variable[0]["var"]["variable"] # Define a new empty state that will be used for mapping the state of # the operations within the for-loop container loop_last_definition = {} loop_state = state.copy( last_definitions=loop_last_definition, next_definitions={}, last_definition_default=-1, ) # We want the loop_state to have state information about variables # defined one scope above its current parent scope. The below code # allows us to do that if self.parent_loop_state: for var in self.parent_loop_state.last_definitions: if var not in state.last_definitions: # state.last_definitions[var] = \ # self.parent_loop_state.last_definitions[var] state.last_definitions[var] = -1 loop_iterator = self.gen_grfn(node.iter, state, "for") # Check: Only the `range` function is supported as a loop iterator at # this moment if ( len(loop_iterator) != 1 or "call" not in loop_iterator[0] or loop_iterator[0]["call"]["function"] != "range" ): raise For2PyError("Can only iterate over a range.") range_call = loop_iterator[0]["call"] loop_condition_inputs.append(f"@variable::{index_name}::0") loop_condition_inputs_lambda.append(index_name) for ip in range_call["inputs"]: for var in ip: if "var" in var: function_input.append( f"@variable::" f"{var['var']['variable']}::" f"{var['var']['index']}" ) container_argument.append( f"@variable::" f"{var['var']['variable']}::-1" ) loop_condition_inputs.append( f"@variable::" f"{var['var']['variable']}::-1" ) loop_condition_inputs_lambda.append(var["var"]["variable"]) elif "call" in var: # TODO: Very specifically for arrays. Will probably break # for other calls self._get_call_inputs( var["call"], function_input, container_argument, loop_condition_inputs, loop_condition_inputs_lambda, state, ) function_input = self._remove_duplicate_from_list(function_input) container_argument = self._remove_duplicate_from_list( container_argument ) loop_condition_inputs = self._remove_duplicate_from_list( loop_condition_inputs ) loop_condition_inputs_lambda = self._remove_duplicate_from_list( loop_condition_inputs_lambda ) # Save the current state of the system so that it can used by a # nested loop to get information about the variables declared in its # outermost scopes. self.parent_loop_state = state # Define some condition and break variables in the loop state loop_state.last_definitions[index_name] = 0 loop_state.last_definitions["IF_0"] = 0 loop_state.last_definitions["EXIT"] = 0 loop_state.variable_types["IF_0"] = "bool" loop_state.variable_types["EXIT"] = "bool" # Now, create the `variable` spec, `function name` and `container # wiring` for the loop index, check condition and break decisions. index_variable_grfn = self.generate_variable_definition( [index_name], None, False, loop_state ) index_function_name = self.generate_function_name( "__assign__", index_variable_grfn["name"], None ) index_function = { "function": index_function_name, "input": [], "output": [f"@variable::{index_name}::0"], "updated": [], } loop_check_variable = self.generate_variable_definition( ["IF_0"], None, False, loop_state ) loop_state.next_definitions["#cond"] = 1 loop_state.last_definitions["#cond"] = 0 loop_check_function_name = self.generate_function_name( "__condition__", loop_check_variable["name"], None ) loop_condition_function = { "function": loop_check_function_name, "input": loop_condition_inputs, "output": [f"@variable::IF_0::0"], "updated": [], } # Create the lambda function for the index variable initiations and # other loop checks. This has to be done through a custom lambda # function operation since the structure of genCode does not conform # with the way this lambda function will be created. # TODO Add code to support a step other than +1 as well assert len(range_call["inputs"]) <= 3, ( f"Only two or three elements in range function supported as of " f"now - {range_call}" ) loop_start = range_call["inputs"][0] loop_end = range_call["inputs"][1] # TODO: need to decide what we'll do with step. if len(range_call["inputs"]) == 3: loop_step = range_call["inputs"][2] # TODO Add a separate function to get the variables/literals of a # more complex form. The one below is for the basic case. if "var" in loop_start[0]: loop_start_name = loop_start[0]["var"]["variable"] elif "type" in loop_start[0] and loop_start[0]["type"] == "literal": loop_start_name = loop_start[0]["value"] else: assert False, "Error in getting loop start name" if "var" in loop_end[0]: # If the loop end is tested against a variable, such as: # for p_idx[0] in range(1, n_p[0]+1): # the loop_end_name should be the variable_name plus 1 loop_end_name = f"{loop_end[0]['var']['variable']}+1" elif "type" in loop_end[0] and loop_end[0]["type"] == "literal": loop_end_name = loop_end[0]["value"] else: assert False, "Error in getting loop end name" # First, lambda function for loop index initiation index_initiation_lambda = self.generate_lambda_function( loop_start_name, index_function_name["name"], True, False, False, False, [], [], state, True, ) index_function["function"]["code"] = index_initiation_lambda # Second, lambda function for IF_0_0 test loop_test_string = f"0 <= {index_name} < {loop_end_name}" loop_continuation_test_lambda = self.generate_lambda_function( loop_test_string, loop_check_function_name["name"], True, False, False, False, loop_condition_inputs_lambda, [], state, True, ) loop_condition_function["function"][ "code" ] = loop_continuation_test_lambda # Parse through the body of the loop container loop = self.gen_grfn(node.body, loop_state, "for") # Separate the body grfn into `variables` and `functions` sub parts ( body_variables_grfn, body_functions_grfn, body_container_grfn, ) = self._get_variables_and_functions(loop) # Get a list of all variables that were used as inputs within the # loop body (nested as well). loop_body_inputs = [] # Get only the dictionaries body_functions_grfn = [ item for item in body_functions_grfn if isinstance(item, dict) ] for function in body_functions_grfn: if function["function"]["type"] == "lambda": for ip in function["input"]: (_, input_var, input_index) = ip.split("::") if ( _ == "@variable" and int(input_index) == -1 and input_var not in loop_body_inputs ): loop_body_inputs.append(input_var) elif function["function"]["type"] == "container": # The same code as above but separating it out just in case # some extra checks are added in the future for ip in function["input"]: (_, input_var, input_index) = ip.split("::") if _ == "@variable" and int(input_index) == -1: loop_body_inputs.append(input_var) # Remove any duplicates since variables can be used multiple times in # various assignments within the body loop_body_inputs = self._remove_duplicate_from_list(loop_body_inputs) # If the index name is a part of the loop body, remove it since it is # not an input to the container if index_name in loop_body_inputs: loop_body_inputs.remove(index_name) # TODO: Not doing this right now. Refine this code and do it then. """ # Now, we remove the variables which were defined inside the loop # body itself and not taken as an input from outside the loop body filtered_loop_body_inputs = [] for input_var in loop_body_inputs: # We filter out those variables which have -1 index in `state` ( # which means it did not have a defined value above the loop # body) and is not a function argument (since they have an index # of -1 as well but have a defined value) if not (state.last_definitions[input_var] == -1 and input_var not in self.function_argument_map[main_function_name][ "argument_list"] ): filtered_loop_body_inputs.append(input_var) """ for item in loop_body_inputs: # TODO Hack for now, this should be filtered off from the code # block above if ( "IF" not in item and state.last_definitions.get(item) is not None ): function_input.append( f"@variable::{item}::" f"{state.last_definitions[item]}" ) container_argument.append(f"@variable::{item}::-1") function_input = self._remove_duplicate_from_list(function_input) container_argument = self._remove_duplicate_from_list( container_argument ) # Creating variable specs for the inputs to the containers. start_definitions = loop_state.last_definitions.copy() container_definitions = start_definitions.copy() container_input_state = loop_state.copy( last_definitions=container_definitions ) for argument in container_argument: (_, var, index) = argument.split("::") container_input_state.last_definitions[var] = int(index) argument_variable = self.generate_variable_definition( [var], None, False, container_input_state ) body_variables_grfn.append(argument_variable) # TODO: Think about removing (or retaining) variables which even # though defined outside the loop, are defined again inside the loop # and then used by an operation after it. # E.g. x = 5 # for ___ : # x = 2 # for ___: # y = x + 2 # Here, loop$1 will have `x` as an input but will loop$0 have `x` as # an input as well? # Currently, such variables are included in the `input`/`argument` # field. # Now, we list out all variables that have been updated/defined # inside the body of the loop loop_body_outputs = {} for function in body_functions_grfn: if function["function"]["type"] == "lambda": # TODO Currently, we only deal with a single output variable. # Modify the line above to not look at only [0] but loop # through the output to incorporate multiple outputs (_, output_var, output_index) = function["output"][0].split( "::" ) loop_body_outputs[output_var] = output_index elif function["function"]["type"] == "container": for ip in function["updated"]: if isinstance(ip, dict): for x in ip["updates"]: (_, output_var, output_index) = x.split("::") loop_body_outputs[output_var] = output_index else: (_, output_var, output_index) = ip.split("::") loop_body_outputs[output_var] = output_index for item in loop_body_outputs: # TODO the indexing variables in of function block and container # block will be different. Figure about the differences and # implement them. # TODO: Hack, this IF check should not even appear in # loop_body_outputs if ( "IF" not in item and "EXIT" not in item and state.last_definitions.get(item) is not None ): if state.last_definitions[item] == -2: updated_index = 0 else: updated_index = state.last_definitions[item] + 1 function_updated.append( f"@variable::{item}::" f"{updated_index}" ) state.last_definitions[item] = updated_index state.next_definitions[item] = updated_index + 1 item_id = loop_state.last_definitions.get( item, loop_body_outputs[item] ) container_updated.append(f"@variable::{item}::" f"{item_id}") # Create variable spec for updated variables in parent scope. # So, temporarily change the current scope to its previous form tmp_scope = self.current_scope self.current_scope = ".".join( self.current_scope.split(".")[:-1] ) updated_variable = self.generate_variable_definition( [item], None, False, state ) body_variables_grfn.append(updated_variable) # Changing it back to its current form self.current_scope = tmp_scope loop_break_variable = self.generate_variable_definition( ["EXIT"], None, False, loop_state ) loop_state.next_definitions["EXIT"] = 1 loop_break_function_name = self.generate_function_name( "__decision__", loop_break_variable["name"], None ) exit_inputs = ["@variable::IF_0::0"] exit_inputs.extend( [ f"@variable::{list(x.keys())[0]}::0" for x in self.exit_candidates ] ) lambda_inputs = [ f"{x.split('::')[1]}_{x.split('::')[2]}" for x in exit_inputs ] loop_break_function = { "function": loop_break_function_name, "input": exit_inputs, "output": [f"@variable::EXIT::0"], "updated": [], } loop_exit_test_lambda = self.generate_lambda_function( ["EXIT"], loop_break_function_name["name"], True, False, False, False, lambda_inputs, [], state, True, ) loop_break_function["function"]["code"] = loop_exit_test_lambda # TODO: For the `loop_body_outputs`, all variables that were # defined/updated inside the loop body are included. Sometimes, # some variables are defined inside the loop body, used within that # body and then not used or re-assigned to another value outside the # loop body. Do we include such variables in the updated list? # Another heuristic to think about is whether to keep only those # variables in the `updated` list which are in the `input` list. loop_variables_grfn.append(index_variable_grfn) loop_variables_grfn.append(loop_check_variable) loop_variables_grfn.append(loop_break_variable) loop_functions_grfn.append(index_function) loop_functions_grfn.append(loop_condition_function) loop_functions_grfn.append(loop_break_function) loop_functions_grfn += body_functions_grfn # Finally, add the index increment variable and function grfn to the # body grfn loop_state.last_definitions[index_name] = 1 index_increment_grfn = self.generate_variable_definition( [index_name], None, False, loop_state ) index_increment_function_name = self.generate_function_name( "__assign__", index_increment_grfn["name"], None ) index_increment_function = { "function": index_increment_function_name, "input": [f"@variable::{index_name}::0"], "output": [f"@variable::{index_name}::1"], "updated": [], } # Finally, lambda function for loop index increment index_increment_lambda = self.generate_lambda_function( f"{index_name} + 1", index_increment_function_name["name"], True, False, False, False, [index_name], [], state, True, ) index_increment_function["function"]["code"] = index_increment_lambda loop_variables_grfn.append(index_increment_grfn) loop_functions_grfn.append(index_increment_function) container_gensym = self.generate_gensym("container") loop_container = { "name": container_id_name, "source_refs": [], "gensym": container_gensym, "type": "loop", "arguments": container_argument, "updated": container_updated, "return_value": container_return_value, "body": loop_functions_grfn, } loop_function = { "function": {"name": container_id_name, "type": "container"}, "input": function_input, "output": function_output, "updated": function_updated, } loop_container = [loop_container] + body_container_grfn loop_variables = body_variables_grfn + loop_variables_grfn grfn = { "containers": loop_container, "variables": loop_variables, "functions": [loop_function], } # Change the current scope back to its previous form. self.current_scope = ".".join(self.current_scope.split(".")[:-1]) return [grfn] def process_while(self, node, state, *_): """ This function handles the while loop. The functionality will be very similar to that of the for loop described in `process_for` """ # Update the scope scope_path = state.scope_path.copy() if len(scope_path) == 0: scope_path.append("@global") scope_path.append("loop") # Initialize intermediate variables container_argument = [] container_return_value = [] container_updated = [] function_output = [] function_updated = [] function_input = [] loop_condition_inputs = [] loop_condition_inputs_lambda = [] loop_variables_grfn = [] loop_functions_grfn = [] # Increment the loop index universally across the program if self.loop_index > -1: self.loop_index += 1 else: self.loop_index = 0 # First, get the `container_id_name` of the loop container container_id_name = self.generate_container_id_name( self.fortran_file, self.current_scope, f"loop${self.loop_index}" ) # Update the scope of the loop container so that everything inside # the body of the loop will have the below scope self.current_scope = f"{self.current_scope}.loop${self.loop_index}" loop_test = self.gen_grfn(node.test, state, "while") # Define a new empty state that will be used for mapping the state of # the operations within the loop container loop_last_definition = {} loop_state = state.copy( last_definitions=loop_last_definition, next_definitions={}, last_definition_default=-1, ) # We want the loop_state to have state information about variables # defined one scope above its current parent scope. The below code # allows us to do that if self.parent_loop_state: for var in self.parent_loop_state.last_definitions: if var not in state.last_definitions: # state.last_definitions[var] = \ # self.parent_loop_state.last_definitions[var] state.last_definitions[var] = -1 # Now populate the IF and EXIT functions for the loop by identifying # the loop conditionals # TODO Add a test to check for loop validity in this area. Need to # test with more types of while loops to finalize on a test condition for item in loop_test: if not isinstance(item, list): item = [item] for var in item: if "var" in var: function_input.append( f"@variable::" f"{var['var']['variable']}::" f"{var['var']['index']}" ) container_argument.append( f"@variable::" f"{var['var']['variable']}::-1" ) loop_condition_inputs.append( f"@variable::" f"{var['var']['variable']}::-1" ) loop_condition_inputs_lambda.append(var["var"]["variable"]) elif "call" in var: # TODO: Very specifically for arrays. Will probably break # for other calls self._get_call_inputs( var["call"], function_input, container_argument, loop_condition_inputs, loop_condition_inputs_lambda, state, ) function_input = self._remove_duplicate_from_list(function_input) container_argument = self._remove_duplicate_from_list( container_argument ) loop_condition_inputs = self._remove_duplicate_from_list( loop_condition_inputs ) loop_condition_inputs_lambda = self._remove_duplicate_from_list( loop_condition_inputs_lambda ) # Save the current state of the system so that it can used by a # nested loop to get information about the variables declared in its # outermost scopes. self.parent_loop_state = state # Define some condition and break variables in the loop state loop_state.last_definitions["IF_0"] = 0 loop_state.last_definitions["EXIT"] = 0 loop_state.variable_types["IF_0"] = "bool" loop_state.variable_types["EXIT"] = "bool" # Now, create the `variable` spec, `function name` and `container # wiring` for the check condition and break decisions. loop_check_variable = self.generate_variable_definition( ["IF_0"], None, False, loop_state ) loop_state.next_definitions["#cond"] = 1 loop_state.last_definitions["#cond"] = 0 loop_check_function_name = self.generate_function_name( "__condition__", loop_check_variable["name"], None ) loop_condition_function = { "function": loop_check_function_name, "input": loop_condition_inputs, "output": [f"@variable::IF_0::0"], "updated": [], } # Create the lambda function for the index variable initiations and # other loop checks. This has to be done through a custom lambda # function operation since the structure of genCode does not conform # with the way this lambda function will be created. # TODO Add a separate function to get the variables/literals of a # more complex form. The one below is for the basic case. # Second, lambda function for IF_0_0 test loop_continuation_test_lambda = self.generate_lambda_function( node.test, loop_check_function_name["name"], True, False, False, False, loop_condition_inputs_lambda, [], state, True, ) loop_condition_function["function"][ "code" ] = loop_continuation_test_lambda # Parse through the body of the loop container loop = self.gen_grfn(node.body, loop_state, "for") # Separate the body grfn into `variables` and `functions` sub parts ( body_variables_grfn, body_functions_grfn, body_container_grfn, ) = self._get_variables_and_functions(loop) # Get a list of all variables that were used as inputs within the # loop body (nested as well). loop_body_inputs = [] # Get only the dictionaries body_functions_grfn = [ item for item in body_functions_grfn if isinstance(item, dict) ] for function in body_functions_grfn: if function["function"]["type"] == "lambda": for ip in function["input"]: (_, input_var, input_index) = ip.split("::") if ( int(input_index) == -1 and input_var not in loop_body_inputs ): loop_body_inputs.append(input_var) elif function["function"]["type"] == "container": # The same code as above but separating it out just in case # some extra checks are added in the future for ip in function["input"]: (_, input_var, input_index) = ip.split("::") # TODO Hack for bypassing `boolean` types. Will be # removed once the `literal` as an input question is # answered. if int(input_index) == -1 and input_var != "boolean": loop_body_inputs.append(input_var) # Remove any duplicates since variables can be used multiple times in # various assignments within the body loop_body_inputs = self._remove_duplicate_from_list(loop_body_inputs) # TODO: Not doing this right now. Refine this code and do it then. """ # Now, we remove the variables which were defined inside the loop # body itself and not taken as an input from outside the loop body filtered_loop_body_inputs = [] for input_var in loop_body_inputs: # We filter out those variables which have -1 index in `state` ( # which means it did not have a defined value above the loop # body) and is not a function argument (since they have an index # of -1 as well but have a defined value) if not (state.last_definitions[input_var] == -1 and input_var not in self.function_argument_map[main_function_name][ "argument_list"] ): filtered_loop_body_inputs.append(input_var) """ # for item in filtered_loop_body_inputs: for item in loop_body_inputs: # TODO Hack for now, this should be filtered off from the code # block above if ( "IF" not in item and state.last_definitions.get(item) is not None ): function_input.append( f"@variable::{item}::" f"{state.last_definitions[item]}" ) container_argument.append(f"@variable::{item}::-1") function_input = self._remove_duplicate_from_list(function_input) container_argument = self._remove_duplicate_from_list( container_argument ) # Creating variable specs for the inputs to the containers. start_definitions = loop_state.last_definitions.copy() container_definitions = start_definitions.copy() container_input_state = loop_state.copy( last_definitions=container_definitions ) for argument in container_argument: (_, var, index) = argument.split("::") container_input_state.last_definitions[var] = int(index) argument_variable = self.generate_variable_definition( [var], None, False, container_input_state ) body_variables_grfn.append(argument_variable) # TODO: Think about removing (or retaining) variables which even # though defined outside the loop, are defined again inside the loop # and then used by an operation after it. # E.g. x = 5 # for ___ : # x = 2 # for ___: # y = x + 2 # Here, loop$1 will have `x` as an input but will loop$0 have `x` as # an input as well? # Currently, such variables are included in the `input`/`argument` # field. # Now, we list out all variables that have been updated/defined # inside the body of the loop loop_body_outputs = {} for function in body_functions_grfn: if function["function"]["type"] == "lambda": # TODO Currently, we only deal with a single output variable. # Modify the line above to not look at only [0] but loop # through the output to incorporate multiple outputs (_, output_var, output_index) = function["output"][0].split( "::" ) loop_body_outputs[output_var] = output_index elif function["function"]["type"] == "container": for ip in function["updated"]: if isinstance(ip, dict): for x in ip["updates"]: (_, output_var, output_index) = x.split("::") loop_body_outputs[output_var] = output_index else: (_, output_var, output_index) = ip.split("::") loop_body_outputs[output_var] = output_index for item in loop_body_outputs: # TODO the indexing variables in of function block and container # block will be different. Figure about the differences and # implement them. # TODO: Hack, this IF check should not even appear in # loop_body_outputs if ( "IF" not in item and "EXIT" not in item and state.last_definitions.get(item) is not None ): if (state.last_definitions[item] == -2) or (item == "EXIT"): updated_index = 0 else: updated_index = state.last_definitions[item] + 1 function_updated.append( f"@variable::{item}::" f"{updated_index}" ) state.last_definitions[item] = updated_index state.next_definitions[item] = updated_index + 1 item_id = loop_state.last_definitions.get( item, loop_body_outputs[item] ) container_updated.append(f"@variable::{item}::" f"{item_id}") # Create variable spec for updated variables in parent scope. # So, temporarily change the current scope to its previous form tmp_scope = self.current_scope self.current_scope = ".".join( self.current_scope.split(".")[:-1] ) updated_variable = self.generate_variable_definition( [item], None, False, state ) body_variables_grfn.append(updated_variable) # Changing it back to its current form self.current_scope = tmp_scope loop_break_variable = self.generate_variable_definition( ["EXIT"], None, False, loop_state ) loop_state.next_definitions["EXIT"] = 1 loop_break_function_name = self.generate_function_name( "__decision__", loop_break_variable["name"], None ) exit_inputs = ["@variable::IF_0::0"] exit_inputs.extend( [ f"@variable::{list(x.keys())[0]}::0" for x in self.exit_candidates ] ) lambda_inputs = [ f"{x.split('::')[1]}_{x.split('::')[2]}" for x in exit_inputs ] loop_break_function = { "function": loop_break_function_name, "input": exit_inputs, "output": [f"@variable::EXIT::0"], "updated": [], } loop_exit_test_lambda = self.generate_lambda_function( ["EXIT"], loop_break_function_name["name"], True, False, False, False, lambda_inputs, [], state, True, ) loop_break_function["function"]["code"] = loop_exit_test_lambda # TODO: For the `loop_body_outputs`, all variables that were # defined/updated inside the loop body are included. Sometimes, # some variables are defined inside the loop body, used within that # body and then not used or re-assigned to another value outside the # loop body. Do we include such variables in the updated list? # Another heuristic to think about is whether to keep only those # variables in the `updated` list which are in the `input` list. loop_variables_grfn.append(loop_check_variable) loop_variables_grfn.append(loop_break_variable) loop_functions_grfn.append(loop_condition_function) loop_functions_grfn.append(loop_break_function) loop_functions_grfn += body_functions_grfn container_gensym = self.generate_gensym("container") loop_container = { "name": container_id_name, "source_refs": [], "gensym": container_gensym, "type": "loop", "arguments": container_argument, "updated": container_updated, "return_value": container_return_value, "body": loop_functions_grfn, } loop_function = { "function": {"name": container_id_name, "type": "container"}, "input": function_input, "output": function_output, "updated": function_updated, } loop_container = [loop_container] + body_container_grfn loop_variables = body_variables_grfn + loop_variables_grfn grfn = { "containers": loop_container, "variables": loop_variables, "functions": [loop_function], } self.current_scope = ".".join(self.current_scope.split(".")[:-1]) return [grfn] def process_if(self, node, state, call_source): """ This function handles the ast.IF node of the AST. It goes through the IF body and generates the `decision` and `condition` type of the `<function_assign_def>`. """ # Update the scope path scope_path = state.scope_path.copy() if len(scope_path) == 0: scope_path.append("@global") state.scope_path = scope_path # First, check whether this is the start of an `if-block` or an # `elif` block # if call_source == "if": if self.elseif_flag: is_else_if = True self.elseif_flag = False if_index = self.elif_index else: is_else_if = False # Increment the loop index universally across the program if self.if_index > -1: self.if_index += 1 if_index = self.if_index else: self.if_index = 0 if_index = self.if_index # Define a new empty state that will be used for mapping the # state of the operations within the for-loop container loop_last_definition = {} if_state = state.copy( last_definitions=loop_last_definition, next_definitions={}, last_definition_default=-1, ) # First, get the `container_id_name` of the if container container_id_name = self.generate_container_id_name( self.fortran_file, self.current_scope, f"IF_{if_index}" ) # Update the scope to include the new `if-block` self.current_scope = f"{self.current_scope}.IF_{if_index}" # We want the if_state to have state information about variables # defined one scope above its current parent scope. The below code # allows us to do that # TODO: How relevant is this for `if-blocks`? Will need to verify if self.parent_if_state: for var in self.parent_if_state.last_definitions: if var not in state.last_definitions: state.last_definitions[var] = -1 grfn = {"functions": [], "variables": [], "containers": []} # Get the GrFN schema of the test condition of the `IF` command # Notice that we'll have two different states depending on whether # this is the main `if-block` or the `elif` block if is_else_if: condition_sources = self.gen_grfn(node.test, state, "if") condition_variables = self.get_variables(condition_sources, state) else: condition_sources = self.gen_grfn(node.test, if_state, "if") condition_variables = self.get_variables( condition_sources, if_state ) # When opening files, if a check for a pre-existing file has to be # done, this if-block is bypassed if isinstance(condition_sources[0], dict) and condition_sources[0].get( "call" ): if ( condition_sources[0]["call"].get("function") and condition_sources[0]["call"]["function"] == "path.exists" ): return [] # The index of the IF_x_x variable will start from 0 if state.last_definition_default in (-1, 0, -2): # default_if_index = state.last_definition_default + 1 default_if_index = 0 else: assert False, ( f"Invalid value of last_definition_default:" f"{state.last_definition_default}" ) # For every new `if-block`, the IF_X value will increase by one. # For every condition check within an `if-block` (i.e. if .. elif .. # elif .. else ..), the COND_X index will start from 0 for the `if` # check and increment by 1 for every `elif` check if not is_else_if: condition_number = 0 if_state.last_definitions["#cond"] = condition_number if_state.next_definitions["#cond"] = condition_number + 1 condition_name = f"COND_{if_index}_{condition_number}" condition_index = self.get_last_definition( condition_name, if_state.last_definitions, 0 ) if_state.variable_types[condition_name] = "bool" if_state.last_definitions[condition_name] = condition_index variable_spec = self.generate_variable_definition( [condition_name], None, False, if_state ) else: condition_number = self._get_next_definition( "#cond", state.last_definitions, state.next_definitions, default_if_index - 1, ) condition_name = f"COND_{if_index}_{condition_number}" condition_index = self.get_last_definition( condition_name, state.last_definitions, 0 ) state.variable_types[condition_name] = "bool" state.last_definitions[condition_name] = condition_index variable_spec = self.generate_variable_definition( [condition_name], None, False, state ) function_name = self.generate_function_name( "__condition__", variable_spec["name"], None ) # Getting the output variable output_regex = re.compile(r".*::(?P<output>.*?)::(?P<index>.*$)") output_match = output_regex.match(variable_spec["name"]) if output_match: output = output_match.group("output") index = output_match.group("index") output_variable = f"@variable::{output}::{index}" else: assert False, ( f"Could not match output variable for " f"{variable_spec['name']}" ) # Create the function statement for the COND_X variables fn = { "function": function_name, "input": [ f"@variable::{src['var']['variable']}::{src['var']['index']}" for src in condition_variables if "var" in src ], "output": [output_variable], "updated": [], } # Save the current state of the system so that it can used by a # nested loop to get information about the variables declared in its # outermost scopes. self.parent_if_state = state # Update the variable definition with the COND_X variable spec grfn["variables"].append(variable_spec) # Generate the lambda function code of the COND_X check lambda_string = self.generate_lambda_function( node.test, function_name["name"], False, False, False, False, [ src["var"]["variable"] for src in condition_variables if "var" in src ], [], state, False, ) fn["function"]["code"] = lambda_string else_node_name = node.orelse.__repr__().split()[0][3:] if is_else_if: if_grfn = self.gen_grfn(node.body, state, "if") if else_node_name == "ast.If": self.elseif_flag = True self.elif_index = if_index else_grfn = self.gen_grfn(node.orelse, state, "if") else: if_grfn = self.gen_grfn(node.body, if_state, "if") if else_node_name == "ast.If": self.elseif_flag = True self.elif_index = if_index else_grfn = self.gen_grfn(node.orelse, if_state, "if") # Sometimes, some if-else body blocks only contain I/O operations, # the GrFN for which will be empty. Check for these and handle # accordingly if ( len(else_grfn) > 0 and len(else_grfn[0]["functions"]) == 0 and len(else_grfn[0]["variables"]) == 0 and len(else_grfn[0]["containers"]) == 0 ): else_grfn = [] # If this is an `elif` block, append the if-body GrFN and else-body # GrFN to the functions with their respective structure and simply # return if is_else_if: grfn["functions"] = [{"condition": [fn], "statements": []}] for spec in if_grfn: grfn["functions"][0]["statements"] += spec["functions"] grfn["variables"] += spec["variables"] grfn["containers"] += spec["containers"] grfn["functions"].append({"condition": None, "statements": []}) for spec in else_grfn: # Check for cases like more than one `elif` where the overall # structure has to stay consistent if "condition" in spec["functions"][0]: grfn["functions"].pop() grfn["functions"] += spec["functions"] else: grfn["functions"][1]["statements"] += spec["functions"] grfn["variables"] += spec["variables"] grfn["containers"] += spec["containers"] return [grfn] # All of the operations from this point is only for the main # `if-block` if statement for spec in if_grfn: grfn["variables"] += spec["variables"] grfn["containers"] += spec["containers"] for spec in else_grfn: grfn["variables"] += spec["variables"] grfn["containers"] += spec["containers"] container_argument = [] function_input = [] if_body_inputs = [] if_body_outputs = {} container_updated = [] container_decisions = [] function_updated = [] container_body = [{"condition": [fn], "statements": []}] for spec in if_grfn: if len(spec["functions"]) > 0: container_body[0]["statements"] += spec["functions"] container_body.append({"condition": None, "statements": []}) for spec in else_grfn: if len(spec["functions"]) > 0: if "condition" in spec["functions"][0]: container_body.pop() container_body += spec["functions"] else: container_body[1]["statements"] += spec["functions"] # If there is no else statement, remove it from the block if ( container_body[-1]["condition"] is None and len(container_body[-1]["statements"]) == 0 ): container_body.pop() current_condition = None for body_dict in container_body: for key in body_dict: if key == "statements": self._fix_input_index(body_dict[key]) if body_dict[key]: for function in body_dict[key]: if key == "condition": current_condition = function["output"][0].split( "::" )[1] if_body_outputs[current_condition] = dict() if function["function"]["type"] == "lambda": for ip in function["input"]: (_, input_var, input_index) = ip.split("::") if ( "@literal" not in ip and int(input_index) == -1 and input_var not in if_body_inputs ): if_body_inputs.append(input_var) (_, output_var, output_index) = function["output"][ 0 ].split("::") if_body_outputs[current_condition][ output_var ] = output_index elif function["function"]["type"] == "container": # The same code as above but separating it out just # in case some extra checks are added in the future for ip in function["input"]: (_, input_var, input_index) = ip.split("::") if int(input_index) == -1: if_body_inputs.append(input_var) for ip in function["updated"]: if isinstance(ip, dict): for x in ip["updates"]: ( _, output_var, output_index, ) = x.split("::") if_body_outputs[current_condition][ output_var ] = output_index else: (_, output_var, output_index) = ip.split( "::" ) if_body_outputs[current_condition][ output_var ] = output_index else: current_condition = None if_body_outputs[current_condition] = dict() # Remove any duplicates since variables can be used multiple times in # various assignments within the body if_body_inputs = self._remove_duplicate_from_list(if_body_inputs) for item in if_body_inputs: if ( "COND" not in item and state.last_definitions.get(item) is not None ): function_input.append( f"@variable::{item}::{state.last_definitions[item]}" ) container_argument.append(f"@variable::{item}::-1") function_input = self._remove_duplicate_from_list(function_input) container_argument = self._remove_duplicate_from_list( container_argument ) # Creating variable specs for the inputs to the containers. start_definitions = if_state.last_definitions.copy() container_definitions = start_definitions.copy() container_input_state = if_state.copy( last_definitions=container_definitions ) for argument in container_argument: (_, var, index) = argument.split("::") container_input_state.last_definitions[var] = int(index) argument_variable = self.generate_variable_definition( [var], None, False, container_input_state ) grfn["variables"].append(argument_variable) updated_vars = [ list(if_body_outputs[x].keys()) for x in if_body_outputs ] updated_vars = list(set([i for x in updated_vars for i in x])) # Start of code that produces the __decisions__ statements # Get the updated variables in a format that is easier for the rest # of this code to work on # Structure: # {'z': [{'COND_0_1': 0, 'COND_0_2': 1, None: 3}, [1, 2, -1]]} decision_inputs = self._get_decision_inputs( if_body_outputs, updated_vars ) # Get the maximum number of condition statements inside this `IF` # container condition_count = if_state.last_definitions.get("#cond", 0) # For every updated variables, we'll make a decision statement and a # lambda function for updated, versions in decision_inputs.items(): condition_indexes = versions[-1] condition_map = versions[0] inputs = [] # If the variable is updated in the `else` clause (i.e. -1), # all condition booleans will be an input to it if -1 in condition_indexes: for i in range(condition_count + 1): inputs.append( {"variable": f"COND_{if_index}_{i}", "index": 0} ) else: # In this case, all condition booleans up to the maximum # condition will be an input for i in range(max(condition_indexes) + 1): inputs.append( {"variable": f"COND_{if_index}_{i}", "index": 0} ) # Now add the updated variables with their respective indexes for cond, index in condition_map.items(): inputs.append({"variable": updated, "index": index}) # If some variables don't end up always getting updated during the # if-else checks, then their -1 indexed versions should be added to # the input list. For example # if cond_0: x = 3 # else: y = 4 # Here, x won't get updated if cond_0 is unmet and vice versa for y # But in cases like: # if cond_0: x = 3 # else: x = 4 # x is always updated so it's -1 index will be not added as an input if len(condition_map) <= condition_count + 1: if state.last_definitions.get(updated) is not None: ip = f"@variable::{updated}::{state.last_definitions[updated]}" if ip not in function_input: function_input.append(ip) ip = f"@variable::{updated}::-1" if ip not in container_argument: container_argument.append(ip) # Also, add the -1 index for the variable which is the # default case when no conditions will be met inputs.append({"variable": updated, "index": -1}) # The output variable is the updated variable with its index as # index = latest_index+1 output = { "variable": updated, "index": self._get_next_definition( updated, if_state.last_definitions, if_state.next_definitions, if_state.last_definition_default, ), } # Create a variable list and add it to the variable tag variable_spec = self.generate_variable_definition( [updated], None, False, if_state ) grfn["variables"].append(variable_spec) # Create a __decision__ function and add it to the `decisions` # tag of the container function_name = self.generate_function_name( "__decision__", variable_spec["name"], None ) fn = { "function": function_name, "input": [ f"@variable::{var['variable']}::{var['index']}" for var in inputs ], "output": [ f"@variable::{output['variable']}:" f":{output['index']}" ], "updated": [], } container_decisions.append(fn) # We sort the condition booleans dictionary in such a way that # the first conditions appear at the beginning # Structure: {'COND_0_1': 0, 'COND_0_2': 1, None: 3} changes to # ('COND_0_1', 0), ('COND_0_2', 1), (None, 3) versions[0] = sorted(versions[0].items(), key=lambda item: item[1]) # The inputs to the lambda function will not have the -1 index # for the variable as `var_-1` is an invalid variable name. So, # `-1` is replaces by `xx`. Default variables will be represented # as `var_xx` lambda_inputs = [] for src in inputs: if src["index"] == -1: lambda_inputs.append(f"{src['variable']}_xx") else: lambda_inputs.append(f"{src['variable']}_{src['index']}") # Generate the lambda function string lambda_string = self.generate_lambda_function( node, function_name["name"], False, True, False, False, lambda_inputs, versions, if_state, False, ) fn["function"]["code"] = lambda_string for index, item in enumerate(if_body_outputs): function_updated.append({"condition": item, "updates": []}) container_updated.append({"condition": item, "updates": []}) for var in if_body_outputs[item]: if "COND" not in var: if state.last_definitions.get(var, -2) == -2: updated_index = 0 else: if var in updated_vars: updated_index = state.last_definitions[var] + 1 else: updated_index = state.last_definitions[var] function_updated[index]["updates"].append( f"@variable::{var}::" f"{updated_index}" ) if var in updated_vars: state.last_definitions[var] = updated_index state.next_definitions[var] = updated_index + 1 # Create variable spec for updated variables in parent # scope. So, temporarily change the current scope to its # previous form. tmp_scope = self.current_scope self.current_scope = ".".join( self.current_scope.split(".")[:-1] ) updated_variable = self.generate_variable_definition( [var], None, False, state ) grfn["variables"].append(updated_variable) # Changing it back to its current form self.current_scope = tmp_scope updated_vars.remove(var) item_id = if_body_outputs[item][var] container_updated[index]["updates"].append( f"@variable:" f":{var}::" f"{item_id}" ) # If there is no else statement, remove it from the block if ( container_updated[-1]["condition"] is None and len(container_updated[-1]["updates"]) == 0 ): container_updated.pop() if ( function_updated[-1]["condition"] is None and len(function_updated[-1]["updates"]) == 0 ): function_updated.pop() function_updated = [] container_updated = [] for statement in container_decisions: for output in statement["output"]: container_updated.append(output) segments = output.split("::") var = segments[1] if state.last_definitions.get(var, -2) == -2: updated_index = 0 else: updated_index = state.last_definitions[var] function_updated.append(f"@variable::{var}::{updated_index}") container_gensym = self.generate_gensym("container") if_type = "if-block" node_lineno = node.lineno for comment in self.comments: if ( self.comments[comment] == "# select-case" and node_lineno == int(comment) + 1 ): if_type = "select-block" merged_body = self._merge_container_body( container_body, container_decisions ) if_container = { "name": container_id_name, "source_refs": [], "gensym": container_gensym, "type": if_type, "arguments": container_argument, "updated": container_updated, "return_value": [], "body": merged_body, } if_function = { "function": {"name": container_id_name, "type": "container"}, "input": function_input, "updated": function_updated, "output": [], } grfn["functions"].append(if_function) grfn["containers"] = [if_container] + grfn["containers"] # Change the current scope back to its previous form. self.current_scope = ".".join(self.current_scope.split(".")[:-1]) return [grfn] def process_unary_operation(self, node, state, *_): """ This function processes unary operations in Python represented by ast.UnaryOp. This node has an `op` key which contains the operation (e.g. USub for -, UAdd for +, Not, Invert) and an `operand` key which contains the operand of the operation. This operand can in itself be any Python object (Number, Function call, Binary Operation, Unary Operation, etc. So, iteratively call the respective ast handler for the operand. """ return self.gen_grfn(node.operand, state, "unaryop") def process_binary_operation(self, node, state, *_): """ This function handles binary operations i.e. ast.BinOp """ # If both the left and right operands are numbers (ast.Num), we can # simply perform the respective operation on these two numbers and # represent this computation in a GrFN spec. if isinstance(node.left, ast.Num) and isinstance(node.right, ast.Num): for op in self.binops: if isinstance(node.op, op): val = self.binops[type(node.op)](node.left.n, node.right.n) data_type = self.annotate_map.get(type(val).__name__) if data_type: return [ { "type": "literal", "dtype": data_type, "value": val, } ] else: assert False, f"Unidentified data type of: {val}" assert False, ( "Both operands are numbers but no operator " "available to handle their computation. Either add " "a handler if possible or remove this assert and " "allow the code below to handle such cases." ) # If the operands are anything other than numbers (ast.Str, # ast.BinOp, etc), call `gen_grfn` on each side so their respective # ast handlers will process them and return a [{grfn_spec}, ..] form # for each side. Add these two sides together to give a single [{ # grfn_spec}, ...] form. operation_grfn = self.gen_grfn( node.left, state, "binop" ) + self.gen_grfn(node.right, state, "binop") return operation_grfn def process_boolean_operation(self, node, state, *_): """ This function will process the ast.BoolOp node that handles boolean operations i.e. AND, OR, etc. """ # TODO: No example of this to test on. This looks like deprecated # format. Will need to be rechecked. grfn_list = [] operation = {ast.And: "and", ast.Or: "or"} for key in operation: if isinstance(node.op, key): grfn_list.append([{"boolean_operation": operation[key]}]) for item in node.values: grfn_list.append(self.gen_grfn(item, state, "boolop")) return grfn_list @staticmethod def process_unnecessary_types(node, *_): """ This function handles various ast tags which are unnecessary and need not be handled since we do not require to parse them """ node_name = node.__repr__().split()[0][2:] assert False, f"Found {node_name}, which should be unnecessary" def process_expression(self, node, state, *_): """ This function handles the ast.Expr node i.e. the expression node. This node appears on function calls such as when calling a function, calling print(), etc. """ expressions = self.gen_grfn(node.value, state, "expr") grfn = {"functions": [], "variables": [], "containers": []} for expr in expressions: if "call" not in expr: # assert False, f"Unsupported expr: {expr}." return [] for expr in expressions: array_set = False string_set = False container_id_name = None input_index = None output_index = None arr_index = None call = expr["call"] function_name = call["function"] io_match = self.check_io_variables(function_name) if io_match: return [] # Bypassing calls to `print` for now. Need further discussion and # decisions to move forward with what we'll do with `print` # statements. if function_name == "print": return [] # A handler for array and string <.set_>/<.set_substr> function if ".set_" in function_name: split_function = function_name.split(".") is_derived_type_array_ref = False if ( len(split_function) > 2 and split_function[0] == self.current_d_object_name ): d_object = split_function[0] call_var = split_function[1] method = split_function[2] is_derived_type_array_ref = True else: call_var = split_function[0] method = split_function[1] # This is an array if len(call["inputs"]) > 1 and method != "set_substr": array_set = True function_name = function_name.replace(".set_", "") for idx in range(0, len(split_function) - 1): input_index = self.get_last_definition( split_function[idx], state.last_definitions, state.last_definition_default, ) output_index = self._get_next_definition( split_function[idx], state.last_definitions, state.next_definitions, state.last_definition_default, ) if is_derived_type_array_ref: function_name = function_name.replace(".", "_") input_index = self.get_last_definition( function_name, state.last_definitions, state.last_definition_default, ) output_index = self._get_next_definition( function_name, state.last_definitions, state.next_definitions, state.last_definition_default, ) state.variable_types[ function_name ] = state.variable_types[call_var] self.arrays[function_name] = self.arrays[call_var] arr_index = self._generate_array_index(node) str_arr_index = "" str_arr_for_varname = "" for idx in arr_index: if function_name not in self.md_array: str_arr_index += str(idx) str_arr_for_varname += str(idx) else: str_arr_index += f"[{idx}]" str_arr_for_varname += f"{idx}" # arr_index = call["inputs"][0][0]["var"]["variable"] # Create a new variable spec for indexed array. Ex. # arr(i) will be arr_i. This will be added as a new # variable in GrFN. variable_spec = self.generate_variable_definition( [function_name], str_arr_for_varname, False, state ) grfn["variables"].append(variable_spec) if function_name not in self.md_array: state.array_assign_name = ( f"{function_name}[{str_arr_index}]" ) else: state.array_assign_name = ( f"{function_name}{str_arr_index}" ) # We want to have a new variable spec for the original # array (arr(i), for example) and generate the function # name with it. variable_spec = self.generate_variable_definition( [function_name], None, False, state ) assign_function = self.generate_function_name( "__assign__", variable_spec["name"], arr_index ) container_id_name = assign_function["name"] function_type = assign_function["type"] # This is a string else: string_set = True function_name = call_var state.string_assign_name = function_name input_index = self._get_next_definition( function_name, state.last_definitions, state.next_definitions, -1, ) variable_spec = self.generate_variable_definition( [function_name], None, False, state ) grfn["variables"].append(variable_spec) assign_function = self.generate_function_name( "__assign__", variable_spec["name"], None ) container_id_name = assign_function["name"] function_type = assign_function["type"] else: if function_name in self.function_argument_map: container_id_name = self.function_argument_map[ function_name ]["name"] elif function_name in self.module_subprograms: container_id_name = function_name else: container_id_name = self.generate_container_id_name( self.fortran_file, self.current_scope, function_name ) function_type = "container" if not container_id_name: pass function = { "function": {"name": container_id_name, "type": function_type}, "input": [], "output": [], "updated": [], } # Array itself needs to be added as an input, so check that it's # and array. If yes, then add it manually. if array_set: function["input"].append( f"@variable::" f"{function_name}::{input_index}" ) function["output"] = [ f"@variable::" f"{function_name}::{output_index}" ] argument_list = [] list_index = 0 for arg in call["inputs"]: # We handle inputs to strings differently, so break out of # this loop if string_set: break generate_lambda_for_arr = False if len(arg) == 1: # TODO: Only variables are represented in function # arguments. But a function can have strings as # arguments as well. Do we add that? if "var" in arg[0]: if arg[0]["var"]["variable"] not in argument_list: function["input"].append( f"@variable::" f"{arg[0]['var']['variable']}::" f"{arg[0]['var']['index']}" ) # This is a case where a variable gets assigned to # an array. For example, arr(i) = var. if array_set: argument_list.append(arg[0]["var"]["variable"]) # If list_index is 0, it means that the current # loop is dealing with the array index (i in arr( # i)), which we do not wish to generate a lambda # function for. list_index > 0 are the RHS values # for array assignment. if list_index > 0: generate_lambda_for_arr = True list_index += 1 # This is a case where either an expression or an array # gets assigned to an array. For example, arr(i) = # __expression__ or arr(i) = arr2(i). elif "call" in arg[0]: # Check if a function argument is a string value # E.g: GET("test", "this", x) if arg[0]["call"].get("function"): if arg[0]["call"]["function"] == "String": # The value can either be a string literal or # a substring of another string. Check for this if "value" in arg[0]["call"]["inputs"][1][0]: value = arg[0]["call"]["inputs"][1][0][ "value" ] function["input"].append( f"@literal::" f"string::" f"'{value}'" ) elif "call" in arg[0]["call"]["inputs"][1][0]: string_variable = arg[0]["call"]["inputs"][ 1 ][0]["call"]["function"] if ".get_substr" in string_variable: string_variable = string_variable.split( "." )[ 0 ] string_index = state.last_definitions[ string_variable ] function["input"].append( f"@variable::{string_variable}::" f"{string_index}" ) else: assert False, ( "Unidentified " "expression in String." ) else: assert ( False ), "Unidentified expression in String." else: function = self._generate_array_setter( node, function, arg, function_name, container_id_name, arr_index, state, ) # This is a case where a literal gets assigned to an array. # For example, arr(i) = 100. elif "type" in arg[0] and array_set: generate_lambda_for_arr = True if generate_lambda_for_arr and state.array_assign_name: argument_list.append(function_name) lambda_string = self.generate_lambda_function( node, container_id_name, True, True, False, False, argument_list, [], state, False, ) function["function"]["code"] = lambda_string else: if function_name in self.arrays: # If array type is <float> the argument holder # has a different structure that it does not hold # function info. like when an array is 'int' type # [{'call': {'function': '_type_', 'inputs': [...]] # which causes an error. Thus, the code below fixes # by correctly structuring it. array_type = self.arrays[function_name]["elem_type"] fixed_arg = [ {"call": {"function": array_type, "inputs": [arg]}} ] function = self._generate_array_setter( node, function, fixed_arg, function_name, container_id_name, arr_index, state, ) else: assert ( "call" in arg[0] ), "Only 1 input per argument supported right now." # Below is a separate loop just for filling in inputs for arrays if array_set: argument_list = [] need_lambdas = False if "set_" in call["function"]: argument_list.append(call["function"].replace(".set_", "")) for arg in call["inputs"]: for ip in arg: if "var" in ip: function["input"].append( f"@variable::" f"{ip['var']['variable']}::" f"{ip['var']['index']}" ) if ip["var"]["variable"] not in argument_list: argument_list.append(ip["var"]["variable"]) elif "call" in ip: function_call = ip["call"] function_name = function_call["function"] need_lambdas = True if ".get_" in function_name: if ".get_substr" in function_name: function_name = function_name.replace( ".get_substr", "" ) else: function_name = function_name.replace( ".get_", "" ) # In some cases, the target array itself will # be an input as well. Don't add such arrays # again. if True not in [ function_name in i for i in function["input"] ]: function["input"].append( f"@variable::" f"{function_name}::" f"{state.last_definitions[function_name]}" ) if function_name not in argument_list: argument_list.append(function_name) for call_input in function_call["inputs"]: # TODO: This is of a recursive nature. Make # this a loop. Works for SIR for now. for var in call_input: if "var" in var: function["input"].append( f"@variable::" f"{var['var']['variable']}::" f"{var['var']['index']}" ) if ( var["var"]["variable"] not in argument_list ): argument_list.append( var["var"]["variable"] ) function["input"] = self._remove_duplicate_from_list( function["input"] ) argument_list = self._remove_duplicate_from_list(argument_list) if ( need_lambdas and container_id_name not in self.generated_lambda_functions ): lambda_string = self.generate_lambda_function( node, container_id_name, True, True, False, False, argument_list, [], state, False, ) function["function"]["code"] = lambda_string need_lambdas = False # Make an assign function for a string .set_ operation if string_set: target = { "var": { "variable": function_name, "index": variable_spec["name"].split("::")[-1], } } source_list = list(chain.from_iterable(call["inputs"])) # If the function is `set_substr`, the target string will # also be an input. if method == "set_substr": source_list.append( { "var": { "variable": function_name, "index": int( variable_spec["name"].split("::")[-1] ) - 1, } } ) function = self.make_fn_dict( assign_function, target, source_list, state ) argument_list = self.make_source_list_dict(source_list) lambda_string = self.generate_lambda_function( node, container_id_name, True, False, True, False, argument_list, [], state, False, ) function["function"]["code"] = lambda_string # This is sort of a hack for SIR to get the updated fields filled # in beforehand. For a generalized approach, look at # `process_module`. if function["function"]["type"] == "container": for functions in self.function_argument_map: if ( self.function_argument_map[functions]["name"] == function["function"]["name"] ): new_input = [] for idx in range(len(function["input"])): input_var = function["input"][idx].rsplit("::") index = input_var[2] if ( input_var[1] in self.f_array_arg or input_var[1] in [ x.rsplit("::")[1] for x in self.function_argument_map[ functions ]["updated_list"] ] or idx in self.function_argument_map[functions][ "updated_indices" ] ): variable_name = input_var[1] function["updated"].append( f"@variable::{variable_name}::{int(index)+1}" ) state.last_definitions[variable_name] += 1 state.next_definitions[variable_name] = ( state.last_definitions[variable_name] + 1 ) variable_spec = self.generate_variable_definition( [variable_name], None, False, state ) grfn["variables"].append(variable_spec) # The inputs might need to be updated since some # inputs to the functions are actually output # variables and are not used as inputs inside the # function if ( idx in self.function_argument_map[functions][ "argument_indices" ] ): new_input.append(function["input"][idx]) function["input"] = new_input # Keep a track of all functions whose `update` might need to be # later updated, along with their scope. if len(function["input"]) > 0: # self.update_functions.append(function_name) self.update_functions[function_name] = { "scope": self.current_scope, "state": state, } grfn["functions"].append(function) return [grfn] def process_compare(self, node, state, *_): """ This function handles ast.Compare i.e. the comparator tag which appears on logical comparison i.e. ==, <, >, <=, etc. This generally occurs within an `if` statement but can occur elsewhere as well. """ return self.gen_grfn(node.left, state, "compare") + self.gen_grfn( node.comparators, state, "compare" ) def process_subscript(self, node, state, *_): """ This function handles the ast.Subscript i.e. subscript tag of the ast. This tag appears on variable names that are indexed i.e. x[0], y[5], var[float], etc. Subscript nodes will have a `slice` tag which gives a information inside the [] of the call. """ # The value inside the [] should be a number for now. # TODO: Remove this and handle further for implementations of arrays, # reference of dictionary item, etc if not isinstance(node.slice.value, ast.Num): # raise For2PyError("can't handle arrays right now.") pass val = self.gen_grfn(node.value, state, "subscript") if val: if val[0]["var"]["variable"] in self.annotated_assigned: if isinstance(node.ctx, ast.Store): val[0]["var"]["index"] = self._get_next_definition( val[0]["var"]["variable"], state.last_definitions, state.next_definitions, state.last_definition_default, ) elif val[0]["var"]["index"] == -1: if isinstance(node.ctx, ast.Store): val[0]["var"]["index"] = self._get_next_definition( val[0]["var"]["variable"], state.last_definitions, state.next_definitions, state.last_definition_default, ) self.annotated_assigned.append(val[0]["var"]["variable"]) else: self.annotated_assigned.append(val[0]["var"]["variable"]) return val def process_name(self, node, state, call_source): """ This function handles the ast.Name node of the AST. This node represents any variable in the code. """ # Currently, bypassing any `i_g_n_o_r_e__m_e___` variables which are # used for comment extraction. if not re.match(r"i_g_n_o_r_e__m_e___.*", node.id): for mod in self.imported_module_paths: mod_name = mod.split(".")[-1][2:] import_str = f"from {mod} import {node.id}\n" if ( mod_name in self.module_summary and node.id in self.module_summary[mod_name]["exports"] and import_str not in state.lambda_strings ): state.lambda_strings.insert(0, import_str) last_definition = self.get_last_definition( node.id, state.last_definitions, state.last_definition_default ) # This is a test. Might not always work if ( call_source == "assign" and isinstance(node.ctx, ast.Store) and last_definition < 0 ): last_definition = self._get_next_definition( node.id, state.last_definitions, state.next_definitions, state.last_definition_default, ) if ( isinstance(node.ctx, ast.Store) and state.next_definitions.get(node.id) and call_source == "annassign" ): last_definition = self._get_next_definition( node.id, state.last_definitions, state.next_definitions, state.last_definition_default, ) # TODO Change this structure. This is not required for the new # spec. It made sense for the old spec but now it is not required. return [{"var": {"variable": node.id, "index": last_definition}}] else: return [] def process_annotated_assign(self, node, state, *_): """ This function handles annotated assignment operations i.e. ast.AnnAssign. This tag appears when a variable has been assigned with an annotation e.g. x: int = 5, y: List[float] = [None], etc. """ # Get the sources and targets of the annotated assignment sources = self.gen_grfn(node.value, state, "annassign") targets = self.gen_grfn(node.target, state, "annassign") # If the source i.e. assigned value is `None` (e.g. day: List[int] = # [None]), only update the data type of the targets and populate the # `annotated_assigned` map. No further processing will be done. if ( len(sources) == 1 and ("value" in sources[0][0].keys()) and sources[0][0]["value"] is None ): for target in targets: state.variable_types[ target["var"]["variable"] ] = self.get_variable_type(node.annotation) if target["var"]["variable"] not in self.annotated_assigned: self.annotated_assigned.append(target["var"]["variable"]) # Check if these variables are io variables. We don't maintain # states for io variables. So, don't add them on the # last_definitions and next_definitions dict. io_match = self.check_io_variables(target["var"]["variable"]) if io_match: self.exclude_list.append(target["var"]["variable"]) # When a variable is AnnAssigned with [None] it is being # declared but not defined. So, it should not be assigned an # index. Having the index as -2 indicates that this variable # has only been declared but never defined. The next # definition of this variable should start with an index of 0 # though. if not io_match: target["var"]["index"] = -2 state.last_definitions[target["var"]["variable"]] = -2 state.next_definitions[target["var"]["variable"]] = 0 return [] grfn = {"functions": [], "variables": [], "containers": []} # Only a single target appears in the current version. The `for` loop # seems unnecessary but will be required when multiple targets start # appearing (e.g. a = b = 5). for target in targets: target_name = target["var"]["variable"] # Because we use the `last_definition_default` to be -1 for # functions with arguments, in these functions the annotated # assigns at the top of the function will get the -1 index which # is incorrect. if target["var"]["index"] == -1: target["var"]["index"] = 0 state.last_definitions[target_name] = 0 # Preprocessing and removing certain Assigns which only pertain # to the Python code and do not relate to the FORTRAN code in any # way. io_match = self.check_io_variables(target_name) if io_match: self.exclude_list.append(target_name) return [] state.variable_types[target_name] = self.get_variable_type( node.annotation ) if target_name not in self.annotated_assigned: self.annotated_assigned.append(target_name) # Update the `next_definition` index of the target since it is # not being explicitly done by `process_name`. # TODO Change this functionality ground up by modifying # `process_name` and `process_subscript` to make it simpler. if not state.next_definitions.get(target_name): state.next_definitions[target_name] = ( target["var"]["index"] + 1 ) variable_spec = self.generate_variable_definition( [target_name], None, False, state ) function_name = self.generate_function_name( "__assign__", variable_spec["name"], None ) # If the source is a list inside of a list, remove the outer list if len(sources) == 1 and isinstance(sources[0], list): sources = sources[0] # TODO Somewhere around here, the Float32 class problem will have # to be handled. fn = self.make_fn_dict(function_name, target, sources, state) if len(sources) > 0: lambda_string = self.generate_lambda_function( node, function_name["name"], False, True, False, False, [ src["var"]["variable"] for src in sources if "var" in src ], [], state, False, ) fn["function"]["code"] = lambda_string # In the case of assignments of the form: "ud: List[float]" # an assignment function will be created with an empty input # list. Also, the function dictionary will be empty. We do # not want such assignments in the GrFN so check for an empty # <fn> dictionary and return [] if found if len(fn) == 0: return [] grfn["functions"].append(fn) grfn["variables"].append(variable_spec) return [grfn] def process_assign(self, node, state, *_): """ This function handles an assignment operation (ast.Assign). """ io_source = False is_function_call = False maybe_d_type_object_assign = False d_type_object_name = None # Get the GrFN element of the RHS side of the assignment which are # the variables involved in the assignment operations. sources = self.gen_grfn(node.value, state, "assign") node_name = node.targets[0].__repr__().split()[0][2:] if node_name == "ast.Attribute": node_value = node.targets[0].value attrib_ast = node_value.__repr__().split()[0][2:] if ( attrib_ast == "ast.Name" and node_value.id in self.derived_type_objects ): maybe_d_type_object_assign = True d_type_object_name = node_value.id object_type = self.derived_type_objects[d_type_object_name] elif ( attrib_ast == "ast.Attribute" and node_value.value.id in self.derived_type_objects ): maybe_d_type_object_assign = True d_type_object_name = node_value.value.id object_type = self.derived_type_objects[d_type_object_name] array_assignment = False is_d_type_obj_declaration = False # Detect assigns which are string initializations of the # following form: String(10). String initialization of the form # String(10, "abcdef") are valid assignments where the index of the # variables will be incremented but for the former case the index # will not be incremented and neither will its variable spec be # generated is_string_assign = False is_string_annotation = False if len(sources) > 0 and "call" in sources[0]: type_name = sources[0]["call"]["function"] if type_name == "String": is_string_assign = True # Check if it just an object initialization or initialization # with value assignment if len(sources[0]["call"]["inputs"]) == 1: # This is just an object initialization e.g. String(10) is_string_annotation = True elif type_name == "Array": array_assignment = True array_dimensions = [] inputs = sources[0]["call"]["inputs"] # If the array type is string, the structure of inputs will # be a bit different than when it is int of float if "call" in inputs[0][0]: if inputs[0][0]["call"]["function"] == "String": array_type = "string" else: array_type = inputs[0][0]["var"]["variable"] self._get_array_dimension(sources, array_dimensions, inputs) elif type_name in self.derived_types: is_d_type_obj_declaration = True if isinstance(node.targets[0], ast.Name): variable_name = node.targets[0].id if variable_name not in self.module_variable_types: for program in self.mode_mapper["public_objects"]: if ( variable_name in self.mode_mapper["public_objects"][program] ): self.module_variable_types[variable_name] = [ program, type_name, ] else: pass else: pass # This reduce function is useful when a single assignment operation # has multiple targets (E.g: a = b = 5). Currently, the translated # python code does not appear in this way and only a single target # will be present. targets = reduce( (lambda x, y: x.append(y)), [ self.gen_grfn(target, state, "assign") for target in node.targets ], ) grfn = {"functions": [], "variables": [], "containers": []} # Again as above, only a single target appears in current version. # The `for` loop seems unnecessary but will be required when multiple # targets start appearing. target_names = [] object_attr_num = 1 for target in targets: # Bypass any assigns that have multiple targets. # E.g. (i[0], x[0], j[0], y[0],) = ... if "list" in target: return [] target_names.append(target["var"]["variable"]) # Fill some data structures if this is a string # assignment/initialization if is_string_assign: state.variable_types[target_names[0]] = "string" state.string_assign_name = target_names[0] self.strings[target_names[0]] = { "length": sources[0]["call"]["inputs"][0][0]["value"] } if is_string_annotation: # If this is just a string initialization, # last_definition should not contain this string's index. # This happens only during assignments. del state.last_definitions[target_names[0]] self.strings[target_names[0]]["annotation"] = True self.strings[target_names[0]]["annotation_assign"] = False return [] else: self.strings[target_names[0]]["annotation"] = False self.strings[target_names[0]]["annotation_assign"] = True # Pre-processing and removing certain Assigns which only pertain # to the Python code and do not relate to the FORTRAN code in any # way. io_match = self.check_io_variables(target_names[0]) if io_match: self.exclude_list.append(target_names[0]) return [] # When declaring a derived type, the source will be the name of the # derived type. If so, bypass the assign if ( len(sources) == 1 and "var" in sources[0] and sources[0]["var"]["variable"] in self.derived_types ): state.last_definitions[target_names[0]] = 0 return [] # If the target is a list of variables, the grfn notation for the # target will be a list of variable names i.e. "[a, b, c]" # TODO: This does not seem right. Discuss with Clay and Paul # about what a proper notation for this would be if target.get("list"): targets = ",".join( [x["var"]["variable"] for x in target["list"]] ) target = {"var": {"variable": targets, "index": 1}} if array_assignment: var_name = target["var"]["variable"] state.array_assign_name = var_name # Just like the same reason as the variables # declared with annotation within function (not # function arguments) need to have index of zero. # Thus, these 3 lines of code fixes the index to # correct value from -1 to 0. if target["var"]["index"] == -1: target["var"]["index"] = 0 state.last_definitions[target_names[0]] = 0 is_mutable = False array_info = { "index": target["var"]["index"], "dimensions": array_dimensions, "elem_type": array_type, "mutable": is_mutable, } self.arrays[var_name] = array_info state.array_types[var_name] = array_type if array_type == "string": length = inputs[0][0]["call"]["inputs"][0][0]["value"] self.strings[var_name] = { "length": length, "annotation": False, "annotation_assign": True, } if ( maybe_d_type_object_assign and object_type and object_type in self.derived_types_attributes and target_names[0] in self.derived_types_attributes[object_type] ): self.current_d_object_name = d_type_object_name is_d_type_object_assignment = True # If targets holds more than 1 variable information and # it's greater than the object attribute number, then # the derived type object is referencing more than # 1 attribute (i.e. x.k.v). if len(targets) > 1 and len(targets) > object_attr_num: object_attr_num += 1 # Therefore, we do not want to go any further before # collecting all the information of the attribute # information, so we need to simply return back to the # beginning of loop and restart the process continue else: is_d_type_object_assignment = False variable_spec = self.generate_variable_definition( target_names, d_type_object_name, is_d_type_object_assignment, state, ) # Do not add the variable spec if this is a string annotation # since this can collide with the variable spec of the first # string assignment. if not is_string_annotation: grfn["variables"].append(variable_spec) # Since a Python class (derived type) object declaration has syntax # is __object_name__ = __class_name__, it's considered as an # assignment that will create __assign__ function GrFN, # which should not. Thus, simply return the [grfn] here to avoid # generating __assign__ function. if is_d_type_obj_declaration: return [grfn] # TODO Hack to not print lambda function for IO assigns. Need a # proper method to handle IO moving on for src in sources: if "call" in src: if self.check_io_variables(src["call"]["function"]): io_source = True function = src["call"]["function"] # Check if the source is a function call by comparing its # value with the list of functions in our program ( # obtained from the mode mapper) for program_functions in self.mode_mapper["subprograms"]: if ( function in self.mode_mapper["subprograms"][ program_functions ] ): is_function_call = True if is_function_call: container_name = self.generate_container_id_name( self.fortran_file, ["@global"], function ) function_name = {"name": container_name, "type": "container"} else: function_name = self.generate_function_name( "__assign__", variable_spec["name"], None ) # If current assignment process is for a derived type object (i.e # x.k), then if is_d_type_object_assignment: # (1) we need to add derived type object as function input. if state.last_definitions.get(d_type_object_name) is not None: index = state.last_definitions[d_type_object_name] elif ( self.global_scope_variables and self.global_scope_variables.last_definitions.get( d_type_object_name ) is not None ): index = 0 else: # Set to default 0. index = 0 # assert False, f"{d_type_object_name} not defined in the " \ # f"the current scope: {self.current_scope} " \ # f"or globally." src = [ {"var": {"variable": d_type_object_name, "index": index,}} ] sources.extend(src) # (2) Generate the object name + attributes variable name new_var_name = d_type_object_name for target_name in target_names: new_var_name += f"__{target_name}" self.current_d_object_attributes.append(target_name) # (3) we need to modify thee target to be "objectName_attribute" # For example, variable: x_k and index: __index_of_x_y__. target["var"] = { "variable": new_var_name, "index": state.last_definitions[new_var_name], } fn = self.make_fn_dict(function_name, target, sources, state) if len(fn) == 0: return [] source_list = self.make_source_list_dict(sources) if not io_source and not is_function_call: lambda_string = self.generate_lambda_function( node, function_name["name"], True, array_assignment, is_string_assign, is_d_type_object_assignment, source_list, [], state, False, ) fn["function"]["code"] = lambda_string grfn["functions"].append(fn) # We need to cleanup the object attribute tracking list. self.current_d_object_attributes = [] return [grfn] def process_tuple(self, node, state, *_): """ This function handles the ast.Tuple node of the AST. This handled in the same way `process_list_ast` is handled. """ elements = [ element[0] for element in [ self.gen_grfn(list_element, state, "ctx") for list_element in node.elts ] ] return elements if len(elements) == 1 else [{"list": elements}] def process_call(self, node, state, *_): """ This function handles the ast.Call node of the AST. This node denotes the call to a function. The body contains of the function name and its arguments. """ # Check if the call is in the form of <module>.<function> (E.g. # math.exp, math.cos, etc). The `module` part here is captured by the # attribute tag. if isinstance(node.func, ast.Attribute): # Check if there is a <sys> call. Bypass it if exists. if ( isinstance(node.func.value, ast.Attribute) and isinstance(node.func.value.value, ast.Name) and node.func.value.value.id == "sys" ): return [] function_node = node.func # The `function_node` can be a ast.Name (e.g. Format(format_10) # where `format_10` will be an ast.Name or it can have another # ast.Attribute (e.g. Format(main.file_10.readline())). # Currently, only these two nodes have been detected, so test for # these will be made. if isinstance(function_node.value, ast.Name): module = function_node.value.id function_name = function_node.attr function_name = module + "." + function_name elif isinstance(function_node.value, ast.Attribute): module = self.gen_grfn(function_node.value, state, "call") function_name = "" func_name = function_node.attr if self.is_d_object_array_assign: function_name = self.current_d_object_name + "." self.is_d_object_array_assign = False function_name += module + "." + func_name elif isinstance(function_node.value, ast.Call): return self.gen_grfn(function_node.value, state, "call") elif isinstance(function_node.value, ast.Str) and hasattr( function_node, "attr" ): module = function_node.value.s function_name = module + function_node.attr else: assert False, ( f"Invalid expression call" f" {dump_ast(function_node)}" ) else: function_name = node.func.id inputs = [] for arg in node.args: argument = self.gen_grfn(arg, state, _) inputs.append(argument) call = {"call": {"function": function_name, "inputs": inputs}} return [call] def process_module(self, node, state, *_): """ This function handles the ast.Module node in the AST. The module node is the starting point of the AST and its body consists of the entire ast of the python code. """ grfn_list = [] for cur in node.body: node_name = cur.__repr__().split()[0][2:] grfn = self.gen_grfn(cur, state, "module") if grfn and "name" in grfn[0] and "@type" in grfn[0]["name"]: self.derived_types_grfn.append(grfn[0]) elif self.current_scope == "global" and node_name in [ "ast.AnnAssign", "ast.Assign", "ast.Expr", ]: if not self.global_grfn["containers"][0]["name"]: namespace = self._get_namespace(self.fortran_file) self.global_grfn["containers"][0][ "name" ] = f"@container::{namespace}::@global" self.global_grfn["containers"][0][ "gensym" ] = self.generate_gensym("container") if len(grfn) > 0: self.global_grfn["containers"][0]["body"] += grfn[0][ "functions" ] self.global_grfn["variables"] += grfn[0]["variables"] else: grfn_list += grfn if self.global_grfn["containers"][0]["name"]: grfn_list += [self.global_grfn] merged_grfn = [self._merge_dictionary(grfn_list)] return merged_grfn # TODO Implement this. This needs to be done for generality # We fill in the `updated` field of function calls by looking at the # `updated` field of their container grfn final_grfn = self.load_updated(merged_grfn) return final_grfn @staticmethod def _process_nameconstant(node, *_): # TODO Change this format according to the new spec if isinstance(node.value, bool): dtype = "boolean" else: dtype = "string" return [{"type": "literal", "dtype": dtype, "value": node.value}] def process_attribute(self, node, state, call_source): """ Handle Attributes: This is a fix on `feature_save` branch to bypass the SAVE statement feature where a SAVEd variable is referenced as <function_name>.<variable_name>. So the code below only returns the <variable_name> which is stored under `node.attr`. The `node.id` stores the <function_name> which is being ignored. """ # If this node appears inside an ast.Call processing, then this is # the case where a function call has been saved in the case of IO # handling. E.g. format_10_obj.read_line(main.file_10.readline())). # Here, main.file_10.readline is if call_source == "call": if ( isinstance(node.value, ast.Name) and node.value.id == self.current_d_object_name ): self.is_d_object_array_assign = True module = node.attr return module # When a computations float value is extracted using the Float32 # class's _val method, an ast.Attribute will be present if node.attr == "_val": return self.gen_grfn(node.value, state, call_source) else: node_value = node.__repr__().split()[0][2:] if node_value != "ast.Attribute": # TODO: This section of the code should be the same as # `process_name`. Verify this. last_definition = self.get_last_definition( node.attr, state.last_definitions, state.last_definition_default, ) # TODO Change the format according to the new spec return [ {"var": {"variable": node.attr, "index": last_definition}} ] else: ( attributes, last_definitions, ) = self.get_derived_type_attributes(node, state) # Derived type reference variable on the RHS of assignment # needs to have a syntax like x__b (x%b in Fortran), so first # form "x_" here. # Currently, only going two levels deep. # TODO: This can be arbitrary level deep if isinstance(node.value, ast.Name): new_variable = node.value.id + "_" elif isinstance(node.value, ast.Attribute) or isinstance( node.value, ast.Subscript ): new_variable = node.value.value.id + "_" elif ( isinstance(node.value, ast.Call) and node.value.func.attr == "get_" ): new_variable = node.value.func.value.id + "_" new_variable += f"_{node.value.args[0].value.id}_" else: assert ( False ), f"Too deep levels or unhandled type. {dump_ast(node)}." new_var_index = 0 for attr in attributes: # Then, append attributes to the new variable new_variable = new_variable + f"_{attr}_" new_var_index = last_definitions[attr] new_variable = new_variable[:-1] # Since we've generated a new variable, we need to update # last_definitions dictionary. state.last_definitions[new_variable] = 0 variable_info = { "var": {"variable": new_variable, "index": new_var_index,} } # In the case of a saved variable, this node is called from # the ast.Subscript if call_source == "subscript": attribs = [] for attr in attributes: variable_info = { "var": { "variable": attr, "index": last_definitions[attr], } } attribs.append(variable_info) return attribs return [variable_info] def process_return_value(self, node, state, *_): """ This function handles the return value from a function. """ grfn = {"functions": [], "variables": [], "containers": []} if node.value: val = self.gen_grfn(node.value, state, "return_value") else: val = None namespace = self._get_namespace(self.fortran_file) function_name = f"{namespace}__{self.current_scope}__return" function_name = self.replace_multiple( function_name, ["$", "-", ":"], "_" ) function_name = function_name.replace(".", "__") return_dict = { "function": {"name": function_name, "type": "return"}, "value": val, } grfn["functions"].append(return_dict) return [grfn] def process_class_def(self, node, state, *_): """This function handles user defined type (class) by populating types grfn attribute. """ class_name = node.name src_string_list = self.original_python_src.split("\n") isClass = False class_code = "" import_code = "" # Read in the Python source string line by line for line in src_string_list: # If the current line is a start of class definition # class myClass: # , then set isClass to True and append @dataclass # to class_code string variable class_info = syntax.is_class_def(line) if class_info[0] and class_info[1] == class_name: isClass = True state.lambda_strings.append("@dataclass\n") class_code += "@dataclass\n" # If isClass is True, then it means that current line # is part of class definition. if isClass: # If a line contains "=", then it means class variables # are one of Array, String, or derived-type type. if "=" in line: splitted_line = line.split("=") var = splitted_line[0].rstrip() rhs_split = splitted_line[1].split("(") class_type = rhs_split[0].strip() if len(rhs_split) > 1: data_type = rhs_split[1].split(",")[0].strip() else: data_type = None if class_type == "Array": if data_type == "String": data_type = "str" line = f"{var}:List[{data_type}]" elif class_type == "String": line = f"{var}:str" elif class_type in self.derived_types: # If type is derived-type, we neeed to extract the module name and # form "from __filename__ import __class_name__" string. # However, we have not discussed where this will be inserted, so # if found out, please modify it. for mod in self.imported_module_paths: mod_name = mod.split(".")[-1][2:] import_str = f"from {mod} import {class_type}\n" if ( mod_name in self.module_summary and import_str not in self.generated_import_codes ): self.generated_import_codes.append(import_str) import_code += import_str state.lambda_strings.insert(0, import_str) state.lambda_strings.append(line + "\n") class_code += f"{line.strip()}\n\t" if not line.strip(): isClass = False grfn = { "name": "", "type": "type", "attributes": [], "code": class_code.strip(), } namespace = self._get_namespace(self.fortran_file) type_name = f"@type::{namespace}::@global::{class_name}" grfn["name"] = type_name # Keep a track of declared user-defined types self.derived_types.append(node.name.lower()) self.derived_types_attributes[node.name] = [] attributes = node.body # Populate class member variables into attributes array. for attrib in attributes: attrib_is_array = False attrib_ast = attrib.__repr__().split()[0][2:] if attrib_ast == "ast.AnnAssign": attrib_name = attrib.target.id if attrib.annotation.id in self.annotate_map: attrib_type = self.annotate_map[attrib.annotation.id] elif attrib.annotation.id in self.derived_types: attrib_type = attrib.annotation.id elif attrib_ast == "ast.Assign": attrib_name = attrib.targets[0].id try: attrib_type = attrib.value.func.id except AttributeError: attrib_type = attrib.value.id assert ( attrib_type in self.derived_types or attrib_type in self.library_types ), f"User-defined type [{attrib_type}] does not exist." if attrib_type == "Array": attrib_is_array = True if attrib_is_array: elem_type = attrib.value.args[0].id # TODO: Currently, derived type array attributes are assumed # to be a single dimensional array with integer type. It maybe # appropriate to handle a multi-dimensional with variable used # as a dimension size. dimension_info = attrib.value.args[1] is_literal = False is_name = False single_dimension = False dimension_list = [] if isinstance(dimension_info.elts[0], ast.Tuple): lower_bound = int(dimension_info.elts[0].elts[0].n) single_dimension = True # Retrieve upper bound of an array. if isinstance(dimension_info.elts[0].elts[1], ast.Num): upper_bound = int(dimension_info.elts[0].elts[1].n) is_literal = True elif isinstance(dimension_info.elts[0].elts[1], ast.Name): upper_bound = dimension_info.elts[0].elts[1].id is_name = True else: assert False, ( f"Currently, ast type " f"[{type(dimension_info.elts[0].elts[1])}] is not " f"supported." ) if is_literal: dimension = (upper_bound - lower_bound) + 1 elif is_name: dimension = upper_bound else: pass dimension_list.append(dimension) elif isinstance(dimension_info.elts[0], ast.Call): lower_bound = int(dimension_info.elts[0].func.elts[0].n) if isinstance( dimension_info.elts[0].func.elts[1], ast.Num ): upper_bound = int( dimension_info.elts[0].func.elts[1].n ) is_literal = True elif isinstance( dimension_info.elts[0].func.elts[1], ast.Name ): upper_bound = dimension_info.elts[0].func.elts[1].id is_name = True if is_literal: first_dimension = (upper_bound - lower_bound) + 1 elif is_name: first_dimension = upper_bound dimension_list.append(first_dimension) lower_bound = int(dimension_info.elts[0].args[0].n) if isinstance(dimension_info.elts[0].args[1], ast.Num): upper_bound = int(dimension_info.elts[0].args[1].n) is_literal = True elif isinstance(dimension_info.elts[0].args[1], ast.Name): upper_bound = dimension_info.elts[0].args[1].id is_name = True if is_literal: second_dimension = (upper_bound - lower_bound) + 1 elif is_name: second_dimension = upper_bound dimension_list.append(second_dimension) dimensions = dimension_list grfn["attributes"].append( { "name": attrib_name, "type": attrib_type, "elem_type": elem_type, "dimensions": dimensions, } ) # Here index is not needed for derived type attributes, # but simply adding it as a placeholder to make a constant # structure with other arrays. self.arrays[attrib_name] = { "index": 0, "dimensions": dimensions, "elem_type": elem_type, "mutable": True, } else: grfn["attributes"].append( {"name": attrib_name, "type": attrib_type} ) pass self.derived_types_attributes[node.name].append(attrib_name) state.variable_types[attrib_name] = attrib_type return [grfn] def process_break(self, node, state, *_): """ Process the breaks in the file, adding an EXIT node """ # Get all the IF_X identifiers and pick the one with the largest # index because that is the current one if_ids = [ int(x[-1]) for x in state.last_definitions.keys() if "IF_" in x ] current_if = f"IF_{max(if_ids)}" self.exit_candidates.append({current_if: "break"}) grfn = { "functions": ["insert_break"], "variables": [], "containers": [], } return [grfn] @staticmethod def process_ast(node, *_): sys.stderr.write( f"No handler for AST.{node.__class__.__name__} in gen_grfn, " f"fields: {node._fields}\n" ) def process_load(self, node, state, call_source): raise For2PyError( f"Found ast.Load, which should not happen. " f"From source: {call_source}" ) def process_store(self, node, state, call_source): raise For2PyError( f"Found ast.Store, which should not happen. " f"From source: {call_source}" ) @staticmethod def process_nomatch(node, *_): sys.stderr.write( f"No handler for {node.__class__.__name__} in gen_grfn, " f"value: {str(node)}\n" ) @staticmethod def _get_namespace(original_fortran_file) -> str: """ This function returns the namespace for every identifier in the system being analyzed. Currently, this function is very barebone and just returns the name of the system being evaluated. After more testing with modules and imports, the namespace will expand into more than just the system file name. """ namespace_path_list = get_path(original_fortran_file, "namespace") namespace_path = ".".join(namespace_path_list) # TODO Hack: Currently only the last element of the # `namespace_path_list` is being returned as the `namespace_path` in # order to make it consistent with the handwritten SIR-Demo GrFN # JSON. Will need a more generic path for later instances. namespace_path = namespace_path_list[-1] return namespace_path def make_source_list_dict(self, source_dictionary): source_list = [] # If the source is a list inside of a list, remove the outer list if len(source_dictionary) == 1 and isinstance( source_dictionary[0], list ): source_dictionary = source_dictionary[0] for src in source_dictionary: if "var" in src: if src["var"]["variable"] not in self.annotate_map: source_list.append(src["var"]["variable"]) elif "call" in src: for ip in src["call"]["inputs"]: source_list.extend(self.make_source_list_dict(ip)) if ( "f_index" in src["call"]["function"] or "get_substr" in src["call"]["function"] ): string_var = src["call"]["function"].split(".")[0] source_list.append(string_var) elif "list" in src: for ip in src["list"]: if "var" in ip: source_list.append(ip["var"]["variable"]) # Removing duplicates unique_source = [] [ unique_source.append(obj) for obj in source_list if obj not in unique_source ] source_list = unique_source return source_list def make_fn_dict(self, name, target, sources, state): source = [] fn = {} io_source = False target_name = target["var"]["variable"] target_string = f"@variable::{target_name}::{target['var']['index']}" # If the source is a list inside of a list, remove the outer list if len(sources) == 1 and isinstance(sources[0], list): sources = sources[0] for src in sources: # Check for a write to a file if re.match(r"\d+", target_name) and "list" in src: return fn if "call" in src: function_name = src["call"]["function"] method_var = function_name.split(".") if len(method_var) > 1: method_name = method_var[1] else: method_name = function_name # Remove first index of an array function as it's # really a type name not the variable for input. if function_name == "Array": del src["call"]["inputs"][0] # If a RHS of an assignment is an array getter, # for example, meani.get_((runs[0])), we only need # the array name (meani in this case) and append # to source. # if ".get_" in src["call"]["function"]: if method_name == "get_": get_array_name = src["call"]["function"].replace( ".get_", "" ) var_arr_name = f"@variable::{get_array_name}::-1" source.append(var_arr_name) # Bypassing identifiers who have I/O constructs on their source # fields too. # Example: (i[0],) = format_10_obj.read_line(file_10.readline()) # 'i' is bypassed here # TODO this is only for PETASCE02.for. Will need to include 'i' # in the long run bypass_match_source = self.check_io_variables(function_name) if bypass_match_source: if "var" in src: self.exclude_list.append(src["var"]["variable"]) # TODO This is a hack for SIR's retval to be included as # an assign function (will not have an input). But, # moving on a proper method for handling IO is required. # Uncomment the line below to revert to old form. # return fn io_source = True # TODO Finalize the spec for calls here of this form: # "@container::<namespace_path_string>::<scope_path_string>:: # <container_base_name>" and add here. if not io_source: for source_ins in self.make_call_body_dict(src): source.append(source_ins) # Check for cases of string index operations if method_name in ["f_index", "get_substr"]: string_var = src["call"]["function"].split(".")[0] index = state.last_definitions[string_var] source.append(f"@variable::{string_var}::{index}") elif "var" in src: source_string = ( f"@variable::{src['var']['variable']}::" f"{src['var']['index']}" ) source.append(source_string) # The code below is commented out to not include any `literal` # values in the input of `function` bodies. The spec does mention # including `literals` so if needed, uncomment the code block below # elif "type" in src and src["type"] == "literal": # variable_type = self.type_def_map[src["dtype"]] # source_string = f"@literal::{variable_type}::{src['value']}" # source.append(source_string) # else: # assert False, f"Unidentified source: {src}" # Removing duplicates unique_source = [] [ unique_source.append(obj) for obj in source if obj not in unique_source ] source = unique_source fn = { "function": name, "input": source, "output": [target_string], "updated": [], } return fn @staticmethod def _remove_io_variables(variable_list): """ This function scans each variable from a list of currently defined variables and removes those which are related to I/O such as format variables, file handles, write lists and write_lines. """ io_regex = re.compile( r"(format_\d+_obj)|(file_\d+)|(write_list_\d+)|" r"(write_line)" ) io_match_list = [io_regex.match(var) for var in variable_list] return [ var for var in variable_list if io_match_list[variable_list.index(var)] is None ] def make_call_body_dict(self, source): """ We are going to remove addition of functions such as "max", "exp", "sin", etc to the source list. The following two lines when commented helps us do that. If user-defined functions come up as sources, some other approach might be required. """ # TODO Try with user defined functions and see if the below two lines # need to be reworked # name = source["call"]["function"] # source_list.append({"name": name, "type": "function"}) source_list = [] for ip in source["call"]["inputs"]: if isinstance(ip, list): for item in ip: if "var" in item: source_string = ( f"@variable::" f"{item['var']['variable']}::" f"{item['var']['index']}" ) source_list.append(source_string) # TODO Adding boolean literals as an input to an assign # function but not integer literals? elif ( "type" in item and item["type"] == "literal" and item["dtype"] == "boolean" ): source_string = ( f"@literal::" f"{item['dtype']}::" f"{item['value']}" ) source_list.append(source_string) elif "call" in item: source_list.extend(self.make_call_body_dict(item)) elif "list" in item: # Handles a case where array declaration size # was given with a variable value. for value in item["list"]: if "var" in value: variable = ( f"@variable:" f":{value['var']['variable']}::0" ) source_list.append(variable) return source_list def process_decorators(self, node, state): """ Go through each decorator and extract relevant information. Currently this function only checks for the static_vars decorator for the SAVEd variables and updates variable_types with the data type of each variable. """ for decorator in node: decorator_function_name = decorator.func.id if decorator_function_name == "static_vars": for arg in decorator.args[0].elts: variable = arg.values[0].s variable_type = arg.values[2].s if "String" in variable_type: length_regex = re.compile(r"String\((\d+)\)", re.I) match = length_regex.match(variable_type) if match: length = match.group(1) elif ( hasattr(arg.values[1], "func") and hasattr(arg.values[1], "args") and hasattr(arg.values[1].args[0], "args") ): length = arg.values[1].args[0].args[0].n else: assert ( False ), "Could not identify valid String type" self.strings[variable] = { "length": length, "annotation": False, "annotation_assign": False, } state.variable_types[variable] = self.annotate_map[ "String" ] else: state.variable_types[variable] = self.annotate_map[ variable_type ] @staticmethod def process_try(node, state, call_source): return [] @staticmethod def _merge_dictionary(dicts: Iterable[Dict]) -> Dict: """ This function merges the entire dictionary created by `gen_grfn` into another dictionary in a managed manner. The `dicts` argument is a list of form [{}, {}, {}] where each {} dictionary is the grfn specification of a function. It contains `functions` and `identifiers` as its keys. Additionally, if the python code has a starting point, that is also present in the last {} of `dicts`. The function merges the values from the `functions` key of each {} in `dicts` into a single key of the same name. Similarly, it does this for every unique key in the `dicts` dictionaries. """ fields = set(chain.from_iterable(d.keys() for d in dicts)) merged_dict = {field: [] for field in fields} # Create a cross-product between each unique key and each grfn # dictionary for field, d in product(fields, dicts): if field in d: if isinstance(d[field], list): merged_dict[field] += d[field] else: merged_dict[field].append(d[field]) return merged_dict def get_last_definition( self, var, last_definitions, last_definition_default ): """ This function returns the last (current) definition (index) of a variable. """ index = last_definition_default # Pre-processing and removing certain Assigns which only pertain to the # Python code and do not relate to the FORTRAN code in any way. bypass_match = self.re_bypass_io.match(var) if not bypass_match: if var in last_definitions: index = last_definitions[var] else: last_definitions[var] = index return index else: return 0 @staticmethod def _get_next_definition( var, last_definitions, next_definitions, last_definition_default ): """ This function returns the next definition i.e. index of a variable. """ # The dictionary `next_definitions` holds the next index of all current # variables in scope. If the variable is not found (happens when it is # assigned for the first time in a scope), its index will be one greater # than the last definition default. index = next_definitions.get(var, last_definition_default + 1) # Update the next definition index of this variable by incrementing # it by 1. This will be used the next time when this variable is # referenced on the LHS side of an assignment. next_definitions[var] = index + 1 # Also update the `last_definitions` dictionary which holds the current # index of all variables in scope. last_definitions[var] = index return index def get_variable_type(self, annotation_node): """ This function returns the data type of a variable using the annotation information used to define that variable """ # If the variable has been wrapped in a list like x: List[int], # `annotation_node` will be a Subscript node if isinstance(annotation_node, ast.Subscript): data_type = annotation_node.slice.value.id else: data_type = annotation_node.id if self.annotate_map.get(data_type): return self.annotate_map[data_type] elif data_type in self.derived_types: return data_type else: assert False, ( "Unsupported type (only float, int, list, real, " "bool and str supported as of now).\n" ) @staticmethod def _get_variables_and_functions(grfn): variables = list( chain.from_iterable(stmt["variables"] for stmt in grfn) ) fns = list(chain.from_iterable(stmt["functions"] for stmt in grfn)) containers = list( chain.from_iterable(stmt["containers"] for stmt in grfn) ) return variables, fns, containers def generate_gensym(self, tag): """ The gensym is used to uniquely identify any identifier in the program. Python's uuid library is used to generate a unique 12 digit HEX string. The uuid4() function of 'uuid' focuses on randomness. Each and every bit of a UUID v4 is generated randomly and with no inherent logic. To every gensym, we add a tag signifying the data type it represents. 'v': variables 'c': containers 'f': functions """ return f"{self.gensym_tag_map[tag]}_{uuid.uuid4().hex[:12]}" def generate_lambda_function( self, node, function_name: str, return_value: bool, array_assign: bool, string_assign: bool, d_type_assign: bool, inputs, decision_versions, state, is_custom: bool, ): self.generated_lambda_functions.append(function_name) lambda_for_var = True inline_lambda = "lambda " lambda_strings = ["\n"] argument_strings = [] # We need to remove the attribute (class member var) from # the source_list as we do not need it in the lambda function # argument. Also, form an __object.attribute__ string. if d_type_assign: d_type = state.variable_types[self.current_d_object_name] target_name = self.current_d_object_name for attr in self.current_d_object_attributes: if attr in self.derived_types_attributes[d_type]: target_name += f".{attr}" # Since the next attribute that will be seen must be # dependent on the current attribute type, here it's # updating the d_type. d_type = state.variable_types[attr] # If a custom lambda function is encountered, create its function # instead if is_custom: lambda_strings.append( f"def {function_name}({', '.join(inputs)}):\n " ) inline_lambda += f"{','.join(inputs)}:" if return_value: if isinstance(node, str): lambda_strings.append(f"return {node}") inline_lambda += node elif isinstance(node, int): lambda_strings.append(f"return {node}") inline_lambda += f"{node}" elif isinstance(node, list) and node[0] == "EXIT": exit_string = f"(not {inputs[0]})" for ip in inputs[1:]: exit_string += f" or (not {ip})" lambda_strings.append(f"return {exit_string}") inline_lambda += exit_string else: lambda_code_generator = genCode(self.use_numpy) code = lambda_code_generator.generate_code( node, PrintState("\n ") ) lambda_strings.append(f"return {code}") inline_lambda += code else: assert False, f"Should always return" lambda_strings.append("\n\n") return inline_lambda # return "".join(lambda_strings) # Sort the arguments in the function call as it is used in the operation input_list = sorted(set(inputs), key=inputs.index) if "__decision__" in function_name: argument_map = self._generate_argument_map(inputs) input_list = list(argument_map.values()) # Add type annotations to the function arguments for ip in input_list: annotation = state.variable_types.get(ip) if ip in state.array_types: lambda_for_var = False if lambda_for_var and not annotation: # `variable_types` does not contain annotations for variables # for indexing such as 'abc_1', etc. Check if the such variables # exist and assign appropriate annotations key_match = lambda var, dicn: ([i for i in dicn if i in var]) if len(key_match(ip, state.variable_types)) > 0: annotation = state.variable_types[ key_match(ip, state.variable_types)[0] ] # function argument requires annotation only when # it's dealing with simple variable (at least for now). # TODO String assignments of all kinds are class/method related # operations and will not involve annotations. Discuss this. if lambda_for_var and annotation != "string": if annotation in self.annotate_map: annotation = self.annotate_map[annotation] # else: # assert annotation in self.derived_types, ( # f"Annotation must be a regular type or user defined " # f"type. Annotation: {annotation}" # ) if annotation: if ( annotation not in self.annotate_map and annotation in self.derived_types ): for mod in self.imported_module_paths: mod_name = mod.split(".")[-1][2:] import_str = f"from {mod} import {annotation}\n" if ( mod_name in self.module_summary and annotation in self.module_summary[mod_name][ "derived_type_list" ] and import_str not in state.lambda_strings ): state.lambda_strings.insert(0, import_str) argument_strings.append(f"{ip}: {annotation}") else: argument_strings.append(f"{ip}") # Currently, this is for array specific else case. else: argument_strings.append(ip) lambda_for_var = True lambda_strings.append( f"def {function_name}({', '.join(argument_strings)}):\n " ) inline_lambda += f"{','.join(input_list)}:" # A case where calculating the sum of array. # In this case, we do not have to invoke genCode function(s). if ( isinstance(node, ast.Assign) and isinstance(node.value, ast.Call) and "attr" in node.value.func._fields and node.value.func.attr == "get_sum" ): arr_name = node.value.func.value.id # TODO: Currently, only handles 1D-list to satisfy cases # that onnly appears in the Min-SPAM files. lambda_strings.append(f"return sum({arr_name})\n") inline_lambda += f"sum({arr_name})" return inline_lambda # return "".join(lambda_strings) # If a `decision` tag comes up, override the call to genCode to manually # enter the python script for the lambda file. if "__decision__" in function_name: # Get the condition var to know the instance of IF function we're # on i.e. COND_1 or COND_0 and so on condition_var = inputs[0].rsplit("_", 2)[0] # Get the maximum number of `if COND` booleans we have for this # if container max_conditions = state.last_definitions.get("#cond", 0) code = self._generate_decision_lambda( decision_versions, condition_var, max_conditions, inputs[-1].rsplit("_", 1)[0], argument_map, ) elif not string_assign: array_name = None if state.array_assign_name: array_name = state.array_assign_name.split("[")[0] if array_name in self.strings: lambda_code_generator = genCode( self.use_numpy, self.strings[array_name]["length"] ) else: lambda_code_generator = genCode(self.use_numpy) code = lambda_code_generator.generate_code( node, PrintState("\n ") ) if return_value: if array_assign: if "_" in state.array_assign_name: names = state.array_assign_name.split("_") if names[0] == self.current_d_object_name: state.array_assign_name = state.array_assign_name.replace( "_", "." ) lambda_strings.append(f"{state.array_assign_name} = {code}\n") lambda_strings.append(f" return {array_name}") if "[" in state.array_assign_name: array_split = state.array_assign_name.split("[") array_name = array_split[0] array_index = array_split[1][:-1] code = ( f"({array_name}.__setitem__({array_index},{code})," f"{array_name})[1]" ) state.array_assign_name = None elif string_assign: lambda_code_generator = genCode( self.use_numpy, self.strings[state.string_assign_name]["length"], ) code = lambda_code_generator.generate_code( node, PrintState("\n "), ) if self.strings[state.string_assign_name]["annotation"]: self.strings[state.string_assign_name][ "annotation" ] = False if self.strings[state.string_assign_name]["annotation_assign"]: self.strings[state.string_assign_name][ "annotation_assign" ] = False lambda_strings.append(f"return {code}") state.string_assign_name = None elif d_type_assign: lambda_strings.append(f"{target_name} = {code}\n") lambda_strings.append(f" return {target_name}") else: lambda_strings.append(f"return {code}") else: lines = code.split("\n") indent = re.search("[^ ]", lines[-1]).start() lines[-1] = lines[-1][:indent] + "return " + lines[-1][indent:] lambda_strings.append("\n".join(lines)) lambda_strings.append("\n\n") inline_lambda += code return inline_lambda # return "".join(lambda_strings) def generate_container_id_name( self, namespace_file: str, scope_path, container_basename: str ) -> str: namespace = self._get_namespace(namespace_file) if isinstance(scope_path, list): scope_path_string = ".".join(scope_path) elif isinstance(scope_path, str): scope_path_string = scope_path else: assert False, f"Invalid scope_path type {scope_path}" container_id = ( f"@container::{namespace}::{scope_path_string}::" f"{container_basename}" ) return container_id def generate_variable_definition( self, variables, reference, d_type_object_assign, state ): """ This function generates the GrFN structure for a variable definition, of the form: variable: { name: source_refs: gensym: domain: domain_constraints: } Args: variables (list): List of variables. reference (str): Either array's indexing variable (i.e. i for array[i]) or derived type object's referencing class member variable (i.e. k for x.k) Returns: list : Generated GrFN. """ namespace = self._get_namespace(self.fortran_file) index = [] domains = [] for variable in variables: if variable in state.last_definitions: index.append(state.last_definitions[variable]) elif ( variable in self.strings and self.strings[variable]["annotation"] ): # If this is a string initialization without assignment, # the index will be 0 by default index.append(0) elif variable in self.arrays: index.append(0) domains.append(self.get_domain_dictionary(variable, state)) for domain in domains: # Since we need to update the domain of arrays that # were passed to a function once the program actually # finds about it, we need to temporarily hold the domain # information in the dictionary of domain list. if "name" in domain: if domain["name"] == "array": if variable in self.array_arg_domain: self.array_arg_domain[variable].append(domain) else: self.array_arg_domain[variable] = [domain] elif domain["name"] in self.derived_types: self.derived_type_objects[variable] = domain["name"] # Only array variables hold dimensions in their domain # when they get declared, we identify the array variable # declaration by simply checking the existence of the dimensions # key in the domain. Also, the array was previously passed # to functions. if "dimensions" in domain and variable in self.array_arg_domain: # Since we can't simply do "dom = domain" # as this will do a replacement of the dict element # not the actual domain object of the original function # argument, we need to clean off the existing contents # first and then add the array domain spec one-by-one. for dom in self.array_arg_domain[variable]: if "name" in dom: del dom["name"] if "type" in dom: del dom["type"] dom["index"] = domain["index"] dom["dimensions"] = domain["dimensions"] dom["elem_type"] = domain["elem_type"] dom["mutable"] = domain["mutable"] variable_gensym = self.generate_gensym("variable") if reference is not None: if d_type_object_assign: variable = reference for var in variables: variable += f"__{var}" # else: # variable = f"{variable}_{reference}" # TODO: The code above has been commented for now but not removed. # Remove this when everything works and the line below doesn't # give any issues state.last_definitions[variable] = index[0] variable_name = ( f"@variable::{namespace}::{self.current_scope}::" f"{variable}::{index[0]}" ) # TODO Change the domain constraint. How do you figure out the domain # constraint? domain_constraint = "(and (> v -infty) (< v infty))" variable_definition = { "name": variable_name, "gensym": variable_gensym, "source_refs": [], "domain": domain, "domain_constraint": domain_constraint, } return variable_definition def get_domain_dictionary(self, variable, state): if variable in self.arrays: domain_dictionary = self.arrays[variable] else: type_name = None if ( variable in state.variable_types and state.variable_types[variable] ): variable_type = state.variable_types[variable] elif variable in self.module_variable_types: variable_type = self.module_variable_types[variable][1] # Is this a derived type variable elif "__" in variable: variable_tail = variable.split("__")[-1] if ( variable_tail in state.variable_types and state.variable_types[variable_tail] ): variable_type = state.variable_types[variable_tail] else: assert False, f"unrecognized variable: {variable}" else: variable_type = None # assert False, f"unrecognized variable: {variable}" # Mark if a variable is mutable or not. if ( variable in self.variable_map and self.variable_map[variable]["parameter"] ): is_mutable = True else: is_mutable = False # Array as a function argument handler. if self.handling_f_args and variable_type == "array": self.f_array_arg.append(variable) # Retrieve variable type name (i.e. integer, float, # __derived_type__) if variable_type in self.type_def_map: type_name = self.type_def_map[variable_type] elif variable_type in self.derived_types: type_name = variable_type # Since derived type variables are not a regular type variable, # we need to needs to them manually here into variable_types # dictionary to be referenced later in the stream. state.variable_types[variable] = type_name elif variable_type == "Real": type_name = "float" elif len(self.imported_module) > 0: for mod in self.imported_module: if ( mod in self.module_summary and variable in self.module_summary[mod]["symbol_types"] ): type_name = self.module_summary[mod]["symbol_types"] else: type_found = False if len(self.module_names) > 1: for mod in self.module_names: if ( mod != "main" and mod in self.module_summary and variable_type in self.module_summary[mod]["derived_type_list"] ): type_found = True type_name = variable_type state.variable_types[variable] = type_name domain_dictionary = { "name": type_name, "type": "type", "mutable": is_mutable, } return domain_dictionary def generate_function_name(self, function_type, variable, arr_index): """ This function generates the name of the function inside the container wiring within the body of a container. """ variable_spec_regex = ( r"@.*?::(?P<namescope>.*?::.*?)::(" r"?P<variable>.*?)::(?P<index>.*)" ) variable_match = re.match(variable_spec_regex, variable) if variable_match: namespace_scope = variable_match.group("namescope") variable_name = variable_match.group("variable") if arr_index: variable_name += "_" for index in arr_index: variable_name = variable_name + f"{index}" variable_index = variable_match.group("index") name = ( namespace_scope + function_type + variable_name + "::" + variable_index ) name = self.replace_multiple(name, ["$", "-", ":"], "_") name = name.replace(".", "__") if any( [ x in function_type for x in ["assign", "condition", "decision"] ] ): spec_type = "lambda" else: spec_type = "None" else: assert False, f"Cannot match regex for variable spec: {variable}" return {"name": name, "type": spec_type} def load_updated(self, grfn_dict): """ This function parses through the GrFN once and finds the container spec of functions whose `updated` fields needs to be filled in that functions' function call spec. """ for container in self.function_argument_map: if container in self.update_functions: for container_grfn in grfn_dict[0]["containers"]: for body_function in container_grfn["body"]: function_name = body_function["function"]["name"] if ( function_name.startswith("@container") and function_name.split("::")[-1] == container ): updated_variable = [ body_function["input"][i] for i in self.function_argument_map[container][ "updated_indices" ] ] for i in range(len(updated_variable)): old_index = int( updated_variable[i].split("::")[-1] ) new_index = old_index + 1 updated_var_list = updated_variable[i].split( "::" )[:-1] updated_var_list.append(str(new_index)) updated_variable[i] = "::".join( updated_var_list ) self.current_scope = self.update_functions[ container ]["scope"] variable_name = updated_var_list[1] variable_spec = self.generate_variable_definition( variable_name, None, False, self.update_functions[container]["state"], ) variable_name_list = variable_spec[ "name" ].split("::")[:-1] variable_name_list.append(str(new_index)) variable_spec["name"] = "::".join( variable_name_list ) grfn_dict[0]["variables"].append(variable_spec) body_function["updated"] = updated_variable return grfn_dict @staticmethod def _get_array_dimension(sources, array_dimensions, inputs): """This function is for extracting bounds of an array. Args: sources (list): A list holding GrFN element of array function. For example, Array (int, [[(0, 10)]). array_dimensions (list): An empty list that will be populated by current function with the dimension info. inputs (list): A list that holds inputs dictionary extracted from sources. Returns: None. """ # A multi-dimensional array handler if len(inputs[1]) > 1: for lst in inputs[1]: low_bound = int(lst[0]["list"][0]["value"]) upper_bound = int(lst[0]["list"][1]["value"]) array_dimensions.append(upper_bound - low_bound + 1) # 1-D array handler else: bounds = inputs[1][0][0]["list"] # Get lower bound of an array if "type" in bounds[0]: # When an index is a scalar value low_bound = bounds[0]["value"] else: # When an index is a variable low_bound = bounds[0]["var"]["variable"] # Get upper bound of an array if "type" in bounds[1]: upper_bound = bounds[1]["value"] else: upper_bound = bounds[1]["var"]["variable"] if isinstance(low_bound, int) and isinstance(upper_bound, int): array_dimensions.append(upper_bound - low_bound + 1) elif isinstance(upper_bound, str): # assert ( # isinstance(low_bound, int) and low_bound == 0 # ), "low_bound must be <integer> type and 0 (zero) for now." array_dimensions.append(upper_bound) else: assert False, ( f"low_bound type: {type(low_bound)} is " f"currently not handled." ) def _generate_array_setter( self, node, function, arg, name, container_id_name, arr_index, state ): """ This function is for handling array setter (ex. means.set_(...)). Args: node: The node referring to the array function (list): A list holding the information of the function for JSON and lambda function generation. arg (list): A list holding the arguments of call['inputs']. name (str): A name of the array. container_id_name (str): A name of function container. It's an array name with other appended info. in this function. arr_index (str): Index of a target array. state: The current state of the system Returns: (list) function: A completed list of function. """ if "_" in name: names = name.split("_") if names[0] == self.current_d_object_name: argument_list = [names[0]] else: argument_list = [name] else: argument_list = [name] # Array index is always one of # the lambda function argument for idx in arr_index: if idx not in self.arithmetic_ops and isinstance(idx, str): argument_list.append(idx) # For array setter value handler for var in arg[0]["call"]["inputs"][0]: # If an input is a simple variable. if "var" in var: var_name = var["var"]["variable"] if var_name not in argument_list: input_index = self.get_last_definition( var_name, state.last_definitions, state.last_definition_default, ) function["input"].append( f"@variable::" f"{var_name}::" f"{input_index}" ) argument_list.append(var_name) else: # It's not an error, so just pass it. pass # If an input is an array. elif "call" in var: ref_call = var["call"] if ".get_" in ref_call["function"]: get_array_name = ref_call["function"].replace(".get_", "") if get_array_name not in argument_list: argument_list.append(get_array_name) if get_array_name != name: ip_index = self.get_last_definition( get_array_name, state.last_definitions, state.last_definition_default, ) function["input"].append( f"@variable::" f"{get_array_name}::" f"{ip_index}" ) else: # It's not an error, so just pass it. pass # Generate lambda function for array[index] lambda_string = self.generate_lambda_function( node, container_id_name, True, True, False, False, argument_list, [], state, False, ) function["function"]["code"] = lambda_string return function def _generate_array_index(self, node): """This function is for generating array index grfn handling both single and multi-dimensional arrays. Args: node: The node referring to the array. Returns: (list) index: Formed array index. """ args = node.value.args[0] args_name = args.__repr__().split()[0][2:] # Case 1: Single dimensional array if args_name == "ast.Subscript": if hasattr(args.value, "value"): return [args.value.value.id] else: return [args.value.id] elif args_name == "ast.Num": return [int(args.n) - 1] # Case 1.1: Single dimensional array with arithmetic # operation as setter index elif args_name == "ast.BinOp": left_ast = args.left.__repr__().split()[0][2:] right_ast = args.right.__repr__().split()[0][2:] # Get the operator's left side value if left_ast == "ast.Subscript": left = args.left.value.id elif left_ast == "ast.Num": left = args.left.n # Get the arithmetic operator op = self.arithmetic_ops[args.op.__repr__().split()[0][6:]] # Get the operator's right side value if right_ast == "ast.Subscript": right = args.right.value.id elif right_ast == "ast.Num": right = args.right.n return [left, op, right] # Case 2: Multi-dimensional array elif args_name == "ast.Tuple": if hasattr(node.value.func.value, "id"): md_array_name = node.value.func.value.id elif hasattr(node.value.func.value, "value"): md_array_name = node.value.func.value.value.id if md_array_name not in self.md_array: self.md_array.append(md_array_name) dimensions = args.elts dimension_list = [] for dimension in dimensions: ast_name = dimension.__repr__().split()[0][2:] if ast_name == "ast.Subscript": if hasattr(dimension.value, "id"): dimension_list.append(dimension.value.id) elif hasattr(dimension.value, "value"): dimension_list.append(dimension.value.value.id) elif ast_name == "ast.Call": dimension_list.append(dimension.func.value.value.id) else: assert ast_name == "ast.Num", ( f"Unable to handle {ast_name} for multi-dimensional " f"array - node: {dump_ast(node)}\n" f"dimension: {dump_ast(dimension)}" ) return dimension_list else: assert False, f"Unable to handle {args_name}" def get_derived_type_attributes(self, node, state): """ This function retrieves the derived type attributes from the ast and return the updated last definition dict and populated attribute list""" attributes = [] node_value = node.value.__repr__().split()[0][2:] if node_value == "ast.Attribute" and node.value.attr: attributes.append(node.value.attr) if node.attr: attributes.append(node.attr) last_definitions = {} for attrib in attributes: last_definitions[attrib] = self.get_last_definition( attrib, state.last_definitions, state.last_definition_default ) return attributes, last_definitions @staticmethod def replace_multiple(main_string, to_be_replaced, new_string): """ Replace a set of multiple sub strings with a new string in main string. """ # Iterate over the strings to be replaced for elem in to_be_replaced: # Check if string is in the main string if elem in main_string: # Replace the string main_string = main_string.replace(elem, new_string) return main_string @staticmethod def _find_updated(argument_list, body_variable_list, f_array_arg, state): """ This function finds and generates a list of updated identifiers in a container. """ # TODO After implementing everything, check if `argument_dict` and # `body_dict` will be the same as `function_state.last_definitions` # before and after getting `body_grfn`. If so, remove the creation # of `argument_dict` and `body_dict` and use the `last_definitions` # instead argument_dict = {} body_dict = {} updated_list = [] variable_regex = re.compile(r".*::(?P<variable>.*?)::(?P<index>.*$)") # First, get mapping of argument variables and their indexes for var in argument_list: var_match = variable_regex.match(var["name"]) if var_match: argument_dict[var_match.group("variable")] = var_match.group( "index" ) else: assert False, ( f"Error when parsing argument variable " f"{var['name']}" ) # Now, get mapping of body variables and their latest indexes for var in body_variable_list: var_match = variable_regex.match(var["name"]) if var_match: body_dict[var_match.group("variable")] = var_match.group( "index" ) else: assert False, ( f"Error when parsing body variable " f"{var['name']}" ) # Now loop through every argument variable over the body variable to # check if the indices mismatch which would indicate an updated variable for argument in argument_dict: if argument in body_dict and int(body_dict[argument]) > int( argument_dict[argument] ): updated_list.append( f"@variable::{argument}::" f"{body_dict[argument]}" ) # If argument is an array type, get the current index and # update it. Then, append to the function's updated list elif argument in f_array_arg: updated_idx = state.last_definitions[argument] updated_list.append( f"@variable::{argument}::" f"{updated_idx}" ) return updated_list @staticmethod def _remove_output_variables(arguments_list, body): """ Remove output variables from the argument list of function definitions """ input_list = [] arg_map = {} for arg in arguments_list: arg_map[arg.split("::")[1]] = arg for obj in body: if obj["functions"]: for statement in obj["functions"]: for ip in statement["input"]: input_list.append(ip.split("::")[1]) if statement["function"]["type"] == "lambda": check = "output" elif statement["function"]["type"] == "container": check = "updated" else: assert False, "Unknown function type detected" for op in statement[check]: op = op.split("::")[1] if op not in input_list and op in arg_map: arguments_list.remove(arg_map[op]) def check_io_variables(self, variable_name): """ This function scans the variable and checks if it is an io variable. It returns the status of this check i.e. True or False. """ io_match = self.re_bypass_io.match(variable_name) return io_match @staticmethod def _get_call_inputs( call_function, function_input, container_argument, loop_condition_inputs, loop_condition_inputs_lambda, state, ): """ This function parses a call function (such as when reading an array) and loads all respective input variables from it. """ # First check if the call is from an array call. We only update the # lists if it is an array operation (such as samples.get_((x[0])) if ".get_" in call_function["function"]: array_name = call_function["function"].replace(".get_", "") array_index = state.last_definitions.get( array_name, state.last_definition_default ) function_input.append( f"@variable::" f"{array_name}::" f"{array_index}" ) container_argument.append(f"@variable::" f"{array_name}::-1") loop_condition_inputs.append(f"@variable::" f"{array_name}::-1") loop_condition_inputs_lambda.append(array_name) for inputs in call_function["inputs"]: if not isinstance(inputs, list): inputs = [inputs] for var in inputs: if "var" in var: function_input.append( f"@variable::" f"{var['var']['variable']}::" f"{var['var']['index']}" ) container_argument.append( f"@variable::{var['var']['variable']}::-1" ) loop_condition_inputs.append( f"@variable::" f"{var['var']['variable']}::-1" ) loop_condition_inputs_lambda.append( var["var"]["variable"] ) else: pass @staticmethod def _remove_duplicate_from_list(input_list): """ This helper function removes any duplicates from a list """ # return list(set(input_list)) return list(OrderedDict.fromkeys(input_list)) def get_variables(self, condition_sources, state): variable_list = list() for item in condition_sources: if isinstance(item, dict) and "var" in item: variable_list.append(item) elif isinstance(item, dict) and "list" in item: variable_list += self.get_variables(item["list"], state) elif isinstance(item, list): variable_list += self.get_variables(item, state) elif "call" in item: function_dict = item["call"] if function_dict["function"] == "abs": for x in function_dict["inputs"]: variable_list += self.get_variables(x, state) elif "__str__" in function_dict["function"]: var_name = function_dict["function"].split(".")[0] var_node = [ { "var": { "variable": var_name, "index": state.last_definitions.get( var_name, -1 ), } } ] variable_list += var_node elif "get_" in function_dict["function"]: var_name = function_dict["function"].split(".")[0] var_node = [ { "var": { "variable": var_name, "index": state.last_definitions.get( var_name, -1 ), } } ] variable_list += var_node for x in function_dict["inputs"]: variable_list += self.get_variables(x, state) # TODO: Will have to add other if cases for other string # types here # Remove any duplicate dictionaries from the list. This is done to # preserve ordering. # Reference: https://www.geeksforgeeks.org/ # python-removing-duplicate-dicts-in-list/ variable_list = [ i for n, i in enumerate(variable_list) if i not in variable_list[n + 1 :] ] return variable_list @staticmethod def _get_decision_inputs(if_body_outputs, updated_vars): """ This is a helper function that converts the updated dictionary of variables in the if-containers into a form that is easier to process for finding the decision tags """ decision_inputs = {} condition_var_regex = re.compile(r"COND_\d+_\d+") for var in updated_vars: if not condition_var_regex.match(var): decision_inputs[var] = [] for var in decision_inputs: condition_index_list = [] condition_index_map = {} for item, value in if_body_outputs.items(): if var in value: condition_index_map[item] = int(value[var]) if item: condition_index_list.append( int(item.rsplit("_", 1)[1]) ) else: condition_index_list.append(-1) decision_inputs[var].append(condition_index_map) decision_inputs[var].append(condition_index_list) return decision_inputs def _generate_decision_lambda( self, decision_versions: list, condition_var: str, max_conditions: int, var: str, argument_map: dict, ): """ This helper function generates the lambda function code for decision statements of if clauses. """ code = "" (cond_tuples, var_indices) = decision_versions if not self.use_numpy: if cond_tuples[0][0] is None: cond_var = argument_map[f"{condition_var}_0_0"] if_var = argument_map[f"{var}_0"] else_var = argument_map[f"{var}_xx"] return f"{if_var} if not {cond_var} else {else_var}" for cond_data in cond_tuples: (cond_name, var_idx) = cond_data var_arg = argument_map[f"{var}_{var_idx}"] if cond_name is None: code += f"{var_arg}" return code cond_arg = argument_map[f"{cond_name}_0"] code += f"{var_arg} if {cond_arg} else " if f"{var}_xx" in argument_map: else_var_name = argument_map[f"{var}_xx"] else: else_var_name = "None" code += f"{else_var_name}" return code else: # Use a where statement if this conditional is a simple if ... else if len(cond_tuples) == 2 and cond_tuples[-1][0] is None: cond_name = cond_tuples[0][0] cond_arg = argument_map[f"{cond_name}_0"] var_if = argument_map[f"{var}_{cond_tuples[0][1]}"] var_else = argument_map[f"{var}_{cond_tuples[-1][1]}"] return f"np.where({cond_arg},{var_if},{var_else})" if cond_tuples[0][0] is None: cond_var = argument_map[f"{condition_var}_0_0"] if_var = argument_map[f"{var}_0"] else_var = argument_map[f"{var}_xx"] return f"np.where(~({cond_var}),{if_var},{else_var})" (cond_names, var_indices) = map(list, zip(*cond_tuples)) cond_list = ",".join( [argument_map[f"{cond_var}_0"] for cond_var in cond_names] ) var_list = ",".join( [argument_map[f"{var}_{v}"] for v in var_indices] ) if f"{var}_xx" in argument_map: var_else = argument_map[f"{var}_xx"] else: var_else = "0" return f"np.select([{cond_list}],[{var_list}],default={var_else})" def _generate_argument_map(self, inputs): """ This function generates a different mapping of the arguments to the lambda function for decision statements. For every variable, the indexing starts from 0 and increases accordingly in the inputs list """ cond_count = 0 var_count = 0 arg_map = {} for ip in inputs: (var, _) = ip.split("_", 1) if var == "COND": arg_map[ip] = f"{var}_{cond_count}" cond_count += 1 else: arg_map[ip] = f"{var}_{var_count}" var_count += 1 return arg_map @staticmethod def _merge_container_body(container_body, container_decisions): """ This function merges the container body of if containers so that every condition and assignment statement is inside a single list. This list is then suffixed with the decisions statements """ final_body = [] for item in container_body: if item["condition"]: final_body += item["condition"] final_body += item["statements"] final_body += container_decisions return final_body @staticmethod def _fix_input_index(statement_list): """ For every statement list of a condition in `if-containers`, all inputs should start from -1 and increase accordingly. This function does the work of checking if such changes need to be for every statement list """ output_list = [] for stmt in statement_list: input_list = stmt["input"] for index in range(len(input_list)): var_parts = input_list[index].split("::") if ( var_parts[1] not in output_list and int(var_parts[-1]) != -1 ): var_parts[-1] = "-1" input_list[index] = "::".join(var_parts) output_list += [x.split("::")[1] for x in stmt["output"]] def get_path(file_name: str, instance: str): """ This function returns the path of a file starting from the root of the delphi repository. The returned path varies depending on whether it is for a namespace or a source variable, which is denoted by the `instance` argument variable. It is important to note that the path refers to that of the original system being analyzed i.e. the Fortran code and not the intermediate Python file which is used to generate the AST. """ if instance == "source": source_match = re.match(r"[./]*(.*)", file_name) assert source_match, ( f"Original Fortran source file for {file_name} " f"not found." ) return source_match.group(1) elif instance == "namespace": source_match = re.match(r"[./]*(.*)\.", file_name) assert source_match, f"Namespace path for {file_name} not found." return source_match.group(1).split("/") else: assert False, f"Error when trying to get the path of file {file_name}." def dump_ast( node, annotate_fields=True, include_attributes=False, indent=" " ): """ Return a formatted dump of the tree in *node*. This is mainly useful for debugging purposes. The returned string will show the names and the values for fields. This makes the code impossible to evaluate, so if evaluation is wanted *annotate_fields* must be set to False. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, *include_attributes* can be set to True. """ def _format(ast_node, level=0): if isinstance(ast_node, ast.AST): fields = [ (a, _format(b, level)) for a, b in ast.iter_fields(ast_node) ] if include_attributes and ast_node._attributes: fields.extend( [ (a, _format(getattr(ast_node, a), level)) for a in ast_node._attributes ] ) return "".join( [ ast_node.__class__.__name__, "(", ", ".join( ("%s=%s" % field for field in fields) if annotate_fields else (b for a, b in fields) ), ")", ] ) elif isinstance(ast_node, list): lines = ["["] lines.extend( ( indent * (level + 2) + _format(x, level + 2) + "," for x in ast_node ) ) if len(lines) > 1: lines.append(indent * (level + 1) + "]") else: lines[-1] += "]" return "\n".join(lines) return repr(ast_node) if not isinstance(node, ast.AST): raise TypeError("expected AST, got %r" % node.__class__.__name__) return _format(node) def process_comments(source_comment_dict, generator_object): """ This function replaces the keys in the source comments that are function names in the source files into their container id name. """ grfn_argument_map = generator_object.function_argument_map for key in source_comment_dict: if key in grfn_argument_map: source_comment_dict[ grfn_argument_map[key]["name"] ] = source_comment_dict.pop(key) return source_comment_dict # noinspection PyDefaultArgument def create_grfn_dict( lambda_file: str, python_source_string: str, file_name: str, mode_mapper_dict: list, original_file: str, mod_log_file_path: str, comments: dict, module_file_exist=False, module_import_paths={}, ) -> Dict: """ Create a Python dict representing the GrFN, with additional metadata for JSON output. """ generator = GrFNGenerator() generator.original_python_src = python_source_string asts = [ast.parse(python_source_string)] # print(dump_ast(asts[-1])) lambda_string_list = [ "from numbers import Real\n", "from random import random\n", "import numpy as np\n", "from automates.program_analysis.for2py.strings import *\n", "from automates.program_analysis.for2py import intrinsics\n", "from automates.program_analysis.for2py.arrays import *\n", "from dataclasses import dataclass\n", "import automates.program_analysis.for2py.math_ext as math\n\n", ] state = GrFNState(lambda_string_list) generator.mode_mapper = mode_mapper_dict[0] # Populate list of modules that the program imports for mod in generator.mode_mapper["modules"]: if mod != "main": generator.module_names.append(mod) generator.fortran_file = original_file generator.comments = comments # Currently, we are specifying the module file with # a prefix "m_", this may be changed in the future. # If it requires a change, simply modify this below prefix. module_file_prefix = "m_" with open(mod_log_file_path) as json_f: module_logs = json.load(json_f) # Load module summary on memory for later use generator.module_summary = module_logs["mod_info"] try: filename_regex = re.compile(r"(?P<path>.*/)(?P<filename>.*).py") file_match = re.match(filename_regex, file_name) assert file_match, f"Can't match filename to any format: {file_name}" path = file_match.group("path") filename = file_match.group("filename") # Since we do not have separate variable pickle file # for m_*.py, we need to use the original program pickle # file that module resides. module_name = None if module_file_exist: module_file_path = file_name # Ignoring the module file prefix module_name = filename[len(module_file_prefix) :] org_file = get_original_file_name(original_file) file_name = path + org_file else: file_name = path + filename with open(f"{file_name}_variable_map.pkl", "rb") as f: variable_map = pickle.load(f) generator.variable_map = variable_map except IOError: raise For2PyError(f"Unable to read file {file_name}.") # Extract variables with type that are declared in module generator.module_variable_types = mode_mapper_dict[0]["symbol_types"] # Extract functions (and subroutines) declared in module for module in mode_mapper_dict[0]["subprograms"]: for subp in mode_mapper_dict[0]["subprograms"][module]: generator.module_subprograms.append(subp) if module in module_logs["mod_info"]: module_logs["mod_info"][module]["symbol_types"][subp] = "func" for module in mode_mapper_dict[0]["imports"]: for subm in mode_mapper_dict[0]["imports"][module]: import_module_name = list(subm.keys())[0] import_function_list = subm[import_module_name] if ( not import_function_list and import_module_name in module_logs["mod_info"] ): symbols = module_logs["mod_info"][import_module_name][ "symbol_types" ] for key, value in symbols.items(): if value == "func": generator.module_subprograms.append(key) generator.module_subprograms.extend(import_function_list) # Generate GrFN with an AST generated from Python IR. grfn = generator.gen_grfn(asts, state, "")[0] if len(generator.mode_mapper["use_mapping"]) > 0: for user, module in generator.mode_mapper["use_mapping"].items(): if (user in generator.module_names) or ( module_name and module_name == user ): module_paths = [] for import_mods in module: for mod_name, target in import_mods.items(): module_path = ( path + module_file_prefix + mod_name + "_AIR.json" ) module_paths.append(module_path) module_import_paths[user] = module_paths # If the GrFN has a `start` node, it will refer to the name of the # PROGRAM module which will be the entry point of the GrFN. if grfn.get("start"): grfn["start"] = [grfn["start"][0]] elif generator.function_definitions: # TODO: The `grfn_spec` mentions this to be null (None) but it looks # like `networks.py` requires a certain function. Finalize after # `networks.py` is completed. # grfn["start"] = None grfn["start"] = [generator.function_definitions[-1]] else: grfn["start"] = None # Add the placeholder to enter the grounding and link hypothesis information grfn["grounding"] = [] # TODO Add a placeholder for `types`. This will have to be populated when # user defined types start appearing. grfn["types"] = generator.derived_types_grfn # Get the file path of the original Fortran code being analyzed source_file = get_path(original_file, "source") # TODO Hack: Currently only the file name is being displayed as the # source in order to match the handwritten SIR model GrFN JSON. Since # the directory of the `SIR-Gillespie-SD_inline.f` file is the root, # it works for this case but will need to be generalized for other cases. file_path_list = source_file.split("/") grfn["source"] = [file_path_list[-1]] # Get the source comments from the original Fortran source file. source_file_comments = get_comments(original_file) comment_dict = process_comments(dict(source_file_comments), generator) source_comments = comment_dict grfn["source_comments"] = source_comments # dateCreated stores the date and time on which the lambda and GrFN files # were created. It is stored in the YYYMMDD format grfn["date_created"] = f"{datetime.utcnow().isoformat('T')}Z" # If some fields are not present, add an empty one if not grfn.get("containers"): grfn["containers"] = [] if not grfn.get("variables"): grfn["variables"] = [] # with open(lambda_file, "w") as lambda_fh: # lambda_fh.write("".join(lambda_string_list)) with open(mod_log_file_path, "w+") as json_f: json_f.write(json.dumps(module_logs, indent=2)) del state return grfn def generate_ast(filename: str): """ This function generates the AST of a python file using Python's ast module. """ return ast.parse(tokenize.open(filename).read()) def get_asts_from_files(file_list: List[str], printast=False) -> List: """ This function returns the AST of each python file in the python_file_list. """ ast_list = [] for file in file_list: ast_list.append(generate_ast(file)) if printast: # If the printAst flag is set, print the AST to console print(dump_ast(ast_list[-1])) return ast_list def get_system_name(pyfile_list: List[str]): """ This function returns the name of the system under analysis. Generally, the system is the one which is not prefixed by `m_` (which represents modules). """ system_name = None path = None for file in pyfile_list: if not file.startswith("m_"): system_name_match = re.match(r".*/(.*)\.py", file) assert system_name_match, f"System name for file {file} not found." system_name = system_name_match.group(1) path_match = re.match(r"(.*)/.*", file) assert path_match, "Target path not found" path = path_match.group(1) if not (system_name or path): assert False, ( f"Error when trying to find the system name of the " f"analyzed program." ) return system_name, path def generate_system_def( python_list: List[str], module_grfn_list: List[str], import_grfn_paths: List[str], module_logs: Dict, original_file_path: str, ): """ This function generates the system definition for the system under analysis and writes this to the main system file. """ (system_name, path) = get_system_name(python_list) system_filepath = f"{path}/system.json" module_name_regex = re.compile( r"(?P<path>.*/)m_(" r"?P<module_name>.*)_AIR.json" ) grfn_components = [] for module_grfn in module_grfn_list: code_sources = [] module_match = re.match(module_name_regex, module_grfn) if module_match: module_name = module_match.group("module_name") if module_name in module_logs["mod_to_file"]: for path in module_logs["mod_to_file"][module_name]: code_sources.append(path) if not code_sources: code_sources.append(original_file_path) grfn_components.append( { "grfn_source": module_grfn, "code_source": code_sources, "imports": [], } ) for grfn in import_grfn_paths: for path in import_grfn_paths[grfn]: if ( path not in grfn_components[0]["imports"] and path != module_grfn ): grfn_components[0]["imports"].append(path) system_def = {"name": system_name, "components": grfn_components} if os.path.isfile(system_filepath): with open(system_filepath, "r") as f: systems_def = json.load(f) systems_def["systems"].append(system_def) else: systems_def = {"systems": [system_def]} return system_def def process_files( python_list: List[str], grfn_tail: str, lambda_tail: str, original_file_path: str, print_ast_flag=False, ): """ This function takes in the list of python files to convert into GrFN and generates each file's AST along with starting the GrFN generation process. """ module_file_exist = False module_mapper = {} grfn_filepath_list = [] ast_list = get_asts_from_files(python_list, print_ast_flag) # Regular expression to identify the path and name of all python files filename_regex = re.compile(r"(?P<path>.*/)(?P<filename>.*).py") # First, find the main python file in order to populate the module # mapper for item in python_list: file_match = re.match(filename_regex, item) assert file_match, "Invalid filename." path = file_match.group("path") filename = file_match.group("filename") # Ignore all Python files of modules created by `pyTranslate.py` # since these module files do not contain a corresponding XML file. if not filename.startswith("m_"): xml_file = f"{path}rectified_{filename}.xml" # Calling the `get_index` function in `mod_index_generator.py` to # map all variables and objects in the various files else: module_file_exist = True file_name = get_original_file_name(original_file_path) xml_file = f"{path}rectified_{file_name}.xml" # Calling the `get_index` function in `mod_index_generator.py` to # map all variables and objects in the various files module_mapper = get_index(xml_file) module_import_paths = {} for index, ast_string in enumerate(ast_list): lambda_file = python_list[index][:-3] + "_" + lambda_tail grfn_file = python_list[index][:-3] + "_" + grfn_tail grfn_dict = create_grfn_dict( lambda_file, [ast_string], python_list[index], module_mapper, original_file_path, module_file_exist, module_import_paths, ) if module_file_exist: main_python_file = path + file_name + ".py" python_list[index] = main_python_file grfn_filepath_list.append(grfn_file) # Write each GrFN JSON into a file with open(grfn_file, "w") as file_handle: file_handle.write(json.dumps(grfn_dict, sort_keys=True, indent=2)) def get_original_file_name(original_file_path): original_file = original_file_path.split("/") return original_file[-1].split(".")[0] if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "-f", "--files", nargs="+", required=True, help="A list of python files to generate a PGM for", ) parser.add_argument( "-p", "--grfn_suffix", nargs=1, required=True, help="Filename for the output PGM", ) parser.add_argument( "-l", "--lambda_suffix", nargs=1, required=True, help="Filename for output lambda functions", ) parser.add_argument( "-o", "--out", nargs=1, required=True, help="Text file containing the list of output python files being " "generated", ) parser.add_argument( "-a", "--print_ast", action="store_true", required=False, help="Print ASTs", ) parser.add_argument( "-g", "--original_file", nargs=1, required=True, help="Filename of the original Fortran file", ) arguments = parser.parse_args(sys.argv[1:]) # Read the outputFile which contains the name of all the python files # generated by `pyTranslate.py`. Multiple files occur in the case of # modules since each module is written out into a separate python file. with open(arguments.out[0], "r") as f: python_files = f.read() # The Python file names are space separated. Append each one to a list. python_file_list = python_files.rstrip().split(" ") grfn_suffix = arguments.grfn_suffix[0] lambda_suffix = arguments.lambda_suffix[0] fortran_file = arguments.original_file[0] print_ast = arguments.print_ast process_files( python_file_list, grfn_suffix, lambda_suffix, fortran_file, print_ast )
#!/usr/bin/env python from pathlib import Path from datetime import datetime from typing import Dict, Any, Sequence, Optional from typing.io import TextIO import xarray import numpy as np import logging from .io import opener, rinexinfo from .common import rinex_string_to_float # STARTCOL2 = 3 # column where numerical data starts for RINEX 2 Nl = {'G': 7, 'R': 3, 'E': 7} # number of additional SV lines def rinexnav2(fn: Path, tlim: Sequence[datetime] = None) -> xarray.Dataset: """ Reads RINEX 2.x NAV files Michael Hirsch, Ph.D. SciVision, Inc. http://gage14.upc.es/gLAB/HTML/GPS_Navigation_Rinex_v2.11.html ftp://igs.org/pub/data/format/rinex211.txt """ fn = Path(fn).expanduser() Lf = 19 # string length per field svs = [] times = [] raws = [] with opener(fn) as f: header = navheader2(f) if header['filetype'] == 'N': svtype = 'G' fields = ['SVclockBias', 'SVclockDrift', 'SVclockDriftRate', 'IODE', 'Crs', 'DeltaN', 'M0', 'Cuc', 'Eccentricity', 'Cus', 'sqrtA', 'Toe', 'Cic', 'Omega0', 'Cis', 'Io', 'Crc', 'omega', 'OmegaDot', 'IDOT', 'CodesL2', 'GPSWeek', 'L2Pflag', 'SVacc', 'health', 'TGD', 'IODC', 'TransTime', 'FitIntvl'] elif header['filetype'] == 'G': svtype = 'R' # GLONASS fields = ['SVclockBias', 'SVrelFreqBias', 'MessageFrameTime', 'X', 'dX', 'dX2', 'health', 'Y', 'dY', 'dY2', 'FreqNum', 'Z', 'dZ', 'dZ2', 'AgeOpInfo'] elif header['filetype'] == 'E': svtype = 'E' # Galileo fields = ['SVclockBias', 'SVclockDrift', 'SVclockDriftRate', 'IODnav', 'Crs', 'DeltaN', 'M0', 'Cuc', 'Eccentricity', 'Cus', 'sqrtA', 'Toe', 'Cic', 'Omega0', 'Cis', 'Io', 'Crc', 'omega', 'OmegaDot', 'IDOT', 'DataSrc', 'GALWeek', 'SISA', 'health', 'BGDe5a', 'BGDe5b', 'TransTime'] else: raise NotImplementedError(f'I do not yet handle Rinex 2 NAV {header['sys']} {fn}') # %% read data for ln in f: time = _timenav(ln) if time is None: # blank or garbage line continue if tlim is not None: if time < tlim[0]: _skip(f, Nl[header['systems']]) continue elif time > tlim[1]: break # %% format I2 http://gage.upc.edu/sites/default/files/gLAB/HTML/GPS_Navigation_Rinex_v2.11.html svs.append(f'{svtype}{ln[:2]}') times.append(time) """ now get the data as one big long string per SV """ raw = ln[22:79] # NOTE: MUST be 79, not 80 due to some files that put \n a character early! for i, ln in zip(range(Nl[header['systems']]), f): raw += ln[STARTCOL2:79] # one line per SV raws.append(raw.replace('D', 'E').replace('\n', '')) if not raws: return None # %% parse svs = [s.replace(' ', '0') for s in svs] svu = sorted(set(svs)) atimes = np.asarray(times) timesu = np.unique(atimes) data = np.empty((len(fields), timesu.size, len(svu))) data.fill(np.nan) for j, sv in enumerate(svu): # for each SV, across all values and times... svi = [i for i, s in enumerate(svs) if s == sv] # these rows are for this SV tu = np.unique(atimes[svi]) # this SV was seen at these times if tu.size != atimes[svi].size: logging.warning(f'duplicate times detected, skipping SV {sv}') continue for i in svi: it = np.nonzero(timesu == times[i])[0][0] # int by defn """ some files sometimes drop the last measurement, this fixes that. It assumes the blank is always in the last measurement for now. """ dvec = [float(raws[i][k*Lf:(k+1)*Lf]) for k in range(min(len(fields), len(raws[i])//Lf))] data[:len(dvec), it, j] = dvec # %% assemble output # NOTE: time must be datetime64[ns] or .to_netcdf will fail nav = xarray.Dataset(coords={'time': timesu.astype('datetime64[ns]'), 'sv': svu}) for i, k in enumerate(fields): if k is None: continue nav[k] = (('time', 'sv'), data[i, :, :]) # GLONASS uses kilometers to report its ephemeris. # Convert to meters here to be consistent with NAV3 implementation. if svtype == 'R': for name in ['X', 'Y', 'Z', 'dX', 'dY', 'dZ', 'dX2', 'dY2', 'dZ2']: nav[name] *= 1e3 # %% other attributes nav.attrs['version'] = header['version'] nav.attrs['filename'] = fn.name nav.attrs['svtype'] = [svtype] # Use list for consistency with NAV3. nav.attrs['rinextype'] = 'nav' if 'ION ALPHA' in header and 'ION BETA' in header: alpha = header['ION ALPHA'] alpha = [rinex_string_to_float(alpha[2 + i*12:2 + (i+1)*12]) for i in range(4)] beta = header['ION BETA'] beta = [rinex_string_to_float(beta[2 + i*12:2 + (i+1)*12]) for i in range(4)] nav.attrs['ionospheric_corr_GPS'] = np.hstack((alpha, beta)) return nav def navheader2(f: TextIO) -> Dict[str, Any]: if isinstance(f, Path): fn = f with fn.open('r') as f: return navheader2(f) # %%verify RINEX version, and that it's NAV hdr = rinexinfo(f) if int(hdr['version']) != 2: raise ValueError('see rinexnav3() for RINEX 3.0 files') for ln in f: if 'END OF HEADER' in ln: break kind, content = ln[60:].strip(), ln[:60] hdr[kind] = content return hdr def _timenav(ln: str) -> Optional[datetime]: """ Python >= 3.7 supports nanoseconds. https://www.python.org/dev/peps/pep-0564/ Python < 3.7 supports microseconds. """ try: year = int(ln[3:5]) if 80 <= year <= 99: year += 1900 elif year < 80: # because we might pass in four-digit year year += 2000 else: raise ValueError(f'unknown year format {year}') return datetime(year=year, month=int(ln[6:8]), day=int(ln[9:11]), hour=int(ln[12:14]), minute=int(ln[15:17]), second=int(float(ln[17:20])), microsecond=int(float(ln[17:22]) % 1 * 1000000) ) except ValueError: return None def _skip(f: TextIO, Nl: int): for _, _ in zip(range(Nl), f): pass def navtime2(fn: Path) -> xarray.DataArray: """ read all times in RINEX 2 NAV file """ times = [] with opener(fn) as f: hdr = navheader2(f) while True: ln = f.readline() if not ln: break time = _timenav(ln) if time is None: continue times.append(time) _skip(f, Nl[hdr['systems']]) if not times: return None times = np.unique(times) timedat = xarray.DataArray(times, dims=['time'], attrs={'filename': fn}) return timedat
#!/usr/bin/env python from pathlib import Path from datetime import datetime from typing import Dict, Any, Sequence, Optional from typing.io import TextIO import xarray import numpy as np import logging from .io import opener, rinexinfo from .common import rinex_string_to_float # STARTCOL2 = 3 # column where numerical data starts for RINEX 2 Nl = {'G': 7, 'R': 3, 'E': 7} # number of additional SV lines def rinexnav2(fn: Path, tlim: Sequence[datetime] = None) -> xarray.Dataset: """ Reads RINEX 2.x NAV files Michael Hirsch, Ph.D. SciVision, Inc. http://gage14.upc.es/gLAB/HTML/GPS_Navigation_Rinex_v2.11.html ftp://igs.org/pub/data/format/rinex211.txt """ fn = Path(fn).expanduser() Lf = 19 # string length per field svs = [] times = [] raws = [] with opener(fn) as f: header = navheader2(f) if header['filetype'] == 'N': svtype = 'G' fields = ['SVclockBias', 'SVclockDrift', 'SVclockDriftRate', 'IODE', 'Crs', 'DeltaN', 'M0', 'Cuc', 'Eccentricity', 'Cus', 'sqrtA', 'Toe', 'Cic', 'Omega0', 'Cis', 'Io', 'Crc', 'omega', 'OmegaDot', 'IDOT', 'CodesL2', 'GPSWeek', 'L2Pflag', 'SVacc', 'health', 'TGD', 'IODC', 'TransTime', 'FitIntvl'] elif header['filetype'] == 'G': svtype = 'R' # GLONASS fields = ['SVclockBias', 'SVrelFreqBias', 'MessageFrameTime', 'X', 'dX', 'dX2', 'health', 'Y', 'dY', 'dY2', 'FreqNum', 'Z', 'dZ', 'dZ2', 'AgeOpInfo'] elif header['filetype'] == 'E': svtype = 'E' # Galileo fields = ['SVclockBias', 'SVclockDrift', 'SVclockDriftRate', 'IODnav', 'Crs', 'DeltaN', 'M0', 'Cuc', 'Eccentricity', 'Cus', 'sqrtA', 'Toe', 'Cic', 'Omega0', 'Cis', 'Io', 'Crc', 'omega', 'OmegaDot', 'IDOT', 'DataSrc', 'GALWeek', 'SISA', 'health', 'BGDe5a', 'BGDe5b', 'TransTime'] else: raise NotImplementedError(f'I do not yet handle Rinex 2 NAV {header["sys"]} {fn}') # %% read data for ln in f: time = _timenav(ln) if time is None: # blank or garbage line continue if tlim is not None: if time < tlim[0]: _skip(f, Nl[header['systems']]) continue elif time > tlim[1]: break # %% format I2 http://gage.upc.edu/sites/default/files/gLAB/HTML/GPS_Navigation_Rinex_v2.11.html svs.append(f'{svtype}{ln[:2]}') times.append(time) """ now get the data as one big long string per SV """ raw = ln[22:79] # NOTE: MUST be 79, not 80 due to some files that put \n a character early! for i, ln in zip(range(Nl[header['systems']]), f): raw += ln[STARTCOL2:79] # one line per SV raws.append(raw.replace('D', 'E').replace('\n', '')) if not raws: return None # %% parse svs = [s.replace(' ', '0') for s in svs] svu = sorted(set(svs)) atimes = np.asarray(times) timesu = np.unique(atimes) data = np.empty((len(fields), timesu.size, len(svu))) data.fill(np.nan) for j, sv in enumerate(svu): # for each SV, across all values and times... svi = [i for i, s in enumerate(svs) if s == sv] # these rows are for this SV tu = np.unique(atimes[svi]) # this SV was seen at these times if tu.size != atimes[svi].size: logging.warning(f'duplicate times detected, skipping SV {sv}') continue for i in svi: it = np.nonzero(timesu == times[i])[0][0] # int by defn """ some files sometimes drop the last measurement, this fixes that. It assumes the blank is always in the last measurement for now. """ dvec = [float(raws[i][k*Lf:(k+1)*Lf]) for k in range(min(len(fields), len(raws[i])//Lf))] data[:len(dvec), it, j] = dvec # %% assemble output # NOTE: time must be datetime64[ns] or .to_netcdf will fail nav = xarray.Dataset(coords={'time': timesu.astype('datetime64[ns]'), 'sv': svu}) for i, k in enumerate(fields): if k is None: continue nav[k] = (('time', 'sv'), data[i, :, :]) # GLONASS uses kilometers to report its ephemeris. # Convert to meters here to be consistent with NAV3 implementation. if svtype == 'R': for name in ['X', 'Y', 'Z', 'dX', 'dY', 'dZ', 'dX2', 'dY2', 'dZ2']: nav[name] *= 1e3 # %% other attributes nav.attrs['version'] = header['version'] nav.attrs['filename'] = fn.name nav.attrs['svtype'] = [svtype] # Use list for consistency with NAV3. nav.attrs['rinextype'] = 'nav' if 'ION ALPHA' in header and 'ION BETA' in header: alpha = header['ION ALPHA'] alpha = [rinex_string_to_float(alpha[2 + i*12:2 + (i+1)*12]) for i in range(4)] beta = header['ION BETA'] beta = [rinex_string_to_float(beta[2 + i*12:2 + (i+1)*12]) for i in range(4)] nav.attrs['ionospheric_corr_GPS'] = np.hstack((alpha, beta)) return nav def navheader2(f: TextIO) -> Dict[str, Any]: if isinstance(f, Path): fn = f with fn.open('r') as f: return navheader2(f) # %%verify RINEX version, and that it's NAV hdr = rinexinfo(f) if int(hdr['version']) != 2: raise ValueError('see rinexnav3() for RINEX 3.0 files') for ln in f: if 'END OF HEADER' in ln: break kind, content = ln[60:].strip(), ln[:60] hdr[kind] = content return hdr def _timenav(ln: str) -> Optional[datetime]: """ Python >= 3.7 supports nanoseconds. https://www.python.org/dev/peps/pep-0564/ Python < 3.7 supports microseconds. """ try: year = int(ln[3:5]) if 80 <= year <= 99: year += 1900 elif year < 80: # because we might pass in four-digit year year += 2000 else: raise ValueError(f'unknown year format {year}') return datetime(year=year, month=int(ln[6:8]), day=int(ln[9:11]), hour=int(ln[12:14]), minute=int(ln[15:17]), second=int(float(ln[17:20])), microsecond=int(float(ln[17:22]) % 1 * 1000000) ) except ValueError: return None def _skip(f: TextIO, Nl: int): for _, _ in zip(range(Nl), f): pass def navtime2(fn: Path) -> xarray.DataArray: """ read all times in RINEX 2 NAV file """ times = [] with opener(fn) as f: hdr = navheader2(f) while True: ln = f.readline() if not ln: break time = _timenav(ln) if time is None: continue times.append(time) _skip(f, Nl[hdr['systems']]) if not times: return None times = np.unique(times) timedat = xarray.DataArray(times, dims=['time'], attrs={'filename': fn}) return timedat
import typing import ast _HANDLE = { } def handle(expr): return _HANDLE[ type(expr) ] (expr) def _strip(s): while ' ' in s: s = s.replace(' ', ' ') return s.strip() def _transformer(expr): args = ', '.join( [ handle(arg) for arg in expr.args ] ) return _strip(f'<{args}>') def _include(expr): args = ', '.join( [ handle(arg) for arg in expr.args ] ) if args.startswith('"<'): args = args[1:-1] return _strip(f'#include {args}') return _strip(f'#include {args}') def ast_num(expr): return f'{expr.n}' def ast_str(expr): return f'"{expr.s}"' def ast_constant(expr): # new in Python 3.6 return f'{expr.n}' def ast_index(expr): return expr.value.id def ast_name(expr): return f'{expr.id}' def ast_call(expr): func = handle(expr.func) if func == '_': # this is the <transformer> syntax return _transformer(expr) if func == '__include__': return _include(expr) if func == 'print': func = 'printf' # close enough args = ', '.join( [ handle(arg) for arg in expr.args ] ) return _strip(f'{func}({args})') def ast_subscript(expr): slic = handle(expr.slice) val = handle(expr.value) return _strip(f'{val} {slic}') def ast_return(expr): return f'return {handle(expr.value)};' def ast_annassign(expr): target = handle(expr.target) ann = handle(expr.annotation) value = handle(expr.value) if expr.value is not None else '' try: slice_ = expr.annotation.slice.value.id except: slice_ = '' if value: return _strip('{} {} = {};'.format(ann, target, value)) return _strip('{} {};'.format(ann, target)) def ast_compare(expr): left = handle(expr.left) comps = [handle(comp) for comp in expr.comparators] ops = [handle(op) for op in expr.ops] return f'{left} {ops[0]} {comps[0]}' def ast_if(expr): test = handle(expr.test) body = [handle(line) for line in expr.body] orelse = expr.orelse return f'if ({test}) ' + '{\n' + '\n'.join(body) + '\n}' def ast_unaryop(expr): operand = handle(expr.operand) op = handle(expr.op) return f'{op} {operand}' def ast_binop(expr): left = handle(expr.left) right = handle(expr.right) op = handle(expr.op) return f'{left} {op} {right}' def ast_matmult(expr): return '@' def ast_attribute(expr): val = handle(expr.value) attr = expr.attr # str return f'{val}.{attr}' def ast_expr(expr): val = handle(expr.value) if val.startswith("#include"): return f'{val}' return f'{val};' def ast_assign(expr): t0 = handle(expr.targets[0]) val = handle(expr.value) return f'{t0} = {val};' def ast_augassign(expr): target = handle(expr.target) op = handle(expr.op) val = handle(expr.value) return f'{target} {op} {val};' def ast_arg(expr): arg = handle(expr.arg) if expr.annotation: ann = handle(expr.annotation) return f'{ann} {arg}' # the space is annoying return f'{arg}' def ast_arguments(expr): return ','.join( [handle(arg) for arg in expr.args] ) def ast_functiondef(expr): returns = handle(expr.returns) if expr.returns else 'void' fname = expr.name if type(expr.name) == str else handle(expr.name) args = handle(expr.args) ass_ = [] for x in expr.body: ass_.append(handle(x)) body = '\n '.join(ass_) return f'{returns} {fname}({args}) ' + '{\n' + body + '\n}' def constant(elt): return lambda _ : elt def identity(elt): return elt _HANDLE[ast.AnnAssign] = ast_annassign _HANDLE[ast.Assign] = ast_assign _HANDLE[ast.AugAssign] = ast_augassign _HANDLE[ast.FunctionDef] = ast_functiondef _HANDLE[ast.Return] = ast_return _HANDLE[ast.Call] = ast_call _HANDLE[ast.Compare] = ast_compare _HANDLE[ast.Subscript] = ast_subscript _HANDLE[ast.Name] = ast_name _HANDLE[ast.Num] = ast_num _HANDLE[ast.Str] = ast_str _HANDLE[str] = identity _HANDLE[ast.Constant] = ast_constant _HANDLE[ast.Index] = ast_index _HANDLE[ast.arguments] = ast_arguments _HANDLE[ast.arg] = ast_arg _HANDLE[ast.If] = ast_if _HANDLE[ast.UnaryOp] = ast_unaryop _HANDLE[ast.BinOp] = ast_binop _HANDLE[ast.Attribute] = ast_attribute _HANDLE[ast.Expr] = ast_expr _HANDLE[ast.Lt] = constant('<') _HANDLE[ast.LtE] = constant('<=') _HANDLE[ast.Gt] = constant('>') _HANDLE[ast.Mult] = constant('*') _HANDLE[ast.Div] = constant('/') _HANDLE[ast.Add] = constant('+') _HANDLE[ast.Sub] = constant('-') _HANDLE[ast.USub] = constant('-') _HANDLE[ast.MatMult] = ast_matmult
import typing import ast _HANDLE = { } def handle(expr): return _HANDLE[ type(expr) ] (expr) def _strip(s): while ' ' in s: s = s.replace(' ', ' ') return s.strip() def _transformer(expr): args = ', '.join( [ handle(arg) for arg in expr.args ] ) return _strip(f'<{args}>') def _include(expr): args = ', '.join( [ handle(arg) for arg in expr.args ] ) if args.startswith('"<'): args = args[1:-1] return _strip(f'#include {args}') return _strip(f'#include {args}') def ast_num(expr): return f'{expr.n}' def ast_str(expr): return f'"{expr.s}"' def ast_constant(expr): # new in Python 3.6 return f'{expr.n}' def ast_index(expr): return expr.value.id def ast_name(expr): return f'{expr.id}' def ast_call(expr): func = handle(expr.func) if func == '_': # this is the <transformer> syntax return _transformer(expr) if func == '__include__': return _include(expr) if func == 'print': func = 'printf' # close enough args = ', '.join( [ handle(arg) for arg in expr.args ] ) return _strip(f'{func}({args})') def ast_subscript(expr): slic = handle(expr.slice) val = handle(expr.value) return _strip(f'{val} {slic}') def ast_return(expr): return f'return {handle(expr.value)};' def ast_annassign(expr): target = handle(expr.target) ann = handle(expr.annotation) value = handle(expr.value) if expr.value is not None else '' try: slice_ = expr.annotation.slice.value.id except: slice_ = '' if value: return _strip('{} {} = {};'.format(ann, target, value)) return _strip('{} {};'.format(ann, target)) def ast_compare(expr): left = handle(expr.left) comps = [handle(comp) for comp in expr.comparators] ops = [handle(op) for op in expr.ops] return f'{left} {ops[0]} {comps[0]}' def ast_if(expr): test = handle(expr.test) body = [handle(line) for line in expr.body] orelse = expr.orelse return f'if ({test}) ' + '{\n' + '\n'.join(body) + '\n}' def ast_unaryop(expr): operand = handle(expr.operand) op = handle(expr.op) return f'{op} {operand}' def ast_binop(expr): left = handle(expr.left) right = handle(expr.right) op = handle(expr.op) return f'{left} {op} {right}' def ast_matmult(expr): return '@' def ast_attribute(expr): val = handle(expr.value) attr = expr.attr # str return f'{val}.{attr}' def ast_expr(expr): val = handle(expr.value) if val.startswith("#include"): return f'{val}' return f'{val};' def ast_assign(expr): t0 = handle(expr.targets[0]) val = handle(expr.value) return f'{t0} = {val};' def ast_augassign(expr): target = handle(expr.target) op = handle(expr.op) val = handle(expr.value) return f'{target} {op} {val};' def ast_arg(expr): arg = handle(expr.arg) if expr.annotation: ann = handle(expr.annotation) return f'{ann} {arg}' # the space is annoying return f'{arg}' def ast_arguments(expr): return ','.join( [handle(arg) for arg in expr.args] ) def ast_functiondef(expr): returns = handle(expr.returns) if expr.returns else 'void' fname = expr.name if type(expr.name) == str else handle(expr.name) args = handle(expr.args) ass_ = [] for x in expr.body: ass_.append(handle(x)) body = '\n '.join(ass_) return f'{returns} {fname}({args}) ' + '{\n' + body + '\n}' def constant(elt): return lambda _ : elt def identity(elt): return elt _HANDLE[ast.AnnAssign] = ast_annassign _HANDLE[ast.Assign] = ast_assign _HANDLE[ast.AugAssign] = ast_augassign _HANDLE[ast.FunctionDef] = ast_functiondef _HANDLE[ast.Return] = ast_return _HANDLE[ast.Call] = ast_call _HANDLE[ast.Compare] = ast_compare _HANDLE[ast.Subscript] = ast_subscript _HANDLE[ast.Name] = ast_name _HANDLE[ast.Num] = ast_num _HANDLE[ast.Str] = ast_str _HANDLE[str] = identity _HANDLE[ast.Constant] = ast_constant _HANDLE[ast.Index] = ast_index _HANDLE[ast.arguments] = ast_arguments _HANDLE[ast.arg] = ast_arg _HANDLE[ast.If] = ast_if _HANDLE[ast.UnaryOp] = ast_unaryop _HANDLE[ast.BinOp] = ast_binop _HANDLE[ast.Attribute] = ast_attribute _HANDLE[ast.Expr] = ast_expr _HANDLE[ast.Lt] = constant('<') _HANDLE[ast.LtE] = constant('<=') _HANDLE[ast.Gt] = constant('>') _HANDLE[ast.Mult] = constant('*') _HANDLE[ast.Div] = constant('/') _HANDLE[ast.Add] = constant('+') _HANDLE[ast.Sub] = constant('-') _HANDLE[ast.USub] = constant('-') _HANDLE[ast.MatMult] = ast_matmult
# # 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 logging import os import yaml # { path -> { name -> config_file } } cached_files = dict() cached_source_files = dict() def resolve_pipeline_source_file(config_name): """ Return the source (file) path of the given config name """ return cached_source_files[config_name] def load(path): """ :param path: config path :returns dict of {name -> loaded config file} from all liminal.y[a]ml files under given path """ if cached_files.get(path): return cached_files[path] config_entities = {} for file_data in find_config_files(path): with open(file_data, 'r') as data: config_file = yaml.safe_load(data) config_entities[config_file['name']] = config_file cached_source_files[config_file['name']] = file_data cached_files[path] = config_entities return config_entities def find_config_files(path): """ :param path: config path :returns list of all liminal.y[a]ml files under config path """ files = [] logging.info(path) for r, d, f in os.walk(path): for file in f: if os.path.basename(file) in ['liminal.yml', 'liminal.yaml']: logging.info(os.path.join(r, file)) files.append(os.path.join(r, file)) return files def dump_liminal_configs(liminal_configs, path): if not (os.path.exists(path)): os.mkdir(path) logging.info(f"Starting to dump liminal configs into {path}") for liminal_config in liminal_configs: dump_liminal_config(liminal_config, f'{path}/{liminal_config['name']}.yml') def dump_liminal_config(liminal_config, file_path): with open(file_path, 'w') as config_file: logging.info(f"Dumping {liminal_config["name"]} into {file_path}") yaml.dump(liminal_config, config_file, default_flow_style=False)
# # 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 logging import os import yaml # { path -> { name -> config_file } } cached_files = dict() cached_source_files = dict() def resolve_pipeline_source_file(config_name): """ Return the source (file) path of the given config name """ return cached_source_files[config_name] def load(path): """ :param path: config path :returns dict of {name -> loaded config file} from all liminal.y[a]ml files under given path """ if cached_files.get(path): return cached_files[path] config_entities = {} for file_data in find_config_files(path): with open(file_data, 'r') as data: config_file = yaml.safe_load(data) config_entities[config_file['name']] = config_file cached_source_files[config_file['name']] = file_data cached_files[path] = config_entities return config_entities def find_config_files(path): """ :param path: config path :returns list of all liminal.y[a]ml files under config path """ files = [] logging.info(path) for r, d, f in os.walk(path): for file in f: if os.path.basename(file) in ['liminal.yml', 'liminal.yaml']: logging.info(os.path.join(r, file)) files.append(os.path.join(r, file)) return files def dump_liminal_configs(liminal_configs, path): if not (os.path.exists(path)): os.mkdir(path) logging.info(f"Starting to dump liminal configs into {path}") for liminal_config in liminal_configs: dump_liminal_config(liminal_config, f'{path}/{liminal_config["name"]}.yml') def dump_liminal_config(liminal_config, file_path): with open(file_path, 'w') as config_file: logging.info(f"Dumping {liminal_config['name']} into {file_path}") yaml.dump(liminal_config, config_file, default_flow_style=False)
""" User actions against Keycloak. """ import asyncio import logging from .token import get_rest_client logger = logging.getLogger('krs.users') def _fix_attributes(user): """ "Fix" user attributes that are only a single value. Translates them from a list to the single value. Operation is done in-place. Args: user (dict): user object """ if 'attributes' in user: for k in user['attributes']: if len(user['attributes'][k]) == 1: user['attributes'][k] = user['attributes'][k][0] class UserDoesNotExist(Exception): pass async def list_users(search=None, rest_client=None): """ List users in Keycloak. Returns: dict: username: user info """ start = 0 inc = 50 ret = {} data = [0]*inc while len(data) == inc: url = f'/users?&max={inc}&first={start}' if search: url += f'&search={search}' data = await rest_client.request('GET', url) start += inc for u in data: _fix_attributes(u) ret[u['username']] = u return ret async def user_info(username, rest_client=None): """ Get user information. Args: username (str): username of user Returns: dict: user info """ url = f'/users?exact=true&username={username}' ret = await rest_client.request('GET', url) if not ret: raise UserDoesNotExist(f'user "{username}" does not exist') _fix_attributes(ret[0]) return ret[0] async def create_user(username, first_name, last_name, email, attribs=None, rest_client=None): """ Create a user in Keycloak. Args: username (str): username of user to create first_name (str): first name last_name (str): last name email (str): email address attribs (dict): user attributes rest_client: keycloak rest client """ if not attribs: attribs = {} try: await user_info(username, rest_client=rest_client) except Exception: logger.info(f'creating user "{username}"') logger.info(username) user = { 'email': email, 'firstName': first_name, 'lastName': last_name, 'username': username, 'enabled': True, 'attributes': attribs, } await rest_client.request('POST', '/users', user) logger.info(f'user "{username}" created') else: logger.info(f'user "{username}" already exists') async def modify_user(username, attribs=None, rest_client=None): """ Modify a user in Keycloak. Args: username (str): username of user to modify attribs (dict): user attributes rest_client: keycloak rest client """ if not attribs: attribs = {} # get current user info try: ret = await user_info(username, rest_client=rest_client) except Exception: logger.info(f'user "{username}" does not exist') url = f'/users/{ret['id']}' ret = await rest_client.request('GET', url) # update info if 'attributes' not in ret: ret['attributes'] = {} for k in attribs: if attribs[k] is None: ret['attributes'].pop(k, None) elif isinstance(attribs[k], list): ret['attributes'][k] = attribs[k] else: ret['attributes'][k] = [attribs[k]] await rest_client.request('PUT', url, ret) async def set_user_password(username, password=None, temporary=False, rest_client=None): """ Set a user's password in Keycloak. Args: username (str): username of user password (str): new password temporary (bool): is this a temporary password that must be changed? """ if password is None: # get password from cmdline import getpass password = getpass.getpass() if not isinstance(password, str): raise Exception('password must be a string') try: ret = await user_info(username, rest_client=rest_client) except Exception: logger.info(f'user "{username}" does not exist') else: url = f'/users/{ret['id']}/reset-password' args = { 'value': password, 'temporary': bool(temporary), } ret = await rest_client.request('PUT', url, args) logger.info(f'user "{username}" password set') async def delete_user(username, rest_client=None): """ Delete a user in Keycloak. Args: username (str): username of user to delete """ try: ret = await user_info(username, rest_client=rest_client) except Exception: logger.info(f'user "{username}" does not exist') else: url = f'/users/{ret['id']}' ret = await rest_client.request('DELETE', url) logger.info(f'user "{username}" deleted') def main(): import argparse from pprint import pprint parser = argparse.ArgumentParser(description='Keycloak user management') subparsers = parser.add_subparsers() parser_list = subparsers.add_parser('list', help='list users') parser_list.add_argument('--search', default=None, help='search string') parser_list.set_defaults(func=list_users) parser_info = subparsers.add_parser('info', help='user info') parser_info.add_argument('username', help='user name') parser_info.set_defaults(func=user_info) parser_create = subparsers.add_parser('create', help='create a new user') parser_create.add_argument('username', help='user name') parser_create.add_argument('first_name', help='first name') parser_create.add_argument('last_name', help='last name') parser_create.add_argument('email', help='email address') parser_create.add_argument('attribs', nargs=argparse.REMAINDER) parser_create.set_defaults(func=create_user) parser_modify = subparsers.add_parser('modify', help='modify an existing user') parser_modify.add_argument('username', help='user name') parser_modify.add_argument('attribs', nargs=argparse.REMAINDER) parser_modify.set_defaults(func=modify_user) parser_set_password = subparsers.add_parser('set_password', help='set a user\'s password') parser_set_password.add_argument('username', help='user name') parser_set_password.add_argument('--password', default=None, help='password') parser_set_password.add_argument('--temporary', default=False, action='store_true', help='is password temporary?') parser_set_password.set_defaults(func=set_user_password) parser_delete = subparsers.add_parser('delete', help='delete a user') parser_delete.add_argument('username', help='user name') parser_delete.set_defaults(func=delete_user) args = vars(parser.parse_args()) logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO) rest_client = get_rest_client() func = args.pop('func') if 'attribs' in args: args['attribs'] = {item.split('=', 1)[0]: item.split('=', 1)[-1] for item in args['attribs']} ret = asyncio.run(func(rest_client=rest_client, **args)) if ret is not None: pprint(ret) if __name__ == '__main__': main()
""" User actions against Keycloak. """ import asyncio import logging from .token import get_rest_client logger = logging.getLogger('krs.users') def _fix_attributes(user): """ "Fix" user attributes that are only a single value. Translates them from a list to the single value. Operation is done in-place. Args: user (dict): user object """ if 'attributes' in user: for k in user['attributes']: if len(user['attributes'][k]) == 1: user['attributes'][k] = user['attributes'][k][0] class UserDoesNotExist(Exception): pass async def list_users(search=None, rest_client=None): """ List users in Keycloak. Returns: dict: username: user info """ start = 0 inc = 50 ret = {} data = [0]*inc while len(data) == inc: url = f'/users?&max={inc}&first={start}' if search: url += f'&search={search}' data = await rest_client.request('GET', url) start += inc for u in data: _fix_attributes(u) ret[u['username']] = u return ret async def user_info(username, rest_client=None): """ Get user information. Args: username (str): username of user Returns: dict: user info """ url = f'/users?exact=true&username={username}' ret = await rest_client.request('GET', url) if not ret: raise UserDoesNotExist(f'user "{username}" does not exist') _fix_attributes(ret[0]) return ret[0] async def create_user(username, first_name, last_name, email, attribs=None, rest_client=None): """ Create a user in Keycloak. Args: username (str): username of user to create first_name (str): first name last_name (str): last name email (str): email address attribs (dict): user attributes rest_client: keycloak rest client """ if not attribs: attribs = {} try: await user_info(username, rest_client=rest_client) except Exception: logger.info(f'creating user "{username}"') logger.info(username) user = { 'email': email, 'firstName': first_name, 'lastName': last_name, 'username': username, 'enabled': True, 'attributes': attribs, } await rest_client.request('POST', '/users', user) logger.info(f'user "{username}" created') else: logger.info(f'user "{username}" already exists') async def modify_user(username, attribs=None, rest_client=None): """ Modify a user in Keycloak. Args: username (str): username of user to modify attribs (dict): user attributes rest_client: keycloak rest client """ if not attribs: attribs = {} # get current user info try: ret = await user_info(username, rest_client=rest_client) except Exception: logger.info(f'user "{username}" does not exist') url = f'/users/{ret["id"]}' ret = await rest_client.request('GET', url) # update info if 'attributes' not in ret: ret['attributes'] = {} for k in attribs: if attribs[k] is None: ret['attributes'].pop(k, None) elif isinstance(attribs[k], list): ret['attributes'][k] = attribs[k] else: ret['attributes'][k] = [attribs[k]] await rest_client.request('PUT', url, ret) async def set_user_password(username, password=None, temporary=False, rest_client=None): """ Set a user's password in Keycloak. Args: username (str): username of user password (str): new password temporary (bool): is this a temporary password that must be changed? """ if password is None: # get password from cmdline import getpass password = getpass.getpass() if not isinstance(password, str): raise Exception('password must be a string') try: ret = await user_info(username, rest_client=rest_client) except Exception: logger.info(f'user "{username}" does not exist') else: url = f'/users/{ret["id"]}/reset-password' args = { 'value': password, 'temporary': bool(temporary), } ret = await rest_client.request('PUT', url, args) logger.info(f'user "{username}" password set') async def delete_user(username, rest_client=None): """ Delete a user in Keycloak. Args: username (str): username of user to delete """ try: ret = await user_info(username, rest_client=rest_client) except Exception: logger.info(f'user "{username}" does not exist') else: url = f'/users/{ret["id"]}' ret = await rest_client.request('DELETE', url) logger.info(f'user "{username}" deleted') def main(): import argparse from pprint import pprint parser = argparse.ArgumentParser(description='Keycloak user management') subparsers = parser.add_subparsers() parser_list = subparsers.add_parser('list', help='list users') parser_list.add_argument('--search', default=None, help='search string') parser_list.set_defaults(func=list_users) parser_info = subparsers.add_parser('info', help='user info') parser_info.add_argument('username', help='user name') parser_info.set_defaults(func=user_info) parser_create = subparsers.add_parser('create', help='create a new user') parser_create.add_argument('username', help='user name') parser_create.add_argument('first_name', help='first name') parser_create.add_argument('last_name', help='last name') parser_create.add_argument('email', help='email address') parser_create.add_argument('attribs', nargs=argparse.REMAINDER) parser_create.set_defaults(func=create_user) parser_modify = subparsers.add_parser('modify', help='modify an existing user') parser_modify.add_argument('username', help='user name') parser_modify.add_argument('attribs', nargs=argparse.REMAINDER) parser_modify.set_defaults(func=modify_user) parser_set_password = subparsers.add_parser('set_password', help='set a user\'s password') parser_set_password.add_argument('username', help='user name') parser_set_password.add_argument('--password', default=None, help='password') parser_set_password.add_argument('--temporary', default=False, action='store_true', help='is password temporary?') parser_set_password.set_defaults(func=set_user_password) parser_delete = subparsers.add_parser('delete', help='delete a user') parser_delete.add_argument('username', help='user name') parser_delete.set_defaults(func=delete_user) args = vars(parser.parse_args()) logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO) rest_client = get_rest_client() func = args.pop('func') if 'attribs' in args: args['attribs'] = {item.split('=', 1)[0]: item.split('=', 1)[-1] for item in args['attribs']} ret = asyncio.run(func(rest_client=rest_client, **args)) if ret is not None: pprint(ret) if __name__ == '__main__': main()
import pymysql import logging import traceback from singleton import Singleton from database_config import MysqlDataBaseConfig from config import Config class MysqlDataBase(metaclass=Singleton): def __init__(self, ticker_priority_exchange): self.logger = logging.getLogger( Config.LOGGING_NAME + "." + str(__name__)) self.connection = None self.ticker_priority_exchange = ticker_priority_exchange self.last_insert = 0 def __parse_sql(self,table : str,row : dict): if type(table) != str and type(row) != dict: return False sql = "insert into " + table + " (" row = {k:v for k,v in row.items() if type(k) == str and not k.startswith("_")} for key in row: sql += key + "," sql = sql[:-1] sql += ") values(" for key in row: if type(row[key]) == str: sql += "'" + row[key] + "'," else: sql += str(row[key]) + "," sql = sql[:-1] sql += ")" return sql def insert(self, table, row): if table == "tickers" and row["source"] != self.ticker_priority_exchange: diff = row["epoch"] - self.last_insert if diff < 60: self.logger.debug(f"recent ticker insert {diff}s from priority exchange {self.ticker_priority_exchange}, discard ticker insert from {row["source"]}") return if self.connection != None: lastrowid = -1 try: sql = self.__parse_sql(table,row) self.logger.debug(sql) if sql: with self.connection.cursor() as cursor: cursor.execute(sql) lastrowid = cursor.lastrowid self.connection.commit() except pymysql.OperationalError as error: self.logger.error( f"OperationalError ticker:{error}->{traceback.format_exc()}") raise e except Exception as e: self.logger.error( f"Error insert mysql ticker:{e}->{traceback.format_exc()}") raise e else: self.logger.debug(f"insert ticker result:{lastrowid}") if table == "tickers" and row["source"] == self.ticker_priority_exchange: self.last_insert = row["epoch"] return def close(self): self.connection.close() self.connection = None def connect(self): try: self.connection = pymysql.connect(host=MysqlDataBaseConfig.host, port=MysqlDataBaseConfig.port, user=MysqlDataBaseConfig.user, password=MysqlDataBaseConfig.password, db=MysqlDataBaseConfig.database, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) except Exception as e: self.logger.error( f"Mysql Connection ERROR:{e}->{traceback.format_exc()}") raise e
import pymysql import logging import traceback from singleton import Singleton from database_config import MysqlDataBaseConfig from config import Config class MysqlDataBase(metaclass=Singleton): def __init__(self, ticker_priority_exchange): self.logger = logging.getLogger( Config.LOGGING_NAME + "." + str(__name__)) self.connection = None self.ticker_priority_exchange = ticker_priority_exchange self.last_insert = 0 def __parse_sql(self,table : str,row : dict): if type(table) != str and type(row) != dict: return False sql = "insert into " + table + " (" row = {k:v for k,v in row.items() if type(k) == str and not k.startswith("_")} for key in row: sql += key + "," sql = sql[:-1] sql += ") values(" for key in row: if type(row[key]) == str: sql += "'" + row[key] + "'," else: sql += str(row[key]) + "," sql = sql[:-1] sql += ")" return sql def insert(self, table, row): if table == "tickers" and row["source"] != self.ticker_priority_exchange: diff = row["epoch"] - self.last_insert if diff < 60: self.logger.debug(f"recent ticker insert {diff}s from priority exchange {self.ticker_priority_exchange}, discard ticker insert from {row['source']}") return if self.connection != None: lastrowid = -1 try: sql = self.__parse_sql(table,row) self.logger.debug(sql) if sql: with self.connection.cursor() as cursor: cursor.execute(sql) lastrowid = cursor.lastrowid self.connection.commit() except pymysql.OperationalError as error: self.logger.error( f"OperationalError ticker:{error}->{traceback.format_exc()}") raise e except Exception as e: self.logger.error( f"Error insert mysql ticker:{e}->{traceback.format_exc()}") raise e else: self.logger.debug(f"insert ticker result:{lastrowid}") if table == "tickers" and row["source"] == self.ticker_priority_exchange: self.last_insert = row["epoch"] return def close(self): self.connection.close() self.connection = None def connect(self): try: self.connection = pymysql.connect(host=MysqlDataBaseConfig.host, port=MysqlDataBaseConfig.port, user=MysqlDataBaseConfig.user, password=MysqlDataBaseConfig.password, db=MysqlDataBaseConfig.database, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) except Exception as e: self.logger.error( f"Mysql Connection ERROR:{e}->{traceback.format_exc()}") raise e
"""This modules contains helper methods to export nitextureproperty type nodes""" # ***** BEGIN LICENSE BLOCK ***** # # Copyright © 2020, NIF File Format Library and Tools contributors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # * Neither the name of the NIF File Format Library and Tools # project nor the names of its contributors may be used to endorse # or promote products derived from this software without specific # prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # ***** END LICENSE BLOCK ***** import bpy from pyffi.formats.nif import NifFormat from io_scene_niftools.modules.nif_export.block_registry import block_store from io_scene_niftools.modules.nif_export.property.texture import TextureSlotManager, TextureWriter from io_scene_niftools.utils.logging import NifLog class NiTextureProp(TextureSlotManager): # TODO Common for import/export """Names (ordered by default index) of shader texture slots for Sid Meier's Railroads and similar games.""" EXTRA_SHADER_TEXTURES = [ "EnvironmentMapIndex", "NormalMapIndex", "SpecularIntensityIndex", "EnvironmentIntensityIndex", "LightCubeMapIndex", "ShadowTextureIndex"] # Default ordering of Extra data blocks for different games USED_EXTRA_SHADER_TEXTURES = { 'SID_MEIER_S_RAILROADS': (3, 0, 4, 1, 5, 2), 'CIVILIZATION_IV': (3, 0, 1, 2) } __instance = None def __init__(self): """ Virtually private constructor. """ if NiTextureProp.__instance: raise Exception("This class is a singleton!") else: super().__init__() NiTextureProp.__instance = self @staticmethod def get(): """ Static access method. """ if not NiTextureProp.__instance: NiTextureProp() return NiTextureProp.__instance def export_texturing_property(self, flags=0x0001, applymode=None, b_mat=None): """Export texturing property.""" self.determine_texture_types(b_mat) texprop = NifFormat.NiTexturingProperty() texprop.flags = flags texprop.apply_mode = applymode texprop.texture_count = 7 self.export_texture_shader_effect(texprop) self.export_nitextureprop_tex_descs(texprop) # search for duplicate for n_block in block_store.block_to_obj: if isinstance(n_block, NifFormat.NiTexturingProperty) and n_block.get_hash() == texprop.get_hash(): return n_block # no texturing property with given settings found, so use and register # the new one return texprop def export_nitextureprop_tex_descs(self, texprop): # go over all valid texture slots for slot_name, b_texture_node in self.slots.items(): if b_texture_node: # get the field name used by nif xml for this texture field_name = f"{slot_name.lower().replace(" ", "_")}_texture" NifLog.debug(f"Activating {field_name} for {b_texture_node.name}") setattr(texprop, "has_"+field_name, True) # get the tex desc link texdesc = getattr(texprop, field_name) uv_index = self.get_uv_node(b_texture_node) # set uv index and source texture to the texdesc texdesc.uv_set = uv_index texdesc.source = TextureWriter.export_source_texture(b_texture_node) # TODO [animation] FIXME Heirarchy # self.texture_anim.export_flip_controller(fliptxt, self.base_mtex.texture, texprop, 0) # todo [texture] support extra shader textures again # if self.slots["Bump Map"]: # if bpy.context.scene.niftools_scene.game not in self.USED_EXTRA_SHADER_TEXTURES: # texprop.has_bump_map_texture = True # self.texture_writer.export_tex_desc(texdesc=texprop.bump_map_texture, # uv_set=uv_index, # b_texture_node=self.slots["Bump Map"]) # texprop.bump_map_luma_scale = 1.0 # texprop.bump_map_luma_offset = 0.0 # texprop.bump_map_matrix.m_11 = 1.0 # texprop.bump_map_matrix.m_12 = 0.0 # texprop.bump_map_matrix.m_21 = 0.0 # texprop.bump_map_matrix.m_22 = 1.0 # # if self.slots["Normal"]: # shadertexdesc = texprop.shader_textures[1] # shadertexdesc.is_used = True # shadertexdesc.texture_data.source = TextureWriter.export_source_texture(n_texture=self.slots["Bump Map"]) # # if self.slots["Gloss"]: # if bpy.context.scene.niftools_scene.game not in self.USED_EXTRA_SHADER_TEXTURES: # texprop.has_gloss_texture = True # self.texture_writer.export_tex_desc(texdesc=texprop.gloss_texture, # uv_set=uv_index, # b_texture_node=self.slots["Gloss"]) # else: # shadertexdesc = texprop.shader_textures[2] # shadertexdesc.is_used = True # shadertexdesc.texture_data.source = TextureWriter.export_source_texture(n_texture=self.slots["Gloss"]) # if self.b_ref_slot: # if bpy.context.scene.niftools_scene.game not in self.USED_EXTRA_SHADER_TEXTURES: # NifLog.warn("Cannot export reflection texture for this game.") # # tex_prop.hasRefTexture = True # # self.export_tex_desc(texdesc=tex_prop.refTexture, uv_set=uv_set, mtex=refmtex) # else: # shadertexdesc = texprop.shader_textures[3] # shadertexdesc.is_used = True # shadertexdesc.texture_data.source = TextureWriter.export_source_texture(n_texture=self.b_ref_slot.texture) def export_texture_effect(self, b_texture_node=None): """Export a texture effect block from material texture mtex (MTex, not Texture).""" texeff = NifFormat.NiTextureEffect() texeff.flags = 4 texeff.rotation.set_identity() texeff.scale = 1.0 texeff.model_projection_matrix.set_identity() texeff.texture_filtering = NifFormat.TexFilterMode.FILTER_TRILERP texeff.texture_clamping = NifFormat.TexClampMode.WRAP_S_WRAP_T texeff.texture_type = NifFormat.EffectType.EFFECT_ENVIRONMENT_MAP texeff.coordinate_generation_type = NifFormat.CoordGenType.CG_SPHERE_MAP if b_texture_node: texeff.source_texture = TextureWriter.export_source_texture(b_texture_node.texture) if bpy.context.scene.niftools_scene.game == 'MORROWIND': texeff.num_affected_node_list_pointers += 1 texeff.affected_node_list_pointers.update_size() texeff.unknown_vector.x = 1.0 return block_store.register_block(texeff) def export_texture_shader_effect(self, tex_prop): # disable return # export extra shader textures if bpy.context.scene.niftools_scene.game == 'SID_MEIER_S_RAILROADS': # sid meier's railroads: # some textures end up in the shader texture list there are 5 slots available, so set them up tex_prop.num_shader_textures = 5 tex_prop.shader_textures.update_size() for mapindex, shadertexdesc in enumerate(tex_prop.shader_textures): # set default values shadertexdesc.is_used = False shadertexdesc.map_index = mapindex # some texture slots required by the engine shadertexdesc_envmap = tex_prop.shader_textures[0] shadertexdesc_envmap.is_used = True shadertexdesc_envmap.texture_data.source = TextureWriter.export_source_texture(filename="RRT_Engine_Env_map.dds") shadertexdesc_cubelightmap = tex_prop.shader_textures[4] shadertexdesc_cubelightmap.is_used = True shadertexdesc_cubelightmap.texture_data.source = TextureWriter.export_source_texture(filename="RRT_Cube_Light_map_128.dds") elif bpy.context.scene.niftools_scene.game == 'CIVILIZATION_IV': # some textures end up in the shader texture list there are 4 slots available, so set them up tex_prop.num_shader_textures = 4 tex_prop.shader_textures.update_size() for mapindex, shadertexdesc in enumerate(tex_prop.shader_textures): # set default values shadertexdesc.is_used = False shadertexdesc.map_index = mapindex def add_shader_integer_extra_datas(self, trishape): """Add extra data blocks for shader indices.""" for shaderindex in self.USED_EXTRA_SHADER_TEXTURES[bpy.context.scene.niftools_scene.game]: shader_name = self.EXTRA_SHADER_TEXTURES[shaderindex] trishape.add_integer_extra_data(shader_name, shaderindex) @staticmethod def get_n_apply_mode_from_b_blend_type(b_blend_type): if b_blend_type == "LIGHTEN": return NifFormat.ApplyMode.APPLY_HILIGHT elif b_blend_type == "MULTIPLY": return NifFormat.ApplyMode.APPLY_HILIGHT2 elif b_blend_type == "MIX": return NifFormat.ApplyMode.APPLY_MODULATE NifLog.warn("Unsupported blend type ({0}) in material, using apply mode APPLY_MODULATE".format(b_blend_type)) return NifFormat.ApplyMode.APPLY_MODULATE
"""This modules contains helper methods to export nitextureproperty type nodes""" # ***** BEGIN LICENSE BLOCK ***** # # Copyright © 2020, NIF File Format Library and Tools contributors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # * Neither the name of the NIF File Format Library and Tools # project nor the names of its contributors may be used to endorse # or promote products derived from this software without specific # prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # ***** END LICENSE BLOCK ***** import bpy from pyffi.formats.nif import NifFormat from io_scene_niftools.modules.nif_export.block_registry import block_store from io_scene_niftools.modules.nif_export.property.texture import TextureSlotManager, TextureWriter from io_scene_niftools.utils.logging import NifLog class NiTextureProp(TextureSlotManager): # TODO Common for import/export """Names (ordered by default index) of shader texture slots for Sid Meier's Railroads and similar games.""" EXTRA_SHADER_TEXTURES = [ "EnvironmentMapIndex", "NormalMapIndex", "SpecularIntensityIndex", "EnvironmentIntensityIndex", "LightCubeMapIndex", "ShadowTextureIndex"] # Default ordering of Extra data blocks for different games USED_EXTRA_SHADER_TEXTURES = { 'SID_MEIER_S_RAILROADS': (3, 0, 4, 1, 5, 2), 'CIVILIZATION_IV': (3, 0, 1, 2) } __instance = None def __init__(self): """ Virtually private constructor. """ if NiTextureProp.__instance: raise Exception("This class is a singleton!") else: super().__init__() NiTextureProp.__instance = self @staticmethod def get(): """ Static access method. """ if not NiTextureProp.__instance: NiTextureProp() return NiTextureProp.__instance def export_texturing_property(self, flags=0x0001, applymode=None, b_mat=None): """Export texturing property.""" self.determine_texture_types(b_mat) texprop = NifFormat.NiTexturingProperty() texprop.flags = flags texprop.apply_mode = applymode texprop.texture_count = 7 self.export_texture_shader_effect(texprop) self.export_nitextureprop_tex_descs(texprop) # search for duplicate for n_block in block_store.block_to_obj: if isinstance(n_block, NifFormat.NiTexturingProperty) and n_block.get_hash() == texprop.get_hash(): return n_block # no texturing property with given settings found, so use and register # the new one return texprop def export_nitextureprop_tex_descs(self, texprop): # go over all valid texture slots for slot_name, b_texture_node in self.slots.items(): if b_texture_node: # get the field name used by nif xml for this texture field_name = f"{slot_name.lower().replace(' ', '_')}_texture" NifLog.debug(f"Activating {field_name} for {b_texture_node.name}") setattr(texprop, "has_"+field_name, True) # get the tex desc link texdesc = getattr(texprop, field_name) uv_index = self.get_uv_node(b_texture_node) # set uv index and source texture to the texdesc texdesc.uv_set = uv_index texdesc.source = TextureWriter.export_source_texture(b_texture_node) # TODO [animation] FIXME Heirarchy # self.texture_anim.export_flip_controller(fliptxt, self.base_mtex.texture, texprop, 0) # todo [texture] support extra shader textures again # if self.slots["Bump Map"]: # if bpy.context.scene.niftools_scene.game not in self.USED_EXTRA_SHADER_TEXTURES: # texprop.has_bump_map_texture = True # self.texture_writer.export_tex_desc(texdesc=texprop.bump_map_texture, # uv_set=uv_index, # b_texture_node=self.slots["Bump Map"]) # texprop.bump_map_luma_scale = 1.0 # texprop.bump_map_luma_offset = 0.0 # texprop.bump_map_matrix.m_11 = 1.0 # texprop.bump_map_matrix.m_12 = 0.0 # texprop.bump_map_matrix.m_21 = 0.0 # texprop.bump_map_matrix.m_22 = 1.0 # # if self.slots["Normal"]: # shadertexdesc = texprop.shader_textures[1] # shadertexdesc.is_used = True # shadertexdesc.texture_data.source = TextureWriter.export_source_texture(n_texture=self.slots["Bump Map"]) # # if self.slots["Gloss"]: # if bpy.context.scene.niftools_scene.game not in self.USED_EXTRA_SHADER_TEXTURES: # texprop.has_gloss_texture = True # self.texture_writer.export_tex_desc(texdesc=texprop.gloss_texture, # uv_set=uv_index, # b_texture_node=self.slots["Gloss"]) # else: # shadertexdesc = texprop.shader_textures[2] # shadertexdesc.is_used = True # shadertexdesc.texture_data.source = TextureWriter.export_source_texture(n_texture=self.slots["Gloss"]) # if self.b_ref_slot: # if bpy.context.scene.niftools_scene.game not in self.USED_EXTRA_SHADER_TEXTURES: # NifLog.warn("Cannot export reflection texture for this game.") # # tex_prop.hasRefTexture = True # # self.export_tex_desc(texdesc=tex_prop.refTexture, uv_set=uv_set, mtex=refmtex) # else: # shadertexdesc = texprop.shader_textures[3] # shadertexdesc.is_used = True # shadertexdesc.texture_data.source = TextureWriter.export_source_texture(n_texture=self.b_ref_slot.texture) def export_texture_effect(self, b_texture_node=None): """Export a texture effect block from material texture mtex (MTex, not Texture).""" texeff = NifFormat.NiTextureEffect() texeff.flags = 4 texeff.rotation.set_identity() texeff.scale = 1.0 texeff.model_projection_matrix.set_identity() texeff.texture_filtering = NifFormat.TexFilterMode.FILTER_TRILERP texeff.texture_clamping = NifFormat.TexClampMode.WRAP_S_WRAP_T texeff.texture_type = NifFormat.EffectType.EFFECT_ENVIRONMENT_MAP texeff.coordinate_generation_type = NifFormat.CoordGenType.CG_SPHERE_MAP if b_texture_node: texeff.source_texture = TextureWriter.export_source_texture(b_texture_node.texture) if bpy.context.scene.niftools_scene.game == 'MORROWIND': texeff.num_affected_node_list_pointers += 1 texeff.affected_node_list_pointers.update_size() texeff.unknown_vector.x = 1.0 return block_store.register_block(texeff) def export_texture_shader_effect(self, tex_prop): # disable return # export extra shader textures if bpy.context.scene.niftools_scene.game == 'SID_MEIER_S_RAILROADS': # sid meier's railroads: # some textures end up in the shader texture list there are 5 slots available, so set them up tex_prop.num_shader_textures = 5 tex_prop.shader_textures.update_size() for mapindex, shadertexdesc in enumerate(tex_prop.shader_textures): # set default values shadertexdesc.is_used = False shadertexdesc.map_index = mapindex # some texture slots required by the engine shadertexdesc_envmap = tex_prop.shader_textures[0] shadertexdesc_envmap.is_used = True shadertexdesc_envmap.texture_data.source = TextureWriter.export_source_texture(filename="RRT_Engine_Env_map.dds") shadertexdesc_cubelightmap = tex_prop.shader_textures[4] shadertexdesc_cubelightmap.is_used = True shadertexdesc_cubelightmap.texture_data.source = TextureWriter.export_source_texture(filename="RRT_Cube_Light_map_128.dds") elif bpy.context.scene.niftools_scene.game == 'CIVILIZATION_IV': # some textures end up in the shader texture list there are 4 slots available, so set them up tex_prop.num_shader_textures = 4 tex_prop.shader_textures.update_size() for mapindex, shadertexdesc in enumerate(tex_prop.shader_textures): # set default values shadertexdesc.is_used = False shadertexdesc.map_index = mapindex def add_shader_integer_extra_datas(self, trishape): """Add extra data blocks for shader indices.""" for shaderindex in self.USED_EXTRA_SHADER_TEXTURES[bpy.context.scene.niftools_scene.game]: shader_name = self.EXTRA_SHADER_TEXTURES[shaderindex] trishape.add_integer_extra_data(shader_name, shaderindex) @staticmethod def get_n_apply_mode_from_b_blend_type(b_blend_type): if b_blend_type == "LIGHTEN": return NifFormat.ApplyMode.APPLY_HILIGHT elif b_blend_type == "MULTIPLY": return NifFormat.ApplyMode.APPLY_HILIGHT2 elif b_blend_type == "MIX": return NifFormat.ApplyMode.APPLY_MODULATE NifLog.warn("Unsupported blend type ({0}) in material, using apply mode APPLY_MODULATE".format(b_blend_type)) return NifFormat.ApplyMode.APPLY_MODULATE
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import logging import os import sys import time from collections import defaultdict import numpy as np import pandas as pd import torch import torch.distributed as dist from tensorboardX import SummaryWriter from torch.utils.data import RandomSampler, SequentialSampler from torch.utils.data.distributed import DistributedSampler from classifier.agent import Agent from classifier.data_loader import ( ClassifierDataLoader, ClassifierDataloader_collate_fn, ClassifierDataset, ) from eval import Evaluation from params import args from utils import set_seed from utils_data import load_detector_classes, read_tsv_img_features, timeSince sys.path.insert(0, "/root/mount/Matterport3DSimulator/") from model_utils import MODEL_CLASS, special_tokens_dict from transformers.pytorch_transformers import ( BertConfig, BertTokenizer, ) logger = logging.getLogger(__name__) TRAIN_VOCAB = "tasks/NDH/data/train_vocab.txt" TRAINVAL_VOCAB = "tasks/NDH/data/trainval_vocab.txt" def train(args, features): encoder_path = os.path.join(args.model_name_or_path, "encoder") decoder_path = os.path.join(args.model_name_or_path, "decoder") tokenizer_path = args.model_name_or_path tmp_root_folder = "srv/oscar_weights/base-vg-labels/ep_107_1192087" config_path = os.path.join(tmp_root_folder, "config.json") config = BertConfig.from_pretrained(config_path) config.img_feature_dim = args.img_feature_dim config.hidden_dropout_prob = args.drop_out config.classifier = "linear" config.loss_type = "CrossEntropy" config.cls_hidden_scale = 2 config.action_space = args.action_space config.detector_classes = len(load_detector_classes()) add_new_extra_embeds = not args.oscar_setting if add_new_extra_embeds: config.vocab_size = config.vocab_size + 3 config.special_vocab_size = config.vocab_size config.type_vocab_size = config.type_vocab_size + 4 config.max_position_embeddings = args.max_seq_length else: config.special_vocab_size = config.vocab_size model_class = MODEL_CLASS["PreTrainOscar"][1] model = model_class(config) bert_encoder = model.bert tokenizer = BertTokenizer.from_pretrained( tokenizer_path, do_lower_case=True, ) if add_new_extra_embeds: num_added_toks = tokenizer.add_special_tokens(special_tokens_dict) logger.info( f"Added {num_added_toks} tokens {" ".join(special_tokens_dict.values())} to Tokenizer" ) train_dataset = ClassifierDataset( args=args, splits=["train"], tokenizer=tokenizer, truncate_dialog=True, ) tensorboard_dir = os.path.join(args.output_dir, "tensorboard") if args.local_rank in [-2, -1, 0]: tb_writer = SummaryWriter(logdir=tensorboard_dir, flush_secs=30) args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) train_sampler = ( RandomSampler(train_dataset) if args.local_rank in [-2, -1] else DistributedSampler(train_dataset) ) train_data_loader = ClassifierDataLoader( dataset=train_dataset, splits=["train"], feature_store=features, tokenizer=tokenizer, batch_size=args.train_batch_size, collate_fn=ClassifierDataloader_collate_fn, sampler=train_sampler, num_workers=args.num_workers, pin_memory=True, drop_last=True, ) agent = Agent( args=args, tokenizer=tokenizer, dataloader=train_data_loader, results_path="", bert=bert_encoder, episode_len=args.max_episode_len, ) agent.load(encoder_path, decoder_path) if args.n_gpu > 1: agent.encoder = torch.nn.DataParallel(agent.encoder) agent.decoder = torch.nn.DataParallel(agent.decoder) if args.local_rank not in [-2, -1]: agent.encoder = torch.nn.parallel.DistributedDataParallel( agent.encoder, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True, ) agent.decoder = torch.nn.parallel.DistributedDataParallel( agent.decoder, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True, ) logger.info("Training an Classifier agent with %s feedback" % args.feedback_method) data_log = defaultdict(list) start = time.time() n_iters = args.num_iterations log_every = args.logging_steps for idx in range(0, n_iters, log_every): interval = min(log_every, n_iters - idx) iter_no = idx + interval if args.local_rank in [-2, -1, 0]: data_log["iteration"].append(iter_no) agent.train(interval, feedback=args.feedback_method) train_losses = np.array(agent.losses) assert len(train_losses) == interval train_loss_avg = np.average(train_losses) loss_str = "" if args.local_rank in [-2, -1, 0]: data_log["train loss"].append(train_loss_avg) loss_str += "train loss: %.4f" % train_loss_avg tb_writer.add_scalar( "classification/loss_train", train_loss_avg, global_step=iter_no ) for metric, value in agent.metrics.items(): loss_str += ", %s: %.3f" % (metric, value) tb_writer.add_scalar( f"classification/{metric}_train", value, global_step=iter_no ) if ( args.local_rank in [-2, -1, 0] and args.save_steps > 0 and idx % args.save_steps == 0 ): df = pd.DataFrame(data_log) df.set_index("iteration") df_path = os.path.join(args.output_dir, "results", f"{iter_no}-log.csv") df.to_csv(df_path) output_dir = os.path.join( args.output_dir, "checkpoints", f"checkpoint-{iter_no}" ) if not os.path.exists(output_dir): os.makedirs(output_dir) agent.save( os.path.join(output_dir, "encoder"), os.path.join(output_dir, "decoder") ) torch.save(args, os.path.join(output_dir, "training_args.bin")) tokenizer.save_pretrained(output_dir) logger.info(f"Saving model checkpoint {iter_no} to {output_dir}") logger.info( "%s (%d %d%%) %s" % ( timeSince(start, float(iter_no) / n_iters), iter_no, float(iter_no) / n_iters * 100, loss_str, ) ) def val(args, features, list_iter_no): tensorboard_dir = os.path.join(args.output_dir, "tensorboard") if args.local_rank in [-2, -1, 0]: tb_writer = SummaryWriter(logdir=tensorboard_dir, flush_secs=30) root_folder = args.model_name_or_path for iter_no in list_iter_no: encoder_path = os.path.join(root_folder, f"checkpoint-{iter_no}", "encoder") decoder_path = os.path.join(root_folder, f"checkpoint-{iter_no}", "decoder") tokenizer_path = os.path.join(root_folder, f"checkpoint-{iter_no}/") tmp_root_folder = "srv/oscar_weights/base-vg-labels/ep_107_1192087" config_path = os.path.join(tmp_root_folder, "config.json") config = BertConfig.from_pretrained(config_path) config.img_feature_dim = args.img_feature_dim config.hidden_dropout_prob = args.drop_out config.classifier = "linear" config.loss_type = "CrossEntropy" config.cls_hidden_scale = 2 config.action_space = args.action_space config.detector_classes = len(load_detector_classes()) add_new_extra_embeds = not args.oscar_setting if add_new_extra_embeds: config.vocab_size = config.vocab_size + 3 config.special_vocab_size = config.vocab_size config.type_vocab_size = config.type_vocab_size + 4 config.max_position_embeddings = args.max_seq_length else: config.special_vocab_size = config.vocab_size model_class = MODEL_CLASS["PreTrainOscar"][1] model = model_class(config) bert_encoder = model.bert tokenizer = BertTokenizer.from_pretrained( tokenizer_path, do_lower_case=True, ) if add_new_extra_embeds: num_added_toks = tokenizer.add_special_tokens(special_tokens_dict) logger.info( f"Added {num_added_toks} tokens {" ".join(special_tokens_dict.values())} to Tokenizer" ) val_seen_dataset = ClassifierDataset( args=args, splits=["val_seen"], tokenizer=tokenizer, truncate_dialog=True, ) val_unseen_dataset = ClassifierDataset( args=args, splits=["val_unseen"], tokenizer=tokenizer, truncate_dialog=True, ) val_datasets = { "val_seen": val_seen_dataset, "val_unseen": val_unseen_dataset, } val_data_loaders = {} args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) for split, val_dataset in val_datasets.items(): val_sampler = SequentialSampler(val_dataset) val_data_loader = ClassifierDataLoader( dataset=val_dataset, splits=["val_seen"], feature_store=features, tokenizer=tokenizer, batch_size=args.eval_batch_size, collate_fn=ClassifierDataloader_collate_fn, sampler=val_sampler, num_workers=args.num_workers, pin_memory=True, drop_last=True, ) evaluation = Evaluation([split], path_type=args.path_type) val_data_loaders[split] = (val_data_loader, evaluation) agent = Agent( args=args, tokenizer=tokenizer, dataloader=val_data_loader, results_path="", bert=bert_encoder, episode_len=args.max_episode_len, ) agent.load(encoder_path, decoder_path) if args.n_gpu > 1: agent.encoder = torch.nn.DataParallel(agent.encoder) agent.decoder = torch.nn.DataParallel(agent.decoder) if args.local_rank not in [-2, -1]: agent.encoder = torch.nn.parallel.DistributedDataParallel( agent.encoder, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True, ) agent.decoder = torch.nn.parallel.DistributedDataParallel( agent.decoder, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True, ) logger.info( "Validating the Classifier agent with %s feedback for iteration %d" % (args.feedback_method, iter_no) ) data_log = defaultdict(list) data_log["iteration"].append(iter_no) for env_name, (dataloader, evaluator) in val_data_loaders.items(): start = time.time() agent.dataloader = dataloader agent.data_iter = iter(agent.dataloader) agent.results_path = os.path.join( args.output_dir, "predictions", f"{env_name}-{iter_no}.json" ) agent.test() val_losses = np.array(agent.losses) val_loss_avg = np.average(val_losses) tb_writer.add_scalar( f"classification/loss_{env_name}", val_loss_avg, global_step=iter_no ) data_log["%s loss" % env_name].append(val_loss_avg) loss_str = ", %s loss: %.4f" % (env_name, val_loss_avg) for metric, val in agent.metrics.items(): data_log["%s %s" % (env_name, metric)].append(val) loss_str += ", %s: %.3f" % (metric, val) tb_writer.add_scalar( f"classification/{metric}_{env_name}", val, global_step=iter_no ) end = time.time() logger.info( "Time: %0.2f min Eval Iter: %d %s" % ( (end - start) / 60, iter_no, loss_str, ) ) df = pd.DataFrame(data_log) df.set_index("iteration") df_path = os.path.join(args.output_dir, "results", f"{iter_no}-log.csv") df.to_csv(df_path) sys.exit() def test_submission(args, features, list_iter_no): root_folder = args.model_name_or_path for iter_no in list_iter_no: encoder_path = os.path.join(root_folder, f"checkpoint-{iter_no}", "encoder") decoder_path = os.path.join(root_folder, f"checkpoint-{iter_no}", "decoder") tokenizer_path = os.path.join(root_folder, f"checkpoint-{iter_no}/") tmp_root_folder = "srv/oscar_weights/base-vg-labels/ep_107_1192087" config_path = os.path.join(tmp_root_folder, "config.json") config = BertConfig.from_pretrained(config_path) config.img_feature_dim = args.img_feature_dim config.hidden_dropout_prob = args.drop_out config.classifier = "linear" config.loss_type = "CrossEntropy" config.cls_hidden_scale = 2 config.action_space = args.action_space add_new_extra_embeds = not args.oscar_setting if add_new_extra_embeds: config.vocab_size = config.vocab_size + 3 config.special_vocab_size = config.vocab_size config.type_vocab_size = config.type_vocab_size + 4 config.max_position_embeddings = args.max_seq_length else: config.special_vocab_size = config.vocab_size model_class = MODEL_CLASS["PreTrainOscar"][1] model = model_class(config) bert_encoder = model.bert tokenizer = BertTokenizer.from_pretrained( tokenizer_path, do_lower_case=True, ) if add_new_extra_embeds: num_added_toks = tokenizer.add_special_tokens(special_tokens_dict) logger.info( f"Added {num_added_toks} tokens {" ".join(special_tokens_dict.values())} to Tokenizer" ) test_dataset = VLNDataset( args=args, splits=["test"], tokenizer=tokenizer, truncate_dialog=True, path_type=args.path_type, ) args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) test_sampler = SequentialSampler(test_dataset) test_data_loader = VLNDataLoader( dataset=test_dataset, splits=["test"], feature_store=features, tokenizer=tokenizer, batch_size=args.eval_batch_size, collate_fn=VLNDataloader_collate_fn, sampler=test_sampler, num_workers=args.num_workers, pin_memory=True, drop_last=False, ) agent = Agent( args=args, tokenizer=tokenizer, dataloader=test_data_loader, results_path="", bert=bert_encoder, episode_len=args.max_episode_len, ) agent.load(encoder_path, decoder_path) if args.n_gpu > 1: agent.encoder = torch.nn.DataParallel(agent.encoder) agent.decoder = torch.nn.DataParallel(agent.decoder) if args.local_rank not in [-2, -1]: agent.encoder = torch.nn.parallel.DistributedDataParallel( agent.encoder, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True, ) agent.decoder = torch.nn.parallel.DistributedDataParallel( agent.decoder, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True, ) logger.info( "Generating test split predictions for the LSTM agent iteration %d" % (iter_no) ) data_log = defaultdict(list) data_log["iteration"].append(iter_no) start = time.time() agent.dataloader = test_data_loader agent.data_iter = iter(agent.dataloader) agent.results_path = os.path.join( args.output_dir, "predictions", f"test-{iter_no}.json" ) agent.test(use_dropout=False, feedback="argmax") agent.write_results() logger.info(f"Saving results to {agent.results_path}") end = time.time() logger.info( "Time: %0.2f min Eval Iter: %d" % ( (end - start) / 60, iter_no, ) ) sys.exit() def main(): if ( args.local_rank in [-1, 0] and os.path.exists(args.output_dir) and os.listdir(args.output_dir) and not args.eval_only and not args.test_only and not args.debug ): raise IOError( "%s \nOutput Directory not empty and train setting is on. Exiting to prevent overwriting..." % (args.output_dir) ) if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]: os.makedirs(args.output_dir) os.makedirs(os.path.join(args.output_dir, "checkpoints")) os.makedirs(os.path.join(args.output_dir, "predictions")) os.makedirs(os.path.join(args.output_dir, "results")) os.makedirs(os.path.join(args.output_dir, "tensorboard")) handlers = [logging.StreamHandler()] if args.local_rank in [-1, 0]: handlers += [ logging.FileHandler(filename=os.path.join(args.output_dir, "log"), mode="a") ] logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN, handlers=handlers, ) # Setup CPU, CUDA, GPU & distributed training if args.local_rank == -1: device = torch.device("cpu") args.local_rank = -2 args.n_gpu = -1 if torch.cuda.is_available(): device = torch.device("cuda") args.local_rank = -1 args.n_gpu = torch.cuda.device_count() else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs torch.cuda.set_device(args.local_rank) device = torch.device("cuda", args.local_rank) torch.distributed.init_process_group(backend="nccl") args.n_gpu = 1 args.device = device if args.path_type == "planner_path": args.max_episode_len = 10 else: args.max_episode_len = 40 logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", args.local_rank, device, args.n_gpu, bool(args.local_rank != -1), "False", ) # Set seed set_seed(args.seed, args.n_gpu) logger.info("Training/evaluation parameters %s", args) if args.debug: feature_path = None else: feature_path = os.path.join(args.img_feat_dir, args.img_feature_file) features = read_tsv_img_features( path=feature_path, feature_size=args.lstm_img_feature_dim, ) if args.test_only: assert ( len(args.eval_iters) != 0 and args.eval_iters != -1 ), "incorrect eval_iters provided!" test_submission(args, features, args.eval_iters) if args.eval_only: assert ( len(args.eval_iters) != 0 and args.eval_iters != -1 ), "incorrect eval_iters provided!" val(args, features, args.eval_iters) else: train(args, features) sys.exit() if __name__ == "__main__": main()
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import logging import os import sys import time from collections import defaultdict import numpy as np import pandas as pd import torch import torch.distributed as dist from tensorboardX import SummaryWriter from torch.utils.data import RandomSampler, SequentialSampler from torch.utils.data.distributed import DistributedSampler from classifier.agent import Agent from classifier.data_loader import ( ClassifierDataLoader, ClassifierDataloader_collate_fn, ClassifierDataset, ) from eval import Evaluation from params import args from utils import set_seed from utils_data import load_detector_classes, read_tsv_img_features, timeSince sys.path.insert(0, "/root/mount/Matterport3DSimulator/") from model_utils import MODEL_CLASS, special_tokens_dict from transformers.pytorch_transformers import ( BertConfig, BertTokenizer, ) logger = logging.getLogger(__name__) TRAIN_VOCAB = "tasks/NDH/data/train_vocab.txt" TRAINVAL_VOCAB = "tasks/NDH/data/trainval_vocab.txt" def train(args, features): encoder_path = os.path.join(args.model_name_or_path, "encoder") decoder_path = os.path.join(args.model_name_or_path, "decoder") tokenizer_path = args.model_name_or_path tmp_root_folder = "srv/oscar_weights/base-vg-labels/ep_107_1192087" config_path = os.path.join(tmp_root_folder, "config.json") config = BertConfig.from_pretrained(config_path) config.img_feature_dim = args.img_feature_dim config.hidden_dropout_prob = args.drop_out config.classifier = "linear" config.loss_type = "CrossEntropy" config.cls_hidden_scale = 2 config.action_space = args.action_space config.detector_classes = len(load_detector_classes()) add_new_extra_embeds = not args.oscar_setting if add_new_extra_embeds: config.vocab_size = config.vocab_size + 3 config.special_vocab_size = config.vocab_size config.type_vocab_size = config.type_vocab_size + 4 config.max_position_embeddings = args.max_seq_length else: config.special_vocab_size = config.vocab_size model_class = MODEL_CLASS["PreTrainOscar"][1] model = model_class(config) bert_encoder = model.bert tokenizer = BertTokenizer.from_pretrained( tokenizer_path, do_lower_case=True, ) if add_new_extra_embeds: num_added_toks = tokenizer.add_special_tokens(special_tokens_dict) logger.info( f"Added {num_added_toks} tokens {' '.join(special_tokens_dict.values())} to Tokenizer" ) train_dataset = ClassifierDataset( args=args, splits=["train"], tokenizer=tokenizer, truncate_dialog=True, ) tensorboard_dir = os.path.join(args.output_dir, "tensorboard") if args.local_rank in [-2, -1, 0]: tb_writer = SummaryWriter(logdir=tensorboard_dir, flush_secs=30) args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) train_sampler = ( RandomSampler(train_dataset) if args.local_rank in [-2, -1] else DistributedSampler(train_dataset) ) train_data_loader = ClassifierDataLoader( dataset=train_dataset, splits=["train"], feature_store=features, tokenizer=tokenizer, batch_size=args.train_batch_size, collate_fn=ClassifierDataloader_collate_fn, sampler=train_sampler, num_workers=args.num_workers, pin_memory=True, drop_last=True, ) agent = Agent( args=args, tokenizer=tokenizer, dataloader=train_data_loader, results_path="", bert=bert_encoder, episode_len=args.max_episode_len, ) agent.load(encoder_path, decoder_path) if args.n_gpu > 1: agent.encoder = torch.nn.DataParallel(agent.encoder) agent.decoder = torch.nn.DataParallel(agent.decoder) if args.local_rank not in [-2, -1]: agent.encoder = torch.nn.parallel.DistributedDataParallel( agent.encoder, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True, ) agent.decoder = torch.nn.parallel.DistributedDataParallel( agent.decoder, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True, ) logger.info("Training an Classifier agent with %s feedback" % args.feedback_method) data_log = defaultdict(list) start = time.time() n_iters = args.num_iterations log_every = args.logging_steps for idx in range(0, n_iters, log_every): interval = min(log_every, n_iters - idx) iter_no = idx + interval if args.local_rank in [-2, -1, 0]: data_log["iteration"].append(iter_no) agent.train(interval, feedback=args.feedback_method) train_losses = np.array(agent.losses) assert len(train_losses) == interval train_loss_avg = np.average(train_losses) loss_str = "" if args.local_rank in [-2, -1, 0]: data_log["train loss"].append(train_loss_avg) loss_str += "train loss: %.4f" % train_loss_avg tb_writer.add_scalar( "classification/loss_train", train_loss_avg, global_step=iter_no ) for metric, value in agent.metrics.items(): loss_str += ", %s: %.3f" % (metric, value) tb_writer.add_scalar( f"classification/{metric}_train", value, global_step=iter_no ) if ( args.local_rank in [-2, -1, 0] and args.save_steps > 0 and idx % args.save_steps == 0 ): df = pd.DataFrame(data_log) df.set_index("iteration") df_path = os.path.join(args.output_dir, "results", f"{iter_no}-log.csv") df.to_csv(df_path) output_dir = os.path.join( args.output_dir, "checkpoints", f"checkpoint-{iter_no}" ) if not os.path.exists(output_dir): os.makedirs(output_dir) agent.save( os.path.join(output_dir, "encoder"), os.path.join(output_dir, "decoder") ) torch.save(args, os.path.join(output_dir, "training_args.bin")) tokenizer.save_pretrained(output_dir) logger.info(f"Saving model checkpoint {iter_no} to {output_dir}") logger.info( "%s (%d %d%%) %s" % ( timeSince(start, float(iter_no) / n_iters), iter_no, float(iter_no) / n_iters * 100, loss_str, ) ) def val(args, features, list_iter_no): tensorboard_dir = os.path.join(args.output_dir, "tensorboard") if args.local_rank in [-2, -1, 0]: tb_writer = SummaryWriter(logdir=tensorboard_dir, flush_secs=30) root_folder = args.model_name_or_path for iter_no in list_iter_no: encoder_path = os.path.join(root_folder, f"checkpoint-{iter_no}", "encoder") decoder_path = os.path.join(root_folder, f"checkpoint-{iter_no}", "decoder") tokenizer_path = os.path.join(root_folder, f"checkpoint-{iter_no}/") tmp_root_folder = "srv/oscar_weights/base-vg-labels/ep_107_1192087" config_path = os.path.join(tmp_root_folder, "config.json") config = BertConfig.from_pretrained(config_path) config.img_feature_dim = args.img_feature_dim config.hidden_dropout_prob = args.drop_out config.classifier = "linear" config.loss_type = "CrossEntropy" config.cls_hidden_scale = 2 config.action_space = args.action_space config.detector_classes = len(load_detector_classes()) add_new_extra_embeds = not args.oscar_setting if add_new_extra_embeds: config.vocab_size = config.vocab_size + 3 config.special_vocab_size = config.vocab_size config.type_vocab_size = config.type_vocab_size + 4 config.max_position_embeddings = args.max_seq_length else: config.special_vocab_size = config.vocab_size model_class = MODEL_CLASS["PreTrainOscar"][1] model = model_class(config) bert_encoder = model.bert tokenizer = BertTokenizer.from_pretrained( tokenizer_path, do_lower_case=True, ) if add_new_extra_embeds: num_added_toks = tokenizer.add_special_tokens(special_tokens_dict) logger.info( f"Added {num_added_toks} tokens {' '.join(special_tokens_dict.values())} to Tokenizer" ) val_seen_dataset = ClassifierDataset( args=args, splits=["val_seen"], tokenizer=tokenizer, truncate_dialog=True, ) val_unseen_dataset = ClassifierDataset( args=args, splits=["val_unseen"], tokenizer=tokenizer, truncate_dialog=True, ) val_datasets = { "val_seen": val_seen_dataset, "val_unseen": val_unseen_dataset, } val_data_loaders = {} args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) for split, val_dataset in val_datasets.items(): val_sampler = SequentialSampler(val_dataset) val_data_loader = ClassifierDataLoader( dataset=val_dataset, splits=["val_seen"], feature_store=features, tokenizer=tokenizer, batch_size=args.eval_batch_size, collate_fn=ClassifierDataloader_collate_fn, sampler=val_sampler, num_workers=args.num_workers, pin_memory=True, drop_last=True, ) evaluation = Evaluation([split], path_type=args.path_type) val_data_loaders[split] = (val_data_loader, evaluation) agent = Agent( args=args, tokenizer=tokenizer, dataloader=val_data_loader, results_path="", bert=bert_encoder, episode_len=args.max_episode_len, ) agent.load(encoder_path, decoder_path) if args.n_gpu > 1: agent.encoder = torch.nn.DataParallel(agent.encoder) agent.decoder = torch.nn.DataParallel(agent.decoder) if args.local_rank not in [-2, -1]: agent.encoder = torch.nn.parallel.DistributedDataParallel( agent.encoder, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True, ) agent.decoder = torch.nn.parallel.DistributedDataParallel( agent.decoder, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True, ) logger.info( "Validating the Classifier agent with %s feedback for iteration %d" % (args.feedback_method, iter_no) ) data_log = defaultdict(list) data_log["iteration"].append(iter_no) for env_name, (dataloader, evaluator) in val_data_loaders.items(): start = time.time() agent.dataloader = dataloader agent.data_iter = iter(agent.dataloader) agent.results_path = os.path.join( args.output_dir, "predictions", f"{env_name}-{iter_no}.json" ) agent.test() val_losses = np.array(agent.losses) val_loss_avg = np.average(val_losses) tb_writer.add_scalar( f"classification/loss_{env_name}", val_loss_avg, global_step=iter_no ) data_log["%s loss" % env_name].append(val_loss_avg) loss_str = ", %s loss: %.4f" % (env_name, val_loss_avg) for metric, val in agent.metrics.items(): data_log["%s %s" % (env_name, metric)].append(val) loss_str += ", %s: %.3f" % (metric, val) tb_writer.add_scalar( f"classification/{metric}_{env_name}", val, global_step=iter_no ) end = time.time() logger.info( "Time: %0.2f min Eval Iter: %d %s" % ( (end - start) / 60, iter_no, loss_str, ) ) df = pd.DataFrame(data_log) df.set_index("iteration") df_path = os.path.join(args.output_dir, "results", f"{iter_no}-log.csv") df.to_csv(df_path) sys.exit() def test_submission(args, features, list_iter_no): root_folder = args.model_name_or_path for iter_no in list_iter_no: encoder_path = os.path.join(root_folder, f"checkpoint-{iter_no}", "encoder") decoder_path = os.path.join(root_folder, f"checkpoint-{iter_no}", "decoder") tokenizer_path = os.path.join(root_folder, f"checkpoint-{iter_no}/") tmp_root_folder = "srv/oscar_weights/base-vg-labels/ep_107_1192087" config_path = os.path.join(tmp_root_folder, "config.json") config = BertConfig.from_pretrained(config_path) config.img_feature_dim = args.img_feature_dim config.hidden_dropout_prob = args.drop_out config.classifier = "linear" config.loss_type = "CrossEntropy" config.cls_hidden_scale = 2 config.action_space = args.action_space add_new_extra_embeds = not args.oscar_setting if add_new_extra_embeds: config.vocab_size = config.vocab_size + 3 config.special_vocab_size = config.vocab_size config.type_vocab_size = config.type_vocab_size + 4 config.max_position_embeddings = args.max_seq_length else: config.special_vocab_size = config.vocab_size model_class = MODEL_CLASS["PreTrainOscar"][1] model = model_class(config) bert_encoder = model.bert tokenizer = BertTokenizer.from_pretrained( tokenizer_path, do_lower_case=True, ) if add_new_extra_embeds: num_added_toks = tokenizer.add_special_tokens(special_tokens_dict) logger.info( f"Added {num_added_toks} tokens {' '.join(special_tokens_dict.values())} to Tokenizer" ) test_dataset = VLNDataset( args=args, splits=["test"], tokenizer=tokenizer, truncate_dialog=True, path_type=args.path_type, ) args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) test_sampler = SequentialSampler(test_dataset) test_data_loader = VLNDataLoader( dataset=test_dataset, splits=["test"], feature_store=features, tokenizer=tokenizer, batch_size=args.eval_batch_size, collate_fn=VLNDataloader_collate_fn, sampler=test_sampler, num_workers=args.num_workers, pin_memory=True, drop_last=False, ) agent = Agent( args=args, tokenizer=tokenizer, dataloader=test_data_loader, results_path="", bert=bert_encoder, episode_len=args.max_episode_len, ) agent.load(encoder_path, decoder_path) if args.n_gpu > 1: agent.encoder = torch.nn.DataParallel(agent.encoder) agent.decoder = torch.nn.DataParallel(agent.decoder) if args.local_rank not in [-2, -1]: agent.encoder = torch.nn.parallel.DistributedDataParallel( agent.encoder, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True, ) agent.decoder = torch.nn.parallel.DistributedDataParallel( agent.decoder, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True, ) logger.info( "Generating test split predictions for the LSTM agent iteration %d" % (iter_no) ) data_log = defaultdict(list) data_log["iteration"].append(iter_no) start = time.time() agent.dataloader = test_data_loader agent.data_iter = iter(agent.dataloader) agent.results_path = os.path.join( args.output_dir, "predictions", f"test-{iter_no}.json" ) agent.test(use_dropout=False, feedback="argmax") agent.write_results() logger.info(f"Saving results to {agent.results_path}") end = time.time() logger.info( "Time: %0.2f min Eval Iter: %d" % ( (end - start) / 60, iter_no, ) ) sys.exit() def main(): if ( args.local_rank in [-1, 0] and os.path.exists(args.output_dir) and os.listdir(args.output_dir) and not args.eval_only and not args.test_only and not args.debug ): raise IOError( "%s \nOutput Directory not empty and train setting is on. Exiting to prevent overwriting..." % (args.output_dir) ) if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]: os.makedirs(args.output_dir) os.makedirs(os.path.join(args.output_dir, "checkpoints")) os.makedirs(os.path.join(args.output_dir, "predictions")) os.makedirs(os.path.join(args.output_dir, "results")) os.makedirs(os.path.join(args.output_dir, "tensorboard")) handlers = [logging.StreamHandler()] if args.local_rank in [-1, 0]: handlers += [ logging.FileHandler(filename=os.path.join(args.output_dir, "log"), mode="a") ] logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN, handlers=handlers, ) # Setup CPU, CUDA, GPU & distributed training if args.local_rank == -1: device = torch.device("cpu") args.local_rank = -2 args.n_gpu = -1 if torch.cuda.is_available(): device = torch.device("cuda") args.local_rank = -1 args.n_gpu = torch.cuda.device_count() else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs torch.cuda.set_device(args.local_rank) device = torch.device("cuda", args.local_rank) torch.distributed.init_process_group(backend="nccl") args.n_gpu = 1 args.device = device if args.path_type == "planner_path": args.max_episode_len = 10 else: args.max_episode_len = 40 logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", args.local_rank, device, args.n_gpu, bool(args.local_rank != -1), "False", ) # Set seed set_seed(args.seed, args.n_gpu) logger.info("Training/evaluation parameters %s", args) if args.debug: feature_path = None else: feature_path = os.path.join(args.img_feat_dir, args.img_feature_file) features = read_tsv_img_features( path=feature_path, feature_size=args.lstm_img_feature_dim, ) if args.test_only: assert ( len(args.eval_iters) != 0 and args.eval_iters != -1 ), "incorrect eval_iters provided!" test_submission(args, features, args.eval_iters) if args.eval_only: assert ( len(args.eval_iters) != 0 and args.eval_iters != -1 ), "incorrect eval_iters provided!" val(args, features, args.eval_iters) else: train(args, features) sys.exit() if __name__ == "__main__": main()
import boto3 import os import traceback from string import ascii_lowercase from random import choice import json import logging import shutil import time from pathlib import Path LOG = logging.getLogger(__name__) def proxy_needed(cluster_name: str, boto3_session: boto3.Session) -> (boto3.client, str): # If there's no vpc zip then we're already in the inner lambda. if not Path('./awsqs_kubernetes_get/vpc.zip').resolve().exists(): return False eks = boto3_session.client('eks') eks_vpc_config = eks.describe_cluster(name=cluster_name)['cluster']['resourcesVpcConfig'] # for now we will always use vpc proxy, until we can work out how to wrap boto3 session in CFN registry when authing # if eks_vpc_config['endpointPublicAccess'] and '0.0.0.0/0' in eks_vpc_config['publicAccessCidrs']: # return False if this_invoke_is_inside_vpc(set(eks_vpc_config['subnetIds']), set(eks_vpc_config['securityGroupIds'])): return False return True def this_invoke_is_inside_vpc(subnet_ids: set, sg_ids: set) -> bool: lmbd = boto3.client('lambda') try: lambda_config = lmbd.get_function_configuration(FunctionName=os.environ['AWS_LAMBDA_FUNCTION_NAME']) l_vpc_id = lambda_config['VpcConfig'].get('VpcId', '') l_subnet_ids = set(lambda_config['VpcConfig'].get('subnetIds', '')) l_sg_ids = set(lambda_config['VpcConfig'].get('securityGroupIds', '')) if l_vpc_id and l_subnet_ids.issubset(subnet_ids) and l_sg_ids.issubset(sg_ids): return True except Exception as e: print(f'failed to get function config for {os.environ['AWS_LAMBDA_FUNCTION_NAME']}') traceback.print_exc() return False def proxy_call(event, sess): return invoke_function(f'awsqs-kubernetes-resource-get-proxy-{event['ClusterName']}', event, sess) def random_string(length=8): return ''.join(choice(ascii_lowercase) for _ in range(length)) def put_function(sess, event): eks = sess.client('eks') eks_vpc_config = eks.describe_cluster(name=event['ClusterName'])['cluster']['resourcesVpcConfig'] ec2 = sess.client('ec2') internal_subnets = [ s['SubnetId'] for s in ec2.describe_subnets(SubnetIds=eks_vpc_config['subnetIds'], Filters=[ {'Name': "tag-key", "Values": ['kubernetes.io/role/internal-elb']} ])['Subnets'] ] sts = sess.client('sts') role_arn = '/'.join(sts.get_caller_identity()['Arn'].replace(':sts:', ':iam:').replace(':assumed-role/', ':role/') .split('/')[:-1]) lmbd = sess.client('lambda') try: with open('./awsqs_kubernetes_get/vpc.zip', 'rb') as zip_file: lmbd.create_function( FunctionName=f'awsqs-kubernetes-resource-get-proxy-{event['ClusterName']}', Runtime='python3.7', Role=role_arn, Handler="awsqs_kubernetes_get.handlers.proxy_wrap", Code={'ZipFile': zip_file.read()}, Timeout=900, MemorySize=512, VpcConfig={ 'SubnetIds': internal_subnets, 'SecurityGroupIds': eks_vpc_config['securityGroupIds'] } ) except lmbd.exceptions.ResourceConflictException as e: if "Function already exist" not in str(e): raise LOG.warning("function already exists...") while True: try: with open('./awsqs_kubernetes_get/vpc.zip', 'rb') as zip_file: lmbd.update_function_code( FunctionName=f'awsqs-kubernetes-resource-get-proxy-{event['ClusterName']}', ZipFile=zip_file.read() ) break except lmbd.exceptions.ResourceConflictException as e: if "The operation cannot be performed at this time." not in str(e): raise LOG.error(str(e)) time.sleep(10) while True: try: lmbd.update_function_configuration( FunctionName=f'awsqs-kubernetes-resource-get-proxy-{event['ClusterName']}', Runtime='python3.7', Role=role_arn, Handler="awsqs_kubernetes_get.handlers.proxy_wrap", Timeout=900, MemorySize=512, VpcConfig={ 'SubnetIds': internal_subnets, 'SecurityGroupIds': eks_vpc_config['securityGroupIds'] } ) break except lmbd.exceptions.ResourceConflictException as e: if "The operation cannot be performed at this time." not in str(e) and 'The function could not be updated due to a concurrent update operation.' not in str(e): raise LOG.error(str(e)) time.sleep(10) def invoke_function(func_arn, event, sess): lmbd = sess.client('lambda') while True: try: response = lmbd.invoke( FunctionName=func_arn, InvocationType='RequestResponse', Payload=json.dumps(event).encode('utf-8') ) return json.loads(response['Payload'].read().decode('utf-8')) except lmbd.exceptions.ResourceConflictException as e: if "The operation cannot be performed at this time." not in str(e): raise LOG.error(str(e)) time.sleep(10)
import boto3 import os import traceback from string import ascii_lowercase from random import choice import json import logging import shutil import time from pathlib import Path LOG = logging.getLogger(__name__) def proxy_needed(cluster_name: str, boto3_session: boto3.Session) -> (boto3.client, str): # If there's no vpc zip then we're already in the inner lambda. if not Path('./awsqs_kubernetes_get/vpc.zip').resolve().exists(): return False eks = boto3_session.client('eks') eks_vpc_config = eks.describe_cluster(name=cluster_name)['cluster']['resourcesVpcConfig'] # for now we will always use vpc proxy, until we can work out how to wrap boto3 session in CFN registry when authing # if eks_vpc_config['endpointPublicAccess'] and '0.0.0.0/0' in eks_vpc_config['publicAccessCidrs']: # return False if this_invoke_is_inside_vpc(set(eks_vpc_config['subnetIds']), set(eks_vpc_config['securityGroupIds'])): return False return True def this_invoke_is_inside_vpc(subnet_ids: set, sg_ids: set) -> bool: lmbd = boto3.client('lambda') try: lambda_config = lmbd.get_function_configuration(FunctionName=os.environ['AWS_LAMBDA_FUNCTION_NAME']) l_vpc_id = lambda_config['VpcConfig'].get('VpcId', '') l_subnet_ids = set(lambda_config['VpcConfig'].get('subnetIds', '')) l_sg_ids = set(lambda_config['VpcConfig'].get('securityGroupIds', '')) if l_vpc_id and l_subnet_ids.issubset(subnet_ids) and l_sg_ids.issubset(sg_ids): return True except Exception as e: print(f'failed to get function config for {os.environ["AWS_LAMBDA_FUNCTION_NAME"]}') traceback.print_exc() return False def proxy_call(event, sess): return invoke_function(f'awsqs-kubernetes-resource-get-proxy-{event["ClusterName"]}', event, sess) def random_string(length=8): return ''.join(choice(ascii_lowercase) for _ in range(length)) def put_function(sess, event): eks = sess.client('eks') eks_vpc_config = eks.describe_cluster(name=event['ClusterName'])['cluster']['resourcesVpcConfig'] ec2 = sess.client('ec2') internal_subnets = [ s['SubnetId'] for s in ec2.describe_subnets(SubnetIds=eks_vpc_config['subnetIds'], Filters=[ {'Name': "tag-key", "Values": ['kubernetes.io/role/internal-elb']} ])['Subnets'] ] sts = sess.client('sts') role_arn = '/'.join(sts.get_caller_identity()['Arn'].replace(':sts:', ':iam:').replace(':assumed-role/', ':role/') .split('/')[:-1]) lmbd = sess.client('lambda') try: with open('./awsqs_kubernetes_get/vpc.zip', 'rb') as zip_file: lmbd.create_function( FunctionName=f'awsqs-kubernetes-resource-get-proxy-{event["ClusterName"]}', Runtime='python3.7', Role=role_arn, Handler="awsqs_kubernetes_get.handlers.proxy_wrap", Code={'ZipFile': zip_file.read()}, Timeout=900, MemorySize=512, VpcConfig={ 'SubnetIds': internal_subnets, 'SecurityGroupIds': eks_vpc_config['securityGroupIds'] } ) except lmbd.exceptions.ResourceConflictException as e: if "Function already exist" not in str(e): raise LOG.warning("function already exists...") while True: try: with open('./awsqs_kubernetes_get/vpc.zip', 'rb') as zip_file: lmbd.update_function_code( FunctionName=f'awsqs-kubernetes-resource-get-proxy-{event["ClusterName"]}', ZipFile=zip_file.read() ) break except lmbd.exceptions.ResourceConflictException as e: if "The operation cannot be performed at this time." not in str(e): raise LOG.error(str(e)) time.sleep(10) while True: try: lmbd.update_function_configuration( FunctionName=f'awsqs-kubernetes-resource-get-proxy-{event["ClusterName"]}', Runtime='python3.7', Role=role_arn, Handler="awsqs_kubernetes_get.handlers.proxy_wrap", Timeout=900, MemorySize=512, VpcConfig={ 'SubnetIds': internal_subnets, 'SecurityGroupIds': eks_vpc_config['securityGroupIds'] } ) break except lmbd.exceptions.ResourceConflictException as e: if "The operation cannot be performed at this time." not in str(e) and 'The function could not be updated due to a concurrent update operation.' not in str(e): raise LOG.error(str(e)) time.sleep(10) def invoke_function(func_arn, event, sess): lmbd = sess.client('lambda') while True: try: response = lmbd.invoke( FunctionName=func_arn, InvocationType='RequestResponse', Payload=json.dumps(event).encode('utf-8') ) return json.loads(response['Payload'].read().decode('utf-8')) except lmbd.exceptions.ResourceConflictException as e: if "The operation cannot be performed at this time." not in str(e): raise LOG.error(str(e)) time.sleep(10)
import http.client import github3.exceptions from github3 import GitHubError from cumulusci.core.exceptions import GithubApiNotFoundError from cumulusci.core.utils import process_bool_arg from cumulusci.tasks.github.base import BaseGithubTask from cumulusci.utils.git import is_release_branch class MergeBranch(BaseGithubTask): task_docs = """ Merges the most recent commit on the current branch into other branches depending on the value of source_branch. If source_branch is a branch that does not start with the specified branch_prefix, then the commit will be merged to all branches that begin with branch_prefix and are not themselves child branches (i.e. branches don't contain '__' in their name). If source_branch begins with branch_prefix, then the commit is merged to all child branches of source_branch. """ task_options = { "commit": { "description": "The commit to merge into feature branches. Defaults to the current head commit." }, "source_branch": { "description": "The source branch to merge from. Defaults to project__git__default_branch." }, "branch_prefix": { "description": "A list of prefixes of branches that should receive the merge. Defaults to project__git__prefix_feature" }, "skip_future_releases": { "description": "If true, then exclude branches that start with the branch prefix if they are not for the lowest release number. Defaults to True." }, "update_future_releases": { "description": "If true, then include release branches that are not the lowest release number even if they are not child branches. Defaults to False." }, } def _init_options(self, kwargs): super()._init_options(kwargs) if "commit" not in self.options: self.options["commit"] = self.project_config.repo_commit if "branch_prefix" not in self.options: self.options[ "branch_prefix" ] = self.project_config.project__git__prefix_feature if "source_branch" not in self.options: self.options[ "source_branch" ] = self.project_config.project__git__default_branch self.options["skip_future_releases"] = process_bool_arg( self.options.get("skip_future_releases") or True ) self.options["update_future_releases"] = process_bool_arg( self.options.get("update_future_releases") or False ) def _init_task(self): super()._init_task() self.repo = self.get_repo() def _run_task(self): self._validate_source_branch(self.options["source_branch"]) branches_to_merge = self._get_branches_to_merge() for branch in branches_to_merge: self._merge( branch.name, self.options["source_branch"], self.options["commit"], ) def _validate_source_branch(self, source_branch): """Validates that the source branch exists in the repository""" try: self.repo.branch(source_branch) except github3.exceptions.NotFoundError: message = f"Branch {source_branch} not found" raise GithubApiNotFoundError(message) def _get_existing_prs(self, source_branch, branch_prefix): """Returns the existing pull requests from the source branch to other branches that are candidates for merging.""" existing_prs = [] for pr in self.repo.pull_requests(state="open"): if pr.base.ref.startswith(branch_prefix) and pr.head.ref == source_branch: existing_prs.append(pr.base.ref) return existing_prs def _get_branches_to_merge(self): """ If source_branch is the default branch (or a branch that doesn't start with a prefix), we gather all branches with branch_prefix that are not child branches. NOTE: We only include the _next_ closest release branch when automerging from main. A change on main may conflict with the current contents of the lowest release branch. In this case, we would like for that conflict to only need to be resolved once (not once for each release branch). If source_branch starts with branch prefix, we gather all branches with branch_prefix that are direct descendents of source_branch. If update_future_releases is True, and source_branch is a release branch then we also collect all future release branches. """ repo_branches = list(self.repo.branches()) next_release = self._get_next_release(repo_branches) skip_future_releases = self.options["skip_future_releases"] update_future_releases = self._update_future_releases(next_release) child_branches = [] main_descendents = [] release_branches = [] for branch in repo_branches: # check for adding future release branches if update_future_releases and self._is_future_release_branch( branch.name, next_release ): release_branches.append(branch) continue # check if we looking at the source_branch if branch.name == self.options["source_branch"]: self.logger.debug(f"Skipping branch {branch.name}: is source branch") continue # check for branch prefix match elif not branch.name.startswith(self.options["branch_prefix"]): self.logger.debug( f"Skipping branch {branch.name}: does not match prefix "{self.options["branch_prefix"]}'" ) continue # check if source_branch doesn't have prefix and is not a child (e.g. main) elif ( not self.options["source_branch"].startswith( self.options["branch_prefix"] ) and "__" not in branch.name ): # only merge to the lowest numbered release branch # when merging from a branch without a prefix (e.g. main) if skip_future_releases and self._is_future_release_branch( branch.name, next_release ): continue main_descendents.append(branch) # else, we have a branch that starts with branch_prefix # check is this branch is a direct descendent elif self._is_source_branch_direct_descendent(branch.name): child_branches.append(branch) # else not a direct descendent else: self.logger.debug( f"Skipping branch {branch.name}: is not a direct descendent of {self.options["source_branch"]}" ) to_merge = [] if child_branches: self.logger.debug( f"Found child branches to update: {[branch.name for branch in child_branches]}" ) to_merge = child_branches elif self.options["source_branch"].startswith(self.options["branch_prefix"]): self.logger.debug( f"No children found for branch {self.options["source_branch"]}" ) if release_branches: self.logger.debug( f"Found future release branches to update: {[branch.name for branch in release_branches]}" ) to_merge = to_merge + release_branches if main_descendents: self.logger.debug( f"Found descendents of {self.options["source_branch"]} to update: {[branch.name for branch in main_descendents]}" ) to_merge = to_merge + main_descendents return to_merge def _get_next_release(self, repo_branches): """Returns the integer that corresponds to the lowest release number found on all release branches. NOTE: We assume that once a release branch is merged that it will be deleted. """ release_nums = [ self._get_release_number(branch.name) for branch in repo_branches if self._is_release_branch(branch.name) ] next_release = sorted(release_nums)[0] if release_nums else None return next_release def _update_future_releases(self, next_release): """Determines whether or not to update future releases. Returns True if all of the below checks are True. False otherwise. Checks: (1) Did we receive the 'update_future_release' flag? (2) Is the source_branch a release branch? (3) Is it the lowest numbered release branch that exists? NOTE: This functionality assumes that the lowest numbered release branch in the repo is the next closest release. Put another way, once a release branch is merged we assume that it is immediately deleted. """ update_future_releases = False if ( self.options["update_future_releases"] and self._is_release_branch(self.options["source_branch"]) and next_release == self._get_release_number(self.options["source_branch"]) ): update_future_releases = True return update_future_releases def _is_release_branch(self, branch_name): """A release branch begins with the given prefix""" return is_release_branch(branch_name, self.options["branch_prefix"]) def _get_release_number(self, branch_name) -> int: """Get the release number from a release branch name. Assumes we already know it is a release branch. """ return int(branch_name.split(self.options["branch_prefix"])[1]) def _merge(self, branch_name, source, commit): """Attempt to merge a commit from source to branch with branch_name""" compare = self.repo.compare_commits(branch_name, commit) if not compare or not compare.files: self.logger.info(f"Skipping branch {branch_name}: no file diffs found") return try: self.repo.merge(branch_name, commit) self.logger.info( f"Merged {compare.behind_by} commits into branch: {branch_name}" ) except GitHubError as e: if e.code != http.client.CONFLICT: raise if branch_name in self._get_existing_prs( self.options["source_branch"], self.options["branch_prefix"] ): self.logger.info( f"Merge conflict on branch {branch_name}: merge PR already exists" ) return try: pull = self.repo.create_pull( title=f"Merge {source} into {branch_name}", base=branch_name, head=source, body="This pull request was automatically generated because " "an automated merge hit a merge conflict", ) self.logger.info( f"Merge conflict on branch {branch_name}: created pull request #{pull.number}" ) except github3.exceptions.UnprocessableEntity as e: self.logger.error( f"Error creating merge conflict pull request to merge {source} into {branch_name}:\n{e.response.text}" ) def _is_source_branch_direct_descendent(self, branch_name): """Returns True if branch is a direct descendent of the source branch""" source_dunder_count = self.options["source_branch"].count("__") return ( branch_name.startswith(f"{self.options["source_branch"]}__") and branch_name.count("__") == source_dunder_count + 1 ) def _is_future_release_branch(self, branch_name, next_release): return ( self._is_release_branch(branch_name) and branch_name != self.options["source_branch"] and self._get_release_num(branch_name) > next_release ) def _get_release_num(self, release_branch_name): """Given a release branch, returns an integer that corresponds to the release number for that branch""" return int(release_branch_name.split(self.options["branch_prefix"])[1])
import http.client import github3.exceptions from github3 import GitHubError from cumulusci.core.exceptions import GithubApiNotFoundError from cumulusci.core.utils import process_bool_arg from cumulusci.tasks.github.base import BaseGithubTask from cumulusci.utils.git import is_release_branch class MergeBranch(BaseGithubTask): task_docs = """ Merges the most recent commit on the current branch into other branches depending on the value of source_branch. If source_branch is a branch that does not start with the specified branch_prefix, then the commit will be merged to all branches that begin with branch_prefix and are not themselves child branches (i.e. branches don't contain '__' in their name). If source_branch begins with branch_prefix, then the commit is merged to all child branches of source_branch. """ task_options = { "commit": { "description": "The commit to merge into feature branches. Defaults to the current head commit." }, "source_branch": { "description": "The source branch to merge from. Defaults to project__git__default_branch." }, "branch_prefix": { "description": "A list of prefixes of branches that should receive the merge. Defaults to project__git__prefix_feature" }, "skip_future_releases": { "description": "If true, then exclude branches that start with the branch prefix if they are not for the lowest release number. Defaults to True." }, "update_future_releases": { "description": "If true, then include release branches that are not the lowest release number even if they are not child branches. Defaults to False." }, } def _init_options(self, kwargs): super()._init_options(kwargs) if "commit" not in self.options: self.options["commit"] = self.project_config.repo_commit if "branch_prefix" not in self.options: self.options[ "branch_prefix" ] = self.project_config.project__git__prefix_feature if "source_branch" not in self.options: self.options[ "source_branch" ] = self.project_config.project__git__default_branch self.options["skip_future_releases"] = process_bool_arg( self.options.get("skip_future_releases") or True ) self.options["update_future_releases"] = process_bool_arg( self.options.get("update_future_releases") or False ) def _init_task(self): super()._init_task() self.repo = self.get_repo() def _run_task(self): self._validate_source_branch(self.options["source_branch"]) branches_to_merge = self._get_branches_to_merge() for branch in branches_to_merge: self._merge( branch.name, self.options["source_branch"], self.options["commit"], ) def _validate_source_branch(self, source_branch): """Validates that the source branch exists in the repository""" try: self.repo.branch(source_branch) except github3.exceptions.NotFoundError: message = f"Branch {source_branch} not found" raise GithubApiNotFoundError(message) def _get_existing_prs(self, source_branch, branch_prefix): """Returns the existing pull requests from the source branch to other branches that are candidates for merging.""" existing_prs = [] for pr in self.repo.pull_requests(state="open"): if pr.base.ref.startswith(branch_prefix) and pr.head.ref == source_branch: existing_prs.append(pr.base.ref) return existing_prs def _get_branches_to_merge(self): """ If source_branch is the default branch (or a branch that doesn't start with a prefix), we gather all branches with branch_prefix that are not child branches. NOTE: We only include the _next_ closest release branch when automerging from main. A change on main may conflict with the current contents of the lowest release branch. In this case, we would like for that conflict to only need to be resolved once (not once for each release branch). If source_branch starts with branch prefix, we gather all branches with branch_prefix that are direct descendents of source_branch. If update_future_releases is True, and source_branch is a release branch then we also collect all future release branches. """ repo_branches = list(self.repo.branches()) next_release = self._get_next_release(repo_branches) skip_future_releases = self.options["skip_future_releases"] update_future_releases = self._update_future_releases(next_release) child_branches = [] main_descendents = [] release_branches = [] for branch in repo_branches: # check for adding future release branches if update_future_releases and self._is_future_release_branch( branch.name, next_release ): release_branches.append(branch) continue # check if we looking at the source_branch if branch.name == self.options["source_branch"]: self.logger.debug(f"Skipping branch {branch.name}: is source branch") continue # check for branch prefix match elif not branch.name.startswith(self.options["branch_prefix"]): self.logger.debug( f"Skipping branch {branch.name}: does not match prefix '{self.options['branch_prefix']}'" ) continue # check if source_branch doesn't have prefix and is not a child (e.g. main) elif ( not self.options["source_branch"].startswith( self.options["branch_prefix"] ) and "__" not in branch.name ): # only merge to the lowest numbered release branch # when merging from a branch without a prefix (e.g. main) if skip_future_releases and self._is_future_release_branch( branch.name, next_release ): continue main_descendents.append(branch) # else, we have a branch that starts with branch_prefix # check is this branch is a direct descendent elif self._is_source_branch_direct_descendent(branch.name): child_branches.append(branch) # else not a direct descendent else: self.logger.debug( f"Skipping branch {branch.name}: is not a direct descendent of {self.options['source_branch']}" ) to_merge = [] if child_branches: self.logger.debug( f"Found child branches to update: {[branch.name for branch in child_branches]}" ) to_merge = child_branches elif self.options["source_branch"].startswith(self.options["branch_prefix"]): self.logger.debug( f"No children found for branch {self.options['source_branch']}" ) if release_branches: self.logger.debug( f"Found future release branches to update: {[branch.name for branch in release_branches]}" ) to_merge = to_merge + release_branches if main_descendents: self.logger.debug( f"Found descendents of {self.options['source_branch']} to update: {[branch.name for branch in main_descendents]}" ) to_merge = to_merge + main_descendents return to_merge def _get_next_release(self, repo_branches): """Returns the integer that corresponds to the lowest release number found on all release branches. NOTE: We assume that once a release branch is merged that it will be deleted. """ release_nums = [ self._get_release_number(branch.name) for branch in repo_branches if self._is_release_branch(branch.name) ] next_release = sorted(release_nums)[0] if release_nums else None return next_release def _update_future_releases(self, next_release): """Determines whether or not to update future releases. Returns True if all of the below checks are True. False otherwise. Checks: (1) Did we receive the 'update_future_release' flag? (2) Is the source_branch a release branch? (3) Is it the lowest numbered release branch that exists? NOTE: This functionality assumes that the lowest numbered release branch in the repo is the next closest release. Put another way, once a release branch is merged we assume that it is immediately deleted. """ update_future_releases = False if ( self.options["update_future_releases"] and self._is_release_branch(self.options["source_branch"]) and next_release == self._get_release_number(self.options["source_branch"]) ): update_future_releases = True return update_future_releases def _is_release_branch(self, branch_name): """A release branch begins with the given prefix""" return is_release_branch(branch_name, self.options["branch_prefix"]) def _get_release_number(self, branch_name) -> int: """Get the release number from a release branch name. Assumes we already know it is a release branch. """ return int(branch_name.split(self.options["branch_prefix"])[1]) def _merge(self, branch_name, source, commit): """Attempt to merge a commit from source to branch with branch_name""" compare = self.repo.compare_commits(branch_name, commit) if not compare or not compare.files: self.logger.info(f"Skipping branch {branch_name}: no file diffs found") return try: self.repo.merge(branch_name, commit) self.logger.info( f"Merged {compare.behind_by} commits into branch: {branch_name}" ) except GitHubError as e: if e.code != http.client.CONFLICT: raise if branch_name in self._get_existing_prs( self.options["source_branch"], self.options["branch_prefix"] ): self.logger.info( f"Merge conflict on branch {branch_name}: merge PR already exists" ) return try: pull = self.repo.create_pull( title=f"Merge {source} into {branch_name}", base=branch_name, head=source, body="This pull request was automatically generated because " "an automated merge hit a merge conflict", ) self.logger.info( f"Merge conflict on branch {branch_name}: created pull request #{pull.number}" ) except github3.exceptions.UnprocessableEntity as e: self.logger.error( f"Error creating merge conflict pull request to merge {source} into {branch_name}:\n{e.response.text}" ) def _is_source_branch_direct_descendent(self, branch_name): """Returns True if branch is a direct descendent of the source branch""" source_dunder_count = self.options["source_branch"].count("__") return ( branch_name.startswith(f"{self.options['source_branch']}__") and branch_name.count("__") == source_dunder_count + 1 ) def _is_future_release_branch(self, branch_name, next_release): return ( self._is_release_branch(branch_name) and branch_name != self.options["source_branch"] and self._get_release_num(branch_name) > next_release ) def _get_release_num(self, release_branch_name): """Given a release branch, returns an integer that corresponds to the release number for that branch""" return int(release_branch_name.split(self.options["branch_prefix"])[1])
from blpapi_import_helper import blpapi from argparse import Action _SESSION_IDENTITY_AUTH_OPTIONS = "sessionIdentityAuthOptions" class AuthOptionsAction(Action): """The action that parses authorization options from user input""" def __call__(self, parser, args, values, option_string=None): vals = values.split('=', 1) auth_type = vals[0] if auth_type == "user": authUser = blpapi.AuthUser.createWithLogonName() authOptions = blpapi.AuthOptions.createWithUser(authUser) elif auth_type == "none": authOptions = None else: if len(vals) != 2: parser.error(f"Invalid auth option '{values}'") if auth_type == "app": appName = vals[1] authOptions = blpapi.AuthOptions.createWithApp(appName) elif auth_type == "userapp": appName = vals[1] authUser = blpapi.AuthUser.createWithLogonName() authOptions = blpapi.AuthOptions.createWithUserAndApp( authUser, appName) elif auth_type == "dir": dirProperty = vals[1] authUser = blpapi.AuthUser.createWithActiveDirectoryProperty( dirProperty) authOptions = blpapi.AuthOptions.createWithUser(authUser) elif auth_type == "manual": parts = vals[1].split(',') if len(parts) != 3: parser.error(f"Invalid auth option '{values}'") appName, ip, userId = parts authUser = blpapi.AuthUser.createWithManualOptions(userId, ip) authOptions = blpapi.AuthOptions.createWithUserAndApp( authUser, appName) else: parser.error(f"Invalid auth option '{values}'") setattr(args, self.dest, authOptions) class AppAuthAction(Action): """The action that parses app authorization options from user input""" def __call__(self, parser, args, values, option_string=None): vals = values.split('=', 1) if len(vals) != 2: parser.error(f"Invalid auth option '{values}'") authType, appName = vals if authType != "app": parser.error(f"Invalid auth option '{values}'") setattr(args, self.dest, appName) authOptions = blpapi.AuthOptions.createWithApp(appName) setattr(args, _SESSION_IDENTITY_AUTH_OPTIONS, authOptions) class HostAction(Action): """The action that parses host options from user input""" def __call__(self, parser, args, values, option_string=None): vals = values.split(':', 1) if len(vals) != 2: parser.error(f"Invalid host option '{values}'") hosts = getattr(args, self.dest) hosts.append((vals[0], int(vals[1]))) class UserIdIpAction(Action): """The action that parses userId and IP authorization options from user input """ def __call__(self, parser, args, values, option_string=None): vals = values.split(":") if len(vals) != 2: parser.error(f"Invalid auth option '{values}'") userId, ip = vals getattr(args, self.dest).append((userId, ip)) def addConnectionAndAuthOptions(parser, forClientServerSetup=False): """ Helper function that adds the options for connection and authorization to the argument parser. """ # Server options server_group = parser.add_argument_group("Connections") server_group.add_argument("-H", "--host", dest="hosts", help="server name or IP (default: 127.0.0.1:8194). Can be specified multiple times.", metavar="host:port", action=HostAction, default=[]) # Auth options if forClientServerSetup: _addArgGroupsAuthAndEntitlementsClientServerSetup(parser) else: _addArgGroupAuth(parser) # TLS Options tls_group = parser.add_argument_group("TLS (specify all or none)") tls_group.add_argument("--tls-client-credentials", dest="tls_client_credentials", help="name a PKCS#12 file to use as a source of " "client credentials", metavar="file") tls_group.add_argument("--tls-client-credentials-password", dest="tls_client_credentials_password", help="specify password for accessing client credentials", metavar="password", default="") tls_group.add_argument("--tls-trust-material", dest="tls_trust_material", help="name a PKCS#7 file to use as a source of " "trusted certificates", metavar="file") tls_group.add_argument("--read-certificate-files", dest="read_certificate_files", help="Enable reading the TLS files and pass the blobs", action="store_true") # ZFP Options zfp_group = parser.add_argument_group( "ZFP connections over leased lines (requires TLS)") zfp_group.add_argument("-z", "--zfp-over-leased-line", dest="remote", help="enable ZFP connections over leased lines on the " "specified port (8194 or 8196)" "\n(When this option is enabled, option -H/--host is ignored.)", metavar="port", type=int) def _addArgGroupAuth(parser): auth_group = parser.add_argument_group("Authorization") auth_group.add_argument("-a", "--auth", dest=_SESSION_IDENTITY_AUTH_OPTIONS, help='''authorization option (default: none) none applicable to Desktop API product that requires Bloomberg Professional service to be installed locally user as a user using OS logon information dir=<property> as a user using directory services app=<app> as the specified application userapp=<app> as user and application using logon information for the user manual=<app,ip,user> as user and application, with manually provided IP address and EMRS user''', metavar="option", action=AuthOptionsAction) def _addArgGroupsAuthAndEntitlementsClientServerSetup(parser): """Adds the auth and entitlements options for the entitlement examples to the argument parser. """ auth_group = parser.add_argument_group("Authorization") auth_group.add_argument("-a", "--auth", dest="authAppName", required=True, help="authorize this application using the specified application", metavar="app=<app>", action=AppAuthAction) entitlements_group = parser.add_argument_group("User Authorization/Entitlements") entitlements_group.add_argument("-u", "--userid-ip", dest="userIdAndIps", help="authorize a user using userId and IP separated by ':'. Can be specified multiple times.", metavar="userId:IP", action=UserIdIpAction, default=[]) entitlements_group.add_argument("-T", "--token", dest="tokens", help="authorize a user using the specified token. Can be specified multiple times.\n" "If the token starts with '-', use " "either -T<token> or --token=<token>.", metavar="token", action="append", default=[]) def _getTlsOptions(options): """Parse TlsOptions from user input""" if (options.tls_client_credentials is None or options.tls_trust_material is None): return None print("TlsOptions enabled") if options.read_certificate_files: with open(options.tls_client_credentials, 'rb') as credentialfile: credential_blob = credentialfile.read() with open(options.tls_trust_material, 'rb') as trustfile: trust_blob = trustfile.read() return blpapi.TlsOptions.createFromBlobs( credential_blob, options.tls_client_credentials_password, trust_blob) return blpapi.TlsOptions.createFromFiles( options.tls_client_credentials, options.tls_client_credentials_password, options.tls_trust_material) def createClientServerSetupAuthOptions(options): """Creates a dictionary whose keys are the identifier representing a user, either userId:IP or token, and whose values are the AuthOptions, either manual option (userId + IP + App) or token. """ authOptionsByIdentifier = {} for userId, ip in options.userIdAndIps: authUser = blpapi.AuthUser.createWithManualOptions(userId, ip) authOptions = blpapi.AuthOptions.createWithUserAndApp( authUser, options.authAppName) authOptionsByIdentifier[f"{userId}:{ip}"] = authOptions for i, token in enumerate(options.tokens): authOptions = blpapi.AuthOptions.createWithToken(token) authOptionsByIdentifier[f"token #{i + 1}"] = authOptions return authOptionsByIdentifier def createSessionOptions(options): """ Creates SessionOptions from the following command line arguments: - connections where servers, TLS and ZFP over Leased lines are specified. - TLS options - authorization options that are used as session identity options. """ tlsOptions = _getTlsOptions(options) if options.remote: if tlsOptions is None: raise RuntimeError("ZFP connections require TLS parameters") print("Creating a ZFP connection for leased lines.") sessionOptions = blpapi.ZfpUtil.getZfpOptionsForLeasedLines( options.remote, tlsOptions) else: sessionOptions = blpapi.SessionOptions() for idx, host in enumerate(options.hosts): sessionOptions.setServerAddress(host[0], host[1], idx) if tlsOptions: sessionOptions.setTlsOptions(tlsOptions) sessionOptions.setSessionIdentityOptions( options.sessionIdentityAuthOptions) print(f"Connecting to " f"{", ".join([h[0] + ":" + str(h[1]) for h in sessionOptions.serverAddresses()])}") return sessionOptions __copyright__ = """ Copyright 2021, Bloomberg Finance L.P. 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 blpapi_import_helper import blpapi from argparse import Action _SESSION_IDENTITY_AUTH_OPTIONS = "sessionIdentityAuthOptions" class AuthOptionsAction(Action): """The action that parses authorization options from user input""" def __call__(self, parser, args, values, option_string=None): vals = values.split('=', 1) auth_type = vals[0] if auth_type == "user": authUser = blpapi.AuthUser.createWithLogonName() authOptions = blpapi.AuthOptions.createWithUser(authUser) elif auth_type == "none": authOptions = None else: if len(vals) != 2: parser.error(f"Invalid auth option '{values}'") if auth_type == "app": appName = vals[1] authOptions = blpapi.AuthOptions.createWithApp(appName) elif auth_type == "userapp": appName = vals[1] authUser = blpapi.AuthUser.createWithLogonName() authOptions = blpapi.AuthOptions.createWithUserAndApp( authUser, appName) elif auth_type == "dir": dirProperty = vals[1] authUser = blpapi.AuthUser.createWithActiveDirectoryProperty( dirProperty) authOptions = blpapi.AuthOptions.createWithUser(authUser) elif auth_type == "manual": parts = vals[1].split(',') if len(parts) != 3: parser.error(f"Invalid auth option '{values}'") appName, ip, userId = parts authUser = blpapi.AuthUser.createWithManualOptions(userId, ip) authOptions = blpapi.AuthOptions.createWithUserAndApp( authUser, appName) else: parser.error(f"Invalid auth option '{values}'") setattr(args, self.dest, authOptions) class AppAuthAction(Action): """The action that parses app authorization options from user input""" def __call__(self, parser, args, values, option_string=None): vals = values.split('=', 1) if len(vals) != 2: parser.error(f"Invalid auth option '{values}'") authType, appName = vals if authType != "app": parser.error(f"Invalid auth option '{values}'") setattr(args, self.dest, appName) authOptions = blpapi.AuthOptions.createWithApp(appName) setattr(args, _SESSION_IDENTITY_AUTH_OPTIONS, authOptions) class HostAction(Action): """The action that parses host options from user input""" def __call__(self, parser, args, values, option_string=None): vals = values.split(':', 1) if len(vals) != 2: parser.error(f"Invalid host option '{values}'") hosts = getattr(args, self.dest) hosts.append((vals[0], int(vals[1]))) class UserIdIpAction(Action): """The action that parses userId and IP authorization options from user input """ def __call__(self, parser, args, values, option_string=None): vals = values.split(":") if len(vals) != 2: parser.error(f"Invalid auth option '{values}'") userId, ip = vals getattr(args, self.dest).append((userId, ip)) def addConnectionAndAuthOptions(parser, forClientServerSetup=False): """ Helper function that adds the options for connection and authorization to the argument parser. """ # Server options server_group = parser.add_argument_group("Connections") server_group.add_argument("-H", "--host", dest="hosts", help="server name or IP (default: 127.0.0.1:8194). Can be specified multiple times.", metavar="host:port", action=HostAction, default=[]) # Auth options if forClientServerSetup: _addArgGroupsAuthAndEntitlementsClientServerSetup(parser) else: _addArgGroupAuth(parser) # TLS Options tls_group = parser.add_argument_group("TLS (specify all or none)") tls_group.add_argument("--tls-client-credentials", dest="tls_client_credentials", help="name a PKCS#12 file to use as a source of " "client credentials", metavar="file") tls_group.add_argument("--tls-client-credentials-password", dest="tls_client_credentials_password", help="specify password for accessing client credentials", metavar="password", default="") tls_group.add_argument("--tls-trust-material", dest="tls_trust_material", help="name a PKCS#7 file to use as a source of " "trusted certificates", metavar="file") tls_group.add_argument("--read-certificate-files", dest="read_certificate_files", help="Enable reading the TLS files and pass the blobs", action="store_true") # ZFP Options zfp_group = parser.add_argument_group( "ZFP connections over leased lines (requires TLS)") zfp_group.add_argument("-z", "--zfp-over-leased-line", dest="remote", help="enable ZFP connections over leased lines on the " "specified port (8194 or 8196)" "\n(When this option is enabled, option -H/--host is ignored.)", metavar="port", type=int) def _addArgGroupAuth(parser): auth_group = parser.add_argument_group("Authorization") auth_group.add_argument("-a", "--auth", dest=_SESSION_IDENTITY_AUTH_OPTIONS, help='''authorization option (default: none) none applicable to Desktop API product that requires Bloomberg Professional service to be installed locally user as a user using OS logon information dir=<property> as a user using directory services app=<app> as the specified application userapp=<app> as user and application using logon information for the user manual=<app,ip,user> as user and application, with manually provided IP address and EMRS user''', metavar="option", action=AuthOptionsAction) def _addArgGroupsAuthAndEntitlementsClientServerSetup(parser): """Adds the auth and entitlements options for the entitlement examples to the argument parser. """ auth_group = parser.add_argument_group("Authorization") auth_group.add_argument("-a", "--auth", dest="authAppName", required=True, help="authorize this application using the specified application", metavar="app=<app>", action=AppAuthAction) entitlements_group = parser.add_argument_group("User Authorization/Entitlements") entitlements_group.add_argument("-u", "--userid-ip", dest="userIdAndIps", help="authorize a user using userId and IP separated by ':'. Can be specified multiple times.", metavar="userId:IP", action=UserIdIpAction, default=[]) entitlements_group.add_argument("-T", "--token", dest="tokens", help="authorize a user using the specified token. Can be specified multiple times.\n" "If the token starts with '-', use " "either -T<token> or --token=<token>.", metavar="token", action="append", default=[]) def _getTlsOptions(options): """Parse TlsOptions from user input""" if (options.tls_client_credentials is None or options.tls_trust_material is None): return None print("TlsOptions enabled") if options.read_certificate_files: with open(options.tls_client_credentials, 'rb') as credentialfile: credential_blob = credentialfile.read() with open(options.tls_trust_material, 'rb') as trustfile: trust_blob = trustfile.read() return blpapi.TlsOptions.createFromBlobs( credential_blob, options.tls_client_credentials_password, trust_blob) return blpapi.TlsOptions.createFromFiles( options.tls_client_credentials, options.tls_client_credentials_password, options.tls_trust_material) def createClientServerSetupAuthOptions(options): """Creates a dictionary whose keys are the identifier representing a user, either userId:IP or token, and whose values are the AuthOptions, either manual option (userId + IP + App) or token. """ authOptionsByIdentifier = {} for userId, ip in options.userIdAndIps: authUser = blpapi.AuthUser.createWithManualOptions(userId, ip) authOptions = blpapi.AuthOptions.createWithUserAndApp( authUser, options.authAppName) authOptionsByIdentifier[f"{userId}:{ip}"] = authOptions for i, token in enumerate(options.tokens): authOptions = blpapi.AuthOptions.createWithToken(token) authOptionsByIdentifier[f"token #{i + 1}"] = authOptions return authOptionsByIdentifier def createSessionOptions(options): """ Creates SessionOptions from the following command line arguments: - connections where servers, TLS and ZFP over Leased lines are specified. - TLS options - authorization options that are used as session identity options. """ tlsOptions = _getTlsOptions(options) if options.remote: if tlsOptions is None: raise RuntimeError("ZFP connections require TLS parameters") print("Creating a ZFP connection for leased lines.") sessionOptions = blpapi.ZfpUtil.getZfpOptionsForLeasedLines( options.remote, tlsOptions) else: sessionOptions = blpapi.SessionOptions() for idx, host in enumerate(options.hosts): sessionOptions.setServerAddress(host[0], host[1], idx) if tlsOptions: sessionOptions.setTlsOptions(tlsOptions) sessionOptions.setSessionIdentityOptions( options.sessionIdentityAuthOptions) print(f"Connecting to " f"{', '.join([h[0] + ':' + str(h[1]) for h in sessionOptions.serverAddresses()])}") return sessionOptions __copyright__ = """ Copyright 2021, Bloomberg Finance L.P. 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. """
pessoas = {'nome': 'Álamo', 'sexo': 'M', 'idade': '26'} print(pessoas['nome']) # quando eu passo o nome da chave dentro de colchetes ele me dá o item dessa chave print(f'O {pessoas['nome']} tem {pessoas['idade']} anos.') # print formatado print(pessoas.keys()) # me retorna todas as chaves print(pessoas.values()) # me mostra todos os dados dentros das chaves print(pessoas.items()) # me mostra uma lista composta com todos os items dentro de tupla for key in pessoas.keys(): # posso usar as funçoes dentro do for para me mostrar os dados print(key) pessoas['nome'] = 'Leandro' # troco o alamo por leandro adicionar um novo dado substitui pessoas['peso'] = 98.5 # adicionei um novo elemento dentro do dic for key, values in pessoas.items(): print(f'{key} = {values}') # del pessoas[sexo] apaga a chave sexo brasil = [] # exemplo de dicionário dentro de lista estado1 = {'uf': 'Minas Gerais', 'sigla': 'MG'} estado2 = {'uf': 'São Paulo', 'sigla': 'SP'} brasil.append(estado1) brasil.append(estado2) print(brasil) print(brasil[0]) # o primeiro indíce dentro de colchetes representa o primeiro dict adcionado print(brasil[0]['sigla']) # aqui eu eu mostro o que esta dentro do indíce de sigla no dict zero estado = dict() brasil = list() for c in range(0, 3): estado['uf'] = str(input('Unidade Federativa: ')) estado['sigla'] = str(input('Sigla do Estado: ')) brasil.append(estado.copy()) # no dicionário o médoto de cópia [:] não funciona é necessaário utilizar o # copy() para acrescentar uma cópia na minha lista estado sem criar uma ligação for e in brasil: for k, v in e.items(): print(f'O campo {k} tem valor {v}') for e in brasil: # usando o laço for para organizar meus prints for v in e.values(): print(v, end=' ') print()
pessoas = {'nome': 'Álamo', 'sexo': 'M', 'idade': '26'} print(pessoas['nome']) # quando eu passo o nome da chave dentro de colchetes ele me dá o item dessa chave print(f'O {pessoas["nome"]} tem {pessoas["idade"]} anos.') # print formatado print(pessoas.keys()) # me retorna todas as chaves print(pessoas.values()) # me mostra todos os dados dentros das chaves print(pessoas.items()) # me mostra uma lista composta com todos os items dentro de tupla for key in pessoas.keys(): # posso usar as funçoes dentro do for para me mostrar os dados print(key) pessoas['nome'] = 'Leandro' # troco o alamo por leandro adicionar um novo dado substitui pessoas['peso'] = 98.5 # adicionei um novo elemento dentro do dic for key, values in pessoas.items(): print(f'{key} = {values}') # del pessoas[sexo] apaga a chave sexo brasil = [] # exemplo de dicionário dentro de lista estado1 = {'uf': 'Minas Gerais', 'sigla': 'MG'} estado2 = {'uf': 'São Paulo', 'sigla': 'SP'} brasil.append(estado1) brasil.append(estado2) print(brasil) print(brasil[0]) # o primeiro indíce dentro de colchetes representa o primeiro dict adcionado print(brasil[0]['sigla']) # aqui eu eu mostro o que esta dentro do indíce de sigla no dict zero estado = dict() brasil = list() for c in range(0, 3): estado['uf'] = str(input('Unidade Federativa: ')) estado['sigla'] = str(input('Sigla do Estado: ')) brasil.append(estado.copy()) # no dicionário o médoto de cópia [:] não funciona é necessaário utilizar o # copy() para acrescentar uma cópia na minha lista estado sem criar uma ligação for e in brasil: for k, v in e.items(): print(f'O campo {k} tem valor {v}') for e in brasil: # usando o laço for para organizar meus prints for v in e.values(): print(v, end=' ') print()
import asyncio import os import sys import traceback import aiohttp from aiohttp import web import cachetools from gidgethub import aiohttp as gh_aiohttp from gidgethub import routing from gidgethub import sansio from webservice import utils router = routing.Router() cache = cachetools.LRUCache(maxsize=500) routes = web.RouteTableDef() @routes.get("/", name="home") async def handle_get(request): return web.Response(text="Hello world") @routes.post("/webhook") async def webhook(request): try: body = await request.read() secret = os.environ.get("GH_SECRET") event = sansio.Event.from_http(request.headers, body, secret=secret) if event.event == "ping": return web.Response(status=200) async with aiohttp.ClientSession() as session: gh = gh_aiohttp.GitHubAPI(session, "demo", cache=cache) await asyncio.sleep(1) await router.dispatch(event, gh) try: print("GH requests remaining:", gh.rate_limit.remaining) except AttributeError: pass return web.Response(status=200) except Exception as exc: traceback.print_exc(file=sys.stderr) return web.Response(status=500) @router.register("installation", action="created") async def repo_installation_added(event, gh, *args, **kwargs): installation_id = event.data["installation"]["id"] pass if __name__ == "__main__": # pragma: no cover app = web.Application() app.router.add_routes(routes) port = os.environ.get("PORT") if port is not None: port = int(port) web.run_app(app, port=port) @router.register("installation", action="created") async def repo_installation_added(event, gh, *args, **kwargs): installation_id = event.data["installation"]["id"] installation_access_token = await utils.get_installation_access_token( gh, installation_id ) maintainer = event.data["sender"]["login"] message = f"Thanks for installing me, @{maintainer}! (I'm a bot)." for repository in event.data["repositories_added"]: url = f"/repos/{repository["full_name"]}/issues/" response = await gh.post( url, data={"title": "Mariatta's bot was installed", "body": message}, oauth_token=installation_access_token["token"], ) issue_url = response["url"] await gh.patch(issue_url, data={"state": "closed"}, oauth_token=installation_access_token["token"] )
import asyncio import os import sys import traceback import aiohttp from aiohttp import web import cachetools from gidgethub import aiohttp as gh_aiohttp from gidgethub import routing from gidgethub import sansio from webservice import utils router = routing.Router() cache = cachetools.LRUCache(maxsize=500) routes = web.RouteTableDef() @routes.get("/", name="home") async def handle_get(request): return web.Response(text="Hello world") @routes.post("/webhook") async def webhook(request): try: body = await request.read() secret = os.environ.get("GH_SECRET") event = sansio.Event.from_http(request.headers, body, secret=secret) if event.event == "ping": return web.Response(status=200) async with aiohttp.ClientSession() as session: gh = gh_aiohttp.GitHubAPI(session, "demo", cache=cache) await asyncio.sleep(1) await router.dispatch(event, gh) try: print("GH requests remaining:", gh.rate_limit.remaining) except AttributeError: pass return web.Response(status=200) except Exception as exc: traceback.print_exc(file=sys.stderr) return web.Response(status=500) @router.register("installation", action="created") async def repo_installation_added(event, gh, *args, **kwargs): installation_id = event.data["installation"]["id"] pass if __name__ == "__main__": # pragma: no cover app = web.Application() app.router.add_routes(routes) port = os.environ.get("PORT") if port is not None: port = int(port) web.run_app(app, port=port) @router.register("installation", action="created") async def repo_installation_added(event, gh, *args, **kwargs): installation_id = event.data["installation"]["id"] installation_access_token = await utils.get_installation_access_token( gh, installation_id ) maintainer = event.data["sender"]["login"] message = f"Thanks for installing me, @{maintainer}! (I'm a bot)." for repository in event.data["repositories_added"]: url = f"/repos/{repository['full_name']}/issues/" response = await gh.post( url, data={"title": "Mariatta's bot was installed", "body": message}, oauth_token=installation_access_token["token"], ) issue_url = response["url"] await gh.patch(issue_url, data={"state": "closed"}, oauth_token=installation_access_token["token"] )
import logging from os import unlink from pathlib import Path from secrets import token_bytes from shutil import copy, move import time import pytest from blspy import AugSchemeMPL from chiapos import DiskPlotter from tranzact.consensus.coinbase import create_puzzlehash_for_pk from tranzact.plotting.util import stream_plot_info_ph, stream_plot_info_pk, PlotRefreshResult, PlotRefreshEvents from tranzact.plotting.manager import PlotManager from tranzact.protocols import farmer_protocol from tranzact.rpc.farmer_rpc_api import FarmerRpcApi from tranzact.rpc.farmer_rpc_client import FarmerRpcClient from tranzact.rpc.harvester_rpc_api import HarvesterRpcApi from tranzact.rpc.harvester_rpc_client import HarvesterRpcClient from tranzact.rpc.rpc_server import start_rpc_server from tranzact.types.blockchain_format.sized_bytes import bytes32 from tranzact.util.bech32m import decode_puzzle_hash, encode_puzzle_hash from tests.block_tools import get_plot_dir from tranzact.util.byte_types import hexstr_to_bytes from tranzact.util.config import load_config, save_config from tranzact.util.hash import std_hash from tranzact.util.ints import uint8, uint16, uint32, uint64 from tranzact.wallet.derive_keys import master_sk_to_wallet_sk, master_sk_to_pooling_authentication_sk from tests.setup_nodes import bt, self_hostname, setup_farmer_harvester, test_constants from tests.time_out_assert import time_out_assert, time_out_assert_custom_interval log = logging.getLogger(__name__) class TestRpc: @pytest.fixture(scope="function") async def simulation(self): async for _ in setup_farmer_harvester(test_constants): yield _ @pytest.mark.asyncio async def test1(self, simulation): test_rpc_port = uint16(21522) test_rpc_port_2 = uint16(21523) harvester, farmer_api = simulation def stop_node_cb(): pass def stop_node_cb_2(): pass config = bt.config hostname = config["self_hostname"] daemon_port = config["daemon_port"] farmer_rpc_api = FarmerRpcApi(farmer_api.farmer) harvester_rpc_api = HarvesterRpcApi(harvester) rpc_cleanup = await start_rpc_server( farmer_rpc_api, hostname, daemon_port, test_rpc_port, stop_node_cb, bt.root_path, config, connect_to_daemon=False, ) rpc_cleanup_2 = await start_rpc_server( harvester_rpc_api, hostname, daemon_port, test_rpc_port_2, stop_node_cb_2, bt.root_path, config, connect_to_daemon=False, ) try: client = await FarmerRpcClient.create(self_hostname, test_rpc_port, bt.root_path, config) client_2 = await HarvesterRpcClient.create(self_hostname, test_rpc_port_2, bt.root_path, config) async def have_connections(): return len(await client.get_connections()) > 0 await time_out_assert(15, have_connections, True) assert (await client.get_signage_point(std_hash(b"2"))) is None assert len(await client.get_signage_points()) == 0 async def have_signage_points(): return len(await client.get_signage_points()) > 0 sp = farmer_protocol.NewSignagePoint( std_hash(b"1"), std_hash(b"2"), std_hash(b"3"), uint64(1), uint64(1000000), uint8(2) ) await farmer_api.new_signage_point(sp) await time_out_assert(5, have_signage_points, True) assert (await client.get_signage_point(std_hash(b"2"))) is not None async def have_plots(): return len((await client_2.get_plots())["plots"]) > 0 await time_out_assert(5, have_plots, True) res = await client_2.get_plots() num_plots = len(res["plots"]) assert num_plots > 0 plot_dir = get_plot_dir() / "subdir" plot_dir.mkdir(parents=True, exist_ok=True) plot_dir_sub = get_plot_dir() / "subdir" / "subsubdir" plot_dir_sub.mkdir(parents=True, exist_ok=True) plotter = DiskPlotter() filename = "test_farmer_harvester_rpc_plot.plot" filename_2 = "test_farmer_harvester_rpc_plot2.plot" plotter.create_plot_disk( str(plot_dir), str(plot_dir), str(plot_dir), filename, 18, stream_plot_info_pk(bt.pool_pk, bt.farmer_pk, AugSchemeMPL.key_gen(bytes([4] * 32))), token_bytes(32), 128, 0, 2000, 0, False, ) # Making a plot with a puzzle hash encoded into it instead of pk plot_id_2 = token_bytes(32) plotter.create_plot_disk( str(plot_dir), str(plot_dir), str(plot_dir), filename_2, 18, stream_plot_info_ph(std_hash(b"random ph"), bt.farmer_pk, AugSchemeMPL.key_gen(bytes([5] * 32))), plot_id_2, 128, 0, 2000, 0, False, ) # Making the same plot, in a different dir. This should not be farmed plotter.create_plot_disk( str(plot_dir_sub), str(plot_dir_sub), str(plot_dir_sub), filename_2, 18, stream_plot_info_ph(std_hash(b"random ph"), bt.farmer_pk, AugSchemeMPL.key_gen(bytes([5] * 32))), plot_id_2, 128, 0, 2000, 0, False, ) res_2 = await client_2.get_plots() assert len(res_2["plots"]) == num_plots # Reset cache and force updates cache every second to make sure the farmer gets the most recent data update_interval_before = farmer_api.farmer.update_harvester_cache_interval farmer_api.farmer.update_harvester_cache_interval = 1 farmer_api.farmer.harvester_cache = {} # Test farmer get_harvesters async def test_get_harvesters(): harvester.plot_manager.trigger_refresh() await time_out_assert(5, harvester.plot_manager.needs_refresh, value=False) farmer_res = await client.get_harvesters() if len(list(farmer_res["harvesters"])) != 1: log.error(f"test_get_harvesters: invalid harvesters {list(farmer_res["harvesters"])}") return False if len(list(farmer_res["harvesters"][0]["plots"])) != num_plots: log.error(f"test_get_harvesters: invalid plots {list(farmer_res["harvesters"])}") return False return True await time_out_assert_custom_interval(30, 1, test_get_harvesters) # Reset cache and reset update interval to avoid hitting the rate limit farmer_api.farmer.update_harvester_cache_interval = update_interval_before farmer_api.farmer.harvester_cache = {} expected_result: PlotRefreshResult = PlotRefreshResult() expected_result_matched = True # Note: We assign `expected_result_matched` in the callback and assert it in the test thread to avoid # crashing the refresh thread of the plot manager with invalid assertions. def test_refresh_callback(event: PlotRefreshEvents, refresh_result: PlotRefreshResult): if event != PlotRefreshEvents.done: # Only validate the final results for this tests return def test_value(name: str, actual: PlotRefreshResult, expected: PlotRefreshResult): nonlocal expected_result_matched try: actual_value = actual.__getattribute__(name) expected_value = expected.__getattribute__(name) if actual_value != expected_value: log.error(f"{name} invalid: actual {actual_value} expected {expected_value}") expected_result_matched = False except AttributeError as error: log.error(f"{error}") expected_result_matched = False test_value("loaded", refresh_result, expected_result) test_value("removed", refresh_result, expected_result) test_value("processed", refresh_result, expected_result) test_value("remaining", refresh_result, expected_result) harvester.plot_manager.set_refresh_callback(test_refresh_callback) async def test_refresh_results(manager: PlotManager, start_refreshing: bool = False): nonlocal expected_result_matched expected_result_matched = True if start_refreshing: manager.start_refreshing() else: manager.trigger_refresh() await time_out_assert(5, manager.needs_refresh, value=False) assert expected_result_matched async def test_case( trigger, expect_loaded, expect_duplicates, expect_removed, expect_processed, expected_directories, expect_total_plots, ): nonlocal expected_result_matched expected_result.loaded = expect_loaded expected_result.removed = expect_removed expected_result.processed = expect_processed await trigger assert len(await client_2.get_plot_directories()) == expected_directories await test_refresh_results(harvester.plot_manager) result = await client_2.get_plots() assert len(result["plots"]) == expect_total_plots assert len(harvester.plot_manager.cache) == expect_total_plots assert len(harvester.plot_manager.get_duplicates()) == expect_duplicates assert len(harvester.plot_manager.failed_to_open_filenames) == 0 # Add plot_dir with two new plots await test_case( client_2.add_plot_directory(str(plot_dir)), expect_loaded=2, expect_removed=0, expect_processed=num_plots + 2, expect_duplicates=0, expected_directories=2, expect_total_plots=num_plots + 2, ) # Add plot_dir_sub with one duplicate await test_case( client_2.add_plot_directory(str(plot_dir_sub)), expect_loaded=0, expect_removed=0, expect_processed=num_plots + 3, expect_duplicates=1, expected_directories=3, expect_total_plots=num_plots + 2, ) assert plot_dir_sub.resolve() / filename_2 in harvester.plot_manager.get_duplicates() # Delete one plot await test_case( client_2.delete_plot(str(plot_dir / filename)), expect_loaded=0, expect_removed=1, expect_processed=num_plots + 2, expect_duplicates=1, expected_directories=3, expect_total_plots=num_plots + 1, ) # Remove directory with the duplicate await test_case( client_2.remove_plot_directory(str(plot_dir_sub)), expect_loaded=0, expect_removed=1, expect_processed=num_plots + 1, expect_duplicates=0, expected_directories=2, expect_total_plots=num_plots + 1, ) assert plot_dir_sub.resolve() / filename_2 not in harvester.plot_manager.get_duplicates() # Re-add the directory with the duplicate for other tests await test_case( client_2.add_plot_directory(str(plot_dir_sub)), expect_loaded=0, expect_removed=0, expect_processed=num_plots + 2, expect_duplicates=1, expected_directories=3, expect_total_plots=num_plots + 1, ) # Remove the directory which has the duplicated plot loaded. This removes the duplicated plot from plot_dir # and in the same run loads the plot from plot_dir_sub which is not longer seen as duplicate. await test_case( client_2.remove_plot_directory(str(plot_dir)), expect_loaded=1, expect_removed=1, expect_processed=num_plots + 1, expect_duplicates=0, expected_directories=2, expect_total_plots=num_plots + 1, ) # Re-add the directory now the plot seen as duplicate is from plot_dir, not from plot_dir_sub like before await test_case( client_2.add_plot_directory(str(plot_dir)), expect_loaded=0, expect_removed=0, expect_processed=num_plots + 2, expect_duplicates=1, expected_directories=3, expect_total_plots=num_plots + 1, ) # Remove the duplicated plot await test_case( client_2.delete_plot(str(plot_dir / filename_2)), expect_loaded=0, expect_removed=1, expect_processed=num_plots + 1, expect_duplicates=0, expected_directories=3, expect_total_plots=num_plots + 1, ) # Remove the directory with the loaded plot which is not longer a duplicate await test_case( client_2.remove_plot_directory(str(plot_dir_sub)), expect_loaded=0, expect_removed=1, expect_processed=num_plots, expect_duplicates=0, expected_directories=2, expect_total_plots=num_plots, ) # Remove the directory which contains all other plots await test_case( client_2.remove_plot_directory(str(get_plot_dir())), expect_loaded=0, expect_removed=num_plots, expect_processed=0, expect_duplicates=0, expected_directories=1, expect_total_plots=0, ) # Recover the plots to test caching # First make sure cache gets written if required and new plots are loaded await test_case( client_2.add_plot_directory(str(get_plot_dir())), expect_loaded=num_plots, expect_removed=0, expect_processed=num_plots, expect_duplicates=0, expected_directories=2, expect_total_plots=num_plots, ) assert harvester.plot_manager.cache.path().exists() unlink(harvester.plot_manager.cache.path()) # Should not write the cache again on shutdown because it didn't change assert not harvester.plot_manager.cache.path().exists() harvester.plot_manager.stop_refreshing() assert not harvester.plot_manager.cache.path().exists() # Manually trigger `save_cache` and make sure it creates a new cache file harvester.plot_manager.cache.save() assert harvester.plot_manager.cache.path().exists() expected_result.loaded = 20 expected_result.removed = 0 expected_result.processed = 20 expected_result.remaining = 0 plot_manager: PlotManager = PlotManager(harvester.root_path, test_refresh_callback) plot_manager.cache.load() assert len(harvester.plot_manager.cache) == len(plot_manager.cache) await test_refresh_results(plot_manager, start_refreshing=True) for path, plot_info in harvester.plot_manager.plots.items(): assert path in plot_manager.plots assert plot_manager.plots[path].prover.get_filename() == plot_info.prover.get_filename() assert plot_manager.plots[path].prover.get_id() == plot_info.prover.get_id() assert plot_manager.plots[path].prover.get_memo() == plot_info.prover.get_memo() assert plot_manager.plots[path].prover.get_size() == plot_info.prover.get_size() assert plot_manager.plots[path].pool_public_key == plot_info.pool_public_key assert plot_manager.plots[path].pool_contract_puzzle_hash == plot_info.pool_contract_puzzle_hash assert plot_manager.plots[path].plot_public_key == plot_info.plot_public_key assert plot_manager.plots[path].file_size == plot_info.file_size assert plot_manager.plots[path].time_modified == plot_info.time_modified assert harvester.plot_manager.plot_filename_paths == plot_manager.plot_filename_paths assert harvester.plot_manager.failed_to_open_filenames == plot_manager.failed_to_open_filenames assert harvester.plot_manager.no_key_filenames == plot_manager.no_key_filenames plot_manager.stop_refreshing() # Modify the content of the plot_manager.dat with open(harvester.plot_manager.cache.path(), "r+b") as file: file.write(b"\xff\xff") # Sets Cache.version to 65535 # Make sure it just loads the plots normally if it fails to load the cache plot_manager = PlotManager(harvester.root_path, test_refresh_callback) plot_manager.cache.load() assert len(plot_manager.cache) == 0 plot_manager.set_public_keys( harvester.plot_manager.farmer_public_keys, harvester.plot_manager.pool_public_keys ) expected_result.loaded = 20 expected_result.removed = 0 expected_result.processed = 20 expected_result.remaining = 0 await test_refresh_results(plot_manager, start_refreshing=True) assert len(plot_manager.plots) == len(harvester.plot_manager.plots) plot_manager.stop_refreshing() # Test re-trying if processing a plot failed # First save the plot retry_test_plot = Path(plot_dir_sub / filename_2).resolve() retry_test_plot_save = Path(plot_dir_sub / "save").resolve() copy(retry_test_plot, retry_test_plot_save) # Invalidate the plot with open(plot_dir_sub / filename_2, "r+b") as file: file.write(bytes(100)) # Add it and validate it fails to load await harvester.add_plot_directory(str(plot_dir_sub)) expected_result.loaded = 0 expected_result.removed = 0 expected_result.processed = num_plots + 1 expected_result.remaining = 0 await test_refresh_results(harvester.plot_manager, start_refreshing=True) assert retry_test_plot in harvester.plot_manager.failed_to_open_filenames # Make sure the file stays in `failed_to_open_filenames` and doesn't get loaded or processed in the next # update round expected_result.loaded = 0 expected_result.processed = num_plots + 1 await test_refresh_results(harvester.plot_manager) assert retry_test_plot in harvester.plot_manager.failed_to_open_filenames # Now decrease the re-try timeout, restore the valid plot file and make sure it properly loads now harvester.plot_manager.refresh_parameter.retry_invalid_seconds = 0 move(retry_test_plot_save, retry_test_plot) expected_result.loaded = 1 expected_result.processed = num_plots + 1 await test_refresh_results(harvester.plot_manager) assert retry_test_plot not in harvester.plot_manager.failed_to_open_filenames # Test re-trying if processing a plot failed # First save the plot retry_test_plot = Path(plot_dir_sub / filename_2).resolve() retry_test_plot_save = Path(plot_dir_sub / "save").resolve() copy(retry_test_plot, retry_test_plot_save) # Invalidate the plot with open(plot_dir_sub / filename_2, "r+b") as file: file.write(bytes(100)) # Add it and validate it fails to load await harvester.add_plot_directory(str(plot_dir_sub)) expected_result.loaded_plots = 0 expected_result.removed_plots = 0 expected_result.processed_files = 1 expected_result.remaining_files = 0 harvester.plot_manager.start_refreshing() await time_out_assert(5, harvester.plot_manager.needs_refresh, value=False) assert retry_test_plot in harvester.plot_manager.failed_to_open_filenames # Make sure the file stays in `failed_to_open_filenames` and doesn't get loaded or processed in the next # update round expected_result.loaded_plots = 0 expected_result.processed_files = 0 harvester.plot_manager.trigger_refresh() await time_out_assert(5, harvester.plot_manager.needs_refresh, value=False) assert retry_test_plot in harvester.plot_manager.failed_to_open_filenames # Now decrease the re-try timeout, restore the valid plot file and make sure it properly loads now harvester.plot_manager.refresh_parameter.retry_invalid_seconds = 0 move(retry_test_plot_save, retry_test_plot) expected_result.loaded_plots = 1 expected_result.processed_files = 1 harvester.plot_manager.trigger_refresh() await time_out_assert(5, harvester.plot_manager.needs_refresh, value=False) assert retry_test_plot not in harvester.plot_manager.failed_to_open_filenames targets_1 = await client.get_reward_targets(False) assert "have_pool_sk" not in targets_1 assert "have_farmer_sk" not in targets_1 targets_2 = await client.get_reward_targets(True) assert targets_2["have_pool_sk"] and targets_2["have_farmer_sk"] new_ph: bytes32 = create_puzzlehash_for_pk(master_sk_to_wallet_sk(bt.farmer_master_sk, uint32(10)).get_g1()) new_ph_2: bytes32 = create_puzzlehash_for_pk( master_sk_to_wallet_sk(bt.pool_master_sk, uint32(472)).get_g1() ) await client.set_reward_targets(encode_puzzle_hash(new_ph, "trz"), encode_puzzle_hash(new_ph_2, "trz")) targets_3 = await client.get_reward_targets(True) assert decode_puzzle_hash(targets_3["farmer_target"]) == new_ph assert decode_puzzle_hash(targets_3["pool_target"]) == new_ph_2 assert targets_3["have_pool_sk"] and targets_3["have_farmer_sk"] new_ph_3: bytes32 = create_puzzlehash_for_pk( master_sk_to_wallet_sk(bt.pool_master_sk, uint32(1888)).get_g1() ) await client.set_reward_targets(None, encode_puzzle_hash(new_ph_3, "trz")) targets_4 = await client.get_reward_targets(True) assert decode_puzzle_hash(targets_4["farmer_target"]) == new_ph assert decode_puzzle_hash(targets_4["pool_target"]) == new_ph_3 assert not targets_4["have_pool_sk"] and targets_3["have_farmer_sk"] root_path = farmer_api.farmer._root_path config = load_config(root_path, "config.yaml") assert config["farmer"]["trz_target_address"] == encode_puzzle_hash(new_ph, "trz") assert config["pool"]["trz_target_address"] == encode_puzzle_hash(new_ph_3, "trz") new_ph_3_encoded = encode_puzzle_hash(new_ph_3, "trz") added_char = new_ph_3_encoded + "a" with pytest.raises(ValueError): await client.set_reward_targets(None, added_char) replaced_char = new_ph_3_encoded[0:-1] + "a" with pytest.raises(ValueError): await client.set_reward_targets(None, replaced_char) assert len((await client.get_pool_state())["pool_state"]) == 0 all_sks = farmer_api.farmer.local_keychain.get_all_private_keys() auth_sk = master_sk_to_pooling_authentication_sk(all_sks[0][0], 2, 1) pool_list = [ { "launcher_id": "ae4ef3b9bfe68949691281a015a9c16630fc8f66d48c19ca548fb80768791afa", "authentication_public_key": bytes(auth_sk.get_g1()).hex(), "owner_public_key": "84c3fcf9d5581c1ddc702cb0f3b4a06043303b334dd993ab42b2c320ebfa98e5ce558448615b3f69638ba92cf7f43da5", # noqa "payout_instructions": "c2b08e41d766da4116e388357ed957d04ad754623a915f3fd65188a8746cf3e8", "pool_url": "localhost", "p2_singleton_puzzle_hash": "16e4bac26558d315cded63d4c5860e98deb447cc59146dd4de06ce7394b14f17", "target_puzzle_hash": "344587cf06a39db471d2cc027504e8688a0a67cce961253500c956c73603fd58", } ] config["pool"]["pool_list"] = pool_list save_config(root_path, "config.yaml", config) await farmer_api.farmer.update_pool_state() pool_state = (await client.get_pool_state())["pool_state"] assert len(pool_state) == 1 assert ( pool_state[0]["pool_config"]["payout_instructions"] == "c2b08e41d766da4116e388357ed957d04ad754623a915f3fd65188a8746cf3e8" ) await client.set_payout_instructions(hexstr_to_bytes(pool_state[0]["pool_config"]["launcher_id"]), "1234vy") await farmer_api.farmer.update_pool_state() pool_state = (await client.get_pool_state())["pool_state"] assert pool_state[0]["pool_config"]["payout_instructions"] == "1234vy" now = time.time() # Big arbitrary numbers used to be unlikely to accidentally collide. before_24h = (now - (25 * 60 * 60), 29984713) since_24h = (now - (23 * 60 * 60), 93049817) for p2_singleton_puzzle_hash, pool_dict in farmer_api.farmer.pool_state.items(): for key in ["points_found_24h", "points_acknowledged_24h"]: pool_dict[key].insert(0, since_24h) pool_dict[key].insert(0, before_24h) sp = farmer_protocol.NewSignagePoint( std_hash(b"1"), std_hash(b"2"), std_hash(b"3"), uint64(1), uint64(1000000), uint8(2) ) await farmer_api.new_signage_point(sp) client_pool_state = await client.get_pool_state() for pool_dict in client_pool_state["pool_state"]: for key in ["points_found_24h", "points_acknowledged_24h"]: assert pool_dict[key][0] == list(since_24h) finally: # Checks that the RPC manages to stop the node client.close() client_2.close() await client.await_closed() await client_2.await_closed() await rpc_cleanup() await rpc_cleanup_2()
import logging from os import unlink from pathlib import Path from secrets import token_bytes from shutil import copy, move import time import pytest from blspy import AugSchemeMPL from chiapos import DiskPlotter from tranzact.consensus.coinbase import create_puzzlehash_for_pk from tranzact.plotting.util import stream_plot_info_ph, stream_plot_info_pk, PlotRefreshResult, PlotRefreshEvents from tranzact.plotting.manager import PlotManager from tranzact.protocols import farmer_protocol from tranzact.rpc.farmer_rpc_api import FarmerRpcApi from tranzact.rpc.farmer_rpc_client import FarmerRpcClient from tranzact.rpc.harvester_rpc_api import HarvesterRpcApi from tranzact.rpc.harvester_rpc_client import HarvesterRpcClient from tranzact.rpc.rpc_server import start_rpc_server from tranzact.types.blockchain_format.sized_bytes import bytes32 from tranzact.util.bech32m import decode_puzzle_hash, encode_puzzle_hash from tests.block_tools import get_plot_dir from tranzact.util.byte_types import hexstr_to_bytes from tranzact.util.config import load_config, save_config from tranzact.util.hash import std_hash from tranzact.util.ints import uint8, uint16, uint32, uint64 from tranzact.wallet.derive_keys import master_sk_to_wallet_sk, master_sk_to_pooling_authentication_sk from tests.setup_nodes import bt, self_hostname, setup_farmer_harvester, test_constants from tests.time_out_assert import time_out_assert, time_out_assert_custom_interval log = logging.getLogger(__name__) class TestRpc: @pytest.fixture(scope="function") async def simulation(self): async for _ in setup_farmer_harvester(test_constants): yield _ @pytest.mark.asyncio async def test1(self, simulation): test_rpc_port = uint16(21522) test_rpc_port_2 = uint16(21523) harvester, farmer_api = simulation def stop_node_cb(): pass def stop_node_cb_2(): pass config = bt.config hostname = config["self_hostname"] daemon_port = config["daemon_port"] farmer_rpc_api = FarmerRpcApi(farmer_api.farmer) harvester_rpc_api = HarvesterRpcApi(harvester) rpc_cleanup = await start_rpc_server( farmer_rpc_api, hostname, daemon_port, test_rpc_port, stop_node_cb, bt.root_path, config, connect_to_daemon=False, ) rpc_cleanup_2 = await start_rpc_server( harvester_rpc_api, hostname, daemon_port, test_rpc_port_2, stop_node_cb_2, bt.root_path, config, connect_to_daemon=False, ) try: client = await FarmerRpcClient.create(self_hostname, test_rpc_port, bt.root_path, config) client_2 = await HarvesterRpcClient.create(self_hostname, test_rpc_port_2, bt.root_path, config) async def have_connections(): return len(await client.get_connections()) > 0 await time_out_assert(15, have_connections, True) assert (await client.get_signage_point(std_hash(b"2"))) is None assert len(await client.get_signage_points()) == 0 async def have_signage_points(): return len(await client.get_signage_points()) > 0 sp = farmer_protocol.NewSignagePoint( std_hash(b"1"), std_hash(b"2"), std_hash(b"3"), uint64(1), uint64(1000000), uint8(2) ) await farmer_api.new_signage_point(sp) await time_out_assert(5, have_signage_points, True) assert (await client.get_signage_point(std_hash(b"2"))) is not None async def have_plots(): return len((await client_2.get_plots())["plots"]) > 0 await time_out_assert(5, have_plots, True) res = await client_2.get_plots() num_plots = len(res["plots"]) assert num_plots > 0 plot_dir = get_plot_dir() / "subdir" plot_dir.mkdir(parents=True, exist_ok=True) plot_dir_sub = get_plot_dir() / "subdir" / "subsubdir" plot_dir_sub.mkdir(parents=True, exist_ok=True) plotter = DiskPlotter() filename = "test_farmer_harvester_rpc_plot.plot" filename_2 = "test_farmer_harvester_rpc_plot2.plot" plotter.create_plot_disk( str(plot_dir), str(plot_dir), str(plot_dir), filename, 18, stream_plot_info_pk(bt.pool_pk, bt.farmer_pk, AugSchemeMPL.key_gen(bytes([4] * 32))), token_bytes(32), 128, 0, 2000, 0, False, ) # Making a plot with a puzzle hash encoded into it instead of pk plot_id_2 = token_bytes(32) plotter.create_plot_disk( str(plot_dir), str(plot_dir), str(plot_dir), filename_2, 18, stream_plot_info_ph(std_hash(b"random ph"), bt.farmer_pk, AugSchemeMPL.key_gen(bytes([5] * 32))), plot_id_2, 128, 0, 2000, 0, False, ) # Making the same plot, in a different dir. This should not be farmed plotter.create_plot_disk( str(plot_dir_sub), str(plot_dir_sub), str(plot_dir_sub), filename_2, 18, stream_plot_info_ph(std_hash(b"random ph"), bt.farmer_pk, AugSchemeMPL.key_gen(bytes([5] * 32))), plot_id_2, 128, 0, 2000, 0, False, ) res_2 = await client_2.get_plots() assert len(res_2["plots"]) == num_plots # Reset cache and force updates cache every second to make sure the farmer gets the most recent data update_interval_before = farmer_api.farmer.update_harvester_cache_interval farmer_api.farmer.update_harvester_cache_interval = 1 farmer_api.farmer.harvester_cache = {} # Test farmer get_harvesters async def test_get_harvesters(): harvester.plot_manager.trigger_refresh() await time_out_assert(5, harvester.plot_manager.needs_refresh, value=False) farmer_res = await client.get_harvesters() if len(list(farmer_res["harvesters"])) != 1: log.error(f"test_get_harvesters: invalid harvesters {list(farmer_res['harvesters'])}") return False if len(list(farmer_res["harvesters"][0]["plots"])) != num_plots: log.error(f"test_get_harvesters: invalid plots {list(farmer_res['harvesters'])}") return False return True await time_out_assert_custom_interval(30, 1, test_get_harvesters) # Reset cache and reset update interval to avoid hitting the rate limit farmer_api.farmer.update_harvester_cache_interval = update_interval_before farmer_api.farmer.harvester_cache = {} expected_result: PlotRefreshResult = PlotRefreshResult() expected_result_matched = True # Note: We assign `expected_result_matched` in the callback and assert it in the test thread to avoid # crashing the refresh thread of the plot manager with invalid assertions. def test_refresh_callback(event: PlotRefreshEvents, refresh_result: PlotRefreshResult): if event != PlotRefreshEvents.done: # Only validate the final results for this tests return def test_value(name: str, actual: PlotRefreshResult, expected: PlotRefreshResult): nonlocal expected_result_matched try: actual_value = actual.__getattribute__(name) expected_value = expected.__getattribute__(name) if actual_value != expected_value: log.error(f"{name} invalid: actual {actual_value} expected {expected_value}") expected_result_matched = False except AttributeError as error: log.error(f"{error}") expected_result_matched = False test_value("loaded", refresh_result, expected_result) test_value("removed", refresh_result, expected_result) test_value("processed", refresh_result, expected_result) test_value("remaining", refresh_result, expected_result) harvester.plot_manager.set_refresh_callback(test_refresh_callback) async def test_refresh_results(manager: PlotManager, start_refreshing: bool = False): nonlocal expected_result_matched expected_result_matched = True if start_refreshing: manager.start_refreshing() else: manager.trigger_refresh() await time_out_assert(5, manager.needs_refresh, value=False) assert expected_result_matched async def test_case( trigger, expect_loaded, expect_duplicates, expect_removed, expect_processed, expected_directories, expect_total_plots, ): nonlocal expected_result_matched expected_result.loaded = expect_loaded expected_result.removed = expect_removed expected_result.processed = expect_processed await trigger assert len(await client_2.get_plot_directories()) == expected_directories await test_refresh_results(harvester.plot_manager) result = await client_2.get_plots() assert len(result["plots"]) == expect_total_plots assert len(harvester.plot_manager.cache) == expect_total_plots assert len(harvester.plot_manager.get_duplicates()) == expect_duplicates assert len(harvester.plot_manager.failed_to_open_filenames) == 0 # Add plot_dir with two new plots await test_case( client_2.add_plot_directory(str(plot_dir)), expect_loaded=2, expect_removed=0, expect_processed=num_plots + 2, expect_duplicates=0, expected_directories=2, expect_total_plots=num_plots + 2, ) # Add plot_dir_sub with one duplicate await test_case( client_2.add_plot_directory(str(plot_dir_sub)), expect_loaded=0, expect_removed=0, expect_processed=num_plots + 3, expect_duplicates=1, expected_directories=3, expect_total_plots=num_plots + 2, ) assert plot_dir_sub.resolve() / filename_2 in harvester.plot_manager.get_duplicates() # Delete one plot await test_case( client_2.delete_plot(str(plot_dir / filename)), expect_loaded=0, expect_removed=1, expect_processed=num_plots + 2, expect_duplicates=1, expected_directories=3, expect_total_plots=num_plots + 1, ) # Remove directory with the duplicate await test_case( client_2.remove_plot_directory(str(plot_dir_sub)), expect_loaded=0, expect_removed=1, expect_processed=num_plots + 1, expect_duplicates=0, expected_directories=2, expect_total_plots=num_plots + 1, ) assert plot_dir_sub.resolve() / filename_2 not in harvester.plot_manager.get_duplicates() # Re-add the directory with the duplicate for other tests await test_case( client_2.add_plot_directory(str(plot_dir_sub)), expect_loaded=0, expect_removed=0, expect_processed=num_plots + 2, expect_duplicates=1, expected_directories=3, expect_total_plots=num_plots + 1, ) # Remove the directory which has the duplicated plot loaded. This removes the duplicated plot from plot_dir # and in the same run loads the plot from plot_dir_sub which is not longer seen as duplicate. await test_case( client_2.remove_plot_directory(str(plot_dir)), expect_loaded=1, expect_removed=1, expect_processed=num_plots + 1, expect_duplicates=0, expected_directories=2, expect_total_plots=num_plots + 1, ) # Re-add the directory now the plot seen as duplicate is from plot_dir, not from plot_dir_sub like before await test_case( client_2.add_plot_directory(str(plot_dir)), expect_loaded=0, expect_removed=0, expect_processed=num_plots + 2, expect_duplicates=1, expected_directories=3, expect_total_plots=num_plots + 1, ) # Remove the duplicated plot await test_case( client_2.delete_plot(str(plot_dir / filename_2)), expect_loaded=0, expect_removed=1, expect_processed=num_plots + 1, expect_duplicates=0, expected_directories=3, expect_total_plots=num_plots + 1, ) # Remove the directory with the loaded plot which is not longer a duplicate await test_case( client_2.remove_plot_directory(str(plot_dir_sub)), expect_loaded=0, expect_removed=1, expect_processed=num_plots, expect_duplicates=0, expected_directories=2, expect_total_plots=num_plots, ) # Remove the directory which contains all other plots await test_case( client_2.remove_plot_directory(str(get_plot_dir())), expect_loaded=0, expect_removed=num_plots, expect_processed=0, expect_duplicates=0, expected_directories=1, expect_total_plots=0, ) # Recover the plots to test caching # First make sure cache gets written if required and new plots are loaded await test_case( client_2.add_plot_directory(str(get_plot_dir())), expect_loaded=num_plots, expect_removed=0, expect_processed=num_plots, expect_duplicates=0, expected_directories=2, expect_total_plots=num_plots, ) assert harvester.plot_manager.cache.path().exists() unlink(harvester.plot_manager.cache.path()) # Should not write the cache again on shutdown because it didn't change assert not harvester.plot_manager.cache.path().exists() harvester.plot_manager.stop_refreshing() assert not harvester.plot_manager.cache.path().exists() # Manually trigger `save_cache` and make sure it creates a new cache file harvester.plot_manager.cache.save() assert harvester.plot_manager.cache.path().exists() expected_result.loaded = 20 expected_result.removed = 0 expected_result.processed = 20 expected_result.remaining = 0 plot_manager: PlotManager = PlotManager(harvester.root_path, test_refresh_callback) plot_manager.cache.load() assert len(harvester.plot_manager.cache) == len(plot_manager.cache) await test_refresh_results(plot_manager, start_refreshing=True) for path, plot_info in harvester.plot_manager.plots.items(): assert path in plot_manager.plots assert plot_manager.plots[path].prover.get_filename() == plot_info.prover.get_filename() assert plot_manager.plots[path].prover.get_id() == plot_info.prover.get_id() assert plot_manager.plots[path].prover.get_memo() == plot_info.prover.get_memo() assert plot_manager.plots[path].prover.get_size() == plot_info.prover.get_size() assert plot_manager.plots[path].pool_public_key == plot_info.pool_public_key assert plot_manager.plots[path].pool_contract_puzzle_hash == plot_info.pool_contract_puzzle_hash assert plot_manager.plots[path].plot_public_key == plot_info.plot_public_key assert plot_manager.plots[path].file_size == plot_info.file_size assert plot_manager.plots[path].time_modified == plot_info.time_modified assert harvester.plot_manager.plot_filename_paths == plot_manager.plot_filename_paths assert harvester.plot_manager.failed_to_open_filenames == plot_manager.failed_to_open_filenames assert harvester.plot_manager.no_key_filenames == plot_manager.no_key_filenames plot_manager.stop_refreshing() # Modify the content of the plot_manager.dat with open(harvester.plot_manager.cache.path(), "r+b") as file: file.write(b"\xff\xff") # Sets Cache.version to 65535 # Make sure it just loads the plots normally if it fails to load the cache plot_manager = PlotManager(harvester.root_path, test_refresh_callback) plot_manager.cache.load() assert len(plot_manager.cache) == 0 plot_manager.set_public_keys( harvester.plot_manager.farmer_public_keys, harvester.plot_manager.pool_public_keys ) expected_result.loaded = 20 expected_result.removed = 0 expected_result.processed = 20 expected_result.remaining = 0 await test_refresh_results(plot_manager, start_refreshing=True) assert len(plot_manager.plots) == len(harvester.plot_manager.plots) plot_manager.stop_refreshing() # Test re-trying if processing a plot failed # First save the plot retry_test_plot = Path(plot_dir_sub / filename_2).resolve() retry_test_plot_save = Path(plot_dir_sub / "save").resolve() copy(retry_test_plot, retry_test_plot_save) # Invalidate the plot with open(plot_dir_sub / filename_2, "r+b") as file: file.write(bytes(100)) # Add it and validate it fails to load await harvester.add_plot_directory(str(plot_dir_sub)) expected_result.loaded = 0 expected_result.removed = 0 expected_result.processed = num_plots + 1 expected_result.remaining = 0 await test_refresh_results(harvester.plot_manager, start_refreshing=True) assert retry_test_plot in harvester.plot_manager.failed_to_open_filenames # Make sure the file stays in `failed_to_open_filenames` and doesn't get loaded or processed in the next # update round expected_result.loaded = 0 expected_result.processed = num_plots + 1 await test_refresh_results(harvester.plot_manager) assert retry_test_plot in harvester.plot_manager.failed_to_open_filenames # Now decrease the re-try timeout, restore the valid plot file and make sure it properly loads now harvester.plot_manager.refresh_parameter.retry_invalid_seconds = 0 move(retry_test_plot_save, retry_test_plot) expected_result.loaded = 1 expected_result.processed = num_plots + 1 await test_refresh_results(harvester.plot_manager) assert retry_test_plot not in harvester.plot_manager.failed_to_open_filenames # Test re-trying if processing a plot failed # First save the plot retry_test_plot = Path(plot_dir_sub / filename_2).resolve() retry_test_plot_save = Path(plot_dir_sub / "save").resolve() copy(retry_test_plot, retry_test_plot_save) # Invalidate the plot with open(plot_dir_sub / filename_2, "r+b") as file: file.write(bytes(100)) # Add it and validate it fails to load await harvester.add_plot_directory(str(plot_dir_sub)) expected_result.loaded_plots = 0 expected_result.removed_plots = 0 expected_result.processed_files = 1 expected_result.remaining_files = 0 harvester.plot_manager.start_refreshing() await time_out_assert(5, harvester.plot_manager.needs_refresh, value=False) assert retry_test_plot in harvester.plot_manager.failed_to_open_filenames # Make sure the file stays in `failed_to_open_filenames` and doesn't get loaded or processed in the next # update round expected_result.loaded_plots = 0 expected_result.processed_files = 0 harvester.plot_manager.trigger_refresh() await time_out_assert(5, harvester.plot_manager.needs_refresh, value=False) assert retry_test_plot in harvester.plot_manager.failed_to_open_filenames # Now decrease the re-try timeout, restore the valid plot file and make sure it properly loads now harvester.plot_manager.refresh_parameter.retry_invalid_seconds = 0 move(retry_test_plot_save, retry_test_plot) expected_result.loaded_plots = 1 expected_result.processed_files = 1 harvester.plot_manager.trigger_refresh() await time_out_assert(5, harvester.plot_manager.needs_refresh, value=False) assert retry_test_plot not in harvester.plot_manager.failed_to_open_filenames targets_1 = await client.get_reward_targets(False) assert "have_pool_sk" not in targets_1 assert "have_farmer_sk" not in targets_1 targets_2 = await client.get_reward_targets(True) assert targets_2["have_pool_sk"] and targets_2["have_farmer_sk"] new_ph: bytes32 = create_puzzlehash_for_pk(master_sk_to_wallet_sk(bt.farmer_master_sk, uint32(10)).get_g1()) new_ph_2: bytes32 = create_puzzlehash_for_pk( master_sk_to_wallet_sk(bt.pool_master_sk, uint32(472)).get_g1() ) await client.set_reward_targets(encode_puzzle_hash(new_ph, "trz"), encode_puzzle_hash(new_ph_2, "trz")) targets_3 = await client.get_reward_targets(True) assert decode_puzzle_hash(targets_3["farmer_target"]) == new_ph assert decode_puzzle_hash(targets_3["pool_target"]) == new_ph_2 assert targets_3["have_pool_sk"] and targets_3["have_farmer_sk"] new_ph_3: bytes32 = create_puzzlehash_for_pk( master_sk_to_wallet_sk(bt.pool_master_sk, uint32(1888)).get_g1() ) await client.set_reward_targets(None, encode_puzzle_hash(new_ph_3, "trz")) targets_4 = await client.get_reward_targets(True) assert decode_puzzle_hash(targets_4["farmer_target"]) == new_ph assert decode_puzzle_hash(targets_4["pool_target"]) == new_ph_3 assert not targets_4["have_pool_sk"] and targets_3["have_farmer_sk"] root_path = farmer_api.farmer._root_path config = load_config(root_path, "config.yaml") assert config["farmer"]["trz_target_address"] == encode_puzzle_hash(new_ph, "trz") assert config["pool"]["trz_target_address"] == encode_puzzle_hash(new_ph_3, "trz") new_ph_3_encoded = encode_puzzle_hash(new_ph_3, "trz") added_char = new_ph_3_encoded + "a" with pytest.raises(ValueError): await client.set_reward_targets(None, added_char) replaced_char = new_ph_3_encoded[0:-1] + "a" with pytest.raises(ValueError): await client.set_reward_targets(None, replaced_char) assert len((await client.get_pool_state())["pool_state"]) == 0 all_sks = farmer_api.farmer.local_keychain.get_all_private_keys() auth_sk = master_sk_to_pooling_authentication_sk(all_sks[0][0], 2, 1) pool_list = [ { "launcher_id": "ae4ef3b9bfe68949691281a015a9c16630fc8f66d48c19ca548fb80768791afa", "authentication_public_key": bytes(auth_sk.get_g1()).hex(), "owner_public_key": "84c3fcf9d5581c1ddc702cb0f3b4a06043303b334dd993ab42b2c320ebfa98e5ce558448615b3f69638ba92cf7f43da5", # noqa "payout_instructions": "c2b08e41d766da4116e388357ed957d04ad754623a915f3fd65188a8746cf3e8", "pool_url": "localhost", "p2_singleton_puzzle_hash": "16e4bac26558d315cded63d4c5860e98deb447cc59146dd4de06ce7394b14f17", "target_puzzle_hash": "344587cf06a39db471d2cc027504e8688a0a67cce961253500c956c73603fd58", } ] config["pool"]["pool_list"] = pool_list save_config(root_path, "config.yaml", config) await farmer_api.farmer.update_pool_state() pool_state = (await client.get_pool_state())["pool_state"] assert len(pool_state) == 1 assert ( pool_state[0]["pool_config"]["payout_instructions"] == "c2b08e41d766da4116e388357ed957d04ad754623a915f3fd65188a8746cf3e8" ) await client.set_payout_instructions(hexstr_to_bytes(pool_state[0]["pool_config"]["launcher_id"]), "1234vy") await farmer_api.farmer.update_pool_state() pool_state = (await client.get_pool_state())["pool_state"] assert pool_state[0]["pool_config"]["payout_instructions"] == "1234vy" now = time.time() # Big arbitrary numbers used to be unlikely to accidentally collide. before_24h = (now - (25 * 60 * 60), 29984713) since_24h = (now - (23 * 60 * 60), 93049817) for p2_singleton_puzzle_hash, pool_dict in farmer_api.farmer.pool_state.items(): for key in ["points_found_24h", "points_acknowledged_24h"]: pool_dict[key].insert(0, since_24h) pool_dict[key].insert(0, before_24h) sp = farmer_protocol.NewSignagePoint( std_hash(b"1"), std_hash(b"2"), std_hash(b"3"), uint64(1), uint64(1000000), uint8(2) ) await farmer_api.new_signage_point(sp) client_pool_state = await client.get_pool_state() for pool_dict in client_pool_state["pool_state"]: for key in ["points_found_24h", "points_acknowledged_24h"]: assert pool_dict[key][0] == list(since_24h) finally: # Checks that the RPC manages to stop the node client.close() client_2.close() await client.await_closed() await client_2.await_closed() await rpc_cleanup() await rpc_cleanup_2()
# -*- coding: utf-8 -*- """Implements the base xonsh parser.""" import os import re import time import textwrap from threading import Thread from ast import parse as pyparse from collections.abc import Iterable, Sequence, Mapping try: from ply import yacc except ImportError: from xonsh.ply.ply import yacc from xonsh import ast from xonsh.ast import has_elts, xonsh_call, load_attribute_chain from xonsh.lexer import Lexer, LexToken from xonsh.platform import PYTHON_VERSION_INFO from xonsh.tokenize import SearchPath, StringPrefix from xonsh.lazyasd import LazyObject from xonsh.parsers.context_check import check_contexts RE_SEARCHPATH = LazyObject(lambda: re.compile(SearchPath), globals(), "RE_SEARCHPATH") RE_STRINGPREFIX = LazyObject( lambda: re.compile(StringPrefix), globals(), "RE_STRINGPREFIX" ) RE_FSTR_ENVVAR = LazyObject( lambda: re.compile(r"\{\s*\$(\w+)"), globals(), "RE_FSTR_ENVVAR" ) class Location(object): """Location in a file.""" def __init__(self, fname, lineno, column=None): """Takes a filename, line number, and optionally a column number.""" self.fname = fname self.lineno = lineno self.column = column def __str__(self): s = "{0}:{1}".format(self.fname, self.lineno) if self.column is not None: s += ":{0}".format(self.column) return s def ensure_has_elts(x, lineno=None, col_offset=None): """Ensures that x is an AST node with elements.""" if not has_elts(x): if not isinstance(x, Iterable): x = [x] lineno = x[0].lineno if lineno is None else lineno col_offset = x[0].col_offset if col_offset is None else col_offset x = ast.Tuple(elts=x, ctx=ast.Load(), lineno=lineno, col_offset=col_offset) return x def empty_list(lineno=None, col=None): """Creates the AST node for an empty list.""" return ast.List(elts=[], ctx=ast.Load(), lineno=lineno, col_offset=col) def binop(x, op, y, lineno=None, col=None): """Creates the AST node for a binary operation.""" lineno = x.lineno if lineno is None else lineno col = x.col_offset if col is None else col return ast.BinOp(left=x, op=op, right=y, lineno=lineno, col_offset=col) def call_split_lines(x, lineno=None, col=None): """Creates the AST node for calling the 'splitlines' attribute of an object, nominally a string. """ return ast.Call( func=ast.Attribute( value=x, attr="splitlines", ctx=ast.Load(), lineno=lineno, col_offset=col ), args=[], keywords=[], starargs=None, kwargs=None, lineno=lineno, col_offset=col, ) def ensure_list_from_str_or_list(x, lineno=None, col=None): """Creates the AST node for the following expression:: [x] if isinstance(x, str) else x Somewhat useful. """ return ast.IfExp( test=ast.Call( func=ast.Name( id="isinstance", ctx=ast.Load(), lineno=lineno, col_offset=col ), args=[x, ast.Name(id="str", ctx=ast.Load(), lineno=lineno, col_offset=col)], keywords=[], starargs=None, kwargs=None, lineno=lineno, col_offset=col, ), body=ast.List(elts=[x], ctx=ast.Load(), lineno=lineno, col_offset=col), orelse=x, lineno=lineno, col_offset=col, ) def xonsh_help(x, lineno=None, col=None): """Creates the AST node for calling the __xonsh__.help() function.""" return xonsh_call("__xonsh__.help", [x], lineno=lineno, col=col) def xonsh_superhelp(x, lineno=None, col=None): """Creates the AST node for calling the __xonsh__.superhelp() function.""" return xonsh_call("__xonsh__.superhelp", [x], lineno=lineno, col=col) def xonsh_pathsearch(pattern, pymode=False, lineno=None, col=None): """Creates the AST node for calling the __xonsh__.pathsearch() function. The pymode argument indicate if it is called from subproc or python mode""" pymode = ast.NameConstant(value=pymode, lineno=lineno, col_offset=col) searchfunc, pattern = RE_SEARCHPATH.match(pattern).groups() pattern = ast.Str(s=pattern, lineno=lineno, col_offset=col) pathobj = False if searchfunc.startswith("@"): func = searchfunc[1:] elif "g" in searchfunc: func = "__xonsh__.globsearch" pathobj = "p" in searchfunc else: func = "__xonsh__.regexsearch" pathobj = "p" in searchfunc func = load_attribute_chain(func, lineno=lineno, col=col) pathobj = ast.NameConstant(value=pathobj, lineno=lineno, col_offset=col) return xonsh_call( "__xonsh__.pathsearch", args=[func, pattern, pymode, pathobj], lineno=lineno, col=col, ) def load_ctx(x): """Recursively sets ctx to ast.Load()""" if not hasattr(x, "ctx"): return x.ctx = ast.Load() if isinstance(x, (ast.Tuple, ast.List)): for e in x.elts: load_ctx(e) elif isinstance(x, ast.Starred): load_ctx(x.value) def store_ctx(x): """Recursively sets ctx to ast.Store()""" if not hasattr(x, "ctx"): return x.ctx = ast.Store() if isinstance(x, (ast.Tuple, ast.List)): for e in x.elts: store_ctx(e) elif isinstance(x, ast.Starred): store_ctx(x.value) def del_ctx(x): """Recursively sets ctx to ast.Del()""" if not hasattr(x, "ctx"): return x.ctx = ast.Del() if isinstance(x, (ast.Tuple, ast.List)): for e in x.elts: del_ctx(e) elif isinstance(x, ast.Starred): del_ctx(x.value) def empty_list_if_newline(x): return [] if x == "\n" else x def lopen_loc(x): """Extracts the line and column number for a node that may have an opening parenthesis, brace, or bracket. """ lineno = x._lopen_lineno if hasattr(x, "_lopen_lineno") else x.lineno col = x._lopen_col if hasattr(x, "_lopen_col") else x.col_offset return lineno, col def hasglobstar(x): """Returns True if a node has literal '*' for globbing.""" if isinstance(x, ast.Str): return "*" in x.s elif isinstance(x, list): for e in x: if hasglobstar(e): return True else: return False else: return False def _repl_sub_env_vars_single(matchobj): return "{__xonsh__.env.detype()['" + matchobj.group(1) + "']" def _repl_sub_env_vars_double(matchobj): return '{__xonsh__.env.detype()["' + matchobj.group(1) + '"]' def sub_env_vars(fstring): """Takes an fstring that may contain environment variables and substitues them for a valid environment lookup call. Roughly, for example, this will take f"{$HOME}" and transform it to be f"{__xonsh__.env.detype()["HOME"]}". """ repl = ( _repl_sub_env_vars_single if fstring[-1] == '"' else _repl_sub_env_vars_double ) return RE_FSTR_ENVVAR.sub(repl, fstring) class YaccLoader(Thread): """Thread to load (but not shave) the yacc parser.""" def __init__(self, parser, yacc_kwargs, *args, **kwargs): super().__init__(*args, **kwargs) self.daemon = True self.parser = parser self.yacc_kwargs = yacc_kwargs self.start() def run(self): self.parser.parser = yacc.yacc(**self.yacc_kwargs) class BaseParser(object): """A base class that parses the xonsh language.""" def __init__( self, lexer_optimize=True, lexer_table="xonsh.lexer_table", yacc_optimize=True, yacc_table="xonsh.parser_table", yacc_debug=False, outputdir=None, ): """Parameters ---------- lexer_optimize : bool, optional Set to false when unstable and true when lexer is stable. lexer_table : str, optional Lexer module used when optimized. yacc_optimize : bool, optional Set to false when unstable and true when parser is stable. yacc_table : str, optional Parser module used when optimized. yacc_debug : debug, optional Dumps extra debug info. outputdir : str or None, optional The directory to place generated tables within. Defaults to the root xonsh dir. """ self.lexer = lexer = Lexer() self.tokens = lexer.tokens self._lines = None self.xonsh_code = None self._attach_nocomma_tok_rules() self._attach_nocloser_base_rules() self._attach_nodedent_base_rules() self._attach_nonewline_base_rules() self._attach_subproc_arg_part_rules() opt_rules = [ "newlines", "arglist", "func_call", "rarrow_test", "typedargslist", "equals_test", "colon_test", "tfpdef", "comma_tfpdef_list", "comma_pow_tfpdef", "vfpdef", "comma_vfpdef_list", "comma_pow_vfpdef", "equals_yield_expr_or_testlist_list", "testlist", "as_name", "period_or_ellipsis_list", "comma_import_as_name_list", "comma_dotted_as_name_list", "comma_name_list", "comma_test", "elif_part_list", "finally_part", "varargslist", "or_and_test_list", "and_not_test_list", "comp_op_expr_list", "xor_and_expr_list", "ampersand_shift_expr_list", "shift_arith_expr_list", "op_factor_list", "trailer_list", "testlist_comp", "yield_expr_or_testlist_comp", "dictorsetmaker", "comma_subscript_list", "test", "sliceop", "comp_iter", "yield_arg", "test_comma_list", "macroarglist", "any_raw_toks", ] for rule in opt_rules: self._opt_rule(rule) list_rules = [ "comma_tfpdef", "comma_vfpdef", "semi_small_stmt", "comma_test_or_star_expr", "period_or_ellipsis", "comma_import_as_name", "comma_dotted_as_name", "period_name", "comma_name", "elif_part", "except_part", "comma_with_item", "or_and_test", "and_not_test", "comp_op_expr", "pipe_xor_expr", "xor_and_expr", "ampersand_shift_expr", "shift_arith_expr", "pm_term", "op_factor", "trailer", "comma_subscript", "comma_expr_or_star_expr", "comma_test", "comma_argument", "comma_item", "attr_period_name", "test_comma", "equals_yield_expr_or_testlist", "comma_nocomma", ] for rule in list_rules: self._list_rule(rule) tok_rules = [ "def", "class", "return", "number", "name", "bang", "none", "true", "false", "ellipsis", "if", "del", "assert", "lparen", "lbrace", "lbracket", "string", "times", "plus", "minus", "divide", "doublediv", "mod", "at", "lshift", "rshift", "pipe", "xor", "ampersand", "for", "colon", "import", "except", "nonlocal", "global", "yield", "from", "raise", "with", "dollar_lparen", "dollar_lbrace", "dollar_lbracket", "try", "bang_lparen", "bang_lbracket", "comma", "rparen", "rbracket", "at_lparen", "atdollar_lparen", "indent", "dedent", "newline", "lambda", "ampersandequal", "as", "atdollar", "atequal", "break", "continue", "divequal", "dollar_name", "double_question", "doubledivequal", "elif", "else", "eq", "equals", "errortoken", "finally", "ge", "in", "is", "le", "lshiftequal", "minusequal", "modequal", "ne", "pass", "period", "pipeequal", "plusequal", "pow", "powequal", "question", "rarrow", "rshiftequal", "semi", "tilde", "timesequal", "while", "xorequal", ] for rule in tok_rules: self._tok_rule(rule) yacc_kwargs = dict( module=self, debug=yacc_debug, start="start_symbols", optimize=yacc_optimize, tabmodule=yacc_table, ) if not yacc_debug: yacc_kwargs["errorlog"] = yacc.NullLogger() if outputdir is None: outputdir = os.path.dirname(os.path.dirname(__file__)) yacc_kwargs["outputdir"] = outputdir if yacc_debug: # create parser on main thread self.parser = yacc.yacc(**yacc_kwargs) else: self.parser = None YaccLoader(self, yacc_kwargs) # Keeps track of the last token given to yacc (the lookahead token) self._last_yielded_token = None def reset(self): """Resets for clean parsing.""" self.lexer.reset() self._last_yielded_token = None self._lines = None self.xonsh_code = None def parse(self, s, filename="<code>", mode="exec", debug_level=0): """Returns an abstract syntax tree of xonsh code. Parameters ---------- s : str The xonsh code. filename : str, optional Name of the file. mode : str, optional Execution mode, one of: exec, eval, or single. debug_level : str, optional Debugging level passed down to yacc. Returns ------- tree : AST """ self.reset() self.xonsh_code = s self.lexer.fname = filename while self.parser is None: time.sleep(0.01) # block until the parser is ready tree = self.parser.parse(input=s, lexer=self.lexer, debug=debug_level) if tree is not None: check_contexts(tree) # hack for getting modes right if mode == "single": if isinstance(tree, ast.Expression): tree = ast.Interactive(body=[self.expr(tree.body)]) elif isinstance(tree, ast.Module): tree = ast.Interactive(body=tree.body) return tree def _lexer_errfunc(self, msg, line, column): self._parse_error(msg, self.currloc(line, column)) def _yacc_lookahead_token(self): """Gets the next-to-last and last token seen by the lexer.""" return self.lexer.beforelast, self.lexer.last def _opt_rule(self, rulename): """For a rule name, creates an associated optional rule. '_opt' is appended to the rule name. """ def optfunc(self, p): p[0] = p[1] optfunc.__doc__ = ("{0}_opt : empty\n" " | {0}").format(rulename) optfunc.__name__ = "p_" + rulename + "_opt" setattr(self.__class__, optfunc.__name__, optfunc) def _list_rule(self, rulename): """For a rule name, creates an associated list rule. '_list' is appended to the rule name. """ def listfunc(self, p): p[0] = p[1] if len(p) == 2 else p[1] + p[2] listfunc.__doc__ = ("{0}_list : {0}\n" " | {0}_list {0}").format( rulename ) listfunc.__name__ = "p_" + rulename + "_list" setattr(self.__class__, listfunc.__name__, listfunc) def _tok_rule(self, rulename): """For a rule name, creates a rule that returns the corresponding token. '_tok' is appended to the rule name. """ def tokfunc(self, p): s, t = self._yacc_lookahead_token() uprule = rulename.upper() if s is not None and s.type == uprule: p[0] = s elif t is not None and t.type == uprule: p[0] = t else: raise TypeError("token for {0!r} not found.".format(rulename)) tokfunc.__doc__ = "{0}_tok : {1}".format(rulename, rulename.upper()) tokfunc.__name__ = "p_" + rulename + "_tok" setattr(self.__class__, tokfunc.__name__, tokfunc) def currloc(self, lineno, column=None): """Returns the current location.""" return Location(fname=self.lexer.fname, lineno=lineno, column=column) def expr(self, p): """Creates an expression for a token.""" expr = ast.Expr(value=p, lineno=p.lineno, col_offset=p.col_offset) expr.max_lineno = self.lineno expr.max_col = self.col return expr def token_col(self, t): """Gets ths token column""" return t.lexpos @property def lineno(self): if self.lexer.last is None: return 1 else: return self.lexer.last.lineno @property def col(self): s, t = self._yacc_lookahead_token() if t is not None: if t.type == "NEWLINE": t = s return self.token_col(t) return 0 @property def lines(self): if self._lines is None and self.xonsh_code is not None: self._lines = self.xonsh_code.splitlines(keepends=True) return self._lines def source_slice(self, start, stop): """Gets the original source code from two (line, col) tuples in source-space (i.e. lineno start at 1). """ bline, bcol = start eline, ecol = stop bline -= 1 lines = self.lines[bline:eline] if ecol == 0: explen = eline - bline if explen == len(lines) and explen > 1: lines[-1] = "" else: lines[-1] = lines[-1][:ecol] lines[0] = lines[0][bcol:] return "".join(lines) def _parse_error(self, msg, loc): if self.xonsh_code is None or loc is None: err_line_pointer = "" else: col = loc.column + 1 lines = self.lines if loc.lineno == 0: loc.lineno = len(lines) i = loc.lineno - 1 if 0 <= i < len(lines): err_line = lines[i].rstrip() err_line_pointer = "\n{}\n{: >{}}".format(err_line, "^", col) else: err_line_pointer = "" err = SyntaxError("{0}: {1}{2}".format(loc, msg, err_line_pointer)) err.loc = loc raise err # # Precedence of operators # precedence = ( ("left", "PIPE"), ("left", "XOR"), ("left", "AMPERSAND"), ("left", "EQ", "NE"), ("left", "GT", "GE", "LT", "LE"), ("left", "RSHIFT", "LSHIFT"), ("left", "PLUS", "MINUS"), ("left", "TIMES", "DIVIDE", "DOUBLEDIV", "MOD"), ("left", "POW"), ) # # Grammar as defined by BNF # def p_start_symbols(self, p): """start_symbols : single_input | file_input | eval_input | empty """ p[0] = p[1] def p_single_input(self, p): """single_input : compound_stmt NEWLINE """ p1 = empty_list_if_newline(p[1]) p0 = ast.Interactive(body=p1) p[0] = p0 def p_file_input(self, p): """file_input : file_stmts""" p[0] = ast.Module(body=p[1]) def p_file_stmts_nl(self, p): """file_stmts : newline_or_stmt""" # newline_or_stmt ENDMARKER p[0] = empty_list_if_newline(p[1]) def p_file_stmts_files(self, p): """file_stmts : file_stmts newline_or_stmt""" # file_input newline_or_stmt ENDMARKER p2 = empty_list_if_newline(p[2]) p[0] = p[1] + p2 def p_newline_or_stmt(self, p): """newline_or_stmt : NEWLINE | stmt """ p[0] = p[1] def p_newlines(self, p): """newlines : NEWLINE | newlines NEWLINE """ p[0] = p[1] if len(p) == 2 else p[1] + p[2] def p_eval_input(self, p): """eval_input : testlist newlines_opt """ p1 = p[1] p[0] = ast.Expression(body=p1, lineno=p1.lineno, col_offset=p1.col_offset) def p_func_call(self, p): """func_call : LPAREN arglist_opt RPAREN""" p[0] = p[2] def p_attr_period_name(self, p): """attr_period_name : PERIOD NAME""" p[0] = [p[2]] def p_attr_name_alone(self, p): """attr_name : name_tok""" p1 = p[1] p[0] = ast.Name( id=p1.value, ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.lexpos ) def p_attr_name_with(self, p): """attr_name : name_tok attr_period_name_list""" p1 = p[1] name = ast.Name( id=p1.value, ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.lexpos ) p2 = p[2] p0 = ast.Attribute( value=name, attr=p2[0], ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.lexpos, ) for a in p2[1:]: p0 = ast.Attribute( value=p0, attr=a, ctx=ast.Load(), lineno=p0.lineno, col_offset=p0.col_offset, ) p[0] = p0 def p_decorator_no_call(self, p): """decorator : at_tok attr_name NEWLINE""" p[0] = p[2] def p_decorator_call(self, p): """decorator : at_tok attr_name func_call NEWLINE""" p1, name, p3 = p[1], p[2], p[3] if isinstance(name, ast.Attribute) or (p3 is not None): lineno, col = name.lineno, name.col_offset else: lineno, col = p1.lineno, p1.lexpos if p3 is None: p0 = ast.Call( func=name, args=[], keywords=[], starargs=None, kwargs=None, lineno=lineno, col_offset=col, ) else: p0 = ast.Call(func=name, lineno=lineno, col_offset=col, **p3) p[0] = p0 def p_decorators(self, p): """decorators : decorator | decorators decorator """ p[0] = [p[1]] if len(p) == 2 else p[1] + [p[2]] def p_decorated(self, p): """decorated : decorators classdef_or_funcdef""" p1, p2 = p[1], p[2] targ = p2[0] targ.decorator_list = p1 # this is silly, CPython. This claims a func or class starts on # the line of the first decorator, rather than the 'def' or 'class' # line. However, it retains the original col_offset. targ.lineno = p1[0].lineno # async functions take the col number of the 'def', unless they are # decorated, in which case they have the col of the 'async'. WAT? if hasattr(targ, "_async_tok"): targ.col_offset = targ._async_tok.lexpos del targ._async_tok p[0] = p2 def p_rarrow_test(self, p): """rarrow_test : RARROW test""" p[0] = p[2] def p_funcdef(self, p): """funcdef : def_tok NAME parameters rarrow_test_opt COLON suite""" f = ast.FunctionDef( name=p[2], args=p[3], returns=p[4], body=p[6], decorator_list=[], lineno=p[1].lineno, col_offset=p[1].lexpos, ) p[0] = [f] def p_parameters(self, p): """parameters : LPAREN typedargslist_opt RPAREN""" p2 = p[2] if p2 is None: p2 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[], ) p[0] = p2 def p_equals_test(self, p): """equals_test : EQUALS test""" p[0] = p[2] def p_typedargslist_kwarg(self, p): """typedargslist : POW tfpdef""" p[0] = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[2], defaults=[] ) def p_typedargslist_times4_tfpdef(self, p): """typedargslist : TIMES tfpdef comma_pow_tfpdef_opt""" # *args, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[3], defaults=[] ) self._set_var_args(p0, p[2], None) p[0] = p0 def p_typedargslist_times4_comma(self, p): """typedargslist : TIMES comma_pow_tfpdef""" # *, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[2], defaults=[] ) p[0] = p0 def p_typedargslist_times5_tdpdef(self, p): """typedargslist : TIMES tfpdef comma_tfpdef_list comma_pow_tfpdef_opt""" # *args, x, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[4], defaults=[] ) self._set_var_args(p0, p[2], p[3]) # *args p[0] = p0 def p_typedargslist_times5_comma(self, p): """typedargslist : TIMES comma_tfpdef_list comma_pow_tfpdef_opt""" # *, x, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[3], defaults=[] ) self._set_var_args(p0, None, p[2]) # *args p[0] = p0 def p_typedargslist_t5(self, p): """typedargslist : tfpdef equals_test_opt comma_tfpdef_list_opt comma_opt""" # x p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[] ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) p[0] = p0 def p_typedargslist_t7(self, p): """typedargslist : tfpdef equals_test_opt comma_tfpdef_list_opt comma_opt POW tfpdef""" # x, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[6], defaults=[] ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) p[0] = p0 def p_typedargslist_t8(self, p): """typedargslist : tfpdef equals_test_opt comma_tfpdef_list_opt comma_opt TIMES tfpdef_opt comma_tfpdef_list_opt""" p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[] ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) self._set_var_args(p0, p[6], p[7]) p[0] = p0 def p_typedargslist_t10(self, p): """typedargslist : tfpdef equals_test_opt comma_tfpdef_list_opt comma_opt TIMES tfpdef_opt COMMA POW vfpdef""" # x, *args, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[9], defaults=[] ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) self._set_var_args(p0, p[6], None) p[0] = p0 def p_typedargslist_t11(self, p): """typedargslist : tfpdef equals_test_opt comma_tfpdef_list_opt comma_opt TIMES tfpdef_opt comma_tfpdef_list COMMA POW tfpdef""" # x, *args, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[10], defaults=[], ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) self._set_var_args(p0, p[6], p[7]) p[0] = p0 def p_colon_test(self, p): """colon_test : COLON test""" p[0] = p[2] def p_tfpdef(self, p): """tfpdef : name_tok colon_test_opt""" p1 = p[1] kwargs = {"arg": p1.value, "annotation": p[2]} if PYTHON_VERSION_INFO >= (3, 5, 1): kwargs.update({"lineno": p1.lineno, "col_offset": p1.lexpos}) p[0] = ast.arg(**kwargs) def p_comma_tfpdef_empty(self, p): """comma_tfpdef : COMMA""" p[0] = [] def p_comma_tfpdef_args(self, p): """comma_tfpdef : COMMA tfpdef equals_test_opt""" p[0] = [{"arg": p[2], "default": p[3]}] def p_comma_pow_tfpdef(self, p): """comma_pow_tfpdef : COMMA POW tfpdef""" p[0] = p[3] def _set_args_def(self, argmts, vals, kwargs=False): args, defs = ( (argmts.kwonlyargs, argmts.kw_defaults) if kwargs else (argmts.args, argmts.defaults) ) if vals is None and kwargs: loc = self.currloc(self.lineno, self.col) self._parse_error("named arguments must follow bare *", loc) for v in vals: args.append(v["arg"]) d = v["default"] if kwargs or (d is not None): defs.append(d) def _set_regular_args(self, p0, p1, p2, p3, p4): if p2 is None and p3 is None: # x p0.args.append(p1) elif p2 is not None and p3 is None: # x=42 p0.args.append(p1) p0.defaults.append(p2) elif p2 is None and p3 is not None: # x, y and x, y=42 p0.args.append(p1) self._set_args_def(p0, p3) else: # x=42, y=42 p0.args.append(p1) p0.defaults.append(p2) self._set_args_def(p0, p3) def _set_var_args(self, p0, vararg, kwargs): if vararg is None and kwargs is not None: self._set_args_def(p0, kwargs, kwargs=True) elif vararg is not None and kwargs is None: # *args p0.vararg = vararg elif vararg is not None and kwargs is not None: # *args, x and *args, x, y and *args, x=10 and *args, x=10, y # and *args, x, y=10, and *args, x=42, y=65 p0.vararg = vararg self._set_args_def(p0, kwargs, kwargs=True) else: assert False def p_varargslist_kwargs(self, p): """varargslist : POW vfpdef""" p[0] = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[2], defaults=[] ) def p_varargslist_times4(self, p): """varargslist : TIMES vfpdef_opt comma_pow_vfpdef_opt""" p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[3], defaults=[] ) self._set_var_args(p0, p[2], None) p[0] = p0 def p_varargslist_times5(self, p): """varargslist : TIMES vfpdef_opt comma_vfpdef_list comma_pow_vfpdef_opt""" # *args, x, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[4], defaults=[] ) self._set_var_args(p0, p[2], p[3]) # *args p[0] = p0 def p_varargslist_v5(self, p): """varargslist : vfpdef equals_test_opt comma_vfpdef_list_opt comma_opt""" # x p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[] ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) p[0] = p0 def p_varargslist_v7(self, p): """varargslist : vfpdef equals_test_opt comma_vfpdef_list_opt comma_opt POW vfpdef""" # x, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[6], defaults=[] ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) p[0] = p0 def p_varargslist_v8(self, p): """varargslist : vfpdef equals_test_opt comma_vfpdef_list_opt comma_opt TIMES vfpdef_opt comma_vfpdef_list_opt""" # x, *args p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[] ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) self._set_var_args(p0, p[6], p[7]) p[0] = p0 def p_varargslist_v10(self, p): """varargslist : vfpdef equals_test_opt comma_vfpdef_list_opt comma_opt TIMES vfpdef_opt COMMA POW vfpdef""" # x, *args, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[9], defaults=[] ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) self._set_var_args(p0, p[6], None) p[0] = p0 def p_varargslist_v11(self, p): """varargslist : vfpdef equals_test_opt comma_vfpdef_list_opt comma_opt TIMES vfpdef_opt comma_vfpdef_list COMMA POW vfpdef""" p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[10], defaults=[], ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) self._set_var_args(p0, p[6], p[7]) p[0] = p0 def p_vfpdef(self, p): """vfpdef : name_tok""" p1 = p[1] kwargs = {"arg": p1.value, "annotation": None} if PYTHON_VERSION_INFO >= (3, 5, 1): kwargs.update({"lineno": p1.lineno, "col_offset": p1.lexpos}) p[0] = ast.arg(**kwargs) def p_comma_vfpdef_empty(self, p): """comma_vfpdef : COMMA""" p[0] = [] def p_comma_vfpdef_value(self, p): """comma_vfpdef : COMMA vfpdef equals_test_opt""" p[0] = [{"arg": p[2], "default": p[3]}] def p_comma_pow_vfpdef(self, p): """comma_pow_vfpdef : COMMA POW vfpdef""" p[0] = p[3] def p_stmt(self, p): """stmt : simple_stmt | compound_stmt """ p[0] = p[1] def p_stmt_list(self, p): """stmt_list : stmt | stmt_list stmt """ if len(p) == 2: p[0] = p[1] else: p[0] = p[1] + p[2] def p_semi_opt(self, p): """semi_opt : SEMI | empty """ if len(p) == 2: p[0] = p[1] def p_semi_small_stmt(self, p): """semi_small_stmt : SEMI small_stmt""" p[0] = [p[2]] def p_simple_stmt_single(self, p): """simple_stmt : small_stmt semi_opt NEWLINE""" p[0] = [p[1]] def p_simple_stmt_many(self, p): """simple_stmt : small_stmt semi_small_stmt_list semi_opt NEWLINE""" p[0] = [p[1]] + p[2] def p_small_stmt(self, p): """small_stmt : expr_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | nonlocal_stmt | assert_stmt """ p[0] = p[1] _augassign_op = { "+=": ast.Add, "-=": ast.Sub, "*=": ast.Mult, "@=": ast.MatMult, "/=": ast.Div, "%=": ast.Mod, "//=": ast.FloorDiv, "**=": ast.Pow, "^=": ast.BitXor, "&=": ast.BitAnd, "|=": ast.BitOr, "<<=": ast.LShift, ">>=": ast.RShift, } def p_expr_stmt_testlist_assign(self, p): """expr_stmt : testlist_star_expr equals_yield_expr_or_testlist_list_opt | testlist equals_yield_expr_or_testlist_list_opt """ p1, p2 = p[1], p[2] if isinstance(p1, ast.Tuple): p1 = [p1] if p2 is None and len(p1) == 1: p[0] = self.expr(p1[0]) elif p2 is None: assert False else: for targ in p1: store_ctx(targ) list(map(store_ctx, p2[:-1])) lineno, col = lopen_loc(p1[0]) p[0] = ast.Assign( targets=p1 + p2[:-1], value=p2[-1], lineno=lineno, col_offset=col ) def p_expr_stmt_augassign(self, p): """expr_stmt : testlist_star_expr augassign yield_expr_or_testlist""" p1, p2 = p[1], p[2] if not isinstance(p1, ast.Tuple): p1 = p1[0] store_ctx(p1) op = self._augassign_op[p2] if op is None: self._parse_error( "operation {0!r} not supported".format(p2), self.currloc(lineno=p.lineno, column=p.lexpos), ) p[0] = ast.AugAssign( target=p1, op=op(), value=p[3], lineno=p1.lineno, col_offset=p1.col_offset ) def store_star_expr(self, p1, p2, targs, rhs): """Stores complex unpacking statements that target *x variables.""" p1 = [] if p1 is None else p1 if isinstance(p1, ast.Tuple): p1 = [p1] for targ in p1: store_ctx(targ) store_ctx(p2) for targ in targs: store_ctx(targ) p1.append(p2) p1.extend(targs) p1 = [ ast.Tuple( elts=p1, ctx=ast.Store(), lineno=p1[0].lineno, col_offset=p1[0].col_offset, ) ] p0 = ast.Assign( targets=p1, value=rhs, lineno=p1[0].lineno, col_offset=p1[0].col_offset ) return p0 def p_expr_stmt_star5(self, p): """expr_stmt : test_comma_list_opt star_expr comma_test_list equals_yield_expr_or_testlist""" targs, rhs = p[3], p[4][0] p[0] = self.store_star_expr(p[1], p[2], targs, rhs) def p_expr_stmt_star6(self, p): """expr_stmt : test_comma_list_opt star_expr comma_opt test_comma_list_opt equals_yield_expr_or_testlist""" targs, rhs = (p[4] or []), p[5][0] p[0] = self.store_star_expr(p[1], p[2], targs, rhs) def p_test_comma(self, p): """test_comma : test COMMA""" p[0] = [p[1]] def p_comma_opt(self, p): """comma_opt : COMMA | empty """ if len(p) == 2: p[0] = p[1] def p_test_or_star_expr(self, p): """test_or_star_expr : test | star_expr """ p[0] = p[1] def p_comma_test_or_star_expr(self, p): """comma_test_or_star_expr : COMMA test_or_star_expr""" p[0] = [p[2]] def p_testlist_star_expr(self, p): """testlist_star_expr : test_or_star_expr comma_test_or_star_expr_list comma_opt | test_or_star_expr comma_opt """ p1, p2 = p[1], p[2] if p2 is None: p0 = [p1] elif p2 == ",": p0 = [ ast.Tuple( elts=[p1], ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.col_offset, ) ] else: p0 = [ ast.Tuple( elts=[p1] + p2, ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.col_offset, ) ] p[0] = p0 def p_augassign(self, p): """augassign : PLUSEQUAL | MINUSEQUAL | TIMESEQUAL | ATEQUAL | DIVEQUAL | MODEQUAL | AMPERSANDEQUAL | PIPEEQUAL | XOREQUAL | LSHIFTEQUAL | RSHIFTEQUAL | POWEQUAL | DOUBLEDIVEQUAL """ p[0] = p[1] def p_yield_expr_or_testlist(self, p): """yield_expr_or_testlist : yield_expr | testlist """ p[0] = p[1] def p_equals_yield_expr_or_testlist(self, p): """equals_yield_expr_or_testlist : EQUALS yield_expr_or_testlist""" p[0] = [p[2]] # # For normal assignments, additional restrictions enforced # by the interpreter # def p_del_stmt(self, p): """del_stmt : del_tok exprlist""" p1 = p[1] p2 = p[2] for targ in p2: del_ctx(targ) p0 = ast.Delete( targets=p2, ctx=ast.Del(), lineno=p1.lineno, col_offset=p1.lexpos ) p[0] = p0 def p_pass_stmt(self, p): """pass_stmt : PASS""" p[0] = ast.Pass(lineno=self.lineno, col_offset=self.col) def p_flow_stmt(self, p): """flow_stmt : break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt """ p[0] = p[1] def p_break_stmt(self, p): """break_stmt : BREAK""" p[0] = ast.Break(lineno=self.lineno, col_offset=self.col) def p_continue_stmt(self, p): """continue_stmt : CONTINUE""" p[0] = ast.Continue(lineno=self.lineno, col_offset=self.col) def p_return_stmt(self, p): """return_stmt : return_tok testlist_opt""" p1 = p[1] p[0] = ast.Return(value=p[2], lineno=p1.lineno, col_offset=p1.lexpos) def p_yield_stmt(self, p): """yield_stmt : yield_expr""" p[0] = self.expr(p[1]) def p_raise_stmt_r1(self, p): """raise_stmt : raise_tok""" p1 = p[1] p[0] = ast.Raise(exc=None, cause=None, lineno=p1.lineno, col_offset=p1.lexpos) def p_raise_stmt_r2(self, p): """raise_stmt : raise_tok test""" p1 = p[1] p[0] = ast.Raise(exc=p[2], cause=None, lineno=p1.lineno, col_offset=p1.lexpos) def p_raise_stmt_r3(self, p): """raise_stmt : raise_tok test FROM test""" p1 = p[1] p[0] = ast.Raise(exc=p[2], cause=p[4], lineno=p1.lineno, col_offset=p1.lexpos) def p_import_stmt(self, p): """import_stmt : import_name | import_from """ p[0] = p[1] def p_import_name(self, p): """import_name : import_tok dotted_as_names """ p1 = p[1] p[0] = ast.Import(names=p[2], lineno=p1.lineno, col_offset=p1.lexpos) def p_import_from_pre_f3(self, p): """import_from_pre : from_tok period_or_ellipsis_list""" p1 = p[1] p[0] = (p[2], p1.lineno, p1.lexpos) def p_import_from_pre_f4(self, p): """import_from_pre : from_tok period_or_ellipsis_list_opt dotted_name""" p1, p2, p3 = p[1], p[2], p[3] p0 = p3 if p2 is None else p2 + p3 p[0] = (p0, p1.lineno, p1.lexpos) def p_import_from_post_times(self, p): """import_from_post : TIMES""" p[0] = [ast.alias(name="*", asname=None)] def p_import_from_post_as(self, p): """import_from_post : import_as_names""" p[0] = p[1] def p_import_from_post_paren(self, p): """import_from_post : LPAREN import_as_names RPAREN""" p[0] = p[2] def p_import_from(self, p): """import_from : import_from_pre IMPORT import_from_post""" # note below: the ('.' | '...') is necessary because '...' is # tokenized as ELLIPSIS p1, lineno, col = p[1] mod = p1.lstrip(".") lvl = len(p1) - len(mod) mod = mod or None p[0] = ast.ImportFrom( module=mod, names=p[3], level=lvl, lineno=lineno, col_offset=col ) def p_period_or_ellipsis(self, p): """period_or_ellipsis : PERIOD | ELLIPSIS """ p[0] = p[1] def p_as_name(self, p): """as_name : AS NAME""" p[0] = p[2] def p_import_as_name(self, p): """import_as_name : NAME as_name_opt""" p[0] = ast.alias(name=p[1], asname=p[2]) def p_comma_import_as_name(self, p): """comma_import_as_name : COMMA import_as_name """ p[0] = [p[2]] def p_dotted_as_name(self, p): """dotted_as_name : dotted_name as_name_opt""" p0 = ast.alias(name=p[1], asname=p[2]) p[0] = p0 def p_comma_dotted_as_name(self, p): """comma_dotted_as_name : COMMA dotted_as_name""" p[0] = [p[2]] def p_import_as_names(self, p): """import_as_names : import_as_name comma_import_as_name_list_opt comma_opt """ p1, p2 = p[1], p[2] p0 = [p1] if p2 is not None: p0.extend(p2) p[0] = p0 def p_dotted_as_names(self, p): """dotted_as_names : dotted_as_name comma_dotted_as_name_list_opt""" p1, p2 = p[1], p[2] p0 = [p1] if p2 is not None: p0.extend(p2) p[0] = p0 def p_period_name(self, p): """period_name : PERIOD NAME""" p[0] = p[1] + p[2] def p_dotted_name(self, p): """dotted_name : NAME | NAME period_name_list """ p[0] = p[1] if len(p) == 2 else p[1] + p[2] def p_comma_name(self, p): """comma_name : COMMA NAME""" p[0] = [p[2]] def p_global_stmt(self, p): """global_stmt : global_tok NAME comma_name_list_opt""" p1, p2, p3 = p[1], p[2], p[3] names = [p2] if p3 is not None: names += p3 p[0] = ast.Global(names=names, lineno=p1.lineno, col_offset=p1.lexpos) def p_nonlocal_stmt(self, p): """nonlocal_stmt : nonlocal_tok NAME comma_name_list_opt""" p1, p2, p3 = p[1], p[2], p[3] names = [p2] if p3 is not None: names += p3 p[0] = ast.Nonlocal(names=names, lineno=p1.lineno, col_offset=p1.lexpos) def p_comma_test(self, p): """comma_test : COMMA test""" p[0] = [p[2]] def p_assert_stmt(self, p): """assert_stmt : assert_tok test comma_test_opt""" p1, p2, p3 = p[1], p[2], p[3] if p3 is not None: if len(p3) != 1: assert False p3 = p3[0] p[0] = ast.Assert(test=p2, msg=p3, lineno=p1.lineno, col_offset=p1.lexpos) def p_compound_stmt(self, p): """compound_stmt : if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated """ p[0] = p[1] def p_elif_part(self, p): """elif_part : ELIF test COLON suite""" p2 = p[2] p[0] = [ ast.If( test=p2, body=p[4], orelse=[], lineno=p2.lineno, col_offset=p2.col_offset, ) ] def p_else_part(self, p): """else_part : ELSE COLON suite""" p[0] = p[3] def p_if_stmt(self, p): """if_stmt : if_tok test COLON suite elif_part_list_opt | if_tok test COLON suite elif_part_list_opt else_part """ p1 = p[1] lastif = ast.If( test=p[2], body=p[4], orelse=[], lineno=p1.lineno, col_offset=p1.lexpos ) p0 = [lastif] p5 = p[5] p6 = p[6] if len(p) > 6 else [] if p5 is not None: for elseif in p5: lastif.orelse.append(elseif) lastif = elseif lastif.orelse = p6 p[0] = p0 def p_while_stmt(self, p): """while_stmt : WHILE test COLON suite | WHILE test COLON suite else_part """ p5 = p[5] if len(p) > 5 else [] p[0] = [ ast.While( test=p[2], body=p[4], orelse=p5, lineno=self.lineno, col_offset=self.col ) ] def p_for_stmt(self, p): """for_stmt : for_tok exprlist IN testlist COLON suite | for_tok exprlist IN testlist COLON suite else_part """ p1, p2 = p[1], p[2] p7 = p[7] if len(p) > 7 else [] if len(p2) == 1: p2 = p2[0] store_ctx(p2) else: for x in p2: store_ctx(x) p2 = ast.Tuple( elts=p2, ctx=ast.Store(), lineno=p2[0].lineno, col_offset=p2[0].col_offset, ) p[0] = [ ast.For( target=p2, iter=p[4], body=p[6], orelse=p7, lineno=p1.lineno, col_offset=p1.lexpos, ) ] def p_except_part(self, p): """except_part : except_clause COLON suite""" p0 = p[1] p0.body = p[3] p[0] = [p0] def p_finally_part(self, p): """finally_part : FINALLY COLON suite""" p[0] = p[3] def p_try_stmt_t5(self, p): """try_stmt : try_tok COLON suite finally_part""" p1 = p[1] p[0] = [ ast.Try( body=p[3], handlers=[], orelse=[], finalbody=p[4], lineno=p1.lineno, col_offset=p1.lexpos, ) ] def p_try_stmt_t6(self, p): """try_stmt : try_tok COLON suite except_part_list finally_part_opt""" p1 = p[1] p[0] = [ ast.Try( body=p[3], handlers=p[4], orelse=[], finalbody=([] if p[5] is None else p[5]), lineno=p1.lineno, col_offset=p1.lexpos, ) ] def p_try_stmt_t7(self, p): """try_stmt : try_tok COLON suite except_part_list else_part finally_part_opt""" p1 = p[1] p[0] = [ ast.Try( body=p[3], handlers=p[4], orelse=([] if p[5] is None else p[5]), finalbody=([] if p[6] is None else p[6]), lineno=p1.lineno, col_offset=p1.lexpos, ) ] def p_with_stmt_w5(self, p): """with_stmt : with_tok with_item COLON suite""" p1 = p[1] p[0] = [ ast.With(items=[p[2]], body=p[4], lineno=p1.lineno, col_offset=p1.lexpos) ] def p_with_stmt_p6(self, p): """with_stmt : with_tok with_item comma_with_item_list COLON suite""" p1 = p[1] p[0] = [ ast.With( items=[p[2]] + p[3], body=p[5], lineno=p1.lineno, col_offset=p1.lexpos ) ] def p_with_bang_stmt_single_suite(self, p): """with_stmt : with_tok BANG with_item rawsuite""" p1, p3, p4 = p[1], p[3], p[4] expr = p3.context_expr l, c = expr.lineno, expr.col_offset gblcall = xonsh_call("globals", [], lineno=l, col=c) loccall = xonsh_call("locals", [], lineno=l, col=c) margs = [expr, p4, gblcall, loccall] p3.context_expr = xonsh_call("__xonsh__.enter_macro", margs, lineno=l, col=c) body = [ast.Pass(lineno=p4.lineno, col_offset=p4.col_offset)] p[0] = [ast.With(items=[p3], body=body, lineno=p1.lineno, col_offset=p1.lexpos)] def p_with_bang_stmt_many_suite(self, p): """with_stmt : with_tok BANG with_item comma_with_item_list rawsuite""" p1, p3, p4, p5 = p[1], p[3], p[4], p[5] items = [p3] + p4 for item in items: expr = item.context_expr l, c = expr.lineno, expr.col_offset gblcall = xonsh_call("globals", [], lineno=l, col=c) loccall = xonsh_call("locals", [], lineno=l, col=c) margs = [expr, p5, gblcall, loccall] item.context_expr = xonsh_call( "__xonsh__.enter_macro", margs, lineno=l, col=c ) body = [ast.Pass(lineno=p5.lineno, col_offset=p5.col_offset)] p[0] = [ ast.With(items=items, body=body, lineno=p1.lineno, col_offset=p1.lexpos) ] def p_as_expr(self, p): """as_expr : AS expr""" p2 = p[2] store_ctx(p2) p[0] = p2 def p_with_item(self, p): """with_item : test | test as_expr """ p2 = p[2] if len(p) > 2 else None p[0] = ast.withitem(context_expr=p[1], optional_vars=p2) def p_comma_with_item(self, p): """comma_with_item : COMMA with_item""" p[0] = [p[2]] def p_except_clause_e2(self, p): """except_clause : except_tok""" p1 = p[1] p[0] = ast.ExceptHandler( type=None, name=None, lineno=p1.lineno, col_offset=p1.lexpos ) def p_except_clause(self, p): """except_clause : except_tok test as_name_opt""" p1 = p[1] p[0] = ast.ExceptHandler( type=p[2], name=p[3], lineno=p1.lineno, col_offset=p1.lexpos ) def p_suite(self, p): """suite : simple_stmt | NEWLINE INDENT stmt_list DEDENT """ p[0] = p[1] if len(p) == 2 else p[3] def p_rawsuite_indent(self, p): """rawsuite : COLON NEWLINE indent_tok nodedent dedent_tok""" p3, p5 = p[3], p[5] beg = (p3.lineno, p3.lexpos) end = (p5.lineno, p5.lexpos) s = self.source_slice(beg, end) s = textwrap.dedent(s) p[0] = ast.Str(s=s, lineno=beg[0], col_offset=beg[1]) def p_rawsuite_simple_stmt(self, p): """rawsuite : colon_tok nonewline newline_tok""" p1, p3 = p[1], p[3] beg = (p1.lineno, p1.lexpos + 1) end = (p3.lineno, p3.lexpos) s = self.source_slice(beg, end).strip() p[0] = ast.Str(s=s, lineno=beg[0], col_offset=beg[1]) def _attach_nodedent_base_rules(self): toks = set(self.tokens) toks.remove("DEDENT") ts = "\n | ".join(sorted(toks)) doc = "nodedent : " + ts + "\n" self.p_nodedent_base.__func__.__doc__ = doc def p_nodedent_base(self, p): # see above attachment function pass def p_nodedent_any(self, p): """nodedent : INDENT any_dedent_toks DEDENT""" pass def p_nodedent_many(self, p): """nodedent : nodedent nodedent""" pass def p_any_dedent_tok(self, p): """any_dedent_tok : nodedent | DEDENT """ pass def p_any_dedent_toks(self, p): """any_dedent_toks : any_dedent_tok | any_dedent_toks any_dedent_tok """ pass def _attach_nonewline_base_rules(self): toks = set(self.tokens) toks -= { "NEWLINE", "LPAREN", "RPAREN", "LBRACE", "RBRACE", "LBRACKET", "RBRACKET", "AT_LPAREN", "BANG_LPAREN", "BANG_LBRACKET", "DOLLAR_LPAREN", "DOLLAR_LBRACE", "DOLLAR_LBRACKET", "ATDOLLAR_LPAREN", } ts = "\n | ".join(sorted(toks)) doc = "nonewline : " + ts + "\n" self.p_nonewline_base.__func__.__doc__ = doc def p_nonewline_base(self, p): # see above attachment function pass def p_nonewline_any(self, p): """nonewline : any_nested_raw""" pass def p_nonewline_many(self, p): """nonewline : nonewline nonewline""" pass def p_test_ol(self, p): """test : or_test | lambdef """ p[0] = p[1] def p_test_o5(self, p): """test : or_test IF or_test ELSE test""" p[0] = ast.IfExp( test=p[3], body=p[1], orelse=p[5], lineno=self.lineno, col_offset=self.col ) def p_test_nocond(self, p): """test_nocond : or_test | lambdef_nocond """ p[0] = p[1] def p_lambdef(self, p): """lambdef : lambda_tok varargslist_opt COLON test""" p1, p2, p4 = p[1], p[2], p[4] if p2 is None: args = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[], ) else: args = p2 p0 = ast.Lambda(args=args, body=p4, lineno=p1.lineno, col_offset=p1.lexpos) p[0] = p0 def p_lambdef_nocond(self, p): """lambdef_nocond : LAMBDA varargslist_opt COLON test_nocond""" assert False def p_or_test(self, p): """or_test : and_test or_and_test_list_opt""" p1, p2 = p[1], p[2] if p2 is None: p0 = p1 elif len(p2) == 2: lineno, col = lopen_loc(p1) p0 = ast.BoolOp(op=p2[0], values=[p1, p2[1]], lineno=lineno, col_offset=col) else: lineno, col = lopen_loc(p1) p0 = ast.BoolOp( op=p2[0], values=[p[1]] + p2[1::2], lineno=lineno, col_offset=col ) p[0] = p0 def p_or_and_test(self, p): """or_and_test : OR and_test""" p[0] = [ast.Or(), p[2]] def p_and_test(self, p): """and_test : not_test and_not_test_list_opt""" p1, p2 = p[1], p[2] if p2 is None: p0 = p1 elif len(p2) == 2: lineno, col = lopen_loc(p1) p0 = ast.BoolOp(op=p2[0], values=[p1, p2[1]], lineno=lineno, col_offset=col) else: lineno, col = lopen_loc(p1) p0 = ast.BoolOp( op=p2[0], values=[p1] + p2[1::2], lineno=lineno, col_offset=col ) p[0] = p0 def p_and_not_test(self, p): """and_not_test : AND not_test""" p[0] = [ast.And(), p[2]] def p_not_test_not(self, p): """not_test : NOT not_test""" p[0] = ast.UnaryOp( op=ast.Not(), operand=p[2], lineno=self.lineno, col_offset=self.col ) def p_not_test(self, p): """not_test : comparison""" p[0] = p[1] def p_comparison(self, p): """comparison : expr comp_op_expr_list_opt""" p1, p2 = p[1], p[2] if p2 is None: p0 = p1 else: p0 = ast.Compare( left=p1, ops=p2[::2], comparators=p2[1::2], lineno=p1.lineno, col_offset=p1.col_offset, ) p[0] = p0 def p_comp_op_expr(self, p): """comp_op_expr : comp_op expr""" p[0] = [p[1], p[2]] _comp_ops = { "<": ast.Lt, ">": ast.Gt, "==": ast.Eq, ">=": ast.GtE, "<=": ast.LtE, "!=": ast.NotEq, "in": ast.In, ("not", "in"): ast.NotIn, "is": ast.Is, ("is", "not"): ast.IsNot, } def p_comp_op_monograph(self, p): """comp_op : LT | GT | EQ | GE | LE | NE | IN | IS """ p[0] = self._comp_ops[p[1]]() def p_comp_op_digraph(self, p): """comp_op : NOT IN | IS NOT """ p[0] = self._comp_ops[(p[1], p[2])]() def p_star_expr(self, p): """star_expr : times_tok expr""" p1 = p[1] p[0] = ast.Starred( value=p[2], ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.lexpos ) def _binop_combine(self, p1, p2): """Combines binary operations""" if p2 is None: p0 = p1 elif isinstance(p2, ast.BinOp): p2.left = p1 p0 = p2 elif isinstance(p2, Sequence) and isinstance(p2[0], ast.BinOp): p0 = p2[0] p0.left = p1 p0.lineno, p0.col_offset = lopen_loc(p1) for bop in p2[1:]: locer = p1 if p0.left is p1 else p0 bop.left = p0 p0.lineno, p0.col_offset = lopen_loc(locer) p0 = bop else: p0 = p1 + p2 return p0 def p_expr(self, p): """expr : xor_expr | xor_expr pipe_xor_expr_list """ p[0] = self._binop_combine(p[1], p[2] if len(p) > 2 else None) def p_pipe_xor_expr(self, p): """pipe_xor_expr : pipe_tok xor_expr""" p1 = p[1] p[0] = [ ast.BinOp( left=None, op=ast.BitOr(), right=p[2], lineno=p1.lineno, col_offset=p1.lexpos, ) ] def p_xor_expr(self, p): """xor_expr : and_expr xor_and_expr_list_opt""" p[0] = self._binop_combine(p[1], p[2]) def p_xor_and_expr(self, p): """xor_and_expr : xor_tok and_expr""" p1 = p[1] p[0] = [ ast.BinOp( left=None, op=ast.BitXor(), right=p[2], lineno=p1.lineno, col_offset=p1.lexpos, ) ] def p_and_expr(self, p): """and_expr : shift_expr ampersand_shift_expr_list_opt""" p[0] = self._binop_combine(p[1], p[2]) def p_ampersand_shift_expr(self, p): """ampersand_shift_expr : ampersand_tok shift_expr""" p1 = p[1] p[0] = [ ast.BinOp( left=None, op=ast.BitAnd(), right=p[2], lineno=p1.lineno, col_offset=p1.lexpos, ) ] def p_shift_expr(self, p): """shift_expr : arith_expr shift_arith_expr_list_opt""" p[0] = self._binop_combine(p[1], p[2]) def p_shift_arith_expr(self, p): """shift_arith_expr : lshift_tok arith_expr | rshift_tok arith_expr """ p1 = p[1] op = ast.LShift() if p1.value == "<<" else ast.RShift() p[0] = [ ast.BinOp( left=None, op=op, right=p[2], lineno=p1.lineno, col_offset=p1.lexpos ) ] def p_arith_expr_single(self, p): """arith_expr : term""" p[0] = p[1] def p_arith_expr_many(self, p): """arith_expr : term pm_term_list""" p1, p2 = p[1], p[2] if len(p2) == 2: lineno, col = lopen_loc(p1) p0 = ast.BinOp( left=p1, op=p2[0], right=p2[1], lineno=lineno, col_offset=col ) else: left = p1 for op, right in zip(p2[::2], p2[1::2]): locer = left if left is p1 else op lineno, col = lopen_loc(locer) left = ast.BinOp( left=left, op=op, right=right, lineno=lineno, col_offset=col ) p0 = left p[0] = p0 _term_binops = { "+": ast.Add, "-": ast.Sub, "*": ast.Mult, "@": ast.MatMult, "/": ast.Div, "%": ast.Mod, "//": ast.FloorDiv, } def p_pm_term(self, p): """pm_term : plus_tok term | minus_tok term """ p1 = p[1] op = self._term_binops[p1.value](lineno=p1.lineno, col_offset=p1.lexpos) p[0] = [op, p[2]] def p_term(self, p): """term : factor op_factor_list_opt""" p1, p2 = p[1], p[2] if p2 is None: p0 = p1 elif len(p2) == 2: lineno, col = lopen_loc(p1) p0 = ast.BinOp( left=p1, op=p2[0], right=p2[1], lineno=lineno, col_offset=col ) else: left = p1 for op, right in zip(p2[::2], p2[1::2]): locer = left if left is p1 else op lineno, col = lopen_loc(locer) left = ast.BinOp( left=left, op=op, right=right, lineno=lineno, col_offset=col ) p0 = left p[0] = p0 def p_op_factor(self, p): """op_factor : times_tok factor | at_tok factor | divide_tok factor | mod_tok factor | doublediv_tok factor """ p1 = p[1] op = self._term_binops[p1.value] if op is None: self._parse_error( "operation {0!r} not supported".format(p1), self.currloc(lineno=p.lineno, column=p.lexpos), ) p[0] = [op(lineno=p1.lineno, col_offset=p1.lexpos), p[2]] _factor_ops = {"+": ast.UAdd, "-": ast.USub, "~": ast.Invert} def p_factor_power(self, p): """factor : power""" p[0] = p[1] def p_factor_unary(self, p): """factor : PLUS factor | MINUS factor | TILDE factor """ op = self._factor_ops[p[1]]() p[0] = ast.UnaryOp(op=op, operand=p[2], lineno=self.lineno, col_offset=self.col) def p_power_atom(self, p): """power : atom_expr""" p[0] = p[1] def p_power(self, p): """power : atom_expr POW factor""" p1 = p[1] p[0] = ast.BinOp( left=p1, op=ast.Pow(), right=p[3], lineno=p1.lineno, col_offset=p1.col_offset, ) def p_yield_expr_or_testlist_comp(self, p): """yield_expr_or_testlist_comp : yield_expr | testlist_comp """ p[0] = p[1] def _list_or_elts_if_not_real_tuple(self, x): if isinstance(x, ast.Tuple) and not ( hasattr(x, "_real_tuple") and x._real_tuple ): rtn = x.elts else: rtn = [x] return rtn def apply_trailers(self, leader, trailers): """Helper function for atom expr.""" if trailers is None: return leader p0 = leader for trailer in trailers: if isinstance(trailer, (ast.Index, ast.Slice, ast.ExtSlice)): p0 = ast.Subscript( value=leader, slice=trailer, ctx=ast.Load(), lineno=leader.lineno, col_offset=leader.col_offset, ) elif isinstance(trailer, Mapping): # call normal functions p0 = ast.Call( func=leader, lineno=leader.lineno, col_offset=leader.col_offset, **trailer ) elif isinstance(trailer, (ast.Tuple, tuple)): # call macro functions l, c = leader.lineno, leader.col_offset gblcall = xonsh_call("globals", [], lineno=l, col=c) loccall = xonsh_call("locals", [], lineno=l, col=c) if isinstance(trailer, tuple): trailer, arglist = trailer margs = [leader, trailer, gblcall, loccall] p0 = xonsh_call("__xonsh__.call_macro", margs, lineno=l, col=c) elif isinstance(trailer, str): if trailer == "?": p0 = xonsh_help(leader, lineno=leader.lineno, col=leader.col_offset) elif trailer == "??": p0 = xonsh_superhelp( leader, lineno=leader.lineno, col=leader.col_offset ) else: p0 = ast.Attribute( value=leader, attr=trailer, ctx=ast.Load(), lineno=leader.lineno, col_offset=leader.col_offset, ) else: assert False leader = p0 return p0 def p_atom_expr(self, p): """atom_expr : atom trailer_list_opt""" p[0] = self.apply_trailers(p[1], p[2]) # # Atom rules! (So does Adam!) # def p_atom_lparen(self, p): """atom : lparen_tok yield_expr_or_testlist_comp_opt RPAREN""" p1, p2 = p[1], p[2] p1, p1_tok = p1.value, p1 if p2 is None: # empty container atom p0 = ast.Tuple( elts=[], ctx=ast.Load(), lineno=self.lineno, col_offset=self.col ) p0._real_tuple = True elif isinstance(p2, ast.AST): p0 = p2 p0._lopen_lineno, p0._lopen_col = p1_tok.lineno, p1_tok.lexpos p0._real_tuple = True elif len(p2) == 1 and isinstance(p2[0], ast.AST): p0 = p2[0] p0._lopen_lineno, p0._lopen_col = p1_tok.lineno, p1_tok.lexpos else: self.p_error(p) p[0] = p0 def p_atom_lbraket(self, p): """atom : lbracket_tok testlist_comp_opt RBRACKET""" p1, p2 = p[1], p[2] p1, p1_tok = p1.value, p1 if p2 is None: p0 = ast.List( elts=[], ctx=ast.Load(), lineno=self.lineno, col_offset=self.col ) elif isinstance(p2, ast.GeneratorExp): p0 = ast.ListComp( elt=p2.elt, generators=p2.generators, lineno=p2.lineno, col_offset=p2.col_offset, ) else: if isinstance(p2, ast.Tuple): if hasattr(p2, "_real_tuple") and p2._real_tuple: elts = [p2] else: elts = p2.elts else: elts = [p2] p0 = ast.List( elts=elts, ctx=ast.Load(), lineno=p1_tok.lineno, col_offset=p1_tok.lexpos, ) p[0] = p0 def p_atom_lbrace(self, p): """atom : lbrace_tok dictorsetmaker_opt RBRACE""" p1, p2 = p[1], p[2] p1, p1_tok = p1.value, p1 if p2 is None: p0 = ast.Dict( keys=[], values=[], ctx=ast.Load(), lineno=self.lineno, col_offset=self.col, ) else: p0 = p2 p0.lineno, p0.col_offset = p1_tok.lineno, p1_tok.lexpos p[0] = p0 def p_atom_ns(self, p): """atom : number | string_literal_list """ p[0] = p[1] def p_atom_name(self, p): """atom : name_tok""" p1 = p[1] p[0] = ast.Name( id=p1.value, ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.lexpos ) def p_atom_ellip(self, p): """atom : ellipsis_tok""" p1 = p[1] p[0] = ast.EllipsisNode(lineno=p1.lineno, col_offset=p1.lexpos) def p_atom_none(self, p): """atom : none_tok""" p1 = p[1] p[0] = ast.NameConstant(value=None, lineno=p1.lineno, col_offset=p1.lexpos) def p_atom_true(self, p): """atom : true_tok""" p1 = p[1] p[0] = ast.NameConstant(value=True, lineno=p1.lineno, col_offset=p1.lexpos) def p_atom_false(self, p): """atom : false_tok""" p1 = p[1] p[0] = ast.NameConstant(value=False, lineno=p1.lineno, col_offset=p1.lexpos) def p_atom_pathsearch(self, p): """atom : SEARCHPATH""" p[0] = xonsh_pathsearch(p[1], pymode=True, lineno=self.lineno, col=self.col) def p_atom_dname(self, p): """atom : DOLLAR_NAME""" p[0] = self._envvar_by_name(p[1][1:], lineno=self.lineno, col=self.col) def p_atom_fistful_of_dollars(self, p): """atom : dollar_lbrace_tok test RBRACE | bang_lparen_tok subproc RPAREN | dollar_lparen_tok subproc RPAREN | bang_lbracket_tok subproc RBRACKET | dollar_lbracket_tok subproc RBRACKET """ p[0] = self._dollar_rules(p) def p_atom_bang_empty_fistful_of_dollars(self, p): """atom : bang_lparen_tok subproc bang_tok RPAREN | dollar_lparen_tok subproc bang_tok RPAREN | bang_lbracket_tok subproc bang_tok RBRACKET | dollar_lbracket_tok subproc bang_tok RBRACKET """ self._append_subproc_bang_empty(p) p[0] = self._dollar_rules(p) def p_atom_bang_fistful_of_dollars(self, p): """atom : bang_lparen_tok subproc bang_tok nocloser rparen_tok | dollar_lparen_tok subproc bang_tok nocloser rparen_tok | bang_lbracket_tok subproc bang_tok nocloser rbracket_tok | dollar_lbracket_tok subproc bang_tok nocloser rbracket_tok """ self._append_subproc_bang(p) p[0] = self._dollar_rules(p) def _attach_nocloser_base_rules(self): toks = set(self.tokens) toks -= { "LPAREN", "RPAREN", "LBRACE", "RBRACE", "LBRACKET", "RBRACKET", "AT_LPAREN", "BANG_LPAREN", "BANG_LBRACKET", "DOLLAR_LPAREN", "DOLLAR_LBRACE", "DOLLAR_LBRACKET", "ATDOLLAR_LPAREN", } ts = "\n | ".join(sorted(toks)) doc = "nocloser : " + ts + "\n" self.p_nocloser_base.__func__.__doc__ = doc def p_nocloser_base(self, p): # see above attachment function pass def p_nocloser_any(self, p): """nocloser : any_nested_raw""" pass def p_nocloser_many(self, p): """nocloser : nocloser nocloser""" pass def p_string_literal(self, p): """string_literal : string_tok""" p1 = p[1] prefix = RE_STRINGPREFIX.match(p1.value).group() if "p" in prefix: value_without_p = prefix.replace("p", "") + p1.value[len(prefix) :] s = ast.Str( s=ast.literal_eval(value_without_p), lineno=p1.lineno, col_offset=p1.lexpos, ) p[0] = xonsh_call( "__xonsh__.path_literal", [s], lineno=p1.lineno, col=p1.lexpos ) elif "f" in prefix or "F" in prefix: s = sub_env_vars(p1.value) s = pyparse(s).body[0].value s = ast.increment_lineno(s, p1.lineno - 1) p[0] = s else: s = ast.literal_eval(p1.value) is_bytes = "b" in prefix or "B" in prefix cls = ast.Bytes if is_bytes else ast.Str p[0] = cls(s=s, lineno=p1.lineno, col_offset=p1.lexpos) def p_string_literal_list(self, p): """string_literal_list : string_literal | string_literal_list string_literal """ if len(p) == 3: p[1].s += p[2].s p[0] = p[1] def p_number(self, p): """number : number_tok""" p1 = p[1] p[0] = ast.Num( n=ast.literal_eval(p1.value.replace("_", "")), lineno=p1.lineno, col_offset=p1.lexpos, ) def p_testlist_comp_comp(self, p): """testlist_comp : test_or_star_expr comp_for""" p1, p2 = p[1], p[2] p[0] = ast.GeneratorExp( elt=p1, generators=p2["comps"], lineno=p1.lineno, col_offset=p1.col_offset ) def p_testlist_comp_comma(self, p): """testlist_comp : test_or_star_expr comma_opt""" p1, p2 = p[1], p[2] if p2 is None: # split out grouping parentheses. p[0] = p1 else: p[0] = ast.Tuple( elts=[p1], ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.col_offset ) def p_testlist_comp_many(self, p): """testlist_comp : test_or_star_expr comma_test_or_star_expr_list comma_opt""" p1, p2 = p[1], p[2] p[0] = ast.Tuple( elts=[p1] + p2, ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.col_offset ) def p_trailer_lparen(self, p): """trailer : LPAREN arglist_opt RPAREN""" p[0] = [p[2] or dict(args=[], keywords=[], starargs=None, kwargs=None)] def p_trailer_bang_lparen(self, p): """trailer : bang_lparen_tok macroarglist_opt rparen_tok | bang_lparen_tok nocomma comma_tok rparen_tok | bang_lparen_tok nocomma comma_tok WS rparen_tok | bang_lparen_tok macroarglist comma_tok rparen_tok | bang_lparen_tok macroarglist comma_tok WS rparen_tok """ p1, p2, p3 = p[1], p[2], p[3] begins = [(p1.lineno, p1.lexpos + 2)] ends = [(p3.lineno, p3.lexpos)] if p2: begins.extend([(x[0], x[1] + 1) for x in p2]) ends = p2 + ends elts = [] for beg, end in zip(begins, ends): s = self.source_slice(beg, end).strip() if not s: if len(begins) == 1: break else: msg = "empty macro arguments not allowed" self._parse_error(msg, self.currloc(*beg)) node = ast.Str(s=s, lineno=beg[0], col_offset=beg[1]) elts.append(node) p0 = ast.Tuple( elts=elts, ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.lexpos ) p[0] = [p0] def p_trailer_p3(self, p): """trailer : LBRACKET subscriptlist RBRACKET | PERIOD NAME """ p[0] = [p[2]] def p_trailer_quest(self, p): """trailer : DOUBLE_QUESTION | QUESTION """ p[0] = [p[1]] def _attach_nocomma_tok_rules(self): toks = set(self.tokens) toks -= { "COMMA", "LPAREN", "RPAREN", "LBRACE", "RBRACE", "LBRACKET", "RBRACKET", "AT_LPAREN", "BANG_LPAREN", "BANG_LBRACKET", "DOLLAR_LPAREN", "DOLLAR_LBRACE", "DOLLAR_LBRACKET", "ATDOLLAR_LPAREN", } ts = "\n | ".join(sorted(toks)) doc = "nocomma_tok : " + ts + "\n" self.p_nocomma_tok.__func__.__doc__ = doc # The following grammar rules are no-ops because we don't need to glue the # source code back together piece-by-piece. Instead, we simply look for # top-level commas and record their positions. With these positions and the # respective positions of the bounding parentheses, we can use the # source_slice() method. This does a much better job of capturing exactly # the source code that was provided. The tokenizer & lexer can be a little # lossy, especially with respect to whitespace. def p_nocomma_tok(self, p): # see attachment function above for docstring pass def p_any_raw_tok(self, p): """any_raw_tok : nocomma | COMMA """ pass def p_any_raw_toks_one(self, p): """any_raw_toks : any_raw_tok""" pass def p_any_raw_toks_many(self, p): """any_raw_toks : any_raw_toks any_raw_tok""" pass def p_nocomma_part_tok(self, p): """nocomma_part : nocomma_tok""" pass def p_any_nested_raw(self, p): """any_nested_raw : LPAREN any_raw_toks_opt RPAREN | LBRACE any_raw_toks_opt RBRACE | LBRACKET any_raw_toks_opt RBRACKET | AT_LPAREN any_raw_toks_opt RPAREN | BANG_LPAREN any_raw_toks_opt RPAREN | BANG_LBRACKET any_raw_toks_opt RBRACKET | DOLLAR_LPAREN any_raw_toks_opt RPAREN | DOLLAR_LBRACE any_raw_toks_opt RBRACE | DOLLAR_LBRACKET any_raw_toks_opt RBRACKET | ATDOLLAR_LPAREN any_raw_toks_opt RPAREN """ pass def p_nocomma_part_any(self, p): """nocomma_part : any_nested_raw""" pass def p_nocomma_base(self, p): """nocomma : nocomma_part""" pass def p_nocomma_append(self, p): """nocomma : nocomma nocomma_part""" pass def p_comma_nocomma(self, p): """comma_nocomma : comma_tok nocomma""" p1 = p[1] p[0] = [(p1.lineno, p1.lexpos)] def p_macroarglist_single(self, p): """macroarglist : nocomma""" p[0] = [] def p_macroarglist_many(self, p): """macroarglist : nocomma comma_nocomma_list""" p[0] = p[2] def p_subscriptlist(self, p): """subscriptlist : subscript comma_subscript_list_opt comma_opt""" p1, p2 = p[1], p[2] if p2 is None: pass elif isinstance(p1, ast.Slice) or any([isinstance(x, ast.Slice) for x in p2]): p1 = ast.ExtSlice(dims=[p1] + p2) else: p1.value = ast.Tuple( elts=[p1.value] + [x.value for x in p2], ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.col_offset, ) p[0] = p1 def p_comma_subscript(self, p): """comma_subscript : COMMA subscript""" p[0] = [p[2]] def p_subscript_test(self, p): """subscript : test""" p1 = p[1] p[0] = ast.Index(value=p1, lineno=p1.lineno, col_offset=p1.col_offset) def p_subscript_tok(self, p): """subscript : test_opt colon_tok test_opt sliceop_opt""" p1 = p[1] if p1 is None: p2 = p[2] lineno, col = p2.lineno, p2.lexpos else: lineno, col = p1.lineno, p1.col_offset p[0] = ast.Slice(lower=p1, upper=p[3], step=p[4], lineno=lineno, col_offset=col) def p_sliceop(self, p): """sliceop : COLON test_opt""" p[0] = p[2] def p_expr_or_star_expr(self, p): """expr_or_star_expr : expr | star_expr """ p[0] = p[1] def p_comma_expr_or_star_expr(self, p): """comma_expr_or_star_expr : COMMA expr_or_star_expr""" p[0] = [p[2]] def p_exprlist_e3(self, p): """exprlist : expr_or_star_expr comma_opt""" p[0] = [p[1]] def p_exprlist_many(self, p): """exprlist : expr_or_star_expr comma_expr_or_star_expr_list comma_opt""" p2 = p[2] p2.insert(0, p[1]) p[0] = p2 def p_testlist_test(self, p): """testlist : test""" p1 = p[1] if isinstance(p1, ast.Tuple) and ( hasattr(p1, "_real_tuple") and p1._real_tuple and p1.elts ): p1.lineno, p1.col_offset = lopen_loc(p1.elts[0]) p[0] = p1 def p_testlist_single(self, p): """testlist : test COMMA""" p1 = p[1] if isinstance(p1, ast.List) or ( isinstance(p1, ast.Tuple) and hasattr(p1, "_real_tuple") and p1._real_tuple ): lineno, col = lopen_loc(p1) p[0] = ast.Tuple( elts=[p1], ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.col_offset ) else: p[0] = ensure_has_elts(p[1]) def p_testlist_many(self, p): """testlist : test comma_test_list COMMA | test comma_test_list """ p1 = p[1] if isinstance(p1, ast.List) or ( isinstance(p1, ast.Tuple) and hasattr(p1, "_real_tuple") and p1._real_tuple ): lineno, col = lopen_loc(p1) p1 = ast.Tuple( elts=[p1], ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.col_offset ) else: p1 = ensure_has_elts(p1) p1.elts += p[2] p[0] = p1 def p_comma_item(self, p): """comma_item : COMMA item""" p[0] = p[2] # # Dict or set maker # def p_dictorsetmaker_t6(self, p): """dictorsetmaker : test COLON test comma_item_list comma_opt""" p1, p4 = p[1], p[4] keys = [p1] vals = [p[3]] for k, v in zip(p4[::2], p4[1::2]): keys.append(k) vals.append(v) lineno, col = lopen_loc(p1) p[0] = ast.Dict( keys=keys, values=vals, ctx=ast.Load(), lineno=lineno, col_offset=col ) def p_dictorsetmaker_i4(self, p): """dictorsetmaker : item comma_item_list comma_opt""" p1, p2 = p[1], p[2] keys = [p1[0]] vals = [p1[1]] for k, v in zip(p2[::2], p2[1::2]): keys.append(k) vals.append(v) lineno, col = lopen_loc(p1[0] or p2[0]) p[0] = ast.Dict( keys=keys, values=vals, ctx=ast.Load(), lineno=lineno, col_offset=col ) def p_dictorsetmaker_t4_dict(self, p): """dictorsetmaker : test COLON testlist""" keys = [p[1]] vals = self._list_or_elts_if_not_real_tuple(p[3]) lineno, col = lopen_loc(p[1]) p[0] = ast.Dict( keys=keys, values=vals, ctx=ast.Load(), lineno=lineno, col_offset=col ) def p_dictorsetmaker_t4_set(self, p): """dictorsetmaker : test_or_star_expr comma_test_or_star_expr_list comma_opt""" p[0] = ast.Set( elts=[p[1]] + p[2], ctx=ast.Load(), lineno=self.lineno, col_offset=self.col ) def p_dictorsetmaker_test_comma(self, p): """dictorsetmaker : test_or_star_expr comma_opt""" elts = self._list_or_elts_if_not_real_tuple(p[1]) p[0] = ast.Set( elts=elts, ctx=ast.Load(), lineno=self.lineno, col_offset=self.col ) def p_dictorsetmaker_testlist(self, p): """dictorsetmaker : testlist""" elts = self._list_or_elts_if_not_real_tuple(p[1]) p[0] = ast.Set( elts=elts, ctx=ast.Load(), lineno=self.lineno, col_offset=self.col ) def p_dictorsetmaker_comp(self, p): """dictorsetmaker : item comp_for | test_or_star_expr comp_for """ p1 = p[1] comps = p[2].get("comps", []) if isinstance(p1, list) and len(p1) == 2: p[0] = ast.DictComp( key=p1[0], value=p1[1], generators=comps, lineno=self.lineno, col_offset=self.col, ) else: p[0] = ast.SetComp( elt=p1, generators=comps, lineno=self.lineno, col_offset=self.col ) def p_classdef(self, p): """classdef : class_tok NAME func_call_opt COLON suite""" p1, p3 = p[1], p[3] b, kw = ([], []) if p3 is None else (p3["args"], p3["keywords"]) c = ast.ClassDef( name=p[2], bases=b, keywords=kw, starargs=None, kwargs=None, body=p[5], decorator_list=[], lineno=p1.lineno, col_offset=p1.lexpos, ) p[0] = [c] def p_comma_argument(self, p): """comma_argument : COMMA argument""" p[0] = [p[2]] def p_comp_iter(self, p): """comp_iter : comp_for | comp_if """ p[0] = p[1] def p_comp_for(self, p): """comp_for : FOR exprlist IN or_test comp_iter_opt""" targs, it, p5 = p[2], p[4], p[5] if len(targs) == 1: targ = targs[0] else: targ = ensure_has_elts(targs) store_ctx(targ) comp = ast.comprehension(target=targ, iter=it, ifs=[]) comps = [comp] p0 = {"comps": comps} if p5 is not None: comps += p5.get("comps", []) comp.ifs += p5.get("if", []) p[0] = p0 def p_comp_if(self, p): """comp_if : IF test_nocond comp_iter_opt""" p2, p3 = p[2], p[3] p0 = {"if": [p2]} if p3 is not None: p0["comps"] = p3.get("comps", []) p[0] = p0 def p_yield_expr(self, p): """yield_expr : yield_tok yield_arg_opt""" p1, p2 = p[1], p[2] if p2 is None: p0 = ast.Yield(value=p2, lineno=p1.lineno, col_offset=p1.lexpos) elif p2["from"]: p0 = ast.YieldFrom(value=p2["val"], lineno=p1.lineno, col_offset=p1.lexpos) else: p0 = ast.Yield(value=p2["val"], lineno=p1.lineno, col_offset=p1.lexpos) p[0] = p0 def p_yield_arg_from(self, p): """yield_arg : FROM test""" p[0] = {"from": True, "val": p[2]} def p_yield_arg_testlist(self, p): """yield_arg : testlist""" p[0] = {"from": False, "val": p[1]} # # subprocess # def _dollar_rules(self, p): """These handle the special xonsh $ shell atoms by looking up in a special __xonsh__.env dictionary injected in the __builtin__. """ lenp = len(p) p1, p2 = p[1], p[2] if isinstance(p1, LexToken): p1, p1_tok = p1.value, p1 lineno, col = p1_tok.lineno, p1_tok.lexpos else: lineno, col = self.lineno, self.col if lenp == 3: # $NAME p0 = self._envvar_by_name(p2, lineno=lineno, col=col) elif p1 == "${": xenv = load_attribute_chain("__xonsh__.env", lineno=lineno, col=col) idx = ast.Index(value=p2) p0 = ast.Subscript( value=xenv, slice=idx, ctx=ast.Load(), lineno=lineno, col_offset=col ) elif p1 == "$(": p0 = xonsh_call( "__xonsh__.subproc_captured_stdout", p2, lineno=lineno, col=col ) elif p1 == "!(": p0 = xonsh_call( "__xonsh__.subproc_captured_object", p2, lineno=lineno, col=col ) elif p1 == "![": p0 = xonsh_call( "__xonsh__.subproc_captured_hiddenobject", p2, lineno=lineno, col=col ) elif p1 == "$[": p0 = xonsh_call("__xonsh__.subproc_uncaptured", p2, lineno=lineno, col=col) else: assert False return p0 def _envvar_getter_by_name(self, var, lineno=None, col=None): xenv = load_attribute_chain("__xonsh__.env", lineno=lineno, col=col) func = ast.Attribute( value=xenv, attr="get", ctx=ast.Load(), lineno=lineno, col_offset=col ) return ast.Call( func=func, args=[ ast.Str(s=var, lineno=lineno, col_offset=col), ast.Str(s="", lineno=lineno, col_offset=col), ], keywords=[], starargs=None, kwargs=None, lineno=lineno, col_offset=col, ) def _envvar_by_name(self, var, lineno=None, col=None): """Looks up a xonsh variable by name.""" xenv = load_attribute_chain("__xonsh__.env", lineno=lineno, col=col) idx = ast.Index(value=ast.Str(s=var, lineno=lineno, col_offset=col)) return ast.Subscript( value=xenv, slice=idx, ctx=ast.Load(), lineno=lineno, col_offset=col ) def _subproc_cliargs(self, args, lineno=None, col=None): """Creates an expression for subprocess CLI arguments.""" cliargs = currlist = empty_list(lineno=lineno, col=col) for arg in args: action = arg._cliarg_action if action == "append": if currlist is None: currlist = empty_list(lineno=lineno, col=col) cliargs = binop( cliargs, ast.Add(), currlist, lineno=lineno, col=col ) currlist.elts.append(arg) elif action == "extend": cliargs = binop(cliargs, ast.Add(), arg, lineno=lineno, col=col) currlist = None elif action == "splitlines": sl = call_split_lines(arg, lineno=lineno, col=col) cliargs = binop(cliargs, ast.Add(), sl, lineno=lineno, col=col) currlist = None elif action == "ensure_list": x = ensure_list_from_str_or_list(arg, lineno=lineno, col=col) cliargs = binop(cliargs, ast.Add(), x, lineno=lineno, col=col) currlist = None else: raise ValueError("action not understood: " + action) del arg._cliarg_action return cliargs def p_pipe(self, p): """pipe : PIPE | WS PIPE | PIPE WS | WS PIPE WS """ p[0] = ast.Str(s="|", lineno=self.lineno, col_offset=self.col) def p_subproc_s2(self, p): """subproc : subproc_atoms | subproc_atoms WS """ p1 = p[1] p[0] = [self._subproc_cliargs(p1, lineno=self.lineno, col=self.col)] def p_subproc_amp(self, p): """subproc : subproc AMPERSAND""" p1 = p[1] p[0] = p1 + [ast.Str(s=p[2], lineno=self.lineno, col_offset=self.col)] def p_subproc_pipe(self, p): """subproc : subproc pipe subproc_atoms | subproc pipe subproc_atoms WS """ p1 = p[1] if len(p1) > 1 and hasattr(p1[-2], "s") and p1[-2].s != "|": msg = "additional redirect following non-pipe redirect" self._parse_error(msg, self.currloc(lineno=self.lineno, column=self.col)) cliargs = self._subproc_cliargs(p[3], lineno=self.lineno, col=self.col) p[0] = p1 + [p[2], cliargs] def p_subproc_atoms_single(self, p): """subproc_atoms : subproc_atom""" p[0] = [p[1]] def p_subproc_atoms_many(self, p): """subproc_atoms : subproc_atoms WS subproc_atom""" p1 = p[1] p1.append(p[3]) p[0] = p1 def p_subproc_atoms_subshell(self, p): """subproc_atoms : lparen_tok any_raw_tok rparen_tok | lparen_tok any_raw_toks rparen_tok """ p1 = p[1] p3 = p[3] l = p1.lineno c = p1.lexpos + 1 subcmd = self.source_slice((l, c), (p3.lineno, p3.lexpos)) subcmd = subcmd.strip() + "\n" p0 = [ ast.Str(s="xonsh", lineno=l, col_offset=c), ast.Str(s="-c", lineno=l, col_offset=c), ast.Str(s=subcmd, lineno=l, col_offset=c), ] for arg in p0: arg._cliarg_action = "append" p[0] = p0 # # Subproc atom rules # def _append_subproc_bang_empty(self, p): """Appends an empty string in subprocess mode to the argument list.""" p3 = p[3] node = ast.Str(s="", lineno=p3.lineno, col_offset=p3.lexpos + 1) p[2][-1].elts.append(node) def _append_subproc_bang(self, p): """Appends the part between ! and the ) or ] in subprocess mode to the argument list. """ p3, p5 = p[3], p[5] beg = (p3.lineno, p3.lexpos + 1) end = (p5.lineno, p5.lexpos) s = self.source_slice(beg, end).strip() node = ast.Str(s=s, lineno=beg[0], col_offset=beg[1]) p[2][-1].elts.append(node) def p_subproc_atom_uncaptured(self, p): """subproc_atom : dollar_lbracket_tok subproc RBRACKET""" p1 = p[1] p0 = xonsh_call( "__xonsh__.subproc_uncaptured", args=p[2], lineno=p1.lineno, col=p1.lexpos ) p0._cliarg_action = "splitlines" p[0] = p0 def p_subproc_atom_uncaptured_bang_empty(self, p): """subproc_atom : dollar_lbracket_tok subproc bang_tok RBRACKET""" self._append_subproc_bang_empty(p) self.p_subproc_atom_uncaptured(p) def p_subproc_atom_uncaptured_bang(self, p): """subproc_atom : dollar_lbracket_tok subproc bang_tok nocloser rbracket_tok""" self._append_subproc_bang(p) self.p_subproc_atom_uncaptured(p) def p_subproc_atom_captured_stdout(self, p): """subproc_atom : dollar_lparen_tok subproc RPAREN""" p1 = p[1] p0 = xonsh_call( "__xonsh__.subproc_captured_stdout", args=p[2], lineno=p1.lineno, col=p1.lexpos, ) p0._cliarg_action = "append" p[0] = p0 def p_subproc_atom_captured_stdout_bang_empty(self, p): """subproc_atom : dollar_lparen_tok subproc bang_tok RPAREN""" self._append_subproc_bang_empty(p) self.p_subproc_atom_captured_stdout(p) def p_subproc_atom_captured_stdout_bang(self, p): """subproc_atom : dollar_lparen_tok subproc bang_tok nocloser rparen_tok""" self._append_subproc_bang(p) self.p_subproc_atom_captured_stdout(p) def p_subproc_atom_pyenv_lookup(self, p): """subproc_atom : dollar_lbrace_tok test RBRACE""" p1 = p[1] lineno, col = p1.lineno, p1.lexpos xenv = load_attribute_chain("__xonsh__.env", lineno=lineno, col=col) func = ast.Attribute( value=xenv, attr="get", ctx=ast.Load(), lineno=lineno, col_offset=col ) p0 = ast.Call( func=func, args=[p[2], ast.Str(s="", lineno=lineno, col_offset=col)], keywords=[], starargs=None, kwargs=None, lineno=lineno, col_offset=col, ) p0._cliarg_action = "append" p[0] = p0 def p_subproc_atom_pyeval(self, p): """subproc_atom : at_lparen_tok testlist_comp RPAREN subproc_arg_part : at_lparen_tok testlist_comp RPAREN """ p1 = p[1] p0 = xonsh_call( "__xonsh__.list_of_strs_or_callables", [p[2]], lineno=p1.lineno, col=p1.lexpos, ) p0._cliarg_action = "extend" p[0] = p0 def p_subproc_atom_subproc_inject(self, p): """subproc_atom : atdollar_lparen_tok subproc RPAREN""" p1 = p[1] p0 = xonsh_call( "__xonsh__.subproc_captured_inject", p[2], lineno=p1.lineno, col=p1.lexpos ) p0._cliarg_action = "extend" p[0] = p0 def p_subproc_atom_subproc_inject_bang_empty(self, p): """subproc_atom : atdollar_lparen_tok subproc bang_tok RPAREN""" self._append_subproc_bang_empty(p) self.p_subproc_atom_subproc_inject(p) def p_subproc_atom_subproc_inject_bang(self, p): """subproc_atom : atdollar_lparen_tok subproc bang_tok nocloser rparen_tok""" self._append_subproc_bang(p) self.p_subproc_atom_subproc_inject(p) def p_subproc_atom_redirect(self, p): """subproc_atom : GT | LT | RSHIFT | IOREDIRECT """ p0 = ast.Str(s=p[1], lineno=self.lineno, col_offset=self.col) p0._cliarg_action = "append" p[0] = p0 def p_subproc_atom_re(self, p): """subproc_atom : SEARCHPATH""" p0 = xonsh_pathsearch(p[1], pymode=False, lineno=self.lineno, col=self.col) p0._cliarg_action = "extend" p[0] = p0 def p_subproc_atom_str(self, p): """subproc_atom : string_literal""" p0 = xonsh_call( "__xonsh__.expand_path", args=[p[1]], lineno=self.lineno, col=self.col ) p0._cliarg_action = "append" p[0] = p0 def p_subproc_atom_arg(self, p): """subproc_atom : subproc_arg""" p1 = p[1] if isinstance(p1, list): # has an expanding function call, such as @(x) p0 = xonsh_call( "__xonsh__.list_of_list_of_strs_outer_product", args=[ensure_has_elts(p1)], lineno=p1[0].lineno, col=p1[0].col_offset, ) p0._cliarg_action = "extend" elif hasglobstar(p1): # globbed literal argument p0 = xonsh_call( "__xonsh__.glob", args=[p1], lineno=p1.lineno, col=p1.col_offset ) p0._cliarg_action = "extend" else: # literal str argument p0 = xonsh_call( "__xonsh__.expand_path", args=[p1], lineno=p1.lineno, col=p1.col_offset ) p0._cliarg_action = "append" p[0] = p0 def p_subproc_arg_single(self, p): """subproc_arg : subproc_arg_part""" p[0] = p[1] def p_subproc_arg_many(self, p): """subproc_arg : subproc_arg subproc_arg_part""" # This glues the string together after parsing p1 = p[1] p2 = p[2] if isinstance(p1, ast.Str) and isinstance(p2, ast.Str): p0 = ast.Str(p1.s + p2.s, lineno=p1.lineno, col_offset=p1.col_offset) elif isinstance(p1, list): if isinstance(p2, list): p1.extend(p2) else: p1.append(p2) p0 = p1 elif isinstance(p2, list): p2.insert(0, p1) p0 = p2 else: p0 = [p1, p2] p[0] = p0 def _attach_subproc_arg_part_rules(self): toks = set(self.tokens) toks -= { "AND", "OR", "NOT", "BANG", "PIPE", "WS", "GT", "LT", "LSHIFT", "RSHIFT", "IOREDIRECT", "SEARCHPATH", "INDENT", "DEDENT", "LPAREN", "RPAREN", "LBRACE", "RBRACE", "LBRACKET", "RBRACKET", "AT_LPAREN", "BANG_LPAREN", "BANG_LBRACKET", "DOLLAR_LPAREN", "DOLLAR_LBRACE", "DOLLAR_LBRACKET", "ATDOLLAR_LPAREN", } ts = "\n | ".join(sorted([t.lower() + "_tok" for t in toks])) doc = "subproc_arg_part : " + ts + "\n" self.p_subproc_arg_part.__func__.__doc__ = doc def p_subproc_arg_part(self, p): # Many tokens cannot be part of this rule, such as $, ', ", () # Use a string atom instead. See above attachment functions p1 = p[1] p[0] = ast.Str(s=p1.value, lineno=p1.lineno, col_offset=p1.lexpos) # # Helpers # def p_test_comma_combine(self, p): """test_comma_list : test comma_test_list | test comma_test_list COMMA """ p2 = p[2] p2.insert(0, p[1]) p[0] = p2 def p_empty(self, p): "empty : " p[0] = None def p_error(self, p): if p is None: self._parse_error("no further code", None) elif p.type == "ERRORTOKEN": if isinstance(p.value, BaseException): raise p.value else: self._parse_error( p.value, self.currloc(lineno=p.lineno, column=p.lexpos) ) else: msg = ("code: {0}".format(p.value),) self._parse_error(msg, self.currloc(lineno=p.lineno, column=p.lexpos))
# -*- coding: utf-8 -*- """Implements the base xonsh parser.""" import os import re import time import textwrap from threading import Thread from ast import parse as pyparse from collections.abc import Iterable, Sequence, Mapping try: from ply import yacc except ImportError: from xonsh.ply.ply import yacc from xonsh import ast from xonsh.ast import has_elts, xonsh_call, load_attribute_chain from xonsh.lexer import Lexer, LexToken from xonsh.platform import PYTHON_VERSION_INFO from xonsh.tokenize import SearchPath, StringPrefix from xonsh.lazyasd import LazyObject from xonsh.parsers.context_check import check_contexts RE_SEARCHPATH = LazyObject(lambda: re.compile(SearchPath), globals(), "RE_SEARCHPATH") RE_STRINGPREFIX = LazyObject( lambda: re.compile(StringPrefix), globals(), "RE_STRINGPREFIX" ) RE_FSTR_ENVVAR = LazyObject( lambda: re.compile(r"\{\s*\$(\w+)"), globals(), "RE_FSTR_ENVVAR" ) class Location(object): """Location in a file.""" def __init__(self, fname, lineno, column=None): """Takes a filename, line number, and optionally a column number.""" self.fname = fname self.lineno = lineno self.column = column def __str__(self): s = "{0}:{1}".format(self.fname, self.lineno) if self.column is not None: s += ":{0}".format(self.column) return s def ensure_has_elts(x, lineno=None, col_offset=None): """Ensures that x is an AST node with elements.""" if not has_elts(x): if not isinstance(x, Iterable): x = [x] lineno = x[0].lineno if lineno is None else lineno col_offset = x[0].col_offset if col_offset is None else col_offset x = ast.Tuple(elts=x, ctx=ast.Load(), lineno=lineno, col_offset=col_offset) return x def empty_list(lineno=None, col=None): """Creates the AST node for an empty list.""" return ast.List(elts=[], ctx=ast.Load(), lineno=lineno, col_offset=col) def binop(x, op, y, lineno=None, col=None): """Creates the AST node for a binary operation.""" lineno = x.lineno if lineno is None else lineno col = x.col_offset if col is None else col return ast.BinOp(left=x, op=op, right=y, lineno=lineno, col_offset=col) def call_split_lines(x, lineno=None, col=None): """Creates the AST node for calling the 'splitlines' attribute of an object, nominally a string. """ return ast.Call( func=ast.Attribute( value=x, attr="splitlines", ctx=ast.Load(), lineno=lineno, col_offset=col ), args=[], keywords=[], starargs=None, kwargs=None, lineno=lineno, col_offset=col, ) def ensure_list_from_str_or_list(x, lineno=None, col=None): """Creates the AST node for the following expression:: [x] if isinstance(x, str) else x Somewhat useful. """ return ast.IfExp( test=ast.Call( func=ast.Name( id="isinstance", ctx=ast.Load(), lineno=lineno, col_offset=col ), args=[x, ast.Name(id="str", ctx=ast.Load(), lineno=lineno, col_offset=col)], keywords=[], starargs=None, kwargs=None, lineno=lineno, col_offset=col, ), body=ast.List(elts=[x], ctx=ast.Load(), lineno=lineno, col_offset=col), orelse=x, lineno=lineno, col_offset=col, ) def xonsh_help(x, lineno=None, col=None): """Creates the AST node for calling the __xonsh__.help() function.""" return xonsh_call("__xonsh__.help", [x], lineno=lineno, col=col) def xonsh_superhelp(x, lineno=None, col=None): """Creates the AST node for calling the __xonsh__.superhelp() function.""" return xonsh_call("__xonsh__.superhelp", [x], lineno=lineno, col=col) def xonsh_pathsearch(pattern, pymode=False, lineno=None, col=None): """Creates the AST node for calling the __xonsh__.pathsearch() function. The pymode argument indicate if it is called from subproc or python mode""" pymode = ast.NameConstant(value=pymode, lineno=lineno, col_offset=col) searchfunc, pattern = RE_SEARCHPATH.match(pattern).groups() pattern = ast.Str(s=pattern, lineno=lineno, col_offset=col) pathobj = False if searchfunc.startswith("@"): func = searchfunc[1:] elif "g" in searchfunc: func = "__xonsh__.globsearch" pathobj = "p" in searchfunc else: func = "__xonsh__.regexsearch" pathobj = "p" in searchfunc func = load_attribute_chain(func, lineno=lineno, col=col) pathobj = ast.NameConstant(value=pathobj, lineno=lineno, col_offset=col) return xonsh_call( "__xonsh__.pathsearch", args=[func, pattern, pymode, pathobj], lineno=lineno, col=col, ) def load_ctx(x): """Recursively sets ctx to ast.Load()""" if not hasattr(x, "ctx"): return x.ctx = ast.Load() if isinstance(x, (ast.Tuple, ast.List)): for e in x.elts: load_ctx(e) elif isinstance(x, ast.Starred): load_ctx(x.value) def store_ctx(x): """Recursively sets ctx to ast.Store()""" if not hasattr(x, "ctx"): return x.ctx = ast.Store() if isinstance(x, (ast.Tuple, ast.List)): for e in x.elts: store_ctx(e) elif isinstance(x, ast.Starred): store_ctx(x.value) def del_ctx(x): """Recursively sets ctx to ast.Del()""" if not hasattr(x, "ctx"): return x.ctx = ast.Del() if isinstance(x, (ast.Tuple, ast.List)): for e in x.elts: del_ctx(e) elif isinstance(x, ast.Starred): del_ctx(x.value) def empty_list_if_newline(x): return [] if x == "\n" else x def lopen_loc(x): """Extracts the line and column number for a node that may have an opening parenthesis, brace, or bracket. """ lineno = x._lopen_lineno if hasattr(x, "_lopen_lineno") else x.lineno col = x._lopen_col if hasattr(x, "_lopen_col") else x.col_offset return lineno, col def hasglobstar(x): """Returns True if a node has literal '*' for globbing.""" if isinstance(x, ast.Str): return "*" in x.s elif isinstance(x, list): for e in x: if hasglobstar(e): return True else: return False else: return False def _repl_sub_env_vars_single(matchobj): return "{__xonsh__.env.detype()['" + matchobj.group(1) + "']" def _repl_sub_env_vars_double(matchobj): return '{__xonsh__.env.detype()["' + matchobj.group(1) + '"]' def sub_env_vars(fstring): """Takes an fstring that may contain environment variables and substitues them for a valid environment lookup call. Roughly, for example, this will take f"{$HOME}" and transform it to be f"{__xonsh__.env.detype()['HOME']}". """ repl = ( _repl_sub_env_vars_single if fstring[-1] == '"' else _repl_sub_env_vars_double ) return RE_FSTR_ENVVAR.sub(repl, fstring) class YaccLoader(Thread): """Thread to load (but not shave) the yacc parser.""" def __init__(self, parser, yacc_kwargs, *args, **kwargs): super().__init__(*args, **kwargs) self.daemon = True self.parser = parser self.yacc_kwargs = yacc_kwargs self.start() def run(self): self.parser.parser = yacc.yacc(**self.yacc_kwargs) class BaseParser(object): """A base class that parses the xonsh language.""" def __init__( self, lexer_optimize=True, lexer_table="xonsh.lexer_table", yacc_optimize=True, yacc_table="xonsh.parser_table", yacc_debug=False, outputdir=None, ): """Parameters ---------- lexer_optimize : bool, optional Set to false when unstable and true when lexer is stable. lexer_table : str, optional Lexer module used when optimized. yacc_optimize : bool, optional Set to false when unstable and true when parser is stable. yacc_table : str, optional Parser module used when optimized. yacc_debug : debug, optional Dumps extra debug info. outputdir : str or None, optional The directory to place generated tables within. Defaults to the root xonsh dir. """ self.lexer = lexer = Lexer() self.tokens = lexer.tokens self._lines = None self.xonsh_code = None self._attach_nocomma_tok_rules() self._attach_nocloser_base_rules() self._attach_nodedent_base_rules() self._attach_nonewline_base_rules() self._attach_subproc_arg_part_rules() opt_rules = [ "newlines", "arglist", "func_call", "rarrow_test", "typedargslist", "equals_test", "colon_test", "tfpdef", "comma_tfpdef_list", "comma_pow_tfpdef", "vfpdef", "comma_vfpdef_list", "comma_pow_vfpdef", "equals_yield_expr_or_testlist_list", "testlist", "as_name", "period_or_ellipsis_list", "comma_import_as_name_list", "comma_dotted_as_name_list", "comma_name_list", "comma_test", "elif_part_list", "finally_part", "varargslist", "or_and_test_list", "and_not_test_list", "comp_op_expr_list", "xor_and_expr_list", "ampersand_shift_expr_list", "shift_arith_expr_list", "op_factor_list", "trailer_list", "testlist_comp", "yield_expr_or_testlist_comp", "dictorsetmaker", "comma_subscript_list", "test", "sliceop", "comp_iter", "yield_arg", "test_comma_list", "macroarglist", "any_raw_toks", ] for rule in opt_rules: self._opt_rule(rule) list_rules = [ "comma_tfpdef", "comma_vfpdef", "semi_small_stmt", "comma_test_or_star_expr", "period_or_ellipsis", "comma_import_as_name", "comma_dotted_as_name", "period_name", "comma_name", "elif_part", "except_part", "comma_with_item", "or_and_test", "and_not_test", "comp_op_expr", "pipe_xor_expr", "xor_and_expr", "ampersand_shift_expr", "shift_arith_expr", "pm_term", "op_factor", "trailer", "comma_subscript", "comma_expr_or_star_expr", "comma_test", "comma_argument", "comma_item", "attr_period_name", "test_comma", "equals_yield_expr_or_testlist", "comma_nocomma", ] for rule in list_rules: self._list_rule(rule) tok_rules = [ "def", "class", "return", "number", "name", "bang", "none", "true", "false", "ellipsis", "if", "del", "assert", "lparen", "lbrace", "lbracket", "string", "times", "plus", "minus", "divide", "doublediv", "mod", "at", "lshift", "rshift", "pipe", "xor", "ampersand", "for", "colon", "import", "except", "nonlocal", "global", "yield", "from", "raise", "with", "dollar_lparen", "dollar_lbrace", "dollar_lbracket", "try", "bang_lparen", "bang_lbracket", "comma", "rparen", "rbracket", "at_lparen", "atdollar_lparen", "indent", "dedent", "newline", "lambda", "ampersandequal", "as", "atdollar", "atequal", "break", "continue", "divequal", "dollar_name", "double_question", "doubledivequal", "elif", "else", "eq", "equals", "errortoken", "finally", "ge", "in", "is", "le", "lshiftequal", "minusequal", "modequal", "ne", "pass", "period", "pipeequal", "plusequal", "pow", "powequal", "question", "rarrow", "rshiftequal", "semi", "tilde", "timesequal", "while", "xorequal", ] for rule in tok_rules: self._tok_rule(rule) yacc_kwargs = dict( module=self, debug=yacc_debug, start="start_symbols", optimize=yacc_optimize, tabmodule=yacc_table, ) if not yacc_debug: yacc_kwargs["errorlog"] = yacc.NullLogger() if outputdir is None: outputdir = os.path.dirname(os.path.dirname(__file__)) yacc_kwargs["outputdir"] = outputdir if yacc_debug: # create parser on main thread self.parser = yacc.yacc(**yacc_kwargs) else: self.parser = None YaccLoader(self, yacc_kwargs) # Keeps track of the last token given to yacc (the lookahead token) self._last_yielded_token = None def reset(self): """Resets for clean parsing.""" self.lexer.reset() self._last_yielded_token = None self._lines = None self.xonsh_code = None def parse(self, s, filename="<code>", mode="exec", debug_level=0): """Returns an abstract syntax tree of xonsh code. Parameters ---------- s : str The xonsh code. filename : str, optional Name of the file. mode : str, optional Execution mode, one of: exec, eval, or single. debug_level : str, optional Debugging level passed down to yacc. Returns ------- tree : AST """ self.reset() self.xonsh_code = s self.lexer.fname = filename while self.parser is None: time.sleep(0.01) # block until the parser is ready tree = self.parser.parse(input=s, lexer=self.lexer, debug=debug_level) if tree is not None: check_contexts(tree) # hack for getting modes right if mode == "single": if isinstance(tree, ast.Expression): tree = ast.Interactive(body=[self.expr(tree.body)]) elif isinstance(tree, ast.Module): tree = ast.Interactive(body=tree.body) return tree def _lexer_errfunc(self, msg, line, column): self._parse_error(msg, self.currloc(line, column)) def _yacc_lookahead_token(self): """Gets the next-to-last and last token seen by the lexer.""" return self.lexer.beforelast, self.lexer.last def _opt_rule(self, rulename): """For a rule name, creates an associated optional rule. '_opt' is appended to the rule name. """ def optfunc(self, p): p[0] = p[1] optfunc.__doc__ = ("{0}_opt : empty\n" " | {0}").format(rulename) optfunc.__name__ = "p_" + rulename + "_opt" setattr(self.__class__, optfunc.__name__, optfunc) def _list_rule(self, rulename): """For a rule name, creates an associated list rule. '_list' is appended to the rule name. """ def listfunc(self, p): p[0] = p[1] if len(p) == 2 else p[1] + p[2] listfunc.__doc__ = ("{0}_list : {0}\n" " | {0}_list {0}").format( rulename ) listfunc.__name__ = "p_" + rulename + "_list" setattr(self.__class__, listfunc.__name__, listfunc) def _tok_rule(self, rulename): """For a rule name, creates a rule that returns the corresponding token. '_tok' is appended to the rule name. """ def tokfunc(self, p): s, t = self._yacc_lookahead_token() uprule = rulename.upper() if s is not None and s.type == uprule: p[0] = s elif t is not None and t.type == uprule: p[0] = t else: raise TypeError("token for {0!r} not found.".format(rulename)) tokfunc.__doc__ = "{0}_tok : {1}".format(rulename, rulename.upper()) tokfunc.__name__ = "p_" + rulename + "_tok" setattr(self.__class__, tokfunc.__name__, tokfunc) def currloc(self, lineno, column=None): """Returns the current location.""" return Location(fname=self.lexer.fname, lineno=lineno, column=column) def expr(self, p): """Creates an expression for a token.""" expr = ast.Expr(value=p, lineno=p.lineno, col_offset=p.col_offset) expr.max_lineno = self.lineno expr.max_col = self.col return expr def token_col(self, t): """Gets ths token column""" return t.lexpos @property def lineno(self): if self.lexer.last is None: return 1 else: return self.lexer.last.lineno @property def col(self): s, t = self._yacc_lookahead_token() if t is not None: if t.type == "NEWLINE": t = s return self.token_col(t) return 0 @property def lines(self): if self._lines is None and self.xonsh_code is not None: self._lines = self.xonsh_code.splitlines(keepends=True) return self._lines def source_slice(self, start, stop): """Gets the original source code from two (line, col) tuples in source-space (i.e. lineno start at 1). """ bline, bcol = start eline, ecol = stop bline -= 1 lines = self.lines[bline:eline] if ecol == 0: explen = eline - bline if explen == len(lines) and explen > 1: lines[-1] = "" else: lines[-1] = lines[-1][:ecol] lines[0] = lines[0][bcol:] return "".join(lines) def _parse_error(self, msg, loc): if self.xonsh_code is None or loc is None: err_line_pointer = "" else: col = loc.column + 1 lines = self.lines if loc.lineno == 0: loc.lineno = len(lines) i = loc.lineno - 1 if 0 <= i < len(lines): err_line = lines[i].rstrip() err_line_pointer = "\n{}\n{: >{}}".format(err_line, "^", col) else: err_line_pointer = "" err = SyntaxError("{0}: {1}{2}".format(loc, msg, err_line_pointer)) err.loc = loc raise err # # Precedence of operators # precedence = ( ("left", "PIPE"), ("left", "XOR"), ("left", "AMPERSAND"), ("left", "EQ", "NE"), ("left", "GT", "GE", "LT", "LE"), ("left", "RSHIFT", "LSHIFT"), ("left", "PLUS", "MINUS"), ("left", "TIMES", "DIVIDE", "DOUBLEDIV", "MOD"), ("left", "POW"), ) # # Grammar as defined by BNF # def p_start_symbols(self, p): """start_symbols : single_input | file_input | eval_input | empty """ p[0] = p[1] def p_single_input(self, p): """single_input : compound_stmt NEWLINE """ p1 = empty_list_if_newline(p[1]) p0 = ast.Interactive(body=p1) p[0] = p0 def p_file_input(self, p): """file_input : file_stmts""" p[0] = ast.Module(body=p[1]) def p_file_stmts_nl(self, p): """file_stmts : newline_or_stmt""" # newline_or_stmt ENDMARKER p[0] = empty_list_if_newline(p[1]) def p_file_stmts_files(self, p): """file_stmts : file_stmts newline_or_stmt""" # file_input newline_or_stmt ENDMARKER p2 = empty_list_if_newline(p[2]) p[0] = p[1] + p2 def p_newline_or_stmt(self, p): """newline_or_stmt : NEWLINE | stmt """ p[0] = p[1] def p_newlines(self, p): """newlines : NEWLINE | newlines NEWLINE """ p[0] = p[1] if len(p) == 2 else p[1] + p[2] def p_eval_input(self, p): """eval_input : testlist newlines_opt """ p1 = p[1] p[0] = ast.Expression(body=p1, lineno=p1.lineno, col_offset=p1.col_offset) def p_func_call(self, p): """func_call : LPAREN arglist_opt RPAREN""" p[0] = p[2] def p_attr_period_name(self, p): """attr_period_name : PERIOD NAME""" p[0] = [p[2]] def p_attr_name_alone(self, p): """attr_name : name_tok""" p1 = p[1] p[0] = ast.Name( id=p1.value, ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.lexpos ) def p_attr_name_with(self, p): """attr_name : name_tok attr_period_name_list""" p1 = p[1] name = ast.Name( id=p1.value, ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.lexpos ) p2 = p[2] p0 = ast.Attribute( value=name, attr=p2[0], ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.lexpos, ) for a in p2[1:]: p0 = ast.Attribute( value=p0, attr=a, ctx=ast.Load(), lineno=p0.lineno, col_offset=p0.col_offset, ) p[0] = p0 def p_decorator_no_call(self, p): """decorator : at_tok attr_name NEWLINE""" p[0] = p[2] def p_decorator_call(self, p): """decorator : at_tok attr_name func_call NEWLINE""" p1, name, p3 = p[1], p[2], p[3] if isinstance(name, ast.Attribute) or (p3 is not None): lineno, col = name.lineno, name.col_offset else: lineno, col = p1.lineno, p1.lexpos if p3 is None: p0 = ast.Call( func=name, args=[], keywords=[], starargs=None, kwargs=None, lineno=lineno, col_offset=col, ) else: p0 = ast.Call(func=name, lineno=lineno, col_offset=col, **p3) p[0] = p0 def p_decorators(self, p): """decorators : decorator | decorators decorator """ p[0] = [p[1]] if len(p) == 2 else p[1] + [p[2]] def p_decorated(self, p): """decorated : decorators classdef_or_funcdef""" p1, p2 = p[1], p[2] targ = p2[0] targ.decorator_list = p1 # this is silly, CPython. This claims a func or class starts on # the line of the first decorator, rather than the 'def' or 'class' # line. However, it retains the original col_offset. targ.lineno = p1[0].lineno # async functions take the col number of the 'def', unless they are # decorated, in which case they have the col of the 'async'. WAT? if hasattr(targ, "_async_tok"): targ.col_offset = targ._async_tok.lexpos del targ._async_tok p[0] = p2 def p_rarrow_test(self, p): """rarrow_test : RARROW test""" p[0] = p[2] def p_funcdef(self, p): """funcdef : def_tok NAME parameters rarrow_test_opt COLON suite""" f = ast.FunctionDef( name=p[2], args=p[3], returns=p[4], body=p[6], decorator_list=[], lineno=p[1].lineno, col_offset=p[1].lexpos, ) p[0] = [f] def p_parameters(self, p): """parameters : LPAREN typedargslist_opt RPAREN""" p2 = p[2] if p2 is None: p2 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[], ) p[0] = p2 def p_equals_test(self, p): """equals_test : EQUALS test""" p[0] = p[2] def p_typedargslist_kwarg(self, p): """typedargslist : POW tfpdef""" p[0] = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[2], defaults=[] ) def p_typedargslist_times4_tfpdef(self, p): """typedargslist : TIMES tfpdef comma_pow_tfpdef_opt""" # *args, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[3], defaults=[] ) self._set_var_args(p0, p[2], None) p[0] = p0 def p_typedargslist_times4_comma(self, p): """typedargslist : TIMES comma_pow_tfpdef""" # *, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[2], defaults=[] ) p[0] = p0 def p_typedargslist_times5_tdpdef(self, p): """typedargslist : TIMES tfpdef comma_tfpdef_list comma_pow_tfpdef_opt""" # *args, x, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[4], defaults=[] ) self._set_var_args(p0, p[2], p[3]) # *args p[0] = p0 def p_typedargslist_times5_comma(self, p): """typedargslist : TIMES comma_tfpdef_list comma_pow_tfpdef_opt""" # *, x, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[3], defaults=[] ) self._set_var_args(p0, None, p[2]) # *args p[0] = p0 def p_typedargslist_t5(self, p): """typedargslist : tfpdef equals_test_opt comma_tfpdef_list_opt comma_opt""" # x p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[] ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) p[0] = p0 def p_typedargslist_t7(self, p): """typedargslist : tfpdef equals_test_opt comma_tfpdef_list_opt comma_opt POW tfpdef""" # x, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[6], defaults=[] ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) p[0] = p0 def p_typedargslist_t8(self, p): """typedargslist : tfpdef equals_test_opt comma_tfpdef_list_opt comma_opt TIMES tfpdef_opt comma_tfpdef_list_opt""" p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[] ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) self._set_var_args(p0, p[6], p[7]) p[0] = p0 def p_typedargslist_t10(self, p): """typedargslist : tfpdef equals_test_opt comma_tfpdef_list_opt comma_opt TIMES tfpdef_opt COMMA POW vfpdef""" # x, *args, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[9], defaults=[] ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) self._set_var_args(p0, p[6], None) p[0] = p0 def p_typedargslist_t11(self, p): """typedargslist : tfpdef equals_test_opt comma_tfpdef_list_opt comma_opt TIMES tfpdef_opt comma_tfpdef_list COMMA POW tfpdef""" # x, *args, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[10], defaults=[], ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) self._set_var_args(p0, p[6], p[7]) p[0] = p0 def p_colon_test(self, p): """colon_test : COLON test""" p[0] = p[2] def p_tfpdef(self, p): """tfpdef : name_tok colon_test_opt""" p1 = p[1] kwargs = {"arg": p1.value, "annotation": p[2]} if PYTHON_VERSION_INFO >= (3, 5, 1): kwargs.update({"lineno": p1.lineno, "col_offset": p1.lexpos}) p[0] = ast.arg(**kwargs) def p_comma_tfpdef_empty(self, p): """comma_tfpdef : COMMA""" p[0] = [] def p_comma_tfpdef_args(self, p): """comma_tfpdef : COMMA tfpdef equals_test_opt""" p[0] = [{"arg": p[2], "default": p[3]}] def p_comma_pow_tfpdef(self, p): """comma_pow_tfpdef : COMMA POW tfpdef""" p[0] = p[3] def _set_args_def(self, argmts, vals, kwargs=False): args, defs = ( (argmts.kwonlyargs, argmts.kw_defaults) if kwargs else (argmts.args, argmts.defaults) ) if vals is None and kwargs: loc = self.currloc(self.lineno, self.col) self._parse_error("named arguments must follow bare *", loc) for v in vals: args.append(v["arg"]) d = v["default"] if kwargs or (d is not None): defs.append(d) def _set_regular_args(self, p0, p1, p2, p3, p4): if p2 is None and p3 is None: # x p0.args.append(p1) elif p2 is not None and p3 is None: # x=42 p0.args.append(p1) p0.defaults.append(p2) elif p2 is None and p3 is not None: # x, y and x, y=42 p0.args.append(p1) self._set_args_def(p0, p3) else: # x=42, y=42 p0.args.append(p1) p0.defaults.append(p2) self._set_args_def(p0, p3) def _set_var_args(self, p0, vararg, kwargs): if vararg is None and kwargs is not None: self._set_args_def(p0, kwargs, kwargs=True) elif vararg is not None and kwargs is None: # *args p0.vararg = vararg elif vararg is not None and kwargs is not None: # *args, x and *args, x, y and *args, x=10 and *args, x=10, y # and *args, x, y=10, and *args, x=42, y=65 p0.vararg = vararg self._set_args_def(p0, kwargs, kwargs=True) else: assert False def p_varargslist_kwargs(self, p): """varargslist : POW vfpdef""" p[0] = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[2], defaults=[] ) def p_varargslist_times4(self, p): """varargslist : TIMES vfpdef_opt comma_pow_vfpdef_opt""" p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[3], defaults=[] ) self._set_var_args(p0, p[2], None) p[0] = p0 def p_varargslist_times5(self, p): """varargslist : TIMES vfpdef_opt comma_vfpdef_list comma_pow_vfpdef_opt""" # *args, x, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[4], defaults=[] ) self._set_var_args(p0, p[2], p[3]) # *args p[0] = p0 def p_varargslist_v5(self, p): """varargslist : vfpdef equals_test_opt comma_vfpdef_list_opt comma_opt""" # x p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[] ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) p[0] = p0 def p_varargslist_v7(self, p): """varargslist : vfpdef equals_test_opt comma_vfpdef_list_opt comma_opt POW vfpdef""" # x, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[6], defaults=[] ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) p[0] = p0 def p_varargslist_v8(self, p): """varargslist : vfpdef equals_test_opt comma_vfpdef_list_opt comma_opt TIMES vfpdef_opt comma_vfpdef_list_opt""" # x, *args p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[] ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) self._set_var_args(p0, p[6], p[7]) p[0] = p0 def p_varargslist_v10(self, p): """varargslist : vfpdef equals_test_opt comma_vfpdef_list_opt comma_opt TIMES vfpdef_opt COMMA POW vfpdef""" # x, *args, **kwargs p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[9], defaults=[] ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) self._set_var_args(p0, p[6], None) p[0] = p0 def p_varargslist_v11(self, p): """varargslist : vfpdef equals_test_opt comma_vfpdef_list_opt comma_opt TIMES vfpdef_opt comma_vfpdef_list COMMA POW vfpdef""" p0 = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=p[10], defaults=[], ) self._set_regular_args(p0, p[1], p[2], p[3], p[4]) self._set_var_args(p0, p[6], p[7]) p[0] = p0 def p_vfpdef(self, p): """vfpdef : name_tok""" p1 = p[1] kwargs = {"arg": p1.value, "annotation": None} if PYTHON_VERSION_INFO >= (3, 5, 1): kwargs.update({"lineno": p1.lineno, "col_offset": p1.lexpos}) p[0] = ast.arg(**kwargs) def p_comma_vfpdef_empty(self, p): """comma_vfpdef : COMMA""" p[0] = [] def p_comma_vfpdef_value(self, p): """comma_vfpdef : COMMA vfpdef equals_test_opt""" p[0] = [{"arg": p[2], "default": p[3]}] def p_comma_pow_vfpdef(self, p): """comma_pow_vfpdef : COMMA POW vfpdef""" p[0] = p[3] def p_stmt(self, p): """stmt : simple_stmt | compound_stmt """ p[0] = p[1] def p_stmt_list(self, p): """stmt_list : stmt | stmt_list stmt """ if len(p) == 2: p[0] = p[1] else: p[0] = p[1] + p[2] def p_semi_opt(self, p): """semi_opt : SEMI | empty """ if len(p) == 2: p[0] = p[1] def p_semi_small_stmt(self, p): """semi_small_stmt : SEMI small_stmt""" p[0] = [p[2]] def p_simple_stmt_single(self, p): """simple_stmt : small_stmt semi_opt NEWLINE""" p[0] = [p[1]] def p_simple_stmt_many(self, p): """simple_stmt : small_stmt semi_small_stmt_list semi_opt NEWLINE""" p[0] = [p[1]] + p[2] def p_small_stmt(self, p): """small_stmt : expr_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | nonlocal_stmt | assert_stmt """ p[0] = p[1] _augassign_op = { "+=": ast.Add, "-=": ast.Sub, "*=": ast.Mult, "@=": ast.MatMult, "/=": ast.Div, "%=": ast.Mod, "//=": ast.FloorDiv, "**=": ast.Pow, "^=": ast.BitXor, "&=": ast.BitAnd, "|=": ast.BitOr, "<<=": ast.LShift, ">>=": ast.RShift, } def p_expr_stmt_testlist_assign(self, p): """expr_stmt : testlist_star_expr equals_yield_expr_or_testlist_list_opt | testlist equals_yield_expr_or_testlist_list_opt """ p1, p2 = p[1], p[2] if isinstance(p1, ast.Tuple): p1 = [p1] if p2 is None and len(p1) == 1: p[0] = self.expr(p1[0]) elif p2 is None: assert False else: for targ in p1: store_ctx(targ) list(map(store_ctx, p2[:-1])) lineno, col = lopen_loc(p1[0]) p[0] = ast.Assign( targets=p1 + p2[:-1], value=p2[-1], lineno=lineno, col_offset=col ) def p_expr_stmt_augassign(self, p): """expr_stmt : testlist_star_expr augassign yield_expr_or_testlist""" p1, p2 = p[1], p[2] if not isinstance(p1, ast.Tuple): p1 = p1[0] store_ctx(p1) op = self._augassign_op[p2] if op is None: self._parse_error( "operation {0!r} not supported".format(p2), self.currloc(lineno=p.lineno, column=p.lexpos), ) p[0] = ast.AugAssign( target=p1, op=op(), value=p[3], lineno=p1.lineno, col_offset=p1.col_offset ) def store_star_expr(self, p1, p2, targs, rhs): """Stores complex unpacking statements that target *x variables.""" p1 = [] if p1 is None else p1 if isinstance(p1, ast.Tuple): p1 = [p1] for targ in p1: store_ctx(targ) store_ctx(p2) for targ in targs: store_ctx(targ) p1.append(p2) p1.extend(targs) p1 = [ ast.Tuple( elts=p1, ctx=ast.Store(), lineno=p1[0].lineno, col_offset=p1[0].col_offset, ) ] p0 = ast.Assign( targets=p1, value=rhs, lineno=p1[0].lineno, col_offset=p1[0].col_offset ) return p0 def p_expr_stmt_star5(self, p): """expr_stmt : test_comma_list_opt star_expr comma_test_list equals_yield_expr_or_testlist""" targs, rhs = p[3], p[4][0] p[0] = self.store_star_expr(p[1], p[2], targs, rhs) def p_expr_stmt_star6(self, p): """expr_stmt : test_comma_list_opt star_expr comma_opt test_comma_list_opt equals_yield_expr_or_testlist""" targs, rhs = (p[4] or []), p[5][0] p[0] = self.store_star_expr(p[1], p[2], targs, rhs) def p_test_comma(self, p): """test_comma : test COMMA""" p[0] = [p[1]] def p_comma_opt(self, p): """comma_opt : COMMA | empty """ if len(p) == 2: p[0] = p[1] def p_test_or_star_expr(self, p): """test_or_star_expr : test | star_expr """ p[0] = p[1] def p_comma_test_or_star_expr(self, p): """comma_test_or_star_expr : COMMA test_or_star_expr""" p[0] = [p[2]] def p_testlist_star_expr(self, p): """testlist_star_expr : test_or_star_expr comma_test_or_star_expr_list comma_opt | test_or_star_expr comma_opt """ p1, p2 = p[1], p[2] if p2 is None: p0 = [p1] elif p2 == ",": p0 = [ ast.Tuple( elts=[p1], ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.col_offset, ) ] else: p0 = [ ast.Tuple( elts=[p1] + p2, ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.col_offset, ) ] p[0] = p0 def p_augassign(self, p): """augassign : PLUSEQUAL | MINUSEQUAL | TIMESEQUAL | ATEQUAL | DIVEQUAL | MODEQUAL | AMPERSANDEQUAL | PIPEEQUAL | XOREQUAL | LSHIFTEQUAL | RSHIFTEQUAL | POWEQUAL | DOUBLEDIVEQUAL """ p[0] = p[1] def p_yield_expr_or_testlist(self, p): """yield_expr_or_testlist : yield_expr | testlist """ p[0] = p[1] def p_equals_yield_expr_or_testlist(self, p): """equals_yield_expr_or_testlist : EQUALS yield_expr_or_testlist""" p[0] = [p[2]] # # For normal assignments, additional restrictions enforced # by the interpreter # def p_del_stmt(self, p): """del_stmt : del_tok exprlist""" p1 = p[1] p2 = p[2] for targ in p2: del_ctx(targ) p0 = ast.Delete( targets=p2, ctx=ast.Del(), lineno=p1.lineno, col_offset=p1.lexpos ) p[0] = p0 def p_pass_stmt(self, p): """pass_stmt : PASS""" p[0] = ast.Pass(lineno=self.lineno, col_offset=self.col) def p_flow_stmt(self, p): """flow_stmt : break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt """ p[0] = p[1] def p_break_stmt(self, p): """break_stmt : BREAK""" p[0] = ast.Break(lineno=self.lineno, col_offset=self.col) def p_continue_stmt(self, p): """continue_stmt : CONTINUE""" p[0] = ast.Continue(lineno=self.lineno, col_offset=self.col) def p_return_stmt(self, p): """return_stmt : return_tok testlist_opt""" p1 = p[1] p[0] = ast.Return(value=p[2], lineno=p1.lineno, col_offset=p1.lexpos) def p_yield_stmt(self, p): """yield_stmt : yield_expr""" p[0] = self.expr(p[1]) def p_raise_stmt_r1(self, p): """raise_stmt : raise_tok""" p1 = p[1] p[0] = ast.Raise(exc=None, cause=None, lineno=p1.lineno, col_offset=p1.lexpos) def p_raise_stmt_r2(self, p): """raise_stmt : raise_tok test""" p1 = p[1] p[0] = ast.Raise(exc=p[2], cause=None, lineno=p1.lineno, col_offset=p1.lexpos) def p_raise_stmt_r3(self, p): """raise_stmt : raise_tok test FROM test""" p1 = p[1] p[0] = ast.Raise(exc=p[2], cause=p[4], lineno=p1.lineno, col_offset=p1.lexpos) def p_import_stmt(self, p): """import_stmt : import_name | import_from """ p[0] = p[1] def p_import_name(self, p): """import_name : import_tok dotted_as_names """ p1 = p[1] p[0] = ast.Import(names=p[2], lineno=p1.lineno, col_offset=p1.lexpos) def p_import_from_pre_f3(self, p): """import_from_pre : from_tok period_or_ellipsis_list""" p1 = p[1] p[0] = (p[2], p1.lineno, p1.lexpos) def p_import_from_pre_f4(self, p): """import_from_pre : from_tok period_or_ellipsis_list_opt dotted_name""" p1, p2, p3 = p[1], p[2], p[3] p0 = p3 if p2 is None else p2 + p3 p[0] = (p0, p1.lineno, p1.lexpos) def p_import_from_post_times(self, p): """import_from_post : TIMES""" p[0] = [ast.alias(name="*", asname=None)] def p_import_from_post_as(self, p): """import_from_post : import_as_names""" p[0] = p[1] def p_import_from_post_paren(self, p): """import_from_post : LPAREN import_as_names RPAREN""" p[0] = p[2] def p_import_from(self, p): """import_from : import_from_pre IMPORT import_from_post""" # note below: the ('.' | '...') is necessary because '...' is # tokenized as ELLIPSIS p1, lineno, col = p[1] mod = p1.lstrip(".") lvl = len(p1) - len(mod) mod = mod or None p[0] = ast.ImportFrom( module=mod, names=p[3], level=lvl, lineno=lineno, col_offset=col ) def p_period_or_ellipsis(self, p): """period_or_ellipsis : PERIOD | ELLIPSIS """ p[0] = p[1] def p_as_name(self, p): """as_name : AS NAME""" p[0] = p[2] def p_import_as_name(self, p): """import_as_name : NAME as_name_opt""" p[0] = ast.alias(name=p[1], asname=p[2]) def p_comma_import_as_name(self, p): """comma_import_as_name : COMMA import_as_name """ p[0] = [p[2]] def p_dotted_as_name(self, p): """dotted_as_name : dotted_name as_name_opt""" p0 = ast.alias(name=p[1], asname=p[2]) p[0] = p0 def p_comma_dotted_as_name(self, p): """comma_dotted_as_name : COMMA dotted_as_name""" p[0] = [p[2]] def p_import_as_names(self, p): """import_as_names : import_as_name comma_import_as_name_list_opt comma_opt """ p1, p2 = p[1], p[2] p0 = [p1] if p2 is not None: p0.extend(p2) p[0] = p0 def p_dotted_as_names(self, p): """dotted_as_names : dotted_as_name comma_dotted_as_name_list_opt""" p1, p2 = p[1], p[2] p0 = [p1] if p2 is not None: p0.extend(p2) p[0] = p0 def p_period_name(self, p): """period_name : PERIOD NAME""" p[0] = p[1] + p[2] def p_dotted_name(self, p): """dotted_name : NAME | NAME period_name_list """ p[0] = p[1] if len(p) == 2 else p[1] + p[2] def p_comma_name(self, p): """comma_name : COMMA NAME""" p[0] = [p[2]] def p_global_stmt(self, p): """global_stmt : global_tok NAME comma_name_list_opt""" p1, p2, p3 = p[1], p[2], p[3] names = [p2] if p3 is not None: names += p3 p[0] = ast.Global(names=names, lineno=p1.lineno, col_offset=p1.lexpos) def p_nonlocal_stmt(self, p): """nonlocal_stmt : nonlocal_tok NAME comma_name_list_opt""" p1, p2, p3 = p[1], p[2], p[3] names = [p2] if p3 is not None: names += p3 p[0] = ast.Nonlocal(names=names, lineno=p1.lineno, col_offset=p1.lexpos) def p_comma_test(self, p): """comma_test : COMMA test""" p[0] = [p[2]] def p_assert_stmt(self, p): """assert_stmt : assert_tok test comma_test_opt""" p1, p2, p3 = p[1], p[2], p[3] if p3 is not None: if len(p3) != 1: assert False p3 = p3[0] p[0] = ast.Assert(test=p2, msg=p3, lineno=p1.lineno, col_offset=p1.lexpos) def p_compound_stmt(self, p): """compound_stmt : if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated """ p[0] = p[1] def p_elif_part(self, p): """elif_part : ELIF test COLON suite""" p2 = p[2] p[0] = [ ast.If( test=p2, body=p[4], orelse=[], lineno=p2.lineno, col_offset=p2.col_offset, ) ] def p_else_part(self, p): """else_part : ELSE COLON suite""" p[0] = p[3] def p_if_stmt(self, p): """if_stmt : if_tok test COLON suite elif_part_list_opt | if_tok test COLON suite elif_part_list_opt else_part """ p1 = p[1] lastif = ast.If( test=p[2], body=p[4], orelse=[], lineno=p1.lineno, col_offset=p1.lexpos ) p0 = [lastif] p5 = p[5] p6 = p[6] if len(p) > 6 else [] if p5 is not None: for elseif in p5: lastif.orelse.append(elseif) lastif = elseif lastif.orelse = p6 p[0] = p0 def p_while_stmt(self, p): """while_stmt : WHILE test COLON suite | WHILE test COLON suite else_part """ p5 = p[5] if len(p) > 5 else [] p[0] = [ ast.While( test=p[2], body=p[4], orelse=p5, lineno=self.lineno, col_offset=self.col ) ] def p_for_stmt(self, p): """for_stmt : for_tok exprlist IN testlist COLON suite | for_tok exprlist IN testlist COLON suite else_part """ p1, p2 = p[1], p[2] p7 = p[7] if len(p) > 7 else [] if len(p2) == 1: p2 = p2[0] store_ctx(p2) else: for x in p2: store_ctx(x) p2 = ast.Tuple( elts=p2, ctx=ast.Store(), lineno=p2[0].lineno, col_offset=p2[0].col_offset, ) p[0] = [ ast.For( target=p2, iter=p[4], body=p[6], orelse=p7, lineno=p1.lineno, col_offset=p1.lexpos, ) ] def p_except_part(self, p): """except_part : except_clause COLON suite""" p0 = p[1] p0.body = p[3] p[0] = [p0] def p_finally_part(self, p): """finally_part : FINALLY COLON suite""" p[0] = p[3] def p_try_stmt_t5(self, p): """try_stmt : try_tok COLON suite finally_part""" p1 = p[1] p[0] = [ ast.Try( body=p[3], handlers=[], orelse=[], finalbody=p[4], lineno=p1.lineno, col_offset=p1.lexpos, ) ] def p_try_stmt_t6(self, p): """try_stmt : try_tok COLON suite except_part_list finally_part_opt""" p1 = p[1] p[0] = [ ast.Try( body=p[3], handlers=p[4], orelse=[], finalbody=([] if p[5] is None else p[5]), lineno=p1.lineno, col_offset=p1.lexpos, ) ] def p_try_stmt_t7(self, p): """try_stmt : try_tok COLON suite except_part_list else_part finally_part_opt""" p1 = p[1] p[0] = [ ast.Try( body=p[3], handlers=p[4], orelse=([] if p[5] is None else p[5]), finalbody=([] if p[6] is None else p[6]), lineno=p1.lineno, col_offset=p1.lexpos, ) ] def p_with_stmt_w5(self, p): """with_stmt : with_tok with_item COLON suite""" p1 = p[1] p[0] = [ ast.With(items=[p[2]], body=p[4], lineno=p1.lineno, col_offset=p1.lexpos) ] def p_with_stmt_p6(self, p): """with_stmt : with_tok with_item comma_with_item_list COLON suite""" p1 = p[1] p[0] = [ ast.With( items=[p[2]] + p[3], body=p[5], lineno=p1.lineno, col_offset=p1.lexpos ) ] def p_with_bang_stmt_single_suite(self, p): """with_stmt : with_tok BANG with_item rawsuite""" p1, p3, p4 = p[1], p[3], p[4] expr = p3.context_expr l, c = expr.lineno, expr.col_offset gblcall = xonsh_call("globals", [], lineno=l, col=c) loccall = xonsh_call("locals", [], lineno=l, col=c) margs = [expr, p4, gblcall, loccall] p3.context_expr = xonsh_call("__xonsh__.enter_macro", margs, lineno=l, col=c) body = [ast.Pass(lineno=p4.lineno, col_offset=p4.col_offset)] p[0] = [ast.With(items=[p3], body=body, lineno=p1.lineno, col_offset=p1.lexpos)] def p_with_bang_stmt_many_suite(self, p): """with_stmt : with_tok BANG with_item comma_with_item_list rawsuite""" p1, p3, p4, p5 = p[1], p[3], p[4], p[5] items = [p3] + p4 for item in items: expr = item.context_expr l, c = expr.lineno, expr.col_offset gblcall = xonsh_call("globals", [], lineno=l, col=c) loccall = xonsh_call("locals", [], lineno=l, col=c) margs = [expr, p5, gblcall, loccall] item.context_expr = xonsh_call( "__xonsh__.enter_macro", margs, lineno=l, col=c ) body = [ast.Pass(lineno=p5.lineno, col_offset=p5.col_offset)] p[0] = [ ast.With(items=items, body=body, lineno=p1.lineno, col_offset=p1.lexpos) ] def p_as_expr(self, p): """as_expr : AS expr""" p2 = p[2] store_ctx(p2) p[0] = p2 def p_with_item(self, p): """with_item : test | test as_expr """ p2 = p[2] if len(p) > 2 else None p[0] = ast.withitem(context_expr=p[1], optional_vars=p2) def p_comma_with_item(self, p): """comma_with_item : COMMA with_item""" p[0] = [p[2]] def p_except_clause_e2(self, p): """except_clause : except_tok""" p1 = p[1] p[0] = ast.ExceptHandler( type=None, name=None, lineno=p1.lineno, col_offset=p1.lexpos ) def p_except_clause(self, p): """except_clause : except_tok test as_name_opt""" p1 = p[1] p[0] = ast.ExceptHandler( type=p[2], name=p[3], lineno=p1.lineno, col_offset=p1.lexpos ) def p_suite(self, p): """suite : simple_stmt | NEWLINE INDENT stmt_list DEDENT """ p[0] = p[1] if len(p) == 2 else p[3] def p_rawsuite_indent(self, p): """rawsuite : COLON NEWLINE indent_tok nodedent dedent_tok""" p3, p5 = p[3], p[5] beg = (p3.lineno, p3.lexpos) end = (p5.lineno, p5.lexpos) s = self.source_slice(beg, end) s = textwrap.dedent(s) p[0] = ast.Str(s=s, lineno=beg[0], col_offset=beg[1]) def p_rawsuite_simple_stmt(self, p): """rawsuite : colon_tok nonewline newline_tok""" p1, p3 = p[1], p[3] beg = (p1.lineno, p1.lexpos + 1) end = (p3.lineno, p3.lexpos) s = self.source_slice(beg, end).strip() p[0] = ast.Str(s=s, lineno=beg[0], col_offset=beg[1]) def _attach_nodedent_base_rules(self): toks = set(self.tokens) toks.remove("DEDENT") ts = "\n | ".join(sorted(toks)) doc = "nodedent : " + ts + "\n" self.p_nodedent_base.__func__.__doc__ = doc def p_nodedent_base(self, p): # see above attachment function pass def p_nodedent_any(self, p): """nodedent : INDENT any_dedent_toks DEDENT""" pass def p_nodedent_many(self, p): """nodedent : nodedent nodedent""" pass def p_any_dedent_tok(self, p): """any_dedent_tok : nodedent | DEDENT """ pass def p_any_dedent_toks(self, p): """any_dedent_toks : any_dedent_tok | any_dedent_toks any_dedent_tok """ pass def _attach_nonewline_base_rules(self): toks = set(self.tokens) toks -= { "NEWLINE", "LPAREN", "RPAREN", "LBRACE", "RBRACE", "LBRACKET", "RBRACKET", "AT_LPAREN", "BANG_LPAREN", "BANG_LBRACKET", "DOLLAR_LPAREN", "DOLLAR_LBRACE", "DOLLAR_LBRACKET", "ATDOLLAR_LPAREN", } ts = "\n | ".join(sorted(toks)) doc = "nonewline : " + ts + "\n" self.p_nonewline_base.__func__.__doc__ = doc def p_nonewline_base(self, p): # see above attachment function pass def p_nonewline_any(self, p): """nonewline : any_nested_raw""" pass def p_nonewline_many(self, p): """nonewline : nonewline nonewline""" pass def p_test_ol(self, p): """test : or_test | lambdef """ p[0] = p[1] def p_test_o5(self, p): """test : or_test IF or_test ELSE test""" p[0] = ast.IfExp( test=p[3], body=p[1], orelse=p[5], lineno=self.lineno, col_offset=self.col ) def p_test_nocond(self, p): """test_nocond : or_test | lambdef_nocond """ p[0] = p[1] def p_lambdef(self, p): """lambdef : lambda_tok varargslist_opt COLON test""" p1, p2, p4 = p[1], p[2], p[4] if p2 is None: args = ast.arguments( args=[], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[], ) else: args = p2 p0 = ast.Lambda(args=args, body=p4, lineno=p1.lineno, col_offset=p1.lexpos) p[0] = p0 def p_lambdef_nocond(self, p): """lambdef_nocond : LAMBDA varargslist_opt COLON test_nocond""" assert False def p_or_test(self, p): """or_test : and_test or_and_test_list_opt""" p1, p2 = p[1], p[2] if p2 is None: p0 = p1 elif len(p2) == 2: lineno, col = lopen_loc(p1) p0 = ast.BoolOp(op=p2[0], values=[p1, p2[1]], lineno=lineno, col_offset=col) else: lineno, col = lopen_loc(p1) p0 = ast.BoolOp( op=p2[0], values=[p[1]] + p2[1::2], lineno=lineno, col_offset=col ) p[0] = p0 def p_or_and_test(self, p): """or_and_test : OR and_test""" p[0] = [ast.Or(), p[2]] def p_and_test(self, p): """and_test : not_test and_not_test_list_opt""" p1, p2 = p[1], p[2] if p2 is None: p0 = p1 elif len(p2) == 2: lineno, col = lopen_loc(p1) p0 = ast.BoolOp(op=p2[0], values=[p1, p2[1]], lineno=lineno, col_offset=col) else: lineno, col = lopen_loc(p1) p0 = ast.BoolOp( op=p2[0], values=[p1] + p2[1::2], lineno=lineno, col_offset=col ) p[0] = p0 def p_and_not_test(self, p): """and_not_test : AND not_test""" p[0] = [ast.And(), p[2]] def p_not_test_not(self, p): """not_test : NOT not_test""" p[0] = ast.UnaryOp( op=ast.Not(), operand=p[2], lineno=self.lineno, col_offset=self.col ) def p_not_test(self, p): """not_test : comparison""" p[0] = p[1] def p_comparison(self, p): """comparison : expr comp_op_expr_list_opt""" p1, p2 = p[1], p[2] if p2 is None: p0 = p1 else: p0 = ast.Compare( left=p1, ops=p2[::2], comparators=p2[1::2], lineno=p1.lineno, col_offset=p1.col_offset, ) p[0] = p0 def p_comp_op_expr(self, p): """comp_op_expr : comp_op expr""" p[0] = [p[1], p[2]] _comp_ops = { "<": ast.Lt, ">": ast.Gt, "==": ast.Eq, ">=": ast.GtE, "<=": ast.LtE, "!=": ast.NotEq, "in": ast.In, ("not", "in"): ast.NotIn, "is": ast.Is, ("is", "not"): ast.IsNot, } def p_comp_op_monograph(self, p): """comp_op : LT | GT | EQ | GE | LE | NE | IN | IS """ p[0] = self._comp_ops[p[1]]() def p_comp_op_digraph(self, p): """comp_op : NOT IN | IS NOT """ p[0] = self._comp_ops[(p[1], p[2])]() def p_star_expr(self, p): """star_expr : times_tok expr""" p1 = p[1] p[0] = ast.Starred( value=p[2], ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.lexpos ) def _binop_combine(self, p1, p2): """Combines binary operations""" if p2 is None: p0 = p1 elif isinstance(p2, ast.BinOp): p2.left = p1 p0 = p2 elif isinstance(p2, Sequence) and isinstance(p2[0], ast.BinOp): p0 = p2[0] p0.left = p1 p0.lineno, p0.col_offset = lopen_loc(p1) for bop in p2[1:]: locer = p1 if p0.left is p1 else p0 bop.left = p0 p0.lineno, p0.col_offset = lopen_loc(locer) p0 = bop else: p0 = p1 + p2 return p0 def p_expr(self, p): """expr : xor_expr | xor_expr pipe_xor_expr_list """ p[0] = self._binop_combine(p[1], p[2] if len(p) > 2 else None) def p_pipe_xor_expr(self, p): """pipe_xor_expr : pipe_tok xor_expr""" p1 = p[1] p[0] = [ ast.BinOp( left=None, op=ast.BitOr(), right=p[2], lineno=p1.lineno, col_offset=p1.lexpos, ) ] def p_xor_expr(self, p): """xor_expr : and_expr xor_and_expr_list_opt""" p[0] = self._binop_combine(p[1], p[2]) def p_xor_and_expr(self, p): """xor_and_expr : xor_tok and_expr""" p1 = p[1] p[0] = [ ast.BinOp( left=None, op=ast.BitXor(), right=p[2], lineno=p1.lineno, col_offset=p1.lexpos, ) ] def p_and_expr(self, p): """and_expr : shift_expr ampersand_shift_expr_list_opt""" p[0] = self._binop_combine(p[1], p[2]) def p_ampersand_shift_expr(self, p): """ampersand_shift_expr : ampersand_tok shift_expr""" p1 = p[1] p[0] = [ ast.BinOp( left=None, op=ast.BitAnd(), right=p[2], lineno=p1.lineno, col_offset=p1.lexpos, ) ] def p_shift_expr(self, p): """shift_expr : arith_expr shift_arith_expr_list_opt""" p[0] = self._binop_combine(p[1], p[2]) def p_shift_arith_expr(self, p): """shift_arith_expr : lshift_tok arith_expr | rshift_tok arith_expr """ p1 = p[1] op = ast.LShift() if p1.value == "<<" else ast.RShift() p[0] = [ ast.BinOp( left=None, op=op, right=p[2], lineno=p1.lineno, col_offset=p1.lexpos ) ] def p_arith_expr_single(self, p): """arith_expr : term""" p[0] = p[1] def p_arith_expr_many(self, p): """arith_expr : term pm_term_list""" p1, p2 = p[1], p[2] if len(p2) == 2: lineno, col = lopen_loc(p1) p0 = ast.BinOp( left=p1, op=p2[0], right=p2[1], lineno=lineno, col_offset=col ) else: left = p1 for op, right in zip(p2[::2], p2[1::2]): locer = left if left is p1 else op lineno, col = lopen_loc(locer) left = ast.BinOp( left=left, op=op, right=right, lineno=lineno, col_offset=col ) p0 = left p[0] = p0 _term_binops = { "+": ast.Add, "-": ast.Sub, "*": ast.Mult, "@": ast.MatMult, "/": ast.Div, "%": ast.Mod, "//": ast.FloorDiv, } def p_pm_term(self, p): """pm_term : plus_tok term | minus_tok term """ p1 = p[1] op = self._term_binops[p1.value](lineno=p1.lineno, col_offset=p1.lexpos) p[0] = [op, p[2]] def p_term(self, p): """term : factor op_factor_list_opt""" p1, p2 = p[1], p[2] if p2 is None: p0 = p1 elif len(p2) == 2: lineno, col = lopen_loc(p1) p0 = ast.BinOp( left=p1, op=p2[0], right=p2[1], lineno=lineno, col_offset=col ) else: left = p1 for op, right in zip(p2[::2], p2[1::2]): locer = left if left is p1 else op lineno, col = lopen_loc(locer) left = ast.BinOp( left=left, op=op, right=right, lineno=lineno, col_offset=col ) p0 = left p[0] = p0 def p_op_factor(self, p): """op_factor : times_tok factor | at_tok factor | divide_tok factor | mod_tok factor | doublediv_tok factor """ p1 = p[1] op = self._term_binops[p1.value] if op is None: self._parse_error( "operation {0!r} not supported".format(p1), self.currloc(lineno=p.lineno, column=p.lexpos), ) p[0] = [op(lineno=p1.lineno, col_offset=p1.lexpos), p[2]] _factor_ops = {"+": ast.UAdd, "-": ast.USub, "~": ast.Invert} def p_factor_power(self, p): """factor : power""" p[0] = p[1] def p_factor_unary(self, p): """factor : PLUS factor | MINUS factor | TILDE factor """ op = self._factor_ops[p[1]]() p[0] = ast.UnaryOp(op=op, operand=p[2], lineno=self.lineno, col_offset=self.col) def p_power_atom(self, p): """power : atom_expr""" p[0] = p[1] def p_power(self, p): """power : atom_expr POW factor""" p1 = p[1] p[0] = ast.BinOp( left=p1, op=ast.Pow(), right=p[3], lineno=p1.lineno, col_offset=p1.col_offset, ) def p_yield_expr_or_testlist_comp(self, p): """yield_expr_or_testlist_comp : yield_expr | testlist_comp """ p[0] = p[1] def _list_or_elts_if_not_real_tuple(self, x): if isinstance(x, ast.Tuple) and not ( hasattr(x, "_real_tuple") and x._real_tuple ): rtn = x.elts else: rtn = [x] return rtn def apply_trailers(self, leader, trailers): """Helper function for atom expr.""" if trailers is None: return leader p0 = leader for trailer in trailers: if isinstance(trailer, (ast.Index, ast.Slice, ast.ExtSlice)): p0 = ast.Subscript( value=leader, slice=trailer, ctx=ast.Load(), lineno=leader.lineno, col_offset=leader.col_offset, ) elif isinstance(trailer, Mapping): # call normal functions p0 = ast.Call( func=leader, lineno=leader.lineno, col_offset=leader.col_offset, **trailer ) elif isinstance(trailer, (ast.Tuple, tuple)): # call macro functions l, c = leader.lineno, leader.col_offset gblcall = xonsh_call("globals", [], lineno=l, col=c) loccall = xonsh_call("locals", [], lineno=l, col=c) if isinstance(trailer, tuple): trailer, arglist = trailer margs = [leader, trailer, gblcall, loccall] p0 = xonsh_call("__xonsh__.call_macro", margs, lineno=l, col=c) elif isinstance(trailer, str): if trailer == "?": p0 = xonsh_help(leader, lineno=leader.lineno, col=leader.col_offset) elif trailer == "??": p0 = xonsh_superhelp( leader, lineno=leader.lineno, col=leader.col_offset ) else: p0 = ast.Attribute( value=leader, attr=trailer, ctx=ast.Load(), lineno=leader.lineno, col_offset=leader.col_offset, ) else: assert False leader = p0 return p0 def p_atom_expr(self, p): """atom_expr : atom trailer_list_opt""" p[0] = self.apply_trailers(p[1], p[2]) # # Atom rules! (So does Adam!) # def p_atom_lparen(self, p): """atom : lparen_tok yield_expr_or_testlist_comp_opt RPAREN""" p1, p2 = p[1], p[2] p1, p1_tok = p1.value, p1 if p2 is None: # empty container atom p0 = ast.Tuple( elts=[], ctx=ast.Load(), lineno=self.lineno, col_offset=self.col ) p0._real_tuple = True elif isinstance(p2, ast.AST): p0 = p2 p0._lopen_lineno, p0._lopen_col = p1_tok.lineno, p1_tok.lexpos p0._real_tuple = True elif len(p2) == 1 and isinstance(p2[0], ast.AST): p0 = p2[0] p0._lopen_lineno, p0._lopen_col = p1_tok.lineno, p1_tok.lexpos else: self.p_error(p) p[0] = p0 def p_atom_lbraket(self, p): """atom : lbracket_tok testlist_comp_opt RBRACKET""" p1, p2 = p[1], p[2] p1, p1_tok = p1.value, p1 if p2 is None: p0 = ast.List( elts=[], ctx=ast.Load(), lineno=self.lineno, col_offset=self.col ) elif isinstance(p2, ast.GeneratorExp): p0 = ast.ListComp( elt=p2.elt, generators=p2.generators, lineno=p2.lineno, col_offset=p2.col_offset, ) else: if isinstance(p2, ast.Tuple): if hasattr(p2, "_real_tuple") and p2._real_tuple: elts = [p2] else: elts = p2.elts else: elts = [p2] p0 = ast.List( elts=elts, ctx=ast.Load(), lineno=p1_tok.lineno, col_offset=p1_tok.lexpos, ) p[0] = p0 def p_atom_lbrace(self, p): """atom : lbrace_tok dictorsetmaker_opt RBRACE""" p1, p2 = p[1], p[2] p1, p1_tok = p1.value, p1 if p2 is None: p0 = ast.Dict( keys=[], values=[], ctx=ast.Load(), lineno=self.lineno, col_offset=self.col, ) else: p0 = p2 p0.lineno, p0.col_offset = p1_tok.lineno, p1_tok.lexpos p[0] = p0 def p_atom_ns(self, p): """atom : number | string_literal_list """ p[0] = p[1] def p_atom_name(self, p): """atom : name_tok""" p1 = p[1] p[0] = ast.Name( id=p1.value, ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.lexpos ) def p_atom_ellip(self, p): """atom : ellipsis_tok""" p1 = p[1] p[0] = ast.EllipsisNode(lineno=p1.lineno, col_offset=p1.lexpos) def p_atom_none(self, p): """atom : none_tok""" p1 = p[1] p[0] = ast.NameConstant(value=None, lineno=p1.lineno, col_offset=p1.lexpos) def p_atom_true(self, p): """atom : true_tok""" p1 = p[1] p[0] = ast.NameConstant(value=True, lineno=p1.lineno, col_offset=p1.lexpos) def p_atom_false(self, p): """atom : false_tok""" p1 = p[1] p[0] = ast.NameConstant(value=False, lineno=p1.lineno, col_offset=p1.lexpos) def p_atom_pathsearch(self, p): """atom : SEARCHPATH""" p[0] = xonsh_pathsearch(p[1], pymode=True, lineno=self.lineno, col=self.col) def p_atom_dname(self, p): """atom : DOLLAR_NAME""" p[0] = self._envvar_by_name(p[1][1:], lineno=self.lineno, col=self.col) def p_atom_fistful_of_dollars(self, p): """atom : dollar_lbrace_tok test RBRACE | bang_lparen_tok subproc RPAREN | dollar_lparen_tok subproc RPAREN | bang_lbracket_tok subproc RBRACKET | dollar_lbracket_tok subproc RBRACKET """ p[0] = self._dollar_rules(p) def p_atom_bang_empty_fistful_of_dollars(self, p): """atom : bang_lparen_tok subproc bang_tok RPAREN | dollar_lparen_tok subproc bang_tok RPAREN | bang_lbracket_tok subproc bang_tok RBRACKET | dollar_lbracket_tok subproc bang_tok RBRACKET """ self._append_subproc_bang_empty(p) p[0] = self._dollar_rules(p) def p_atom_bang_fistful_of_dollars(self, p): """atom : bang_lparen_tok subproc bang_tok nocloser rparen_tok | dollar_lparen_tok subproc bang_tok nocloser rparen_tok | bang_lbracket_tok subproc bang_tok nocloser rbracket_tok | dollar_lbracket_tok subproc bang_tok nocloser rbracket_tok """ self._append_subproc_bang(p) p[0] = self._dollar_rules(p) def _attach_nocloser_base_rules(self): toks = set(self.tokens) toks -= { "LPAREN", "RPAREN", "LBRACE", "RBRACE", "LBRACKET", "RBRACKET", "AT_LPAREN", "BANG_LPAREN", "BANG_LBRACKET", "DOLLAR_LPAREN", "DOLLAR_LBRACE", "DOLLAR_LBRACKET", "ATDOLLAR_LPAREN", } ts = "\n | ".join(sorted(toks)) doc = "nocloser : " + ts + "\n" self.p_nocloser_base.__func__.__doc__ = doc def p_nocloser_base(self, p): # see above attachment function pass def p_nocloser_any(self, p): """nocloser : any_nested_raw""" pass def p_nocloser_many(self, p): """nocloser : nocloser nocloser""" pass def p_string_literal(self, p): """string_literal : string_tok""" p1 = p[1] prefix = RE_STRINGPREFIX.match(p1.value).group() if "p" in prefix: value_without_p = prefix.replace("p", "") + p1.value[len(prefix) :] s = ast.Str( s=ast.literal_eval(value_without_p), lineno=p1.lineno, col_offset=p1.lexpos, ) p[0] = xonsh_call( "__xonsh__.path_literal", [s], lineno=p1.lineno, col=p1.lexpos ) elif "f" in prefix or "F" in prefix: s = sub_env_vars(p1.value) s = pyparse(s).body[0].value s = ast.increment_lineno(s, p1.lineno - 1) p[0] = s else: s = ast.literal_eval(p1.value) is_bytes = "b" in prefix or "B" in prefix cls = ast.Bytes if is_bytes else ast.Str p[0] = cls(s=s, lineno=p1.lineno, col_offset=p1.lexpos) def p_string_literal_list(self, p): """string_literal_list : string_literal | string_literal_list string_literal """ if len(p) == 3: p[1].s += p[2].s p[0] = p[1] def p_number(self, p): """number : number_tok""" p1 = p[1] p[0] = ast.Num( n=ast.literal_eval(p1.value.replace("_", "")), lineno=p1.lineno, col_offset=p1.lexpos, ) def p_testlist_comp_comp(self, p): """testlist_comp : test_or_star_expr comp_for""" p1, p2 = p[1], p[2] p[0] = ast.GeneratorExp( elt=p1, generators=p2["comps"], lineno=p1.lineno, col_offset=p1.col_offset ) def p_testlist_comp_comma(self, p): """testlist_comp : test_or_star_expr comma_opt""" p1, p2 = p[1], p[2] if p2 is None: # split out grouping parentheses. p[0] = p1 else: p[0] = ast.Tuple( elts=[p1], ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.col_offset ) def p_testlist_comp_many(self, p): """testlist_comp : test_or_star_expr comma_test_or_star_expr_list comma_opt""" p1, p2 = p[1], p[2] p[0] = ast.Tuple( elts=[p1] + p2, ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.col_offset ) def p_trailer_lparen(self, p): """trailer : LPAREN arglist_opt RPAREN""" p[0] = [p[2] or dict(args=[], keywords=[], starargs=None, kwargs=None)] def p_trailer_bang_lparen(self, p): """trailer : bang_lparen_tok macroarglist_opt rparen_tok | bang_lparen_tok nocomma comma_tok rparen_tok | bang_lparen_tok nocomma comma_tok WS rparen_tok | bang_lparen_tok macroarglist comma_tok rparen_tok | bang_lparen_tok macroarglist comma_tok WS rparen_tok """ p1, p2, p3 = p[1], p[2], p[3] begins = [(p1.lineno, p1.lexpos + 2)] ends = [(p3.lineno, p3.lexpos)] if p2: begins.extend([(x[0], x[1] + 1) for x in p2]) ends = p2 + ends elts = [] for beg, end in zip(begins, ends): s = self.source_slice(beg, end).strip() if not s: if len(begins) == 1: break else: msg = "empty macro arguments not allowed" self._parse_error(msg, self.currloc(*beg)) node = ast.Str(s=s, lineno=beg[0], col_offset=beg[1]) elts.append(node) p0 = ast.Tuple( elts=elts, ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.lexpos ) p[0] = [p0] def p_trailer_p3(self, p): """trailer : LBRACKET subscriptlist RBRACKET | PERIOD NAME """ p[0] = [p[2]] def p_trailer_quest(self, p): """trailer : DOUBLE_QUESTION | QUESTION """ p[0] = [p[1]] def _attach_nocomma_tok_rules(self): toks = set(self.tokens) toks -= { "COMMA", "LPAREN", "RPAREN", "LBRACE", "RBRACE", "LBRACKET", "RBRACKET", "AT_LPAREN", "BANG_LPAREN", "BANG_LBRACKET", "DOLLAR_LPAREN", "DOLLAR_LBRACE", "DOLLAR_LBRACKET", "ATDOLLAR_LPAREN", } ts = "\n | ".join(sorted(toks)) doc = "nocomma_tok : " + ts + "\n" self.p_nocomma_tok.__func__.__doc__ = doc # The following grammar rules are no-ops because we don't need to glue the # source code back together piece-by-piece. Instead, we simply look for # top-level commas and record their positions. With these positions and the # respective positions of the bounding parentheses, we can use the # source_slice() method. This does a much better job of capturing exactly # the source code that was provided. The tokenizer & lexer can be a little # lossy, especially with respect to whitespace. def p_nocomma_tok(self, p): # see attachment function above for docstring pass def p_any_raw_tok(self, p): """any_raw_tok : nocomma | COMMA """ pass def p_any_raw_toks_one(self, p): """any_raw_toks : any_raw_tok""" pass def p_any_raw_toks_many(self, p): """any_raw_toks : any_raw_toks any_raw_tok""" pass def p_nocomma_part_tok(self, p): """nocomma_part : nocomma_tok""" pass def p_any_nested_raw(self, p): """any_nested_raw : LPAREN any_raw_toks_opt RPAREN | LBRACE any_raw_toks_opt RBRACE | LBRACKET any_raw_toks_opt RBRACKET | AT_LPAREN any_raw_toks_opt RPAREN | BANG_LPAREN any_raw_toks_opt RPAREN | BANG_LBRACKET any_raw_toks_opt RBRACKET | DOLLAR_LPAREN any_raw_toks_opt RPAREN | DOLLAR_LBRACE any_raw_toks_opt RBRACE | DOLLAR_LBRACKET any_raw_toks_opt RBRACKET | ATDOLLAR_LPAREN any_raw_toks_opt RPAREN """ pass def p_nocomma_part_any(self, p): """nocomma_part : any_nested_raw""" pass def p_nocomma_base(self, p): """nocomma : nocomma_part""" pass def p_nocomma_append(self, p): """nocomma : nocomma nocomma_part""" pass def p_comma_nocomma(self, p): """comma_nocomma : comma_tok nocomma""" p1 = p[1] p[0] = [(p1.lineno, p1.lexpos)] def p_macroarglist_single(self, p): """macroarglist : nocomma""" p[0] = [] def p_macroarglist_many(self, p): """macroarglist : nocomma comma_nocomma_list""" p[0] = p[2] def p_subscriptlist(self, p): """subscriptlist : subscript comma_subscript_list_opt comma_opt""" p1, p2 = p[1], p[2] if p2 is None: pass elif isinstance(p1, ast.Slice) or any([isinstance(x, ast.Slice) for x in p2]): p1 = ast.ExtSlice(dims=[p1] + p2) else: p1.value = ast.Tuple( elts=[p1.value] + [x.value for x in p2], ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.col_offset, ) p[0] = p1 def p_comma_subscript(self, p): """comma_subscript : COMMA subscript""" p[0] = [p[2]] def p_subscript_test(self, p): """subscript : test""" p1 = p[1] p[0] = ast.Index(value=p1, lineno=p1.lineno, col_offset=p1.col_offset) def p_subscript_tok(self, p): """subscript : test_opt colon_tok test_opt sliceop_opt""" p1 = p[1] if p1 is None: p2 = p[2] lineno, col = p2.lineno, p2.lexpos else: lineno, col = p1.lineno, p1.col_offset p[0] = ast.Slice(lower=p1, upper=p[3], step=p[4], lineno=lineno, col_offset=col) def p_sliceop(self, p): """sliceop : COLON test_opt""" p[0] = p[2] def p_expr_or_star_expr(self, p): """expr_or_star_expr : expr | star_expr """ p[0] = p[1] def p_comma_expr_or_star_expr(self, p): """comma_expr_or_star_expr : COMMA expr_or_star_expr""" p[0] = [p[2]] def p_exprlist_e3(self, p): """exprlist : expr_or_star_expr comma_opt""" p[0] = [p[1]] def p_exprlist_many(self, p): """exprlist : expr_or_star_expr comma_expr_or_star_expr_list comma_opt""" p2 = p[2] p2.insert(0, p[1]) p[0] = p2 def p_testlist_test(self, p): """testlist : test""" p1 = p[1] if isinstance(p1, ast.Tuple) and ( hasattr(p1, "_real_tuple") and p1._real_tuple and p1.elts ): p1.lineno, p1.col_offset = lopen_loc(p1.elts[0]) p[0] = p1 def p_testlist_single(self, p): """testlist : test COMMA""" p1 = p[1] if isinstance(p1, ast.List) or ( isinstance(p1, ast.Tuple) and hasattr(p1, "_real_tuple") and p1._real_tuple ): lineno, col = lopen_loc(p1) p[0] = ast.Tuple( elts=[p1], ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.col_offset ) else: p[0] = ensure_has_elts(p[1]) def p_testlist_many(self, p): """testlist : test comma_test_list COMMA | test comma_test_list """ p1 = p[1] if isinstance(p1, ast.List) or ( isinstance(p1, ast.Tuple) and hasattr(p1, "_real_tuple") and p1._real_tuple ): lineno, col = lopen_loc(p1) p1 = ast.Tuple( elts=[p1], ctx=ast.Load(), lineno=p1.lineno, col_offset=p1.col_offset ) else: p1 = ensure_has_elts(p1) p1.elts += p[2] p[0] = p1 def p_comma_item(self, p): """comma_item : COMMA item""" p[0] = p[2] # # Dict or set maker # def p_dictorsetmaker_t6(self, p): """dictorsetmaker : test COLON test comma_item_list comma_opt""" p1, p4 = p[1], p[4] keys = [p1] vals = [p[3]] for k, v in zip(p4[::2], p4[1::2]): keys.append(k) vals.append(v) lineno, col = lopen_loc(p1) p[0] = ast.Dict( keys=keys, values=vals, ctx=ast.Load(), lineno=lineno, col_offset=col ) def p_dictorsetmaker_i4(self, p): """dictorsetmaker : item comma_item_list comma_opt""" p1, p2 = p[1], p[2] keys = [p1[0]] vals = [p1[1]] for k, v in zip(p2[::2], p2[1::2]): keys.append(k) vals.append(v) lineno, col = lopen_loc(p1[0] or p2[0]) p[0] = ast.Dict( keys=keys, values=vals, ctx=ast.Load(), lineno=lineno, col_offset=col ) def p_dictorsetmaker_t4_dict(self, p): """dictorsetmaker : test COLON testlist""" keys = [p[1]] vals = self._list_or_elts_if_not_real_tuple(p[3]) lineno, col = lopen_loc(p[1]) p[0] = ast.Dict( keys=keys, values=vals, ctx=ast.Load(), lineno=lineno, col_offset=col ) def p_dictorsetmaker_t4_set(self, p): """dictorsetmaker : test_or_star_expr comma_test_or_star_expr_list comma_opt""" p[0] = ast.Set( elts=[p[1]] + p[2], ctx=ast.Load(), lineno=self.lineno, col_offset=self.col ) def p_dictorsetmaker_test_comma(self, p): """dictorsetmaker : test_or_star_expr comma_opt""" elts = self._list_or_elts_if_not_real_tuple(p[1]) p[0] = ast.Set( elts=elts, ctx=ast.Load(), lineno=self.lineno, col_offset=self.col ) def p_dictorsetmaker_testlist(self, p): """dictorsetmaker : testlist""" elts = self._list_or_elts_if_not_real_tuple(p[1]) p[0] = ast.Set( elts=elts, ctx=ast.Load(), lineno=self.lineno, col_offset=self.col ) def p_dictorsetmaker_comp(self, p): """dictorsetmaker : item comp_for | test_or_star_expr comp_for """ p1 = p[1] comps = p[2].get("comps", []) if isinstance(p1, list) and len(p1) == 2: p[0] = ast.DictComp( key=p1[0], value=p1[1], generators=comps, lineno=self.lineno, col_offset=self.col, ) else: p[0] = ast.SetComp( elt=p1, generators=comps, lineno=self.lineno, col_offset=self.col ) def p_classdef(self, p): """classdef : class_tok NAME func_call_opt COLON suite""" p1, p3 = p[1], p[3] b, kw = ([], []) if p3 is None else (p3["args"], p3["keywords"]) c = ast.ClassDef( name=p[2], bases=b, keywords=kw, starargs=None, kwargs=None, body=p[5], decorator_list=[], lineno=p1.lineno, col_offset=p1.lexpos, ) p[0] = [c] def p_comma_argument(self, p): """comma_argument : COMMA argument""" p[0] = [p[2]] def p_comp_iter(self, p): """comp_iter : comp_for | comp_if """ p[0] = p[1] def p_comp_for(self, p): """comp_for : FOR exprlist IN or_test comp_iter_opt""" targs, it, p5 = p[2], p[4], p[5] if len(targs) == 1: targ = targs[0] else: targ = ensure_has_elts(targs) store_ctx(targ) comp = ast.comprehension(target=targ, iter=it, ifs=[]) comps = [comp] p0 = {"comps": comps} if p5 is not None: comps += p5.get("comps", []) comp.ifs += p5.get("if", []) p[0] = p0 def p_comp_if(self, p): """comp_if : IF test_nocond comp_iter_opt""" p2, p3 = p[2], p[3] p0 = {"if": [p2]} if p3 is not None: p0["comps"] = p3.get("comps", []) p[0] = p0 def p_yield_expr(self, p): """yield_expr : yield_tok yield_arg_opt""" p1, p2 = p[1], p[2] if p2 is None: p0 = ast.Yield(value=p2, lineno=p1.lineno, col_offset=p1.lexpos) elif p2["from"]: p0 = ast.YieldFrom(value=p2["val"], lineno=p1.lineno, col_offset=p1.lexpos) else: p0 = ast.Yield(value=p2["val"], lineno=p1.lineno, col_offset=p1.lexpos) p[0] = p0 def p_yield_arg_from(self, p): """yield_arg : FROM test""" p[0] = {"from": True, "val": p[2]} def p_yield_arg_testlist(self, p): """yield_arg : testlist""" p[0] = {"from": False, "val": p[1]} # # subprocess # def _dollar_rules(self, p): """These handle the special xonsh $ shell atoms by looking up in a special __xonsh__.env dictionary injected in the __builtin__. """ lenp = len(p) p1, p2 = p[1], p[2] if isinstance(p1, LexToken): p1, p1_tok = p1.value, p1 lineno, col = p1_tok.lineno, p1_tok.lexpos else: lineno, col = self.lineno, self.col if lenp == 3: # $NAME p0 = self._envvar_by_name(p2, lineno=lineno, col=col) elif p1 == "${": xenv = load_attribute_chain("__xonsh__.env", lineno=lineno, col=col) idx = ast.Index(value=p2) p0 = ast.Subscript( value=xenv, slice=idx, ctx=ast.Load(), lineno=lineno, col_offset=col ) elif p1 == "$(": p0 = xonsh_call( "__xonsh__.subproc_captured_stdout", p2, lineno=lineno, col=col ) elif p1 == "!(": p0 = xonsh_call( "__xonsh__.subproc_captured_object", p2, lineno=lineno, col=col ) elif p1 == "![": p0 = xonsh_call( "__xonsh__.subproc_captured_hiddenobject", p2, lineno=lineno, col=col ) elif p1 == "$[": p0 = xonsh_call("__xonsh__.subproc_uncaptured", p2, lineno=lineno, col=col) else: assert False return p0 def _envvar_getter_by_name(self, var, lineno=None, col=None): xenv = load_attribute_chain("__xonsh__.env", lineno=lineno, col=col) func = ast.Attribute( value=xenv, attr="get", ctx=ast.Load(), lineno=lineno, col_offset=col ) return ast.Call( func=func, args=[ ast.Str(s=var, lineno=lineno, col_offset=col), ast.Str(s="", lineno=lineno, col_offset=col), ], keywords=[], starargs=None, kwargs=None, lineno=lineno, col_offset=col, ) def _envvar_by_name(self, var, lineno=None, col=None): """Looks up a xonsh variable by name.""" xenv = load_attribute_chain("__xonsh__.env", lineno=lineno, col=col) idx = ast.Index(value=ast.Str(s=var, lineno=lineno, col_offset=col)) return ast.Subscript( value=xenv, slice=idx, ctx=ast.Load(), lineno=lineno, col_offset=col ) def _subproc_cliargs(self, args, lineno=None, col=None): """Creates an expression for subprocess CLI arguments.""" cliargs = currlist = empty_list(lineno=lineno, col=col) for arg in args: action = arg._cliarg_action if action == "append": if currlist is None: currlist = empty_list(lineno=lineno, col=col) cliargs = binop( cliargs, ast.Add(), currlist, lineno=lineno, col=col ) currlist.elts.append(arg) elif action == "extend": cliargs = binop(cliargs, ast.Add(), arg, lineno=lineno, col=col) currlist = None elif action == "splitlines": sl = call_split_lines(arg, lineno=lineno, col=col) cliargs = binop(cliargs, ast.Add(), sl, lineno=lineno, col=col) currlist = None elif action == "ensure_list": x = ensure_list_from_str_or_list(arg, lineno=lineno, col=col) cliargs = binop(cliargs, ast.Add(), x, lineno=lineno, col=col) currlist = None else: raise ValueError("action not understood: " + action) del arg._cliarg_action return cliargs def p_pipe(self, p): """pipe : PIPE | WS PIPE | PIPE WS | WS PIPE WS """ p[0] = ast.Str(s="|", lineno=self.lineno, col_offset=self.col) def p_subproc_s2(self, p): """subproc : subproc_atoms | subproc_atoms WS """ p1 = p[1] p[0] = [self._subproc_cliargs(p1, lineno=self.lineno, col=self.col)] def p_subproc_amp(self, p): """subproc : subproc AMPERSAND""" p1 = p[1] p[0] = p1 + [ast.Str(s=p[2], lineno=self.lineno, col_offset=self.col)] def p_subproc_pipe(self, p): """subproc : subproc pipe subproc_atoms | subproc pipe subproc_atoms WS """ p1 = p[1] if len(p1) > 1 and hasattr(p1[-2], "s") and p1[-2].s != "|": msg = "additional redirect following non-pipe redirect" self._parse_error(msg, self.currloc(lineno=self.lineno, column=self.col)) cliargs = self._subproc_cliargs(p[3], lineno=self.lineno, col=self.col) p[0] = p1 + [p[2], cliargs] def p_subproc_atoms_single(self, p): """subproc_atoms : subproc_atom""" p[0] = [p[1]] def p_subproc_atoms_many(self, p): """subproc_atoms : subproc_atoms WS subproc_atom""" p1 = p[1] p1.append(p[3]) p[0] = p1 def p_subproc_atoms_subshell(self, p): """subproc_atoms : lparen_tok any_raw_tok rparen_tok | lparen_tok any_raw_toks rparen_tok """ p1 = p[1] p3 = p[3] l = p1.lineno c = p1.lexpos + 1 subcmd = self.source_slice((l, c), (p3.lineno, p3.lexpos)) subcmd = subcmd.strip() + "\n" p0 = [ ast.Str(s="xonsh", lineno=l, col_offset=c), ast.Str(s="-c", lineno=l, col_offset=c), ast.Str(s=subcmd, lineno=l, col_offset=c), ] for arg in p0: arg._cliarg_action = "append" p[0] = p0 # # Subproc atom rules # def _append_subproc_bang_empty(self, p): """Appends an empty string in subprocess mode to the argument list.""" p3 = p[3] node = ast.Str(s="", lineno=p3.lineno, col_offset=p3.lexpos + 1) p[2][-1].elts.append(node) def _append_subproc_bang(self, p): """Appends the part between ! and the ) or ] in subprocess mode to the argument list. """ p3, p5 = p[3], p[5] beg = (p3.lineno, p3.lexpos + 1) end = (p5.lineno, p5.lexpos) s = self.source_slice(beg, end).strip() node = ast.Str(s=s, lineno=beg[0], col_offset=beg[1]) p[2][-1].elts.append(node) def p_subproc_atom_uncaptured(self, p): """subproc_atom : dollar_lbracket_tok subproc RBRACKET""" p1 = p[1] p0 = xonsh_call( "__xonsh__.subproc_uncaptured", args=p[2], lineno=p1.lineno, col=p1.lexpos ) p0._cliarg_action = "splitlines" p[0] = p0 def p_subproc_atom_uncaptured_bang_empty(self, p): """subproc_atom : dollar_lbracket_tok subproc bang_tok RBRACKET""" self._append_subproc_bang_empty(p) self.p_subproc_atom_uncaptured(p) def p_subproc_atom_uncaptured_bang(self, p): """subproc_atom : dollar_lbracket_tok subproc bang_tok nocloser rbracket_tok""" self._append_subproc_bang(p) self.p_subproc_atom_uncaptured(p) def p_subproc_atom_captured_stdout(self, p): """subproc_atom : dollar_lparen_tok subproc RPAREN""" p1 = p[1] p0 = xonsh_call( "__xonsh__.subproc_captured_stdout", args=p[2], lineno=p1.lineno, col=p1.lexpos, ) p0._cliarg_action = "append" p[0] = p0 def p_subproc_atom_captured_stdout_bang_empty(self, p): """subproc_atom : dollar_lparen_tok subproc bang_tok RPAREN""" self._append_subproc_bang_empty(p) self.p_subproc_atom_captured_stdout(p) def p_subproc_atom_captured_stdout_bang(self, p): """subproc_atom : dollar_lparen_tok subproc bang_tok nocloser rparen_tok""" self._append_subproc_bang(p) self.p_subproc_atom_captured_stdout(p) def p_subproc_atom_pyenv_lookup(self, p): """subproc_atom : dollar_lbrace_tok test RBRACE""" p1 = p[1] lineno, col = p1.lineno, p1.lexpos xenv = load_attribute_chain("__xonsh__.env", lineno=lineno, col=col) func = ast.Attribute( value=xenv, attr="get", ctx=ast.Load(), lineno=lineno, col_offset=col ) p0 = ast.Call( func=func, args=[p[2], ast.Str(s="", lineno=lineno, col_offset=col)], keywords=[], starargs=None, kwargs=None, lineno=lineno, col_offset=col, ) p0._cliarg_action = "append" p[0] = p0 def p_subproc_atom_pyeval(self, p): """subproc_atom : at_lparen_tok testlist_comp RPAREN subproc_arg_part : at_lparen_tok testlist_comp RPAREN """ p1 = p[1] p0 = xonsh_call( "__xonsh__.list_of_strs_or_callables", [p[2]], lineno=p1.lineno, col=p1.lexpos, ) p0._cliarg_action = "extend" p[0] = p0 def p_subproc_atom_subproc_inject(self, p): """subproc_atom : atdollar_lparen_tok subproc RPAREN""" p1 = p[1] p0 = xonsh_call( "__xonsh__.subproc_captured_inject", p[2], lineno=p1.lineno, col=p1.lexpos ) p0._cliarg_action = "extend" p[0] = p0 def p_subproc_atom_subproc_inject_bang_empty(self, p): """subproc_atom : atdollar_lparen_tok subproc bang_tok RPAREN""" self._append_subproc_bang_empty(p) self.p_subproc_atom_subproc_inject(p) def p_subproc_atom_subproc_inject_bang(self, p): """subproc_atom : atdollar_lparen_tok subproc bang_tok nocloser rparen_tok""" self._append_subproc_bang(p) self.p_subproc_atom_subproc_inject(p) def p_subproc_atom_redirect(self, p): """subproc_atom : GT | LT | RSHIFT | IOREDIRECT """ p0 = ast.Str(s=p[1], lineno=self.lineno, col_offset=self.col) p0._cliarg_action = "append" p[0] = p0 def p_subproc_atom_re(self, p): """subproc_atom : SEARCHPATH""" p0 = xonsh_pathsearch(p[1], pymode=False, lineno=self.lineno, col=self.col) p0._cliarg_action = "extend" p[0] = p0 def p_subproc_atom_str(self, p): """subproc_atom : string_literal""" p0 = xonsh_call( "__xonsh__.expand_path", args=[p[1]], lineno=self.lineno, col=self.col ) p0._cliarg_action = "append" p[0] = p0 def p_subproc_atom_arg(self, p): """subproc_atom : subproc_arg""" p1 = p[1] if isinstance(p1, list): # has an expanding function call, such as @(x) p0 = xonsh_call( "__xonsh__.list_of_list_of_strs_outer_product", args=[ensure_has_elts(p1)], lineno=p1[0].lineno, col=p1[0].col_offset, ) p0._cliarg_action = "extend" elif hasglobstar(p1): # globbed literal argument p0 = xonsh_call( "__xonsh__.glob", args=[p1], lineno=p1.lineno, col=p1.col_offset ) p0._cliarg_action = "extend" else: # literal str argument p0 = xonsh_call( "__xonsh__.expand_path", args=[p1], lineno=p1.lineno, col=p1.col_offset ) p0._cliarg_action = "append" p[0] = p0 def p_subproc_arg_single(self, p): """subproc_arg : subproc_arg_part""" p[0] = p[1] def p_subproc_arg_many(self, p): """subproc_arg : subproc_arg subproc_arg_part""" # This glues the string together after parsing p1 = p[1] p2 = p[2] if isinstance(p1, ast.Str) and isinstance(p2, ast.Str): p0 = ast.Str(p1.s + p2.s, lineno=p1.lineno, col_offset=p1.col_offset) elif isinstance(p1, list): if isinstance(p2, list): p1.extend(p2) else: p1.append(p2) p0 = p1 elif isinstance(p2, list): p2.insert(0, p1) p0 = p2 else: p0 = [p1, p2] p[0] = p0 def _attach_subproc_arg_part_rules(self): toks = set(self.tokens) toks -= { "AND", "OR", "NOT", "BANG", "PIPE", "WS", "GT", "LT", "LSHIFT", "RSHIFT", "IOREDIRECT", "SEARCHPATH", "INDENT", "DEDENT", "LPAREN", "RPAREN", "LBRACE", "RBRACE", "LBRACKET", "RBRACKET", "AT_LPAREN", "BANG_LPAREN", "BANG_LBRACKET", "DOLLAR_LPAREN", "DOLLAR_LBRACE", "DOLLAR_LBRACKET", "ATDOLLAR_LPAREN", } ts = "\n | ".join(sorted([t.lower() + "_tok" for t in toks])) doc = "subproc_arg_part : " + ts + "\n" self.p_subproc_arg_part.__func__.__doc__ = doc def p_subproc_arg_part(self, p): # Many tokens cannot be part of this rule, such as $, ', ", () # Use a string atom instead. See above attachment functions p1 = p[1] p[0] = ast.Str(s=p1.value, lineno=p1.lineno, col_offset=p1.lexpos) # # Helpers # def p_test_comma_combine(self, p): """test_comma_list : test comma_test_list | test comma_test_list COMMA """ p2 = p[2] p2.insert(0, p[1]) p[0] = p2 def p_empty(self, p): "empty : " p[0] = None def p_error(self, p): if p is None: self._parse_error("no further code", None) elif p.type == "ERRORTOKEN": if isinstance(p.value, BaseException): raise p.value else: self._parse_error( p.value, self.currloc(lineno=p.lineno, column=p.lexpos) ) else: msg = ("code: {0}".format(p.value),) self._parse_error(msg, self.currloc(lineno=p.lineno, column=p.lexpos))
from dataclasses import make_dataclass import numpy as np from scipy.optimize import OptimizeResult from .util import TAB, ReprMixin, spearman2d, pearson2d class Parameter(ReprMixin): def __init__(self, guess, bounds, grid_range=None): """ Class that defines the fitting characteristics of a Parameter. Parameters ---------- guess : float Initial guess for the parameter value. bounds: array-like of length 2 Parameter bounds. The first and second element indicate the lower and upper bound of the parameter. grid_range: array-like Points to visit in the initial parameter gridsearch search. It makes sense to restrict this to a range of _likely_ values, rather than minimal and maximal bounds. """ self.guess = guess self.bounds = bounds self.grid_range = bounds if grid_range is None else grid_range def copy(self): return Parameter(self.guess, self.bounds, self.grid_range) class ParameterSet(ReprMixin): def __init__(self, parameters, names, constraints=None): """ Container class for all Parameters of a model. Parameters ---------- parameters : dict[str, Parameter] The dictionary must have the form {parameter_name1: Parameter(..), parameter_name2: Parameter(..), ..} names: List[str] List of parameter names of a model. constraints: List[Dict] List of scipy minimize constraints (each constraint is a dictionary with keys 'type' and 'fun'} """ self.base_names = names self.base_is_multiple = [isinstance(parameters[p], list) for p in names] self.base_len = [len(parameters[p]) if isinstance(parameters[p], list) else 1 for p in names] # noqa self.names = sum([[f'{p}_{i}' for i in range(len(parameters[p]))] if isinstance(parameters[p], list) # noqa else [p] for p in names], []) self.guess = np.array(sum([[parameters[p][i].guess for i in range(len(parameters[p]))] if # noqa isinstance(parameters[p], list) else [parameters[p].guess] for p in names], [])) self.bounds = np.array(sum([[parameters[p][i].bounds for i in range(len(parameters[p]))] if # noqa isinstance(parameters[p], list) else [parameters[p].bounds] for p in names], [])) self.grid_range = np.array(sum([[parameters[p][i].grid_range for i in range(len(parameters[p]))] if # noqa isinstance(parameters[p], list) else [parameters[p].grid_range] for p in names], []), dtype=object) self.constraints = [] if constraints is None else constraints self.nparams = len(names) class Data(ReprMixin): def __init__(self, cfg, stimuli, choices, confidence): """ Container class for behavioral data. Parameters ---------- cfg : configuration.Configuration Settings stimuli : array-like of shape (n_samples) Array of signed stimulus intensity values, where the sign codes the stimulus category (+: cat1; -: cat2) and the absolut value codes the intensity. The scale of the data is not relevant, as a normalisation to [-1; 1] is applied. choices : array-like of shape (n_samples) Array of choices coded as 0 (cat1) and 1 (cat2) for the two stimulus categories. See parameter 'stimuli' for the definition of cat1 and cat2. confidence : array-like of shape (n_samples) Confidence ratings; must be normalized to the range [0;1]. """ self.cfg = cfg self.stimuli_unnorm = np.array(stimuli) self.choices = np.array(choices) self.confidence = np.array(confidence) self.stimuli = None self.stimulus_ids = None self.stimuli_unnorm_max = None self.stimuli_min = None self.correct = None self.stimuli_2d = None self.choices_2d = None self.confidence_2d = None self.nsamples = len(self.stimuli_unnorm) def preproc(self): self.stimulus_ids = (np.sign(self.stimuli_unnorm) == 1).astype(int) self.correct = self.stimulus_ids == self.choices # convert to 0/1 scheme if choices are provides as -1's and 1's if np.array_equal(np.unique(self.choices[~np.isnan(self.choices)]), [-1, 1]): self.choices[self.choices == -1] = 0 self.stimuli_unnorm_max = np.max(np.abs(self.stimuli_unnorm)) # Normalize stimuli if self.cfg.normalize_stimuli_by_max: self.stimuli = self.stimuli_unnorm / self.stimuli_unnorm_max else: if np.max(np.abs(self.stimuli_unnorm)) > 1: raise ValueError('Stimuli are not normalized to the range [-1; 1].') self.stimuli = self.stimuli_unnorm self.stimuli_min = np.abs(self.stimuli).min() if self.cfg.confidence_bounds_error > 0: self.confidence[self.confidence <= self.cfg.confidence_bounds_error] = 0 self.confidence[self.confidence >= 1 - self.cfg.confidence_bounds_error] = 1 self.stimuli_2d = self.stimuli.reshape(-1, 1) self.choices_2d = self.choices.reshape(-1, 1) self.confidence_2d = self.confidence.reshape(-1, 1) def summary(self, full=False): desc = dict( nsamples=self.nsamples ) if full: dict_extended = dict( stimulus_ids=(self.stimuli >= 0).astype(int), stimuli_unnorm=self.stimuli_unnorm, stimuli_norm=self.stimuli, choices=self.choices, confidence=self.confidence ) data_extended = make_dataclass('DataExtended', dict_extended.keys()) data_extended.__module__ = '__main__' desc.update(dict(data=data_extended(**dict_extended))) data_summary = make_dataclass('DataSummary', desc.keys()) def _repr(self_): txt = f'{self_.__class__.__name__}\n' txt += '\n'.join([f"\t{k}: {"<not displayed>" if k == "data" else v}" for k, v in self_.__dict__.items()]) return txt data_summary.__repr__ = _repr data_summary.__module__ = '__main__' return data_summary(**desc) class Model(ReprMixin): def __init__(self, cfg): """ Container class for behavioral data. Parameters ---------- cfg : configuration.Configuration Settings """ self.cfg = cfg self.super_thresh = None self.stimuli_final = None self.stimuli_warped_tresh = None self.stimuli_warped_super = None self.choiceprob = None self.posterior = None self.dv_sens_considered = None self.dv_sens_considered_abs = None self.dv_meta_considered = None self.dv_sens_mode = None self.dv_sens_pmf = None self.dv_sens_pmf_renorm = None self.dv_meta_mode = None self.confidence = None self.likelihood_meta = None self.likelihood_meta_mode = None self.likelihood_meta_weighted_cum = None self.likelihood_meta_weighted_cum_renorm = None self.noise_meta = None self.nsamples_meta = None self.params = None self.params_sens = None self.params_sens_full = None self.params_sens_unnorm = None self.params_meta = None self.likelihood_dist_meta = None self.fit = ModelFit() def store_sens(self, negll, params_sens, choiceprob, posterior, stimuli_final, stimulus_norm_coefficent): self.params_sens = params_sens self.stimuli_final = stimuli_final.reshape(-1, 1) self.choiceprob = choiceprob self.posterior = posterior self.fit.fit_sens.negll = negll if not self.cfg.enable_noise_sens: self.params_sens['noise_sens'] = self.cfg.noise_sens_default self.params_sens_unnorm = {k: list(np.array(v) * stimulus_norm_coefficent) if hasattr(v, '__len__') else v * stimulus_norm_coefficent for k, v in params_sens.items()} def store_meta(self, negll, params_meta, noise_meta, likelihood, dv_meta_considered, likelihood_weighted_cum, likelihood_pdf): self.params_meta = params_meta self.noise_meta = noise_meta self.likelihood_meta = likelihood self.dv_meta_considered = dv_meta_considered if self.cfg.detection_model: col_ind = np.round(np.abs(self.dv_sens_mode)).astype(int) self.dv_meta_mode = dv_meta_considered[np.arange(len(dv_meta_considered)), col_ind] self.likelihood_meta_mode = likelihood[np.arange(len(likelihood)), col_ind] else: self.dv_meta_mode = dv_meta_considered[:, int((dv_meta_considered.shape[1] - 1) / 2)] self.likelihood_meta_mode = likelihood[:, int((likelihood.shape[1] - 1) / 2)] self.likelihood_meta_weighted_cum = likelihood_weighted_cum self.dv_sens_pmf_renorm = self.dv_sens_pmf / np.nansum(self.dv_sens_pmf, axis=1).reshape(-1, 1) self.likelihood_meta_weighted_cum_renorm = np.nansum(likelihood * self.dv_sens_pmf_renorm, axis=1) self.fit.fit_meta.negll = negll self.fit.fit_meta.negll_pdf = -np.sum(np.log(np.maximum(np.nansum(self.dv_sens_pmf * likelihood_pdf, axis=1), 1e-10))) self.nsamples_meta = len(self.confidence) def report_fit_sens(self, verbose=True): if verbose: for k, v in self.params_sens.items(): true_string = '' if self.cfg.true_params is None else \ (f" (true: [{", ".join([f"{p:.3f}' for p in self.cfg.true_params[k]])}])" if # noqa hasattr(self.cfg.true_params[k], '__len__') else f' (true: {self.cfg.true_params[k]:.3f})') # noqa value_string = f"[{", ".join([f"{p:.3f}' for p in v])}]" if hasattr(v, '__len__') else f'{v:.3f}' print(f'{TAB}[final] {k}: {value_string}{true_string}') if hasattr(self.fit.fit_sens, 'execution_time'): print(f'Final stats: {self.fit.fit_sens.execution_time:.2f} secs, {self.fit.fit_sens.nfev} fevs') print(f'Final neg. LL: {self.fit.fit_sens.negll:.2f}') if self.cfg.true_params is not None and hasattr(self.fit.fit_sens, 'negll_true'): print(f'Neg. LL using true params: {self.fit.fit_sens.negll_true:.2f}') def report_fit_meta(self, verbose=True): if self.cfg.true_params is not None: if 'criteria' in self.cfg.meta_link_function: for i, k in enumerate(['', '_neg', '_pos']): if f'slope_or_criteria{k}_meta' in self.cfg.true_params: if '_variable' in self.cfg.meta_link_function: self.cfg.true_params.update( {f"{"confidence_level" if np.mod(i, 2) else "criterion"}_meta_{int(i / 2) + 1}{k}": v for i, v in enumerate(self.cfg.true_params[f'slope_or_criteria{k}_meta'])}) else: self.cfg.true_params.update({f"criterion_meta_{i + 1}{k}": v for i, v in enumerate(self.cfg.true_params[f'slope_or_criteria{k}_meta'])}) if verbose: for k, v in self.params_meta.items(): true_string = '' if self.cfg.true_params is None else \ (f" (true: [{", ".join([f"{p:.3f}' for p in self.cfg.true_params[k]])}])" if hasattr(self.cfg.true_params[k], '__len__') else f' (true: {self.cfg.true_params[k]:.3f})') value_string = f"[{", ".join([f"{p:.3f}' for p in v])}]" if hasattr(v, '__len__') else f'{v:.3f}' print(f'{TAB}[final] {k}: {value_string}{true_string}') if hasattr(self.fit.fit_meta, 'execution_time'): print(f'Final stats: {self.fit.fit_meta.execution_time:.2f} secs, ' f'{self.fit.fit_meta.nfev} fevs') print(f'Final neg. LL: {self.fit.fit_meta.negll:.2f}') if self.cfg.true_params is not None: if verbose: print(f'Neg. LL using true params: {self.fit.fit_meta.negll_true:.2f}') def summary(self, extended=False, fun_meta=None, confidence_gen=None, confidence_emp=None): if not self.cfg.skip_meta: if self.cfg.detection_model: confidence_mode = self.confidence[np.arange(len(self.confidence)), np.round(np.abs(self.dv_sens_mode)).astype(int)] else: confidence_mode = self.confidence[:, int((self.confidence.shape[1] - 1) / 2)] if confidence_gen is not None: confidence_tiled = np.tile(confidence_emp, (confidence_gen.shape[0], 1)) self.fit.fit_meta.confidence_gen_pearson = \ np.tanh(np.nanmean(np.arctanh(pearson2d(confidence_gen, confidence_tiled)))) self.fit.fit_meta.confidence_gen_spearman = \ np.tanh(np.nanmean(np.arctanh( spearman2d(confidence_gen, confidence_tiled, axis=1)))) # ToDo: what is this axis=1 doing here? self.fit.fit_meta.confidence_gen_mae = np.nanmean(np.abs(confidence_gen - confidence_emp)) self.fit.fit_meta.confidence_gen_medae = np.nanmedian(np.abs(confidence_gen - confidence_emp)) self.fit.fit_meta.negll_persample = self.fit.fit_meta.negll / self.nsamples_meta self.fit.fit_meta.negll_mode = -np.nansum(np.log(np.maximum(self.likelihood_meta_mode, 1e-10))) self.fit.negll = self.fit.fit_sens.negll + self.fit.fit_meta.negll desc = dict( nsamples=self.nsamples_meta, nparams_sens=self.cfg.paramset_sens.nparams, params_sens=self.params_sens, params_sens_unnorm=self.params_sens_unnorm, fit=self.fit ) if not self.cfg.skip_meta: desc.update(dict( nparams_meta=self.cfg.paramset_meta.nparams, params_meta=self.params_meta, nparams=self.cfg.paramset_sens.nparams + self.cfg.paramset_meta.nparams, )) if extended: likelihood_01 = fun_meta(self.fit.fit_meta.x, mock_binsize=0.1)[1] likelihood_025 = fun_meta(self.fit.fit_meta.x, mock_binsize=0.25)[1] dict_extended = dict( noise_meta=self.noise_meta, likelihood=self.likelihood_meta, likelihood_mode=self.likelihood_meta_mode, likelihood_weighted_cum=self.likelihood_meta_weighted_cum, likelihood_weighted_cum_renorm_01=np.nansum(likelihood_01 * self.dv_sens_pmf_renorm, axis=1), likelihood_weighted_cum_renorm_025=np.nansum(likelihood_025 * self.dv_sens_pmf_renorm, axis=1), confidence=self.confidence, dv_meta=self.dv_meta_considered, dv_sens=self.dv_sens_considered, dv_sens_pmf=self.dv_sens_pmf, dv_sens_pmf_renorm=self.dv_sens_pmf_renorm, dv_meta_mode=self.dv_meta_mode, dv_sens_mode=self.dv_sens_mode, confidence_mode=confidence_mode, # noqa choiceprob=self.choiceprob, posterior=self.posterior, ) model_extended = make_dataclass('ModelExtended', dict_extended.keys()) model_extended.__module__ = '__main__' desc.update(dict(extended=model_extended(**dict_extended))) model_summary = make_dataclass('ModelSummary', desc.keys()) def _repr(self_): txt = f'{self_.__class__.__name__}' for k, v in self_.__dict__.items(): if k in ('data', 'fit'): txt += f"\n\t{k}: <not displayed>" elif k == 'extended': txt += f"\n\t{k}: additional modeling results (attributes: " \ f"{", ".join([a for a in self_.extended.__dict__.keys()])})" else: txt += f"\n\t{k}: {v}" return txt model_summary.__repr__ = _repr model_summary.__module__ = '__main__' return model_summary(**desc) class ModelFit(ReprMixin): fit_sens: OptimizeResult = None fit_meta: OptimizeResult = None
from dataclasses import make_dataclass import numpy as np from scipy.optimize import OptimizeResult from .util import TAB, ReprMixin, spearman2d, pearson2d class Parameter(ReprMixin): def __init__(self, guess, bounds, grid_range=None): """ Class that defines the fitting characteristics of a Parameter. Parameters ---------- guess : float Initial guess for the parameter value. bounds: array-like of length 2 Parameter bounds. The first and second element indicate the lower and upper bound of the parameter. grid_range: array-like Points to visit in the initial parameter gridsearch search. It makes sense to restrict this to a range of _likely_ values, rather than minimal and maximal bounds. """ self.guess = guess self.bounds = bounds self.grid_range = bounds if grid_range is None else grid_range def copy(self): return Parameter(self.guess, self.bounds, self.grid_range) class ParameterSet(ReprMixin): def __init__(self, parameters, names, constraints=None): """ Container class for all Parameters of a model. Parameters ---------- parameters : dict[str, Parameter] The dictionary must have the form {parameter_name1: Parameter(..), parameter_name2: Parameter(..), ..} names: List[str] List of parameter names of a model. constraints: List[Dict] List of scipy minimize constraints (each constraint is a dictionary with keys 'type' and 'fun'} """ self.base_names = names self.base_is_multiple = [isinstance(parameters[p], list) for p in names] self.base_len = [len(parameters[p]) if isinstance(parameters[p], list) else 1 for p in names] # noqa self.names = sum([[f'{p}_{i}' for i in range(len(parameters[p]))] if isinstance(parameters[p], list) # noqa else [p] for p in names], []) self.guess = np.array(sum([[parameters[p][i].guess for i in range(len(parameters[p]))] if # noqa isinstance(parameters[p], list) else [parameters[p].guess] for p in names], [])) self.bounds = np.array(sum([[parameters[p][i].bounds for i in range(len(parameters[p]))] if # noqa isinstance(parameters[p], list) else [parameters[p].bounds] for p in names], [])) self.grid_range = np.array(sum([[parameters[p][i].grid_range for i in range(len(parameters[p]))] if # noqa isinstance(parameters[p], list) else [parameters[p].grid_range] for p in names], []), dtype=object) self.constraints = [] if constraints is None else constraints self.nparams = len(names) class Data(ReprMixin): def __init__(self, cfg, stimuli, choices, confidence): """ Container class for behavioral data. Parameters ---------- cfg : configuration.Configuration Settings stimuli : array-like of shape (n_samples) Array of signed stimulus intensity values, where the sign codes the stimulus category (+: cat1; -: cat2) and the absolut value codes the intensity. The scale of the data is not relevant, as a normalisation to [-1; 1] is applied. choices : array-like of shape (n_samples) Array of choices coded as 0 (cat1) and 1 (cat2) for the two stimulus categories. See parameter 'stimuli' for the definition of cat1 and cat2. confidence : array-like of shape (n_samples) Confidence ratings; must be normalized to the range [0;1]. """ self.cfg = cfg self.stimuli_unnorm = np.array(stimuli) self.choices = np.array(choices) self.confidence = np.array(confidence) self.stimuli = None self.stimulus_ids = None self.stimuli_unnorm_max = None self.stimuli_min = None self.correct = None self.stimuli_2d = None self.choices_2d = None self.confidence_2d = None self.nsamples = len(self.stimuli_unnorm) def preproc(self): self.stimulus_ids = (np.sign(self.stimuli_unnorm) == 1).astype(int) self.correct = self.stimulus_ids == self.choices # convert to 0/1 scheme if choices are provides as -1's and 1's if np.array_equal(np.unique(self.choices[~np.isnan(self.choices)]), [-1, 1]): self.choices[self.choices == -1] = 0 self.stimuli_unnorm_max = np.max(np.abs(self.stimuli_unnorm)) # Normalize stimuli if self.cfg.normalize_stimuli_by_max: self.stimuli = self.stimuli_unnorm / self.stimuli_unnorm_max else: if np.max(np.abs(self.stimuli_unnorm)) > 1: raise ValueError('Stimuli are not normalized to the range [-1; 1].') self.stimuli = self.stimuli_unnorm self.stimuli_min = np.abs(self.stimuli).min() if self.cfg.confidence_bounds_error > 0: self.confidence[self.confidence <= self.cfg.confidence_bounds_error] = 0 self.confidence[self.confidence >= 1 - self.cfg.confidence_bounds_error] = 1 self.stimuli_2d = self.stimuli.reshape(-1, 1) self.choices_2d = self.choices.reshape(-1, 1) self.confidence_2d = self.confidence.reshape(-1, 1) def summary(self, full=False): desc = dict( nsamples=self.nsamples ) if full: dict_extended = dict( stimulus_ids=(self.stimuli >= 0).astype(int), stimuli_unnorm=self.stimuli_unnorm, stimuli_norm=self.stimuli, choices=self.choices, confidence=self.confidence ) data_extended = make_dataclass('DataExtended', dict_extended.keys()) data_extended.__module__ = '__main__' desc.update(dict(data=data_extended(**dict_extended))) data_summary = make_dataclass('DataSummary', desc.keys()) def _repr(self_): txt = f'{self_.__class__.__name__}\n' txt += '\n'.join([f"\t{k}: {'<not displayed>' if k == 'data' else v}" for k, v in self_.__dict__.items()]) return txt data_summary.__repr__ = _repr data_summary.__module__ = '__main__' return data_summary(**desc) class Model(ReprMixin): def __init__(self, cfg): """ Container class for behavioral data. Parameters ---------- cfg : configuration.Configuration Settings """ self.cfg = cfg self.super_thresh = None self.stimuli_final = None self.stimuli_warped_tresh = None self.stimuli_warped_super = None self.choiceprob = None self.posterior = None self.dv_sens_considered = None self.dv_sens_considered_abs = None self.dv_meta_considered = None self.dv_sens_mode = None self.dv_sens_pmf = None self.dv_sens_pmf_renorm = None self.dv_meta_mode = None self.confidence = None self.likelihood_meta = None self.likelihood_meta_mode = None self.likelihood_meta_weighted_cum = None self.likelihood_meta_weighted_cum_renorm = None self.noise_meta = None self.nsamples_meta = None self.params = None self.params_sens = None self.params_sens_full = None self.params_sens_unnorm = None self.params_meta = None self.likelihood_dist_meta = None self.fit = ModelFit() def store_sens(self, negll, params_sens, choiceprob, posterior, stimuli_final, stimulus_norm_coefficent): self.params_sens = params_sens self.stimuli_final = stimuli_final.reshape(-1, 1) self.choiceprob = choiceprob self.posterior = posterior self.fit.fit_sens.negll = negll if not self.cfg.enable_noise_sens: self.params_sens['noise_sens'] = self.cfg.noise_sens_default self.params_sens_unnorm = {k: list(np.array(v) * stimulus_norm_coefficent) if hasattr(v, '__len__') else v * stimulus_norm_coefficent for k, v in params_sens.items()} def store_meta(self, negll, params_meta, noise_meta, likelihood, dv_meta_considered, likelihood_weighted_cum, likelihood_pdf): self.params_meta = params_meta self.noise_meta = noise_meta self.likelihood_meta = likelihood self.dv_meta_considered = dv_meta_considered if self.cfg.detection_model: col_ind = np.round(np.abs(self.dv_sens_mode)).astype(int) self.dv_meta_mode = dv_meta_considered[np.arange(len(dv_meta_considered)), col_ind] self.likelihood_meta_mode = likelihood[np.arange(len(likelihood)), col_ind] else: self.dv_meta_mode = dv_meta_considered[:, int((dv_meta_considered.shape[1] - 1) / 2)] self.likelihood_meta_mode = likelihood[:, int((likelihood.shape[1] - 1) / 2)] self.likelihood_meta_weighted_cum = likelihood_weighted_cum self.dv_sens_pmf_renorm = self.dv_sens_pmf / np.nansum(self.dv_sens_pmf, axis=1).reshape(-1, 1) self.likelihood_meta_weighted_cum_renorm = np.nansum(likelihood * self.dv_sens_pmf_renorm, axis=1) self.fit.fit_meta.negll = negll self.fit.fit_meta.negll_pdf = -np.sum(np.log(np.maximum(np.nansum(self.dv_sens_pmf * likelihood_pdf, axis=1), 1e-10))) self.nsamples_meta = len(self.confidence) def report_fit_sens(self, verbose=True): if verbose: for k, v in self.params_sens.items(): true_string = '' if self.cfg.true_params is None else \ (f" (true: [{', '.join([f'{p:.3f}' for p in self.cfg.true_params[k]])}])" if # noqa hasattr(self.cfg.true_params[k], '__len__') else f' (true: {self.cfg.true_params[k]:.3f})') # noqa value_string = f"[{', '.join([f'{p:.3f}' for p in v])}]" if hasattr(v, '__len__') else f'{v:.3f}' print(f'{TAB}[final] {k}: {value_string}{true_string}') if hasattr(self.fit.fit_sens, 'execution_time'): print(f'Final stats: {self.fit.fit_sens.execution_time:.2f} secs, {self.fit.fit_sens.nfev} fevs') print(f'Final neg. LL: {self.fit.fit_sens.negll:.2f}') if self.cfg.true_params is not None and hasattr(self.fit.fit_sens, 'negll_true'): print(f'Neg. LL using true params: {self.fit.fit_sens.negll_true:.2f}') def report_fit_meta(self, verbose=True): if self.cfg.true_params is not None: if 'criteria' in self.cfg.meta_link_function: for i, k in enumerate(['', '_neg', '_pos']): if f'slope_or_criteria{k}_meta' in self.cfg.true_params: if '_variable' in self.cfg.meta_link_function: self.cfg.true_params.update( {f"{'confidence_level' if np.mod(i, 2) else 'criterion'}_meta_{int(i / 2) + 1}{k}": v for i, v in enumerate(self.cfg.true_params[f'slope_or_criteria{k}_meta'])}) else: self.cfg.true_params.update({f"criterion_meta_{i + 1}{k}": v for i, v in enumerate(self.cfg.true_params[f'slope_or_criteria{k}_meta'])}) if verbose: for k, v in self.params_meta.items(): true_string = '' if self.cfg.true_params is None else \ (f" (true: [{', '.join([f'{p:.3f}' for p in self.cfg.true_params[k]])}])" if hasattr(self.cfg.true_params[k], '__len__') else f' (true: {self.cfg.true_params[k]:.3f})') value_string = f"[{', '.join([f'{p:.3f}' for p in v])}]" if hasattr(v, '__len__') else f'{v:.3f}' print(f'{TAB}[final] {k}: {value_string}{true_string}') if hasattr(self.fit.fit_meta, 'execution_time'): print(f'Final stats: {self.fit.fit_meta.execution_time:.2f} secs, ' f'{self.fit.fit_meta.nfev} fevs') print(f'Final neg. LL: {self.fit.fit_meta.negll:.2f}') if self.cfg.true_params is not None: if verbose: print(f'Neg. LL using true params: {self.fit.fit_meta.negll_true:.2f}') def summary(self, extended=False, fun_meta=None, confidence_gen=None, confidence_emp=None): if not self.cfg.skip_meta: if self.cfg.detection_model: confidence_mode = self.confidence[np.arange(len(self.confidence)), np.round(np.abs(self.dv_sens_mode)).astype(int)] else: confidence_mode = self.confidence[:, int((self.confidence.shape[1] - 1) / 2)] if confidence_gen is not None: confidence_tiled = np.tile(confidence_emp, (confidence_gen.shape[0], 1)) self.fit.fit_meta.confidence_gen_pearson = \ np.tanh(np.nanmean(np.arctanh(pearson2d(confidence_gen, confidence_tiled)))) self.fit.fit_meta.confidence_gen_spearman = \ np.tanh(np.nanmean(np.arctanh( spearman2d(confidence_gen, confidence_tiled, axis=1)))) # ToDo: what is this axis=1 doing here? self.fit.fit_meta.confidence_gen_mae = np.nanmean(np.abs(confidence_gen - confidence_emp)) self.fit.fit_meta.confidence_gen_medae = np.nanmedian(np.abs(confidence_gen - confidence_emp)) self.fit.fit_meta.negll_persample = self.fit.fit_meta.negll / self.nsamples_meta self.fit.fit_meta.negll_mode = -np.nansum(np.log(np.maximum(self.likelihood_meta_mode, 1e-10))) self.fit.negll = self.fit.fit_sens.negll + self.fit.fit_meta.negll desc = dict( nsamples=self.nsamples_meta, nparams_sens=self.cfg.paramset_sens.nparams, params_sens=self.params_sens, params_sens_unnorm=self.params_sens_unnorm, fit=self.fit ) if not self.cfg.skip_meta: desc.update(dict( nparams_meta=self.cfg.paramset_meta.nparams, params_meta=self.params_meta, nparams=self.cfg.paramset_sens.nparams + self.cfg.paramset_meta.nparams, )) if extended: likelihood_01 = fun_meta(self.fit.fit_meta.x, mock_binsize=0.1)[1] likelihood_025 = fun_meta(self.fit.fit_meta.x, mock_binsize=0.25)[1] dict_extended = dict( noise_meta=self.noise_meta, likelihood=self.likelihood_meta, likelihood_mode=self.likelihood_meta_mode, likelihood_weighted_cum=self.likelihood_meta_weighted_cum, likelihood_weighted_cum_renorm_01=np.nansum(likelihood_01 * self.dv_sens_pmf_renorm, axis=1), likelihood_weighted_cum_renorm_025=np.nansum(likelihood_025 * self.dv_sens_pmf_renorm, axis=1), confidence=self.confidence, dv_meta=self.dv_meta_considered, dv_sens=self.dv_sens_considered, dv_sens_pmf=self.dv_sens_pmf, dv_sens_pmf_renorm=self.dv_sens_pmf_renorm, dv_meta_mode=self.dv_meta_mode, dv_sens_mode=self.dv_sens_mode, confidence_mode=confidence_mode, # noqa choiceprob=self.choiceprob, posterior=self.posterior, ) model_extended = make_dataclass('ModelExtended', dict_extended.keys()) model_extended.__module__ = '__main__' desc.update(dict(extended=model_extended(**dict_extended))) model_summary = make_dataclass('ModelSummary', desc.keys()) def _repr(self_): txt = f'{self_.__class__.__name__}' for k, v in self_.__dict__.items(): if k in ('data', 'fit'): txt += f"\n\t{k}: <not displayed>" elif k == 'extended': txt += f"\n\t{k}: additional modeling results (attributes: " \ f"{', '.join([a for a in self_.extended.__dict__.keys()])})" else: txt += f"\n\t{k}: {v}" return txt model_summary.__repr__ = _repr model_summary.__module__ = '__main__' return model_summary(**desc) class ModelFit(ReprMixin): fit_sens: OptimizeResult = None fit_meta: OptimizeResult = None
import abc import typing as t from collections import namedtuple import discord.errors from botcore.site_api import ResponseCodeError from discord import Guild from discord.ext.commands import Context from more_itertools import chunked import bot from bot.log import get_logger log = get_logger(__name__) CHUNK_SIZE = 1000 # These objects are declared as namedtuples because tuples are hashable, # something that we make use of when diffing site roles against guild roles. _Role = namedtuple('Role', ('id', 'name', 'colour', 'permissions', 'position')) _Diff = namedtuple('Diff', ('created', 'updated', 'deleted')) # Implementation of static abstract methods are not enforced if the subclass is never instantiated. # However, methods are kept abstract to at least symbolise that they should be abstract. class Syncer(abc.ABC): """Base class for synchronising the database with objects in the Discord cache.""" @staticmethod @property @abc.abstractmethod def name() -> str: """The name of the syncer; used in output messages and logging.""" raise NotImplementedError # pragma: no cover @staticmethod @abc.abstractmethod async def _get_diff(guild: Guild) -> _Diff: """Return the difference between the cache of `guild` and the database.""" raise NotImplementedError # pragma: no cover @staticmethod @abc.abstractmethod async def _sync(diff: _Diff) -> None: """Perform the API calls for synchronisation.""" raise NotImplementedError # pragma: no cover @classmethod async def sync(cls, guild: Guild, ctx: t.Optional[Context] = None) -> None: """ Synchronise the database with the cache of `guild`. If `ctx` is given, send a message with the results. """ log.info(f"Starting {cls.name} syncer.") if ctx: message = await ctx.send(f"📊 Synchronising {cls.name}s.") else: message = None diff = await cls._get_diff(guild) try: await cls._sync(diff) except ResponseCodeError as e: log.exception(f"{cls.name} syncer failed!") # Don't show response text because it's probably some really long HTML. results = f"status {e.status}\n```{e.response_json or "See log output for details"}```" content = f":x: Synchronisation of {cls.name}s failed: {results}" else: diff_dict = diff._asdict() results = (f"{name} `{len(val)}`" for name, val in diff_dict.items() if val is not None) results = ", ".join(results) log.info(f"{cls.name} syncer finished: {results}.") content = f":ok_hand: Synchronisation of {cls.name}s complete: {results}" if message: await message.edit(content=content) class RoleSyncer(Syncer): """Synchronise the database with roles in the cache.""" name = "role" @staticmethod async def _get_diff(guild: Guild) -> _Diff: """Return the difference of roles between the cache of `guild` and the database.""" log.trace("Getting the diff for roles.") roles = await bot.instance.api_client.get('bot/roles') # Pack DB roles and guild roles into one common, hashable format. # They're hashable so that they're easily comparable with sets later. db_roles = {_Role(**role_dict) for role_dict in roles} guild_roles = { _Role( id=role.id, name=role.name, colour=role.colour.value, permissions=role.permissions.value, position=role.position, ) for role in guild.roles } guild_role_ids = {role.id for role in guild_roles} api_role_ids = {role.id for role in db_roles} new_role_ids = guild_role_ids - api_role_ids deleted_role_ids = api_role_ids - guild_role_ids # New roles are those which are on the cached guild but not on the # DB guild, going by the role ID. We need to send them in for creation. roles_to_create = {role for role in guild_roles if role.id in new_role_ids} roles_to_update = guild_roles - db_roles - roles_to_create roles_to_delete = {role for role in db_roles if role.id in deleted_role_ids} return _Diff(roles_to_create, roles_to_update, roles_to_delete) @staticmethod async def _sync(diff: _Diff) -> None: """Synchronise the database with the role cache of `guild`.""" log.trace("Syncing created roles...") for role in diff.created: await bot.instance.api_client.post('bot/roles', json=role._asdict()) log.trace("Syncing updated roles...") for role in diff.updated: await bot.instance.api_client.put(f'bot/roles/{role.id}', json=role._asdict()) log.trace("Syncing deleted roles...") for role in diff.deleted: await bot.instance.api_client.delete(f'bot/roles/{role.id}') class UserSyncer(Syncer): """Synchronise the database with users in the cache.""" name = "user" @staticmethod async def _get_diff(guild: Guild) -> _Diff: """Return the difference of users between the cache of `guild` and the database.""" log.trace("Getting the diff for users.") users_to_create = [] users_to_update = [] seen_guild_users = set() async for db_user in UserSyncer._get_users(): # Store user fields which are to be updated. updated_fields = {} def maybe_update(db_field: str, guild_value: t.Union[str, int]) -> None: # Equalize DB user and guild user attributes. if db_user[db_field] != guild_value: updated_fields[db_field] = guild_value guild_user = guild.get_member(db_user["id"]) if not guild_user and db_user["in_guild"]: # The member was in the guild during the last sync. # We try to fetch them to verify cache integrity. try: guild_user = await guild.fetch_member(db_user["id"]) except discord.errors.NotFound: guild_user = None if guild_user: seen_guild_users.add(guild_user.id) maybe_update("name", guild_user.name) maybe_update("discriminator", int(guild_user.discriminator)) maybe_update("in_guild", True) guild_roles = [role.id for role in guild_user.roles] if set(db_user["roles"]) != set(guild_roles): updated_fields["roles"] = guild_roles elif db_user["in_guild"]: # The user is known in the DB but not the guild, and the # DB currently specifies that the user is a member of the guild. # This means that the user has left since the last sync. # Update the `in_guild` attribute of the user on the site # to signify that the user left. updated_fields["in_guild"] = False if updated_fields: updated_fields["id"] = db_user["id"] users_to_update.append(updated_fields) for member in guild.members: if member.id not in seen_guild_users: # The user is known on the guild but not on the API. This means # that the user has joined since the last sync. Create it. new_user = { "id": member.id, "name": member.name, "discriminator": int(member.discriminator), "roles": [role.id for role in member.roles], "in_guild": True } users_to_create.append(new_user) return _Diff(users_to_create, users_to_update, None) @staticmethod async def _get_users() -> t.AsyncIterable: """GET users from database.""" query_params = { "page": 1 } while query_params["page"]: res = await bot.instance.api_client.get("bot/users", params=query_params) for user in res["results"]: yield user query_params["page"] = res["next_page_no"] @staticmethod async def _sync(diff: _Diff) -> None: """Synchronise the database with the user cache of `guild`.""" # Using asyncio.gather would still consume too many resources on the site. log.trace("Syncing created users...") if diff.created: for chunk in chunked(diff.created, CHUNK_SIZE): await bot.instance.api_client.post("bot/users", json=chunk) log.trace("Syncing updated users...") if diff.updated: for chunk in chunked(diff.updated, CHUNK_SIZE): await bot.instance.api_client.patch("bot/users/bulk_patch", json=chunk)
import abc import typing as t from collections import namedtuple import discord.errors from botcore.site_api import ResponseCodeError from discord import Guild from discord.ext.commands import Context from more_itertools import chunked import bot from bot.log import get_logger log = get_logger(__name__) CHUNK_SIZE = 1000 # These objects are declared as namedtuples because tuples are hashable, # something that we make use of when diffing site roles against guild roles. _Role = namedtuple('Role', ('id', 'name', 'colour', 'permissions', 'position')) _Diff = namedtuple('Diff', ('created', 'updated', 'deleted')) # Implementation of static abstract methods are not enforced if the subclass is never instantiated. # However, methods are kept abstract to at least symbolise that they should be abstract. class Syncer(abc.ABC): """Base class for synchronising the database with objects in the Discord cache.""" @staticmethod @property @abc.abstractmethod def name() -> str: """The name of the syncer; used in output messages and logging.""" raise NotImplementedError # pragma: no cover @staticmethod @abc.abstractmethod async def _get_diff(guild: Guild) -> _Diff: """Return the difference between the cache of `guild` and the database.""" raise NotImplementedError # pragma: no cover @staticmethod @abc.abstractmethod async def _sync(diff: _Diff) -> None: """Perform the API calls for synchronisation.""" raise NotImplementedError # pragma: no cover @classmethod async def sync(cls, guild: Guild, ctx: t.Optional[Context] = None) -> None: """ Synchronise the database with the cache of `guild`. If `ctx` is given, send a message with the results. """ log.info(f"Starting {cls.name} syncer.") if ctx: message = await ctx.send(f"📊 Synchronising {cls.name}s.") else: message = None diff = await cls._get_diff(guild) try: await cls._sync(diff) except ResponseCodeError as e: log.exception(f"{cls.name} syncer failed!") # Don't show response text because it's probably some really long HTML. results = f"status {e.status}\n```{e.response_json or 'See log output for details'}```" content = f":x: Synchronisation of {cls.name}s failed: {results}" else: diff_dict = diff._asdict() results = (f"{name} `{len(val)}`" for name, val in diff_dict.items() if val is not None) results = ", ".join(results) log.info(f"{cls.name} syncer finished: {results}.") content = f":ok_hand: Synchronisation of {cls.name}s complete: {results}" if message: await message.edit(content=content) class RoleSyncer(Syncer): """Synchronise the database with roles in the cache.""" name = "role" @staticmethod async def _get_diff(guild: Guild) -> _Diff: """Return the difference of roles between the cache of `guild` and the database.""" log.trace("Getting the diff for roles.") roles = await bot.instance.api_client.get('bot/roles') # Pack DB roles and guild roles into one common, hashable format. # They're hashable so that they're easily comparable with sets later. db_roles = {_Role(**role_dict) for role_dict in roles} guild_roles = { _Role( id=role.id, name=role.name, colour=role.colour.value, permissions=role.permissions.value, position=role.position, ) for role in guild.roles } guild_role_ids = {role.id for role in guild_roles} api_role_ids = {role.id for role in db_roles} new_role_ids = guild_role_ids - api_role_ids deleted_role_ids = api_role_ids - guild_role_ids # New roles are those which are on the cached guild but not on the # DB guild, going by the role ID. We need to send them in for creation. roles_to_create = {role for role in guild_roles if role.id in new_role_ids} roles_to_update = guild_roles - db_roles - roles_to_create roles_to_delete = {role for role in db_roles if role.id in deleted_role_ids} return _Diff(roles_to_create, roles_to_update, roles_to_delete) @staticmethod async def _sync(diff: _Diff) -> None: """Synchronise the database with the role cache of `guild`.""" log.trace("Syncing created roles...") for role in diff.created: await bot.instance.api_client.post('bot/roles', json=role._asdict()) log.trace("Syncing updated roles...") for role in diff.updated: await bot.instance.api_client.put(f'bot/roles/{role.id}', json=role._asdict()) log.trace("Syncing deleted roles...") for role in diff.deleted: await bot.instance.api_client.delete(f'bot/roles/{role.id}') class UserSyncer(Syncer): """Synchronise the database with users in the cache.""" name = "user" @staticmethod async def _get_diff(guild: Guild) -> _Diff: """Return the difference of users between the cache of `guild` and the database.""" log.trace("Getting the diff for users.") users_to_create = [] users_to_update = [] seen_guild_users = set() async for db_user in UserSyncer._get_users(): # Store user fields which are to be updated. updated_fields = {} def maybe_update(db_field: str, guild_value: t.Union[str, int]) -> None: # Equalize DB user and guild user attributes. if db_user[db_field] != guild_value: updated_fields[db_field] = guild_value guild_user = guild.get_member(db_user["id"]) if not guild_user and db_user["in_guild"]: # The member was in the guild during the last sync. # We try to fetch them to verify cache integrity. try: guild_user = await guild.fetch_member(db_user["id"]) except discord.errors.NotFound: guild_user = None if guild_user: seen_guild_users.add(guild_user.id) maybe_update("name", guild_user.name) maybe_update("discriminator", int(guild_user.discriminator)) maybe_update("in_guild", True) guild_roles = [role.id for role in guild_user.roles] if set(db_user["roles"]) != set(guild_roles): updated_fields["roles"] = guild_roles elif db_user["in_guild"]: # The user is known in the DB but not the guild, and the # DB currently specifies that the user is a member of the guild. # This means that the user has left since the last sync. # Update the `in_guild` attribute of the user on the site # to signify that the user left. updated_fields["in_guild"] = False if updated_fields: updated_fields["id"] = db_user["id"] users_to_update.append(updated_fields) for member in guild.members: if member.id not in seen_guild_users: # The user is known on the guild but not on the API. This means # that the user has joined since the last sync. Create it. new_user = { "id": member.id, "name": member.name, "discriminator": int(member.discriminator), "roles": [role.id for role in member.roles], "in_guild": True } users_to_create.append(new_user) return _Diff(users_to_create, users_to_update, None) @staticmethod async def _get_users() -> t.AsyncIterable: """GET users from database.""" query_params = { "page": 1 } while query_params["page"]: res = await bot.instance.api_client.get("bot/users", params=query_params) for user in res["results"]: yield user query_params["page"] = res["next_page_no"] @staticmethod async def _sync(diff: _Diff) -> None: """Synchronise the database with the user cache of `guild`.""" # Using asyncio.gather would still consume too many resources on the site. log.trace("Syncing created users...") if diff.created: for chunk in chunked(diff.created, CHUNK_SIZE): await bot.instance.api_client.post("bot/users", json=chunk) log.trace("Syncing updated users...") if diff.updated: for chunk in chunked(diff.updated, CHUNK_SIZE): await bot.instance.api_client.patch("bot/users/bulk_patch", json=chunk)
from io import StringIO import json import shutil default_dir_schema = 'schema.json' class Schema: """ {[clear] -> load} -> [create] -> (safe) edit -> dump note: [] is optional, {} is init states: loaded -> created """ def __init__(self, dir_schema: str=None) -> None: self.schema = {} self.info = [] self.paragraph = [] self.summary = [] self.loaded = False self.identical = False self.dir_schema = default_dir_schema if dir_schema is None else dir_schema def clear(self): self.schema.clear() return self def load(self, output=False): with open(self.dir_schema, 'r') as f: self.schema = json.load(f) if output: print(json.dumps(self.schema, indent=4)) try: self.info = self.schema['info'] self.paragraph = self.schema['paragraph'] self.summary = self.schema['summary'] except KeyError as e: print(f"{e}") print("Error: broken schema.") self.loaded = False self.clear() else: self.loaded = True return self def create(self): if self.loaded: self.schema.update({'session':{ 'info': {}.fromkeys(self.info, ""), 'para_list': [], 'summary': {}.fromkeys(self.summary, "") }}) else: print("Error: create while unloaded.") return self def dump(self): if self.loaded: shutil.copyfile(self.dir_schema, f'{self.dir_schema}.bak') with open(self.dir_schema, 'w') as f: json.dump(self.schema, f, indent=4) else: print("Error: dump while unloaded.") return self ''' is_ utils''' def is_identical(self): if not self.loaded: return False for prop in ['info', 'summary']: for item in self.schema[prop]: if not item in self.schema['session'][prop].keys(): return False for item_ses in self.schema['session']['para_list']: for item in item_ses: if not item in self.schema['paragraph']: return False return True @staticmethod def valid_str(string: str): return string != "" and not string.isspace() def input_prop_item(self, prop: str, item: str): previous = self.schema['session'][prop][item] filling = input(f'{item} {f'({previous})' if self.valid_str(previous) else ''}: ') self.schema['session'][prop][item] = filling if not (filling.isspace() or filling == "") else previous def input_prop(self, prop: str): for item in self.schema[prop]: self.input_prop_item(prop, item) def input_para_item(self, index: int, item: str): para_list = self.schema['session']['para_list'] previous = para_list[index][item] filling = input(f'{item} {f'({previous})' if self.valid_str(previous) else ''}: ') para_list[index][item] = filling if not (filling.isspace() or filling == "") else previous def input_para(self, index: int=None): if index is None: para_list = self.schema['session']['para_list'] index = len(para_list) if index == 0: para_list.append({}.fromkeys(self.paragraph, "")) print("Appended para.") else: index -= 1 print(f"Inputting: para {index}.") for item in self.paragraph: self.input_para_item(index, item) def input(self) -> bool: """ create and continue if not identical """ if not self.is_identical(): self.create() self.input_prop('info') while True: self.input_para() filling = input('Another paragraph? [Y/n] ') if filling.lower() != 'y': break self.input_prop('summary') return True def output(self, verbose: bool=False) -> None: if verbose: print(json.dumps(self.schema, indent=4)) else: print(json.dumps(self.schema['session'], indent=4)) @staticmethod def dumps(obj): return json.dumps(obj, indent=4) def content_fixed(self) -> dict: if not (self.loaded and self.is_identical()): return None content = {} content.update(self.schema['session']['info']) content.update(self.schema['session']['summary']) content.update(self.schema['session']['para_list'][0]) # Todo: remove para_list # print(json.dumps(content, indent=4)) return content if __name__ == "__main__": schema = Schema(default_dir_schema).load() # schema.output(verbose=True) # schema.input() # schema.output() schema.content() schema.dump()
from io import StringIO import json import shutil default_dir_schema = 'schema.json' class Schema: """ {[clear] -> load} -> [create] -> (safe) edit -> dump note: [] is optional, {} is init states: loaded -> created """ def __init__(self, dir_schema: str=None) -> None: self.schema = {} self.info = [] self.paragraph = [] self.summary = [] self.loaded = False self.identical = False self.dir_schema = default_dir_schema if dir_schema is None else dir_schema def clear(self): self.schema.clear() return self def load(self, output=False): with open(self.dir_schema, 'r') as f: self.schema = json.load(f) if output: print(json.dumps(self.schema, indent=4)) try: self.info = self.schema['info'] self.paragraph = self.schema['paragraph'] self.summary = self.schema['summary'] except KeyError as e: print(f"{e}") print("Error: broken schema.") self.loaded = False self.clear() else: self.loaded = True return self def create(self): if self.loaded: self.schema.update({'session':{ 'info': {}.fromkeys(self.info, ""), 'para_list': [], 'summary': {}.fromkeys(self.summary, "") }}) else: print("Error: create while unloaded.") return self def dump(self): if self.loaded: shutil.copyfile(self.dir_schema, f'{self.dir_schema}.bak') with open(self.dir_schema, 'w') as f: json.dump(self.schema, f, indent=4) else: print("Error: dump while unloaded.") return self ''' is_ utils''' def is_identical(self): if not self.loaded: return False for prop in ['info', 'summary']: for item in self.schema[prop]: if not item in self.schema['session'][prop].keys(): return False for item_ses in self.schema['session']['para_list']: for item in item_ses: if not item in self.schema['paragraph']: return False return True @staticmethod def valid_str(string: str): return string != "" and not string.isspace() def input_prop_item(self, prop: str, item: str): previous = self.schema['session'][prop][item] filling = input(f'{item} {f"({previous})" if self.valid_str(previous) else ""}: ') self.schema['session'][prop][item] = filling if not (filling.isspace() or filling == "") else previous def input_prop(self, prop: str): for item in self.schema[prop]: self.input_prop_item(prop, item) def input_para_item(self, index: int, item: str): para_list = self.schema['session']['para_list'] previous = para_list[index][item] filling = input(f'{item} {f"({previous})" if self.valid_str(previous) else ""}: ') para_list[index][item] = filling if not (filling.isspace() or filling == "") else previous def input_para(self, index: int=None): if index is None: para_list = self.schema['session']['para_list'] index = len(para_list) if index == 0: para_list.append({}.fromkeys(self.paragraph, "")) print("Appended para.") else: index -= 1 print(f"Inputting: para {index}.") for item in self.paragraph: self.input_para_item(index, item) def input(self) -> bool: """ create and continue if not identical """ if not self.is_identical(): self.create() self.input_prop('info') while True: self.input_para() filling = input('Another paragraph? [Y/n] ') if filling.lower() != 'y': break self.input_prop('summary') return True def output(self, verbose: bool=False) -> None: if verbose: print(json.dumps(self.schema, indent=4)) else: print(json.dumps(self.schema['session'], indent=4)) @staticmethod def dumps(obj): return json.dumps(obj, indent=4) def content_fixed(self) -> dict: if not (self.loaded and self.is_identical()): return None content = {} content.update(self.schema['session']['info']) content.update(self.schema['session']['summary']) content.update(self.schema['session']['para_list'][0]) # Todo: remove para_list # print(json.dumps(content, indent=4)) return content if __name__ == "__main__": schema = Schema(default_dir_schema).load() # schema.output(verbose=True) # schema.input() # schema.output() schema.content() schema.dump()
import subprocess, os, struct from . import flatten_list, _monitor_brand_lookup class _EDID: ''' simple structure and method to extract monitor serial and name from an EDID string. The EDID parsing was created with inspiration from the [pyedid library](https://github.com/jojonas/pyedid) ''' EDID_FORMAT = (">" # big-endian "8s" # constant header (8 bytes) "H" # manufacturer id (2 bytes) "H" # product id (2 bytes) "I" # serial number (4 bytes) "B" # manufactoring week (1 byte) "B" # manufactoring year (1 byte) "B" # edid version (1 byte) "B" # edid revision (1 byte) "B" # video input type (1 byte) "B" # horizontal size in cm (1 byte) "B" # vertical size in cm (1 byte) "B" # display gamma (1 byte) "B" # supported features (1 byte) "10s" # color characteristics (10 bytes) "H" # supported timings (2 bytes) "B" # reserved timing (1 byte) "16s" # EDID supported timings (16 bytes) "18s" # detailed timing block 1 (18 bytes) "18s" # detailed timing block 2 (18 bytes) "18s" # detailed timing block 3 (18 bytes) "18s" # detailed timing block 4 (18 bytes) "B" # extension flag (1 byte) "B") # checksum (1 byte) def parse_edid(edid): '''internal function, do not call''' def filter_hex(st): st = str(st) while '\\x' in st: i = st.index('\\x') st = st.replace(st[i:i+4], '') return st.replace('\\n','')[2:-1] if ' ' in edid: edid = edid.replace(' ','') edid = bytes.fromhex(edid) data = struct.unpack(_EDID.EDID_FORMAT, edid) serial = filter_hex(data[18]) #other info can be anywhere in this range, I don't know why name = None for i in data[19:22]: try: st = str(i)[2:-1].rstrip(' ').rstrip('\t') if st.index(' ')<len(st)-1: name = filter_hex(i).split(' ') name = name[0].lower().capitalize()+' '+name[1] except:pass return name, serial class Light: '''collection of screen brightness related methods using the light executable''' executable = 'light' '''the light executable to be called''' def __filter_monitors(display, *args): '''internal function, do not call''' monitors = Light.get_display_info() if len(args)==0 else args[0] if type(display) is int: return monitors[display] else: return [i for i in monitors if display in (i['name'], i['edid'], i['path'], i['edid'])] def get_display_info(*args): ''' Returns information about detected displays as reported by Light Args: monitor (str or int): [*Optional*] the monitor to return information about. Can be index, name, path or edid Returns: list: list of dictionaries if no monitor is specified dict: if a monitor is specified Example: ```python import screen_brightness_control as sbc # get info about all monitors info = sbc.linux.Light.get_display_info() # EG output: [{'name': 'edp-backlight', 'path': '/sys/class/backlight/edp-backlight', edid': '00ffffffffffff00'...}] # get info about the primary monitor primary_info = sbc.linux.Light.get_display_info(0) # get info about a monitor called 'edp-backlight' edp_info = sbc.linux.Light.get_display_info('edp-backlight') ``` ''' res=subprocess.run([Light.executable, '-L'],stdout=subprocess.PIPE).stdout.decode().split('\n') displays = [] count=0 for r in res: if 'backlight' in r and 'sysfs/backlight/auto' not in r: r = r[r.index('backlight/')+10:] if os.path.isdir(f'/sys/class/backlight/{r}'): tmp = {'name':r, 'path': f'/sys/class/backlight/{r}', 'light_path': f'sysfs/backlight/{r}', 'method': Light, 'index':count, 'model':None, 'serial':None, 'manufacturer':None, 'manufacturer_id':None, 'edid':None} count+=1 if os.path.isfile(tmp['path']+'/device/edid'): try: out = subprocess.check_output(['hexdump', tmp['path']+'/device/edid'], stderr=subprocess.DEVNULL).decode().split('\n') #either the hexdump reports each hex char backwards (ff00 instead of 00ff) or both xrandr and ddcutil do so I swap these bits around edid = '' for line in out: line = line.split(' ') for i in line: if len(i)==4: edid+=i[2:]+i[:2] tmp['edid'] = edid name, serial = _EDID.parse_edid(edid) if name!=None: tmp['serial'] = serial tmp['name'] = name tmp['manufacturer'] = name.split(' ')[0] tmp['manufacturer_id'] = _monitor_brand_lookup(tmp['manufacturer']) tmp['model'] = name.split(' ')[1] except: pass displays.append(tmp) if len(args)==1: displays = Light.__filter_monitors(args[0], displays) if len(displays)==1: displays = displays[0] return displays def get_display_names(): ''' Returns the names of each display, as reported by light Returns: list: list of strings Example: ```python import screen_brightness_control as sbc names = sbc.linux.Light.get_display_names() # EG output: ['edp-backlight'] ``` ''' return [i['name'] for i in Light.get_display_info()] def set_brightness(value, display = None, no_return = False): ''' Sets the brightness for a display using the light executable Args: value (int): Sets the brightness to this value display (int or str): The index, name, edid or path of the display you wish to change no_return (bool): if True, this function returns None Returns: The result of `Light.get_brightness()` or `None` (see `no_return` kwarg) Example: ```python import screen_brightness_control as sbc # set the brightness to 50% sbc.linux.Light.set_brightness(50) # set the primary display brightness to 75% sbc.linux.Light.set_brightness(75, display = 0) # set the display called 'edp-backlight' to 25% sbc.linux.Light.set_brightness(75, display = 'edp-backlight') ``` ''' info = Light.get_display_info() if display!=None: info = Light.__filter_monitors(display, info) for i in info: light_path = i['light_path'] command = f'{Light.executable} -S {value} -s {light_path}' subprocess.call(command.split(" ")) return Light.get_brightness(display=display) if not no_return else None def get_brightness(display = None): ''' Sets the brightness for a display using the light executable Args: display (int or str): display (int or str): The index, name, edid or path of the display you wish to query Returns: int: from 0 to 100 if only one display is detected list: list of integers if multiple displays are detected Example: ```python import screen_brightness_control as sbc # get the current display brightness current_brightness = sbc.linux.Light.get_brightness() # get the brightness of the primary display primary_brightness = sbc.linux.Light.get_brightness(display = 0) # get the brightness of the display called 'edp-backlight' edp_brightness = sbc.linux.Light.get_brightness(display = 'edp-backlight') ``` ''' info = Light.get_display_info() if display!=None: info = Light.__filter_monitors(display, info) results = [] for i in info: light_path = i['light_path'] command = f'{Light.executable} -G -s {light_path}' results.append(subprocess.run(command.split(' '),stdout=subprocess.PIPE).stdout.decode()) results = [int(round(float(str(i)),0)) for i in results] return results[0] if len(results)==1 else results class XBacklight: '''collection of screen brightness related methods using the xbacklight executable''' executable = 'xbacklight' '''the xbacklight executable to be called''' def set_brightness(value, no_return = False, **kwargs): ''' Sets the screen brightness to a supplied value Args: no_return (bool): if True, this function returns None, returns the result of self.get_brightness() otherwise Returns: int: from 0 to 100 None: if `no_return` is set to `True` Example: ```python import screen_brightness_control as sbc # set the brightness to 100% sbc.linux.XBacklight.set_brightness(100) ``` ''' subprocess.call([XBacklight.executable, '-set', str(value)]) return XBacklight.get_brightness() if not no_return else None def get_brightness(**kwargs): ''' Returns the screen brightness as reported by xbacklight Returns: int: from 0 to 100 Example: ```python import screen_brightness_control as sbc current_brightness = sbc.linux.XBacklight.get_brightness() ``` ''' res=subprocess.run([XBacklight.executable, '-get'],stdout=subprocess.PIPE).stdout.decode() return int(round(float(str(res)),0)) class XRandr: '''collection of screen brightness related methods using the xrandr executable''' executable = 'xrandr' '''the xrandr executable to be called''' def __filter_monitors(display, *args): '''internal function, do not call''' monitors = XRandr.get_display_info() if len(args)==0 else args[0] if type(display) is int: return monitors[display] else: return [i for i in monitors if display in (i['name'], i['serial'], i['interface'], i['model'], i['edid'])] def get_display_info(*args): ''' Returns a dictionary of info about all detected monitors as reported by xrandr Args: monitor (str or int): [*Optional*] the monitor to return info about. Pass in the serial number, name, model, interface or index Returns: list: list of dictonaries if a monitor is not specified or the given `monitor` argument has multiple matches dict: one dictionary if a monitor is specified and only one match is found Example: ```python import screen_brightness_control as sbc info = sbc.linux.XRandr.get_display_info() for i in info: print('================') for key, value in i.items(): print(key, ':', value) # get information about the first XRandr addressable monitor primary_info = sbc.linux.XRandr.get_display_info(0) # get information about a monitor with a specific name benq_info = sbc.linux.XRandr.get_display_info('BenQ GL2450HM') ``` ''' out = [i for i in subprocess.check_output([XRandr.executable, '--verbose']).decode().split('\n') if i!=''] names = XRandr.get_display_interfaces() data = [] tmp = {} count = 0 for i in out: if i.startswith(tuple(names)): data.append(tmp) tmp = {'interface':i.split(' ')[0], 'line':i, 'method':XRandr, 'index':count, 'model':None, 'serial':None, 'manufacturer':None, 'manufacturer_id':None, 'edid':None} count+=1 elif 'EDID:' in i: st = out[out.index(tmp['line']):] edid = [st[j].replace('\t','').replace(' ', '') for j in range(st.index(i)+1, st.index(i)+9)] edid = ''.join(edid) tmp['edid'] = edid name, serial = _EDID.parse_edid(edid) tmp['name'] = name if name!=None else tmp['interface'] if name!=None: tmp['manufacturer'] = name.split(' ')[0] tmp['manufacturer_id'] = _monitor_brand_lookup(tmp['manufacturer']) tmp['model'] = name.split(' ')[1] tmp['serial'] = serial elif 'Brightness:' in i: tmp['brightness'] = int(float(i.replace('Brightness:','').replace(' ','').replace('\t',''))*100) data.append(tmp) data = [{k:v for k,v in i.items() if k!='line'} for i in data if i!={} and (i['serial']==None or '\\x' not in i['serial'])] if len(args)==1: data = XRandr.__filter_monitors(args[0], data) if data==[]: raise LookupError('display not found') if len(data)==1: data=data[0] return data def get_display_interfaces(): ''' Returns the interfaces of each display, as reported by xrandr Returns: list: list of strings Example: ```python import screen_brightness_control as sbc names = sbc.linux.XRandr.get_display_names() # EG output: ['eDP-1', 'HDMI1', 'HDMI2'] ``` ''' out = subprocess.check_output(['xrandr', '-q']).decode().split('\n') return [i.split(' ')[0] for i in out if 'connected' in i and not 'disconnected' in i] def get_display_names(): ''' Returns the names of each display, as reported by xrandr Returns: list: list of strings Example: ```python import screen_brightness_control as sbc names = sbc.linux.XRandr.get_display_names() # EG output: ['BenQ GL2450HM', 'Dell U2211H'] ``` ''' return [i['name'] for i in XRandr.get_display_info()] def get_brightness(display = None): ''' Returns the brightness for a display using the xrandr executable Args: display (int): The index of the display you wish to query Returns: int: an integer from 0 to 100 if only one display is detected list: list of integers (from 0 to 100) if there are multiple displays connected Example: ```python import screen_brightness_control as sbc # get the current brightness current_brightness = sbc.linux.XRandr.get_brightness() # get the current brightness for the primary display primary_brightness = sbc.linux.XRandr.get_brightness(display=0) ``` ''' monitors = XRandr.get_display_info() if display!=None: monitors = XRandr.__filter_monitors(display, monitors) brightness = [i['brightness'] for i in monitors] return brightness[0] if len(brightness)==1 else brightness def set_brightness(value, display = None, no_return = False): ''' Sets the brightness for a display using the xrandr executable Args: value (int): Sets the brightness to this value display (int): The index of the display you wish to change no_return (bool): if True, this function returns None, returns the result of `XRandr.get_brightness()` otherwise Returns: The result of `XRandr.get_brightness()` or `None` (see `no_return` kwarg) Example: ```python import screen_brightness_control as sbc # set the brightness to 50 sbc.linux.XRandr.set_brightness(50) # set the brightness of the primary display to 75 sbc.linux.XRandr.set_brightness(75, display=0) ``` ''' value = str(float(value)/100) interfaces = XRandr.get_display_interfaces() if display!=None: interfaces = [i['interface'] for i in XRandr.__filter_monitors(display)] for interface in interfaces: subprocess.run([XRandr.executable,'--output', interface, '--brightness', value]) return XRandr.get_brightness(display=display) if not no_return else None class DDCUtil: '''collection of screen brightness related methods using the ddcutil executable''' executable = 'ddcutil' '''the ddcutil executable to be called''' sleep_multiplier = 0.5 '''how long ddcutil should sleep between each DDC request (lower is shorter). See [the ddcutil docs](https://www.ddcutil.com/performance_options/) for more info.''' def __filter_monitors(display, *args): '''internal function, do not call''' monitors = DDCUtil.get_display_info() if len(args)==0 else args[0] if type(display) is int: return monitors[display] else: return [i for i in monitors if display in (i['name'], i['serial'], i['i2c_bus'], i['model'], i['edid'])] def get_display_info(*args): ''' Returns information about all DDC compatible monitors shown by DDCUtil Works by calling the command 'ddcutil detect' and parsing the output. Args: monitor (int or str): [*Optional*] the monitor to return info about. Pass in the serial number, name, model, i2c bus or index Returns: list: list of dictonaries if a monitor is not specified or the given `monitor` argument has multiple matches dict: one dictionary if a monitor is specified and only one match is found Usage ```python import screen_brightness_control as sbc info = sbc.linux.DDCUtil.get_display_info() for i in info: print('================') for key, value in i.items(): print(key, ':', value) # get information about the first XRandr addressable monitor primary_info = sbc.linux.DDCUtil.get_display_info(0) # get information about a monitor with a specific name benq_info = sbc.linux.DDCUtil.get_display_info('BenQ GL2450HM') ``` ''' out = [] #use -v to get EDID string but this means output cannot be decoded. Use str()[2:-1] workaround for line in str(subprocess.check_output([DDCUtil.executable, 'detect', '-v', f'--sleep-multiplier={DDCUtil.sleep_multiplier}'], stderr=subprocess.DEVNULL))[2:-1].split('\\n'): if line!='' and line.startswith(('Invalid display', 'Display', '\t', ' ')): out.append(line) data = [] tmp = {} count = 0 for i in range(len(out)): line = out[i] if not line.startswith(('\t', ' ')): data.append(tmp) tmp = {'tmp': line, 'method':DDCUtil, 'index':count, 'model':None, 'serial':None, 'manufacturer':None, 'manufacturer_id':None, 'edid':None} count+=1 else: if 'I2C bus' in line: tmp['i2c_bus'] = line[line.index('/'):] tmp['bus_number'] = int(tmp['i2c_bus'].replace('/dev/i2c-','')) elif 'Mfg id' in line: tmp['manufacturer_id'] = line.replace('Mfg id:', '').replace('\t', '').replace(' ', '') tmp['manufacturer'] = _monitor_brand_lookup(tmp['manufacturer_id']) elif 'Model' in line: name = [i for i in line.replace('Model:', '').replace('\t', '').split(' ') if i!=''] try:name[0] = name[0].lower().capitalize() except IndexError:pass tmp['name'] = ' '.join(name) try:tmp['model'] = name[1] except IndexError:pass elif 'Serial number' in line: tmp['serial'] = line.replace('Serial number:', '').replace('\t', '').replace(' ', '') elif 'EDID hex dump:' in line: try:tmp['edid'] = ''.join([j[j.index('+0')+8:j.index('+0')+55].replace(' ','') for j in out[i+2:i+10]]) except:pass data.append(tmp) ret = [{k:v for k,v in i.items() if k!='tmp'} for i in data if i!={} and 'Invalid display' not in i['tmp']] if len(args)==1: ret = DDCUtil.__filter_monitors(args[0], data) if ret==[]: raise LookupError('display not found') if len(ret)==1: ret=ret[0] return ret def get_display_names(): ''' Returns the names of each display, as reported by ddcutil Returns: list: list of strings Example: ```python import screen_brightness_control as sbc names = sbc.linux.DDCUtil.get_display_names() # EG output: ['Dell U2211H', 'BenQ GL2450H'] ``` ''' return [i['name'] for i in DDCUtil.get_display_info()] def get_brightness(display = None): ''' Returns the brightness for a display using the ddcutil executable Args: display (int or str): the display you wish to query. Can be index, name, model, serial or i2c bus Returns: int: an integer from 0 to 100 if only one display is detected or the `display` kwarg is specified list: list of integers (from 0 to 100) if there are multiple displays connected and the `display` kwarg is not specified Example: ```python import screen_brightness_control as sbc # get the current brightness current_brightness = sbc.linux.DDCUtil.get_brightness() # get the current brightness for the primary display primary_brightness = sbc.linux.DDCUtil.get_brightness(display=0) ``` ''' monitors = DDCUtil.get_display_info() if display!=None: monitors = DDCUtil.__filter_monitors(display, monitors) res = [] for m in monitors: out = subprocess.check_output([DDCUtil.executable,'getvcp','10','-t','-b',str(m['bus_number']), f'--sleep-multiplier={DDCUtil.sleep_multiplier}']).decode().split(' ')[-2] try:res.append(int(out)) except:pass if len(res) == 1: res = res[0] return res def set_brightness(value, display = None, no_return = False): ''' Sets the brightness for a display using the ddcutil executable Args: value (int): Sets the brightness to this value display (int or str): The display you wish to change. Can be index, name, model, serial or i2c bus no_return (bool): if True, this function returns None, returns the result of `DDCUtil.get_brightness()` otherwise Returns: The result of `DDCUtil.get_brightness()` or `None` (see `no_return` kwarg) Example: ```python import screen_brightness_control as sbc # set the brightness to 50 sbc.linux.DDCUtil.set_brightness(50) # set the brightness of the primary display to 75 sbc.linux.DDCUtil.set_brightness(75, display=0) ``` ''' monitors = DDCUtil.get_display_info() if display!=None: monitors = DDCUtil.__filter_monitors(display, monitors) for m in monitors: subprocess.run([DDCUtil.executable,'setvcp','10',str(value),'-b', str(m['bus_number']), f'--sleep-multiplier={DDCUtil.sleep_multiplier}']) return DDCUtil.get_brightness(display=display) if not no_return else None class Monitor(object): '''A class to manage a single monitor and its relevant information''' def __init__(self, display): ''' Args: display (int or str): the index/model name/serial/edid of the display you wish to control Raises: LookupError: if the given display is a string but that string does not match any known displays TypeError: if the given display type is not int or str Example: ```python import screen_brightness_control as sbc # create a class for the primary monitor and then a specificly named monitor primary = sbc.linux.Monitor(0) benq_monitor = sbc.linux.Monitor('BenQ GL2450HM') # check if the benq monitor is the primary one if primary.serial == benq_monitor.serial: print('BenQ GL2450HM is the primary display') else: print('The primary display is', primary.name) # this class can also be accessed like a dictionary print(primary['name']) print(benq_monitor['name']) ``` ''' if type(display) is dict: info = display else: info = list_monitors_info() if type(display) is int: info = info[display] elif type(display) is str: for i in info: try: if display in (i['serial'], i['name'], i['model'], i['edid']): info = i except KeyError: pass if type(info) == list:#we haven't found a match raise LookupError('could not match display info to known displays') else: raise TypeError(f'display arg must be int or str, not {type(display)}') self.serial = info['serial']##fix keyerror by smart iteration '''a unique string assigned by the manufacturer to this monitor''' self.name = info['name'] '''the monitors manufacturer name plus its model''' self.method = info['method'] '''the method by which this monitor can be addressed. Will be either `XRandr` or `DDCUtil` or `Light`''' self.manufacturer = info['manufacturer'] '''the name of the brand of the monitor''' self.manufacturer_id = info['manufacturer_id'] '''the 3 letter manufacturing code corresponding to the manufacturer name''' self.model = info['model'] '''the general model of the display''' self.index = info['index'] '''the index of the monitor FOR THE SPECIFIC METHOD THIS MONITOR USES. This means that if the monitor uses `XRandr`, the index is out of the list of `XRandr` addressable monitors ONLY. Same for `DDCUtil` and `Light`''' self.edid = info['edid'] '''a unique string returned by the monitor that contains its VCP capabilities, serial and name''' def __getitem__(self, item): return getattr(self, item) def set_brightness(self, *args, **kwargs): ''' Sets the brightness for this display Args: args (tuple): passed directly to this monitor's brightness method kwargs (dict): passed directly to this monitor's brightness method (the `display` kwarg is always overwritten) Returns: int: from 0 to 100 Example: ```python import screen_brightness_control as sbc # set the brightness of the primary monitor to 50% primary = sbc.linux.Monitor(0) primary_brightness = primary.set_brightness(50) ``` ''' if self.edid!=None: kwargs['display'] = self.edid elif self.serial!=None: kwargs['display'] = self.serial else: kwargs['display'] = self.index return self.method.set_brightness(*args, **kwargs) def get_brightness(self, **kwargs): ''' Returns the brightness of this display Args: kwargs (dict): passed directly to this monitor's brightness method (`display` kwarg is always overwritten) Returns: int: from 0 to 100 Example: ```python import screen_brightness_control as sbc # get the brightness of the primary monitor primary = sbc.linux.Monitor(0) primary_brightness = primary.get_brightness() ``` ''' if self.edid!=None: kwargs['display'] = self.edid elif self.serial!=None: kwargs['display'] = self.serial else: kwargs['display'] = self.index return self.method.get_brightness(**kwargs) def get_info(self): ''' Returns all known information about this monitor instance Returns: dict Example: ```python import screen_brightness_control as sbc # initialize class for primary monitor primary = sbc.linux.Monitor(0) # get the info info = primary.get_info() ``` ''' return { 'name':self.name, 'model':self.model, 'serial':self.serial, 'manufacturer': self.manufacturer, 'manufacturer_id': self.manufacturer_id, 'method': self.method, 'index': self.index, 'edid': self.edid } def is_active(self): ''' Attempts to retrieve the brightness for this display. If it works the display is deemed active Returns: bool: True means active, False means inactive Example: ```python import screen_brightness_control as sbc primary = sbc.linux.Monitor(0) if primary.is_active(): primary.set_brightness(50) ``` ''' try: self.get_brightness() return True except: return False def list_monitors_info(method=None): ''' Lists detailed information about all detected monitors Args: method (str): the method the monitor can be addressed by. Can be 'xrandr' or 'ddcutil' Returns: list: list of dictionaries upon success, empty list upon failure Raises: ValueError: if the method kwarg is invalid Example: ```python import screen_brightness_control as sbc monitors = sbc.linux.list_monitors_info() for info in monitors: print('=======================') print('Name:', info['name']) # the manufacturer name plus the model OR a generic name for the monitor, depending on the method if info['method'] in (sbc.linux.XRandr, sbc.linux.DDCUtil): print('Model:', info['model']) # the general model of the display print('Serial:', info['serial']) # a unique string assigned by Windows to this display print('Manufacturer:', info['manufacturer']) # the name of the brand of the monitor print('Manufacturer ID:', info['manufacturer_id']) # the 3 letter code corresponding to the brand name, EG: BNQ -> BenQ print('Index:', info['index']) # the index of that display FOR THE SPECIFIC METHOD THE DISPLAY USES print('Method:', info['method']) # the method this monitor can be addressed by ``` ''' tmp = [] methods = [XRandr, DDCUtil, Light] if method!=None: if method.lower()=='xrandr':methods = [XRandr] elif method.lower()=='ddcutil':methods = [DDCUtil] elif method.lower()=='light':methods = [Light] else:raise ValueError('method must be \'xrandr\' or \'ddcutil\' or \'light\' to get monitor information') for m in methods: try:tmp.append(m.get_display_info()) except:pass tmp = flatten_list(tmp) info = [] edids = [] #to make sure each display (with unique EDID) is only reported once for i in tmp: try: if i['edid'] not in edids: edids.append(i['edid']) info.append(i) except: info.append(i) return flatten_list(info) def list_monitors(method=None): ''' Returns a list of all addressable monitor names Args: method (str): the method the monitor can be addressed by. Can be 'xrandr' or 'ddcutil' or 'light' Returns: list: list of strings Example: ```python import screen_brightness_control as sbc monitors = sbc.linux.list_monitors() # EG output: ['BenQ GL2450HM', 'Dell U2211H', 'edp-backlight'] ``` ''' displays = [i['name'] for i in list_monitors_info(method=method)] return flatten_list(displays) def get_brightness_from_sysfiles(display = None): ''' Returns the current display brightness by reading files from `/sys/class/backlight` Args: display (int): The index of the display you wish to query Returns: int: from 0 to 100 Raises: Exception: if no values could be obtained from reading `/sys/class/backlight` FileNotFoundError: if the `/sys/class/backlight` directory doesn't exist or it is empty Example: ```python import screen_brightness_control as sbc brightness = sbc.linux.get_brightness_from_sysfiles() # Eg Output: 100 ``` ''' backlight_dir = '/sys/class/backlight/' error = [] #if function has not returned yet try reading the brightness file if os.path.isdir(backlight_dir) and os.listdir(backlight_dir)!=[]: #if the backlight dir exists and is not empty folders=[folder for folder in os.listdir(backlight_dir) if os.path.isdir(os.path.join(backlight_dir,folder))] if display!=None: folders = [folders[display]] for folder in folders: try: #try to read the brightness value in the file with open(os.path.join(backlight_dir,folder,'brightness'),'r') as f: brightness_value=int(float(str(f.read().rstrip('\n')))) try: #try open the max_brightness file to calculate the value to set the brightness file to with open(os.path.join(backlight_dir,folder,'max_brightness'),'r') as f: max_brightness=int(float(str(f.read().rstrip('\n')))) except: #if the file does not exist we cannot calculate the brightness return False brightness_value=int(round((brightness_value/max_brightness)*100,0)) return brightness_value except Exception as e: error.append([type(Exception).__name__,e]) #if function hasn't returned, it failed exc = f'Failed to get brightness from {backlight_dir}:' for e in error: exc+=f'\n {e[0]}: {e[1]}' raise Exception(exc) raise FileNotFoundError(f'Backlight directory {backlight_dir} not found') def __filter_monitors(display = None, method = None): '''internal function, do not call filters the list of all addressable monitors by: whether their name/model/serial/edid matches the display kwarg whether they use the method matching the method kwarg''' monitors = list_monitors_info(method=method) if display!=None: if type(display) not in (str, int): raise TypeError(f'display kwarg must be int or str, not {type(display)}') monitors = [i for i in monitors if display in (i['edid'], i['serial'], i['name'], i['index'])] if monitors == []: msg = 'no monitors found' if display!=None: msg+=f' with name/serial/model/edid of "{display}"' if method!=None: msg+=f' with method of "{method}"' raise LookupError(msg) return monitors def __set_and_get_brightness(*args, display=None, method=None, meta_method='get', **kwargs): '''internal function, do not call. either sets the brightness or gets it. Exists because set_brightness and get_brightness only have a couple differences''' errors = [] try: # filter knwon list of monitors according to kwargs monitors = __filter_monitors(display = display, method = method) except Exception as e: errors.append(['',type(e).__name__, e]) else: output = [] for m in monitors: # add the output of each brightness method to the output list try: identifier = m['index'] if m['edid'] == None else m['edid'] output.append( getattr(m['method'], meta_method+'_brightness')(*args, display = identifier, **kwargs) ) except Exception as e: output.append(None) errors.append([f"{m["name"]}", type(e).__name__, e]) if output!=[] and not all(i==None for i in output): # flatten and return any valid output output = flatten_list(output) return output[0] if len(output)==1 else output else: try: return getattr(XBacklight, meta_method+'_brightness')(*args, **kwargs) except Exception as e: errors.append([f"XBacklight", type(e).__name__, e]) #if function hasn't already returned it has failed if method==None and meta_method == 'get': try: return get_brightness_from_sysfiles(**kwargs) except Exception as e: errors.append(['/sys/class/backlight/*', type(e).__name__, e]) msg='\n' for e in errors: msg+=f'\t{e[0]} -> {e[1]}: {e[2]}\n' if msg=='\n': msg+='\tno valid output was received from brightness methods' raise Exception(msg) def set_brightness(value, display = None, method = None, **kwargs): ''' Sets the brightness for a display, cycles through Light, XRandr, DDCUtil and XBacklight methods untill one works Args: value (int): Sets the brightness to this value method (str): the method to use ('light', 'xrandr', 'ddcutil' or 'xbacklight') kwargs (dict): passed directly to the chosen brightness method Returns: int: an integer between 0 and 100 if only one display is detected (or `XBacklight` is used) list: if the brightness method detects multiple displays it may return a list of integers (invalid monitors return `None`) Raises: ValueError: if you pass in an invalid value for `method` LookupError: if the chosen display or method is not found TypeError: if the value given for `display` is not int or str Exception: if the brightness could not be obtained by any method Example: ```python import screen_brightness_control as sbc # set brightness to 50% sbc.linux.set_brightness(50) # set brightness of the primary display to 75% sbc.linux.set_brightness(75, display=0) # set the brightness to 25% via the XRandr method sbc.linux.set_brightness(25, method='xrandr') ``` ''' if method!=None and method.lower()=='xbacklight': return XBacklight.set_brightness(value, **kwargs) else: return __set_and_get_brightness(value, display = display, method = method, meta_method='set', **kwargs) def get_brightness(display = None, method = None, **kwargs): ''' Returns the brightness for a display, cycles through Light, XRandr, DDCUtil and XBacklight methods untill one works Args: method (str): the method to use ('light', 'xrandr', 'ddcutil' or 'xbacklight') kwargs (dict): passed directly to chosen brightness method Returns: int: an integer between 0 and 100 if only one display is detected (or `XBacklight` is used) list: if the brightness method detects multiple displays it may return a list of integers (invalid monitors return `None`) Raises: ValueError: if you pass in an invalid value for `method` LookupError: if the chosen display or method is not found TypeError: if the value given for `display` is not int or str Exception: if the brightness could not be obtained by any method Example: ```python import screen_brightness_control as sbc # get the current screen brightness current_brightness = sbc.linux.get_brightness() # get the brightness of the primary display primary_brightness = sbc.linux.get_brightness(display=0) # get the brightness via the XRandr method xrandr_brightness = sbc.linux.get_brightness(method='xrandr') # get the brightness of the secondary display using Light light_brightness = sbc.get_brightness(display=1, method='light') ``` ''' if method!=None and method.lower()=='xbacklight': return XBacklight.get_brightness(**kwargs) else: return __set_and_get_brightness(display = display, method = method, meta_method='get', **kwargs)
import subprocess, os, struct from . import flatten_list, _monitor_brand_lookup class _EDID: ''' simple structure and method to extract monitor serial and name from an EDID string. The EDID parsing was created with inspiration from the [pyedid library](https://github.com/jojonas/pyedid) ''' EDID_FORMAT = (">" # big-endian "8s" # constant header (8 bytes) "H" # manufacturer id (2 bytes) "H" # product id (2 bytes) "I" # serial number (4 bytes) "B" # manufactoring week (1 byte) "B" # manufactoring year (1 byte) "B" # edid version (1 byte) "B" # edid revision (1 byte) "B" # video input type (1 byte) "B" # horizontal size in cm (1 byte) "B" # vertical size in cm (1 byte) "B" # display gamma (1 byte) "B" # supported features (1 byte) "10s" # color characteristics (10 bytes) "H" # supported timings (2 bytes) "B" # reserved timing (1 byte) "16s" # EDID supported timings (16 bytes) "18s" # detailed timing block 1 (18 bytes) "18s" # detailed timing block 2 (18 bytes) "18s" # detailed timing block 3 (18 bytes) "18s" # detailed timing block 4 (18 bytes) "B" # extension flag (1 byte) "B") # checksum (1 byte) def parse_edid(edid): '''internal function, do not call''' def filter_hex(st): st = str(st) while '\\x' in st: i = st.index('\\x') st = st.replace(st[i:i+4], '') return st.replace('\\n','')[2:-1] if ' ' in edid: edid = edid.replace(' ','') edid = bytes.fromhex(edid) data = struct.unpack(_EDID.EDID_FORMAT, edid) serial = filter_hex(data[18]) #other info can be anywhere in this range, I don't know why name = None for i in data[19:22]: try: st = str(i)[2:-1].rstrip(' ').rstrip('\t') if st.index(' ')<len(st)-1: name = filter_hex(i).split(' ') name = name[0].lower().capitalize()+' '+name[1] except:pass return name, serial class Light: '''collection of screen brightness related methods using the light executable''' executable = 'light' '''the light executable to be called''' def __filter_monitors(display, *args): '''internal function, do not call''' monitors = Light.get_display_info() if len(args)==0 else args[0] if type(display) is int: return monitors[display] else: return [i for i in monitors if display in (i['name'], i['edid'], i['path'], i['edid'])] def get_display_info(*args): ''' Returns information about detected displays as reported by Light Args: monitor (str or int): [*Optional*] the monitor to return information about. Can be index, name, path or edid Returns: list: list of dictionaries if no monitor is specified dict: if a monitor is specified Example: ```python import screen_brightness_control as sbc # get info about all monitors info = sbc.linux.Light.get_display_info() # EG output: [{'name': 'edp-backlight', 'path': '/sys/class/backlight/edp-backlight', edid': '00ffffffffffff00'...}] # get info about the primary monitor primary_info = sbc.linux.Light.get_display_info(0) # get info about a monitor called 'edp-backlight' edp_info = sbc.linux.Light.get_display_info('edp-backlight') ``` ''' res=subprocess.run([Light.executable, '-L'],stdout=subprocess.PIPE).stdout.decode().split('\n') displays = [] count=0 for r in res: if 'backlight' in r and 'sysfs/backlight/auto' not in r: r = r[r.index('backlight/')+10:] if os.path.isdir(f'/sys/class/backlight/{r}'): tmp = {'name':r, 'path': f'/sys/class/backlight/{r}', 'light_path': f'sysfs/backlight/{r}', 'method': Light, 'index':count, 'model':None, 'serial':None, 'manufacturer':None, 'manufacturer_id':None, 'edid':None} count+=1 if os.path.isfile(tmp['path']+'/device/edid'): try: out = subprocess.check_output(['hexdump', tmp['path']+'/device/edid'], stderr=subprocess.DEVNULL).decode().split('\n') #either the hexdump reports each hex char backwards (ff00 instead of 00ff) or both xrandr and ddcutil do so I swap these bits around edid = '' for line in out: line = line.split(' ') for i in line: if len(i)==4: edid+=i[2:]+i[:2] tmp['edid'] = edid name, serial = _EDID.parse_edid(edid) if name!=None: tmp['serial'] = serial tmp['name'] = name tmp['manufacturer'] = name.split(' ')[0] tmp['manufacturer_id'] = _monitor_brand_lookup(tmp['manufacturer']) tmp['model'] = name.split(' ')[1] except: pass displays.append(tmp) if len(args)==1: displays = Light.__filter_monitors(args[0], displays) if len(displays)==1: displays = displays[0] return displays def get_display_names(): ''' Returns the names of each display, as reported by light Returns: list: list of strings Example: ```python import screen_brightness_control as sbc names = sbc.linux.Light.get_display_names() # EG output: ['edp-backlight'] ``` ''' return [i['name'] for i in Light.get_display_info()] def set_brightness(value, display = None, no_return = False): ''' Sets the brightness for a display using the light executable Args: value (int): Sets the brightness to this value display (int or str): The index, name, edid or path of the display you wish to change no_return (bool): if True, this function returns None Returns: The result of `Light.get_brightness()` or `None` (see `no_return` kwarg) Example: ```python import screen_brightness_control as sbc # set the brightness to 50% sbc.linux.Light.set_brightness(50) # set the primary display brightness to 75% sbc.linux.Light.set_brightness(75, display = 0) # set the display called 'edp-backlight' to 25% sbc.linux.Light.set_brightness(75, display = 'edp-backlight') ``` ''' info = Light.get_display_info() if display!=None: info = Light.__filter_monitors(display, info) for i in info: light_path = i['light_path'] command = f'{Light.executable} -S {value} -s {light_path}' subprocess.call(command.split(" ")) return Light.get_brightness(display=display) if not no_return else None def get_brightness(display = None): ''' Sets the brightness for a display using the light executable Args: display (int or str): display (int or str): The index, name, edid or path of the display you wish to query Returns: int: from 0 to 100 if only one display is detected list: list of integers if multiple displays are detected Example: ```python import screen_brightness_control as sbc # get the current display brightness current_brightness = sbc.linux.Light.get_brightness() # get the brightness of the primary display primary_brightness = sbc.linux.Light.get_brightness(display = 0) # get the brightness of the display called 'edp-backlight' edp_brightness = sbc.linux.Light.get_brightness(display = 'edp-backlight') ``` ''' info = Light.get_display_info() if display!=None: info = Light.__filter_monitors(display, info) results = [] for i in info: light_path = i['light_path'] command = f'{Light.executable} -G -s {light_path}' results.append(subprocess.run(command.split(' '),stdout=subprocess.PIPE).stdout.decode()) results = [int(round(float(str(i)),0)) for i in results] return results[0] if len(results)==1 else results class XBacklight: '''collection of screen brightness related methods using the xbacklight executable''' executable = 'xbacklight' '''the xbacklight executable to be called''' def set_brightness(value, no_return = False, **kwargs): ''' Sets the screen brightness to a supplied value Args: no_return (bool): if True, this function returns None, returns the result of self.get_brightness() otherwise Returns: int: from 0 to 100 None: if `no_return` is set to `True` Example: ```python import screen_brightness_control as sbc # set the brightness to 100% sbc.linux.XBacklight.set_brightness(100) ``` ''' subprocess.call([XBacklight.executable, '-set', str(value)]) return XBacklight.get_brightness() if not no_return else None def get_brightness(**kwargs): ''' Returns the screen brightness as reported by xbacklight Returns: int: from 0 to 100 Example: ```python import screen_brightness_control as sbc current_brightness = sbc.linux.XBacklight.get_brightness() ``` ''' res=subprocess.run([XBacklight.executable, '-get'],stdout=subprocess.PIPE).stdout.decode() return int(round(float(str(res)),0)) class XRandr: '''collection of screen brightness related methods using the xrandr executable''' executable = 'xrandr' '''the xrandr executable to be called''' def __filter_monitors(display, *args): '''internal function, do not call''' monitors = XRandr.get_display_info() if len(args)==0 else args[0] if type(display) is int: return monitors[display] else: return [i for i in monitors if display in (i['name'], i['serial'], i['interface'], i['model'], i['edid'])] def get_display_info(*args): ''' Returns a dictionary of info about all detected monitors as reported by xrandr Args: monitor (str or int): [*Optional*] the monitor to return info about. Pass in the serial number, name, model, interface or index Returns: list: list of dictonaries if a monitor is not specified or the given `monitor` argument has multiple matches dict: one dictionary if a monitor is specified and only one match is found Example: ```python import screen_brightness_control as sbc info = sbc.linux.XRandr.get_display_info() for i in info: print('================') for key, value in i.items(): print(key, ':', value) # get information about the first XRandr addressable monitor primary_info = sbc.linux.XRandr.get_display_info(0) # get information about a monitor with a specific name benq_info = sbc.linux.XRandr.get_display_info('BenQ GL2450HM') ``` ''' out = [i for i in subprocess.check_output([XRandr.executable, '--verbose']).decode().split('\n') if i!=''] names = XRandr.get_display_interfaces() data = [] tmp = {} count = 0 for i in out: if i.startswith(tuple(names)): data.append(tmp) tmp = {'interface':i.split(' ')[0], 'line':i, 'method':XRandr, 'index':count, 'model':None, 'serial':None, 'manufacturer':None, 'manufacturer_id':None, 'edid':None} count+=1 elif 'EDID:' in i: st = out[out.index(tmp['line']):] edid = [st[j].replace('\t','').replace(' ', '') for j in range(st.index(i)+1, st.index(i)+9)] edid = ''.join(edid) tmp['edid'] = edid name, serial = _EDID.parse_edid(edid) tmp['name'] = name if name!=None else tmp['interface'] if name!=None: tmp['manufacturer'] = name.split(' ')[0] tmp['manufacturer_id'] = _monitor_brand_lookup(tmp['manufacturer']) tmp['model'] = name.split(' ')[1] tmp['serial'] = serial elif 'Brightness:' in i: tmp['brightness'] = int(float(i.replace('Brightness:','').replace(' ','').replace('\t',''))*100) data.append(tmp) data = [{k:v for k,v in i.items() if k!='line'} for i in data if i!={} and (i['serial']==None or '\\x' not in i['serial'])] if len(args)==1: data = XRandr.__filter_monitors(args[0], data) if data==[]: raise LookupError('display not found') if len(data)==1: data=data[0] return data def get_display_interfaces(): ''' Returns the interfaces of each display, as reported by xrandr Returns: list: list of strings Example: ```python import screen_brightness_control as sbc names = sbc.linux.XRandr.get_display_names() # EG output: ['eDP-1', 'HDMI1', 'HDMI2'] ``` ''' out = subprocess.check_output(['xrandr', '-q']).decode().split('\n') return [i.split(' ')[0] for i in out if 'connected' in i and not 'disconnected' in i] def get_display_names(): ''' Returns the names of each display, as reported by xrandr Returns: list: list of strings Example: ```python import screen_brightness_control as sbc names = sbc.linux.XRandr.get_display_names() # EG output: ['BenQ GL2450HM', 'Dell U2211H'] ``` ''' return [i['name'] for i in XRandr.get_display_info()] def get_brightness(display = None): ''' Returns the brightness for a display using the xrandr executable Args: display (int): The index of the display you wish to query Returns: int: an integer from 0 to 100 if only one display is detected list: list of integers (from 0 to 100) if there are multiple displays connected Example: ```python import screen_brightness_control as sbc # get the current brightness current_brightness = sbc.linux.XRandr.get_brightness() # get the current brightness for the primary display primary_brightness = sbc.linux.XRandr.get_brightness(display=0) ``` ''' monitors = XRandr.get_display_info() if display!=None: monitors = XRandr.__filter_monitors(display, monitors) brightness = [i['brightness'] for i in monitors] return brightness[0] if len(brightness)==1 else brightness def set_brightness(value, display = None, no_return = False): ''' Sets the brightness for a display using the xrandr executable Args: value (int): Sets the brightness to this value display (int): The index of the display you wish to change no_return (bool): if True, this function returns None, returns the result of `XRandr.get_brightness()` otherwise Returns: The result of `XRandr.get_brightness()` or `None` (see `no_return` kwarg) Example: ```python import screen_brightness_control as sbc # set the brightness to 50 sbc.linux.XRandr.set_brightness(50) # set the brightness of the primary display to 75 sbc.linux.XRandr.set_brightness(75, display=0) ``` ''' value = str(float(value)/100) interfaces = XRandr.get_display_interfaces() if display!=None: interfaces = [i['interface'] for i in XRandr.__filter_monitors(display)] for interface in interfaces: subprocess.run([XRandr.executable,'--output', interface, '--brightness', value]) return XRandr.get_brightness(display=display) if not no_return else None class DDCUtil: '''collection of screen brightness related methods using the ddcutil executable''' executable = 'ddcutil' '''the ddcutil executable to be called''' sleep_multiplier = 0.5 '''how long ddcutil should sleep between each DDC request (lower is shorter). See [the ddcutil docs](https://www.ddcutil.com/performance_options/) for more info.''' def __filter_monitors(display, *args): '''internal function, do not call''' monitors = DDCUtil.get_display_info() if len(args)==0 else args[0] if type(display) is int: return monitors[display] else: return [i for i in monitors if display in (i['name'], i['serial'], i['i2c_bus'], i['model'], i['edid'])] def get_display_info(*args): ''' Returns information about all DDC compatible monitors shown by DDCUtil Works by calling the command 'ddcutil detect' and parsing the output. Args: monitor (int or str): [*Optional*] the monitor to return info about. Pass in the serial number, name, model, i2c bus or index Returns: list: list of dictonaries if a monitor is not specified or the given `monitor` argument has multiple matches dict: one dictionary if a monitor is specified and only one match is found Usage ```python import screen_brightness_control as sbc info = sbc.linux.DDCUtil.get_display_info() for i in info: print('================') for key, value in i.items(): print(key, ':', value) # get information about the first XRandr addressable monitor primary_info = sbc.linux.DDCUtil.get_display_info(0) # get information about a monitor with a specific name benq_info = sbc.linux.DDCUtil.get_display_info('BenQ GL2450HM') ``` ''' out = [] #use -v to get EDID string but this means output cannot be decoded. Use str()[2:-1] workaround for line in str(subprocess.check_output([DDCUtil.executable, 'detect', '-v', f'--sleep-multiplier={DDCUtil.sleep_multiplier}'], stderr=subprocess.DEVNULL))[2:-1].split('\\n'): if line!='' and line.startswith(('Invalid display', 'Display', '\t', ' ')): out.append(line) data = [] tmp = {} count = 0 for i in range(len(out)): line = out[i] if not line.startswith(('\t', ' ')): data.append(tmp) tmp = {'tmp': line, 'method':DDCUtil, 'index':count, 'model':None, 'serial':None, 'manufacturer':None, 'manufacturer_id':None, 'edid':None} count+=1 else: if 'I2C bus' in line: tmp['i2c_bus'] = line[line.index('/'):] tmp['bus_number'] = int(tmp['i2c_bus'].replace('/dev/i2c-','')) elif 'Mfg id' in line: tmp['manufacturer_id'] = line.replace('Mfg id:', '').replace('\t', '').replace(' ', '') tmp['manufacturer'] = _monitor_brand_lookup(tmp['manufacturer_id']) elif 'Model' in line: name = [i for i in line.replace('Model:', '').replace('\t', '').split(' ') if i!=''] try:name[0] = name[0].lower().capitalize() except IndexError:pass tmp['name'] = ' '.join(name) try:tmp['model'] = name[1] except IndexError:pass elif 'Serial number' in line: tmp['serial'] = line.replace('Serial number:', '').replace('\t', '').replace(' ', '') elif 'EDID hex dump:' in line: try:tmp['edid'] = ''.join([j[j.index('+0')+8:j.index('+0')+55].replace(' ','') for j in out[i+2:i+10]]) except:pass data.append(tmp) ret = [{k:v for k,v in i.items() if k!='tmp'} for i in data if i!={} and 'Invalid display' not in i['tmp']] if len(args)==1: ret = DDCUtil.__filter_monitors(args[0], data) if ret==[]: raise LookupError('display not found') if len(ret)==1: ret=ret[0] return ret def get_display_names(): ''' Returns the names of each display, as reported by ddcutil Returns: list: list of strings Example: ```python import screen_brightness_control as sbc names = sbc.linux.DDCUtil.get_display_names() # EG output: ['Dell U2211H', 'BenQ GL2450H'] ``` ''' return [i['name'] for i in DDCUtil.get_display_info()] def get_brightness(display = None): ''' Returns the brightness for a display using the ddcutil executable Args: display (int or str): the display you wish to query. Can be index, name, model, serial or i2c bus Returns: int: an integer from 0 to 100 if only one display is detected or the `display` kwarg is specified list: list of integers (from 0 to 100) if there are multiple displays connected and the `display` kwarg is not specified Example: ```python import screen_brightness_control as sbc # get the current brightness current_brightness = sbc.linux.DDCUtil.get_brightness() # get the current brightness for the primary display primary_brightness = sbc.linux.DDCUtil.get_brightness(display=0) ``` ''' monitors = DDCUtil.get_display_info() if display!=None: monitors = DDCUtil.__filter_monitors(display, monitors) res = [] for m in monitors: out = subprocess.check_output([DDCUtil.executable,'getvcp','10','-t','-b',str(m['bus_number']), f'--sleep-multiplier={DDCUtil.sleep_multiplier}']).decode().split(' ')[-2] try:res.append(int(out)) except:pass if len(res) == 1: res = res[0] return res def set_brightness(value, display = None, no_return = False): ''' Sets the brightness for a display using the ddcutil executable Args: value (int): Sets the brightness to this value display (int or str): The display you wish to change. Can be index, name, model, serial or i2c bus no_return (bool): if True, this function returns None, returns the result of `DDCUtil.get_brightness()` otherwise Returns: The result of `DDCUtil.get_brightness()` or `None` (see `no_return` kwarg) Example: ```python import screen_brightness_control as sbc # set the brightness to 50 sbc.linux.DDCUtil.set_brightness(50) # set the brightness of the primary display to 75 sbc.linux.DDCUtil.set_brightness(75, display=0) ``` ''' monitors = DDCUtil.get_display_info() if display!=None: monitors = DDCUtil.__filter_monitors(display, monitors) for m in monitors: subprocess.run([DDCUtil.executable,'setvcp','10',str(value),'-b', str(m['bus_number']), f'--sleep-multiplier={DDCUtil.sleep_multiplier}']) return DDCUtil.get_brightness(display=display) if not no_return else None class Monitor(object): '''A class to manage a single monitor and its relevant information''' def __init__(self, display): ''' Args: display (int or str): the index/model name/serial/edid of the display you wish to control Raises: LookupError: if the given display is a string but that string does not match any known displays TypeError: if the given display type is not int or str Example: ```python import screen_brightness_control as sbc # create a class for the primary monitor and then a specificly named monitor primary = sbc.linux.Monitor(0) benq_monitor = sbc.linux.Monitor('BenQ GL2450HM') # check if the benq monitor is the primary one if primary.serial == benq_monitor.serial: print('BenQ GL2450HM is the primary display') else: print('The primary display is', primary.name) # this class can also be accessed like a dictionary print(primary['name']) print(benq_monitor['name']) ``` ''' if type(display) is dict: info = display else: info = list_monitors_info() if type(display) is int: info = info[display] elif type(display) is str: for i in info: try: if display in (i['serial'], i['name'], i['model'], i['edid']): info = i except KeyError: pass if type(info) == list:#we haven't found a match raise LookupError('could not match display info to known displays') else: raise TypeError(f'display arg must be int or str, not {type(display)}') self.serial = info['serial']##fix keyerror by smart iteration '''a unique string assigned by the manufacturer to this monitor''' self.name = info['name'] '''the monitors manufacturer name plus its model''' self.method = info['method'] '''the method by which this monitor can be addressed. Will be either `XRandr` or `DDCUtil` or `Light`''' self.manufacturer = info['manufacturer'] '''the name of the brand of the monitor''' self.manufacturer_id = info['manufacturer_id'] '''the 3 letter manufacturing code corresponding to the manufacturer name''' self.model = info['model'] '''the general model of the display''' self.index = info['index'] '''the index of the monitor FOR THE SPECIFIC METHOD THIS MONITOR USES. This means that if the monitor uses `XRandr`, the index is out of the list of `XRandr` addressable monitors ONLY. Same for `DDCUtil` and `Light`''' self.edid = info['edid'] '''a unique string returned by the monitor that contains its VCP capabilities, serial and name''' def __getitem__(self, item): return getattr(self, item) def set_brightness(self, *args, **kwargs): ''' Sets the brightness for this display Args: args (tuple): passed directly to this monitor's brightness method kwargs (dict): passed directly to this monitor's brightness method (the `display` kwarg is always overwritten) Returns: int: from 0 to 100 Example: ```python import screen_brightness_control as sbc # set the brightness of the primary monitor to 50% primary = sbc.linux.Monitor(0) primary_brightness = primary.set_brightness(50) ``` ''' if self.edid!=None: kwargs['display'] = self.edid elif self.serial!=None: kwargs['display'] = self.serial else: kwargs['display'] = self.index return self.method.set_brightness(*args, **kwargs) def get_brightness(self, **kwargs): ''' Returns the brightness of this display Args: kwargs (dict): passed directly to this monitor's brightness method (`display` kwarg is always overwritten) Returns: int: from 0 to 100 Example: ```python import screen_brightness_control as sbc # get the brightness of the primary monitor primary = sbc.linux.Monitor(0) primary_brightness = primary.get_brightness() ``` ''' if self.edid!=None: kwargs['display'] = self.edid elif self.serial!=None: kwargs['display'] = self.serial else: kwargs['display'] = self.index return self.method.get_brightness(**kwargs) def get_info(self): ''' Returns all known information about this monitor instance Returns: dict Example: ```python import screen_brightness_control as sbc # initialize class for primary monitor primary = sbc.linux.Monitor(0) # get the info info = primary.get_info() ``` ''' return { 'name':self.name, 'model':self.model, 'serial':self.serial, 'manufacturer': self.manufacturer, 'manufacturer_id': self.manufacturer_id, 'method': self.method, 'index': self.index, 'edid': self.edid } def is_active(self): ''' Attempts to retrieve the brightness for this display. If it works the display is deemed active Returns: bool: True means active, False means inactive Example: ```python import screen_brightness_control as sbc primary = sbc.linux.Monitor(0) if primary.is_active(): primary.set_brightness(50) ``` ''' try: self.get_brightness() return True except: return False def list_monitors_info(method=None): ''' Lists detailed information about all detected monitors Args: method (str): the method the monitor can be addressed by. Can be 'xrandr' or 'ddcutil' Returns: list: list of dictionaries upon success, empty list upon failure Raises: ValueError: if the method kwarg is invalid Example: ```python import screen_brightness_control as sbc monitors = sbc.linux.list_monitors_info() for info in monitors: print('=======================') print('Name:', info['name']) # the manufacturer name plus the model OR a generic name for the monitor, depending on the method if info['method'] in (sbc.linux.XRandr, sbc.linux.DDCUtil): print('Model:', info['model']) # the general model of the display print('Serial:', info['serial']) # a unique string assigned by Windows to this display print('Manufacturer:', info['manufacturer']) # the name of the brand of the monitor print('Manufacturer ID:', info['manufacturer_id']) # the 3 letter code corresponding to the brand name, EG: BNQ -> BenQ print('Index:', info['index']) # the index of that display FOR THE SPECIFIC METHOD THE DISPLAY USES print('Method:', info['method']) # the method this monitor can be addressed by ``` ''' tmp = [] methods = [XRandr, DDCUtil, Light] if method!=None: if method.lower()=='xrandr':methods = [XRandr] elif method.lower()=='ddcutil':methods = [DDCUtil] elif method.lower()=='light':methods = [Light] else:raise ValueError('method must be \'xrandr\' or \'ddcutil\' or \'light\' to get monitor information') for m in methods: try:tmp.append(m.get_display_info()) except:pass tmp = flatten_list(tmp) info = [] edids = [] #to make sure each display (with unique EDID) is only reported once for i in tmp: try: if i['edid'] not in edids: edids.append(i['edid']) info.append(i) except: info.append(i) return flatten_list(info) def list_monitors(method=None): ''' Returns a list of all addressable monitor names Args: method (str): the method the monitor can be addressed by. Can be 'xrandr' or 'ddcutil' or 'light' Returns: list: list of strings Example: ```python import screen_brightness_control as sbc monitors = sbc.linux.list_monitors() # EG output: ['BenQ GL2450HM', 'Dell U2211H', 'edp-backlight'] ``` ''' displays = [i['name'] for i in list_monitors_info(method=method)] return flatten_list(displays) def get_brightness_from_sysfiles(display = None): ''' Returns the current display brightness by reading files from `/sys/class/backlight` Args: display (int): The index of the display you wish to query Returns: int: from 0 to 100 Raises: Exception: if no values could be obtained from reading `/sys/class/backlight` FileNotFoundError: if the `/sys/class/backlight` directory doesn't exist or it is empty Example: ```python import screen_brightness_control as sbc brightness = sbc.linux.get_brightness_from_sysfiles() # Eg Output: 100 ``` ''' backlight_dir = '/sys/class/backlight/' error = [] #if function has not returned yet try reading the brightness file if os.path.isdir(backlight_dir) and os.listdir(backlight_dir)!=[]: #if the backlight dir exists and is not empty folders=[folder for folder in os.listdir(backlight_dir) if os.path.isdir(os.path.join(backlight_dir,folder))] if display!=None: folders = [folders[display]] for folder in folders: try: #try to read the brightness value in the file with open(os.path.join(backlight_dir,folder,'brightness'),'r') as f: brightness_value=int(float(str(f.read().rstrip('\n')))) try: #try open the max_brightness file to calculate the value to set the brightness file to with open(os.path.join(backlight_dir,folder,'max_brightness'),'r') as f: max_brightness=int(float(str(f.read().rstrip('\n')))) except: #if the file does not exist we cannot calculate the brightness return False brightness_value=int(round((brightness_value/max_brightness)*100,0)) return brightness_value except Exception as e: error.append([type(Exception).__name__,e]) #if function hasn't returned, it failed exc = f'Failed to get brightness from {backlight_dir}:' for e in error: exc+=f'\n {e[0]}: {e[1]}' raise Exception(exc) raise FileNotFoundError(f'Backlight directory {backlight_dir} not found') def __filter_monitors(display = None, method = None): '''internal function, do not call filters the list of all addressable monitors by: whether their name/model/serial/edid matches the display kwarg whether they use the method matching the method kwarg''' monitors = list_monitors_info(method=method) if display!=None: if type(display) not in (str, int): raise TypeError(f'display kwarg must be int or str, not {type(display)}') monitors = [i for i in monitors if display in (i['edid'], i['serial'], i['name'], i['index'])] if monitors == []: msg = 'no monitors found' if display!=None: msg+=f' with name/serial/model/edid of "{display}"' if method!=None: msg+=f' with method of "{method}"' raise LookupError(msg) return monitors def __set_and_get_brightness(*args, display=None, method=None, meta_method='get', **kwargs): '''internal function, do not call. either sets the brightness or gets it. Exists because set_brightness and get_brightness only have a couple differences''' errors = [] try: # filter knwon list of monitors according to kwargs monitors = __filter_monitors(display = display, method = method) except Exception as e: errors.append(['',type(e).__name__, e]) else: output = [] for m in monitors: # add the output of each brightness method to the output list try: identifier = m['index'] if m['edid'] == None else m['edid'] output.append( getattr(m['method'], meta_method+'_brightness')(*args, display = identifier, **kwargs) ) except Exception as e: output.append(None) errors.append([f"{m['name']}", type(e).__name__, e]) if output!=[] and not all(i==None for i in output): # flatten and return any valid output output = flatten_list(output) return output[0] if len(output)==1 else output else: try: return getattr(XBacklight, meta_method+'_brightness')(*args, **kwargs) except Exception as e: errors.append([f"XBacklight", type(e).__name__, e]) #if function hasn't already returned it has failed if method==None and meta_method == 'get': try: return get_brightness_from_sysfiles(**kwargs) except Exception as e: errors.append(['/sys/class/backlight/*', type(e).__name__, e]) msg='\n' for e in errors: msg+=f'\t{e[0]} -> {e[1]}: {e[2]}\n' if msg=='\n': msg+='\tno valid output was received from brightness methods' raise Exception(msg) def set_brightness(value, display = None, method = None, **kwargs): ''' Sets the brightness for a display, cycles through Light, XRandr, DDCUtil and XBacklight methods untill one works Args: value (int): Sets the brightness to this value method (str): the method to use ('light', 'xrandr', 'ddcutil' or 'xbacklight') kwargs (dict): passed directly to the chosen brightness method Returns: int: an integer between 0 and 100 if only one display is detected (or `XBacklight` is used) list: if the brightness method detects multiple displays it may return a list of integers (invalid monitors return `None`) Raises: ValueError: if you pass in an invalid value for `method` LookupError: if the chosen display or method is not found TypeError: if the value given for `display` is not int or str Exception: if the brightness could not be obtained by any method Example: ```python import screen_brightness_control as sbc # set brightness to 50% sbc.linux.set_brightness(50) # set brightness of the primary display to 75% sbc.linux.set_brightness(75, display=0) # set the brightness to 25% via the XRandr method sbc.linux.set_brightness(25, method='xrandr') ``` ''' if method!=None and method.lower()=='xbacklight': return XBacklight.set_brightness(value, **kwargs) else: return __set_and_get_brightness(value, display = display, method = method, meta_method='set', **kwargs) def get_brightness(display = None, method = None, **kwargs): ''' Returns the brightness for a display, cycles through Light, XRandr, DDCUtil and XBacklight methods untill one works Args: method (str): the method to use ('light', 'xrandr', 'ddcutil' or 'xbacklight') kwargs (dict): passed directly to chosen brightness method Returns: int: an integer between 0 and 100 if only one display is detected (or `XBacklight` is used) list: if the brightness method detects multiple displays it may return a list of integers (invalid monitors return `None`) Raises: ValueError: if you pass in an invalid value for `method` LookupError: if the chosen display or method is not found TypeError: if the value given for `display` is not int or str Exception: if the brightness could not be obtained by any method Example: ```python import screen_brightness_control as sbc # get the current screen brightness current_brightness = sbc.linux.get_brightness() # get the brightness of the primary display primary_brightness = sbc.linux.get_brightness(display=0) # get the brightness via the XRandr method xrandr_brightness = sbc.linux.get_brightness(method='xrandr') # get the brightness of the secondary display using Light light_brightness = sbc.get_brightness(display=1, method='light') ``` ''' if method!=None and method.lower()=='xbacklight': return XBacklight.get_brightness(**kwargs) else: return __set_and_get_brightness(display = display, method = method, meta_method='get', **kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2012-2021 Snowflake Computing Inc. All right reserved. # from __future__ import division import os import shutil import time from collections import namedtuple from io import BytesIO from logging import getLogger from typing import TYPE_CHECKING from boto3 import Session from .azure_util import SnowflakeAzureUtil from .constants import ResultStatus from .encryption_util import SnowflakeEncryptionUtil from .gcs_util import SnowflakeGCSUtil from .s3_util import SnowflakeS3Util if TYPE_CHECKING: # pragma: no cover from .file_transfer_agent import SnowflakeFileMeta DEFAULT_CONCURRENCY = 1 DEFAULT_MAX_RETRY = 5 logger = getLogger(__name__) """ Encryption Material """ SnowflakeFileEncryptionMaterial = namedtuple( "SnowflakeS3FileEncryptionMaterial", [ "query_stage_master_key", # query stage master key "query_id", # query id "smk_id", # SMK id ], ) class NeedRenewTokenError(Exception): pass class SnowflakeRemoteStorageUtil(object): @staticmethod def get_for_storage_type(_type): if _type == "S3": return SnowflakeS3Util elif _type == "AZURE": return SnowflakeAzureUtil elif _type == "GCS": return SnowflakeGCSUtil else: return None @staticmethod def create_client( stage_info, use_accelerate_endpoint: bool = False, use_s3_regional_url: bool = False, s3_connection_pool_size: int = 1, ) -> Session.resource: util_class = SnowflakeRemoteStorageUtil.get_for_storage_type( stage_info["locationType"] ) return util_class.create_client( stage_info, use_accelerate_endpoint=use_accelerate_endpoint, use_s3_regional_url=use_s3_regional_url, s3_connection_pool_size=s3_connection_pool_size, ) @staticmethod def upload_one_file(meta: "SnowflakeFileMeta") -> None: """Uploads a file to S3.""" encryption_metadata = None if meta.encryption_material is not None: if meta.src_stream is None: (encryption_metadata, data_file) = SnowflakeEncryptionUtil.encrypt_file( meta.encryption_material, meta.real_src_file_name, tmp_dir=meta.tmp_dir, ) logger.debug( f"encrypted data file={data_file}, size={os.path.getsize(data_file)}" ) else: encrypted_stream = BytesIO() src_stream = meta.real_src_stream or meta.src_stream src_stream.seek(0) encryption_metadata = SnowflakeEncryptionUtil.encrypt_stream( meta.encryption_material, src_stream, encrypted_stream ) src_stream.seek(0) logger.debug( f"encrypted data stream size={encrypted_stream.seek(0, os.SEEK_END)}" ) encrypted_stream.seek(0) if meta.real_src_stream is not None: meta.real_src_stream.close() meta.real_src_stream = encrypted_stream data_file = meta.real_src_file_name else: logger.debug("not encrypted data file") data_file = meta.real_src_file_name util_class = SnowflakeRemoteStorageUtil.get_for_storage_type( meta.client_meta.stage_info["locationType"] ) logger.debug( f"putting a file: {meta.client_meta.stage_info["location"]}, {meta.dst_file_name}" ) max_concurrency = meta.parallel last_err = None max_retry = DEFAULT_MAX_RETRY for retry in range(max_retry): if not meta.overwrite: file_header = util_class.get_file_header(meta, meta.dst_file_name) if file_header and meta.result_status == ResultStatus.UPLOADED: logger.debug( f'file already exists location="{meta.client_meta.stage_info['location']}", ' f'file_name="{meta.dst_file_name}"' ) meta.dst_file_size = 0 meta.result_status = ResultStatus.SKIPPED return if meta.overwrite or meta.result_status == ResultStatus.NOT_FOUND_FILE: util_class.upload_file( data_file, meta, encryption_metadata, max_concurrency, multipart_threshold=meta.multipart_threshold, ) if meta.result_status == ResultStatus.UPLOADED: return elif meta.result_status == ResultStatus.RENEW_TOKEN: return elif meta.result_status == ResultStatus.RENEW_PRESIGNED_URL: return elif meta.result_status == ResultStatus.NEED_RETRY: last_err = meta.last_error logger.debug( f"Failed to upload a file: {data_file}, err: {last_err}. Retrying with " f"max concurrency: {max_concurrency}" ) if not meta.no_sleeping_time: sleeping_time = min(2 ** retry, 16) logger.debug(f"sleeping {sleeping_time}") time.sleep(sleeping_time) elif meta.result_status == ResultStatus.NEED_RETRY_WITH_LOWER_CONCURRENCY: last_err = meta.last_error max_concurrency = meta.parallel - int(retry * meta.parallel / max_retry) max_concurrency = max(DEFAULT_CONCURRENCY, max_concurrency) meta.last_max_concurrency = max_concurrency logger.debug( f"Failed to upload a file: {data_file}, err: {last_err}. Retrying with " f"max concurrency: {max_concurrency}" ) if meta.no_sleeping_time is None: sleeping_time = min(2 ** retry, 16) logger.debug(f"sleeping: {sleeping_time}") time.sleep(sleeping_time) else: if last_err: raise last_err else: msg = f"Unknown Error in uploading a file: {data_file}" raise Exception(msg) @staticmethod def download_one_file(meta: "SnowflakeFileMeta") -> None: """Downloads a file from S3.""" full_dst_file_name = os.path.join( meta.local_location, os.path.basename(meta.dst_file_name) ) full_dst_file_name = os.path.realpath(full_dst_file_name) # TODO: validate full_dst_file_name is under the writable directory base_dir = os.path.dirname(full_dst_file_name) if not os.path.exists(base_dir): os.makedirs(base_dir) util_class = SnowflakeRemoteStorageUtil.get_for_storage_type( meta.client_meta.stage_info["locationType"] ) file_header = util_class.get_file_header(meta, meta.src_file_name) if file_header: meta.src_file_size = file_header.content_length full_dst_file_name = os.path.join( meta.local_location, os.path.basename(meta.dst_file_name) ) full_dst_file_name = os.path.realpath(full_dst_file_name) max_concurrency = meta.parallel last_err = None max_retry = DEFAULT_MAX_RETRY for retry in range(max_retry): util_class._native_download_file(meta, full_dst_file_name, max_concurrency) if meta.result_status == ResultStatus.DOWNLOADED: if meta.encryption_material is not None: logger.debug(f"encrypted data file={full_dst_file_name}") # For storage utils that do not have the privilege of # getting the metadata early, both object and metadata # are downloaded at once. In which case, the file meta will # be updated with all the metadata that we need and # then we can call get_file_header to get just that and also # preserve the idea of getting metadata in the first place. # One example of this is the utils that use presigned url # for upload/download and not the storage client library. if meta.presigned_url is not None: file_header = util_class.get_file_header( meta, meta.src_file_name ) tmp_dst_file_name = SnowflakeEncryptionUtil.decrypt_file( file_header.encryption_metadata, meta.encryption_material, full_dst_file_name, tmp_dir=meta.tmp_dir, ) shutil.copyfile(tmp_dst_file_name, full_dst_file_name) os.unlink(tmp_dst_file_name) else: logger.debug(f"not encrypted data file={full_dst_file_name}") stat_info = os.stat(full_dst_file_name) meta.dst_file_size = stat_info.st_size return elif meta.result_status == ResultStatus.RENEW_PRESIGNED_URL: return elif meta.result_status == ResultStatus.RENEW_TOKEN: return elif meta.result_status == ResultStatus.NEED_RETRY_WITH_LOWER_CONCURRENCY: max_concurrency = meta.parallel - int(retry * meta.parallel / max_retry) max_concurrency = max(DEFAULT_CONCURRENCY, max_concurrency) meta.last_max_concurrency = max_concurrency last_err = meta.last_error logger.debug( f"Failed to download a file: {full_dst_file_name}, err: {last_err}. Retrying with " f"max concurrency: {max_concurrency}" ) if not meta.no_sleeping_time: sleeping_time = min(2 ** retry, 16) logger.debug("sleeping: %s", sleeping_time) time.sleep(sleeping_time) elif meta.result_status == ResultStatus.NEED_RETRY: last_err = meta.last_error logger.debug( f"Failed to download a file: {full_dst_file_name}, err: {last_err}. Retrying with " f"max concurrency: {max_concurrency}" ) if not meta.no_sleeping_time: sleeping_time = min(2 ** retry, 16) logger.debug(f"sleeping: {sleeping_time}") time.sleep(sleeping_time) else: if last_err: raise last_err else: msg = f"Unknown Error in downloading a file: {full_dst_file_name}" raise Exception(msg) @staticmethod def upload_one_file_with_retry(meta: "SnowflakeFileMeta") -> None: """Uploads one file with retry.""" util_class = SnowflakeRemoteStorageUtil.get_for_storage_type( meta.client_meta.stage_info["locationType"] ) for _ in range(10): # retry SnowflakeRemoteStorageUtil.upload_one_file(meta) if meta.result_status == ResultStatus.UPLOADED: for _ in range(10): util_class.get_file_header(meta, meta.dst_file_name) if meta.result_status == ResultStatus.NOT_FOUND_FILE: time.sleep(1) # wait 1 second logger.debug("not found. double checking...") continue break else: # not found. retry with the outer loop logger.debug("not found. gave up. re-uploading...") continue break else: # could not upload a file even after retry meta.result_status = ResultStatus.ERROR
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2012-2021 Snowflake Computing Inc. All right reserved. # from __future__ import division import os import shutil import time from collections import namedtuple from io import BytesIO from logging import getLogger from typing import TYPE_CHECKING from boto3 import Session from .azure_util import SnowflakeAzureUtil from .constants import ResultStatus from .encryption_util import SnowflakeEncryptionUtil from .gcs_util import SnowflakeGCSUtil from .s3_util import SnowflakeS3Util if TYPE_CHECKING: # pragma: no cover from .file_transfer_agent import SnowflakeFileMeta DEFAULT_CONCURRENCY = 1 DEFAULT_MAX_RETRY = 5 logger = getLogger(__name__) """ Encryption Material """ SnowflakeFileEncryptionMaterial = namedtuple( "SnowflakeS3FileEncryptionMaterial", [ "query_stage_master_key", # query stage master key "query_id", # query id "smk_id", # SMK id ], ) class NeedRenewTokenError(Exception): pass class SnowflakeRemoteStorageUtil(object): @staticmethod def get_for_storage_type(_type): if _type == "S3": return SnowflakeS3Util elif _type == "AZURE": return SnowflakeAzureUtil elif _type == "GCS": return SnowflakeGCSUtil else: return None @staticmethod def create_client( stage_info, use_accelerate_endpoint: bool = False, use_s3_regional_url: bool = False, s3_connection_pool_size: int = 1, ) -> Session.resource: util_class = SnowflakeRemoteStorageUtil.get_for_storage_type( stage_info["locationType"] ) return util_class.create_client( stage_info, use_accelerate_endpoint=use_accelerate_endpoint, use_s3_regional_url=use_s3_regional_url, s3_connection_pool_size=s3_connection_pool_size, ) @staticmethod def upload_one_file(meta: "SnowflakeFileMeta") -> None: """Uploads a file to S3.""" encryption_metadata = None if meta.encryption_material is not None: if meta.src_stream is None: (encryption_metadata, data_file) = SnowflakeEncryptionUtil.encrypt_file( meta.encryption_material, meta.real_src_file_name, tmp_dir=meta.tmp_dir, ) logger.debug( f"encrypted data file={data_file}, size={os.path.getsize(data_file)}" ) else: encrypted_stream = BytesIO() src_stream = meta.real_src_stream or meta.src_stream src_stream.seek(0) encryption_metadata = SnowflakeEncryptionUtil.encrypt_stream( meta.encryption_material, src_stream, encrypted_stream ) src_stream.seek(0) logger.debug( f"encrypted data stream size={encrypted_stream.seek(0, os.SEEK_END)}" ) encrypted_stream.seek(0) if meta.real_src_stream is not None: meta.real_src_stream.close() meta.real_src_stream = encrypted_stream data_file = meta.real_src_file_name else: logger.debug("not encrypted data file") data_file = meta.real_src_file_name util_class = SnowflakeRemoteStorageUtil.get_for_storage_type( meta.client_meta.stage_info["locationType"] ) logger.debug( f"putting a file: {meta.client_meta.stage_info['location']}, {meta.dst_file_name}" ) max_concurrency = meta.parallel last_err = None max_retry = DEFAULT_MAX_RETRY for retry in range(max_retry): if not meta.overwrite: file_header = util_class.get_file_header(meta, meta.dst_file_name) if file_header and meta.result_status == ResultStatus.UPLOADED: logger.debug( f'file already exists location="{meta.client_meta.stage_info["location"]}", ' f'file_name="{meta.dst_file_name}"' ) meta.dst_file_size = 0 meta.result_status = ResultStatus.SKIPPED return if meta.overwrite or meta.result_status == ResultStatus.NOT_FOUND_FILE: util_class.upload_file( data_file, meta, encryption_metadata, max_concurrency, multipart_threshold=meta.multipart_threshold, ) if meta.result_status == ResultStatus.UPLOADED: return elif meta.result_status == ResultStatus.RENEW_TOKEN: return elif meta.result_status == ResultStatus.RENEW_PRESIGNED_URL: return elif meta.result_status == ResultStatus.NEED_RETRY: last_err = meta.last_error logger.debug( f"Failed to upload a file: {data_file}, err: {last_err}. Retrying with " f"max concurrency: {max_concurrency}" ) if not meta.no_sleeping_time: sleeping_time = min(2 ** retry, 16) logger.debug(f"sleeping {sleeping_time}") time.sleep(sleeping_time) elif meta.result_status == ResultStatus.NEED_RETRY_WITH_LOWER_CONCURRENCY: last_err = meta.last_error max_concurrency = meta.parallel - int(retry * meta.parallel / max_retry) max_concurrency = max(DEFAULT_CONCURRENCY, max_concurrency) meta.last_max_concurrency = max_concurrency logger.debug( f"Failed to upload a file: {data_file}, err: {last_err}. Retrying with " f"max concurrency: {max_concurrency}" ) if meta.no_sleeping_time is None: sleeping_time = min(2 ** retry, 16) logger.debug(f"sleeping: {sleeping_time}") time.sleep(sleeping_time) else: if last_err: raise last_err else: msg = f"Unknown Error in uploading a file: {data_file}" raise Exception(msg) @staticmethod def download_one_file(meta: "SnowflakeFileMeta") -> None: """Downloads a file from S3.""" full_dst_file_name = os.path.join( meta.local_location, os.path.basename(meta.dst_file_name) ) full_dst_file_name = os.path.realpath(full_dst_file_name) # TODO: validate full_dst_file_name is under the writable directory base_dir = os.path.dirname(full_dst_file_name) if not os.path.exists(base_dir): os.makedirs(base_dir) util_class = SnowflakeRemoteStorageUtil.get_for_storage_type( meta.client_meta.stage_info["locationType"] ) file_header = util_class.get_file_header(meta, meta.src_file_name) if file_header: meta.src_file_size = file_header.content_length full_dst_file_name = os.path.join( meta.local_location, os.path.basename(meta.dst_file_name) ) full_dst_file_name = os.path.realpath(full_dst_file_name) max_concurrency = meta.parallel last_err = None max_retry = DEFAULT_MAX_RETRY for retry in range(max_retry): util_class._native_download_file(meta, full_dst_file_name, max_concurrency) if meta.result_status == ResultStatus.DOWNLOADED: if meta.encryption_material is not None: logger.debug(f"encrypted data file={full_dst_file_name}") # For storage utils that do not have the privilege of # getting the metadata early, both object and metadata # are downloaded at once. In which case, the file meta will # be updated with all the metadata that we need and # then we can call get_file_header to get just that and also # preserve the idea of getting metadata in the first place. # One example of this is the utils that use presigned url # for upload/download and not the storage client library. if meta.presigned_url is not None: file_header = util_class.get_file_header( meta, meta.src_file_name ) tmp_dst_file_name = SnowflakeEncryptionUtil.decrypt_file( file_header.encryption_metadata, meta.encryption_material, full_dst_file_name, tmp_dir=meta.tmp_dir, ) shutil.copyfile(tmp_dst_file_name, full_dst_file_name) os.unlink(tmp_dst_file_name) else: logger.debug(f"not encrypted data file={full_dst_file_name}") stat_info = os.stat(full_dst_file_name) meta.dst_file_size = stat_info.st_size return elif meta.result_status == ResultStatus.RENEW_PRESIGNED_URL: return elif meta.result_status == ResultStatus.RENEW_TOKEN: return elif meta.result_status == ResultStatus.NEED_RETRY_WITH_LOWER_CONCURRENCY: max_concurrency = meta.parallel - int(retry * meta.parallel / max_retry) max_concurrency = max(DEFAULT_CONCURRENCY, max_concurrency) meta.last_max_concurrency = max_concurrency last_err = meta.last_error logger.debug( f"Failed to download a file: {full_dst_file_name}, err: {last_err}. Retrying with " f"max concurrency: {max_concurrency}" ) if not meta.no_sleeping_time: sleeping_time = min(2 ** retry, 16) logger.debug("sleeping: %s", sleeping_time) time.sleep(sleeping_time) elif meta.result_status == ResultStatus.NEED_RETRY: last_err = meta.last_error logger.debug( f"Failed to download a file: {full_dst_file_name}, err: {last_err}. Retrying with " f"max concurrency: {max_concurrency}" ) if not meta.no_sleeping_time: sleeping_time = min(2 ** retry, 16) logger.debug(f"sleeping: {sleeping_time}") time.sleep(sleeping_time) else: if last_err: raise last_err else: msg = f"Unknown Error in downloading a file: {full_dst_file_name}" raise Exception(msg) @staticmethod def upload_one_file_with_retry(meta: "SnowflakeFileMeta") -> None: """Uploads one file with retry.""" util_class = SnowflakeRemoteStorageUtil.get_for_storage_type( meta.client_meta.stage_info["locationType"] ) for _ in range(10): # retry SnowflakeRemoteStorageUtil.upload_one_file(meta) if meta.result_status == ResultStatus.UPLOADED: for _ in range(10): util_class.get_file_header(meta, meta.dst_file_name) if meta.result_status == ResultStatus.NOT_FOUND_FILE: time.sleep(1) # wait 1 second logger.debug("not found. double checking...") continue break else: # not found. retry with the outer loop logger.debug("not found. gave up. re-uploading...") continue break else: # could not upload a file even after retry meta.result_status = ResultStatus.ERROR
import os, sys from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, QEvent, QBuffer, QIODevice, QLocale, Qt, QVariant, QModelIndex from PyQt5 import QtGui, QtWidgets, QtCore import time import numpy as np from pymodaq.daq_utils import daq_utils as utils from pymodaq.daq_utils.gui_utils import select_file from pyqtgraph.parametertree import Parameter, ParameterTree, registerParameterType, parameterTypes from pymodaq.daq_utils import custom_parameter_tree as custom_tree logger = utils.set_logger(utils.get_module_name(__file__)) remote_path = utils.get_set_remote_path() remote_types = ['ShortCut', 'Joystick'] actuator_actions = ['move_Rel', 'move_Rel_p', 'move_Rel_m'] detector_actions = ['snap', 'grab', 'stop'] try: import pygame except ModuleNotFoundError as e: remote_types.pop(remote_types.index('Joystick')) logger.warning('Could not load pygame module, no joystick configurable') class ScalableGroupRemote(parameterTypes.GroupParameter): """ """ def __init__(self, **opts): opts['type'] = 'groupremote' opts['addText'] = "Add" if 'remote' not in opts: opts['remote'] = remote_types[0] if 'addList' not in opts: opts['addList'] = [] super().__init__(**opts) def addNew(self, typ): """ Add a child. """ childnames = [par.name() for par in self.children()] if childnames == []: newindex = 0 else: newindex = len(childnames) params = [{'title': 'Action:', 'name': 'action', 'type': 'list', 'value': typ, 'values': self.opts['addList']}, {'title': 'Remote:', 'name': 'remote_type', 'type': 'list', 'value': 'Keyboard', 'values': ['Keyboard', 'Joystick']}, ] params.extend([ {'title': 'Set Shortcut:', 'name': 'set_shortcut', 'type': 'bool_push', 'label': 'Set', 'value': False}, {'title': 'Shortcut:', 'name': 'shortcut', 'type': 'str', 'value': ''}, {'title': 'Set Joystick ID:', 'name': 'set_joystick', 'type': 'bool_push', 'label': 'Set', 'value': False, 'visible': False}, {'title': 'Joystick ID:', 'name': 'joystickID', 'type': 'int', 'value': -1, 'visible': False}, {'title': 'Actionner type:', 'name': 'actionner_type', 'type': 'list', 'values': ['Axis', 'Button', 'Hat'], 'visible': False}, {'title': 'Actionner ID:', 'name': 'actionnerID', 'type': 'int', 'value': -1, 'visible': False}, ]) # for param in params: # if param['type'] == 'itemselect' or param['type'] == 'list': # param['show_pb'] = True child = {'title': f'Action {newindex:02d}', 'name': f'action{newindex:02d}', 'type': 'group', 'removable': True, 'children': params, 'removable': True, 'renamable': False} self.addChild(child) registerParameterType('groupremote', ScalableGroupRemote, override=True) class ScalableGroupModules(parameterTypes.GroupParameter): """ """ def __init__(self, **opts): opts['type'] = 'groupremote' opts['addText'] = "Add" if 'modtype' not in opts: opts['modtype'] = 'Actuator' if 'addList' not in opts: opts['addList'] = [] super().__init__(**opts) def addNew(self, typ): """ Add a child. """ childnames = [par.name() for par in self.children()] if childnames == []: newindex = 0 else: newindex = len(childnames) if self.opts['modtype'] == 'Actuator': addlist = actuator_actions else: addlist = detector_actions params = [ {'title': 'Actions:', 'name': 'actions', 'type': 'groupremote', 'value': typ, 'values': self.opts['addList'], 'addList': addlist}, ] # for param in params: # if param['type'] == 'itemselect' or param['type'] == 'list': # param['show_pb'] = True if self.opts['modtype'] == 'Actuator': child = {'title': f'Actuator {typ}', 'name': f'act_{newindex:03d}', 'type': 'group', 'removable': True, 'children': params, 'removable': True, 'renamable': False} else: child = {'title': f'Detector {typ}', 'name': f'det_{newindex:03d}', 'type': 'group', 'removable': True, 'children': params, 'removable': True, 'renamable': False} if child['name'] not in [child.name() for child in self.children()]: self.addChild(child) registerParameterType('groupmodules', ScalableGroupModules, override=True) class ShortcutSelection(QtWidgets.QDialog): def __init__(self): super().__init__() layout = QtWidgets.QVBoxLayout() self.setLayout(layout) horwidget = QtWidgets.QWidget() layout.addWidget(horwidget) hor_layout = QtWidgets.QHBoxLayout() horwidget.setLayout(hor_layout) label = QtWidgets.QLabel('Pressed key on the keyboard:') self.label = QtWidgets.QLabel('') hor_layout.addWidget(label) hor_layout.addWidget(self.label) buttonBox = QtWidgets.QDialogButtonBox() buttonBox.addButton(QtWidgets.QDialogButtonBox.Ok) buttonBox.addButton(QtWidgets.QDialogButtonBox.Cancel) layout.addWidget(self.label) layout.addWidget(buttonBox) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) def keyPressEvent(self, event): keyseq = QtGui.QKeySequence(event.key()) self.label.setText(keyseq.toString()) class JoystickButtonsSelection(QtWidgets.QDialog): def __init__(self): super().__init__() self.setupUI() self.selection = None pygame.init() pygame.joystick.init() # width, height = 64 * 10, 64 * 8 # self.screen = pygame.display.set_mode((width, height)) joystick_count = pygame.joystick.get_count() for ind in range(joystick_count): joystick = pygame.joystick.Joystick(ind) joystick.init() self.startTimer(10) def timerEvent(self, event): for event in pygame.event.get(): # User did something. if 'joy' in event.dict: self.settings.child(('joystickID')).setValue(event.joy) self.selection = dict(joy=event.joy) if event.type == pygame.QUIT: # If user clicked close. self.reject() elif event.type == pygame.JOYBUTTONDOWN or event.type == pygame.JOYBUTTONUP: self.settings.child(('buttonID')).show(True) self.settings.child(('axisID')).show(False) self.settings.child(('hatID')).show(False) self.settings.child(('axis_value')).show(False) self.settings.child(('hat_value1')).show(False) self.settings.child(('hat_value2')).show(False) self.settings.child(('buttonID')).setValue(event.button) self.selection.update(dict(button=event.button)) elif event.type == pygame.JOYAXISMOTION: self.settings.child(('buttonID')).show(False) self.settings.child(('axisID')).show(True) self.settings.child(('hatID')).show(False) self.settings.child(('axis_value')).show(True) self.settings.child(('axisID')).setValue(event.axis) self.settings.child(('axis_value')).setValue(event.value) self.settings.child(('hat_value1')).show(False) self.settings.child(('hat_value2')).show(False) self.selection.update(dict(axis=event.axis, value=event.value)) elif event.type == pygame.JOYHATMOTION: self.settings.child(('buttonID')).show(False) self.settings.child(('axisID')).show(False) self.settings.child(('hatID')).show(True) self.settings.child(('axis_value')).show(True) self.settings.child(('hat_value1')).show(True) self.settings.child(('hat_value2')).show(True) self.settings.child(('hat_value1')).setValue(event.value[0]) self.settings.child(('hat_value2')).setValue(event.value[1]) self.selection.update(dict(hat=event.hat, value=event.value)) def setupUI(self): layout = QtWidgets.QVBoxLayout() self.setLayout(layout) label = QtWidgets.QLabel('Press a button or move an axis on the Joystick:') layout.addWidget(label) params = [{'title': 'Joystick ID', 'name': 'joystickID', 'type': 'int', 'value': -1}, {'title': 'Button ID', 'name': 'buttonID', 'type': 'int', 'value': -1, 'visible': False}, {'title': 'Axis ID', 'name': 'axisID', 'type': 'int', 'value': -1, 'visible': False}, {'title': 'Value:', 'name': 'axis_value', 'type': 'float', 'value': 0., 'visible': False}, {'title': 'Hat ID', 'name': 'hatID', 'type': 'int', 'value': -1, 'visible': False}, {'title': 'Value x:', 'name': 'hat_value1', 'type': 'int', 'value': 0, 'visible': False}, {'title': 'Value y:', 'name': 'hat_value2', 'type': 'int', 'value': 0, 'visible': False},] self.settings = Parameter.create(name='settings', type='group', children=params) self.settings_tree = ParameterTree() # tree.setMinimumWidth(400) #self.settings_tree.setMinimumHeight(500) self.settings_tree.setParameters(self.settings, showTop=False) layout.addWidget(self.settings_tree) buttonBox = QtWidgets.QDialogButtonBox() buttonBox.addButton(QtWidgets.QDialogButtonBox.Ok) buttonBox.addButton(QtWidgets.QDialogButtonBox.Cancel) layout.addWidget(buttonBox) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) class RemoteManager(QObject): remote_changed = pyqtSignal(dict) def __init__(self, actuators=[], detectors=[], msgbox=False): super().__init__() self.actuators = actuators self.detectors = detectors if msgbox: msgBox = QtWidgets.QMessageBox() msgBox.setText("Preset Manager?") msgBox.setInformativeText("What do you want to do?"); cancel_button = msgBox.addButton(QtWidgets.QMessageBox.Cancel) new_button = msgBox.addButton("New", QtWidgets.QMessageBox.ActionRole) modify_button = msgBox.addButton('Modify', QtWidgets.QMessageBox.AcceptRole) msgBox.setDefaultButton(QtWidgets.QMessageBox.Cancel) ret = msgBox.exec() if msgBox.clickedButton() == new_button: self.set_new_remote() elif msgBox.clickedButton() == modify_button: path = select_file(start_path=remote_path, save=False, ext='xml') if path != '': self.set_file_remote(str(path)) else: # cancel pass params = [{'title': 'Activate all', 'name': 'activate_all', 'type': 'action'}, {'title': 'Deactivate all', 'name': 'deactivate_all', 'type': 'action'}, {'title:': 'Actions', 'name': 'action_group', 'type': 'group'}] self.remote_actions = dict(shortcuts=dict([]), joysticks=dict([])) self.remote_settings = Parameter.create(title='Remote Settings', name='remote', type='group', children=params) self.remote_settings.sigTreeStateChanged.connect(self.remote_settings_changed) self.remote_settings_tree = ParameterTree() self.remote_settings_tree.setParameters(self.remote_settings, showTop=False) self.remote_settings.child(('activate_all')).sigActivated.connect(lambda: self.activate_all(True)) self.remote_settings.child(('deactivate_all')).sigActivated.connect(lambda: self.activate_all(False)) def activate_all(self, activate=True): for child in self.remote_settings.child(('action_group')).children(): child.setValue(activate) def set_remote_configuration(self): #remove existing shorcuts while len(self.remote_actions['shortcuts']): self.remote_actions['shortcuts'].pop(list(self.remote_actions['shortcuts'].keys())[0]) while len(self.remote_actions['joysticks']): self.remote_actions['joysticks'].pop(list(self.remote_actions['joysticks'].keys())[0]) all_actions = [] for child in self.remote_params.child('act_actions').children(): module_name = child.opts['title'].split('Actuator ')[1] module_type = 'act' for action in child.child(('actions')).children(): all_actions.append((module_name, action, module_type)) for child in self.remote_params.child('det_actions').children(): module_name = child.opts['title'].split('Detector ')[1] module_type = 'det' for action in child.child(('actions')).children(): all_actions.append((module_name, action, module_type)) for ind, action_tuple in enumerate(all_actions): module, action, module_type = action_tuple if action.child('remote_type').value() == 'Keyboard': #stc = QtWidgets.QShortcut(QtGui.QKeySequence(action.child(('shortcut')).value()), self.dockarea) self.remote_settings.child(('action_group')).addChild( {'title': f"{module}: {action.child(("action")).value()} " f"{action.child(("shortcut")).value()}:", 'name': f'shortcut{ind:02d}', 'type': 'led_push', 'value': False}) self.remote_actions['shortcuts'][f'shortcut{ind:02d}'] = \ dict(shortcut=action.child(('shortcut')).value(), activated=False, name=f'shortcut{ind:02d}', action=action.child(('action')).value(), module_name=module, module_type=module_type) else: self.remote_settings.child(('action_group')).addChild( {'title': f"{module}: {action.child(("action")).value()}=>" f"J{action.child(("joystickID")).value()}/" f"{action.child(("actionner_type")).value()}" f"{action.child(("actionnerID")).value()}:", 'name': f'joy{ind:02d}', 'type': 'led_push', 'value': False}) self.remote_actions['joysticks'][f'joy{ind:02d}'] =\ dict(joystickID=action.child(('joystickID')).value(), actionner_type=action.child(('actionner_type')).value(), actionnerID=action.child(('actionnerID')).value(), activated=False, name=f'joy{ind:02d}', action=action.child(('action')).value(), module_name=module, module_type=module_type) self.activate_all() def set_new_remote(self, file=None): if file is None: file = 'remote_default' param = [ {'title': 'Filename:', 'name': 'filename', 'type': 'str', 'value': file}, ] params_action = [{'title': 'Actuator Actions:', 'name': 'act_actions', 'type': 'groupmodules', 'addList': self.actuators, 'modtype': 'Actuator'}, {'title': 'Detector Actions:', 'name': 'det_actions', 'type': 'groupmodules', 'addList': self.detectors, 'modtype': 'Detector'} ] # PresetScalableGroupMove(name="Moves")] self.remote_params = Parameter.create(title='Preset', name='Preset', type='group', children=param + params_action) self.remote_params.sigTreeStateChanged.connect(self.parameter_tree_changed) logger.info('Creating a new remote file') self.show_remote() def parameter_tree_changed(self, param, changes): """ Check for changes in the given (parameter,change,information) tuple list. In case of value changed, update the DAQscan_settings tree consequently. =============== ============================================ ============================== **Parameters** **Type** **Description** *param* instance of pyqtgraph parameter the parameter to be checked *changes* (parameter,change,information) tuple list the current changes state =============== ============================================ ============================== """ for param, change, data in changes: path = self.remote_params.childPath(param) if change == 'childAdded': pass elif change == 'value': if param.name() == 'remote_type': status = data == 'Keyboard' param.parent().child(('set_shortcut')).show(status) param.parent().child(('shortcut')).show(status) param.parent().child(('set_joystick')).show(not status) param.parent().child(('joystickID')).show(not status) param.parent().child(('actionner_type')).show(not status) param.parent().child(('actionnerID')).show(not status) elif param.name() == 'set_shortcut': msgBox = ShortcutSelection() ret = msgBox.exec() if ret: param.parent().child(('shortcut')).setValue(msgBox.label.text()) elif param.name() == 'set_joystick': msgBox = JoystickButtonsSelection() ret = msgBox.exec() if ret: param.parent().child(('joystickID')).setValue(msgBox.selection['joy']) """ possible cases: ['Axis', 'Button', 'Hat'] """ if 'axis' in msgBox.selection: param.parent().child(('actionner_type')).setValue('Axis') param.parent().child(('actionnerID')).setValue(msgBox.selection['axis']) elif 'button' in msgBox.selection: param.parent().child(('actionner_type')).setValue('Button') param.parent().child(('actionnerID')).setValue(msgBox.selection['button']) elif 'hat' in msgBox.selection: param.parent().child(('actionner_type')).setValue('Hat') param.parent().child(('actionnerID')).setValue(msgBox.selection['hat']) elif change == 'parent': pass def remote_settings_changed(self, param, changes): for param, change, data in changes: path = self.remote_params.childPath(param) if change == 'childAdded': pass elif change == 'value': if 'shortcut' in param.name(): self.remote_actions['shortcuts'][param.name()]['activated'] = data self.remote_changed.emit(dict(action_type='shortcut', action_name=param.name(), action_dict=self.remote_actions['shortcuts'][param.name()])) elif 'joy' in param.name(): self.remote_actions['joysticks'][param.name()]['activated'] = data self.remote_changed.emit(dict(action_type='joystick', action_name=param.name(), action_dict=self.remote_actions['joysticks'][param.name()])) def set_file_remote(self, filename, show=True): """ """ children = custom_tree.XML_file_to_parameter(filename) self.remote_params = Parameter.create(title='Shortcuts:', name='shortcuts', type='group', children=children) if show: self.show_remote() def show_remote(self): """ """ dialog = QtWidgets.QDialog() vlayout = QtWidgets.QVBoxLayout() tree = ParameterTree() # tree.setMinimumWidth(400) tree.setMinimumHeight(500) tree.setParameters(self.remote_params, showTop=False) vlayout.addWidget(tree) dialog.setLayout(vlayout) buttonBox = QtWidgets.QDialogButtonBox(parent=dialog) buttonBox.addButton('Save', buttonBox.AcceptRole) buttonBox.accepted.connect(dialog.accept) buttonBox.addButton('Cancel', buttonBox.RejectRole) buttonBox.rejected.connect(dialog.reject) vlayout.addWidget(buttonBox) dialog.setWindowTitle('Fill in information about the actions and their shortcuts') res = dialog.exec() if res == dialog.Accepted: # save preset parameters in a xml file custom_tree.parameter_to_xml_file(self.remote_params, os.path.join(remote_path, self.remote_params.child( ('filename')).value())) if __name__ == '__main__': actuators = ['act0', 'act1', 'act2'] detectors = ['det0', 'det1', 'det2'] app = QtWidgets.QApplication(sys.argv) #prog = RemoteManager(actuators=actuators, detectors=detectors, msgbox=True) msgBox = JoystickButtonsSelection() ret = msgBox.exec() sys.exit(app.exec_())
import os, sys from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, QEvent, QBuffer, QIODevice, QLocale, Qt, QVariant, QModelIndex from PyQt5 import QtGui, QtWidgets, QtCore import time import numpy as np from pymodaq.daq_utils import daq_utils as utils from pymodaq.daq_utils.gui_utils import select_file from pyqtgraph.parametertree import Parameter, ParameterTree, registerParameterType, parameterTypes from pymodaq.daq_utils import custom_parameter_tree as custom_tree logger = utils.set_logger(utils.get_module_name(__file__)) remote_path = utils.get_set_remote_path() remote_types = ['ShortCut', 'Joystick'] actuator_actions = ['move_Rel', 'move_Rel_p', 'move_Rel_m'] detector_actions = ['snap', 'grab', 'stop'] try: import pygame except ModuleNotFoundError as e: remote_types.pop(remote_types.index('Joystick')) logger.warning('Could not load pygame module, no joystick configurable') class ScalableGroupRemote(parameterTypes.GroupParameter): """ """ def __init__(self, **opts): opts['type'] = 'groupremote' opts['addText'] = "Add" if 'remote' not in opts: opts['remote'] = remote_types[0] if 'addList' not in opts: opts['addList'] = [] super().__init__(**opts) def addNew(self, typ): """ Add a child. """ childnames = [par.name() for par in self.children()] if childnames == []: newindex = 0 else: newindex = len(childnames) params = [{'title': 'Action:', 'name': 'action', 'type': 'list', 'value': typ, 'values': self.opts['addList']}, {'title': 'Remote:', 'name': 'remote_type', 'type': 'list', 'value': 'Keyboard', 'values': ['Keyboard', 'Joystick']}, ] params.extend([ {'title': 'Set Shortcut:', 'name': 'set_shortcut', 'type': 'bool_push', 'label': 'Set', 'value': False}, {'title': 'Shortcut:', 'name': 'shortcut', 'type': 'str', 'value': ''}, {'title': 'Set Joystick ID:', 'name': 'set_joystick', 'type': 'bool_push', 'label': 'Set', 'value': False, 'visible': False}, {'title': 'Joystick ID:', 'name': 'joystickID', 'type': 'int', 'value': -1, 'visible': False}, {'title': 'Actionner type:', 'name': 'actionner_type', 'type': 'list', 'values': ['Axis', 'Button', 'Hat'], 'visible': False}, {'title': 'Actionner ID:', 'name': 'actionnerID', 'type': 'int', 'value': -1, 'visible': False}, ]) # for param in params: # if param['type'] == 'itemselect' or param['type'] == 'list': # param['show_pb'] = True child = {'title': f'Action {newindex:02d}', 'name': f'action{newindex:02d}', 'type': 'group', 'removable': True, 'children': params, 'removable': True, 'renamable': False} self.addChild(child) registerParameterType('groupremote', ScalableGroupRemote, override=True) class ScalableGroupModules(parameterTypes.GroupParameter): """ """ def __init__(self, **opts): opts['type'] = 'groupremote' opts['addText'] = "Add" if 'modtype' not in opts: opts['modtype'] = 'Actuator' if 'addList' not in opts: opts['addList'] = [] super().__init__(**opts) def addNew(self, typ): """ Add a child. """ childnames = [par.name() for par in self.children()] if childnames == []: newindex = 0 else: newindex = len(childnames) if self.opts['modtype'] == 'Actuator': addlist = actuator_actions else: addlist = detector_actions params = [ {'title': 'Actions:', 'name': 'actions', 'type': 'groupremote', 'value': typ, 'values': self.opts['addList'], 'addList': addlist}, ] # for param in params: # if param['type'] == 'itemselect' or param['type'] == 'list': # param['show_pb'] = True if self.opts['modtype'] == 'Actuator': child = {'title': f'Actuator {typ}', 'name': f'act_{newindex:03d}', 'type': 'group', 'removable': True, 'children': params, 'removable': True, 'renamable': False} else: child = {'title': f'Detector {typ}', 'name': f'det_{newindex:03d}', 'type': 'group', 'removable': True, 'children': params, 'removable': True, 'renamable': False} if child['name'] not in [child.name() for child in self.children()]: self.addChild(child) registerParameterType('groupmodules', ScalableGroupModules, override=True) class ShortcutSelection(QtWidgets.QDialog): def __init__(self): super().__init__() layout = QtWidgets.QVBoxLayout() self.setLayout(layout) horwidget = QtWidgets.QWidget() layout.addWidget(horwidget) hor_layout = QtWidgets.QHBoxLayout() horwidget.setLayout(hor_layout) label = QtWidgets.QLabel('Pressed key on the keyboard:') self.label = QtWidgets.QLabel('') hor_layout.addWidget(label) hor_layout.addWidget(self.label) buttonBox = QtWidgets.QDialogButtonBox() buttonBox.addButton(QtWidgets.QDialogButtonBox.Ok) buttonBox.addButton(QtWidgets.QDialogButtonBox.Cancel) layout.addWidget(self.label) layout.addWidget(buttonBox) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) def keyPressEvent(self, event): keyseq = QtGui.QKeySequence(event.key()) self.label.setText(keyseq.toString()) class JoystickButtonsSelection(QtWidgets.QDialog): def __init__(self): super().__init__() self.setupUI() self.selection = None pygame.init() pygame.joystick.init() # width, height = 64 * 10, 64 * 8 # self.screen = pygame.display.set_mode((width, height)) joystick_count = pygame.joystick.get_count() for ind in range(joystick_count): joystick = pygame.joystick.Joystick(ind) joystick.init() self.startTimer(10) def timerEvent(self, event): for event in pygame.event.get(): # User did something. if 'joy' in event.dict: self.settings.child(('joystickID')).setValue(event.joy) self.selection = dict(joy=event.joy) if event.type == pygame.QUIT: # If user clicked close. self.reject() elif event.type == pygame.JOYBUTTONDOWN or event.type == pygame.JOYBUTTONUP: self.settings.child(('buttonID')).show(True) self.settings.child(('axisID')).show(False) self.settings.child(('hatID')).show(False) self.settings.child(('axis_value')).show(False) self.settings.child(('hat_value1')).show(False) self.settings.child(('hat_value2')).show(False) self.settings.child(('buttonID')).setValue(event.button) self.selection.update(dict(button=event.button)) elif event.type == pygame.JOYAXISMOTION: self.settings.child(('buttonID')).show(False) self.settings.child(('axisID')).show(True) self.settings.child(('hatID')).show(False) self.settings.child(('axis_value')).show(True) self.settings.child(('axisID')).setValue(event.axis) self.settings.child(('axis_value')).setValue(event.value) self.settings.child(('hat_value1')).show(False) self.settings.child(('hat_value2')).show(False) self.selection.update(dict(axis=event.axis, value=event.value)) elif event.type == pygame.JOYHATMOTION: self.settings.child(('buttonID')).show(False) self.settings.child(('axisID')).show(False) self.settings.child(('hatID')).show(True) self.settings.child(('axis_value')).show(True) self.settings.child(('hat_value1')).show(True) self.settings.child(('hat_value2')).show(True) self.settings.child(('hat_value1')).setValue(event.value[0]) self.settings.child(('hat_value2')).setValue(event.value[1]) self.selection.update(dict(hat=event.hat, value=event.value)) def setupUI(self): layout = QtWidgets.QVBoxLayout() self.setLayout(layout) label = QtWidgets.QLabel('Press a button or move an axis on the Joystick:') layout.addWidget(label) params = [{'title': 'Joystick ID', 'name': 'joystickID', 'type': 'int', 'value': -1}, {'title': 'Button ID', 'name': 'buttonID', 'type': 'int', 'value': -1, 'visible': False}, {'title': 'Axis ID', 'name': 'axisID', 'type': 'int', 'value': -1, 'visible': False}, {'title': 'Value:', 'name': 'axis_value', 'type': 'float', 'value': 0., 'visible': False}, {'title': 'Hat ID', 'name': 'hatID', 'type': 'int', 'value': -1, 'visible': False}, {'title': 'Value x:', 'name': 'hat_value1', 'type': 'int', 'value': 0, 'visible': False}, {'title': 'Value y:', 'name': 'hat_value2', 'type': 'int', 'value': 0, 'visible': False},] self.settings = Parameter.create(name='settings', type='group', children=params) self.settings_tree = ParameterTree() # tree.setMinimumWidth(400) #self.settings_tree.setMinimumHeight(500) self.settings_tree.setParameters(self.settings, showTop=False) layout.addWidget(self.settings_tree) buttonBox = QtWidgets.QDialogButtonBox() buttonBox.addButton(QtWidgets.QDialogButtonBox.Ok) buttonBox.addButton(QtWidgets.QDialogButtonBox.Cancel) layout.addWidget(buttonBox) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) class RemoteManager(QObject): remote_changed = pyqtSignal(dict) def __init__(self, actuators=[], detectors=[], msgbox=False): super().__init__() self.actuators = actuators self.detectors = detectors if msgbox: msgBox = QtWidgets.QMessageBox() msgBox.setText("Preset Manager?") msgBox.setInformativeText("What do you want to do?"); cancel_button = msgBox.addButton(QtWidgets.QMessageBox.Cancel) new_button = msgBox.addButton("New", QtWidgets.QMessageBox.ActionRole) modify_button = msgBox.addButton('Modify', QtWidgets.QMessageBox.AcceptRole) msgBox.setDefaultButton(QtWidgets.QMessageBox.Cancel) ret = msgBox.exec() if msgBox.clickedButton() == new_button: self.set_new_remote() elif msgBox.clickedButton() == modify_button: path = select_file(start_path=remote_path, save=False, ext='xml') if path != '': self.set_file_remote(str(path)) else: # cancel pass params = [{'title': 'Activate all', 'name': 'activate_all', 'type': 'action'}, {'title': 'Deactivate all', 'name': 'deactivate_all', 'type': 'action'}, {'title:': 'Actions', 'name': 'action_group', 'type': 'group'}] self.remote_actions = dict(shortcuts=dict([]), joysticks=dict([])) self.remote_settings = Parameter.create(title='Remote Settings', name='remote', type='group', children=params) self.remote_settings.sigTreeStateChanged.connect(self.remote_settings_changed) self.remote_settings_tree = ParameterTree() self.remote_settings_tree.setParameters(self.remote_settings, showTop=False) self.remote_settings.child(('activate_all')).sigActivated.connect(lambda: self.activate_all(True)) self.remote_settings.child(('deactivate_all')).sigActivated.connect(lambda: self.activate_all(False)) def activate_all(self, activate=True): for child in self.remote_settings.child(('action_group')).children(): child.setValue(activate) def set_remote_configuration(self): #remove existing shorcuts while len(self.remote_actions['shortcuts']): self.remote_actions['shortcuts'].pop(list(self.remote_actions['shortcuts'].keys())[0]) while len(self.remote_actions['joysticks']): self.remote_actions['joysticks'].pop(list(self.remote_actions['joysticks'].keys())[0]) all_actions = [] for child in self.remote_params.child('act_actions').children(): module_name = child.opts['title'].split('Actuator ')[1] module_type = 'act' for action in child.child(('actions')).children(): all_actions.append((module_name, action, module_type)) for child in self.remote_params.child('det_actions').children(): module_name = child.opts['title'].split('Detector ')[1] module_type = 'det' for action in child.child(('actions')).children(): all_actions.append((module_name, action, module_type)) for ind, action_tuple in enumerate(all_actions): module, action, module_type = action_tuple if action.child('remote_type').value() == 'Keyboard': #stc = QtWidgets.QShortcut(QtGui.QKeySequence(action.child(('shortcut')).value()), self.dockarea) self.remote_settings.child(('action_group')).addChild( {'title': f"{module}: {action.child(('action')).value()} " f"{action.child(('shortcut')).value()}:", 'name': f'shortcut{ind:02d}', 'type': 'led_push', 'value': False}) self.remote_actions['shortcuts'][f'shortcut{ind:02d}'] = \ dict(shortcut=action.child(('shortcut')).value(), activated=False, name=f'shortcut{ind:02d}', action=action.child(('action')).value(), module_name=module, module_type=module_type) else: self.remote_settings.child(('action_group')).addChild( {'title': f"{module}: {action.child(('action')).value()}=>" f"J{action.child(('joystickID')).value()}/" f"{action.child(('actionner_type')).value()}" f"{action.child(('actionnerID')).value()}:", 'name': f'joy{ind:02d}', 'type': 'led_push', 'value': False}) self.remote_actions['joysticks'][f'joy{ind:02d}'] =\ dict(joystickID=action.child(('joystickID')).value(), actionner_type=action.child(('actionner_type')).value(), actionnerID=action.child(('actionnerID')).value(), activated=False, name=f'joy{ind:02d}', action=action.child(('action')).value(), module_name=module, module_type=module_type) self.activate_all() def set_new_remote(self, file=None): if file is None: file = 'remote_default' param = [ {'title': 'Filename:', 'name': 'filename', 'type': 'str', 'value': file}, ] params_action = [{'title': 'Actuator Actions:', 'name': 'act_actions', 'type': 'groupmodules', 'addList': self.actuators, 'modtype': 'Actuator'}, {'title': 'Detector Actions:', 'name': 'det_actions', 'type': 'groupmodules', 'addList': self.detectors, 'modtype': 'Detector'} ] # PresetScalableGroupMove(name="Moves")] self.remote_params = Parameter.create(title='Preset', name='Preset', type='group', children=param + params_action) self.remote_params.sigTreeStateChanged.connect(self.parameter_tree_changed) logger.info('Creating a new remote file') self.show_remote() def parameter_tree_changed(self, param, changes): """ Check for changes in the given (parameter,change,information) tuple list. In case of value changed, update the DAQscan_settings tree consequently. =============== ============================================ ============================== **Parameters** **Type** **Description** *param* instance of pyqtgraph parameter the parameter to be checked *changes* (parameter,change,information) tuple list the current changes state =============== ============================================ ============================== """ for param, change, data in changes: path = self.remote_params.childPath(param) if change == 'childAdded': pass elif change == 'value': if param.name() == 'remote_type': status = data == 'Keyboard' param.parent().child(('set_shortcut')).show(status) param.parent().child(('shortcut')).show(status) param.parent().child(('set_joystick')).show(not status) param.parent().child(('joystickID')).show(not status) param.parent().child(('actionner_type')).show(not status) param.parent().child(('actionnerID')).show(not status) elif param.name() == 'set_shortcut': msgBox = ShortcutSelection() ret = msgBox.exec() if ret: param.parent().child(('shortcut')).setValue(msgBox.label.text()) elif param.name() == 'set_joystick': msgBox = JoystickButtonsSelection() ret = msgBox.exec() if ret: param.parent().child(('joystickID')).setValue(msgBox.selection['joy']) """ possible cases: ['Axis', 'Button', 'Hat'] """ if 'axis' in msgBox.selection: param.parent().child(('actionner_type')).setValue('Axis') param.parent().child(('actionnerID')).setValue(msgBox.selection['axis']) elif 'button' in msgBox.selection: param.parent().child(('actionner_type')).setValue('Button') param.parent().child(('actionnerID')).setValue(msgBox.selection['button']) elif 'hat' in msgBox.selection: param.parent().child(('actionner_type')).setValue('Hat') param.parent().child(('actionnerID')).setValue(msgBox.selection['hat']) elif change == 'parent': pass def remote_settings_changed(self, param, changes): for param, change, data in changes: path = self.remote_params.childPath(param) if change == 'childAdded': pass elif change == 'value': if 'shortcut' in param.name(): self.remote_actions['shortcuts'][param.name()]['activated'] = data self.remote_changed.emit(dict(action_type='shortcut', action_name=param.name(), action_dict=self.remote_actions['shortcuts'][param.name()])) elif 'joy' in param.name(): self.remote_actions['joysticks'][param.name()]['activated'] = data self.remote_changed.emit(dict(action_type='joystick', action_name=param.name(), action_dict=self.remote_actions['joysticks'][param.name()])) def set_file_remote(self, filename, show=True): """ """ children = custom_tree.XML_file_to_parameter(filename) self.remote_params = Parameter.create(title='Shortcuts:', name='shortcuts', type='group', children=children) if show: self.show_remote() def show_remote(self): """ """ dialog = QtWidgets.QDialog() vlayout = QtWidgets.QVBoxLayout() tree = ParameterTree() # tree.setMinimumWidth(400) tree.setMinimumHeight(500) tree.setParameters(self.remote_params, showTop=False) vlayout.addWidget(tree) dialog.setLayout(vlayout) buttonBox = QtWidgets.QDialogButtonBox(parent=dialog) buttonBox.addButton('Save', buttonBox.AcceptRole) buttonBox.accepted.connect(dialog.accept) buttonBox.addButton('Cancel', buttonBox.RejectRole) buttonBox.rejected.connect(dialog.reject) vlayout.addWidget(buttonBox) dialog.setWindowTitle('Fill in information about the actions and their shortcuts') res = dialog.exec() if res == dialog.Accepted: # save preset parameters in a xml file custom_tree.parameter_to_xml_file(self.remote_params, os.path.join(remote_path, self.remote_params.child( ('filename')).value())) if __name__ == '__main__': actuators = ['act0', 'act1', 'act2'] detectors = ['det0', 'det1', 'det2'] app = QtWidgets.QApplication(sys.argv) #prog = RemoteManager(actuators=actuators, detectors=detectors, msgbox=True) msgBox = JoystickButtonsSelection() ret = msgBox.exec() sys.exit(app.exec_())
from collections import ( namedtuple, ) import datetime import hashlib import hmac import json import os import urllib from jupyterhub.spawner import ( Spawner, ) from tornado import ( gen, ) from tornado.concurrent import ( Future, ) from tornado.httpclient import ( AsyncHTTPClient, HTTPError, HTTPRequest, ) from traitlets.config.configurable import ( Configurable, ) from traitlets import ( Bool, Dict, Instance, Int, List, TraitType, Type, Unicode, default, ) AwsCreds = namedtuple('AwsCreds', [ 'access_key_id', 'secret_access_key', 'pre_auth_headers', ]) class Datetime(TraitType): klass = datetime.datetime default_value = datetime.datetime(1900, 1, 1) class FargateSpawnerAuthentication(Configurable): async def get_credentials(self): raise NotImplementedError() class FargateSpawnerSecretAccessKeyAuthentication(FargateSpawnerAuthentication): aws_access_key_id = Unicode(config=True) aws_secret_access_key = Unicode(config=True) pre_auth_headers = Dict() async def get_credentials(self): return AwsCreds( access_key_id=self.aws_access_key_id, secret_access_key=self.aws_secret_access_key, pre_auth_headers=self.pre_auth_headers, ) class FargateSpawnerECSRoleAuthentication(FargateSpawnerAuthentication): aws_access_key_id = Unicode() aws_secret_access_key = Unicode() pre_auth_headers = Dict() expiration = Datetime() async def get_credentials(self): now = datetime.datetime.now() if now > self.expiration: request = HTTPRequest('http://169.254.170.2' + os.environ['AWS_CONTAINER_CREDENTIALS_RELATIVE_URI'], method='GET') creds = json.loads((await AsyncHTTPClient().fetch(request)).body.decode('utf-8')) self.aws_access_key_id = creds['AccessKeyId'] self.aws_secret_access_key = creds['SecretAccessKey'] self.pre_auth_headers = { 'x-amz-security-token': creds['Token'], } self.expiration = datetime.datetime.strptime(creds['Expiration'], '%Y-%m-%dT%H:%M:%SZ') return AwsCreds( access_key_id=self.aws_access_key_id, secret_access_key=self.aws_secret_access_key, pre_auth_headers=self.pre_auth_headers, ) class FargateSpawner(Spawner): aws_region = Unicode(config=True) aws_ecs_host = Unicode(config=True) task_role_arn = Unicode(config=True) task_cluster_name = Unicode(config=True) task_container_name = Unicode(config=True) task_definition_arn = Unicode(config=True) task_security_groups = List(trait=Unicode, config=True) task_subnets = List(trait=Unicode, config=True) notebook_port = Int(config=True) notebook_scheme = Unicode(config=True) notebook_args = List(trait=Unicode, config=True) authentication_class = Type(FargateSpawnerAuthentication, config=True) authentication = Instance(FargateSpawnerAuthentication) @default('authentication') def _default_authentication(self): return self.authentication_class(parent=self) task_arn = Unicode('') # We mostly are able to call the AWS API to determine status. However, when we yield the # event loop to create the task, if there is a poll before the creation is complete, # we must behave as though we are running/starting, but we have no IDs to use with which # to check the task. calling_run_task = Bool(False) progress_buffer = None def load_state(self, state): ''' Misleading name: this "loads" the state onto self, to be used by other methods ''' super().load_state(state) # Called when first created: we might have no state from a previous invocation self.task_arn = state.get('task_arn', '') def get_state(self): ''' Misleading name: the return value of get_state is saved to the database in order to be able to restore after the hub went down ''' state = super().get_state() state['task_arn'] = self.task_arn return state async def poll(self): # Return values, as dictacted by the Jupyterhub framework: # 0 == not running, or not starting up, i.e. we need to call start # None == running, or not finished starting # 1, or anything else == error return \ None if self.calling_run_task else \ 0 if self.task_arn == '' else \ None if (await _get_task_status(self.log, self._aws_endpoint(), self.task_cluster_name, self.task_arn)) in ALLOWED_STATUSES else \ 1 async def start(self): self.log.debug('Starting spawner') task_port = self.notebook_port self.progress_buffer.write({'progress': 0.5, 'message': 'Starting server...'}) try: self.calling_run_task = True debug_args = ['--debug'] if self.debug else [] args = debug_args + ['--port=' + str(task_port)] + self.notebook_args run_response = await _run_task( self.log, self._aws_endpoint(), self.task_role_arn, self.task_cluster_name, self.task_container_name, self.task_definition_arn, self.task_security_groups, self.task_subnets, self.cmd + args, self.get_env()) task_arn = run_response['tasks'][0]['taskArn'] self.progress_buffer.write({'progress': 1}) finally: self.calling_run_task = False self.task_arn = task_arn max_polls = 50 num_polls = 0 task_ip = '' while task_ip == '': num_polls += 1 if num_polls >= max_polls: raise Exception('Task {} took too long to find IP address'.format(self.task_arn)) task_ip = await _get_task_ip(self.log, self._aws_endpoint(), self.task_cluster_name, task_arn) await gen.sleep(1) self.progress_buffer.write({'progress': 1 + num_polls / max_polls}) self.progress_buffer.write({'progress': 2}) max_polls = self.start_timeout num_polls = 0 status = '' while status != 'RUNNING': num_polls += 1 if num_polls >= max_polls: raise Exception('Task {} took too long to become running'.format(self.task_arn)) status = await _get_task_status(self.log, self._aws_endpoint(), self.task_cluster_name, task_arn) if status not in ALLOWED_STATUSES: raise Exception('Task {} is {}'.format(self.task_arn, status)) await gen.sleep(1) self.progress_buffer.write({'progress': 2 + num_polls / max_polls * 98}) self.progress_buffer.write({'progress': 100, 'message': 'Server started'}) await gen.sleep(1) self.progress_buffer.close() return f'{self.notebook_scheme}://{task_ip}:{task_port}' async def stop(self, now=False): if self.task_arn == '': return self.log.debug('Stopping task (%s)...', self.task_arn) await _ensure_stopped_task(self.log, self._aws_endpoint(), self.task_cluster_name, self.task_arn) self.log.debug('Stopped task (%s)... (done)', self.task_arn) def clear_state(self): super().clear_state() self.log.debug('Clearing state: (%s)', self.task_arn) self.task_arn = '' self.progress_buffer = AsyncIteratorBuffer() async def progress(self): async for progress_message in self.progress_buffer: yield progress_message def _aws_endpoint(self): return { 'region': self.aws_region, 'ecs_host': self.aws_ecs_host, 'ecs_auth': self.authentication.get_credentials, } ALLOWED_STATUSES = ('', 'PROVISIONING', 'PENDING', 'RUNNING') async def _ensure_stopped_task(logger, aws_endpoint, task_cluster_name, task_arn): try: return await _make_ecs_request(logger, aws_endpoint, 'StopTask', { 'cluster': task_cluster_name, 'task': task_arn }) except HTTPError as exception: if b'task was not found' not in exception.response.body: raise async def _get_task_ip(logger, aws_endpoint, task_cluster_name, task_arn): described_task = await _describe_task(logger, aws_endpoint, task_cluster_name, task_arn) ip_address_attachements = [ attachment['value'] for attachment in described_task['attachments'][0]['details'] if attachment['name'] == 'privateIPv4Address' ] if described_task and 'attachments' in described_task and described_task['attachments'] else [] ip_address = ip_address_attachements[0] if ip_address_attachements else '' return ip_address async def _get_task_status(logger, aws_endpoint, task_cluster_name, task_arn): described_task = await _describe_task(logger, aws_endpoint, task_cluster_name, task_arn) status = described_task['lastStatus'] if described_task else '' return status async def _describe_task(logger, aws_endpoint, task_cluster_name, task_arn): described_tasks = await _make_ecs_request(logger, aws_endpoint, 'DescribeTasks', { 'cluster': task_cluster_name, 'tasks': [task_arn] }) # Very strangely, sometimes 'tasks' is returned, sometimes 'task' # Also, creating a task seems to be eventually consistent, so it might # not be present at all task = \ described_tasks['tasks'][0] if 'tasks' in described_tasks and described_tasks['tasks'] else \ described_tasks['task'] if 'task' in described_tasks else \ None return task async def _run_task(logger, aws_endpoint, task_role_arn, task_cluster_name, task_container_name, task_definition_arn, task_security_groups, task_subnets, task_command_and_args, task_env): return await _make_ecs_request(logger, aws_endpoint, 'RunTask', { 'cluster': task_cluster_name, 'taskDefinition': task_definition_arn, 'overrides': { 'taskRoleArn': task_role_arn, 'containerOverrides': [{ 'command': task_command_and_args, 'environment': [ { 'name': name, 'value': value, } for name, value in task_env.items() ], 'name': task_container_name, }], }, 'count': 1, 'launchType': 'FARGATE', 'networkConfiguration': { 'awsvpcConfiguration': { 'assignPublicIp': 'DISABLED', 'securityGroups': task_security_groups, 'subnets': task_subnets, }, }, }) async def _make_ecs_request(logger, aws_endpoint, target, dict_data): service = 'ecs' body = json.dumps(dict_data).encode('utf-8') credentials = await aws_endpoint['ecs_auth']() pre_auth_headers = { 'X-Amz-Target': f'AmazonEC2ContainerServiceV20141113.{target}', 'Content-Type': 'application/x-amz-json-1.1', **credentials.pre_auth_headers, } path = '/' query = {} headers = _aws_headers(service, credentials.access_key_id, credentials.secret_access_key, aws_endpoint['region'], aws_endpoint['ecs_host'], 'POST', path, query, pre_auth_headers, body) client = AsyncHTTPClient() url = f'https://{aws_endpoint['ecs_host']}{path}' request = HTTPRequest(url, method='POST', headers=headers, body=body) logger.debug('Making request (%s)', body) try: response = await client.fetch(request) except HTTPError as exception: logger.exception('HTTPError from ECS (%s)', exception.response.body) raise logger.debug('Request response (%s)', response.body) return json.loads(response.body) def _aws_headers(service, access_key_id, secret_access_key, region, host, method, path, query, pre_auth_headers, payload): algorithm = 'AWS4-HMAC-SHA256' now = datetime.datetime.utcnow() amzdate = now.strftime('%Y%m%dT%H%M%SZ') datestamp = now.strftime('%Y%m%d') credential_scope = f'{datestamp}/{region}/{service}/aws4_request' headers_lower = { header_key.lower().strip(): header_value.strip() for header_key, header_value in pre_auth_headers.items() } required_headers = ['host', 'x-amz-content-sha256', 'x-amz-date'] signed_header_keys = sorted([header_key for header_key in headers_lower.keys()] + required_headers) signed_headers = ';'.join(signed_header_keys) payload_hash = hashlib.sha256(payload).hexdigest() def signature(): def canonical_request(): header_values = { **headers_lower, 'host': host, 'x-amz-content-sha256': payload_hash, 'x-amz-date': amzdate, } canonical_uri = urllib.parse.quote(path, safe='/~') query_keys = sorted(query.keys()) canonical_querystring = '&'.join([ urllib.parse.quote(key, safe='~') + '=' + urllib.parse.quote(query[key], safe='~') for key in query_keys ]) canonical_headers = ''.join([ header_key + ':' + header_values[header_key] + '\n' for header_key in signed_header_keys ]) return f'{method}\n{canonical_uri}\n{canonical_querystring}\n' + \ f'{canonical_headers}\n{signed_headers}\n{payload_hash}' def sign(key, msg): return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest() string_to_sign = \ f'{algorithm}\n{amzdate}\n{credential_scope}\n' + \ hashlib.sha256(canonical_request().encode('utf-8')).hexdigest() date_key = sign(('AWS4' + secret_access_key).encode('utf-8'), datestamp) region_key = sign(date_key, region) service_key = sign(region_key, service) request_key = sign(service_key, 'aws4_request') return sign(request_key, string_to_sign).hex() return { **pre_auth_headers, 'x-amz-date': amzdate, 'x-amz-content-sha256': payload_hash, 'Authorization': ( f'{algorithm} Credential={access_key_id}/{credential_scope}, ' + f'SignedHeaders={signed_headers}, Signature=' + signature() ), } class AsyncIteratorBuffer: # The progress streaming endpoint may be requested multiple times, so each # call to `__aiter__` must return an iterator that starts from the first message class _Iterator: def __init__(self, parent): self.parent = parent self.cursor = 0 async def __anext__(self): future = self.parent.futures[self.cursor] self.cursor += 1 return await future def __init__(self): self.futures = [Future()] def __aiter__(self): return self._Iterator(self) def close(self): self.futures[-1].set_exception(StopAsyncIteration()) def write(self, item): self.futures[-1].set_result(item) self.futures.append(Future())
from collections import ( namedtuple, ) import datetime import hashlib import hmac import json import os import urllib from jupyterhub.spawner import ( Spawner, ) from tornado import ( gen, ) from tornado.concurrent import ( Future, ) from tornado.httpclient import ( AsyncHTTPClient, HTTPError, HTTPRequest, ) from traitlets.config.configurable import ( Configurable, ) from traitlets import ( Bool, Dict, Instance, Int, List, TraitType, Type, Unicode, default, ) AwsCreds = namedtuple('AwsCreds', [ 'access_key_id', 'secret_access_key', 'pre_auth_headers', ]) class Datetime(TraitType): klass = datetime.datetime default_value = datetime.datetime(1900, 1, 1) class FargateSpawnerAuthentication(Configurable): async def get_credentials(self): raise NotImplementedError() class FargateSpawnerSecretAccessKeyAuthentication(FargateSpawnerAuthentication): aws_access_key_id = Unicode(config=True) aws_secret_access_key = Unicode(config=True) pre_auth_headers = Dict() async def get_credentials(self): return AwsCreds( access_key_id=self.aws_access_key_id, secret_access_key=self.aws_secret_access_key, pre_auth_headers=self.pre_auth_headers, ) class FargateSpawnerECSRoleAuthentication(FargateSpawnerAuthentication): aws_access_key_id = Unicode() aws_secret_access_key = Unicode() pre_auth_headers = Dict() expiration = Datetime() async def get_credentials(self): now = datetime.datetime.now() if now > self.expiration: request = HTTPRequest('http://169.254.170.2' + os.environ['AWS_CONTAINER_CREDENTIALS_RELATIVE_URI'], method='GET') creds = json.loads((await AsyncHTTPClient().fetch(request)).body.decode('utf-8')) self.aws_access_key_id = creds['AccessKeyId'] self.aws_secret_access_key = creds['SecretAccessKey'] self.pre_auth_headers = { 'x-amz-security-token': creds['Token'], } self.expiration = datetime.datetime.strptime(creds['Expiration'], '%Y-%m-%dT%H:%M:%SZ') return AwsCreds( access_key_id=self.aws_access_key_id, secret_access_key=self.aws_secret_access_key, pre_auth_headers=self.pre_auth_headers, ) class FargateSpawner(Spawner): aws_region = Unicode(config=True) aws_ecs_host = Unicode(config=True) task_role_arn = Unicode(config=True) task_cluster_name = Unicode(config=True) task_container_name = Unicode(config=True) task_definition_arn = Unicode(config=True) task_security_groups = List(trait=Unicode, config=True) task_subnets = List(trait=Unicode, config=True) notebook_port = Int(config=True) notebook_scheme = Unicode(config=True) notebook_args = List(trait=Unicode, config=True) authentication_class = Type(FargateSpawnerAuthentication, config=True) authentication = Instance(FargateSpawnerAuthentication) @default('authentication') def _default_authentication(self): return self.authentication_class(parent=self) task_arn = Unicode('') # We mostly are able to call the AWS API to determine status. However, when we yield the # event loop to create the task, if there is a poll before the creation is complete, # we must behave as though we are running/starting, but we have no IDs to use with which # to check the task. calling_run_task = Bool(False) progress_buffer = None def load_state(self, state): ''' Misleading name: this "loads" the state onto self, to be used by other methods ''' super().load_state(state) # Called when first created: we might have no state from a previous invocation self.task_arn = state.get('task_arn', '') def get_state(self): ''' Misleading name: the return value of get_state is saved to the database in order to be able to restore after the hub went down ''' state = super().get_state() state['task_arn'] = self.task_arn return state async def poll(self): # Return values, as dictacted by the Jupyterhub framework: # 0 == not running, or not starting up, i.e. we need to call start # None == running, or not finished starting # 1, or anything else == error return \ None if self.calling_run_task else \ 0 if self.task_arn == '' else \ None if (await _get_task_status(self.log, self._aws_endpoint(), self.task_cluster_name, self.task_arn)) in ALLOWED_STATUSES else \ 1 async def start(self): self.log.debug('Starting spawner') task_port = self.notebook_port self.progress_buffer.write({'progress': 0.5, 'message': 'Starting server...'}) try: self.calling_run_task = True debug_args = ['--debug'] if self.debug else [] args = debug_args + ['--port=' + str(task_port)] + self.notebook_args run_response = await _run_task( self.log, self._aws_endpoint(), self.task_role_arn, self.task_cluster_name, self.task_container_name, self.task_definition_arn, self.task_security_groups, self.task_subnets, self.cmd + args, self.get_env()) task_arn = run_response['tasks'][0]['taskArn'] self.progress_buffer.write({'progress': 1}) finally: self.calling_run_task = False self.task_arn = task_arn max_polls = 50 num_polls = 0 task_ip = '' while task_ip == '': num_polls += 1 if num_polls >= max_polls: raise Exception('Task {} took too long to find IP address'.format(self.task_arn)) task_ip = await _get_task_ip(self.log, self._aws_endpoint(), self.task_cluster_name, task_arn) await gen.sleep(1) self.progress_buffer.write({'progress': 1 + num_polls / max_polls}) self.progress_buffer.write({'progress': 2}) max_polls = self.start_timeout num_polls = 0 status = '' while status != 'RUNNING': num_polls += 1 if num_polls >= max_polls: raise Exception('Task {} took too long to become running'.format(self.task_arn)) status = await _get_task_status(self.log, self._aws_endpoint(), self.task_cluster_name, task_arn) if status not in ALLOWED_STATUSES: raise Exception('Task {} is {}'.format(self.task_arn, status)) await gen.sleep(1) self.progress_buffer.write({'progress': 2 + num_polls / max_polls * 98}) self.progress_buffer.write({'progress': 100, 'message': 'Server started'}) await gen.sleep(1) self.progress_buffer.close() return f'{self.notebook_scheme}://{task_ip}:{task_port}' async def stop(self, now=False): if self.task_arn == '': return self.log.debug('Stopping task (%s)...', self.task_arn) await _ensure_stopped_task(self.log, self._aws_endpoint(), self.task_cluster_name, self.task_arn) self.log.debug('Stopped task (%s)... (done)', self.task_arn) def clear_state(self): super().clear_state() self.log.debug('Clearing state: (%s)', self.task_arn) self.task_arn = '' self.progress_buffer = AsyncIteratorBuffer() async def progress(self): async for progress_message in self.progress_buffer: yield progress_message def _aws_endpoint(self): return { 'region': self.aws_region, 'ecs_host': self.aws_ecs_host, 'ecs_auth': self.authentication.get_credentials, } ALLOWED_STATUSES = ('', 'PROVISIONING', 'PENDING', 'RUNNING') async def _ensure_stopped_task(logger, aws_endpoint, task_cluster_name, task_arn): try: return await _make_ecs_request(logger, aws_endpoint, 'StopTask', { 'cluster': task_cluster_name, 'task': task_arn }) except HTTPError as exception: if b'task was not found' not in exception.response.body: raise async def _get_task_ip(logger, aws_endpoint, task_cluster_name, task_arn): described_task = await _describe_task(logger, aws_endpoint, task_cluster_name, task_arn) ip_address_attachements = [ attachment['value'] for attachment in described_task['attachments'][0]['details'] if attachment['name'] == 'privateIPv4Address' ] if described_task and 'attachments' in described_task and described_task['attachments'] else [] ip_address = ip_address_attachements[0] if ip_address_attachements else '' return ip_address async def _get_task_status(logger, aws_endpoint, task_cluster_name, task_arn): described_task = await _describe_task(logger, aws_endpoint, task_cluster_name, task_arn) status = described_task['lastStatus'] if described_task else '' return status async def _describe_task(logger, aws_endpoint, task_cluster_name, task_arn): described_tasks = await _make_ecs_request(logger, aws_endpoint, 'DescribeTasks', { 'cluster': task_cluster_name, 'tasks': [task_arn] }) # Very strangely, sometimes 'tasks' is returned, sometimes 'task' # Also, creating a task seems to be eventually consistent, so it might # not be present at all task = \ described_tasks['tasks'][0] if 'tasks' in described_tasks and described_tasks['tasks'] else \ described_tasks['task'] if 'task' in described_tasks else \ None return task async def _run_task(logger, aws_endpoint, task_role_arn, task_cluster_name, task_container_name, task_definition_arn, task_security_groups, task_subnets, task_command_and_args, task_env): return await _make_ecs_request(logger, aws_endpoint, 'RunTask', { 'cluster': task_cluster_name, 'taskDefinition': task_definition_arn, 'overrides': { 'taskRoleArn': task_role_arn, 'containerOverrides': [{ 'command': task_command_and_args, 'environment': [ { 'name': name, 'value': value, } for name, value in task_env.items() ], 'name': task_container_name, }], }, 'count': 1, 'launchType': 'FARGATE', 'networkConfiguration': { 'awsvpcConfiguration': { 'assignPublicIp': 'DISABLED', 'securityGroups': task_security_groups, 'subnets': task_subnets, }, }, }) async def _make_ecs_request(logger, aws_endpoint, target, dict_data): service = 'ecs' body = json.dumps(dict_data).encode('utf-8') credentials = await aws_endpoint['ecs_auth']() pre_auth_headers = { 'X-Amz-Target': f'AmazonEC2ContainerServiceV20141113.{target}', 'Content-Type': 'application/x-amz-json-1.1', **credentials.pre_auth_headers, } path = '/' query = {} headers = _aws_headers(service, credentials.access_key_id, credentials.secret_access_key, aws_endpoint['region'], aws_endpoint['ecs_host'], 'POST', path, query, pre_auth_headers, body) client = AsyncHTTPClient() url = f'https://{aws_endpoint["ecs_host"]}{path}' request = HTTPRequest(url, method='POST', headers=headers, body=body) logger.debug('Making request (%s)', body) try: response = await client.fetch(request) except HTTPError as exception: logger.exception('HTTPError from ECS (%s)', exception.response.body) raise logger.debug('Request response (%s)', response.body) return json.loads(response.body) def _aws_headers(service, access_key_id, secret_access_key, region, host, method, path, query, pre_auth_headers, payload): algorithm = 'AWS4-HMAC-SHA256' now = datetime.datetime.utcnow() amzdate = now.strftime('%Y%m%dT%H%M%SZ') datestamp = now.strftime('%Y%m%d') credential_scope = f'{datestamp}/{region}/{service}/aws4_request' headers_lower = { header_key.lower().strip(): header_value.strip() for header_key, header_value in pre_auth_headers.items() } required_headers = ['host', 'x-amz-content-sha256', 'x-amz-date'] signed_header_keys = sorted([header_key for header_key in headers_lower.keys()] + required_headers) signed_headers = ';'.join(signed_header_keys) payload_hash = hashlib.sha256(payload).hexdigest() def signature(): def canonical_request(): header_values = { **headers_lower, 'host': host, 'x-amz-content-sha256': payload_hash, 'x-amz-date': amzdate, } canonical_uri = urllib.parse.quote(path, safe='/~') query_keys = sorted(query.keys()) canonical_querystring = '&'.join([ urllib.parse.quote(key, safe='~') + '=' + urllib.parse.quote(query[key], safe='~') for key in query_keys ]) canonical_headers = ''.join([ header_key + ':' + header_values[header_key] + '\n' for header_key in signed_header_keys ]) return f'{method}\n{canonical_uri}\n{canonical_querystring}\n' + \ f'{canonical_headers}\n{signed_headers}\n{payload_hash}' def sign(key, msg): return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest() string_to_sign = \ f'{algorithm}\n{amzdate}\n{credential_scope}\n' + \ hashlib.sha256(canonical_request().encode('utf-8')).hexdigest() date_key = sign(('AWS4' + secret_access_key).encode('utf-8'), datestamp) region_key = sign(date_key, region) service_key = sign(region_key, service) request_key = sign(service_key, 'aws4_request') return sign(request_key, string_to_sign).hex() return { **pre_auth_headers, 'x-amz-date': amzdate, 'x-amz-content-sha256': payload_hash, 'Authorization': ( f'{algorithm} Credential={access_key_id}/{credential_scope}, ' + f'SignedHeaders={signed_headers}, Signature=' + signature() ), } class AsyncIteratorBuffer: # The progress streaming endpoint may be requested multiple times, so each # call to `__aiter__` must return an iterator that starts from the first message class _Iterator: def __init__(self, parent): self.parent = parent self.cursor = 0 async def __anext__(self): future = self.parent.futures[self.cursor] self.cursor += 1 return await future def __init__(self): self.futures = [Future()] def __aiter__(self): return self._Iterator(self) def close(self): self.futures[-1].set_exception(StopAsyncIteration()) def write(self, item): self.futures[-1].set_result(item) self.futures.append(Future())
import argparse import json from bs4 import BeautifulSoup def format_answer(data): with open(args.data, "r") as file: data = file.readlines() soups = [BeautifulSoup(d, 'html.parser') for d in data] is_first = True doc_id = -1 sent_id = 0 for soup in soups: sent_id += 1 for gloss_id, mention in enumerate(soup.find_all('mention')): if mention["id"] == "0": entity_map = {} doc_id += 1 if is_first: print(f"#begin document ({mention["document_id"]}); ") is_first = False else: print("#end document") sent_id = 1 print(f"#begin document ({mention["document_id"]}); ") try: entity = mention['entity'] if entity in entity_map: entity = entity_map[entity] else: entity_map[entity] = len(entity_map) entity = entity_map[entity] print(f"test{sent_id} {doc_id} {gloss_id} {mention.text} ({entity})") except: print(f"test{sent_id} {doc_id} {gloss_id} {mention.text} -") print() print("#end document") def format_key(data): data = json.load(open(data, "r")) for i, (vid_id, vid_data) in enumerate(data.items()): print(f"#begin document ({vid_id}); ") entity_map = {} num_sents = len(vid_data["glosses"]) for sent_id, sent in enumerate(vid_data["glosses"]): for gloss_id, gloss in enumerate(sent): entity = gloss.get("entity") if entity is not None: if entity in entity_map: entity = entity_map[entity] else: entity_map[entity] = len(entity_map) entity = entity_map[entity] print(f"test{sent_id + 1} {i} {gloss_id} {gloss["Lexeme_Sign"]} ({entity})") else: print(f"test{sent_id + 1} {i} {gloss_id} {gloss["Lexeme_Sign"]} -") #if sent_id != num_sents -1: print() print("#end document") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--data", required=True) parser.add_argument("--key", default=False, action="store_true") args = parser.parse_args() if args.key: format_key(args.data) else: format_answer(args.data)
import argparse import json from bs4 import BeautifulSoup def format_answer(data): with open(args.data, "r") as file: data = file.readlines() soups = [BeautifulSoup(d, 'html.parser') for d in data] is_first = True doc_id = -1 sent_id = 0 for soup in soups: sent_id += 1 for gloss_id, mention in enumerate(soup.find_all('mention')): if mention["id"] == "0": entity_map = {} doc_id += 1 if is_first: print(f"#begin document ({mention['document_id']}); ") is_first = False else: print("#end document") sent_id = 1 print(f"#begin document ({mention['document_id']}); ") try: entity = mention['entity'] if entity in entity_map: entity = entity_map[entity] else: entity_map[entity] = len(entity_map) entity = entity_map[entity] print(f"test{sent_id} {doc_id} {gloss_id} {mention.text} ({entity})") except: print(f"test{sent_id} {doc_id} {gloss_id} {mention.text} -") print() print("#end document") def format_key(data): data = json.load(open(data, "r")) for i, (vid_id, vid_data) in enumerate(data.items()): print(f"#begin document ({vid_id}); ") entity_map = {} num_sents = len(vid_data["glosses"]) for sent_id, sent in enumerate(vid_data["glosses"]): for gloss_id, gloss in enumerate(sent): entity = gloss.get("entity") if entity is not None: if entity in entity_map: entity = entity_map[entity] else: entity_map[entity] = len(entity_map) entity = entity_map[entity] print(f"test{sent_id + 1} {i} {gloss_id} {gloss['Lexeme_Sign']} ({entity})") else: print(f"test{sent_id + 1} {i} {gloss_id} {gloss['Lexeme_Sign']} -") #if sent_id != num_sents -1: print() print("#end document") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--data", required=True) parser.add_argument("--key", default=False, action="store_true") args = parser.parse_args() if args.key: format_key(args.data) else: format_answer(args.data)
#!/usr/bin/env python3 import os import pathlib import pprint import sys import traceback import m2r import msgpack from jinja2 import Template from tqdm import tqdm DISABLE_TQDM = "CI" in os.environ REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent LOCAL_CACHE_PATH = pathlib.Path( os.environ.get("LOCAL_CACHE_PATH") or REPO_ROOT.joinpath(".cache") ).resolve() if not LOCAL_CACHE_PATH.is_dir(): LOCAL_CACHE_PATH.mkdir(0o755) PACKAGE_INFO_CACHE = LOCAL_CACHE_PATH / "packages-info" if not PACKAGE_INFO_CACHE.is_dir(): PACKAGE_INFO_CACHE.mkdir(0o755) RESULTS_DIR = REPO_ROOT / "results" print(f"Local Cache Path: {LOCAL_CACHE_PATH}", file=sys.stderr, flush=True) print(f"Results Path: {RESULTS_DIR}", file=sys.stderr, flush=True) if sys.version_info < (3, 7): print("This script is meant to only run on Py3.7+", file=sys.stderr, flush=True) def set_progress_description(progress, message): progress.set_description(f"{message: <60}") def collect_extensions_info(): extensions = {} for path in sorted(PACKAGE_INFO_CACHE.glob("*.msgpack")): if path.stem == "salt-extensions": continue extension_data = msgpack.unpackb(path.read_bytes()) extension = extension_data["info"]["name"] description = extension_data["info"]["description"].rstrip() if "markdown" in extension_data["info"]["description_content_type"]: description = m2r.convert(description) summary = extension_data["info"]["summary"].strip() extensions[extension] = { "summary": summary, "description": description, } return extensions def collect_extensions_results(): results = {} results["osnames"] = [] results["python_versions"] = [] for extension in sorted(RESULTS_DIR.iterdir()): if not extension.is_dir(): continue results[extension.name] = {} for salt_version in sorted(extension.iterdir()): results[extension.name][salt_version.name] = {} for ospath in sorted(salt_version.iterdir()): osname = ospath.name.replace("-latest", "") if osname not in results["osnames"]: results["osnames"].append(osname) results[extension.name][salt_version.name][osname] = {} for python_version in sorted(ospath.iterdir()): python_version_name = python_version.name if python_version_name not in results["python_versions"]: results["python_versions"].append(python_version_name) url = python_version.joinpath("url").read_text().strip() status = python_version.joinpath("status").read_text().strip() results[extension.name][salt_version.name][osname][ python_version_name ] = {"url": url, "status": status} return results def main(): results = collect_extensions_results() extensions = collect_extensions_info() sphinx_results_dir = REPO_ROOT / "docs" / "results" if not sphinx_results_dir.is_dir(): sphinx_results_dir.mkdir(0o0755) docs_dir = REPO_ROOT / "docs" table_template = REPO_ROOT / "templates" / "results.html.j2" sphinx_index = REPO_ROOT / "docs" / "index.rst" progress = tqdm( total=len(results), unit="pkg", unit_scale=True, desc=f"{" " * 60} :", disable=DISABLE_TQDM, ) with progress: progress.write(f"Collected Extension Test Results:\n{pprint.pformat(results)}") progress.write(f"Collected Extensions:\n{pprint.pformat(extensions)}") contents = f"{sphinx_index.read_text()}\n" for extension in results: if extension in ("osnames", "python_versions"): progress.update() continue set_progress_description(progress, f"Processing {extension}") if extension not in extensions: progress.write( f"The extension {extension!r} cannot be found in the extensions listing" ) progress.update() continue title = extension header = "-" * len(title) summary = extensions[extension]["summary"] description = extensions[extension]["description"] context = dict( results=results[extension], python_versions=results["python_versions"], osnames=results["osnames"], ) extension_index = docs_dir / f"{extension}.rst" table_contents = Template(table_template.read_text()).render(**context) html_table_path = sphinx_results_dir / f"{extension}.html" html_table_path.write_text(table_contents) html_table_rel_path = html_table_path.relative_to(docs_dir) contents += ( f"{title}\n{header}\n{summary} (:ref:`more info<{extension}>`)\n\n" ) contents += f".. raw:: html\n :file: {html_table_rel_path}\n\n" extension_contents = ( ":orphan:\n\n" f".. _{extension}:\n\n{title}\n{header.replace("-", "=")}\n\n" ) extension_contents += "Compatibility\n-------------\n" extension_contents += f".. raw:: html\n :file: {html_table_rel_path}\n\n" extension_contents += f"Description\n-----------\n{description}\n" extension_index.write_text(extension_contents) progress.update() set_progress_description(progress, "Writing extenstions index") contents += ".. |date| date::\n\nLast Updated on |date|" sphinx_index.write_text(f"{contents}\n") progress.write("Complete") if __name__ == "__main__": exitcode = 0 try: main() except Exception: exitcode = 1 traceback.print_exc() finally: sys.exit(exitcode)
#!/usr/bin/env python3 import os import pathlib import pprint import sys import traceback import m2r import msgpack from jinja2 import Template from tqdm import tqdm DISABLE_TQDM = "CI" in os.environ REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent LOCAL_CACHE_PATH = pathlib.Path( os.environ.get("LOCAL_CACHE_PATH") or REPO_ROOT.joinpath(".cache") ).resolve() if not LOCAL_CACHE_PATH.is_dir(): LOCAL_CACHE_PATH.mkdir(0o755) PACKAGE_INFO_CACHE = LOCAL_CACHE_PATH / "packages-info" if not PACKAGE_INFO_CACHE.is_dir(): PACKAGE_INFO_CACHE.mkdir(0o755) RESULTS_DIR = REPO_ROOT / "results" print(f"Local Cache Path: {LOCAL_CACHE_PATH}", file=sys.stderr, flush=True) print(f"Results Path: {RESULTS_DIR}", file=sys.stderr, flush=True) if sys.version_info < (3, 7): print("This script is meant to only run on Py3.7+", file=sys.stderr, flush=True) def set_progress_description(progress, message): progress.set_description(f"{message: <60}") def collect_extensions_info(): extensions = {} for path in sorted(PACKAGE_INFO_CACHE.glob("*.msgpack")): if path.stem == "salt-extensions": continue extension_data = msgpack.unpackb(path.read_bytes()) extension = extension_data["info"]["name"] description = extension_data["info"]["description"].rstrip() if "markdown" in extension_data["info"]["description_content_type"]: description = m2r.convert(description) summary = extension_data["info"]["summary"].strip() extensions[extension] = { "summary": summary, "description": description, } return extensions def collect_extensions_results(): results = {} results["osnames"] = [] results["python_versions"] = [] for extension in sorted(RESULTS_DIR.iterdir()): if not extension.is_dir(): continue results[extension.name] = {} for salt_version in sorted(extension.iterdir()): results[extension.name][salt_version.name] = {} for ospath in sorted(salt_version.iterdir()): osname = ospath.name.replace("-latest", "") if osname not in results["osnames"]: results["osnames"].append(osname) results[extension.name][salt_version.name][osname] = {} for python_version in sorted(ospath.iterdir()): python_version_name = python_version.name if python_version_name not in results["python_versions"]: results["python_versions"].append(python_version_name) url = python_version.joinpath("url").read_text().strip() status = python_version.joinpath("status").read_text().strip() results[extension.name][salt_version.name][osname][ python_version_name ] = {"url": url, "status": status} return results def main(): results = collect_extensions_results() extensions = collect_extensions_info() sphinx_results_dir = REPO_ROOT / "docs" / "results" if not sphinx_results_dir.is_dir(): sphinx_results_dir.mkdir(0o0755) docs_dir = REPO_ROOT / "docs" table_template = REPO_ROOT / "templates" / "results.html.j2" sphinx_index = REPO_ROOT / "docs" / "index.rst" progress = tqdm( total=len(results), unit="pkg", unit_scale=True, desc=f"{' ' * 60} :", disable=DISABLE_TQDM, ) with progress: progress.write(f"Collected Extension Test Results:\n{pprint.pformat(results)}") progress.write(f"Collected Extensions:\n{pprint.pformat(extensions)}") contents = f"{sphinx_index.read_text()}\n" for extension in results: if extension in ("osnames", "python_versions"): progress.update() continue set_progress_description(progress, f"Processing {extension}") if extension not in extensions: progress.write( f"The extension {extension!r} cannot be found in the extensions listing" ) progress.update() continue title = extension header = "-" * len(title) summary = extensions[extension]["summary"] description = extensions[extension]["description"] context = dict( results=results[extension], python_versions=results["python_versions"], osnames=results["osnames"], ) extension_index = docs_dir / f"{extension}.rst" table_contents = Template(table_template.read_text()).render(**context) html_table_path = sphinx_results_dir / f"{extension}.html" html_table_path.write_text(table_contents) html_table_rel_path = html_table_path.relative_to(docs_dir) contents += ( f"{title}\n{header}\n{summary} (:ref:`more info<{extension}>`)\n\n" ) contents += f".. raw:: html\n :file: {html_table_rel_path}\n\n" extension_contents = ( ":orphan:\n\n" f".. _{extension}:\n\n{title}\n{header.replace('-', '=')}\n\n" ) extension_contents += "Compatibility\n-------------\n" extension_contents += f".. raw:: html\n :file: {html_table_rel_path}\n\n" extension_contents += f"Description\n-----------\n{description}\n" extension_index.write_text(extension_contents) progress.update() set_progress_description(progress, "Writing extenstions index") contents += ".. |date| date::\n\nLast Updated on |date|" sphinx_index.write_text(f"{contents}\n") progress.write("Complete") if __name__ == "__main__": exitcode = 0 try: main() except Exception: exitcode = 1 traceback.print_exc() finally: sys.exit(exitcode)
import logging from asyncio import sleep as asleep # For waiting asynchronously. from os import listdir # To check files on disk. from asyncpg import IntegrityConstraintViolationError # To check for database conflicts. from discord import Embed, Activity, ActivityType # For bot status from discord.ext import commands # For implementation of bot commands. import travus_bot_base as tbb # TBB functions and classes. from travus_bot_base import clean # Shorthand for cleaning output. def setup(bot: tbb.TravusBotBase): """Setup function ran when module is loaded.""" bot.add_cog(CoreFunctionalityCog(bot)) # Add cog and command help info. bot.add_command_help(CoreFunctionalityCog.botconfig_prefix, "Core", None, ["$", "bot!", "bot ?", "remove"]) bot.add_command_help(CoreFunctionalityCog.botconfig_deletemessages, "Core", None, ["enable", "y", "disable", "n"]) bot.add_command_help(CoreFunctionalityCog.module_list, "Core", {"perms": ["Administrator"]}, [""]) bot.add_command_help(CoreFunctionalityCog.module_load, "Core", {"perms": ["Administrator"]}, ["fun", "economy"]) bot.add_command_help(CoreFunctionalityCog.module_unload, "Core", {"perms": ["Administrator"]}, ["fun", "economy"]) bot.add_command_help(CoreFunctionalityCog.module_reload, "Core", {"perms": ["Administrator"]}, ["fun", "economy"]) bot.add_command_help(CoreFunctionalityCog.default, "Core", None, ["list", "add", "remove"]) bot.add_command_help(CoreFunctionalityCog.default_list, "Core", None, [""]) bot.add_command_help(CoreFunctionalityCog.default_add, "Core", None, ["fun", "economy"]) bot.add_command_help(CoreFunctionalityCog.default_remove, "Core", None, ["fun", "economy"]) bot.add_command_help(CoreFunctionalityCog.command_enable, "Core", {"perms": ["Administrator"]}, ["balance", "pay"]) bot.add_command_help(CoreFunctionalityCog.command_disable, "Core", {"perms": ["Administrator"]}, ["balance", "pay"]) bot.add_command_help(CoreFunctionalityCog.command_show, "Core", {"perms": ["Administrator"]}, ["module", "balance"]) bot.add_command_help(CoreFunctionalityCog.command_hide, "Core", {"perms": ["Administrator"]}, ["module", "balance"]) bot.add_command_help(CoreFunctionalityCog.about, "Core", None, ["", "fun"]) bot.add_command_help(CoreFunctionalityCog.usage, "Core", None, ["", "dev"]) bot.add_command_help(CoreFunctionalityCog.config, "Core", {"perms": ["Administrator"]}, ["get", "set", "unset"]) bot.add_command_help(CoreFunctionalityCog.config_get, "Core", {"perms": ["Administrator"]}, ["alert_channel"]) bot.add_command_help(CoreFunctionalityCog.config_unset, "Core", {"perms": ["Administrator"]}, ["alert_channel"]) bot.add_command_help(CoreFunctionalityCog.shutdown, "Core", None, ["", "1h", "1h30m", "10m-30s", "2m30s"]) bot.add_command_help( CoreFunctionalityCog.botconfig, "Core", None, ["prefix", "deletemessages", "description", "credits"] ) bot.add_command_help( CoreFunctionalityCog.botconfig_description, "Core", None, ["remove", "This is a sample description."] ) bot.add_command_help( CoreFunctionalityCog.module, "Core", {"perms": ["Administrator"]}, ["list", "load", "unload", "reload"] ) bot.add_command_help( CoreFunctionalityCog.command, "Core", {"perms": ["Administrator"]}, ["enable", "disable", "show", "hide"] ) bot.add_command_help( CoreFunctionalityCog.config_set, "Core", {"perms": ["Administrator"]}, ["alert_channel 353246496952418305"] ) bot.add_command_help( CoreFunctionalityCog.botconfig_credits, "Core", None, ["remove", "`\n```\n[Person](URL):\n\tBot Profile Image\n``"], ) def teardown(bot: tbb.TravusBotBase): """Teardown function ran when module is unloaded.""" bot.remove_cog("CoreFunctionalityCog") # Remove cog and command help info. bot.remove_command_help(CoreFunctionalityCog) class CoreFunctionalityCog(commands.Cog): """Cog that holds default functionality.""" def __init__(self, bot: tbb.TravusBotBase): """Initialization function loading bot object for cog.""" self.bot = bot self.log = logging.getLogger("core_commands") self.log.setLevel(logging.INFO) async def _module_operation(self, ctx: commands.Context, operation: str, mod: str): """To avoid code duplication in the except blocks all module command functionality is grouped together.""" async def load(): """Contains the logic for loading a module.""" if f"{mod}.py" in listdir("modules"): self.bot.load_extension(f"modules.{mod}") await self.bot.update_command_states() await ctx.send(f"Module `{mod_name}` successfully loaded.") self.log.info(f"{ctx.author.id}: loaded '{mod}' module.") else: await ctx.send(f"No `{mod_name}` module was found.") async def unload(): """Contains the logic for unloading a module.""" self.bot.unload_extension(f"modules.{mod}") await ctx.send(f"Module `{mod_name}` successfully unloaded.") self.log.info(f"{ctx.author.id}: unloaded '{mod}' module.") async def reload(): """Contains the logic for reloading a module.""" if f"{mod}.py" in listdir("modules"): self.bot.reload_extension(f"modules.{mod}") await self.bot.update_command_states() await ctx.send(f"Module `{mod_name}` successfully reloaded.") self.log.info(f"{ctx.author.id}: reloaded '{mod}' module.") else: if mod in self.bot.modules: await ctx.send(f"The `{mod_name}` module file is no longer found on disk. Reload canceled.") else: await ctx.send(f"No `{mod_name}` module was found.") old_help = dict(self.bot.help) # Save old help and module info in we need to roll back. old_modules = dict(self.bot.modules) self.bot.extension_ctx = ctx # Save context in case loaded module has use for it. mod_name = clean(ctx, mod, False, True) try: if operation == "load": await load() elif operation == "unload": await unload() elif operation == "reload": await reload() except commands.ExtensionAlreadyLoaded: # If module was already loaded. await ctx.send(f"The `{mod_name}` module was already loaded.") except commands.ExtensionNotLoaded: # If module wasn't loaded to begin with. await ctx.send(f"No `{mod_name}` module is loaded.") except commands.ExtensionFailed as e: self.bot.help = old_help self.bot.modules = old_modules if isinstance(e.original, tbb.DependencyError): missing_deps = [f"`{clean(ctx, elem, False, True)}`" for elem in e.original.missing_dependencies] await ctx.send(f"Module `{mod_name}` requires these missing dependencies: {", ".join(missing_deps)}") else: await ctx.send( "**Error! Something went really wrong! Contact module maintainer.**\nError logged to console and " "stored in module error command." ) self.log.error(f"{ctx.author.id}: tried loading '{mod}' module, and it failed:\n\n{str(e)}") self.bot.last_module_error = ( f"The `{clean(ctx, mod, False)}` module failed while loading. The error was:\n\n{clean(ctx, str(e))}" ) except Exception as e: self.bot.help = old_help self.bot.modules = old_modules await ctx.send( "**Error! Something went really wrong! Contact module maintainer.**\nError logged to console and " "stored in module error command." ) if isinstance(e, commands.ExtensionNotFound): # Clarify error further in case it was an import error. e = e.__cause__ self.log.error(f"{ctx.author.id}: tried loading '{mod}' module, and it failed:\n\n{str(e)}") self.bot.last_module_error = ( f"The `{clean(ctx, mod, False)}` module failed while loading. The error was:\n\n{clean(ctx, str(e))}" ) finally: # Reset context as loading has concluded. self.bot.extension_ctx = None @commands.is_owner() @commands.group(invoke_without_command=True, name="botconfig", usage="<prefix/deletemessages/description/credits>") async def botconfig(self, ctx: commands.Context): """This command sets the bot's prefix, command trigger deletion behaviour, description and additional credits section. Fore more information check the help entry of one of these subcommands; `prefix`, `deletemessages`, `description`, `credits`.""" raise commands.BadArgument(f"No subcommand given for {ctx.command.name}.") @commands.is_owner() @botconfig.command(name="prefix", usage="<NEW PREFIX/remove>") async def botconfig_prefix(self, ctx: commands.Context, *, new_prefix: str): """This command changes the bot prefix. The default prefix is `!`. Prefixes can be everything from symbols to words or a combination of the two, and can even include spaces, though they cannot start or end with spaces since Discord removes empty space at the start and end of messages. The prefix is saved across reboots. Setting the prefix to `remove` will remove the prefix. The bot will always listen to pings as if they were a prefix, regardless of if there is another prefix set or not. Maximum prefix length is 20.""" if len(new_prefix) > 20: await ctx.send("The maximum prefix length is 20.") return self.bot.prefix = new_prefix if new_prefix.lower() != "remove" else None # If 'remove', prefix is set to None. activity = Activity( type=ActivityType.listening, name=f"prefix: {new_prefix}" if new_prefix.lower() != "remove" else "pings only", ) await self.bot.change_presence(activity=activity) # Set status. async with self.bot.db.acquire() as conn: await conn.execute( "UPDATE settings SET value = $1 WHERE key = 'prefix'", new_prefix if new_prefix.lower() != "remove" else "", ) # Empty string is no prefix. if new_prefix.lower() != "remove": # Give feedback to user. await ctx.send(f"The bot prefix has successfully been changed to `{new_prefix}`.") else: await ctx.send("The bot is now only listens to pings.") @commands.is_owner() @botconfig.command( name="deletemessages", aliases=["deletemsgs", "deletecommands", "deletecmds", "delmessages", "delmsgs", "delcommands", "delcmds"], usage="<enable/disable>", ) async def botconfig_deletemessages(self, ctx: commands.Context, operation: str): """This command sets the behaviour for deletion of command triggers. If this is enabled then messages that trigger commands will be deleted. Is this is disabled then the bot will not delete messages that trigger commands. Per default this is enabled. This setting is saved across restarts.""" op = operation.lower() async with self.bot.db.acquire() as conn: if op in ["enable", "true", "on", "yes", "y", "+", "1"]: # Values interpreted as true. if self.bot.delete_messages: await ctx.send("The bot is already deleting command triggers.") return await conn.execute("UPDATE settings SET value = '1' WHERE key = 'delete_messages'") self.bot.delete_messages = 1 await ctx.send("Now deleting command triggers.") elif op in ["disable", "false", "off", "no", "n", "-", "0"]: # Values interpreted as false. if not self.bot.delete_messages: await ctx.send("The bot is already not deleting command triggers.") return await conn.execute("UPDATE settings SET value = '0' WHERE key = 'delete_messages'") self.bot.delete_messages = 0 await ctx.send("No longer deleting command triggers.") else: raise commands.BadArgument("Operation not supported.") @commands.is_owner() @botconfig.command(name="description", aliases=["desc"], usage="<DESCRIPTION/remove>") async def botconfig_description(self, ctx: commands.Context, *, description: str): """This command sets the bot description that is used by the about command. The description can technically be up to 4096 characters long, keep however in mind that Discord messages have a maximum length of 4000 characters (2000 without Nitro). If `remove` is sent along then the description will be removed. The special keyword `_prefix_` wil be replaced by the current bot prefix.""" async with self.bot.db.acquire() as conn: if description.lower() == "remove": await conn.execute("UPDATE settings SET value = '' WHERE key = 'bot_description'") self.bot.modules[ self.bot.user.name.lower() ].description = "No description for the bot found. Set description with `botconfig` command." await ctx.send("The description has been removed.") else: await conn.execute("UPDATE settings SET value = $1 WHERE key = 'bot_description'", description) self.bot.modules[self.bot.user.name.lower()].description = description await ctx.send("The description has been set.") @commands.is_owner() @botconfig.command(name="credits", usage="<CREDITS/remove> *OBS: See help command entry!*") async def botconfig_credits(self, ctx: commands.Context, *, description: str): """This command sets the additional credits section of the about command. The additional credits section can be at most 1024 characters long, and supports both new lines, indents and embedded links. Indents of 5 spaces are recommended. Embedded links should look like so; `[displayed text](URL)`. The credits should be passed inside a multi-line code block in order for new lines and tabs to work correctly. If `remove` is passed instead then the additional credits section is removed.""" description = description.strip() async with self.bot.db.acquire() as conn: if description.lower() == "remove": await conn.execute("UPDATE settings SET value = '' WHERE key = 'additional_credits'") self.bot.modules[self.bot.user.name.lower()].credits = None await ctx.send("The additional credits section has been removed.") return if description.count("```") != 2 or description[:3] != "```" or description[-3:] != "```": await ctx.send("Credits must be fully encased in a multi-line code block.") return description = description.strip("```").strip() # Remove code block. description = description.replace(" ", "\u202F") # Prevent whitespace from disappearing. if len(description) > 1024: await ctx.send("Credits too long. Credits can be at most 1024 characters long.") return await conn.execute("UPDATE settings SET value = $1 WHERE key = 'additional_credits'", description) self.bot.modules[self.bot.user.name.lower()].credits = description await ctx.send("The additional credits section has been set.") @commands.has_permissions(administrator=True) @commands.group( invoke_without_command=True, name="module", aliases=["modules"], usage="<list/load/unload/reload/error>" ) async def module(self, ctx: commands.Context): """This command can load, unload, reload and list available modules. It can also show any errors that occur during the loading process. Modules contain added functionality, such as commands. The intended purpose for modules is to extend the bot's functionality in semi-independent packages so that parts of the bot's functionality can be removed or restarted without affecting the rest of the bot's functionality. See the help text for the subcommands for more info.""" raise commands.BadArgument(f"No subcommand given for {ctx.command.name}.") @commands.has_permissions(administrator=True) @module.command(name="list") async def module_list(self, ctx: commands.Context): """This command lists all currently loaded and available modules. For the bot to find new modules they need to be placed inside the modules folder inside the bot directory. Modules listed by this command can be loaded, unloaded and reloaded by the respective commands for this. See help text for `module load`, `module unload` and `module reload` for more info on this.""" loaded_modules = [ f"`{clean(ctx, mod.replace("modules.", ""), False, True)}`, " for mod in self.bot.extensions if mod != "core_commands" ] or ["None, "] available_modules = [ f"`{clean(ctx, mod, False, True).replace(".py", "")}`, " for mod in listdir("modules") if mod.endswith(".py") ] available_modules = [mod for mod in available_modules if mod not in loaded_modules] or ["None, "] loaded_modules[-1] = loaded_modules[-1][:-2] available_modules[-1] = available_modules[-1][:-2] paginator = commands.Paginator(prefix="", suffix="", linesep="") paginator.add_line("Loaded modules: ") for mod in loaded_modules: paginator.add_line(mod) paginator.add_line("\nAvailable Modules: ") for mod in available_modules: paginator.add_line(mod) for page in paginator.pages: await ctx.send(page) @commands.has_permissions(administrator=True) @module.command(name="load", aliases=["l"], usage="<MODULE NAME>") async def module_load(self, ctx: commands.Context, *, mod: str): """This command loads modules. Modules should be located inside the module folder in the bot directory. The `module list` command can be used to show all modules available for loading. Once a module is loaded the functionality defined in the module file will be added to the bot. If an error is encountered during the loading process the user will be informed and the `module error` command can then be used to see the error details. The module will then not be loaded. If you want modules to stay loaded after restarts, see the `default` command.""" await self._module_operation(ctx, "load", mod) @commands.has_permissions(administrator=True) @module.command(name="unload", aliases=["ul"], usage="<MODULE NAME>") async def module_unload(self, ctx: commands.Context, *, mod: str): """This command unloads modules. When a loaded module is unloaded it's functionality will be removed. You can use the `module list` command to see all currently loaded modules. This will not prevent default modules from being loaded when the bot starts. See the `default` command for removing modules starting with the bot.""" await self._module_operation(ctx, "unload", mod) @commands.has_permissions(administrator=True) @module.command(name="reload", aliases=["rl"], usage="<MODULE NAME>") async def module_reload(self, ctx: commands.Context, *, mod: str): """This command reloads a module that is currently loaded. This will unload and load the module in one command. If the module is no longer present or the loading process encounters an error the module will not be reloaded and the functionality from before the reload will be retained and the user informed, the `module error` command can then be used to see the error details. You can use the module list command to see all currently loaded modules.""" await self._module_operation(ctx, "reload", mod) @commands.has_permissions(administrator=True) @module.command(name="error") async def module_error(self, ctx: commands.Context): """This command will show the last error that was encountered during the module load or reloading process. This information will also be logged to the console when the error first is encountered. This command retains this information until another error replaces it, or the bot shuts down.""" if self.bot.last_module_error: await ctx.send(self.bot.last_module_error[:1999]) else: await ctx.send("There have not been any errors loading modules since the last restart.") @commands.is_owner() @commands.group(invoke_without_command=True, name="default", aliases=["defaults"], usage="<add/remove/list>") async def default(self, ctx: commands.Context): """This command is used to add, remove or list default modules. Modules contain added functionality, such as commands. Default modules are loaded automatically when the bot starts and as such any functionality in them will be available as soon as the bot is online. For more info see the help text of the subcommands.""" raise commands.BadArgument(f"No subcommand given for {ctx.command.name}.") @commands.is_owner() @default.command(name="list") async def default_list(self, ctx: commands.Context): """This command lists all current default modules. For more information on modules see the help text for the `module` command. All modules in this list start as soon as the bot is launched. For a list of all available or loaded modules see the `module list` command.""" async with self.bot.db.acquire() as conn: result = await conn.fetch("SELECT module FROM default_modules") result = [f"`{clean(ctx, val["module"], False, True)}`, " for val in result] or ["None, "] result[-1] = result[-1][:-2] paginator = commands.Paginator(prefix="", suffix="", linesep="") paginator.add_line("Default modules: ") for mod in result: paginator.add_line(mod) for page in paginator.pages: await ctx.send(page) @commands.is_owner() @default.command(name="add", usage="<MODULE NAME>") async def default_add(self, ctx: commands.Context, *, mod: str): """This command adds a module to the list of default modules. Modules in this list are loaded automatically once the bot starts. This command does not load modules if they are not already loaded until the bot is started the next time. For that, see the `module load` command. For a list of existing default modules, see the `default list` command. For more info on modules see the help text for the `module` command.""" if f"{mod}.py" in listdir("modules"): # Check if such a module even exists. try: async with self.bot.db.acquire() as conn: await conn.execute("INSERT INTO default_modules VALUES ($1)", mod) await ctx.send(f"The `{clean(ctx, mod, False, True)}` module is now a default module.") except IntegrityConstraintViolationError: await ctx.send(f"The `{clean(ctx, mod, False, True)}` module is already a default module.") else: await ctx.send(f"No `{clean(ctx, mod, False, True)}` module was found.") @commands.is_owner() @default.command(name="remove", usage="<MODULE NAME>") async def default_remove(self, ctx: commands.Context, *, mod: str): """This command removes a module from the list of default modules. Once removed from this list the module will no longer automatically be loaded when the bot starts. This command will not unload commands that are already loaded. For that, see the `module unload` command. For a list of existing default modules, see the `default list` command. For more info on modules see the help text for the `module` command.""" async with self.bot.db.acquire() as conn: result = await conn.fetchval("SELECT module FROM default_modules WHERE module = $1", mod) if result: await conn.execute("DELETE FROM default_modules WHERE module = $1", mod) await ctx.send(f"Removed `{clean(ctx, mod, False, True)}` module from default modules.") else: await ctx.send(f"No `{clean(ctx, mod, False, True)}` module in default modules.") @commands.has_permissions(administrator=True) @commands.group( invoke_without_command=True, name="command", aliases=["commands"], usage="<enable/disable/show/hide>" ) async def command(self, ctx: commands.Context): """This command disables, enables, hides and shows other commands. Hiding commands means they don't show up in the overall help command list. Disabling a command means it can't be used. Disabled commands also do not show up in the overall help command list and the specific help text for the command will not be viewable. Core commands cannot be disabled. These settings are saved across restarts.""" raise commands.BadArgument(f"No subcommand given for {ctx.command.name}.") async def _command_get_state(self, command: commands.Command) -> int: """Helper function for command command that gets the state of the command.""" async with self.bot.db.acquire() as conn: cog_com_name = f"{command.cog.__class__.__name__ + "." if command.cog else ""}{command.name}" response = await conn.fetchval("SELECT state FROM command_states WHERE command = $1", cog_com_name) if response is None: await conn.execute("INSERT INTO command_states VALUES ($1, $2)", cog_com_name, 0) response = 0 return response async def _command_set_state(self, command: commands.Command, state: int): """Helper function for command command that sets the state of the command.""" async with self.bot.db.acquire() as conn: await conn.execute( "UPDATE command_states SET state = $1 WHERE command = $2", state, f"{command.cog.__class__.__name__ + "." if command.cog else ""}{command.name}", ) @commands.has_permissions(administrator=True) @command.command(name="enable", usage="<COMMAND NAME>") async def command_enable(self, ctx: commands.Context, *, command_name: str): """This command enables commands which have previously been disabled. This will allow them to be used again. It will also add the command back into the list of commands shown by the help command and re-enable the viewing of it's help text given the command has help text and it has not otherwise been hidden.""" if command_name in self.bot.all_commands.keys(): # Check if command exists and get it's state. state = await self._command_get_state(self.bot.all_commands[command_name]) if self.bot.all_commands[command_name].enabled: # If command is already enabled, report back. await ctx.send(f"The `{clean(ctx, command_name)}` command is already enabled.") else: self.bot.all_commands[command_name].enabled = True await self._command_set_state(self.bot.all_commands[command_name], 0 if state == 2 else 1) await ctx.send(f"The `{clean(ctx, command_name)}` command is now enabled.") else: await ctx.send(f"No `{clean(ctx, command_name)}` command found.") @commands.has_permissions(administrator=True) @command.command(name="disable", usage="<COMMAND NAME>") async def command_disable(self, ctx: commands.Context, *, command_name: str): """This command can disable other commands. Disabled commands cannot be used and are removed from the list of commands shown by the help command. The command's help text will also not be viewable. Core commands cannot be disabled. Disabled commands can be re-enabled with the `command enable` command.""" if command_name in self.bot.all_commands.keys(): # Check if command exists and get it's state. state = await self._command_get_state(self.bot.all_commands[command_name]) if command_name in self.bot.help.keys() and self.bot.help[command_name].category.lower() == "core": await ctx.send("Core commands cannot be disabled.") else: if not self.bot.all_commands[command_name].enabled: # Check if the command is already disabled. await ctx.send(f"The `{clean(ctx, command_name)}` command is already disabled.") else: self.bot.all_commands[command_name].enabled = False await self._command_set_state(self.bot.all_commands[command_name], 2 if state == 0 else 3) await ctx.send(f"The `{clean(ctx, command_name)}` command is now disabled.") else: await ctx.send(f"No `{clean(ctx, command_name)}` command found.") @commands.has_permissions(administrator=True) @command.command(name="show", usage="<COMMAND NAME>") async def command_show(self, ctx: commands.Context, *, command_name: str): """This command will show commands which have previously been hidden, reversing the hiding of the command. This will add the command back into the list of commands shown by the help command. This will not re-enable the command if it has been disabled. Showing disabled commands alone will not be enough to re-add them to the help list since disabling them also hides them from the help list. See the `command enable` command to re-enable disabled commands.""" if command_name in self.bot.all_commands.keys(): # Check if command exists and get it's state. state = await self._command_get_state(self.bot.all_commands[command_name]) if not self.bot.all_commands[command_name].hidden: # Check if command i already visible. await ctx.send(f"The `{clean(ctx, command_name)}` command is already shown.") else: self.bot.all_commands[command_name].hidden = False await self._command_set_state(self.bot.all_commands[command_name], 0 if state == 1 else 2) await ctx.send(f"The `{clean(ctx, command_name)}` command is now shown.") else: await ctx.send(f"No `{clean(ctx, command_name)}` command found.") @commands.has_permissions(administrator=True) @command.command(name="hide", usage="<COMMAND NAME>") async def command_hide(self, ctx: commands.Context, *, command_name: str): """This command will hide commands from the list of commands shown by the help command. It will not disable the viewing of the help text for the command if someone already knows it's name. Commands who have been hidden can be un-hidden with the `command show` command.""" if command_name in self.bot.all_commands.keys(): # Check if command exists and get it's state. state = await self._command_get_state(self.bot.all_commands[command_name]) if self.bot.all_commands[command_name].hidden: # Check if command is already hidden. await ctx.send(f"The `{clean(ctx, command_name)}` command is already hidden.") else: self.bot.all_commands[command_name].hidden = True await self._command_set_state(self.bot.all_commands[command_name], 1 if state == 0 else 3) await ctx.send(f"The `{clean(ctx, command_name)}` command is now hidden.") else: await ctx.send(f"No `{clean(ctx, command_name)}` command found.") @commands.command(name="about", alias=["info"], usage="(MODULE NAME)") async def about(self, ctx: commands.Context, *, module_name: str = None): """This command gives information about modules, such as a description, authors, and other credits. Module authors can even add a small image to be displayed alongside this info. If no module name is given or the bot's name is used then information about the bot itself is shown.""" if module_name is None: # If no value is passed along we display the about page for the bot itself. if self.bot.user.name.lower() in self.bot.modules.keys(): # Check if the bot has an entry. embed = self.bot.modules[self.bot.user.name.lower()].make_about_embed(ctx) # Make and send response. await ctx.send(embed=embed) else: raise RuntimeError("Bot info module not found.") elif module_name.lower() in self.bot.modules.keys(): # Check if the passed along value has an entry. embed = self.bot.modules[module_name.lower()].make_about_embed(ctx) # Make and send response. await ctx.send(embed=embed) else: response = f"No information for `{clean(ctx, module_name)}` module was found." if module_name not in [mod.replace("modules.", "") for mod in self.bot.extensions.keys()]: response += "\nAdditionally no module with this name is loaded." await ctx.send(response) @commands.command(name="usage", usage="(MODULE NAME)") async def usage(self, ctx: commands.Context, *, module_name: str = None): """This command explains how a module is intended to be used. If no module name is given it will show some basic information about usage of the bot itself.""" if module_name is None or module_name.lower() in [self.bot.user.name.lower(), "core_commands", "core commands"]: pref = self.bot.get_bot_prefix() response = ( f"**How To Use:**\nThis bot features a variety of commands. You can get a list of all commands " f"you have access to with the `{pref}help` command. In order to use a command your message has " f"to start with the *bot prefix*, the bot prefix is currently set to `{pref}`. Simply type " f"this prefix, followed by a command name, and you will run the command. For more information " f"on individual commands, run `{pref}help` followed by the command name. This will give you " f"info on the command, along with some examples of it and any aliases the command might have. " f"You might not have access to all commands everywhere, the help command will only tell you " f"about commands you have access to in that channel, and commands you can run only in the DMs " f"with the bot. DM only commands will be labeled as such by the help command.\n\nSome commands " f"accept extra input, an example would be how the help command accepts a command name. You can " f"usually see an example of how the command is used on the command's help page. If you use a " f"command incorrectly by missing some input or sending invalid input, it will send you the " f"expected input. This is how to read the expected input:\n\nArguments encased in `<>` are " f"obligatory.\nArguments encased in `()` are optional and can be skipped.\nArguments written " f"in all uppercase are placeholders like names.\nArguments not written in uppercase are exact " f"values.\nIf an argument lists multiple things separated by `/` then any one of them is valid." f"\nThe `<>` and `()` symbols are not part of the command.\n\nSample expected input: `{pref}" f"about (MODULE NAME)`\nHere `{pref}about` is the command, and it takes an optional argument. " f"The argument is written in all uppercase, so it is a placeholder. In other words you are " f"expected to replace 'MODULE NAME' with the actual name of a module. Since the module name is " f"optional, sending just `{pref}about` is also a valid command." ) await ctx.send(response) elif module_name.lower() in self.bot.modules.keys(): usage = self.bot.modules[module_name.lower()].usage if usage is None: await ctx.send(f"The `{clean(ctx, module_name)}` module does not have its usage defined.") else: usage_content = usage() if isinstance(usage_content, str): await ctx.send(usage_content if len(usage_content) < 1950 else f"{usage_content[:1949]}...") elif isinstance(usage_content, Embed): await ctx.send(embed=usage_content) else: response = f"No information for `{clean(ctx, module_name)}` module was found." if module_name not in [mod.replace("modules.", "") for mod in self.bot.extensions.keys()]: response += "\nAdditionally no module with this name is loaded." await ctx.send(response) @commands.has_permissions(administrator=True) @commands.group(invoke_without_command=True, name="config", usage="<get/set/unset>") async def config(self, ctx: commands.Context): """This command is used to get, set and unset configuration options used by other modules or commands. All config options are saves as strings. Converting them to the proper type is up to the module or command that uses them. See the help text for the subcommands for more info.""" raise commands.BadArgument(f"No subcommand given for {ctx.command.name}.") @commands.has_permissions(administrator=True) @config.command(name="get", usage="<CONFIG_OPTION/all>") async def config_get(self, ctx: commands.Context, option: str): """This command is used to get the value of config options. Using this, one can check what configuration options are set to. Using the keyword `all` instead of an option name will print all options and their values.""" option = option.lower() if option == "all": if not self.bot.config: await ctx.send("No configuration options are set.") return paginator = commands.Paginator() for line in [f"{key}: {value}" for key, value in self.bot.config.items()]: line = tbb.clean(ctx, line, False, True) paginator.add_line(line if len(line) < 1992 else f"{line[:1989]}...") for page in paginator.pages: await ctx.send(page) elif option.lower() in self.bot.config: value = tbb.clean(ctx, self.bot.config[option], False, True) option = tbb.clean(ctx, option, False, True) line = f"Option: `{option}`, value: `{value}`" await ctx.send(line if len(line) < 1994 else f"{line[:1991]}...") else: option = tbb.clean(ctx, option, False, True) await ctx.send(f"No configuration option `{option if len(option) < 1960 else option[:1959]}...` is set.") @commands.has_permissions(administrator=True) @config.command(name="set", usage="CONFIG_OPTION> <VALUE>") async def config_set(self, ctx: commands.Context, option: str, *, value: str): """This command sets a configuration option. Configuration options are used by other modules or commands. Setting an option which already exists will overwrite the option. Setting an option which does not exist will create it. The keyword all cannot be used as a configuration option as it is used by the get command to get all options.""" option = option.lower() if option == "all": await ctx.send("The keyword `all` cannot be used as a configuration option.") else: self.bot.config[option] = value async with self.bot.db.acquire() as conn: await conn.execute( "INSERT INTO config VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = $2", option, value ) option = tbb.clean(ctx, option, False, True) value = tbb.clean(ctx, value, False, True) line = f"Configuration option `{option}` has been set to `{value}`." await ctx.send(line if len(line) < 2000 else f"{line[:1996]}...") @commands.has_permissions(administrator=True) @config.command(name="unset", usage="<CONFIG_OPTION> <VALUE>") async def config_unset(self, ctx: commands.Context, option: str): """This command allows for the removal of configuration options. Removing configuration options which are required by commands or modules will stop these from working.""" option = option.lower() if option in self.bot.config: del self.bot.config[option] async with self.bot.db.acquire() as conn: await conn.execute("DELETE FROM config WHERE key = $1", option) option = tbb.clean(ctx, option, False, True) line = f"Configuration option `{option}` has been unset." await ctx.send(line if len(line) < 2000 else f"{line[:1996]}...") else: option = tbb.clean(ctx, option, False, True) line = f"No configuration option `{option}` exists." await ctx.send(line if len(line) < 2000 else f"{line[:1996]}...") @commands.is_owner() @commands.command(name="shutdown", aliases=["goodbye", "goodnight"], usage="(TIME BEFORE SHUTDOWN)") async def shutdown(self, ctx: commands.Context, countdown: str = None): """This command turns the bot off. A delay can be set causing the bot to wait before shutting down. The time uses a format of numbers followed by units, see examples for details. Times supported are weeks (w), days (d), hours (h), minutes (m) and seconds (s), and even negative numbers. For this command the delay must be between 0 seconds and 24 hours. Supplying no time will cause the bot to shut down immediately. Once started, a shutdown cannot be stopped.""" if countdown is None: # If no time is passed along, shut down the bot immediately. await ctx.send("Goodbye!") await self.bot.close() await self.bot.db.close() else: try: time = tbb.parse_time(countdown, 0, 86400, True) # Parse time to get time in seconds. await ctx.send(f"Shutdown will commence in {time} seconds.") await asleep(time) await ctx.send("Shutting down!") await self.bot.logout() await self.bot.db.close() except ValueError as e: # If time parser encounters error, and error is exceeding of limit, report back. if str(e) in ["Time too short.", "Time too long."]: await ctx.send("The time for this command must be between 0 seconds to 24 hours.") else: # If another error is encountered, log to console. await ctx.send("The time could not be parsed correctly.") self.log.error(f"{ctx.author.id}: {str(e)}") self.bot.last_error = f"{ctx.author.id}: {str(e)}"
import logging from asyncio import sleep as asleep # For waiting asynchronously. from os import listdir # To check files on disk. from asyncpg import IntegrityConstraintViolationError # To check for database conflicts. from discord import Embed, Activity, ActivityType # For bot status from discord.ext import commands # For implementation of bot commands. import travus_bot_base as tbb # TBB functions and classes. from travus_bot_base import clean # Shorthand for cleaning output. def setup(bot: tbb.TravusBotBase): """Setup function ran when module is loaded.""" bot.add_cog(CoreFunctionalityCog(bot)) # Add cog and command help info. bot.add_command_help(CoreFunctionalityCog.botconfig_prefix, "Core", None, ["$", "bot!", "bot ?", "remove"]) bot.add_command_help(CoreFunctionalityCog.botconfig_deletemessages, "Core", None, ["enable", "y", "disable", "n"]) bot.add_command_help(CoreFunctionalityCog.module_list, "Core", {"perms": ["Administrator"]}, [""]) bot.add_command_help(CoreFunctionalityCog.module_load, "Core", {"perms": ["Administrator"]}, ["fun", "economy"]) bot.add_command_help(CoreFunctionalityCog.module_unload, "Core", {"perms": ["Administrator"]}, ["fun", "economy"]) bot.add_command_help(CoreFunctionalityCog.module_reload, "Core", {"perms": ["Administrator"]}, ["fun", "economy"]) bot.add_command_help(CoreFunctionalityCog.default, "Core", None, ["list", "add", "remove"]) bot.add_command_help(CoreFunctionalityCog.default_list, "Core", None, [""]) bot.add_command_help(CoreFunctionalityCog.default_add, "Core", None, ["fun", "economy"]) bot.add_command_help(CoreFunctionalityCog.default_remove, "Core", None, ["fun", "economy"]) bot.add_command_help(CoreFunctionalityCog.command_enable, "Core", {"perms": ["Administrator"]}, ["balance", "pay"]) bot.add_command_help(CoreFunctionalityCog.command_disable, "Core", {"perms": ["Administrator"]}, ["balance", "pay"]) bot.add_command_help(CoreFunctionalityCog.command_show, "Core", {"perms": ["Administrator"]}, ["module", "balance"]) bot.add_command_help(CoreFunctionalityCog.command_hide, "Core", {"perms": ["Administrator"]}, ["module", "balance"]) bot.add_command_help(CoreFunctionalityCog.about, "Core", None, ["", "fun"]) bot.add_command_help(CoreFunctionalityCog.usage, "Core", None, ["", "dev"]) bot.add_command_help(CoreFunctionalityCog.config, "Core", {"perms": ["Administrator"]}, ["get", "set", "unset"]) bot.add_command_help(CoreFunctionalityCog.config_get, "Core", {"perms": ["Administrator"]}, ["alert_channel"]) bot.add_command_help(CoreFunctionalityCog.config_unset, "Core", {"perms": ["Administrator"]}, ["alert_channel"]) bot.add_command_help(CoreFunctionalityCog.shutdown, "Core", None, ["", "1h", "1h30m", "10m-30s", "2m30s"]) bot.add_command_help( CoreFunctionalityCog.botconfig, "Core", None, ["prefix", "deletemessages", "description", "credits"] ) bot.add_command_help( CoreFunctionalityCog.botconfig_description, "Core", None, ["remove", "This is a sample description."] ) bot.add_command_help( CoreFunctionalityCog.module, "Core", {"perms": ["Administrator"]}, ["list", "load", "unload", "reload"] ) bot.add_command_help( CoreFunctionalityCog.command, "Core", {"perms": ["Administrator"]}, ["enable", "disable", "show", "hide"] ) bot.add_command_help( CoreFunctionalityCog.config_set, "Core", {"perms": ["Administrator"]}, ["alert_channel 353246496952418305"] ) bot.add_command_help( CoreFunctionalityCog.botconfig_credits, "Core", None, ["remove", "`\n```\n[Person](URL):\n\tBot Profile Image\n``"], ) def teardown(bot: tbb.TravusBotBase): """Teardown function ran when module is unloaded.""" bot.remove_cog("CoreFunctionalityCog") # Remove cog and command help info. bot.remove_command_help(CoreFunctionalityCog) class CoreFunctionalityCog(commands.Cog): """Cog that holds default functionality.""" def __init__(self, bot: tbb.TravusBotBase): """Initialization function loading bot object for cog.""" self.bot = bot self.log = logging.getLogger("core_commands") self.log.setLevel(logging.INFO) async def _module_operation(self, ctx: commands.Context, operation: str, mod: str): """To avoid code duplication in the except blocks all module command functionality is grouped together.""" async def load(): """Contains the logic for loading a module.""" if f"{mod}.py" in listdir("modules"): self.bot.load_extension(f"modules.{mod}") await self.bot.update_command_states() await ctx.send(f"Module `{mod_name}` successfully loaded.") self.log.info(f"{ctx.author.id}: loaded '{mod}' module.") else: await ctx.send(f"No `{mod_name}` module was found.") async def unload(): """Contains the logic for unloading a module.""" self.bot.unload_extension(f"modules.{mod}") await ctx.send(f"Module `{mod_name}` successfully unloaded.") self.log.info(f"{ctx.author.id}: unloaded '{mod}' module.") async def reload(): """Contains the logic for reloading a module.""" if f"{mod}.py" in listdir("modules"): self.bot.reload_extension(f"modules.{mod}") await self.bot.update_command_states() await ctx.send(f"Module `{mod_name}` successfully reloaded.") self.log.info(f"{ctx.author.id}: reloaded '{mod}' module.") else: if mod in self.bot.modules: await ctx.send(f"The `{mod_name}` module file is no longer found on disk. Reload canceled.") else: await ctx.send(f"No `{mod_name}` module was found.") old_help = dict(self.bot.help) # Save old help and module info in we need to roll back. old_modules = dict(self.bot.modules) self.bot.extension_ctx = ctx # Save context in case loaded module has use for it. mod_name = clean(ctx, mod, False, True) try: if operation == "load": await load() elif operation == "unload": await unload() elif operation == "reload": await reload() except commands.ExtensionAlreadyLoaded: # If module was already loaded. await ctx.send(f"The `{mod_name}` module was already loaded.") except commands.ExtensionNotLoaded: # If module wasn't loaded to begin with. await ctx.send(f"No `{mod_name}` module is loaded.") except commands.ExtensionFailed as e: self.bot.help = old_help self.bot.modules = old_modules if isinstance(e.original, tbb.DependencyError): missing_deps = [f"`{clean(ctx, elem, False, True)}`" for elem in e.original.missing_dependencies] await ctx.send(f"Module `{mod_name}` requires these missing dependencies: {', '.join(missing_deps)}") else: await ctx.send( "**Error! Something went really wrong! Contact module maintainer.**\nError logged to console and " "stored in module error command." ) self.log.error(f"{ctx.author.id}: tried loading '{mod}' module, and it failed:\n\n{str(e)}") self.bot.last_module_error = ( f"The `{clean(ctx, mod, False)}` module failed while loading. The error was:\n\n{clean(ctx, str(e))}" ) except Exception as e: self.bot.help = old_help self.bot.modules = old_modules await ctx.send( "**Error! Something went really wrong! Contact module maintainer.**\nError logged to console and " "stored in module error command." ) if isinstance(e, commands.ExtensionNotFound): # Clarify error further in case it was an import error. e = e.__cause__ self.log.error(f"{ctx.author.id}: tried loading '{mod}' module, and it failed:\n\n{str(e)}") self.bot.last_module_error = ( f"The `{clean(ctx, mod, False)}` module failed while loading. The error was:\n\n{clean(ctx, str(e))}" ) finally: # Reset context as loading has concluded. self.bot.extension_ctx = None @commands.is_owner() @commands.group(invoke_without_command=True, name="botconfig", usage="<prefix/deletemessages/description/credits>") async def botconfig(self, ctx: commands.Context): """This command sets the bot's prefix, command trigger deletion behaviour, description and additional credits section. Fore more information check the help entry of one of these subcommands; `prefix`, `deletemessages`, `description`, `credits`.""" raise commands.BadArgument(f"No subcommand given for {ctx.command.name}.") @commands.is_owner() @botconfig.command(name="prefix", usage="<NEW PREFIX/remove>") async def botconfig_prefix(self, ctx: commands.Context, *, new_prefix: str): """This command changes the bot prefix. The default prefix is `!`. Prefixes can be everything from symbols to words or a combination of the two, and can even include spaces, though they cannot start or end with spaces since Discord removes empty space at the start and end of messages. The prefix is saved across reboots. Setting the prefix to `remove` will remove the prefix. The bot will always listen to pings as if they were a prefix, regardless of if there is another prefix set or not. Maximum prefix length is 20.""" if len(new_prefix) > 20: await ctx.send("The maximum prefix length is 20.") return self.bot.prefix = new_prefix if new_prefix.lower() != "remove" else None # If 'remove', prefix is set to None. activity = Activity( type=ActivityType.listening, name=f"prefix: {new_prefix}" if new_prefix.lower() != "remove" else "pings only", ) await self.bot.change_presence(activity=activity) # Set status. async with self.bot.db.acquire() as conn: await conn.execute( "UPDATE settings SET value = $1 WHERE key = 'prefix'", new_prefix if new_prefix.lower() != "remove" else "", ) # Empty string is no prefix. if new_prefix.lower() != "remove": # Give feedback to user. await ctx.send(f"The bot prefix has successfully been changed to `{new_prefix}`.") else: await ctx.send("The bot is now only listens to pings.") @commands.is_owner() @botconfig.command( name="deletemessages", aliases=["deletemsgs", "deletecommands", "deletecmds", "delmessages", "delmsgs", "delcommands", "delcmds"], usage="<enable/disable>", ) async def botconfig_deletemessages(self, ctx: commands.Context, operation: str): """This command sets the behaviour for deletion of command triggers. If this is enabled then messages that trigger commands will be deleted. Is this is disabled then the bot will not delete messages that trigger commands. Per default this is enabled. This setting is saved across restarts.""" op = operation.lower() async with self.bot.db.acquire() as conn: if op in ["enable", "true", "on", "yes", "y", "+", "1"]: # Values interpreted as true. if self.bot.delete_messages: await ctx.send("The bot is already deleting command triggers.") return await conn.execute("UPDATE settings SET value = '1' WHERE key = 'delete_messages'") self.bot.delete_messages = 1 await ctx.send("Now deleting command triggers.") elif op in ["disable", "false", "off", "no", "n", "-", "0"]: # Values interpreted as false. if not self.bot.delete_messages: await ctx.send("The bot is already not deleting command triggers.") return await conn.execute("UPDATE settings SET value = '0' WHERE key = 'delete_messages'") self.bot.delete_messages = 0 await ctx.send("No longer deleting command triggers.") else: raise commands.BadArgument("Operation not supported.") @commands.is_owner() @botconfig.command(name="description", aliases=["desc"], usage="<DESCRIPTION/remove>") async def botconfig_description(self, ctx: commands.Context, *, description: str): """This command sets the bot description that is used by the about command. The description can technically be up to 4096 characters long, keep however in mind that Discord messages have a maximum length of 4000 characters (2000 without Nitro). If `remove` is sent along then the description will be removed. The special keyword `_prefix_` wil be replaced by the current bot prefix.""" async with self.bot.db.acquire() as conn: if description.lower() == "remove": await conn.execute("UPDATE settings SET value = '' WHERE key = 'bot_description'") self.bot.modules[ self.bot.user.name.lower() ].description = "No description for the bot found. Set description with `botconfig` command." await ctx.send("The description has been removed.") else: await conn.execute("UPDATE settings SET value = $1 WHERE key = 'bot_description'", description) self.bot.modules[self.bot.user.name.lower()].description = description await ctx.send("The description has been set.") @commands.is_owner() @botconfig.command(name="credits", usage="<CREDITS/remove> *OBS: See help command entry!*") async def botconfig_credits(self, ctx: commands.Context, *, description: str): """This command sets the additional credits section of the about command. The additional credits section can be at most 1024 characters long, and supports both new lines, indents and embedded links. Indents of 5 spaces are recommended. Embedded links should look like so; `[displayed text](URL)`. The credits should be passed inside a multi-line code block in order for new lines and tabs to work correctly. If `remove` is passed instead then the additional credits section is removed.""" description = description.strip() async with self.bot.db.acquire() as conn: if description.lower() == "remove": await conn.execute("UPDATE settings SET value = '' WHERE key = 'additional_credits'") self.bot.modules[self.bot.user.name.lower()].credits = None await ctx.send("The additional credits section has been removed.") return if description.count("```") != 2 or description[:3] != "```" or description[-3:] != "```": await ctx.send("Credits must be fully encased in a multi-line code block.") return description = description.strip("```").strip() # Remove code block. description = description.replace(" ", "\u202F") # Prevent whitespace from disappearing. if len(description) > 1024: await ctx.send("Credits too long. Credits can be at most 1024 characters long.") return await conn.execute("UPDATE settings SET value = $1 WHERE key = 'additional_credits'", description) self.bot.modules[self.bot.user.name.lower()].credits = description await ctx.send("The additional credits section has been set.") @commands.has_permissions(administrator=True) @commands.group( invoke_without_command=True, name="module", aliases=["modules"], usage="<list/load/unload/reload/error>" ) async def module(self, ctx: commands.Context): """This command can load, unload, reload and list available modules. It can also show any errors that occur during the loading process. Modules contain added functionality, such as commands. The intended purpose for modules is to extend the bot's functionality in semi-independent packages so that parts of the bot's functionality can be removed or restarted without affecting the rest of the bot's functionality. See the help text for the subcommands for more info.""" raise commands.BadArgument(f"No subcommand given for {ctx.command.name}.") @commands.has_permissions(administrator=True) @module.command(name="list") async def module_list(self, ctx: commands.Context): """This command lists all currently loaded and available modules. For the bot to find new modules they need to be placed inside the modules folder inside the bot directory. Modules listed by this command can be loaded, unloaded and reloaded by the respective commands for this. See help text for `module load`, `module unload` and `module reload` for more info on this.""" loaded_modules = [ f"`{clean(ctx, mod.replace('modules.', ''), False, True)}`, " for mod in self.bot.extensions if mod != "core_commands" ] or ["None, "] available_modules = [ f"`{clean(ctx, mod, False, True).replace('.py', '')}`, " for mod in listdir("modules") if mod.endswith(".py") ] available_modules = [mod for mod in available_modules if mod not in loaded_modules] or ["None, "] loaded_modules[-1] = loaded_modules[-1][:-2] available_modules[-1] = available_modules[-1][:-2] paginator = commands.Paginator(prefix="", suffix="", linesep="") paginator.add_line("Loaded modules: ") for mod in loaded_modules: paginator.add_line(mod) paginator.add_line("\nAvailable Modules: ") for mod in available_modules: paginator.add_line(mod) for page in paginator.pages: await ctx.send(page) @commands.has_permissions(administrator=True) @module.command(name="load", aliases=["l"], usage="<MODULE NAME>") async def module_load(self, ctx: commands.Context, *, mod: str): """This command loads modules. Modules should be located inside the module folder in the bot directory. The `module list` command can be used to show all modules available for loading. Once a module is loaded the functionality defined in the module file will be added to the bot. If an error is encountered during the loading process the user will be informed and the `module error` command can then be used to see the error details. The module will then not be loaded. If you want modules to stay loaded after restarts, see the `default` command.""" await self._module_operation(ctx, "load", mod) @commands.has_permissions(administrator=True) @module.command(name="unload", aliases=["ul"], usage="<MODULE NAME>") async def module_unload(self, ctx: commands.Context, *, mod: str): """This command unloads modules. When a loaded module is unloaded it's functionality will be removed. You can use the `module list` command to see all currently loaded modules. This will not prevent default modules from being loaded when the bot starts. See the `default` command for removing modules starting with the bot.""" await self._module_operation(ctx, "unload", mod) @commands.has_permissions(administrator=True) @module.command(name="reload", aliases=["rl"], usage="<MODULE NAME>") async def module_reload(self, ctx: commands.Context, *, mod: str): """This command reloads a module that is currently loaded. This will unload and load the module in one command. If the module is no longer present or the loading process encounters an error the module will not be reloaded and the functionality from before the reload will be retained and the user informed, the `module error` command can then be used to see the error details. You can use the module list command to see all currently loaded modules.""" await self._module_operation(ctx, "reload", mod) @commands.has_permissions(administrator=True) @module.command(name="error") async def module_error(self, ctx: commands.Context): """This command will show the last error that was encountered during the module load or reloading process. This information will also be logged to the console when the error first is encountered. This command retains this information until another error replaces it, or the bot shuts down.""" if self.bot.last_module_error: await ctx.send(self.bot.last_module_error[:1999]) else: await ctx.send("There have not been any errors loading modules since the last restart.") @commands.is_owner() @commands.group(invoke_without_command=True, name="default", aliases=["defaults"], usage="<add/remove/list>") async def default(self, ctx: commands.Context): """This command is used to add, remove or list default modules. Modules contain added functionality, such as commands. Default modules are loaded automatically when the bot starts and as such any functionality in them will be available as soon as the bot is online. For more info see the help text of the subcommands.""" raise commands.BadArgument(f"No subcommand given for {ctx.command.name}.") @commands.is_owner() @default.command(name="list") async def default_list(self, ctx: commands.Context): """This command lists all current default modules. For more information on modules see the help text for the `module` command. All modules in this list start as soon as the bot is launched. For a list of all available or loaded modules see the `module list` command.""" async with self.bot.db.acquire() as conn: result = await conn.fetch("SELECT module FROM default_modules") result = [f"`{clean(ctx, val['module'], False, True)}`, " for val in result] or ["None, "] result[-1] = result[-1][:-2] paginator = commands.Paginator(prefix="", suffix="", linesep="") paginator.add_line("Default modules: ") for mod in result: paginator.add_line(mod) for page in paginator.pages: await ctx.send(page) @commands.is_owner() @default.command(name="add", usage="<MODULE NAME>") async def default_add(self, ctx: commands.Context, *, mod: str): """This command adds a module to the list of default modules. Modules in this list are loaded automatically once the bot starts. This command does not load modules if they are not already loaded until the bot is started the next time. For that, see the `module load` command. For a list of existing default modules, see the `default list` command. For more info on modules see the help text for the `module` command.""" if f"{mod}.py" in listdir("modules"): # Check if such a module even exists. try: async with self.bot.db.acquire() as conn: await conn.execute("INSERT INTO default_modules VALUES ($1)", mod) await ctx.send(f"The `{clean(ctx, mod, False, True)}` module is now a default module.") except IntegrityConstraintViolationError: await ctx.send(f"The `{clean(ctx, mod, False, True)}` module is already a default module.") else: await ctx.send(f"No `{clean(ctx, mod, False, True)}` module was found.") @commands.is_owner() @default.command(name="remove", usage="<MODULE NAME>") async def default_remove(self, ctx: commands.Context, *, mod: str): """This command removes a module from the list of default modules. Once removed from this list the module will no longer automatically be loaded when the bot starts. This command will not unload commands that are already loaded. For that, see the `module unload` command. For a list of existing default modules, see the `default list` command. For more info on modules see the help text for the `module` command.""" async with self.bot.db.acquire() as conn: result = await conn.fetchval("SELECT module FROM default_modules WHERE module = $1", mod) if result: await conn.execute("DELETE FROM default_modules WHERE module = $1", mod) await ctx.send(f"Removed `{clean(ctx, mod, False, True)}` module from default modules.") else: await ctx.send(f"No `{clean(ctx, mod, False, True)}` module in default modules.") @commands.has_permissions(administrator=True) @commands.group( invoke_without_command=True, name="command", aliases=["commands"], usage="<enable/disable/show/hide>" ) async def command(self, ctx: commands.Context): """This command disables, enables, hides and shows other commands. Hiding commands means they don't show up in the overall help command list. Disabling a command means it can't be used. Disabled commands also do not show up in the overall help command list and the specific help text for the command will not be viewable. Core commands cannot be disabled. These settings are saved across restarts.""" raise commands.BadArgument(f"No subcommand given for {ctx.command.name}.") async def _command_get_state(self, command: commands.Command) -> int: """Helper function for command command that gets the state of the command.""" async with self.bot.db.acquire() as conn: cog_com_name = f"{command.cog.__class__.__name__ + '.' if command.cog else ''}{command.name}" response = await conn.fetchval("SELECT state FROM command_states WHERE command = $1", cog_com_name) if response is None: await conn.execute("INSERT INTO command_states VALUES ($1, $2)", cog_com_name, 0) response = 0 return response async def _command_set_state(self, command: commands.Command, state: int): """Helper function for command command that sets the state of the command.""" async with self.bot.db.acquire() as conn: await conn.execute( "UPDATE command_states SET state = $1 WHERE command = $2", state, f"{command.cog.__class__.__name__ + '.' if command.cog else ''}{command.name}", ) @commands.has_permissions(administrator=True) @command.command(name="enable", usage="<COMMAND NAME>") async def command_enable(self, ctx: commands.Context, *, command_name: str): """This command enables commands which have previously been disabled. This will allow them to be used again. It will also add the command back into the list of commands shown by the help command and re-enable the viewing of it's help text given the command has help text and it has not otherwise been hidden.""" if command_name in self.bot.all_commands.keys(): # Check if command exists and get it's state. state = await self._command_get_state(self.bot.all_commands[command_name]) if self.bot.all_commands[command_name].enabled: # If command is already enabled, report back. await ctx.send(f"The `{clean(ctx, command_name)}` command is already enabled.") else: self.bot.all_commands[command_name].enabled = True await self._command_set_state(self.bot.all_commands[command_name], 0 if state == 2 else 1) await ctx.send(f"The `{clean(ctx, command_name)}` command is now enabled.") else: await ctx.send(f"No `{clean(ctx, command_name)}` command found.") @commands.has_permissions(administrator=True) @command.command(name="disable", usage="<COMMAND NAME>") async def command_disable(self, ctx: commands.Context, *, command_name: str): """This command can disable other commands. Disabled commands cannot be used and are removed from the list of commands shown by the help command. The command's help text will also not be viewable. Core commands cannot be disabled. Disabled commands can be re-enabled with the `command enable` command.""" if command_name in self.bot.all_commands.keys(): # Check if command exists and get it's state. state = await self._command_get_state(self.bot.all_commands[command_name]) if command_name in self.bot.help.keys() and self.bot.help[command_name].category.lower() == "core": await ctx.send("Core commands cannot be disabled.") else: if not self.bot.all_commands[command_name].enabled: # Check if the command is already disabled. await ctx.send(f"The `{clean(ctx, command_name)}` command is already disabled.") else: self.bot.all_commands[command_name].enabled = False await self._command_set_state(self.bot.all_commands[command_name], 2 if state == 0 else 3) await ctx.send(f"The `{clean(ctx, command_name)}` command is now disabled.") else: await ctx.send(f"No `{clean(ctx, command_name)}` command found.") @commands.has_permissions(administrator=True) @command.command(name="show", usage="<COMMAND NAME>") async def command_show(self, ctx: commands.Context, *, command_name: str): """This command will show commands which have previously been hidden, reversing the hiding of the command. This will add the command back into the list of commands shown by the help command. This will not re-enable the command if it has been disabled. Showing disabled commands alone will not be enough to re-add them to the help list since disabling them also hides them from the help list. See the `command enable` command to re-enable disabled commands.""" if command_name in self.bot.all_commands.keys(): # Check if command exists and get it's state. state = await self._command_get_state(self.bot.all_commands[command_name]) if not self.bot.all_commands[command_name].hidden: # Check if command i already visible. await ctx.send(f"The `{clean(ctx, command_name)}` command is already shown.") else: self.bot.all_commands[command_name].hidden = False await self._command_set_state(self.bot.all_commands[command_name], 0 if state == 1 else 2) await ctx.send(f"The `{clean(ctx, command_name)}` command is now shown.") else: await ctx.send(f"No `{clean(ctx, command_name)}` command found.") @commands.has_permissions(administrator=True) @command.command(name="hide", usage="<COMMAND NAME>") async def command_hide(self, ctx: commands.Context, *, command_name: str): """This command will hide commands from the list of commands shown by the help command. It will not disable the viewing of the help text for the command if someone already knows it's name. Commands who have been hidden can be un-hidden with the `command show` command.""" if command_name in self.bot.all_commands.keys(): # Check if command exists and get it's state. state = await self._command_get_state(self.bot.all_commands[command_name]) if self.bot.all_commands[command_name].hidden: # Check if command is already hidden. await ctx.send(f"The `{clean(ctx, command_name)}` command is already hidden.") else: self.bot.all_commands[command_name].hidden = True await self._command_set_state(self.bot.all_commands[command_name], 1 if state == 0 else 3) await ctx.send(f"The `{clean(ctx, command_name)}` command is now hidden.") else: await ctx.send(f"No `{clean(ctx, command_name)}` command found.") @commands.command(name="about", alias=["info"], usage="(MODULE NAME)") async def about(self, ctx: commands.Context, *, module_name: str = None): """This command gives information about modules, such as a description, authors, and other credits. Module authors can even add a small image to be displayed alongside this info. If no module name is given or the bot's name is used then information about the bot itself is shown.""" if module_name is None: # If no value is passed along we display the about page for the bot itself. if self.bot.user.name.lower() in self.bot.modules.keys(): # Check if the bot has an entry. embed = self.bot.modules[self.bot.user.name.lower()].make_about_embed(ctx) # Make and send response. await ctx.send(embed=embed) else: raise RuntimeError("Bot info module not found.") elif module_name.lower() in self.bot.modules.keys(): # Check if the passed along value has an entry. embed = self.bot.modules[module_name.lower()].make_about_embed(ctx) # Make and send response. await ctx.send(embed=embed) else: response = f"No information for `{clean(ctx, module_name)}` module was found." if module_name not in [mod.replace("modules.", "") for mod in self.bot.extensions.keys()]: response += "\nAdditionally no module with this name is loaded." await ctx.send(response) @commands.command(name="usage", usage="(MODULE NAME)") async def usage(self, ctx: commands.Context, *, module_name: str = None): """This command explains how a module is intended to be used. If no module name is given it will show some basic information about usage of the bot itself.""" if module_name is None or module_name.lower() in [self.bot.user.name.lower(), "core_commands", "core commands"]: pref = self.bot.get_bot_prefix() response = ( f"**How To Use:**\nThis bot features a variety of commands. You can get a list of all commands " f"you have access to with the `{pref}help` command. In order to use a command your message has " f"to start with the *bot prefix*, the bot prefix is currently set to `{pref}`. Simply type " f"this prefix, followed by a command name, and you will run the command. For more information " f"on individual commands, run `{pref}help` followed by the command name. This will give you " f"info on the command, along with some examples of it and any aliases the command might have. " f"You might not have access to all commands everywhere, the help command will only tell you " f"about commands you have access to in that channel, and commands you can run only in the DMs " f"with the bot. DM only commands will be labeled as such by the help command.\n\nSome commands " f"accept extra input, an example would be how the help command accepts a command name. You can " f"usually see an example of how the command is used on the command's help page. If you use a " f"command incorrectly by missing some input or sending invalid input, it will send you the " f"expected input. This is how to read the expected input:\n\nArguments encased in `<>` are " f"obligatory.\nArguments encased in `()` are optional and can be skipped.\nArguments written " f"in all uppercase are placeholders like names.\nArguments not written in uppercase are exact " f"values.\nIf an argument lists multiple things separated by `/` then any one of them is valid." f"\nThe `<>` and `()` symbols are not part of the command.\n\nSample expected input: `{pref}" f"about (MODULE NAME)`\nHere `{pref}about` is the command, and it takes an optional argument. " f"The argument is written in all uppercase, so it is a placeholder. In other words you are " f"expected to replace 'MODULE NAME' with the actual name of a module. Since the module name is " f"optional, sending just `{pref}about` is also a valid command." ) await ctx.send(response) elif module_name.lower() in self.bot.modules.keys(): usage = self.bot.modules[module_name.lower()].usage if usage is None: await ctx.send(f"The `{clean(ctx, module_name)}` module does not have its usage defined.") else: usage_content = usage() if isinstance(usage_content, str): await ctx.send(usage_content if len(usage_content) < 1950 else f"{usage_content[:1949]}...") elif isinstance(usage_content, Embed): await ctx.send(embed=usage_content) else: response = f"No information for `{clean(ctx, module_name)}` module was found." if module_name not in [mod.replace("modules.", "") for mod in self.bot.extensions.keys()]: response += "\nAdditionally no module with this name is loaded." await ctx.send(response) @commands.has_permissions(administrator=True) @commands.group(invoke_without_command=True, name="config", usage="<get/set/unset>") async def config(self, ctx: commands.Context): """This command is used to get, set and unset configuration options used by other modules or commands. All config options are saves as strings. Converting them to the proper type is up to the module or command that uses them. See the help text for the subcommands for more info.""" raise commands.BadArgument(f"No subcommand given for {ctx.command.name}.") @commands.has_permissions(administrator=True) @config.command(name="get", usage="<CONFIG_OPTION/all>") async def config_get(self, ctx: commands.Context, option: str): """This command is used to get the value of config options. Using this, one can check what configuration options are set to. Using the keyword `all` instead of an option name will print all options and their values.""" option = option.lower() if option == "all": if not self.bot.config: await ctx.send("No configuration options are set.") return paginator = commands.Paginator() for line in [f"{key}: {value}" for key, value in self.bot.config.items()]: line = tbb.clean(ctx, line, False, True) paginator.add_line(line if len(line) < 1992 else f"{line[:1989]}...") for page in paginator.pages: await ctx.send(page) elif option.lower() in self.bot.config: value = tbb.clean(ctx, self.bot.config[option], False, True) option = tbb.clean(ctx, option, False, True) line = f"Option: `{option}`, value: `{value}`" await ctx.send(line if len(line) < 1994 else f"{line[:1991]}...") else: option = tbb.clean(ctx, option, False, True) await ctx.send(f"No configuration option `{option if len(option) < 1960 else option[:1959]}...` is set.") @commands.has_permissions(administrator=True) @config.command(name="set", usage="CONFIG_OPTION> <VALUE>") async def config_set(self, ctx: commands.Context, option: str, *, value: str): """This command sets a configuration option. Configuration options are used by other modules or commands. Setting an option which already exists will overwrite the option. Setting an option which does not exist will create it. The keyword all cannot be used as a configuration option as it is used by the get command to get all options.""" option = option.lower() if option == "all": await ctx.send("The keyword `all` cannot be used as a configuration option.") else: self.bot.config[option] = value async with self.bot.db.acquire() as conn: await conn.execute( "INSERT INTO config VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = $2", option, value ) option = tbb.clean(ctx, option, False, True) value = tbb.clean(ctx, value, False, True) line = f"Configuration option `{option}` has been set to `{value}`." await ctx.send(line if len(line) < 2000 else f"{line[:1996]}...") @commands.has_permissions(administrator=True) @config.command(name="unset", usage="<CONFIG_OPTION> <VALUE>") async def config_unset(self, ctx: commands.Context, option: str): """This command allows for the removal of configuration options. Removing configuration options which are required by commands or modules will stop these from working.""" option = option.lower() if option in self.bot.config: del self.bot.config[option] async with self.bot.db.acquire() as conn: await conn.execute("DELETE FROM config WHERE key = $1", option) option = tbb.clean(ctx, option, False, True) line = f"Configuration option `{option}` has been unset." await ctx.send(line if len(line) < 2000 else f"{line[:1996]}...") else: option = tbb.clean(ctx, option, False, True) line = f"No configuration option `{option}` exists." await ctx.send(line if len(line) < 2000 else f"{line[:1996]}...") @commands.is_owner() @commands.command(name="shutdown", aliases=["goodbye", "goodnight"], usage="(TIME BEFORE SHUTDOWN)") async def shutdown(self, ctx: commands.Context, countdown: str = None): """This command turns the bot off. A delay can be set causing the bot to wait before shutting down. The time uses a format of numbers followed by units, see examples for details. Times supported are weeks (w), days (d), hours (h), minutes (m) and seconds (s), and even negative numbers. For this command the delay must be between 0 seconds and 24 hours. Supplying no time will cause the bot to shut down immediately. Once started, a shutdown cannot be stopped.""" if countdown is None: # If no time is passed along, shut down the bot immediately. await ctx.send("Goodbye!") await self.bot.close() await self.bot.db.close() else: try: time = tbb.parse_time(countdown, 0, 86400, True) # Parse time to get time in seconds. await ctx.send(f"Shutdown will commence in {time} seconds.") await asleep(time) await ctx.send("Shutting down!") await self.bot.logout() await self.bot.db.close() except ValueError as e: # If time parser encounters error, and error is exceeding of limit, report back. if str(e) in ["Time too short.", "Time too long."]: await ctx.send("The time for this command must be between 0 seconds to 24 hours.") else: # If another error is encountered, log to console. await ctx.send("The time could not be parsed correctly.") self.log.error(f"{ctx.author.id}: {str(e)}") self.bot.last_error = f"{ctx.author.id}: {str(e)}"
import sys import pytest import pytorch_testing_utils as ptu import torch import torch.nn.functional as F from torch import nn from torch.utils import data from pystiche import loss, ops, optim from tests import mocks skip_if_py38 = pytest.mark.skipif( sys.version_info >= (3, 8), reason=( "Test errors on Python 3.8 only. This is most likely caused by the test " "itself rather than the code it should test." ), ) def test_default_image_optimizer(): torch.manual_seed(0) image = torch.rand(1, 3, 128, 128) optimizer = optim.default_image_optimizer(image) assert isinstance(optimizer, torch.optim.Optimizer) actual = optimizer.param_groups[0]["params"][0] desired = image ptu.assert_allclose(actual, desired) def test_image_optimization_optimizer_preprocessor(): input_image = torch.empty(1) criterion = nn.Module() optimizer = optim.default_image_optimizer(input_image) preprocessor = nn.Module() with pytest.raises(RuntimeError): optim.image_optimization( input_image, criterion, optimizer, preprocessor=preprocessor ) @skip_if_py38 @pytest.mark.flaky def test_default_image_optim_loop(optim_asset_loader): asset = optim_asset_loader("default_image_optim_loop") actual = optim.image_optimization( asset.input.image, asset.input.perceptual_loss, optimizer=asset.params.get_optimizer, num_steps=asset.params.num_steps, quiet=True, ) desired = asset.output.image ptu.assert_allclose(actual, desired, rtol=1e-4) @skip_if_py38 @pytest.mark.skip( "'pystiche.image.transforms' is needed to load the asset, " "but is no longer accessible." ) @pytest.mark.flaky def test_default_image_optim_loop_processing(optim_asset_loader): asset = optim_asset_loader("default_image_optim_loop_processing") actual = optim.image_optimization( asset.input.image, asset.input.perceptual_loss, optimizer=asset.params.get_optimizer, num_steps=asset.params.num_steps, preprocessor=asset.params.preprocessor, postprocessor=asset.params.postprocessor, quiet=True, ) desired = asset.output.image ptu.assert_allclose(actual, desired, rtol=1e-4) @skip_if_py38 @pytest.mark.flaky def test_default_image_pyramid_optim_loop(optim_asset_loader): asset = optim_asset_loader("default_image_pyramid_optim_loop") actual = optim.pyramid_image_optimization( asset.input.image, asset.input.perceptual_loss, asset.input.pyramid, get_optimizer=asset.params.get_optimizer, quiet=True, ) desired = asset.output.image ptu.assert_allclose(actual, desired, rtol=1e-4) @skip_if_py38 @pytest.mark.flaky def test_default_image_pyramid_optim_loop_processing(optim_asset_loader): asset = optim_asset_loader("default_image_pyramid_optim_loop") actual = optim.pyramid_image_optimization( asset.input.image, asset.input.perceptual_loss, asset.input.pyramid, get_optimizer=asset.params.get_optimizer, preprocessor=asset.params.preprocessor, postprocessor=asset.params.postprocessor, quiet=True, ) desired = asset.output.image ptu.assert_allclose(actual, desired, rtol=1e-4) def test_default_transformer_optimizer(): torch.manual_seed(0) transformer = nn.Conv2d(3, 3, 1) optimizer = optim.default_model_optimizer(transformer) assert isinstance(optimizer, torch.optim.Optimizer) actuals = optimizer.param_groups[0]["params"] desireds = tuple(transformer.parameters()) for actual, desired in zip(actuals, desireds): ptu.assert_allclose(actual, desired) def make_torch_ge_1_6_compatible(image_loader, criterion): # See https://github.com/pmeier/pystiche/pull/348 for a discussion of this image_loader.generator = None for module in criterion.modules(): module._non_persistent_buffers_set = set() @skip_if_py38 @pytest.mark.flaky def test_default_transformer_optim_loop(optim_asset_loader): asset = optim_asset_loader("default_transformer_optim_loop") image_loader = asset.input.image_loader criterion = asset.input.perceptual_loss make_torch_ge_1_6_compatible(image_loader, criterion) transformer = asset.input.transformer optimizer = asset.params.get_optimizer(transformer) transformer = optim.model_optimization( image_loader, transformer, criterion, asset.input.criterion_update_fn, optimizer=optimizer, quiet=True, ) actual = tuple(transformer.parameters()) desired = tuple(asset.output.transformer.parameters()) ptu.assert_allclose(actual, desired, rtol=1e-4) @skip_if_py38 @pytest.mark.flaky def test_default_transformer_epoch_optim_loop(optim_asset_loader): asset = optim_asset_loader("default_transformer_epoch_optim_loop") image_loader = asset.input.image_loader criterion = asset.input.perceptual_loss make_torch_ge_1_6_compatible(image_loader, criterion) transformer = asset.input.transformer optimizer = asset.params.get_optimizer(transformer) lr_scheduler = asset.params.get_lr_scheduler(optimizer) transformer = optim.multi_epoch_model_optimization( image_loader, transformer, criterion, asset.input.criterion_update_fn, asset.input.epochs, optimizer=optimizer, lr_scheduler=lr_scheduler, quiet=True, ) actual = tuple(transformer.parameters()) desired = tuple(asset.output.transformer.parameters()) ptu.assert_allclose(actual, desired, rtol=1e-4) class Dataset(data.Dataset): def __init__(self, image, supervised=False): if image.dim() == 4: image = image.squeeze(0) self.image = image self.supervised = supervised def __len__(self): return 1 def __getitem__(self, _): if self.supervised: return self.image, torch.zeros(self.image.size()[0]) else: return self.image @pytest.fixture def image_loader(test_image): return data.DataLoader(Dataset(test_image)) class TransformerMock(mocks.ModuleMock): def __init__(self): super().__init__() self.register_parameter( "parameter", nn.Parameter(torch.zeros(1).squeeze(), requires_grad=True) ) def forward(self, input, *args, **kwargs): return super().forward(input + self.parameter, *args, **kwargs) @pytest.fixture def transformer(): return TransformerMock() class CriterionMock(mocks.ModuleMock): def forward(self, *args, **kwargs): return torch.sum(super().forward(*args, **kwargs)) @pytest.fixture def criterion(): return CriterionMock() class MSEOperator(ops.PixelComparisonOperator): def image_to_repr(self, image): return image def input_image_to_repr( self, image, ctx, ): return image def target_image_to_repr(self, image): return image, None def calculate_score( self, input_repr, target_repr, ctx, ): return F.mse_loss(input_repr, target_repr) def test_model_default_optimization_criterion_update_fn( transformer, test_image, ): image_loader = data.DataLoader(Dataset(test_image)) content_loss = MSEOperator() style_loss = MSEOperator() criterion = loss.PerceptualLoss(content_loss, style_loss) content_loss.set_target_image(torch.rand_like(test_image)) style_loss.set_target_image(torch.rand_like(test_image)) optim.model_optimization(image_loader, transformer, criterion) ptu.assert_allclose(content_loss.target_image, test_image) def test_model_optimization_criterion_update_fn_error( image_loader, transformer, criterion ): with pytest.raises(RuntimeError): optim.model_optimization(image_loader, transformer, criterion) @pytest.mark.parametrize( "supervised", (True, False), ids=lambda supervised: f"{"" if supervised else "un"}supervised", ) def test_model_optimization_image_loader( transformer, criterion, test_image, supervised ): image_loader = data.DataLoader(Dataset(test_image, supervised=supervised)) optim.model_optimization( image_loader, transformer, criterion, criterion_update_fn=lambda input_image, criterion: None, ) transformer.assert_called_once_with(test_image)
import sys import pytest import pytorch_testing_utils as ptu import torch import torch.nn.functional as F from torch import nn from torch.utils import data from pystiche import loss, ops, optim from tests import mocks skip_if_py38 = pytest.mark.skipif( sys.version_info >= (3, 8), reason=( "Test errors on Python 3.8 only. This is most likely caused by the test " "itself rather than the code it should test." ), ) def test_default_image_optimizer(): torch.manual_seed(0) image = torch.rand(1, 3, 128, 128) optimizer = optim.default_image_optimizer(image) assert isinstance(optimizer, torch.optim.Optimizer) actual = optimizer.param_groups[0]["params"][0] desired = image ptu.assert_allclose(actual, desired) def test_image_optimization_optimizer_preprocessor(): input_image = torch.empty(1) criterion = nn.Module() optimizer = optim.default_image_optimizer(input_image) preprocessor = nn.Module() with pytest.raises(RuntimeError): optim.image_optimization( input_image, criterion, optimizer, preprocessor=preprocessor ) @skip_if_py38 @pytest.mark.flaky def test_default_image_optim_loop(optim_asset_loader): asset = optim_asset_loader("default_image_optim_loop") actual = optim.image_optimization( asset.input.image, asset.input.perceptual_loss, optimizer=asset.params.get_optimizer, num_steps=asset.params.num_steps, quiet=True, ) desired = asset.output.image ptu.assert_allclose(actual, desired, rtol=1e-4) @skip_if_py38 @pytest.mark.skip( "'pystiche.image.transforms' is needed to load the asset, " "but is no longer accessible." ) @pytest.mark.flaky def test_default_image_optim_loop_processing(optim_asset_loader): asset = optim_asset_loader("default_image_optim_loop_processing") actual = optim.image_optimization( asset.input.image, asset.input.perceptual_loss, optimizer=asset.params.get_optimizer, num_steps=asset.params.num_steps, preprocessor=asset.params.preprocessor, postprocessor=asset.params.postprocessor, quiet=True, ) desired = asset.output.image ptu.assert_allclose(actual, desired, rtol=1e-4) @skip_if_py38 @pytest.mark.flaky def test_default_image_pyramid_optim_loop(optim_asset_loader): asset = optim_asset_loader("default_image_pyramid_optim_loop") actual = optim.pyramid_image_optimization( asset.input.image, asset.input.perceptual_loss, asset.input.pyramid, get_optimizer=asset.params.get_optimizer, quiet=True, ) desired = asset.output.image ptu.assert_allclose(actual, desired, rtol=1e-4) @skip_if_py38 @pytest.mark.flaky def test_default_image_pyramid_optim_loop_processing(optim_asset_loader): asset = optim_asset_loader("default_image_pyramid_optim_loop") actual = optim.pyramid_image_optimization( asset.input.image, asset.input.perceptual_loss, asset.input.pyramid, get_optimizer=asset.params.get_optimizer, preprocessor=asset.params.preprocessor, postprocessor=asset.params.postprocessor, quiet=True, ) desired = asset.output.image ptu.assert_allclose(actual, desired, rtol=1e-4) def test_default_transformer_optimizer(): torch.manual_seed(0) transformer = nn.Conv2d(3, 3, 1) optimizer = optim.default_model_optimizer(transformer) assert isinstance(optimizer, torch.optim.Optimizer) actuals = optimizer.param_groups[0]["params"] desireds = tuple(transformer.parameters()) for actual, desired in zip(actuals, desireds): ptu.assert_allclose(actual, desired) def make_torch_ge_1_6_compatible(image_loader, criterion): # See https://github.com/pmeier/pystiche/pull/348 for a discussion of this image_loader.generator = None for module in criterion.modules(): module._non_persistent_buffers_set = set() @skip_if_py38 @pytest.mark.flaky def test_default_transformer_optim_loop(optim_asset_loader): asset = optim_asset_loader("default_transformer_optim_loop") image_loader = asset.input.image_loader criterion = asset.input.perceptual_loss make_torch_ge_1_6_compatible(image_loader, criterion) transformer = asset.input.transformer optimizer = asset.params.get_optimizer(transformer) transformer = optim.model_optimization( image_loader, transformer, criterion, asset.input.criterion_update_fn, optimizer=optimizer, quiet=True, ) actual = tuple(transformer.parameters()) desired = tuple(asset.output.transformer.parameters()) ptu.assert_allclose(actual, desired, rtol=1e-4) @skip_if_py38 @pytest.mark.flaky def test_default_transformer_epoch_optim_loop(optim_asset_loader): asset = optim_asset_loader("default_transformer_epoch_optim_loop") image_loader = asset.input.image_loader criterion = asset.input.perceptual_loss make_torch_ge_1_6_compatible(image_loader, criterion) transformer = asset.input.transformer optimizer = asset.params.get_optimizer(transformer) lr_scheduler = asset.params.get_lr_scheduler(optimizer) transformer = optim.multi_epoch_model_optimization( image_loader, transformer, criterion, asset.input.criterion_update_fn, asset.input.epochs, optimizer=optimizer, lr_scheduler=lr_scheduler, quiet=True, ) actual = tuple(transformer.parameters()) desired = tuple(asset.output.transformer.parameters()) ptu.assert_allclose(actual, desired, rtol=1e-4) class Dataset(data.Dataset): def __init__(self, image, supervised=False): if image.dim() == 4: image = image.squeeze(0) self.image = image self.supervised = supervised def __len__(self): return 1 def __getitem__(self, _): if self.supervised: return self.image, torch.zeros(self.image.size()[0]) else: return self.image @pytest.fixture def image_loader(test_image): return data.DataLoader(Dataset(test_image)) class TransformerMock(mocks.ModuleMock): def __init__(self): super().__init__() self.register_parameter( "parameter", nn.Parameter(torch.zeros(1).squeeze(), requires_grad=True) ) def forward(self, input, *args, **kwargs): return super().forward(input + self.parameter, *args, **kwargs) @pytest.fixture def transformer(): return TransformerMock() class CriterionMock(mocks.ModuleMock): def forward(self, *args, **kwargs): return torch.sum(super().forward(*args, **kwargs)) @pytest.fixture def criterion(): return CriterionMock() class MSEOperator(ops.PixelComparisonOperator): def image_to_repr(self, image): return image def input_image_to_repr( self, image, ctx, ): return image def target_image_to_repr(self, image): return image, None def calculate_score( self, input_repr, target_repr, ctx, ): return F.mse_loss(input_repr, target_repr) def test_model_default_optimization_criterion_update_fn( transformer, test_image, ): image_loader = data.DataLoader(Dataset(test_image)) content_loss = MSEOperator() style_loss = MSEOperator() criterion = loss.PerceptualLoss(content_loss, style_loss) content_loss.set_target_image(torch.rand_like(test_image)) style_loss.set_target_image(torch.rand_like(test_image)) optim.model_optimization(image_loader, transformer, criterion) ptu.assert_allclose(content_loss.target_image, test_image) def test_model_optimization_criterion_update_fn_error( image_loader, transformer, criterion ): with pytest.raises(RuntimeError): optim.model_optimization(image_loader, transformer, criterion) @pytest.mark.parametrize( "supervised", (True, False), ids=lambda supervised: f"{'' if supervised else 'un'}supervised", ) def test_model_optimization_image_loader( transformer, criterion, test_image, supervised ): image_loader = data.DataLoader(Dataset(test_image, supervised=supervised)) optim.model_optimization( image_loader, transformer, criterion, criterion_update_fn=lambda input_image, criterion: None, ) transformer.assert_called_once_with(test_image)
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the NiBabel package for the # copyright and license terms. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## """ Read / write access to NIfTI1 image format NIfTI1 format defined at http://nifti.nimh.nih.gov/nifti-1/ """ import warnings from io import BytesIO import numpy as np import numpy.linalg as npl from numpy.compat.py3k import asstr from .filebasedimages import SerializableImage from .volumeutils import Recoder, make_dt_codes, endian_codes from .spatialimages import HeaderDataError, ImageFileError from .batteryrunners import Report from .quaternions import fillpositive, quat2mat, mat2quat from . import analyze # module import from .spm99analyze import SpmAnalyzeHeader from .casting import have_binary128 from .pydicom_compat import have_dicom, pydicom as pdcm # nifti1 flat header definition for Analyze-like first 348 bytes # first number in comments indicates offset in file header in bytes header_dtd = [ ('sizeof_hdr', 'i4'), # 0; must be 348 ('data_type', 'S10'), # 4; unused ('db_name', 'S18'), # 14; unused ('extents', 'i4'), # 32; unused ('session_error', 'i2'), # 36; unused ('regular', 'S1'), # 38; unused ('dim_info', 'u1'), # 39; MRI slice ordering code ('dim', 'i2', (8,)), # 40; data array dimensions ('intent_p1', 'f4'), # 56; first intent parameter ('intent_p2', 'f4'), # 60; second intent parameter ('intent_p3', 'f4'), # 64; third intent parameter ('intent_code', 'i2'), # 68; NIFTI intent code ('datatype', 'i2'), # 70; it's the datatype ('bitpix', 'i2'), # 72; number of bits per voxel ('slice_start', 'i2'), # 74; first slice index ('pixdim', 'f4', (8,)), # 76; grid spacings (units below) ('vox_offset', 'f4'), # 108; offset to data in image file ('scl_slope', 'f4'), # 112; data scaling slope ('scl_inter', 'f4'), # 116; data scaling intercept ('slice_end', 'i2'), # 120; last slice index ('slice_code', 'u1'), # 122; slice timing order ('xyzt_units', 'u1'), # 123; units of pixdim[1..4] ('cal_max', 'f4'), # 124; max display intensity ('cal_min', 'f4'), # 128; min display intensity ('slice_duration', 'f4'), # 132; time for 1 slice ('toffset', 'f4'), # 136; time axis shift ('glmax', 'i4'), # 140; unused ('glmin', 'i4'), # 144; unused ('descrip', 'S80'), # 148; any text ('aux_file', 'S24'), # 228; auxiliary filename ('qform_code', 'i2'), # 252; xform code ('sform_code', 'i2'), # 254; xform code ('quatern_b', 'f4'), # 256; quaternion b param ('quatern_c', 'f4'), # 260; quaternion c param ('quatern_d', 'f4'), # 264; quaternion d param ('qoffset_x', 'f4'), # 268; quaternion x shift ('qoffset_y', 'f4'), # 272; quaternion y shift ('qoffset_z', 'f4'), # 276; quaternion z shift ('srow_x', 'f4', (4,)), # 280; 1st row affine transform ('srow_y', 'f4', (4,)), # 296; 2nd row affine transform ('srow_z', 'f4', (4,)), # 312; 3rd row affine transform ('intent_name', 'S16'), # 328; name or meaning of data ('magic', 'S4') # 344; must be 'ni1\0' or 'n+1\0' ] # Full header numpy dtype header_dtype = np.dtype(header_dtd) # datatypes not in analyze format, with codes if have_binary128(): # Only enable 128 bit floats if we really have IEEE binary 128 longdoubles _float128t = np.longdouble _complex256t = np.longcomplex else: _float128t = np.void _complex256t = np.void _dtdefs = ( # code, label, dtype definition, niistring (0, 'none', np.void, ""), (1, 'binary', np.void, ""), (2, 'uint8', np.uint8, "NIFTI_TYPE_UINT8"), (4, 'int16', np.int16, "NIFTI_TYPE_INT16"), (8, 'int32', np.int32, "NIFTI_TYPE_INT32"), (16, 'float32', np.float32, "NIFTI_TYPE_FLOAT32"), (32, 'complex64', np.complex64, "NIFTI_TYPE_COMPLEX64"), (64, 'float64', np.float64, "NIFTI_TYPE_FLOAT64"), (128, 'RGB', np.dtype([('R', 'u1'), ('G', 'u1'), ('B', 'u1')]), "NIFTI_TYPE_RGB24"), (255, 'all', np.void, ''), (256, 'int8', np.int8, "NIFTI_TYPE_INT8"), (512, 'uint16', np.uint16, "NIFTI_TYPE_UINT16"), (768, 'uint32', np.uint32, "NIFTI_TYPE_UINT32"), (1024, 'int64', np.int64, "NIFTI_TYPE_INT64"), (1280, 'uint64', np.uint64, "NIFTI_TYPE_UINT64"), (1536, 'float128', _float128t, "NIFTI_TYPE_FLOAT128"), (1792, 'complex128', np.complex128, "NIFTI_TYPE_COMPLEX128"), (2048, 'complex256', _complex256t, "NIFTI_TYPE_COMPLEX256"), (2304, 'RGBA', np.dtype([('R', 'u1'), ('G', 'u1'), ('B', 'u1'), ('A', 'u1')]), "NIFTI_TYPE_RGBA32"), ) # Make full code alias bank, including dtype column data_type_codes = make_dt_codes(_dtdefs) # Transform (qform, sform) codes xform_codes = Recoder(( # code, label, niistring (0, 'unknown', "NIFTI_XFORM_UNKNOWN"), (1, 'scanner', "NIFTI_XFORM_SCANNER_ANAT"), (2, 'aligned', "NIFTI_XFORM_ALIGNED_ANAT"), (3, 'talairach', "NIFTI_XFORM_TALAIRACH"), (4, 'mni', "NIFTI_XFORM_MNI_152"), (5, 'template', "NIFTI_XFORM_TEMPLATE_OTHER"), ), fields=('code', 'label', 'niistring')) # unit codes unit_codes = Recoder(( # code, label (0, 'unknown'), (1, 'meter'), (2, 'mm'), (3, 'micron'), (8, 'sec'), (16, 'msec'), (24, 'usec'), (32, 'hz'), (40, 'ppm'), (48, 'rads')), fields=('code', 'label')) slice_order_codes = Recoder(( # code, label (0, 'unknown'), (1, 'sequential increasing', 'seq inc'), (2, 'sequential decreasing', 'seq dec'), (3, 'alternating increasing', 'alt inc'), (4, 'alternating decreasing', 'alt dec'), (5, 'alternating increasing 2', 'alt inc 2'), (6, 'alternating decreasing 2', 'alt dec 2')), fields=('code', 'label')) intent_codes = Recoder(( # code, label, parameters description tuple (0, 'none', (), "NIFTI_INTENT_NONE"), (2, 'correlation', ('p1 = DOF',), "NIFTI_INTENT_CORREL"), (3, 't test', ('p1 = DOF',), "NIFTI_INTENT_TTEST"), (4, 'f test', ('p1 = numerator DOF', 'p2 = denominator DOF'), "NIFTI_INTENT_FTEST"), (5, 'z score', (), "NIFTI_INTENT_ZSCORE"), (6, 'chi2', ('p1 = DOF',), "NIFTI_INTENT_CHISQ"), # two parameter beta distribution (7, 'beta', ('p1=a', 'p2=b'), "NIFTI_INTENT_BETA"), # Prob(x) = (p1 choose x) * p2^x * (1-p2)^(p1-x), for x=0,1,...,p1 (8, 'binomial', ('p1 = number of trials', 'p2 = probability per trial'), "NIFTI_INTENT_BINOM"), # 2 parameter gamma # Density(x) proportional to # x^(p1-1) * exp(-p2*x) (9, 'gamma', ('p1 = shape, p2 = scale', 2), "NIFTI_INTENT_GAMMA"), (10, 'poisson', ('p1 = mean',), "NIFTI_INTENT_POISSON"), (11, 'normal', ('p1 = mean', 'p2 = standard deviation',), "NIFTI_INTENT_NORMAL"), (12, 'non central f test', ('p1 = numerator DOF', 'p2 = denominator DOF', 'p3 = numerator noncentrality parameter',), "NIFTI_INTENT_FTEST_NONC"), (13, 'non central chi2', ('p1 = DOF', 'p2 = noncentrality parameter',), "NIFTI_INTENT_CHISQ_NONC"), (14, 'logistic', ('p1 = location', 'p2 = scale',), "NIFTI_INTENT_LOGISTIC"), (15, 'laplace', ('p1 = location', 'p2 = scale'), "NIFTI_INTENT_LAPLACE"), (16, 'uniform', ('p1 = lower end', 'p2 = upper end'), "NIFTI_INTENT_UNIFORM"), (17, 'non central t test', ('p1 = DOF', 'p2 = noncentrality parameter'), "NIFTI_INTENT_TTEST_NONC"), (18, 'weibull', ('p1 = location', 'p2 = scale, p3 = power'), "NIFTI_INTENT_WEIBULL"), # p1 = 1 = 'half normal' distribution # p1 = 2 = Rayleigh distribution # p1 = 3 = Maxwell-Boltzmann distribution. (19, 'chi', ('p1 = DOF',), "NIFTI_INTENT_CHI"), (20, 'inverse gaussian', ('pi = mu', 'p2 = lambda'), "NIFTI_INTENT_INVGAUSS"), (21, 'extreme value 1', ('p1 = location', 'p2 = scale'), "NIFTI_INTENT_EXTVAL"), (22, 'p value', (), "NIFTI_INTENT_PVAL"), (23, 'log p value', (), "NIFTI_INTENT_LOGPVAL"), (24, 'log10 p value', (), "NIFTI_INTENT_LOG10PVAL"), (1001, 'estimate', (), "NIFTI_INTENT_ESTIMATE"), (1002, 'label', (), "NIFTI_INTENT_LABEL"), (1003, 'neuroname', (), "NIFTI_INTENT_NEURONAME"), (1004, 'general matrix', ('p1 = M', 'p2 = N'), "NIFTI_INTENT_GENMATRIX"), (1005, 'symmetric matrix', ('p1 = M',), "NIFTI_INTENT_SYMMATRIX"), (1006, 'displacement vector', (), "NIFTI_INTENT_DISPVECT"), (1007, 'vector', (), "NIFTI_INTENT_VECTOR"), (1008, 'pointset', (), "NIFTI_INTENT_POINTSET"), (1009, 'triangle', (), "NIFTI_INTENT_TRIANGLE"), (1010, 'quaternion', (), "NIFTI_INTENT_QUATERNION"), (1011, 'dimensionless', (), "NIFTI_INTENT_DIMLESS"), (2001, 'time series', (), "NIFTI_INTENT_TIME_SERIES", "NIFTI_INTENT_TIMESERIES"), # this mis-spell occurs in the wild (2002, 'node index', (), "NIFTI_INTENT_NODE_INDEX"), (2003, 'rgb vector', (), "NIFTI_INTENT_RGB_VECTOR"), (2004, 'rgba vector', (), "NIFTI_INTENT_RGBA_VECTOR"), (2005, 'shape', (), "NIFTI_INTENT_SHAPE"), # FSL-specific intent codes - codes used by FNIRT # ($FSLDIR/warpfns/fnirt_file_reader.h:104) (2006, 'fnirt disp field', (), 'FSL_FNIRT_DISPLACEMENT_FIELD'), (2007, 'fnirt cubic spline coef', (), 'FSL_CUBIC_SPLINE_COEFFICIENTS'), (2008, 'fnirt dct coef', (), 'FSL_DCT_COEFFICIENTS'), (2009, 'fnirt quad spline coef', (), 'FSL_QUADRATIC_SPLINE_COEFFICIENTS'), # FSL-specific intent codes - codes used by TOPUP # ($FSLDIR/topup/topup_file_io.h:104) (2016, 'topup cubic spline coef ', (), 'FSL_TOPUP_CUBIC_SPLINE_COEFFICIENTS'), (2017, 'topup quad spline coef', (), 'FSL_TOPUP_QUADRATIC_SPLINE_COEFFICIENTS'), (2018, 'topup field', (), 'FSL_TOPUP_FIELD'), ), fields=('code', 'label', 'parameters', 'niistring')) class Nifti1Extension(object): """Baseclass for NIfTI1 header extensions. This class is sufficient to handle very simple text-based extensions, such as `comment`. More sophisticated extensions should/will be supported by dedicated subclasses. """ def __init__(self, code, content): """ Parameters ---------- code : int or str Canonical extension code as defined in the NIfTI standard, given either as integer or corresponding label (see :data:`~nibabel.nifti1.extension_codes`) content : str Extension content as read from the NIfTI file header. This content is converted into a runtime representation. """ try: self._code = extension_codes.code[code] except KeyError: # XXX or fail or at least complain? self._code = code self._content = self._unmangle(content) def _unmangle(self, value): """Convert the extension content into its runtime representation. The default implementation does nothing at all. Parameters ---------- value : str Extension content as read from file. Returns ------- The same object that was passed as `value`. Notes ----- Subclasses should reimplement this method to provide the desired unmangling procedure and may return any type of object. """ return value def _mangle(self, value): """Convert the extension content into NIfTI file header representation. The default implementation does nothing at all. Parameters ---------- value : str Extension content in runtime form. Returns ------- str Notes ----- Subclasses should reimplement this method to provide the desired mangling procedure. """ return value def get_code(self): """Return the canonical extension type code.""" return self._code def get_content(self): """Return the extension content in its runtime representation.""" return self._content def get_sizeondisk(self): """Return the size of the extension in the NIfTI file. """ # need raw value size plus 8 bytes for esize and ecode size = len(self._mangle(self._content)) size += 8 # extensions size has to be a multiple of 16 bytes if size % 16 != 0: size += 16 - (size % 16) return size def __repr__(self): try: code = extension_codes.label[self._code] except KeyError: # deal with unknown codes code = self._code s = f"Nifti1Extension('{code}', '{self._content}')" return s def __eq__(self, other): return (self._code, self._content) == (other._code, other._content) def __ne__(self, other): return not self == other def write_to(self, fileobj, byteswap): """ Write header extensions to fileobj Write starts at fileobj current file position. Parameters ---------- fileobj : file-like object Should implement ``write`` method byteswap : boolean Flag if byteswapping the data is required. Returns ------- None """ extstart = fileobj.tell() rawsize = self.get_sizeondisk() # write esize and ecode first extinfo = np.array((rawsize, self._code), dtype=np.int32) if byteswap: extinfo = extinfo.byteswap() fileobj.write(extinfo.tobytes()) # followed by the actual extension content # XXX if mangling upon load is implemented, it should be reverted here fileobj.write(self._mangle(self._content)) # be nice and zero out remaining part of the extension till the # next 16 byte border fileobj.write(b'\x00' * (extstart + rawsize - fileobj.tell())) class Nifti1DicomExtension(Nifti1Extension): """NIfTI1 DICOM header extension This class is a thin wrapper around pydicom to read a binary DICOM byte string. If pydicom is available, content is exposed as a Dicom Dataset. Otherwise, this silently falls back to the standard NiftiExtension class and content is the raw bytestring loaded directly from the nifti file header. """ def __init__(self, code, content, parent_hdr=None): """ Parameters ---------- code : int or str Canonical extension code as defined in the NIfTI standard, given either as integer or corresponding label (see :data:`~nibabel.nifti1.extension_codes`) content : bytes or pydicom Dataset or None Extension content - either a bytestring as read from the NIfTI file header or an existing pydicom Dataset. If a bystestring, the content is converted into a Dataset on initialization. If None, a new empty Dataset is created. parent_hdr : :class:`~nibabel.nifti1.Nifti1Header`, optional If a dicom extension belongs to an existing :class:`~nibabel.nifti1.Nifti1Header`, it may be provided here to ensure that the DICOM dataset is written with correctly corresponding endianness; otherwise it is assumed the dataset is little endian. Notes ----- code should always be 2 for DICOM. """ self._code = code if parent_hdr: self._is_little_endian = parent_hdr.endianness == '<' else: self._is_little_endian = True if isinstance(content, pdcm.dataset.Dataset): self._is_implicit_VR = False self._raw_content = self._mangle(content) self._content = content elif isinstance(content, bytes): # Got a byte string - unmangle it self._raw_content = content self._is_implicit_VR = self._guess_implicit_VR() ds = self._unmangle(content, self._is_implicit_VR, self._is_little_endian) self._content = ds elif content is None: # initialize a new dicom dataset self._is_implicit_VR = False self._content = pdcm.dataset.Dataset() else: raise TypeError(f"content must be either a bytestring or a pydicom Dataset. " f"Got {content.__class__}") def _guess_implicit_VR(self): """Try to guess DICOM syntax by checking for valid VRs. Without a DICOM Transfer Syntax, it's difficult to tell if Value Representations (VRs) are included in the DICOM encoding or not. This reads where the first VR would be and checks it against a list of valid VRs """ potential_vr = self._raw_content[4:6].decode() if potential_vr in pdcm.values.converters.keys(): implicit_VR = False else: implicit_VR = True return implicit_VR def _unmangle(self, value, is_implicit_VR=False, is_little_endian=True): bio = BytesIO(value) ds = pdcm.filereader.read_dataset(bio, is_implicit_VR, is_little_endian) return ds def _mangle(self, dataset): bio = BytesIO() dio = pdcm.filebase.DicomFileLike(bio) dio.is_implicit_VR = self._is_implicit_VR dio.is_little_endian = self._is_little_endian ds_len = pdcm.filewriter.write_dataset(dio, dataset) dio.seek(0) return dio.read(ds_len) # NIfTI header extension type codes (ECODE) # see nifti1_io.h for a complete list of all known extensions and # references to their description or contacts of the respective # initiators extension_codes = Recoder(( (0, "ignore", Nifti1Extension), (2, "dicom", Nifti1DicomExtension if have_dicom else Nifti1Extension), (4, "afni", Nifti1Extension), (6, "comment", Nifti1Extension), (8, "xcede", Nifti1Extension), (10, "jimdiminfo", Nifti1Extension), (12, "workflow_fwds", Nifti1Extension), (14, "freesurfer", Nifti1Extension), (16, "pypickle", Nifti1Extension), ), fields=('code', 'label', 'handler')) class Nifti1Extensions(list): """Simple extension collection, implemented as a list-subclass. """ def count(self, ecode): """Returns the number of extensions matching a given *ecode*. Parameters ---------- code : int | str The ecode can be specified either literal or as numerical value. """ count = 0 code = extension_codes.code[ecode] for e in self: if e.get_code() == code: count += 1 return count def get_codes(self): """Return a list of the extension code of all available extensions""" return [e.get_code() for e in self] def get_sizeondisk(self): """Return the size of the complete header extensions in the NIfTI file. """ return np.sum([e.get_sizeondisk() for e in self]) def __repr__(self): return "Nifti1Extensions(%s)" % ', '.join(str(e) for e in self) def __cmp__(self, other): return cmp(list(self), list(other)) def write_to(self, fileobj, byteswap): """ Write header extensions to fileobj Write starts at fileobj current file position. Parameters ---------- fileobj : file-like object Should implement ``write`` method byteswap : boolean Flag if byteswapping the data is required. Returns ------- None """ for e in self: e.write_to(fileobj, byteswap) @classmethod def from_fileobj(klass, fileobj, size, byteswap): """Read header extensions from a fileobj Parameters ---------- fileobj : file-like object We begin reading the extensions at the current file position size : int Number of bytes to read. If negative, fileobj will be read till its end. byteswap : boolean Flag if byteswapping the read data is required. Returns ------- An extension list. This list might be empty in case not extensions were present in fileobj. """ # make empty extension list extensions = klass() # assume the file pointer is at the beginning of any extensions. # read until the whole header is parsed (each extension is a multiple # of 16 bytes) or in case of a separate header file till the end # (break inside the body) while size >= 16 or size < 0: # the next 8 bytes should have esize and ecode ext_def = fileobj.read(8) # nothing was read and instructed to read till the end # -> assume all extensions where parsed and break if not len(ext_def) and size < 0: break # otherwise there should be a full extension header if not len(ext_def) == 8: raise HeaderDataError('failed to read extension header') ext_def = np.frombuffer(ext_def, dtype=np.int32) if byteswap: ext_def = ext_def.byteswap() # be extra verbose ecode = ext_def[1] esize = ext_def[0] if esize % 16: warnings.warn( 'Extension size is not a multiple of 16 bytes; ' 'Assuming size is correct and hoping for the best', UserWarning) # read extension itself; esize includes the 8 bytes already read evalue = fileobj.read(int(esize - 8)) if not len(evalue) == esize - 8: raise HeaderDataError('failed to read extension content') # note that we read a full extension size -= esize # store raw extension content, but strip trailing NULL chars evalue = evalue.rstrip(b'\x00') # 'extension_codes' also knows the best implementation to handle # a particular extension type try: ext = extension_codes.handler[ecode](ecode, evalue) except KeyError: # unknown extension type # XXX complain or fail or go with a generic extension ext = Nifti1Extension(ecode, evalue) extensions.append(ext) return extensions class Nifti1Header(SpmAnalyzeHeader): """ Class for NIfTI1 header The NIfTI1 header has many more coded fields than the simpler Analyze variants. NIfTI1 headers also have extensions. Nifti allows the header to be a separate file, as part of a nifti image / header pair, or to precede the data in a single file. The object needs to know which type it is, in order to manage the voxel offset pointing to the data, extension reading, and writing the correct magic string. This class handles the header-preceding-data case. """ # Copies of module level definitions template_dtype = header_dtype _data_type_codes = data_type_codes # fields with recoders for their values _field_recoders = {'datatype': data_type_codes, 'qform_code': xform_codes, 'sform_code': xform_codes, 'intent_code': intent_codes, 'slice_code': slice_order_codes} # data scaling capabilities has_data_slope = True has_data_intercept = True # Extension class; should implement __call__ for construction, and # ``from_fileobj`` for reading from file exts_klass = Nifti1Extensions # Signal whether this is single (header + data) file is_single = True # Default voxel data offsets for single and pair pair_vox_offset = 0 single_vox_offset = 352 # Magics for single and pair pair_magic = b'ni1' single_magic = b'n+1' # Quaternion threshold near 0, based on float32 precision quaternion_threshold = -np.finfo(np.float32).eps * 3 def __init__(self, binaryblock=None, endianness=None, check=True, extensions=()): """ Initialize header from binary data block and extensions """ super(Nifti1Header, self).__init__(binaryblock, endianness, check) self.extensions = self.exts_klass(extensions) def copy(self): """ Return copy of header Take reference to extensions as well as copy of header contents """ return self.__class__( self.binaryblock, self.endianness, False, self.extensions) @classmethod def from_fileobj(klass, fileobj, endianness=None, check=True): raw_str = fileobj.read(klass.template_dtype.itemsize) hdr = klass(raw_str, endianness, check) # Read next 4 bytes to see if we have extensions. The nifti standard # has this as a 4 byte string; if the first value is not zero, then we # have extensions. extension_status = fileobj.read(4) # Need to test *slice* of extension_status to preserve byte string type # on Python 3 if len(extension_status) < 4 or extension_status[0:1] == b'\x00': return hdr # If this is a detached header file read to end if not klass.is_single: extsize = -1 else: # otherwise read until the beginning of the data extsize = hdr._structarr['vox_offset'] - fileobj.tell() byteswap = endian_codes['native'] != hdr.endianness hdr.extensions = klass.exts_klass.from_fileobj(fileobj, extsize, byteswap) return hdr def write_to(self, fileobj): # First check that vox offset is large enough; set if necessary if self.is_single: vox_offset = self._structarr['vox_offset'] min_vox_offset = (self.single_vox_offset + self.extensions.get_sizeondisk()) if vox_offset == 0: # vox offset unset; set as necessary self._structarr['vox_offset'] = min_vox_offset elif vox_offset < min_vox_offset: raise HeaderDataError( f'vox offset set to {vox_offset}, but need at least {min_vox_offset}') super(Nifti1Header, self).write_to(fileobj) # Write extensions if len(self.extensions) == 0: # If single file, write required 0 stream to signal no extensions if self.is_single: fileobj.write(b'\x00' * 4) return # Signal there are extensions that follow fileobj.write(b'\x01\x00\x00\x00') byteswap = endian_codes['native'] != self.endianness self.extensions.write_to(fileobj, byteswap) def get_best_affine(self): """ Select best of available transforms """ hdr = self._structarr if hdr['sform_code'] != 0: return self.get_sform() if hdr['qform_code'] != 0: return self.get_qform() return self.get_base_affine() @classmethod def default_structarr(klass, endianness=None): """ Create empty header binary block with given endianness """ hdr_data = super(Nifti1Header, klass).default_structarr(endianness) if klass.is_single: hdr_data['magic'] = klass.single_magic else: hdr_data['magic'] = klass.pair_magic return hdr_data @classmethod def from_header(klass, header=None, check=True): """ Class method to create header from another header Extend Analyze header copy by copying extensions from other Nifti types. Parameters ---------- header : ``Header`` instance or mapping a header of this class, or another class of header for conversion to this type check : {True, False} whether to check header for integrity Returns ------- hdr : header instance fresh header instance of our own class """ new_hdr = super(Nifti1Header, klass).from_header(header, check) if isinstance(header, Nifti1Header): new_hdr.extensions[:] = header.extensions[:] return new_hdr def get_data_shape(self): """ Get shape of data Examples -------- >>> hdr = Nifti1Header() >>> hdr.get_data_shape() (0,) >>> hdr.set_data_shape((1,2,3)) >>> hdr.get_data_shape() (1, 2, 3) Expanding number of dimensions gets default zooms >>> hdr.get_zooms() (1.0, 1.0, 1.0) Notes ----- Applies freesurfer hack for large vectors described in `issue 100`_ and `save_nifti.m <save77_>`_. Allows for freesurfer hack for 7th order icosahedron surface described in `issue 309`_, load_nifti.m_, and `save_nifti.m <save50_>`_. """ shape = super(Nifti1Header, self).get_data_shape() # Apply freesurfer hack for large vectors if shape[:3] == (-1, 1, 1): vec_len = int(self._structarr['glmin']) if vec_len == 0: raise HeaderDataError('-1 in dim[1] but 0 in glmin; ' 'inconsistent freesurfer type header?') return (vec_len, 1, 1) + shape[3:] # Apply freesurfer hack for ico7 surface elif shape[:3] == (27307, 1, 6): return (163842, 1, 1) + shape[3:] else: # Normal case return shape def set_data_shape(self, shape): """ Set shape of data # noqa If ``ndims == len(shape)`` then we set zooms for dimensions higher than ``ndims`` to 1.0 Nifti1 images can have up to seven dimensions. For FreeSurfer-variant Nifti surface files, the first dimension is assumed to correspond to vertices/nodes on a surface, and dimensions two and three are constrained to have depth of 1. Dimensions 4-7 are constrained only by type bounds. Parameters ---------- shape : sequence sequence of integers specifying data array shape Notes ----- Applies freesurfer hack for large vectors described in `issue 100`_ and `save_nifti.m <save77_>`_. Allows for freesurfer hack for 7th order icosahedron surface described in `issue 309`_, load_nifti.m_, and `save_nifti.m <save50_>`_. The Nifti1 `standard header`_ allows for the following "point set" definition of a surface, not currently implemented in nibabel. :: To signify that the vector value at each voxel is really a spatial coordinate (e.g., the vertices or nodes of a surface mesh): - dataset must have a 5th dimension - intent_code must be NIFTI_INTENT_POINTSET - dim[0] = 5 - dim[1] = number of points - dim[2] = dim[3] = dim[4] = 1 - dim[5] must be the dimensionality of space (e.g., 3 => 3D space). - intent_name may describe the object these points come from (e.g., "pial", "gray/white" , "EEG", "MEG"). .. _issue 100: https://github.com/nipy/nibabel/issues/100 .. _issue 309: https://github.com/nipy/nibabel/issues/309 .. _save77: https://github.com/fieldtrip/fieldtrip/blob/428798b/external/freesurfer/save_nifti.m#L77-L82 .. _save50: https://github.com/fieldtrip/fieldtrip/blob/428798b/external/freesurfer/save_nifti.m#L50-L56 .. _load_nifti.m: https://github.com/fieldtrip/fieldtrip/blob/428798b/external/freesurfer/load_nifti.m#L86-L89 .. _standard header: http://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1.h """ hdr = self._structarr shape = tuple(shape) # Apply freesurfer hack for ico7 surface if shape[:3] == (163842, 1, 1): shape = (27307, 1, 6) + shape[3:] # Apply freesurfer hack for large vectors elif (len(shape) >= 3 and shape[1:3] == (1, 1) and shape[0] > np.iinfo(hdr['dim'].dtype.base).max): try: hdr['glmin'] = shape[0] except OverflowError: overflow = True else: overflow = hdr['glmin'] != shape[0] if overflow: raise HeaderDataError(f'shape[0] {shape[0]} does not fit in glmax datatype') warnings.warn('Using large vector Freesurfer hack; header will ' 'not be compatible with SPM or FSL', stacklevel=2) shape = (-1, 1, 1) + shape[3:] super(Nifti1Header, self).set_data_shape(shape) def get_qform_quaternion(self): """ Compute quaternion from b, c, d of quaternion Fills a value by assuming this is a unit quaternion """ hdr = self._structarr bcd = [hdr['quatern_b'], hdr['quatern_c'], hdr['quatern_d']] # Adjust threshold to precision of stored values in header return fillpositive(bcd, self.quaternion_threshold) def get_qform(self, coded=False): """ Return 4x4 affine matrix from qform parameters in header Parameters ---------- coded : bool, optional If True, return {affine or None}, and qform code. If False, just return affine. {affine or None} means, return None if qform code == 0, and affine otherwise. Returns ------- affine : None or (4,4) ndarray If `coded` is False, always return affine reconstructed from qform quaternion. If `coded` is True, return None if qform code is 0, else return the affine. code : int Qform code. Only returned if `coded` is True. """ hdr = self._structarr code = int(hdr['qform_code']) if code == 0 and coded: return None, 0 quat = self.get_qform_quaternion() R = quat2mat(quat) vox = hdr['pixdim'][1:4].copy() if np.any(vox < 0): raise HeaderDataError('pixdims[1,2,3] should be positive') qfac = hdr['pixdim'][0] if qfac not in (-1, 1): raise HeaderDataError('qfac (pixdim[0]) should be 1 or -1') vox[-1] *= qfac S = np.diag(vox) M = np.dot(R, S) out = np.eye(4) out[0:3, 0:3] = M out[0:3, 3] = [hdr['qoffset_x'], hdr['qoffset_y'], hdr['qoffset_z']] if coded: return out, code return out def set_qform(self, affine, code=None, strip_shears=True): """ Set qform header values from 4x4 affine Parameters ---------- affine : None or 4x4 array affine transform to write into sform. If None, only set code. code : None, string or integer, optional String or integer giving meaning of transform in *affine*. The default is None. If code is None, then: * If affine is None, `code`-> 0 * If affine not None and existing qform code in header == 0, `code`-> 2 (aligned) * If affine not None and existing qform code in header != 0, `code`-> existing qform code in header strip_shears : bool, optional Whether to strip shears in `affine`. If True, shears will be silently stripped. If False, the presence of shears will raise a ``HeaderDataError`` Notes ----- The qform transform only encodes translations, rotations and zooms. If there are shear components to the `affine` transform, and `strip_shears` is True (the default), the written qform gives the closest approximation where the rotation matrix is orthogonal. This is to allow quaternion representation. The orthogonal representation enforces orthogonal axes. Examples -------- >>> hdr = Nifti1Header() >>> int(hdr['qform_code']) # gives 0 - unknown 0 >>> affine = np.diag([1,2,3,1]) >>> np.all(hdr.get_qform() == affine) False >>> hdr.set_qform(affine) >>> np.all(hdr.get_qform() == affine) True >>> int(hdr['qform_code']) # gives 2 - aligned 2 >>> hdr.set_qform(affine, code='talairach') >>> int(hdr['qform_code']) 3 >>> hdr.set_qform(affine, code=None) >>> int(hdr['qform_code']) 3 >>> hdr.set_qform(affine, code='scanner') >>> int(hdr['qform_code']) 1 >>> hdr.set_qform(None) >>> int(hdr['qform_code']) 0 """ hdr = self._structarr old_code = hdr['qform_code'] if code is None: if affine is None: code = 0 elif old_code == 0: code = 2 # aligned else: code = old_code else: # code set code = self._field_recoders['qform_code'][code] hdr['qform_code'] = code if affine is None: return affine = np.asarray(affine) if not affine.shape == (4, 4): raise TypeError('Need 4x4 affine as input') trans = affine[:3, 3] RZS = affine[:3, :3] zooms = np.sqrt(np.sum(RZS * RZS, axis=0)) R = RZS / zooms # Set qfac to make R determinant positive if npl.det(R) > 0: qfac = 1 else: qfac = -1 R[:, -1] *= -1 # Make R orthogonal (to allow quaternion representation) # The orthogonal representation enforces orthogonal axes # (a subtle requirement of the NIFTI format qform transform) # Transform below is polar decomposition, returning the closest # orthogonal matrix PR, to input R P, S, Qs = npl.svd(R) PR = np.dot(P, Qs) if not strip_shears and not np.allclose(PR, R): raise HeaderDataError("Shears in affine and `strip_shears` is " "False") # Convert to quaternion quat = mat2quat(PR) # Set into header hdr['qoffset_x'], hdr['qoffset_y'], hdr['qoffset_z'] = trans hdr['pixdim'][0] = qfac hdr['pixdim'][1:4] = zooms hdr['quatern_b'], hdr['quatern_c'], hdr['quatern_d'] = quat[1:] def get_sform(self, coded=False): """ Return 4x4 affine matrix from sform parameters in header Parameters ---------- coded : bool, optional If True, return {affine or None}, and sform code. If False, just return affine. {affine or None} means, return None if sform code == 0, and affine otherwise. Returns ------- affine : None or (4,4) ndarray If `coded` is False, always return affine from sform fields. If `coded` is True, return None if sform code is 0, else return the affine. code : int Sform code. Only returned if `coded` is True. """ hdr = self._structarr code = int(hdr['sform_code']) if code == 0 and coded: return None, 0 out = np.eye(4) out[0, :] = hdr['srow_x'][:] out[1, :] = hdr['srow_y'][:] out[2, :] = hdr['srow_z'][:] if coded: return out, code return out def set_sform(self, affine, code=None): """ Set sform transform from 4x4 affine Parameters ---------- affine : None or 4x4 array affine transform to write into sform. If None, only set `code` code : None, string or integer, optional String or integer giving meaning of transform in *affine*. The default is None. If code is None, then: * If affine is None, `code`-> 0 * If affine not None and existing sform code in header == 0, `code`-> 2 (aligned) * If affine not None and existing sform code in header != 0, `code`-> existing sform code in header Examples -------- >>> hdr = Nifti1Header() >>> int(hdr['sform_code']) # gives 0 - unknown 0 >>> affine = np.diag([1,2,3,1]) >>> np.all(hdr.get_sform() == affine) False >>> hdr.set_sform(affine) >>> np.all(hdr.get_sform() == affine) True >>> int(hdr['sform_code']) # gives 2 - aligned 2 >>> hdr.set_sform(affine, code='talairach') >>> int(hdr['sform_code']) 3 >>> hdr.set_sform(affine, code=None) >>> int(hdr['sform_code']) 3 >>> hdr.set_sform(affine, code='scanner') >>> int(hdr['sform_code']) 1 >>> hdr.set_sform(None) >>> int(hdr['sform_code']) 0 """ hdr = self._structarr old_code = hdr['sform_code'] if code is None: if affine is None: code = 0 elif old_code == 0: code = 2 # aligned else: code = old_code else: # code set code = self._field_recoders['sform_code'][code] hdr['sform_code'] = code if affine is None: return affine = np.asarray(affine) hdr['srow_x'][:] = affine[0, :] hdr['srow_y'][:] = affine[1, :] hdr['srow_z'][:] = affine[2, :] def get_slope_inter(self): """ Get data scaling (slope) and DC offset (intercept) from header data Returns ------- slope : None or float scaling (slope). None if there is no valid scaling from these fields inter : None or float offset (intercept). None if there is no valid scaling or if offset is not finite. Examples -------- >>> hdr = Nifti1Header() >>> hdr.get_slope_inter() (1.0, 0.0) >>> hdr['scl_slope'] = 0 >>> hdr.get_slope_inter() (None, None) >>> hdr['scl_slope'] = np.nan >>> hdr.get_slope_inter() (None, None) >>> hdr['scl_slope'] = 1 >>> hdr['scl_inter'] = 1 >>> hdr.get_slope_inter() (1.0, 1.0) >>> hdr['scl_inter'] = np.inf >>> hdr.get_slope_inter() #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... HeaderDataError: Valid slope but invalid intercept inf """ # Note that we are returning float (float64) scalefactors and # intercepts, although they are stored as in nifti1 as float32. slope = float(self['scl_slope']) inter = float(self['scl_inter']) if slope == 0 or not np.isfinite(slope): return None, None if not np.isfinite(inter): raise HeaderDataError(f'Valid slope but invalid intercept {inter}') return slope, inter def set_slope_inter(self, slope, inter=None): """ Set slope and / or intercept into header Set slope and intercept for image data, such that, if the image data is ``arr``, then the scaled image data will be ``(arr * slope) + inter`` (`slope`, `inter`) of (NaN, NaN) is a signal to a containing image to set `slope`, `inter` automatically on write. Parameters ---------- slope : None or float If None, implies `slope` of NaN. If `slope` is None or NaN then `inter` should be None or NaN. Values of 0, Inf or -Inf raise HeaderDataError inter : None or float, optional Intercept. If None, implies `inter` of NaN. If `slope` is None or NaN then `inter` should be None or NaN. Values of Inf or -Inf raise HeaderDataError """ if slope is None: slope = np.nan if inter is None: inter = np.nan if slope in (0, np.inf, -np.inf): raise HeaderDataError('Slope cannot be 0 or infinite') if inter in (np.inf, -np.inf): raise HeaderDataError('Intercept cannot be infinite') if np.isnan(slope) ^ np.isnan(inter): raise HeaderDataError('None or both of slope, inter should be nan') self._structarr['scl_slope'] = slope self._structarr['scl_inter'] = inter def get_dim_info(self): """ Gets NIfTI MRI slice etc dimension information Returns ------- freq : {None,0,1,2} Which data array axis is frequency encode direction phase : {None,0,1,2} Which data array axis is phase encode direction slice : {None,0,1,2} Which data array axis is slice encode direction where ``data array`` is the array returned by ``get_data`` Because NIfTI1 files are natively Fortran indexed: 0 is fastest changing in file 1 is medium changing in file 2 is slowest changing in file ``None`` means the axis appears not to be specified. Examples -------- See set_dim_info function """ hdr = self._structarr info = int(hdr['dim_info']) freq = info & 3 phase = (info >> 2) & 3 slice = (info >> 4) & 3 return (freq - 1 if freq else None, phase - 1 if phase else None, slice - 1 if slice else None) def set_dim_info(self, freq=None, phase=None, slice=None): """ Sets nifti MRI slice etc dimension information Parameters ---------- freq : {None, 0, 1, 2} axis of data array referring to frequency encoding phase : {None, 0, 1, 2} axis of data array referring to phase encoding slice : {None, 0, 1, 2} axis of data array referring to slice encoding ``None`` means the axis is not specified. Examples -------- >>> hdr = Nifti1Header() >>> hdr.set_dim_info(1, 2, 0) >>> hdr.get_dim_info() (1, 2, 0) >>> hdr.set_dim_info(freq=1, phase=2, slice=0) >>> hdr.get_dim_info() (1, 2, 0) >>> hdr.set_dim_info() >>> hdr.get_dim_info() (None, None, None) >>> hdr.set_dim_info(freq=1, phase=None, slice=0) >>> hdr.get_dim_info() (1, None, 0) Notes ----- This is stored in one byte in the header """ for inp in (freq, phase, slice): # Don't use == on None to avoid a FutureWarning in python3 if inp is not None and inp not in (0, 1, 2): raise HeaderDataError('Inputs must be in [None, 0, 1, 2]') info = 0 if freq is not None: info = info | ((freq + 1) & 3) if phase is not None: info = info | (((phase + 1) & 3) << 2) if slice is not None: info = info | (((slice + 1) & 3) << 4) self._structarr['dim_info'] = info def get_intent(self, code_repr='label'): """ Get intent code, parameters and name Parameters ---------- code_repr : string string giving output form of intent code representation. Default is 'label'; use 'code' for integer representation. Returns ------- code : string or integer intent code, or string describing code parameters : tuple parameters for the intent name : string intent name Examples -------- >>> hdr = Nifti1Header() >>> hdr.set_intent('t test', (10,), name='some score') >>> hdr.get_intent() ('t test', (10.0,), 'some score') >>> hdr.get_intent('code') (3, (10.0,), 'some score') """ hdr = self._structarr recoder = self._field_recoders['intent_code'] code = int(hdr['intent_code']) known_intent = code in recoder if code_repr == 'code': label = code elif code_repr == 'label': if known_intent: label = recoder.label[code] else: label = 'unknown code ' + str(code) else: raise TypeError('repr can be "label" or "code"') n_params = len(recoder.parameters[code]) if known_intent else 0 params = (float(hdr['intent_p%d' % (i + 1)]) for i in range(n_params)) name = asstr(hdr['intent_name'].item()) return label, tuple(params), name def set_intent(self, code, params=(), name='', allow_unknown=False): """ Set the intent code, parameters and name If parameters are not specified, assumed to be all zero. Each intent code has a set number of parameters associated. If you specify any parameters, then it will need to be the correct number (e.g the "f test" intent requires 2). However, parameters can also be set in the file data, so we also allow not setting any parameters (empty parameter tuple). Parameters ---------- code : integer or string code specifying nifti intent params : list, tuple of scalars parameters relating to intent (see intent_codes) defaults to (). Unspecified parameters are set to 0.0 name : string intent name (description). Defaults to '' allow_unknown : {False, True}, optional Allow unknown integer intent codes. If False (the default), a KeyError is raised on attempts to set the intent to an unknown code. Returns ------- None Examples -------- >>> hdr = Nifti1Header() >>> hdr.set_intent(0) # no intent >>> hdr.set_intent('z score') >>> hdr.get_intent() ('z score', (), '') >>> hdr.get_intent('code') (5, (), '') >>> hdr.set_intent('t test', (10,), name='some score') >>> hdr.get_intent() ('t test', (10.0,), 'some score') >>> hdr.set_intent('f test', (2, 10), name='another score') >>> hdr.get_intent() ('f test', (2.0, 10.0), 'another score') >>> hdr.set_intent('f test') >>> hdr.get_intent() ('f test', (0.0, 0.0), '') >>> hdr.set_intent(9999, allow_unknown=True) # unknown code >>> hdr.get_intent() ('unknown code 9999', (), '') """ hdr = self._structarr known_intent = code in intent_codes if not known_intent: # We can set intent via an unknown integer code, but can't via an # unknown string label if not allow_unknown or isinstance(code, str): raise KeyError('Unknown intent code: ' + str(code)) if known_intent: icode = intent_codes.code[code] p_descr = intent_codes.parameters[code] else: icode = code p_descr = ('p1', 'p2', 'p3') if len(params) and len(params) != len(p_descr): raise HeaderDataError(f'Need params of form {p_descr}, or empty') hdr['intent_code'] = icode hdr['intent_name'] = name all_params = [0] * 3 all_params[:len(params)] = params[:] for i, param in enumerate(all_params): hdr['intent_p%d' % (i + 1)] = param def get_slice_duration(self): """ Get slice duration Returns ------- slice_duration : float time to acquire one slice Examples -------- >>> hdr = Nifti1Header() >>> hdr.set_dim_info(slice=2) >>> hdr.set_slice_duration(0.3) >>> print("%0.1f" % hdr.get_slice_duration()) 0.3 Notes ----- The NIfTI1 spec appears to require the slice dimension to be defined for slice_duration to have meaning. """ _, _, slice_dim = self.get_dim_info() if slice_dim is None: raise HeaderDataError('Slice dimension must be set ' 'for duration to be valid') return float(self._structarr['slice_duration']) def set_slice_duration(self, duration): """ Set slice duration Parameters ---------- duration : scalar time to acquire one slice Examples -------- See ``get_slice_duration`` """ _, _, slice_dim = self.get_dim_info() if slice_dim is None: raise HeaderDataError('Slice dimension must be set ' 'for duration to be valid') self._structarr['slice_duration'] = duration def get_n_slices(self): """ Return the number of slices """ _, _, slice_dim = self.get_dim_info() if slice_dim is None: raise HeaderDataError('Slice dimension not set in header ' 'dim_info') shape = self.get_data_shape() try: slice_len = shape[slice_dim] except IndexError: raise HeaderDataError(f'Slice dimension index ({slice_dim}) ' f'outside shape tuple ({shape})') return slice_len def get_slice_times(self): """ Get slice times from slice timing information Returns ------- slice_times : tuple Times of acquisition of slices, where 0 is the beginning of the acquisition, ordered by position in file. nifti allows slices at the top and bottom of the volume to be excluded from the standard slice timing specification, and calls these "padding slices". We give padding slices ``None`` as a time of acquisition Examples -------- >>> hdr = Nifti1Header() >>> hdr.set_dim_info(slice=2) >>> hdr.set_data_shape((1, 1, 7)) >>> hdr.set_slice_duration(0.1) >>> hdr['slice_code'] = slice_order_codes['sequential increasing'] >>> slice_times = hdr.get_slice_times() >>> np.allclose(slice_times, [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6]) True """ hdr = self._structarr slice_len = self.get_n_slices() duration = self.get_slice_duration() slabel = self.get_value_label('slice_code') if slabel == 'unknown': raise HeaderDataError('Cannot get slice times when ' 'Slice code is "unknown"') slice_start, slice_end = (int(hdr['slice_start']), int(hdr['slice_end'])) if slice_start < 0: raise HeaderDataError('slice_start should be >= 0') if slice_end == 0: slice_end = slice_len - 1 n_timed = slice_end - slice_start + 1 if n_timed < 1: raise HeaderDataError('slice_end should be > slice_start') st_order = self._slice_time_order(slabel, n_timed) times = st_order * duration return ((None,) * slice_start + tuple(times) + (None,) * (slice_len - slice_end - 1)) def set_slice_times(self, slice_times): """ Set slice times into *hdr* Parameters ---------- slice_times : tuple tuple of slice times, one value per slice tuple can include None to indicate no slice time for that slice Examples -------- >>> hdr = Nifti1Header() >>> hdr.set_dim_info(slice=2) >>> hdr.set_data_shape([1, 1, 7]) >>> hdr.set_slice_duration(0.1) >>> times = [None, 0.2, 0.4, 0.1, 0.3, 0.0, None] >>> hdr.set_slice_times(times) >>> hdr.get_value_label('slice_code') 'alternating decreasing' >>> int(hdr['slice_start']) 1 >>> int(hdr['slice_end']) 5 """ # Check if number of slices matches header hdr = self._structarr slice_len = self.get_n_slices() if slice_len != len(slice_times): raise HeaderDataError('Number of slice times does not ' 'match number of slices') # Extract Nones at beginning and end. Check for others for ind, time in enumerate(slice_times): if time is not None: slice_start = ind break else: raise HeaderDataError('Not all slice times can be None') for ind, time in enumerate(slice_times[::-1]): if time is not None: slice_end = slice_len - ind - 1 break timed = slice_times[slice_start:slice_end + 1] for time in timed: if time is None: raise HeaderDataError('Cannot have None in middle ' 'of slice time vector') # Find slice duration, check times are compatible with single # duration tdiffs = np.diff(np.sort(timed)) if not np.allclose(np.diff(tdiffs), 0): raise HeaderDataError('Slice times not compatible with ' 'single slice duration') duration = np.mean(tdiffs) # To slice time order st_order = np.round(np.array(timed) / duration) # Check if slice times fit known schemes n_timed = len(timed) so_recoder = self._field_recoders['slice_code'] labels = so_recoder.value_set('label') labels.remove('unknown') matching_labels = [] for label in labels: if np.all(st_order == self._slice_time_order( label, n_timed)): matching_labels.append(label) if not matching_labels: raise HeaderDataError(f'slice ordering of {st_order} fits with no known scheme') if len(matching_labels) > 1: warnings.warn( f"Multiple slice orders satisfy: {", ".join(matching_labels)}. " "Choosing the first one") label = matching_labels[0] # Set values into header hdr['slice_start'] = slice_start hdr['slice_end'] = slice_end hdr['slice_duration'] = duration hdr['slice_code'] = slice_order_codes.code[label] def _slice_time_order(self, slabel, n_slices): """ Supporting function to give time order of slices from label """ if slabel == 'sequential increasing': sp_ind_time_order = list(range(n_slices)) elif slabel == 'sequential decreasing': sp_ind_time_order = list(range(n_slices)[::-1]) elif slabel == 'alternating increasing': sp_ind_time_order = (list(range(0, n_slices, 2)) + list(range(1, n_slices, 2))) elif slabel == 'alternating decreasing': sp_ind_time_order = (list(range(n_slices - 1, -1, -2)) + list(range(n_slices - 2, -1, -2))) elif slabel == 'alternating increasing 2': sp_ind_time_order = (list(range(1, n_slices, 2)) + list(range(0, n_slices, 2))) elif slabel == 'alternating decreasing 2': sp_ind_time_order = (list(range(n_slices - 2, -1, -2)) + list(range(n_slices - 1, -1, -2))) else: raise HeaderDataError(f'We do not handle slice ordering "{slabel}"') return np.argsort(sp_ind_time_order) def get_xyzt_units(self): xyz_code = self.structarr['xyzt_units'] % 8 t_code = self.structarr['xyzt_units'] - xyz_code return (unit_codes.label[xyz_code], unit_codes.label[t_code]) def set_xyzt_units(self, xyz=None, t=None): if xyz is None: xyz = 0 if t is None: t = 0 xyz_code = self.structarr['xyzt_units'] % 8 t_code = self.structarr['xyzt_units'] - xyz_code xyz_code = unit_codes[xyz] t_code = unit_codes[t] self.structarr['xyzt_units'] = xyz_code + t_code def _clean_after_mapping(self): """ Set format-specific stuff after converting header from mapping Clean up header after it has been initialized from an ``as_analyze_map`` method of another header type See :meth:`nibabel.analyze.AnalyzeHeader._clean_after_mapping` for a more detailed description. """ self._structarr['magic'] = (self.single_magic if self.is_single else self.pair_magic) """ Checks only below here """ @classmethod def _get_checks(klass): # We need to return our own versions of - e.g. chk_datatype, to # pick up the Nifti datatypes from our class return (klass._chk_sizeof_hdr, klass._chk_datatype, klass._chk_bitpix, klass._chk_pixdims, klass._chk_qfac, klass._chk_magic, klass._chk_offset, klass._chk_qform_code, klass._chk_sform_code) @staticmethod def _chk_qfac(hdr, fix=False): rep = Report(HeaderDataError) if hdr['pixdim'][0] in (-1, 1): return hdr, rep rep.problem_level = 20 rep.problem_msg = 'pixdim[0] (qfac) should be 1 (default) or -1' if fix: hdr['pixdim'][0] = 1 rep.fix_msg = 'setting qfac to 1' return hdr, rep @staticmethod def _chk_magic(hdr, fix=False): rep = Report(HeaderDataError) magic = hdr['magic'].item() if magic in (hdr.pair_magic, hdr.single_magic): return hdr, rep rep.problem_msg = f'magic string "{asstr(magic)}" is not valid' rep.problem_level = 45 if fix: rep.fix_msg = 'leaving as is, but future errors are likely' return hdr, rep @staticmethod def _chk_offset(hdr, fix=False): rep = Report(HeaderDataError) # for ease of later string formatting, use scalar of byte string magic = hdr['magic'].item() offset = hdr['vox_offset'].item() if offset == 0: return hdr, rep if magic == hdr.single_magic and offset < hdr.single_vox_offset: rep.problem_level = 40 rep.problem_msg = ('vox offset %d too low for ' 'single file nifti1' % offset) if fix: hdr['vox_offset'] = hdr.single_vox_offset rep.fix_msg = f'setting to minimum value of {hdr.single_vox_offset}' return hdr, rep if not offset % 16: return hdr, rep # SPM uses memory mapping to read the data, and # apparently this has to start on 16 byte boundaries rep.problem_msg = f'vox offset (={offset:g}) not divisible by 16, not SPM compatible' rep.problem_level = 30 if fix: rep.fix_msg = 'leaving at current value' return hdr, rep @classmethod def _chk_qform_code(klass, hdr, fix=False): return klass._chk_xform_code('qform_code', hdr, fix) @classmethod def _chk_sform_code(klass, hdr, fix=False): return klass._chk_xform_code('sform_code', hdr, fix) @classmethod def _chk_xform_code(klass, code_type, hdr, fix): # utility method for sform and qform codes rep = Report(HeaderDataError) code = int(hdr[code_type]) recoder = klass._field_recoders[code_type] if code in recoder.value_set(): return hdr, rep rep.problem_level = 30 rep.problem_msg = '%s %d not valid' % (code_type, code) if fix: hdr[code_type] = 0 rep.fix_msg = 'setting to 0' return hdr, rep @classmethod def may_contain_header(klass, binaryblock): if len(binaryblock) < klass.sizeof_hdr: return False hdr_struct = np.ndarray(shape=(), dtype=header_dtype, buffer=binaryblock[:klass.sizeof_hdr]) return hdr_struct['magic'] in (b'ni1', b'n+1') class Nifti1PairHeader(Nifti1Header): """ Class for NIfTI1 pair header """ # Signal whether this is single (header + data) file is_single = False class Nifti1Pair(analyze.AnalyzeImage): """ Class for NIfTI1 format image, header pair """ header_class = Nifti1PairHeader _meta_sniff_len = header_class.sizeof_hdr rw = True def __init__(self, dataobj, affine, header=None, extra=None, file_map=None): super(Nifti1Pair, self).__init__(dataobj, affine, header, extra, file_map) # Force set of s/q form when header is None unless affine is also None if header is None and affine is not None: self._affine2header() # Copy docstring __init__.__doc__ = analyze.AnalyzeImage.__init__.__doc__ + """ Notes ----- If both a `header` and an `affine` are specified, and the `affine` does not match the affine that is in the `header`, the `affine` will be used, but the ``sform_code`` and ``qform_code`` fields in the header will be re-initialised to their default values. This is performed on the basis that, if you are changing the affine, you are likely to be changing the space to which the affine is pointing. The :meth:`set_sform` and :meth:`set_qform` methods can be used to update the codes after an image has been created - see those methods, and the :ref:`manual <default-sform-qform-codes>` for more details. """ def update_header(self): """ Harmonize header with image data and affine See AnalyzeImage.update_header for more examples Examples -------- >>> data = np.zeros((2,3,4)) >>> affine = np.diag([1.0,2.0,3.0,1.0]) >>> img = Nifti1Image(data, affine) >>> hdr = img.header >>> np.all(hdr.get_qform() == affine) True >>> np.all(hdr.get_sform() == affine) True """ super(Nifti1Pair, self).update_header() hdr = self._header hdr['magic'] = hdr.pair_magic def _affine2header(self): """ Unconditionally set affine into the header """ hdr = self._header # Set affine into sform with default code hdr.set_sform(self._affine, code='aligned') # Make qform 'unknown' hdr.set_qform(self._affine, code='unknown') def get_qform(self, coded=False): """ Return 4x4 affine matrix from qform parameters in header Parameters ---------- coded : bool, optional If True, return {affine or None}, and qform code. If False, just return affine. {affine or None} means, return None if qform code == 0, and affine otherwise. Returns ------- affine : None or (4,4) ndarray If `coded` is False, always return affine reconstructed from qform quaternion. If `coded` is True, return None if qform code is 0, else return the affine. code : int Qform code. Only returned if `coded` is True. See also -------- set_qform get_sform """ return self._header.get_qform(coded) def set_qform(self, affine, code=None, strip_shears=True, **kwargs): """ Set qform header values from 4x4 affine Parameters ---------- affine : None or 4x4 array affine transform to write into sform. If None, only set code. code : None, string or integer String or integer giving meaning of transform in *affine*. The default is None. If code is None, then: * If affine is None, `code`-> 0 * If affine not None and existing qform code in header == 0, `code`-> 2 (aligned) * If affine not None and existing qform code in header != 0, `code`-> existing qform code in header strip_shears : bool, optional Whether to strip shears in `affine`. If True, shears will be silently stripped. If False, the presence of shears will raise a ``HeaderDataError`` update_affine : bool, optional Whether to update the image affine from the header best affine after setting the qform. Must be keyword argument (because of different position in `set_qform`). Default is True See also -------- get_qform set_sform Examples -------- >>> data = np.arange(24).reshape((2,3,4)) >>> aff = np.diag([2, 3, 4, 1]) >>> img = Nifti1Pair(data, aff) >>> img.get_qform() array([[2., 0., 0., 0.], [0., 3., 0., 0.], [0., 0., 4., 0.], [0., 0., 0., 1.]]) >>> img.get_qform(coded=True) (None, 0) >>> aff2 = np.diag([3, 4, 5, 1]) >>> img.set_qform(aff2, 'talairach') >>> qaff, code = img.get_qform(coded=True) >>> np.all(qaff == aff2) True >>> int(code) 3 """ update_affine = kwargs.pop('update_affine', True) if kwargs: raise TypeError(f'Unexpected keyword argument(s) {kwargs}') self._header.set_qform(affine, code, strip_shears) if update_affine: if self._affine is None: self._affine = self._header.get_best_affine() else: self._affine[:] = self._header.get_best_affine() def get_sform(self, coded=False): """ Return 4x4 affine matrix from sform parameters in header Parameters ---------- coded : bool, optional If True, return {affine or None}, and sform code. If False, just return affine. {affine or None} means, return None if sform code == 0, and affine otherwise. Returns ------- affine : None or (4,4) ndarray If `coded` is False, always return affine from sform fields. If `coded` is True, return None if sform code is 0, else return the affine. code : int Sform code. Only returned if `coded` is True. See also -------- set_sform get_qform """ return self._header.get_sform(coded) def set_sform(self, affine, code=None, **kwargs): """ Set sform transform from 4x4 affine Parameters ---------- affine : None or 4x4 array affine transform to write into sform. If None, only set `code` code : None, string or integer String or integer giving meaning of transform in *affine*. The default is None. If code is None, then: * If affine is None, `code`-> 0 * If affine not None and existing sform code in header == 0, `code`-> 2 (aligned) * If affine not None and existing sform code in header != 0, `code`-> existing sform code in header update_affine : bool, optional Whether to update the image affine from the header best affine after setting the qform. Must be keyword argument (because of different position in `set_qform`). Default is True See also -------- get_sform set_qform Examples -------- >>> data = np.arange(24).reshape((2,3,4)) >>> aff = np.diag([2, 3, 4, 1]) >>> img = Nifti1Pair(data, aff) >>> img.get_sform() array([[2., 0., 0., 0.], [0., 3., 0., 0.], [0., 0., 4., 0.], [0., 0., 0., 1.]]) >>> saff, code = img.get_sform(coded=True) >>> saff array([[2., 0., 0., 0.], [0., 3., 0., 0.], [0., 0., 4., 0.], [0., 0., 0., 1.]]) >>> int(code) 2 >>> aff2 = np.diag([3, 4, 5, 1]) >>> img.set_sform(aff2, 'talairach') >>> saff, code = img.get_sform(coded=True) >>> np.all(saff == aff2) True >>> int(code) 3 """ update_affine = kwargs.pop('update_affine', True) if kwargs: raise TypeError(f'Unexpected keyword argument(s) {kwargs}') self._header.set_sform(affine, code) if update_affine: if self._affine is None: self._affine = self._header.get_best_affine() else: self._affine[:] = self._header.get_best_affine() def as_reoriented(self, ornt): """Apply an orientation change and return a new image If ornt is identity transform, return the original image, unchanged Parameters ---------- ornt : (n,2) orientation array orientation transform. ``ornt[N,1]` is flip of axis N of the array implied by `shape`, where 1 means no flip and -1 means flip. For example, if ``N==0`` and ``ornt[0,1] == -1``, and there's an array ``arr`` of shape `shape`, the flip would correspond to the effect of ``np.flipud(arr)``. ``ornt[:,0]`` is the transpose that needs to be done to the implied array, as in ``arr.transpose(ornt[:,0])`` """ img = super(Nifti1Pair, self).as_reoriented(ornt) if img is self: return img # Also apply the transform to the dim_info fields new_dim = [ None if orig_dim is None else int(ornt[orig_dim, 0]) for orig_dim in img.header.get_dim_info()] img.header.set_dim_info(*new_dim) return img class Nifti1Image(Nifti1Pair, SerializableImage): """ Class for single file NIfTI1 format image """ header_class = Nifti1Header valid_exts = ('.nii',) files_types = (('image', '.nii'),) @staticmethod def _get_fileholders(file_map): """ Return fileholder for header and image For single-file niftis, the fileholder for the header and the image will be the same """ return file_map['image'], file_map['image'] def update_header(self): """ Harmonize header with image data and affine """ super(Nifti1Image, self).update_header() hdr = self._header hdr['magic'] = hdr.single_magic def load(filename): """ Load NIfTI1 single or pair from `filename` Parameters ---------- filename : str filename of image to be loaded Returns ------- img : Nifti1Image or Nifti1Pair NIfTI1 single or pair image instance Raises ------ ImageFileError if `filename` doesn't look like NIfTI1; IOError if `filename` does not exist. """ try: img = Nifti1Image.load(filename) except ImageFileError: return Nifti1Pair.load(filename) return img def save(img, filename): """ Save NIfTI1 single or pair to `filename` Parameters ---------- filename : str filename to which to save image """ try: Nifti1Image.instance_to_filename(img, filename) except ImageFileError: Nifti1Pair.instance_to_filename(img, filename)
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the NiBabel package for the # copyright and license terms. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## """ Read / write access to NIfTI1 image format NIfTI1 format defined at http://nifti.nimh.nih.gov/nifti-1/ """ import warnings from io import BytesIO import numpy as np import numpy.linalg as npl from numpy.compat.py3k import asstr from .filebasedimages import SerializableImage from .volumeutils import Recoder, make_dt_codes, endian_codes from .spatialimages import HeaderDataError, ImageFileError from .batteryrunners import Report from .quaternions import fillpositive, quat2mat, mat2quat from . import analyze # module import from .spm99analyze import SpmAnalyzeHeader from .casting import have_binary128 from .pydicom_compat import have_dicom, pydicom as pdcm # nifti1 flat header definition for Analyze-like first 348 bytes # first number in comments indicates offset in file header in bytes header_dtd = [ ('sizeof_hdr', 'i4'), # 0; must be 348 ('data_type', 'S10'), # 4; unused ('db_name', 'S18'), # 14; unused ('extents', 'i4'), # 32; unused ('session_error', 'i2'), # 36; unused ('regular', 'S1'), # 38; unused ('dim_info', 'u1'), # 39; MRI slice ordering code ('dim', 'i2', (8,)), # 40; data array dimensions ('intent_p1', 'f4'), # 56; first intent parameter ('intent_p2', 'f4'), # 60; second intent parameter ('intent_p3', 'f4'), # 64; third intent parameter ('intent_code', 'i2'), # 68; NIFTI intent code ('datatype', 'i2'), # 70; it's the datatype ('bitpix', 'i2'), # 72; number of bits per voxel ('slice_start', 'i2'), # 74; first slice index ('pixdim', 'f4', (8,)), # 76; grid spacings (units below) ('vox_offset', 'f4'), # 108; offset to data in image file ('scl_slope', 'f4'), # 112; data scaling slope ('scl_inter', 'f4'), # 116; data scaling intercept ('slice_end', 'i2'), # 120; last slice index ('slice_code', 'u1'), # 122; slice timing order ('xyzt_units', 'u1'), # 123; units of pixdim[1..4] ('cal_max', 'f4'), # 124; max display intensity ('cal_min', 'f4'), # 128; min display intensity ('slice_duration', 'f4'), # 132; time for 1 slice ('toffset', 'f4'), # 136; time axis shift ('glmax', 'i4'), # 140; unused ('glmin', 'i4'), # 144; unused ('descrip', 'S80'), # 148; any text ('aux_file', 'S24'), # 228; auxiliary filename ('qform_code', 'i2'), # 252; xform code ('sform_code', 'i2'), # 254; xform code ('quatern_b', 'f4'), # 256; quaternion b param ('quatern_c', 'f4'), # 260; quaternion c param ('quatern_d', 'f4'), # 264; quaternion d param ('qoffset_x', 'f4'), # 268; quaternion x shift ('qoffset_y', 'f4'), # 272; quaternion y shift ('qoffset_z', 'f4'), # 276; quaternion z shift ('srow_x', 'f4', (4,)), # 280; 1st row affine transform ('srow_y', 'f4', (4,)), # 296; 2nd row affine transform ('srow_z', 'f4', (4,)), # 312; 3rd row affine transform ('intent_name', 'S16'), # 328; name or meaning of data ('magic', 'S4') # 344; must be 'ni1\0' or 'n+1\0' ] # Full header numpy dtype header_dtype = np.dtype(header_dtd) # datatypes not in analyze format, with codes if have_binary128(): # Only enable 128 bit floats if we really have IEEE binary 128 longdoubles _float128t = np.longdouble _complex256t = np.longcomplex else: _float128t = np.void _complex256t = np.void _dtdefs = ( # code, label, dtype definition, niistring (0, 'none', np.void, ""), (1, 'binary', np.void, ""), (2, 'uint8', np.uint8, "NIFTI_TYPE_UINT8"), (4, 'int16', np.int16, "NIFTI_TYPE_INT16"), (8, 'int32', np.int32, "NIFTI_TYPE_INT32"), (16, 'float32', np.float32, "NIFTI_TYPE_FLOAT32"), (32, 'complex64', np.complex64, "NIFTI_TYPE_COMPLEX64"), (64, 'float64', np.float64, "NIFTI_TYPE_FLOAT64"), (128, 'RGB', np.dtype([('R', 'u1'), ('G', 'u1'), ('B', 'u1')]), "NIFTI_TYPE_RGB24"), (255, 'all', np.void, ''), (256, 'int8', np.int8, "NIFTI_TYPE_INT8"), (512, 'uint16', np.uint16, "NIFTI_TYPE_UINT16"), (768, 'uint32', np.uint32, "NIFTI_TYPE_UINT32"), (1024, 'int64', np.int64, "NIFTI_TYPE_INT64"), (1280, 'uint64', np.uint64, "NIFTI_TYPE_UINT64"), (1536, 'float128', _float128t, "NIFTI_TYPE_FLOAT128"), (1792, 'complex128', np.complex128, "NIFTI_TYPE_COMPLEX128"), (2048, 'complex256', _complex256t, "NIFTI_TYPE_COMPLEX256"), (2304, 'RGBA', np.dtype([('R', 'u1'), ('G', 'u1'), ('B', 'u1'), ('A', 'u1')]), "NIFTI_TYPE_RGBA32"), ) # Make full code alias bank, including dtype column data_type_codes = make_dt_codes(_dtdefs) # Transform (qform, sform) codes xform_codes = Recoder(( # code, label, niistring (0, 'unknown', "NIFTI_XFORM_UNKNOWN"), (1, 'scanner', "NIFTI_XFORM_SCANNER_ANAT"), (2, 'aligned', "NIFTI_XFORM_ALIGNED_ANAT"), (3, 'talairach', "NIFTI_XFORM_TALAIRACH"), (4, 'mni', "NIFTI_XFORM_MNI_152"), (5, 'template', "NIFTI_XFORM_TEMPLATE_OTHER"), ), fields=('code', 'label', 'niistring')) # unit codes unit_codes = Recoder(( # code, label (0, 'unknown'), (1, 'meter'), (2, 'mm'), (3, 'micron'), (8, 'sec'), (16, 'msec'), (24, 'usec'), (32, 'hz'), (40, 'ppm'), (48, 'rads')), fields=('code', 'label')) slice_order_codes = Recoder(( # code, label (0, 'unknown'), (1, 'sequential increasing', 'seq inc'), (2, 'sequential decreasing', 'seq dec'), (3, 'alternating increasing', 'alt inc'), (4, 'alternating decreasing', 'alt dec'), (5, 'alternating increasing 2', 'alt inc 2'), (6, 'alternating decreasing 2', 'alt dec 2')), fields=('code', 'label')) intent_codes = Recoder(( # code, label, parameters description tuple (0, 'none', (), "NIFTI_INTENT_NONE"), (2, 'correlation', ('p1 = DOF',), "NIFTI_INTENT_CORREL"), (3, 't test', ('p1 = DOF',), "NIFTI_INTENT_TTEST"), (4, 'f test', ('p1 = numerator DOF', 'p2 = denominator DOF'), "NIFTI_INTENT_FTEST"), (5, 'z score', (), "NIFTI_INTENT_ZSCORE"), (6, 'chi2', ('p1 = DOF',), "NIFTI_INTENT_CHISQ"), # two parameter beta distribution (7, 'beta', ('p1=a', 'p2=b'), "NIFTI_INTENT_BETA"), # Prob(x) = (p1 choose x) * p2^x * (1-p2)^(p1-x), for x=0,1,...,p1 (8, 'binomial', ('p1 = number of trials', 'p2 = probability per trial'), "NIFTI_INTENT_BINOM"), # 2 parameter gamma # Density(x) proportional to # x^(p1-1) * exp(-p2*x) (9, 'gamma', ('p1 = shape, p2 = scale', 2), "NIFTI_INTENT_GAMMA"), (10, 'poisson', ('p1 = mean',), "NIFTI_INTENT_POISSON"), (11, 'normal', ('p1 = mean', 'p2 = standard deviation',), "NIFTI_INTENT_NORMAL"), (12, 'non central f test', ('p1 = numerator DOF', 'p2 = denominator DOF', 'p3 = numerator noncentrality parameter',), "NIFTI_INTENT_FTEST_NONC"), (13, 'non central chi2', ('p1 = DOF', 'p2 = noncentrality parameter',), "NIFTI_INTENT_CHISQ_NONC"), (14, 'logistic', ('p1 = location', 'p2 = scale',), "NIFTI_INTENT_LOGISTIC"), (15, 'laplace', ('p1 = location', 'p2 = scale'), "NIFTI_INTENT_LAPLACE"), (16, 'uniform', ('p1 = lower end', 'p2 = upper end'), "NIFTI_INTENT_UNIFORM"), (17, 'non central t test', ('p1 = DOF', 'p2 = noncentrality parameter'), "NIFTI_INTENT_TTEST_NONC"), (18, 'weibull', ('p1 = location', 'p2 = scale, p3 = power'), "NIFTI_INTENT_WEIBULL"), # p1 = 1 = 'half normal' distribution # p1 = 2 = Rayleigh distribution # p1 = 3 = Maxwell-Boltzmann distribution. (19, 'chi', ('p1 = DOF',), "NIFTI_INTENT_CHI"), (20, 'inverse gaussian', ('pi = mu', 'p2 = lambda'), "NIFTI_INTENT_INVGAUSS"), (21, 'extreme value 1', ('p1 = location', 'p2 = scale'), "NIFTI_INTENT_EXTVAL"), (22, 'p value', (), "NIFTI_INTENT_PVAL"), (23, 'log p value', (), "NIFTI_INTENT_LOGPVAL"), (24, 'log10 p value', (), "NIFTI_INTENT_LOG10PVAL"), (1001, 'estimate', (), "NIFTI_INTENT_ESTIMATE"), (1002, 'label', (), "NIFTI_INTENT_LABEL"), (1003, 'neuroname', (), "NIFTI_INTENT_NEURONAME"), (1004, 'general matrix', ('p1 = M', 'p2 = N'), "NIFTI_INTENT_GENMATRIX"), (1005, 'symmetric matrix', ('p1 = M',), "NIFTI_INTENT_SYMMATRIX"), (1006, 'displacement vector', (), "NIFTI_INTENT_DISPVECT"), (1007, 'vector', (), "NIFTI_INTENT_VECTOR"), (1008, 'pointset', (), "NIFTI_INTENT_POINTSET"), (1009, 'triangle', (), "NIFTI_INTENT_TRIANGLE"), (1010, 'quaternion', (), "NIFTI_INTENT_QUATERNION"), (1011, 'dimensionless', (), "NIFTI_INTENT_DIMLESS"), (2001, 'time series', (), "NIFTI_INTENT_TIME_SERIES", "NIFTI_INTENT_TIMESERIES"), # this mis-spell occurs in the wild (2002, 'node index', (), "NIFTI_INTENT_NODE_INDEX"), (2003, 'rgb vector', (), "NIFTI_INTENT_RGB_VECTOR"), (2004, 'rgba vector', (), "NIFTI_INTENT_RGBA_VECTOR"), (2005, 'shape', (), "NIFTI_INTENT_SHAPE"), # FSL-specific intent codes - codes used by FNIRT # ($FSLDIR/warpfns/fnirt_file_reader.h:104) (2006, 'fnirt disp field', (), 'FSL_FNIRT_DISPLACEMENT_FIELD'), (2007, 'fnirt cubic spline coef', (), 'FSL_CUBIC_SPLINE_COEFFICIENTS'), (2008, 'fnirt dct coef', (), 'FSL_DCT_COEFFICIENTS'), (2009, 'fnirt quad spline coef', (), 'FSL_QUADRATIC_SPLINE_COEFFICIENTS'), # FSL-specific intent codes - codes used by TOPUP # ($FSLDIR/topup/topup_file_io.h:104) (2016, 'topup cubic spline coef ', (), 'FSL_TOPUP_CUBIC_SPLINE_COEFFICIENTS'), (2017, 'topup quad spline coef', (), 'FSL_TOPUP_QUADRATIC_SPLINE_COEFFICIENTS'), (2018, 'topup field', (), 'FSL_TOPUP_FIELD'), ), fields=('code', 'label', 'parameters', 'niistring')) class Nifti1Extension(object): """Baseclass for NIfTI1 header extensions. This class is sufficient to handle very simple text-based extensions, such as `comment`. More sophisticated extensions should/will be supported by dedicated subclasses. """ def __init__(self, code, content): """ Parameters ---------- code : int or str Canonical extension code as defined in the NIfTI standard, given either as integer or corresponding label (see :data:`~nibabel.nifti1.extension_codes`) content : str Extension content as read from the NIfTI file header. This content is converted into a runtime representation. """ try: self._code = extension_codes.code[code] except KeyError: # XXX or fail or at least complain? self._code = code self._content = self._unmangle(content) def _unmangle(self, value): """Convert the extension content into its runtime representation. The default implementation does nothing at all. Parameters ---------- value : str Extension content as read from file. Returns ------- The same object that was passed as `value`. Notes ----- Subclasses should reimplement this method to provide the desired unmangling procedure and may return any type of object. """ return value def _mangle(self, value): """Convert the extension content into NIfTI file header representation. The default implementation does nothing at all. Parameters ---------- value : str Extension content in runtime form. Returns ------- str Notes ----- Subclasses should reimplement this method to provide the desired mangling procedure. """ return value def get_code(self): """Return the canonical extension type code.""" return self._code def get_content(self): """Return the extension content in its runtime representation.""" return self._content def get_sizeondisk(self): """Return the size of the extension in the NIfTI file. """ # need raw value size plus 8 bytes for esize and ecode size = len(self._mangle(self._content)) size += 8 # extensions size has to be a multiple of 16 bytes if size % 16 != 0: size += 16 - (size % 16) return size def __repr__(self): try: code = extension_codes.label[self._code] except KeyError: # deal with unknown codes code = self._code s = f"Nifti1Extension('{code}', '{self._content}')" return s def __eq__(self, other): return (self._code, self._content) == (other._code, other._content) def __ne__(self, other): return not self == other def write_to(self, fileobj, byteswap): """ Write header extensions to fileobj Write starts at fileobj current file position. Parameters ---------- fileobj : file-like object Should implement ``write`` method byteswap : boolean Flag if byteswapping the data is required. Returns ------- None """ extstart = fileobj.tell() rawsize = self.get_sizeondisk() # write esize and ecode first extinfo = np.array((rawsize, self._code), dtype=np.int32) if byteswap: extinfo = extinfo.byteswap() fileobj.write(extinfo.tobytes()) # followed by the actual extension content # XXX if mangling upon load is implemented, it should be reverted here fileobj.write(self._mangle(self._content)) # be nice and zero out remaining part of the extension till the # next 16 byte border fileobj.write(b'\x00' * (extstart + rawsize - fileobj.tell())) class Nifti1DicomExtension(Nifti1Extension): """NIfTI1 DICOM header extension This class is a thin wrapper around pydicom to read a binary DICOM byte string. If pydicom is available, content is exposed as a Dicom Dataset. Otherwise, this silently falls back to the standard NiftiExtension class and content is the raw bytestring loaded directly from the nifti file header. """ def __init__(self, code, content, parent_hdr=None): """ Parameters ---------- code : int or str Canonical extension code as defined in the NIfTI standard, given either as integer or corresponding label (see :data:`~nibabel.nifti1.extension_codes`) content : bytes or pydicom Dataset or None Extension content - either a bytestring as read from the NIfTI file header or an existing pydicom Dataset. If a bystestring, the content is converted into a Dataset on initialization. If None, a new empty Dataset is created. parent_hdr : :class:`~nibabel.nifti1.Nifti1Header`, optional If a dicom extension belongs to an existing :class:`~nibabel.nifti1.Nifti1Header`, it may be provided here to ensure that the DICOM dataset is written with correctly corresponding endianness; otherwise it is assumed the dataset is little endian. Notes ----- code should always be 2 for DICOM. """ self._code = code if parent_hdr: self._is_little_endian = parent_hdr.endianness == '<' else: self._is_little_endian = True if isinstance(content, pdcm.dataset.Dataset): self._is_implicit_VR = False self._raw_content = self._mangle(content) self._content = content elif isinstance(content, bytes): # Got a byte string - unmangle it self._raw_content = content self._is_implicit_VR = self._guess_implicit_VR() ds = self._unmangle(content, self._is_implicit_VR, self._is_little_endian) self._content = ds elif content is None: # initialize a new dicom dataset self._is_implicit_VR = False self._content = pdcm.dataset.Dataset() else: raise TypeError(f"content must be either a bytestring or a pydicom Dataset. " f"Got {content.__class__}") def _guess_implicit_VR(self): """Try to guess DICOM syntax by checking for valid VRs. Without a DICOM Transfer Syntax, it's difficult to tell if Value Representations (VRs) are included in the DICOM encoding or not. This reads where the first VR would be and checks it against a list of valid VRs """ potential_vr = self._raw_content[4:6].decode() if potential_vr in pdcm.values.converters.keys(): implicit_VR = False else: implicit_VR = True return implicit_VR def _unmangle(self, value, is_implicit_VR=False, is_little_endian=True): bio = BytesIO(value) ds = pdcm.filereader.read_dataset(bio, is_implicit_VR, is_little_endian) return ds def _mangle(self, dataset): bio = BytesIO() dio = pdcm.filebase.DicomFileLike(bio) dio.is_implicit_VR = self._is_implicit_VR dio.is_little_endian = self._is_little_endian ds_len = pdcm.filewriter.write_dataset(dio, dataset) dio.seek(0) return dio.read(ds_len) # NIfTI header extension type codes (ECODE) # see nifti1_io.h for a complete list of all known extensions and # references to their description or contacts of the respective # initiators extension_codes = Recoder(( (0, "ignore", Nifti1Extension), (2, "dicom", Nifti1DicomExtension if have_dicom else Nifti1Extension), (4, "afni", Nifti1Extension), (6, "comment", Nifti1Extension), (8, "xcede", Nifti1Extension), (10, "jimdiminfo", Nifti1Extension), (12, "workflow_fwds", Nifti1Extension), (14, "freesurfer", Nifti1Extension), (16, "pypickle", Nifti1Extension), ), fields=('code', 'label', 'handler')) class Nifti1Extensions(list): """Simple extension collection, implemented as a list-subclass. """ def count(self, ecode): """Returns the number of extensions matching a given *ecode*. Parameters ---------- code : int | str The ecode can be specified either literal or as numerical value. """ count = 0 code = extension_codes.code[ecode] for e in self: if e.get_code() == code: count += 1 return count def get_codes(self): """Return a list of the extension code of all available extensions""" return [e.get_code() for e in self] def get_sizeondisk(self): """Return the size of the complete header extensions in the NIfTI file. """ return np.sum([e.get_sizeondisk() for e in self]) def __repr__(self): return "Nifti1Extensions(%s)" % ', '.join(str(e) for e in self) def __cmp__(self, other): return cmp(list(self), list(other)) def write_to(self, fileobj, byteswap): """ Write header extensions to fileobj Write starts at fileobj current file position. Parameters ---------- fileobj : file-like object Should implement ``write`` method byteswap : boolean Flag if byteswapping the data is required. Returns ------- None """ for e in self: e.write_to(fileobj, byteswap) @classmethod def from_fileobj(klass, fileobj, size, byteswap): """Read header extensions from a fileobj Parameters ---------- fileobj : file-like object We begin reading the extensions at the current file position size : int Number of bytes to read. If negative, fileobj will be read till its end. byteswap : boolean Flag if byteswapping the read data is required. Returns ------- An extension list. This list might be empty in case not extensions were present in fileobj. """ # make empty extension list extensions = klass() # assume the file pointer is at the beginning of any extensions. # read until the whole header is parsed (each extension is a multiple # of 16 bytes) or in case of a separate header file till the end # (break inside the body) while size >= 16 or size < 0: # the next 8 bytes should have esize and ecode ext_def = fileobj.read(8) # nothing was read and instructed to read till the end # -> assume all extensions where parsed and break if not len(ext_def) and size < 0: break # otherwise there should be a full extension header if not len(ext_def) == 8: raise HeaderDataError('failed to read extension header') ext_def = np.frombuffer(ext_def, dtype=np.int32) if byteswap: ext_def = ext_def.byteswap() # be extra verbose ecode = ext_def[1] esize = ext_def[0] if esize % 16: warnings.warn( 'Extension size is not a multiple of 16 bytes; ' 'Assuming size is correct and hoping for the best', UserWarning) # read extension itself; esize includes the 8 bytes already read evalue = fileobj.read(int(esize - 8)) if not len(evalue) == esize - 8: raise HeaderDataError('failed to read extension content') # note that we read a full extension size -= esize # store raw extension content, but strip trailing NULL chars evalue = evalue.rstrip(b'\x00') # 'extension_codes' also knows the best implementation to handle # a particular extension type try: ext = extension_codes.handler[ecode](ecode, evalue) except KeyError: # unknown extension type # XXX complain or fail or go with a generic extension ext = Nifti1Extension(ecode, evalue) extensions.append(ext) return extensions class Nifti1Header(SpmAnalyzeHeader): """ Class for NIfTI1 header The NIfTI1 header has many more coded fields than the simpler Analyze variants. NIfTI1 headers also have extensions. Nifti allows the header to be a separate file, as part of a nifti image / header pair, or to precede the data in a single file. The object needs to know which type it is, in order to manage the voxel offset pointing to the data, extension reading, and writing the correct magic string. This class handles the header-preceding-data case. """ # Copies of module level definitions template_dtype = header_dtype _data_type_codes = data_type_codes # fields with recoders for their values _field_recoders = {'datatype': data_type_codes, 'qform_code': xform_codes, 'sform_code': xform_codes, 'intent_code': intent_codes, 'slice_code': slice_order_codes} # data scaling capabilities has_data_slope = True has_data_intercept = True # Extension class; should implement __call__ for construction, and # ``from_fileobj`` for reading from file exts_klass = Nifti1Extensions # Signal whether this is single (header + data) file is_single = True # Default voxel data offsets for single and pair pair_vox_offset = 0 single_vox_offset = 352 # Magics for single and pair pair_magic = b'ni1' single_magic = b'n+1' # Quaternion threshold near 0, based on float32 precision quaternion_threshold = -np.finfo(np.float32).eps * 3 def __init__(self, binaryblock=None, endianness=None, check=True, extensions=()): """ Initialize header from binary data block and extensions """ super(Nifti1Header, self).__init__(binaryblock, endianness, check) self.extensions = self.exts_klass(extensions) def copy(self): """ Return copy of header Take reference to extensions as well as copy of header contents """ return self.__class__( self.binaryblock, self.endianness, False, self.extensions) @classmethod def from_fileobj(klass, fileobj, endianness=None, check=True): raw_str = fileobj.read(klass.template_dtype.itemsize) hdr = klass(raw_str, endianness, check) # Read next 4 bytes to see if we have extensions. The nifti standard # has this as a 4 byte string; if the first value is not zero, then we # have extensions. extension_status = fileobj.read(4) # Need to test *slice* of extension_status to preserve byte string type # on Python 3 if len(extension_status) < 4 or extension_status[0:1] == b'\x00': return hdr # If this is a detached header file read to end if not klass.is_single: extsize = -1 else: # otherwise read until the beginning of the data extsize = hdr._structarr['vox_offset'] - fileobj.tell() byteswap = endian_codes['native'] != hdr.endianness hdr.extensions = klass.exts_klass.from_fileobj(fileobj, extsize, byteswap) return hdr def write_to(self, fileobj): # First check that vox offset is large enough; set if necessary if self.is_single: vox_offset = self._structarr['vox_offset'] min_vox_offset = (self.single_vox_offset + self.extensions.get_sizeondisk()) if vox_offset == 0: # vox offset unset; set as necessary self._structarr['vox_offset'] = min_vox_offset elif vox_offset < min_vox_offset: raise HeaderDataError( f'vox offset set to {vox_offset}, but need at least {min_vox_offset}') super(Nifti1Header, self).write_to(fileobj) # Write extensions if len(self.extensions) == 0: # If single file, write required 0 stream to signal no extensions if self.is_single: fileobj.write(b'\x00' * 4) return # Signal there are extensions that follow fileobj.write(b'\x01\x00\x00\x00') byteswap = endian_codes['native'] != self.endianness self.extensions.write_to(fileobj, byteswap) def get_best_affine(self): """ Select best of available transforms """ hdr = self._structarr if hdr['sform_code'] != 0: return self.get_sform() if hdr['qform_code'] != 0: return self.get_qform() return self.get_base_affine() @classmethod def default_structarr(klass, endianness=None): """ Create empty header binary block with given endianness """ hdr_data = super(Nifti1Header, klass).default_structarr(endianness) if klass.is_single: hdr_data['magic'] = klass.single_magic else: hdr_data['magic'] = klass.pair_magic return hdr_data @classmethod def from_header(klass, header=None, check=True): """ Class method to create header from another header Extend Analyze header copy by copying extensions from other Nifti types. Parameters ---------- header : ``Header`` instance or mapping a header of this class, or another class of header for conversion to this type check : {True, False} whether to check header for integrity Returns ------- hdr : header instance fresh header instance of our own class """ new_hdr = super(Nifti1Header, klass).from_header(header, check) if isinstance(header, Nifti1Header): new_hdr.extensions[:] = header.extensions[:] return new_hdr def get_data_shape(self): """ Get shape of data Examples -------- >>> hdr = Nifti1Header() >>> hdr.get_data_shape() (0,) >>> hdr.set_data_shape((1,2,3)) >>> hdr.get_data_shape() (1, 2, 3) Expanding number of dimensions gets default zooms >>> hdr.get_zooms() (1.0, 1.0, 1.0) Notes ----- Applies freesurfer hack for large vectors described in `issue 100`_ and `save_nifti.m <save77_>`_. Allows for freesurfer hack for 7th order icosahedron surface described in `issue 309`_, load_nifti.m_, and `save_nifti.m <save50_>`_. """ shape = super(Nifti1Header, self).get_data_shape() # Apply freesurfer hack for large vectors if shape[:3] == (-1, 1, 1): vec_len = int(self._structarr['glmin']) if vec_len == 0: raise HeaderDataError('-1 in dim[1] but 0 in glmin; ' 'inconsistent freesurfer type header?') return (vec_len, 1, 1) + shape[3:] # Apply freesurfer hack for ico7 surface elif shape[:3] == (27307, 1, 6): return (163842, 1, 1) + shape[3:] else: # Normal case return shape def set_data_shape(self, shape): """ Set shape of data # noqa If ``ndims == len(shape)`` then we set zooms for dimensions higher than ``ndims`` to 1.0 Nifti1 images can have up to seven dimensions. For FreeSurfer-variant Nifti surface files, the first dimension is assumed to correspond to vertices/nodes on a surface, and dimensions two and three are constrained to have depth of 1. Dimensions 4-7 are constrained only by type bounds. Parameters ---------- shape : sequence sequence of integers specifying data array shape Notes ----- Applies freesurfer hack for large vectors described in `issue 100`_ and `save_nifti.m <save77_>`_. Allows for freesurfer hack for 7th order icosahedron surface described in `issue 309`_, load_nifti.m_, and `save_nifti.m <save50_>`_. The Nifti1 `standard header`_ allows for the following "point set" definition of a surface, not currently implemented in nibabel. :: To signify that the vector value at each voxel is really a spatial coordinate (e.g., the vertices or nodes of a surface mesh): - dataset must have a 5th dimension - intent_code must be NIFTI_INTENT_POINTSET - dim[0] = 5 - dim[1] = number of points - dim[2] = dim[3] = dim[4] = 1 - dim[5] must be the dimensionality of space (e.g., 3 => 3D space). - intent_name may describe the object these points come from (e.g., "pial", "gray/white" , "EEG", "MEG"). .. _issue 100: https://github.com/nipy/nibabel/issues/100 .. _issue 309: https://github.com/nipy/nibabel/issues/309 .. _save77: https://github.com/fieldtrip/fieldtrip/blob/428798b/external/freesurfer/save_nifti.m#L77-L82 .. _save50: https://github.com/fieldtrip/fieldtrip/blob/428798b/external/freesurfer/save_nifti.m#L50-L56 .. _load_nifti.m: https://github.com/fieldtrip/fieldtrip/blob/428798b/external/freesurfer/load_nifti.m#L86-L89 .. _standard header: http://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1.h """ hdr = self._structarr shape = tuple(shape) # Apply freesurfer hack for ico7 surface if shape[:3] == (163842, 1, 1): shape = (27307, 1, 6) + shape[3:] # Apply freesurfer hack for large vectors elif (len(shape) >= 3 and shape[1:3] == (1, 1) and shape[0] > np.iinfo(hdr['dim'].dtype.base).max): try: hdr['glmin'] = shape[0] except OverflowError: overflow = True else: overflow = hdr['glmin'] != shape[0] if overflow: raise HeaderDataError(f'shape[0] {shape[0]} does not fit in glmax datatype') warnings.warn('Using large vector Freesurfer hack; header will ' 'not be compatible with SPM or FSL', stacklevel=2) shape = (-1, 1, 1) + shape[3:] super(Nifti1Header, self).set_data_shape(shape) def get_qform_quaternion(self): """ Compute quaternion from b, c, d of quaternion Fills a value by assuming this is a unit quaternion """ hdr = self._structarr bcd = [hdr['quatern_b'], hdr['quatern_c'], hdr['quatern_d']] # Adjust threshold to precision of stored values in header return fillpositive(bcd, self.quaternion_threshold) def get_qform(self, coded=False): """ Return 4x4 affine matrix from qform parameters in header Parameters ---------- coded : bool, optional If True, return {affine or None}, and qform code. If False, just return affine. {affine or None} means, return None if qform code == 0, and affine otherwise. Returns ------- affine : None or (4,4) ndarray If `coded` is False, always return affine reconstructed from qform quaternion. If `coded` is True, return None if qform code is 0, else return the affine. code : int Qform code. Only returned if `coded` is True. """ hdr = self._structarr code = int(hdr['qform_code']) if code == 0 and coded: return None, 0 quat = self.get_qform_quaternion() R = quat2mat(quat) vox = hdr['pixdim'][1:4].copy() if np.any(vox < 0): raise HeaderDataError('pixdims[1,2,3] should be positive') qfac = hdr['pixdim'][0] if qfac not in (-1, 1): raise HeaderDataError('qfac (pixdim[0]) should be 1 or -1') vox[-1] *= qfac S = np.diag(vox) M = np.dot(R, S) out = np.eye(4) out[0:3, 0:3] = M out[0:3, 3] = [hdr['qoffset_x'], hdr['qoffset_y'], hdr['qoffset_z']] if coded: return out, code return out def set_qform(self, affine, code=None, strip_shears=True): """ Set qform header values from 4x4 affine Parameters ---------- affine : None or 4x4 array affine transform to write into sform. If None, only set code. code : None, string or integer, optional String or integer giving meaning of transform in *affine*. The default is None. If code is None, then: * If affine is None, `code`-> 0 * If affine not None and existing qform code in header == 0, `code`-> 2 (aligned) * If affine not None and existing qform code in header != 0, `code`-> existing qform code in header strip_shears : bool, optional Whether to strip shears in `affine`. If True, shears will be silently stripped. If False, the presence of shears will raise a ``HeaderDataError`` Notes ----- The qform transform only encodes translations, rotations and zooms. If there are shear components to the `affine` transform, and `strip_shears` is True (the default), the written qform gives the closest approximation where the rotation matrix is orthogonal. This is to allow quaternion representation. The orthogonal representation enforces orthogonal axes. Examples -------- >>> hdr = Nifti1Header() >>> int(hdr['qform_code']) # gives 0 - unknown 0 >>> affine = np.diag([1,2,3,1]) >>> np.all(hdr.get_qform() == affine) False >>> hdr.set_qform(affine) >>> np.all(hdr.get_qform() == affine) True >>> int(hdr['qform_code']) # gives 2 - aligned 2 >>> hdr.set_qform(affine, code='talairach') >>> int(hdr['qform_code']) 3 >>> hdr.set_qform(affine, code=None) >>> int(hdr['qform_code']) 3 >>> hdr.set_qform(affine, code='scanner') >>> int(hdr['qform_code']) 1 >>> hdr.set_qform(None) >>> int(hdr['qform_code']) 0 """ hdr = self._structarr old_code = hdr['qform_code'] if code is None: if affine is None: code = 0 elif old_code == 0: code = 2 # aligned else: code = old_code else: # code set code = self._field_recoders['qform_code'][code] hdr['qform_code'] = code if affine is None: return affine = np.asarray(affine) if not affine.shape == (4, 4): raise TypeError('Need 4x4 affine as input') trans = affine[:3, 3] RZS = affine[:3, :3] zooms = np.sqrt(np.sum(RZS * RZS, axis=0)) R = RZS / zooms # Set qfac to make R determinant positive if npl.det(R) > 0: qfac = 1 else: qfac = -1 R[:, -1] *= -1 # Make R orthogonal (to allow quaternion representation) # The orthogonal representation enforces orthogonal axes # (a subtle requirement of the NIFTI format qform transform) # Transform below is polar decomposition, returning the closest # orthogonal matrix PR, to input R P, S, Qs = npl.svd(R) PR = np.dot(P, Qs) if not strip_shears and not np.allclose(PR, R): raise HeaderDataError("Shears in affine and `strip_shears` is " "False") # Convert to quaternion quat = mat2quat(PR) # Set into header hdr['qoffset_x'], hdr['qoffset_y'], hdr['qoffset_z'] = trans hdr['pixdim'][0] = qfac hdr['pixdim'][1:4] = zooms hdr['quatern_b'], hdr['quatern_c'], hdr['quatern_d'] = quat[1:] def get_sform(self, coded=False): """ Return 4x4 affine matrix from sform parameters in header Parameters ---------- coded : bool, optional If True, return {affine or None}, and sform code. If False, just return affine. {affine or None} means, return None if sform code == 0, and affine otherwise. Returns ------- affine : None or (4,4) ndarray If `coded` is False, always return affine from sform fields. If `coded` is True, return None if sform code is 0, else return the affine. code : int Sform code. Only returned if `coded` is True. """ hdr = self._structarr code = int(hdr['sform_code']) if code == 0 and coded: return None, 0 out = np.eye(4) out[0, :] = hdr['srow_x'][:] out[1, :] = hdr['srow_y'][:] out[2, :] = hdr['srow_z'][:] if coded: return out, code return out def set_sform(self, affine, code=None): """ Set sform transform from 4x4 affine Parameters ---------- affine : None or 4x4 array affine transform to write into sform. If None, only set `code` code : None, string or integer, optional String or integer giving meaning of transform in *affine*. The default is None. If code is None, then: * If affine is None, `code`-> 0 * If affine not None and existing sform code in header == 0, `code`-> 2 (aligned) * If affine not None and existing sform code in header != 0, `code`-> existing sform code in header Examples -------- >>> hdr = Nifti1Header() >>> int(hdr['sform_code']) # gives 0 - unknown 0 >>> affine = np.diag([1,2,3,1]) >>> np.all(hdr.get_sform() == affine) False >>> hdr.set_sform(affine) >>> np.all(hdr.get_sform() == affine) True >>> int(hdr['sform_code']) # gives 2 - aligned 2 >>> hdr.set_sform(affine, code='talairach') >>> int(hdr['sform_code']) 3 >>> hdr.set_sform(affine, code=None) >>> int(hdr['sform_code']) 3 >>> hdr.set_sform(affine, code='scanner') >>> int(hdr['sform_code']) 1 >>> hdr.set_sform(None) >>> int(hdr['sform_code']) 0 """ hdr = self._structarr old_code = hdr['sform_code'] if code is None: if affine is None: code = 0 elif old_code == 0: code = 2 # aligned else: code = old_code else: # code set code = self._field_recoders['sform_code'][code] hdr['sform_code'] = code if affine is None: return affine = np.asarray(affine) hdr['srow_x'][:] = affine[0, :] hdr['srow_y'][:] = affine[1, :] hdr['srow_z'][:] = affine[2, :] def get_slope_inter(self): """ Get data scaling (slope) and DC offset (intercept) from header data Returns ------- slope : None or float scaling (slope). None if there is no valid scaling from these fields inter : None or float offset (intercept). None if there is no valid scaling or if offset is not finite. Examples -------- >>> hdr = Nifti1Header() >>> hdr.get_slope_inter() (1.0, 0.0) >>> hdr['scl_slope'] = 0 >>> hdr.get_slope_inter() (None, None) >>> hdr['scl_slope'] = np.nan >>> hdr.get_slope_inter() (None, None) >>> hdr['scl_slope'] = 1 >>> hdr['scl_inter'] = 1 >>> hdr.get_slope_inter() (1.0, 1.0) >>> hdr['scl_inter'] = np.inf >>> hdr.get_slope_inter() #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... HeaderDataError: Valid slope but invalid intercept inf """ # Note that we are returning float (float64) scalefactors and # intercepts, although they are stored as in nifti1 as float32. slope = float(self['scl_slope']) inter = float(self['scl_inter']) if slope == 0 or not np.isfinite(slope): return None, None if not np.isfinite(inter): raise HeaderDataError(f'Valid slope but invalid intercept {inter}') return slope, inter def set_slope_inter(self, slope, inter=None): """ Set slope and / or intercept into header Set slope and intercept for image data, such that, if the image data is ``arr``, then the scaled image data will be ``(arr * slope) + inter`` (`slope`, `inter`) of (NaN, NaN) is a signal to a containing image to set `slope`, `inter` automatically on write. Parameters ---------- slope : None or float If None, implies `slope` of NaN. If `slope` is None or NaN then `inter` should be None or NaN. Values of 0, Inf or -Inf raise HeaderDataError inter : None or float, optional Intercept. If None, implies `inter` of NaN. If `slope` is None or NaN then `inter` should be None or NaN. Values of Inf or -Inf raise HeaderDataError """ if slope is None: slope = np.nan if inter is None: inter = np.nan if slope in (0, np.inf, -np.inf): raise HeaderDataError('Slope cannot be 0 or infinite') if inter in (np.inf, -np.inf): raise HeaderDataError('Intercept cannot be infinite') if np.isnan(slope) ^ np.isnan(inter): raise HeaderDataError('None or both of slope, inter should be nan') self._structarr['scl_slope'] = slope self._structarr['scl_inter'] = inter def get_dim_info(self): """ Gets NIfTI MRI slice etc dimension information Returns ------- freq : {None,0,1,2} Which data array axis is frequency encode direction phase : {None,0,1,2} Which data array axis is phase encode direction slice : {None,0,1,2} Which data array axis is slice encode direction where ``data array`` is the array returned by ``get_data`` Because NIfTI1 files are natively Fortran indexed: 0 is fastest changing in file 1 is medium changing in file 2 is slowest changing in file ``None`` means the axis appears not to be specified. Examples -------- See set_dim_info function """ hdr = self._structarr info = int(hdr['dim_info']) freq = info & 3 phase = (info >> 2) & 3 slice = (info >> 4) & 3 return (freq - 1 if freq else None, phase - 1 if phase else None, slice - 1 if slice else None) def set_dim_info(self, freq=None, phase=None, slice=None): """ Sets nifti MRI slice etc dimension information Parameters ---------- freq : {None, 0, 1, 2} axis of data array referring to frequency encoding phase : {None, 0, 1, 2} axis of data array referring to phase encoding slice : {None, 0, 1, 2} axis of data array referring to slice encoding ``None`` means the axis is not specified. Examples -------- >>> hdr = Nifti1Header() >>> hdr.set_dim_info(1, 2, 0) >>> hdr.get_dim_info() (1, 2, 0) >>> hdr.set_dim_info(freq=1, phase=2, slice=0) >>> hdr.get_dim_info() (1, 2, 0) >>> hdr.set_dim_info() >>> hdr.get_dim_info() (None, None, None) >>> hdr.set_dim_info(freq=1, phase=None, slice=0) >>> hdr.get_dim_info() (1, None, 0) Notes ----- This is stored in one byte in the header """ for inp in (freq, phase, slice): # Don't use == on None to avoid a FutureWarning in python3 if inp is not None and inp not in (0, 1, 2): raise HeaderDataError('Inputs must be in [None, 0, 1, 2]') info = 0 if freq is not None: info = info | ((freq + 1) & 3) if phase is not None: info = info | (((phase + 1) & 3) << 2) if slice is not None: info = info | (((slice + 1) & 3) << 4) self._structarr['dim_info'] = info def get_intent(self, code_repr='label'): """ Get intent code, parameters and name Parameters ---------- code_repr : string string giving output form of intent code representation. Default is 'label'; use 'code' for integer representation. Returns ------- code : string or integer intent code, or string describing code parameters : tuple parameters for the intent name : string intent name Examples -------- >>> hdr = Nifti1Header() >>> hdr.set_intent('t test', (10,), name='some score') >>> hdr.get_intent() ('t test', (10.0,), 'some score') >>> hdr.get_intent('code') (3, (10.0,), 'some score') """ hdr = self._structarr recoder = self._field_recoders['intent_code'] code = int(hdr['intent_code']) known_intent = code in recoder if code_repr == 'code': label = code elif code_repr == 'label': if known_intent: label = recoder.label[code] else: label = 'unknown code ' + str(code) else: raise TypeError('repr can be "label" or "code"') n_params = len(recoder.parameters[code]) if known_intent else 0 params = (float(hdr['intent_p%d' % (i + 1)]) for i in range(n_params)) name = asstr(hdr['intent_name'].item()) return label, tuple(params), name def set_intent(self, code, params=(), name='', allow_unknown=False): """ Set the intent code, parameters and name If parameters are not specified, assumed to be all zero. Each intent code has a set number of parameters associated. If you specify any parameters, then it will need to be the correct number (e.g the "f test" intent requires 2). However, parameters can also be set in the file data, so we also allow not setting any parameters (empty parameter tuple). Parameters ---------- code : integer or string code specifying nifti intent params : list, tuple of scalars parameters relating to intent (see intent_codes) defaults to (). Unspecified parameters are set to 0.0 name : string intent name (description). Defaults to '' allow_unknown : {False, True}, optional Allow unknown integer intent codes. If False (the default), a KeyError is raised on attempts to set the intent to an unknown code. Returns ------- None Examples -------- >>> hdr = Nifti1Header() >>> hdr.set_intent(0) # no intent >>> hdr.set_intent('z score') >>> hdr.get_intent() ('z score', (), '') >>> hdr.get_intent('code') (5, (), '') >>> hdr.set_intent('t test', (10,), name='some score') >>> hdr.get_intent() ('t test', (10.0,), 'some score') >>> hdr.set_intent('f test', (2, 10), name='another score') >>> hdr.get_intent() ('f test', (2.0, 10.0), 'another score') >>> hdr.set_intent('f test') >>> hdr.get_intent() ('f test', (0.0, 0.0), '') >>> hdr.set_intent(9999, allow_unknown=True) # unknown code >>> hdr.get_intent() ('unknown code 9999', (), '') """ hdr = self._structarr known_intent = code in intent_codes if not known_intent: # We can set intent via an unknown integer code, but can't via an # unknown string label if not allow_unknown or isinstance(code, str): raise KeyError('Unknown intent code: ' + str(code)) if known_intent: icode = intent_codes.code[code] p_descr = intent_codes.parameters[code] else: icode = code p_descr = ('p1', 'p2', 'p3') if len(params) and len(params) != len(p_descr): raise HeaderDataError(f'Need params of form {p_descr}, or empty') hdr['intent_code'] = icode hdr['intent_name'] = name all_params = [0] * 3 all_params[:len(params)] = params[:] for i, param in enumerate(all_params): hdr['intent_p%d' % (i + 1)] = param def get_slice_duration(self): """ Get slice duration Returns ------- slice_duration : float time to acquire one slice Examples -------- >>> hdr = Nifti1Header() >>> hdr.set_dim_info(slice=2) >>> hdr.set_slice_duration(0.3) >>> print("%0.1f" % hdr.get_slice_duration()) 0.3 Notes ----- The NIfTI1 spec appears to require the slice dimension to be defined for slice_duration to have meaning. """ _, _, slice_dim = self.get_dim_info() if slice_dim is None: raise HeaderDataError('Slice dimension must be set ' 'for duration to be valid') return float(self._structarr['slice_duration']) def set_slice_duration(self, duration): """ Set slice duration Parameters ---------- duration : scalar time to acquire one slice Examples -------- See ``get_slice_duration`` """ _, _, slice_dim = self.get_dim_info() if slice_dim is None: raise HeaderDataError('Slice dimension must be set ' 'for duration to be valid') self._structarr['slice_duration'] = duration def get_n_slices(self): """ Return the number of slices """ _, _, slice_dim = self.get_dim_info() if slice_dim is None: raise HeaderDataError('Slice dimension not set in header ' 'dim_info') shape = self.get_data_shape() try: slice_len = shape[slice_dim] except IndexError: raise HeaderDataError(f'Slice dimension index ({slice_dim}) ' f'outside shape tuple ({shape})') return slice_len def get_slice_times(self): """ Get slice times from slice timing information Returns ------- slice_times : tuple Times of acquisition of slices, where 0 is the beginning of the acquisition, ordered by position in file. nifti allows slices at the top and bottom of the volume to be excluded from the standard slice timing specification, and calls these "padding slices". We give padding slices ``None`` as a time of acquisition Examples -------- >>> hdr = Nifti1Header() >>> hdr.set_dim_info(slice=2) >>> hdr.set_data_shape((1, 1, 7)) >>> hdr.set_slice_duration(0.1) >>> hdr['slice_code'] = slice_order_codes['sequential increasing'] >>> slice_times = hdr.get_slice_times() >>> np.allclose(slice_times, [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6]) True """ hdr = self._structarr slice_len = self.get_n_slices() duration = self.get_slice_duration() slabel = self.get_value_label('slice_code') if slabel == 'unknown': raise HeaderDataError('Cannot get slice times when ' 'Slice code is "unknown"') slice_start, slice_end = (int(hdr['slice_start']), int(hdr['slice_end'])) if slice_start < 0: raise HeaderDataError('slice_start should be >= 0') if slice_end == 0: slice_end = slice_len - 1 n_timed = slice_end - slice_start + 1 if n_timed < 1: raise HeaderDataError('slice_end should be > slice_start') st_order = self._slice_time_order(slabel, n_timed) times = st_order * duration return ((None,) * slice_start + tuple(times) + (None,) * (slice_len - slice_end - 1)) def set_slice_times(self, slice_times): """ Set slice times into *hdr* Parameters ---------- slice_times : tuple tuple of slice times, one value per slice tuple can include None to indicate no slice time for that slice Examples -------- >>> hdr = Nifti1Header() >>> hdr.set_dim_info(slice=2) >>> hdr.set_data_shape([1, 1, 7]) >>> hdr.set_slice_duration(0.1) >>> times = [None, 0.2, 0.4, 0.1, 0.3, 0.0, None] >>> hdr.set_slice_times(times) >>> hdr.get_value_label('slice_code') 'alternating decreasing' >>> int(hdr['slice_start']) 1 >>> int(hdr['slice_end']) 5 """ # Check if number of slices matches header hdr = self._structarr slice_len = self.get_n_slices() if slice_len != len(slice_times): raise HeaderDataError('Number of slice times does not ' 'match number of slices') # Extract Nones at beginning and end. Check for others for ind, time in enumerate(slice_times): if time is not None: slice_start = ind break else: raise HeaderDataError('Not all slice times can be None') for ind, time in enumerate(slice_times[::-1]): if time is not None: slice_end = slice_len - ind - 1 break timed = slice_times[slice_start:slice_end + 1] for time in timed: if time is None: raise HeaderDataError('Cannot have None in middle ' 'of slice time vector') # Find slice duration, check times are compatible with single # duration tdiffs = np.diff(np.sort(timed)) if not np.allclose(np.diff(tdiffs), 0): raise HeaderDataError('Slice times not compatible with ' 'single slice duration') duration = np.mean(tdiffs) # To slice time order st_order = np.round(np.array(timed) / duration) # Check if slice times fit known schemes n_timed = len(timed) so_recoder = self._field_recoders['slice_code'] labels = so_recoder.value_set('label') labels.remove('unknown') matching_labels = [] for label in labels: if np.all(st_order == self._slice_time_order( label, n_timed)): matching_labels.append(label) if not matching_labels: raise HeaderDataError(f'slice ordering of {st_order} fits with no known scheme') if len(matching_labels) > 1: warnings.warn( f"Multiple slice orders satisfy: {', '.join(matching_labels)}. " "Choosing the first one") label = matching_labels[0] # Set values into header hdr['slice_start'] = slice_start hdr['slice_end'] = slice_end hdr['slice_duration'] = duration hdr['slice_code'] = slice_order_codes.code[label] def _slice_time_order(self, slabel, n_slices): """ Supporting function to give time order of slices from label """ if slabel == 'sequential increasing': sp_ind_time_order = list(range(n_slices)) elif slabel == 'sequential decreasing': sp_ind_time_order = list(range(n_slices)[::-1]) elif slabel == 'alternating increasing': sp_ind_time_order = (list(range(0, n_slices, 2)) + list(range(1, n_slices, 2))) elif slabel == 'alternating decreasing': sp_ind_time_order = (list(range(n_slices - 1, -1, -2)) + list(range(n_slices - 2, -1, -2))) elif slabel == 'alternating increasing 2': sp_ind_time_order = (list(range(1, n_slices, 2)) + list(range(0, n_slices, 2))) elif slabel == 'alternating decreasing 2': sp_ind_time_order = (list(range(n_slices - 2, -1, -2)) + list(range(n_slices - 1, -1, -2))) else: raise HeaderDataError(f'We do not handle slice ordering "{slabel}"') return np.argsort(sp_ind_time_order) def get_xyzt_units(self): xyz_code = self.structarr['xyzt_units'] % 8 t_code = self.structarr['xyzt_units'] - xyz_code return (unit_codes.label[xyz_code], unit_codes.label[t_code]) def set_xyzt_units(self, xyz=None, t=None): if xyz is None: xyz = 0 if t is None: t = 0 xyz_code = self.structarr['xyzt_units'] % 8 t_code = self.structarr['xyzt_units'] - xyz_code xyz_code = unit_codes[xyz] t_code = unit_codes[t] self.structarr['xyzt_units'] = xyz_code + t_code def _clean_after_mapping(self): """ Set format-specific stuff after converting header from mapping Clean up header after it has been initialized from an ``as_analyze_map`` method of another header type See :meth:`nibabel.analyze.AnalyzeHeader._clean_after_mapping` for a more detailed description. """ self._structarr['magic'] = (self.single_magic if self.is_single else self.pair_magic) """ Checks only below here """ @classmethod def _get_checks(klass): # We need to return our own versions of - e.g. chk_datatype, to # pick up the Nifti datatypes from our class return (klass._chk_sizeof_hdr, klass._chk_datatype, klass._chk_bitpix, klass._chk_pixdims, klass._chk_qfac, klass._chk_magic, klass._chk_offset, klass._chk_qform_code, klass._chk_sform_code) @staticmethod def _chk_qfac(hdr, fix=False): rep = Report(HeaderDataError) if hdr['pixdim'][0] in (-1, 1): return hdr, rep rep.problem_level = 20 rep.problem_msg = 'pixdim[0] (qfac) should be 1 (default) or -1' if fix: hdr['pixdim'][0] = 1 rep.fix_msg = 'setting qfac to 1' return hdr, rep @staticmethod def _chk_magic(hdr, fix=False): rep = Report(HeaderDataError) magic = hdr['magic'].item() if magic in (hdr.pair_magic, hdr.single_magic): return hdr, rep rep.problem_msg = f'magic string "{asstr(magic)}" is not valid' rep.problem_level = 45 if fix: rep.fix_msg = 'leaving as is, but future errors are likely' return hdr, rep @staticmethod def _chk_offset(hdr, fix=False): rep = Report(HeaderDataError) # for ease of later string formatting, use scalar of byte string magic = hdr['magic'].item() offset = hdr['vox_offset'].item() if offset == 0: return hdr, rep if magic == hdr.single_magic and offset < hdr.single_vox_offset: rep.problem_level = 40 rep.problem_msg = ('vox offset %d too low for ' 'single file nifti1' % offset) if fix: hdr['vox_offset'] = hdr.single_vox_offset rep.fix_msg = f'setting to minimum value of {hdr.single_vox_offset}' return hdr, rep if not offset % 16: return hdr, rep # SPM uses memory mapping to read the data, and # apparently this has to start on 16 byte boundaries rep.problem_msg = f'vox offset (={offset:g}) not divisible by 16, not SPM compatible' rep.problem_level = 30 if fix: rep.fix_msg = 'leaving at current value' return hdr, rep @classmethod def _chk_qform_code(klass, hdr, fix=False): return klass._chk_xform_code('qform_code', hdr, fix) @classmethod def _chk_sform_code(klass, hdr, fix=False): return klass._chk_xform_code('sform_code', hdr, fix) @classmethod def _chk_xform_code(klass, code_type, hdr, fix): # utility method for sform and qform codes rep = Report(HeaderDataError) code = int(hdr[code_type]) recoder = klass._field_recoders[code_type] if code in recoder.value_set(): return hdr, rep rep.problem_level = 30 rep.problem_msg = '%s %d not valid' % (code_type, code) if fix: hdr[code_type] = 0 rep.fix_msg = 'setting to 0' return hdr, rep @classmethod def may_contain_header(klass, binaryblock): if len(binaryblock) < klass.sizeof_hdr: return False hdr_struct = np.ndarray(shape=(), dtype=header_dtype, buffer=binaryblock[:klass.sizeof_hdr]) return hdr_struct['magic'] in (b'ni1', b'n+1') class Nifti1PairHeader(Nifti1Header): """ Class for NIfTI1 pair header """ # Signal whether this is single (header + data) file is_single = False class Nifti1Pair(analyze.AnalyzeImage): """ Class for NIfTI1 format image, header pair """ header_class = Nifti1PairHeader _meta_sniff_len = header_class.sizeof_hdr rw = True def __init__(self, dataobj, affine, header=None, extra=None, file_map=None): super(Nifti1Pair, self).__init__(dataobj, affine, header, extra, file_map) # Force set of s/q form when header is None unless affine is also None if header is None and affine is not None: self._affine2header() # Copy docstring __init__.__doc__ = analyze.AnalyzeImage.__init__.__doc__ + """ Notes ----- If both a `header` and an `affine` are specified, and the `affine` does not match the affine that is in the `header`, the `affine` will be used, but the ``sform_code`` and ``qform_code`` fields in the header will be re-initialised to their default values. This is performed on the basis that, if you are changing the affine, you are likely to be changing the space to which the affine is pointing. The :meth:`set_sform` and :meth:`set_qform` methods can be used to update the codes after an image has been created - see those methods, and the :ref:`manual <default-sform-qform-codes>` for more details. """ def update_header(self): """ Harmonize header with image data and affine See AnalyzeImage.update_header for more examples Examples -------- >>> data = np.zeros((2,3,4)) >>> affine = np.diag([1.0,2.0,3.0,1.0]) >>> img = Nifti1Image(data, affine) >>> hdr = img.header >>> np.all(hdr.get_qform() == affine) True >>> np.all(hdr.get_sform() == affine) True """ super(Nifti1Pair, self).update_header() hdr = self._header hdr['magic'] = hdr.pair_magic def _affine2header(self): """ Unconditionally set affine into the header """ hdr = self._header # Set affine into sform with default code hdr.set_sform(self._affine, code='aligned') # Make qform 'unknown' hdr.set_qform(self._affine, code='unknown') def get_qform(self, coded=False): """ Return 4x4 affine matrix from qform parameters in header Parameters ---------- coded : bool, optional If True, return {affine or None}, and qform code. If False, just return affine. {affine or None} means, return None if qform code == 0, and affine otherwise. Returns ------- affine : None or (4,4) ndarray If `coded` is False, always return affine reconstructed from qform quaternion. If `coded` is True, return None if qform code is 0, else return the affine. code : int Qform code. Only returned if `coded` is True. See also -------- set_qform get_sform """ return self._header.get_qform(coded) def set_qform(self, affine, code=None, strip_shears=True, **kwargs): """ Set qform header values from 4x4 affine Parameters ---------- affine : None or 4x4 array affine transform to write into sform. If None, only set code. code : None, string or integer String or integer giving meaning of transform in *affine*. The default is None. If code is None, then: * If affine is None, `code`-> 0 * If affine not None and existing qform code in header == 0, `code`-> 2 (aligned) * If affine not None and existing qform code in header != 0, `code`-> existing qform code in header strip_shears : bool, optional Whether to strip shears in `affine`. If True, shears will be silently stripped. If False, the presence of shears will raise a ``HeaderDataError`` update_affine : bool, optional Whether to update the image affine from the header best affine after setting the qform. Must be keyword argument (because of different position in `set_qform`). Default is True See also -------- get_qform set_sform Examples -------- >>> data = np.arange(24).reshape((2,3,4)) >>> aff = np.diag([2, 3, 4, 1]) >>> img = Nifti1Pair(data, aff) >>> img.get_qform() array([[2., 0., 0., 0.], [0., 3., 0., 0.], [0., 0., 4., 0.], [0., 0., 0., 1.]]) >>> img.get_qform(coded=True) (None, 0) >>> aff2 = np.diag([3, 4, 5, 1]) >>> img.set_qform(aff2, 'talairach') >>> qaff, code = img.get_qform(coded=True) >>> np.all(qaff == aff2) True >>> int(code) 3 """ update_affine = kwargs.pop('update_affine', True) if kwargs: raise TypeError(f'Unexpected keyword argument(s) {kwargs}') self._header.set_qform(affine, code, strip_shears) if update_affine: if self._affine is None: self._affine = self._header.get_best_affine() else: self._affine[:] = self._header.get_best_affine() def get_sform(self, coded=False): """ Return 4x4 affine matrix from sform parameters in header Parameters ---------- coded : bool, optional If True, return {affine or None}, and sform code. If False, just return affine. {affine or None} means, return None if sform code == 0, and affine otherwise. Returns ------- affine : None or (4,4) ndarray If `coded` is False, always return affine from sform fields. If `coded` is True, return None if sform code is 0, else return the affine. code : int Sform code. Only returned if `coded` is True. See also -------- set_sform get_qform """ return self._header.get_sform(coded) def set_sform(self, affine, code=None, **kwargs): """ Set sform transform from 4x4 affine Parameters ---------- affine : None or 4x4 array affine transform to write into sform. If None, only set `code` code : None, string or integer String or integer giving meaning of transform in *affine*. The default is None. If code is None, then: * If affine is None, `code`-> 0 * If affine not None and existing sform code in header == 0, `code`-> 2 (aligned) * If affine not None and existing sform code in header != 0, `code`-> existing sform code in header update_affine : bool, optional Whether to update the image affine from the header best affine after setting the qform. Must be keyword argument (because of different position in `set_qform`). Default is True See also -------- get_sform set_qform Examples -------- >>> data = np.arange(24).reshape((2,3,4)) >>> aff = np.diag([2, 3, 4, 1]) >>> img = Nifti1Pair(data, aff) >>> img.get_sform() array([[2., 0., 0., 0.], [0., 3., 0., 0.], [0., 0., 4., 0.], [0., 0., 0., 1.]]) >>> saff, code = img.get_sform(coded=True) >>> saff array([[2., 0., 0., 0.], [0., 3., 0., 0.], [0., 0., 4., 0.], [0., 0., 0., 1.]]) >>> int(code) 2 >>> aff2 = np.diag([3, 4, 5, 1]) >>> img.set_sform(aff2, 'talairach') >>> saff, code = img.get_sform(coded=True) >>> np.all(saff == aff2) True >>> int(code) 3 """ update_affine = kwargs.pop('update_affine', True) if kwargs: raise TypeError(f'Unexpected keyword argument(s) {kwargs}') self._header.set_sform(affine, code) if update_affine: if self._affine is None: self._affine = self._header.get_best_affine() else: self._affine[:] = self._header.get_best_affine() def as_reoriented(self, ornt): """Apply an orientation change and return a new image If ornt is identity transform, return the original image, unchanged Parameters ---------- ornt : (n,2) orientation array orientation transform. ``ornt[N,1]` is flip of axis N of the array implied by `shape`, where 1 means no flip and -1 means flip. For example, if ``N==0`` and ``ornt[0,1] == -1``, and there's an array ``arr`` of shape `shape`, the flip would correspond to the effect of ``np.flipud(arr)``. ``ornt[:,0]`` is the transpose that needs to be done to the implied array, as in ``arr.transpose(ornt[:,0])`` """ img = super(Nifti1Pair, self).as_reoriented(ornt) if img is self: return img # Also apply the transform to the dim_info fields new_dim = [ None if orig_dim is None else int(ornt[orig_dim, 0]) for orig_dim in img.header.get_dim_info()] img.header.set_dim_info(*new_dim) return img class Nifti1Image(Nifti1Pair, SerializableImage): """ Class for single file NIfTI1 format image """ header_class = Nifti1Header valid_exts = ('.nii',) files_types = (('image', '.nii'),) @staticmethod def _get_fileholders(file_map): """ Return fileholder for header and image For single-file niftis, the fileholder for the header and the image will be the same """ return file_map['image'], file_map['image'] def update_header(self): """ Harmonize header with image data and affine """ super(Nifti1Image, self).update_header() hdr = self._header hdr['magic'] = hdr.single_magic def load(filename): """ Load NIfTI1 single or pair from `filename` Parameters ---------- filename : str filename of image to be loaded Returns ------- img : Nifti1Image or Nifti1Pair NIfTI1 single or pair image instance Raises ------ ImageFileError if `filename` doesn't look like NIfTI1; IOError if `filename` does not exist. """ try: img = Nifti1Image.load(filename) except ImageFileError: return Nifti1Pair.load(filename) return img def save(img, filename): """ Save NIfTI1 single or pair to `filename` Parameters ---------- filename : str filename to which to save image """ try: Nifti1Image.instance_to_filename(img, filename) except ImageFileError: Nifti1Pair.instance_to_filename(img, filename)
# --------- Notes --------- # This version uses PostgreSQL as the backend database # The reason why is that SQLite3 locks up very fast and is not recommended for cogs like these, where high read/write speeds are key # Make sure to have an PostgreSQL server running, and a database called "disquest" import asyncio import math import os import random import discord import uvloop from discord.commands import slash_command from discord.ext import commands from dotenv import load_dotenv from sqlalchemy import (BigInteger, Column, Integer, MetaData, Sequence, Table, func, select) from sqlalchemy.ext.asyncio import create_async_engine load_dotenv() # Make sure to create an .env file and add the env values Password = os.getenv("Postgres_Password") IP = os.getenv("Postgres_Server_IP") Username = os.getenv("Postgres_Username") class disaccount: def __init__(self, ctx): self.id = ctx.author.id self.gid = ctx.guild.id async def getxp(self): meta = MetaData() engine = create_async_engine( f"postgresql+asyncpg://{Username}:{Password}@{IP}:5432/disquest" ) users = Table( "users", meta, Column( "tracking_id", Integer, Sequence("tracking_id"), primary_key=True, autoincrement=True, ), Column("id", BigInteger), Column("gid", BigInteger), Column("xp", Integer), ) async with engine.connect() as conn: s = select(users.c.xp).where( users.c.id == self.id, users.c.gid == self.gid) results = await conn.execute(s) results_fetched = results.fetchone() if results_fetched is None: insert_new = users.insert().values(xp=0, id=self.id, gid=self.gid) await conn.execute(insert_new) else: for row in results_fetched: return row async def setxp(self, xp): meta = MetaData() engine = create_async_engine( f"postgresql+asyncpg://{Username}:{Password}@{IP}:5432/rin-disquest" ) users = Table( "users", meta, Column( "tracking_id", Integer, Sequence("tracking_id"), primary_key=True, autoincrement=True, ), Column("id", BigInteger), Column("gid", BigInteger), Column("xp", Integer), ) async with engine.begin() as conn: update_values = ( users.update() .values(xp=xp) .filter(users.c.id == self.id) .filter(users.c.gid == self.gid) ) await conn.execute(update_values) async def addxp(self, offset): pxp = await self.getxp() pxp += offset await self.setxp(pxp) class lvl: def near(xp): return round(xp / 100) def next(xp): return math.ceil(xp / 100) def cur(xp): return int(xp / 100) class DisQuest(commands.Cog): def __init__(self, bot): self.bot = bot @slash_command( name="mylvl", description="Displays your activity level!", guild_ids=[866199405090308116], ) async def mylvl(self, ctx): user = disaccount(ctx) xp = await user.getxp() embedVar = discord.Embed(color=discord.Color.from_rgb(255, 217, 254)) embedVar.add_field( name="User", value=f"{ctx.author.mention}", inline=True) embedVar.add_field(name="LVL", value=f"{lvl.cur(xp)}", inline=True) embedVar.add_field( name="XP", value=f"{xp}/{lvl.next(xp)*100}", inline=True) await ctx.respond(embed=embedVar) asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) class DisQuestV2(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command( name="rank", help="Displays the most active members of your server!" ) @slash_command( name="rank", description="Displays the most active members of your server!", guild_ids=[866199405090308116], ) async def rank(self, ctx): gid = ctx.guild.id meta = MetaData() engine = create_async_engine( f"postgresql+asyncpg://{Username}:{Password}@{IP}:5432/rin-disquest" ) users = Table( "users", meta, Column( "tracking_id", Integer, Sequence("tracking_id"), primary_key=True, autoincrement=True, ), Column("id", BigInteger), Column("gid", BigInteger), Column("xp", Integer), ) async with engine.connect() as conn: s = ( select(Column("id", BigInteger), Column("xp", Integer)) .where(users.c.gid == gid) .order_by(users.c.xp.desc()) ) results = await conn.execute(s) members = list(results.fetchall()) for i, mem in enumerate(members): members[ i ] = f"{i}. {(await self.bot.fetch_user(mem[0])).name} | XP. {mem[1]}\n" embedVar = discord.Embed( color=discord.Color.from_rgb(254, 255, 217)) embedVar.description = f"**Server Rankings**\n{"".join(members)}" await ctx.respond(embed=embedVar) asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) class DisQuestV3(commands.Cog): def __init__(self, bot): self.bot = bot @slash_command( name="globalrank", description="Displays the most active members of all servers that this bot is connected to!", guild_ids=[866199405090308116], ) async def grank(self, ctx): meta = MetaData() engine = create_async_engine( f"postgresql+asyncpg://{Username}:{Password}@{IP}:5432/rin-disquest" ) users = Table( "users", meta, Column( "tracking_id", Integer, Sequence("tracking_id"), primary_key=True, autoincrement=True, ), Column("id", BigInteger), Column("gid", BigInteger), Column("xp", Integer), ) async with engine.connect() as conn: s = ( select(Column("id", Integer), func.sum( users.c.xp).label("txp")) .group_by(users.c.id) .group_by(users.c.xp) .order_by(users.c.xp.desc()) .limit(10) ) results = await conn.execute(s) results_fetched = results.fetchall() members = list(results_fetched) for i, mem in enumerate(members): members[ i ] = f"{i}. {(await self.bot.fetch_user(mem[0])).name} | XP. {mem[1]}\n" embedVar = discord.Embed( color=discord.Color.from_rgb(217, 255, 251)) embedVar.description = f"**Global Rankings**\n{"".join(members)}" await ctx.respond(embed=embedVar) asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) class DisQuestV4(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_message(self, ctx): if ctx.author.bot: return user = disaccount(ctx) reward = random.randint(0, 20) await user.addxp(reward) asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) def setup(bot): bot.add_cog(DisQuest(bot)) bot.add_cog(DisQuestV2(bot)) bot.add_cog(DisQuestV3(bot)) bot.add_cog(DisQuestV4(bot))
# --------- Notes --------- # This version uses PostgreSQL as the backend database # The reason why is that SQLite3 locks up very fast and is not recommended for cogs like these, where high read/write speeds are key # Make sure to have an PostgreSQL server running, and a database called "disquest" import asyncio import math import os import random import discord import uvloop from discord.commands import slash_command from discord.ext import commands from dotenv import load_dotenv from sqlalchemy import (BigInteger, Column, Integer, MetaData, Sequence, Table, func, select) from sqlalchemy.ext.asyncio import create_async_engine load_dotenv() # Make sure to create an .env file and add the env values Password = os.getenv("Postgres_Password") IP = os.getenv("Postgres_Server_IP") Username = os.getenv("Postgres_Username") class disaccount: def __init__(self, ctx): self.id = ctx.author.id self.gid = ctx.guild.id async def getxp(self): meta = MetaData() engine = create_async_engine( f"postgresql+asyncpg://{Username}:{Password}@{IP}:5432/disquest" ) users = Table( "users", meta, Column( "tracking_id", Integer, Sequence("tracking_id"), primary_key=True, autoincrement=True, ), Column("id", BigInteger), Column("gid", BigInteger), Column("xp", Integer), ) async with engine.connect() as conn: s = select(users.c.xp).where( users.c.id == self.id, users.c.gid == self.gid) results = await conn.execute(s) results_fetched = results.fetchone() if results_fetched is None: insert_new = users.insert().values(xp=0, id=self.id, gid=self.gid) await conn.execute(insert_new) else: for row in results_fetched: return row async def setxp(self, xp): meta = MetaData() engine = create_async_engine( f"postgresql+asyncpg://{Username}:{Password}@{IP}:5432/rin-disquest" ) users = Table( "users", meta, Column( "tracking_id", Integer, Sequence("tracking_id"), primary_key=True, autoincrement=True, ), Column("id", BigInteger), Column("gid", BigInteger), Column("xp", Integer), ) async with engine.begin() as conn: update_values = ( users.update() .values(xp=xp) .filter(users.c.id == self.id) .filter(users.c.gid == self.gid) ) await conn.execute(update_values) async def addxp(self, offset): pxp = await self.getxp() pxp += offset await self.setxp(pxp) class lvl: def near(xp): return round(xp / 100) def next(xp): return math.ceil(xp / 100) def cur(xp): return int(xp / 100) class DisQuest(commands.Cog): def __init__(self, bot): self.bot = bot @slash_command( name="mylvl", description="Displays your activity level!", guild_ids=[866199405090308116], ) async def mylvl(self, ctx): user = disaccount(ctx) xp = await user.getxp() embedVar = discord.Embed(color=discord.Color.from_rgb(255, 217, 254)) embedVar.add_field( name="User", value=f"{ctx.author.mention}", inline=True) embedVar.add_field(name="LVL", value=f"{lvl.cur(xp)}", inline=True) embedVar.add_field( name="XP", value=f"{xp}/{lvl.next(xp)*100}", inline=True) await ctx.respond(embed=embedVar) asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) class DisQuestV2(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command( name="rank", help="Displays the most active members of your server!" ) @slash_command( name="rank", description="Displays the most active members of your server!", guild_ids=[866199405090308116], ) async def rank(self, ctx): gid = ctx.guild.id meta = MetaData() engine = create_async_engine( f"postgresql+asyncpg://{Username}:{Password}@{IP}:5432/rin-disquest" ) users = Table( "users", meta, Column( "tracking_id", Integer, Sequence("tracking_id"), primary_key=True, autoincrement=True, ), Column("id", BigInteger), Column("gid", BigInteger), Column("xp", Integer), ) async with engine.connect() as conn: s = ( select(Column("id", BigInteger), Column("xp", Integer)) .where(users.c.gid == gid) .order_by(users.c.xp.desc()) ) results = await conn.execute(s) members = list(results.fetchall()) for i, mem in enumerate(members): members[ i ] = f"{i}. {(await self.bot.fetch_user(mem[0])).name} | XP. {mem[1]}\n" embedVar = discord.Embed( color=discord.Color.from_rgb(254, 255, 217)) embedVar.description = f"**Server Rankings**\n{''.join(members)}" await ctx.respond(embed=embedVar) asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) class DisQuestV3(commands.Cog): def __init__(self, bot): self.bot = bot @slash_command( name="globalrank", description="Displays the most active members of all servers that this bot is connected to!", guild_ids=[866199405090308116], ) async def grank(self, ctx): meta = MetaData() engine = create_async_engine( f"postgresql+asyncpg://{Username}:{Password}@{IP}:5432/rin-disquest" ) users = Table( "users", meta, Column( "tracking_id", Integer, Sequence("tracking_id"), primary_key=True, autoincrement=True, ), Column("id", BigInteger), Column("gid", BigInteger), Column("xp", Integer), ) async with engine.connect() as conn: s = ( select(Column("id", Integer), func.sum( users.c.xp).label("txp")) .group_by(users.c.id) .group_by(users.c.xp) .order_by(users.c.xp.desc()) .limit(10) ) results = await conn.execute(s) results_fetched = results.fetchall() members = list(results_fetched) for i, mem in enumerate(members): members[ i ] = f"{i}. {(await self.bot.fetch_user(mem[0])).name} | XP. {mem[1]}\n" embedVar = discord.Embed( color=discord.Color.from_rgb(217, 255, 251)) embedVar.description = f"**Global Rankings**\n{''.join(members)}" await ctx.respond(embed=embedVar) asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) class DisQuestV4(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_message(self, ctx): if ctx.author.bot: return user = disaccount(ctx) reward = random.randint(0, 20) await user.addxp(reward) asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) def setup(bot): bot.add_cog(DisQuest(bot)) bot.add_cog(DisQuestV2(bot)) bot.add_cog(DisQuestV3(bot)) bot.add_cog(DisQuestV4(bot))
import requests from .enums import TransactionStatus from .exceptions import InvalidPaymentException, SslcommerzAPIException from .services import PayloadSchema, is_verify_sign_valid DEFAULT_CONFIG = { "base_url": "https://sandbox.sslcommerz.com", "session_url": "/gwprocess/v4/api.php", "validation_url": "/validator/api/validationserverAPI.php", "transaction_url": "/validator/api/merchantTransIDvalidationAPI.php", } class SslcommerzStore: def __init__(self, store_id, store_passwd, **kwargs): self.id = store_id self.credentials = dict(store_id=store_id, store_passwd=store_passwd) self.config = {**DEFAULT_CONFIG, **kwargs} def request(self, method, url, **kwargs): url = self.config["base_url"] + url return requests.request(method, url, **kwargs) def create_session(self, **kwargs): response = self.request( method="POST", url=self.config["session_url"], data={**self.credentials, **kwargs}, ) if response.status_code != 200: raise SslcommerzAPIException( f"Unexpected status code: {response.status_code}" ) response_json = response.json() if response_json["status"] != "SUCCESS": raise SslcommerzAPIException(f"Error: {response_json["failedreason"]}") return response_json def validate_ipn_payload(self, payload): try: if not is_verify_sign_valid( store_passwd=self.credentials["store_passwd"], payload=payload["original"], ): raise InvalidPaymentException("verify_sign mismatch") if payload["status"] == TransactionStatus.VALID: validation_response = self.validate_transaction(payload["val_id"]) if validation_response["status"] not in ( TransactionStatus.VALID, TransactionStatus.VALIDATED, ): raise InvalidPaymentException( f"Payment status: {validation_response["status"]}" ) return PayloadSchema().load(validation_response) except KeyError as key: raise InvalidPaymentException(f"{key} is missing in payload") from key def validate_transaction(self, val_id): response = self.request( method="GET", url=self.config["validation_url"], params=dict(**self.credentials, val_id=val_id, format="json"), ) if response.status_code != 200: raise SslcommerzAPIException( f"Unexpected status code: {response.status_code}" ) return response.json() def query_transaction_by_sessionkey(self, sessionkey): response = self.request( method="GET", url=self.config["transaction_url"], params=dict(**self.credentials, sessionkey=sessionkey, format="json"), ) return response.json() def query_transaction_by_tran_id(self, tran_id): response = self.request( method="GET", url=self.config["transaction_url"], params=dict(**self.credentials, tran_id=tran_id, format="json"), ) return response.json() def init_refund(self, bank_tran_id, refund_amount, refund_remarks): response = self.request( method="GET", url=self.config["transaction_url"], params=dict( **self.credentials, bank_tran_id=bank_tran_id, refund_amount=refund_amount, refund_remarks=refund_remarks, format="json", ), ) return response.json() def query_refund_status(self, refund_ref_id): response = self.request( method="GET", url=self.config["transaction_url"], params=dict(**self.credentials, refund_ref_id=refund_ref_id, format="json"), ) return response.json()
import requests from .enums import TransactionStatus from .exceptions import InvalidPaymentException, SslcommerzAPIException from .services import PayloadSchema, is_verify_sign_valid DEFAULT_CONFIG = { "base_url": "https://sandbox.sslcommerz.com", "session_url": "/gwprocess/v4/api.php", "validation_url": "/validator/api/validationserverAPI.php", "transaction_url": "/validator/api/merchantTransIDvalidationAPI.php", } class SslcommerzStore: def __init__(self, store_id, store_passwd, **kwargs): self.id = store_id self.credentials = dict(store_id=store_id, store_passwd=store_passwd) self.config = {**DEFAULT_CONFIG, **kwargs} def request(self, method, url, **kwargs): url = self.config["base_url"] + url return requests.request(method, url, **kwargs) def create_session(self, **kwargs): response = self.request( method="POST", url=self.config["session_url"], data={**self.credentials, **kwargs}, ) if response.status_code != 200: raise SslcommerzAPIException( f"Unexpected status code: {response.status_code}" ) response_json = response.json() if response_json["status"] != "SUCCESS": raise SslcommerzAPIException(f"Error: {response_json['failedreason']}") return response_json def validate_ipn_payload(self, payload): try: if not is_verify_sign_valid( store_passwd=self.credentials["store_passwd"], payload=payload["original"], ): raise InvalidPaymentException("verify_sign mismatch") if payload["status"] == TransactionStatus.VALID: validation_response = self.validate_transaction(payload["val_id"]) if validation_response["status"] not in ( TransactionStatus.VALID, TransactionStatus.VALIDATED, ): raise InvalidPaymentException( f"Payment status: {validation_response['status']}" ) return PayloadSchema().load(validation_response) except KeyError as key: raise InvalidPaymentException(f"{key} is missing in payload") from key def validate_transaction(self, val_id): response = self.request( method="GET", url=self.config["validation_url"], params=dict(**self.credentials, val_id=val_id, format="json"), ) if response.status_code != 200: raise SslcommerzAPIException( f"Unexpected status code: {response.status_code}" ) return response.json() def query_transaction_by_sessionkey(self, sessionkey): response = self.request( method="GET", url=self.config["transaction_url"], params=dict(**self.credentials, sessionkey=sessionkey, format="json"), ) return response.json() def query_transaction_by_tran_id(self, tran_id): response = self.request( method="GET", url=self.config["transaction_url"], params=dict(**self.credentials, tran_id=tran_id, format="json"), ) return response.json() def init_refund(self, bank_tran_id, refund_amount, refund_remarks): response = self.request( method="GET", url=self.config["transaction_url"], params=dict( **self.credentials, bank_tran_id=bank_tran_id, refund_amount=refund_amount, refund_remarks=refund_remarks, format="json", ), ) return response.json() def query_refund_status(self, refund_ref_id): response = self.request( method="GET", url=self.config["transaction_url"], params=dict(**self.credentials, refund_ref_id=refund_ref_id, format="json"), ) return response.json()
"""Config flow for ZHA.""" from __future__ import annotations import os from typing import Any import serial.tools.list_ports import voluptuous as vol from zigpy.config import CONF_DEVICE, CONF_DEVICE_PATH from homeassistant import config_entries from .core.const import ( CONF_BAUDRATE, CONF_FLOWCONTROL, CONF_RADIO_TYPE, DOMAIN, RadioType, ) CONF_MANUAL_PATH = "Enter Manually" SUPPORTED_PORT_SETTINGS = ( CONF_BAUDRATE, CONF_FLOWCONTROL, ) class ZhaFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow.""" VERSION = 2 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH def __init__(self): """Initialize flow instance.""" self._device_path = None self._radio_type = None async def async_step_user(self, user_input=None): """Handle a zha config flow start.""" if self._async_current_entries(): return self.async_abort(reason="single_instance_allowed") ports = await self.hass.async_add_executor_job(serial.tools.list_ports.comports) list_of_ports = [ f"{p}, s/n: {p.serial_number or "n/a"}" + (f" - {p.manufacturer}" if p.manufacturer else "") for p in ports ] if not list_of_ports: return await self.async_step_pick_radio() list_of_ports.append(CONF_MANUAL_PATH) if user_input is not None: user_selection = user_input[CONF_DEVICE_PATH] if user_selection == CONF_MANUAL_PATH: return await self.async_step_pick_radio() port = ports[list_of_ports.index(user_selection)] dev_path = await self.hass.async_add_executor_job( get_serial_by_id, port.device ) auto_detected_data = await detect_radios(dev_path) if auto_detected_data is not None: title = f"{port.description}, s/n: {port.serial_number or "n/a"}" title += f" - {port.manufacturer}" if port.manufacturer else "" return self.async_create_entry( title=title, data=auto_detected_data, ) # did not detect anything self._device_path = dev_path return await self.async_step_pick_radio() schema = vol.Schema({vol.Required(CONF_DEVICE_PATH): vol.In(list_of_ports)}) return self.async_show_form(step_id="user", data_schema=schema) async def async_step_pick_radio(self, user_input=None): """Select radio type.""" if user_input is not None: self._radio_type = RadioType.get_by_description(user_input[CONF_RADIO_TYPE]) return await self.async_step_port_config() schema = {vol.Required(CONF_RADIO_TYPE): vol.In(sorted(RadioType.list()))} return self.async_show_form( step_id="pick_radio", data_schema=vol.Schema(schema), ) async def async_step_port_config(self, user_input=None): """Enter port settings specific for this type of radio.""" errors = {} app_cls = RadioType[self._radio_type].controller if user_input is not None: self._device_path = user_input.get(CONF_DEVICE_PATH) if await app_cls.probe(user_input): serial_by_id = await self.hass.async_add_executor_job( get_serial_by_id, user_input[CONF_DEVICE_PATH] ) user_input[CONF_DEVICE_PATH] = serial_by_id return self.async_create_entry( title=user_input[CONF_DEVICE_PATH], data={CONF_DEVICE: user_input, CONF_RADIO_TYPE: self._radio_type}, ) errors["base"] = "cannot_connect" schema = { vol.Required( CONF_DEVICE_PATH, default=self._device_path or vol.UNDEFINED ): str } radio_schema = app_cls.SCHEMA_DEVICE.schema if isinstance(radio_schema, vol.Schema): radio_schema = radio_schema.schema for param, value in radio_schema.items(): if param in SUPPORTED_PORT_SETTINGS: schema[param] = value return self.async_show_form( step_id="port_config", data_schema=vol.Schema(schema), errors=errors, ) async def detect_radios(dev_path: str) -> dict[str, Any] | None: """Probe all radio types on the device port.""" for radio in RadioType: dev_config = radio.controller.SCHEMA_DEVICE({CONF_DEVICE_PATH: dev_path}) if await radio.controller.probe(dev_config): return {CONF_RADIO_TYPE: radio.name, CONF_DEVICE: dev_config} return None def get_serial_by_id(dev_path: str) -> str: """Return a /dev/serial/by-id match for given device if available.""" by_id = "/dev/serial/by-id" if not os.path.isdir(by_id): return dev_path for path in (entry.path for entry in os.scandir(by_id) if entry.is_symlink()): if os.path.realpath(path) == dev_path: return path return dev_path
"""Config flow for ZHA.""" from __future__ import annotations import os from typing import Any import serial.tools.list_ports import voluptuous as vol from zigpy.config import CONF_DEVICE, CONF_DEVICE_PATH from homeassistant import config_entries from .core.const import ( CONF_BAUDRATE, CONF_FLOWCONTROL, CONF_RADIO_TYPE, DOMAIN, RadioType, ) CONF_MANUAL_PATH = "Enter Manually" SUPPORTED_PORT_SETTINGS = ( CONF_BAUDRATE, CONF_FLOWCONTROL, ) class ZhaFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow.""" VERSION = 2 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH def __init__(self): """Initialize flow instance.""" self._device_path = None self._radio_type = None async def async_step_user(self, user_input=None): """Handle a zha config flow start.""" if self._async_current_entries(): return self.async_abort(reason="single_instance_allowed") ports = await self.hass.async_add_executor_job(serial.tools.list_ports.comports) list_of_ports = [ f"{p}, s/n: {p.serial_number or 'n/a'}" + (f" - {p.manufacturer}" if p.manufacturer else "") for p in ports ] if not list_of_ports: return await self.async_step_pick_radio() list_of_ports.append(CONF_MANUAL_PATH) if user_input is not None: user_selection = user_input[CONF_DEVICE_PATH] if user_selection == CONF_MANUAL_PATH: return await self.async_step_pick_radio() port = ports[list_of_ports.index(user_selection)] dev_path = await self.hass.async_add_executor_job( get_serial_by_id, port.device ) auto_detected_data = await detect_radios(dev_path) if auto_detected_data is not None: title = f"{port.description}, s/n: {port.serial_number or 'n/a'}" title += f" - {port.manufacturer}" if port.manufacturer else "" return self.async_create_entry( title=title, data=auto_detected_data, ) # did not detect anything self._device_path = dev_path return await self.async_step_pick_radio() schema = vol.Schema({vol.Required(CONF_DEVICE_PATH): vol.In(list_of_ports)}) return self.async_show_form(step_id="user", data_schema=schema) async def async_step_pick_radio(self, user_input=None): """Select radio type.""" if user_input is not None: self._radio_type = RadioType.get_by_description(user_input[CONF_RADIO_TYPE]) return await self.async_step_port_config() schema = {vol.Required(CONF_RADIO_TYPE): vol.In(sorted(RadioType.list()))} return self.async_show_form( step_id="pick_radio", data_schema=vol.Schema(schema), ) async def async_step_port_config(self, user_input=None): """Enter port settings specific for this type of radio.""" errors = {} app_cls = RadioType[self._radio_type].controller if user_input is not None: self._device_path = user_input.get(CONF_DEVICE_PATH) if await app_cls.probe(user_input): serial_by_id = await self.hass.async_add_executor_job( get_serial_by_id, user_input[CONF_DEVICE_PATH] ) user_input[CONF_DEVICE_PATH] = serial_by_id return self.async_create_entry( title=user_input[CONF_DEVICE_PATH], data={CONF_DEVICE: user_input, CONF_RADIO_TYPE: self._radio_type}, ) errors["base"] = "cannot_connect" schema = { vol.Required( CONF_DEVICE_PATH, default=self._device_path or vol.UNDEFINED ): str } radio_schema = app_cls.SCHEMA_DEVICE.schema if isinstance(radio_schema, vol.Schema): radio_schema = radio_schema.schema for param, value in radio_schema.items(): if param in SUPPORTED_PORT_SETTINGS: schema[param] = value return self.async_show_form( step_id="port_config", data_schema=vol.Schema(schema), errors=errors, ) async def detect_radios(dev_path: str) -> dict[str, Any] | None: """Probe all radio types on the device port.""" for radio in RadioType: dev_config = radio.controller.SCHEMA_DEVICE({CONF_DEVICE_PATH: dev_path}) if await radio.controller.probe(dev_config): return {CONF_RADIO_TYPE: radio.name, CONF_DEVICE: dev_config} return None def get_serial_by_id(dev_path: str) -> str: """Return a /dev/serial/by-id match for given device if available.""" by_id = "/dev/serial/by-id" if not os.path.isdir(by_id): return dev_path for path in (entry.path for entry in os.scandir(by_id) if entry.is_symlink()): if os.path.realpath(path) == dev_path: return path return dev_path
#!/usr/local/bin/python3 import sys import app from parser import create_parser, ACTIONS REQUIRED_FIELDS = ['path'] if __name__ == '__main__': app.setup_directories() parser = create_parser() args = parser.parse_args() if (args.new): if not all([getattr(args, field) for field in REQUIRED_FIELDS]): sys.exit(f'"--new" must specify all following params: {','.join(REQUIRED_FIELDS)}') app.create_app_home_and_scripts(args.name) app.create_app_proxy_executable(args.name, args.path) elif (args.delete): app.uninstall_app(args.name)
#!/usr/local/bin/python3 import sys import app from parser import create_parser, ACTIONS REQUIRED_FIELDS = ['path'] if __name__ == '__main__': app.setup_directories() parser = create_parser() args = parser.parse_args() if (args.new): if not all([getattr(args, field) for field in REQUIRED_FIELDS]): sys.exit(f'"--new" must specify all following params: {",".join(REQUIRED_FIELDS)}') app.create_app_home_and_scripts(args.name) app.create_app_proxy_executable(args.name, args.path) elif (args.delete): app.uninstall_app(args.name)
import math from copy import deepcopy from pathlib import Path import matplotlib.pyplot as plt import numpy as np import seaborn as sns from miyanmaayeh.runner import Runner PLOT_DIR = "verification/" Path(PLOT_DIR).mkdir(parents=True, exist_ok=True) NUM_RUNS = 5 ITERS = 500 def generate_plots(runners): sns.set_theme() plt.figure("Verification") width = NUM_RUNS height = int(math.floor(float(len(runners)) / float(width))) fig, ax = plt.subplots(height, width, figsize=(45, 25)) fig.suptitle("Market Prices", fontsize=54) for i, item in enumerate(runners): config, runner = item[0], item[1] plot_x = int(i // width) plot_y = int(i % width) prices = [item.price for item in runner.history] ticks = np.arange(0, len(prices)) z = np.polyfit(ticks, prices, 1) trendline_func = np.poly1d(z) trendline = [trendline_func(tick) for tick in ticks] ax[plot_x, plot_y].plot(ticks, prices, label="Market Price") ax[plot_x, plot_y].plot( ticks, trendline, label=f"Trendline - y = {trendline_func.coefficients[0]:0.4f}x + {trendline_func.coefficients[1]:0.4f}", color="green", ) ax[plot_x, plot_y].legend(loc="upper right", fontsize=14) ax[plot_x, plot_y].set_title( f"Cash={config["agents-config"]["initial-cash"]}, INV={config["agents-config"]["initial-inventory"]} - {i % NUM_RUNS + 1}", fontsize=24, ) ax[plot_x, plot_y].set_xlabel("Time", fontsize=16) ax[plot_x, plot_y].set_ylabel("Price", fontsize=16) plt.savefig(PLOT_DIR + "prices.png") plt.close("Verification") def main(): steps = math.ceil(ITERS / 1) config = { "snapshots_in": [i for i in range(0, ITERS, steps)] + [ITERS - 1], "total_agents": 300, "verifier_count": 100 / 100, "agents-config": { "production-average": 3000, "production-std": 200, "producers-percentage": 0, "income-alpha": 4, "income-beta": 0, "initial-inventory": 1000, "initial-cash": 20000, }, } runners = [] for i in range(NUM_RUNS): runner = Runner(config=config) runner.run(ITERS) runners.append((deepcopy(config), runner)) config["agents-config"]["initial-cash"] *= 2 for i in range(NUM_RUNS): runner = Runner(config=config.copy()) runner.run(ITERS) runners.append((deepcopy(config), runner)) config["agents-config"]["initial-cash"] /= 2 config["agents-config"]["initial-inventory"] *= 2 for i in range(NUM_RUNS): runner = Runner(config=config.copy()) runner.run(ITERS) runners.append((deepcopy(config), runner)) generate_plots(runners) if __name__ == "__main__": main()
import math from copy import deepcopy from pathlib import Path import matplotlib.pyplot as plt import numpy as np import seaborn as sns from miyanmaayeh.runner import Runner PLOT_DIR = "verification/" Path(PLOT_DIR).mkdir(parents=True, exist_ok=True) NUM_RUNS = 5 ITERS = 500 def generate_plots(runners): sns.set_theme() plt.figure("Verification") width = NUM_RUNS height = int(math.floor(float(len(runners)) / float(width))) fig, ax = plt.subplots(height, width, figsize=(45, 25)) fig.suptitle("Market Prices", fontsize=54) for i, item in enumerate(runners): config, runner = item[0], item[1] plot_x = int(i // width) plot_y = int(i % width) prices = [item.price for item in runner.history] ticks = np.arange(0, len(prices)) z = np.polyfit(ticks, prices, 1) trendline_func = np.poly1d(z) trendline = [trendline_func(tick) for tick in ticks] ax[plot_x, plot_y].plot(ticks, prices, label="Market Price") ax[plot_x, plot_y].plot( ticks, trendline, label=f"Trendline - y = {trendline_func.coefficients[0]:0.4f}x + {trendline_func.coefficients[1]:0.4f}", color="green", ) ax[plot_x, plot_y].legend(loc="upper right", fontsize=14) ax[plot_x, plot_y].set_title( f"Cash={config['agents-config']['initial-cash']}, INV={config['agents-config']['initial-inventory']} - {i % NUM_RUNS + 1}", fontsize=24, ) ax[plot_x, plot_y].set_xlabel("Time", fontsize=16) ax[plot_x, plot_y].set_ylabel("Price", fontsize=16) plt.savefig(PLOT_DIR + "prices.png") plt.close("Verification") def main(): steps = math.ceil(ITERS / 1) config = { "snapshots_in": [i for i in range(0, ITERS, steps)] + [ITERS - 1], "total_agents": 300, "verifier_count": 100 / 100, "agents-config": { "production-average": 3000, "production-std": 200, "producers-percentage": 0, "income-alpha": 4, "income-beta": 0, "initial-inventory": 1000, "initial-cash": 20000, }, } runners = [] for i in range(NUM_RUNS): runner = Runner(config=config) runner.run(ITERS) runners.append((deepcopy(config), runner)) config["agents-config"]["initial-cash"] *= 2 for i in range(NUM_RUNS): runner = Runner(config=config.copy()) runner.run(ITERS) runners.append((deepcopy(config), runner)) config["agents-config"]["initial-cash"] /= 2 config["agents-config"]["initial-inventory"] *= 2 for i in range(NUM_RUNS): runner = Runner(config=config.copy()) runner.run(ITERS) runners.append((deepcopy(config), runner)) generate_plots(runners) if __name__ == "__main__": main()
"""Datastructures for Adaptive immune receptor (IR) data. Currently only used as intermediate storage. See also discussion at https://github.com/theislab/anndata/issues/115 """ from ..util import _is_na2, _is_true2, _doc_params from typing import Collection, Dict, Iterable, List, Mapping, Optional, Iterator, Tuple from airr import RearrangementSchema import scanpy import json import numpy as np from ._util import doc_working_model from collections.abc import MutableMapping class AirrCell(MutableMapping): """Data structure for a Cell with immune receptors. Represents one row of `adata.obs`. This data structure is compliant with the AIRR rearrangement schema v1.0. An AirrCell can hold multiple chains (i.e. rows from the rearrangement TSV) which belong to the same cell. A chain is represented as a dictionary, where the keys are AIRR-rearrangement fields. The AirrCell can, additionally, hold cell-level attributes which can be set in a dict-like fashion. Keys marked as "cell-level" via `cell_attribute_fields` will be automatically transferred to the cell-level when added through a chain. They are required to have the same value for all chains. Parameters ---------- cell_id cell id or barcode. Needs to match the cell id used for transcriptomics data (i.e. the `adata.obs_names`) cell_attribute_fields List of field-names which are supposed to be stored at the cell-level rather than the chain level. If a chain with these fields is added to the cell, they are set on the cell-level instead. If the values already exist on the cell-level, a `ValueError` is raised, if they differ from the values that are already present. logger A logger to write messages to. If not specified, use scanpy's default logger. """ #: Identifiers of loci with a :term:`V-J<V(D)J>` junction VJ_LOCI = ("TRA", "TRG", "IGK", "IGL") #: Identifiers of loci with a :term:`V-D-J<V(D)J>` junction VDJ_LOCI = ("TRB", "TRD", "IGH") #: Valid chains are IMGT locus names #: see https://docs.airr-community.org/en/latest/datarep/rearrangements.html#locus-names VALID_LOCI = VJ_LOCI + VDJ_LOCI def __init__( self, cell_id: str, cell_attribute_fields: Collection[str] = (), *, logger=scanpy.logging, ): self._logger = logger self._chain_fields = None # A list of fields that are supposed to be stored at the cell level # rather than the chain level self._cell_attribute_fields = cell_attribute_fields # storage for these values, accessible through MutableMapping interface self._cell_attrs = dict() # A list of AIRR compliant dictionaries self._chains = list() self["cell_id"] = cell_id # legacy argument for the old AnnData scheme (when there was no `extra_chains` field) self["multi_chain"] = False def __repr__(self): return "AirrCell {} with {} chains".format(self.cell_id, len(self.chains)) @property def cell_id(self) -> str: """Unique identifier (barcode) of the cell.""" return self["cell_id"] @property def chains(self) -> List[dict]: """List of chain-dictionaries added to the cell.""" return self._chains @property def fields(self) -> List[str]: """Return a list of all fields (chain-level and cell-level)""" if self._chain_fields is None: return list(self) return list(self) + self._chain_fields def __delitem__(self, key) -> None: del self._cell_attrs[key] def __getitem__(self, key): return self._cell_attrs[key] def __iter__(self) -> Iterator: return iter(self._cell_attrs) def __len__(self) -> int: return len(self._cell_attrs) def __setitem__(self, k, v) -> None: if k == "multi_chain": v = _is_true2(v) try: existing_value = self._cell_attrs[k] if existing_value != v and not _is_na2(existing_value): raise ValueError( "Cell-level attributes differ between different chains. " f"Already present: `{existing_value}`. Tried to add `{v}`." ) except KeyError: self._cell_attrs[k] = v def add_chain(self, chain: Mapping) -> None: """Add a chain to the cell. A chain is a dictionary following the `AIRR Rearrangement Schema <https://docs.airr-community.org/en/latest/datarep/rearrangements.html#productive>`__. """ # ensure consistent ordering chain = dict(sorted(chain.items())) # sanitize NA values chain = {k: None if _is_na2(v) else v for k, v in chain.items()} # TODO this should be `.validate_obj` but currently does not work # because of https://github.com/airr-community/airr-standards/issues/508 RearrangementSchema.validate_header(chain.keys()) RearrangementSchema.validate_row(chain) for tmp_field in self._cell_attribute_fields: # It is ok if a field specified as cell attribute is not present in the chain try: self[tmp_field] = chain.pop(tmp_field) except KeyError: pass if self._chain_fields is None: self._chain_fields = list(chain.keys()) elif self._chain_fields != list(chain.keys()): raise ValueError("All chains must have the same fields!") if "locus" not in chain: self._logger.warning( "`locus` field not specified, but required for most scirpy functionality. " ) # type: ignore elif chain["locus"] not in self.VALID_LOCI: # TODO seems this isn't actually ignored. Chain will just be moved to `extra chains`. self._logger.warning(f"Non-standard locus name ignored: {chain["locus"]} ") # type: ignore self.chains.append(chain) def add_serialized_chains(self, serialized_chains: str) -> None: """Add chains serialized as JSON. The JSON object needs to be a list of dicts. If `serialized_chains` is a value interpreted as NA, the function passes silently and does nothing.""" if not _is_na2(serialized_chains): tmp_chains = json.loads(serialized_chains) for chain in tmp_chains: tmp_chain = AirrCell.empty_chain_dict() tmp_chain.update(chain) self.add_chain(tmp_chain) def _split_chains(self) -> Tuple[bool, dict]: """ Splits the chains into productive VJ, productive VDJ, and extra chains. Returns ------- is_multichain Boolean that indicates if the current cell is a multichain split_chains dictionary with the following entries: * `vj_chains`: The (up to) two most highly expressed, productive VJ-chains * `vdj_chains`: The (up to) two most highly expressed, productive VDJ chains * `extra_chains`: All remaining chains """ is_multichain = self["multi_chain"] split_chains = {"VJ": list(), "VDJ": list(), "extra": list()} for tmp_chain in self.chains: if "locus" not in tmp_chain: split_chains["extra"].append(tmp_chain) elif ( tmp_chain["locus"] in self.VJ_LOCI and tmp_chain["productive"] and not _is_na2(tmp_chain["junction_aa"]) ): split_chains["VJ"].append(tmp_chain) elif ( tmp_chain["locus"] in self.VDJ_LOCI and tmp_chain["productive"] and not _is_na2(tmp_chain["junction_aa"]) ): split_chains["VDJ"].append(tmp_chain) else: split_chains["extra"].append(tmp_chain) if ( "duplicate_count" not in self.fields and "consensus_count" not in self.fields and len(self.chains) # don't warn for empty cells ): self._logger.warning( "No expression information available. Cannot rank chains by expression. " ) # type: ignore for junction_type in ["VJ", "VDJ"]: split_chains[junction_type] = sorted( split_chains[junction_type], key=self._key_sort_chains, reverse=True ) # only keep the (up to) two most highly expressed chains tmp_extra_chains = split_chains[junction_type][2:] # if productive chains are appended to extra chains, it's a multichain cell! is_multichain = is_multichain or len(tmp_extra_chains) split_chains["extra"].extend(tmp_extra_chains) split_chains[junction_type] = split_chains[junction_type][:2] return bool(is_multichain), split_chains @staticmethod def _key_sort_chains(chain) -> Tuple: """Get key to sort chains by expression""" sort_tuple = ( chain.get("duplicate_count", 0), chain.get("consensus_count", 0), chain.get("junction", ""), chain.get("junction_aa", ""), ) # replace None by -1 to make sure it comes in last return tuple(-1 if x is None else x for x in sort_tuple) @staticmethod def _serialize_chains( chains: List[MutableMapping], include_fields: Optional[Collection[str]] = None ) -> str: """Serialize chains into a JSON object. This is useful for storing an arbitrary number of extra chains in a single column of a dataframe.""" # convert numpy dtypes to python types # https://stackoverflow.com/questions/9452775/converting-numpy-dtypes-to-native-python-types for chain in chains: for k, v in chain.items(): try: chain[k] = chain[k].item() except AttributeError: pass # Filter chains for `include_fields` chains_filtered = [ {k: v for k, v in chain.items() if k in include_fields} for chain in chains ] return json.dumps(chains_filtered) def to_airr_records(self) -> Iterable[dict]: """Iterate over chains as AIRR-Rearrangent compliant dictonaries. Each dictionary will also include the cell-level information. Yields ------ Dictionary representing one row of a AIRR rearrangement table """ for tmp_chain in self.chains: chain = AirrCell.empty_chain_dict() # add the actual data chain.update(tmp_chain) # add cell-level attributes chain.update(self) yield chain @_doc_params(doc_working_model=doc_working_model) def to_scirpy_record( self, include_fields: Optional[Collection[str]] = None ) -> dict: """\ Convert the cell to a scirpy record (i.e. one row of `adata.obs`) according to our working model of adaptive immune receptors. {doc_working_model} Parameters ---------- include_fields AIRR fields to include into `adata.obs` (to save space and to not clutter `obs`). Set to `None` to include all fields. Returns ------- Dictionary representing one row of scirpy's `adata.obs`. """ res_dict = dict() if include_fields is None: include_fields = self.fields # ensure cell_id is always added include_fields = set(include_fields) include_fields.add("cell_id") res_dict["multi_chain"], chain_dict = self._split_chains() res_dict["extra_chains"] = self._serialize_chains( chain_dict.pop("extra"), include_fields=include_fields ) # add cell-level attributes for key in self: if key in include_fields: res_dict[key] = self[key] # add chain-level attributes, do nothing when cell with no chains if self._chain_fields is not None: for key in self._chain_fields: if key in include_fields: for junction_type, tmp_chains in chain_dict.items(): for i in range(2): try: tmp_chain = tmp_chains[i] except IndexError: tmp_chain = dict() res_dict[ "IR_{}_{}_{}".format(junction_type, i + 1, key) ] = tmp_chain.get(key, None) # use this check instead of `is None`, as the fields are missing in an empty cell. def _is_nan_or_missing(col): return col not in res_dict or res_dict[col] is None # in some weird reasons, it can happen that a cell has been called from # TCR-seq but no TCR seqs have been found. `has_ir` should be equal # to "at least one productive chain" res_dict["has_ir"] = not ( _is_nan_or_missing("IR_VJ_1_junction_aa") and _is_nan_or_missing("IR_VDJ_1_junction_aa") ) # if there are no chains at all, we want multi-chain to be nan # This is to be consistent with what happens when turning an anndata object into # airr_cells and converting it back to anndata. if not len(self.chains): res_dict["multi_chain"] = np.nan if _is_nan_or_missing("IR_VJ_1_junction_aa"): assert _is_nan_or_missing( "IR_VJ_2_junction_aa" ), f"There can't be a secondary chain if there is no primary one: {res_dict}" if _is_nan_or_missing("IR_VDJ_1_junction_aa"): assert _is_nan_or_missing( "IR_VDJ_2_junction_aa" ), f"There can't be a secondary chain if there is no primary one: {res_dict}" return res_dict @staticmethod def empty_chain_dict() -> dict: """Generate an empty chain dictionary, containing all required AIRR columns, but set to `None`""" return {field: None for field in RearrangementSchema.required}
"""Datastructures for Adaptive immune receptor (IR) data. Currently only used as intermediate storage. See also discussion at https://github.com/theislab/anndata/issues/115 """ from ..util import _is_na2, _is_true2, _doc_params from typing import Collection, Dict, Iterable, List, Mapping, Optional, Iterator, Tuple from airr import RearrangementSchema import scanpy import json import numpy as np from ._util import doc_working_model from collections.abc import MutableMapping class AirrCell(MutableMapping): """Data structure for a Cell with immune receptors. Represents one row of `adata.obs`. This data structure is compliant with the AIRR rearrangement schema v1.0. An AirrCell can hold multiple chains (i.e. rows from the rearrangement TSV) which belong to the same cell. A chain is represented as a dictionary, where the keys are AIRR-rearrangement fields. The AirrCell can, additionally, hold cell-level attributes which can be set in a dict-like fashion. Keys marked as "cell-level" via `cell_attribute_fields` will be automatically transferred to the cell-level when added through a chain. They are required to have the same value for all chains. Parameters ---------- cell_id cell id or barcode. Needs to match the cell id used for transcriptomics data (i.e. the `adata.obs_names`) cell_attribute_fields List of field-names which are supposed to be stored at the cell-level rather than the chain level. If a chain with these fields is added to the cell, they are set on the cell-level instead. If the values already exist on the cell-level, a `ValueError` is raised, if they differ from the values that are already present. logger A logger to write messages to. If not specified, use scanpy's default logger. """ #: Identifiers of loci with a :term:`V-J<V(D)J>` junction VJ_LOCI = ("TRA", "TRG", "IGK", "IGL") #: Identifiers of loci with a :term:`V-D-J<V(D)J>` junction VDJ_LOCI = ("TRB", "TRD", "IGH") #: Valid chains are IMGT locus names #: see https://docs.airr-community.org/en/latest/datarep/rearrangements.html#locus-names VALID_LOCI = VJ_LOCI + VDJ_LOCI def __init__( self, cell_id: str, cell_attribute_fields: Collection[str] = (), *, logger=scanpy.logging, ): self._logger = logger self._chain_fields = None # A list of fields that are supposed to be stored at the cell level # rather than the chain level self._cell_attribute_fields = cell_attribute_fields # storage for these values, accessible through MutableMapping interface self._cell_attrs = dict() # A list of AIRR compliant dictionaries self._chains = list() self["cell_id"] = cell_id # legacy argument for the old AnnData scheme (when there was no `extra_chains` field) self["multi_chain"] = False def __repr__(self): return "AirrCell {} with {} chains".format(self.cell_id, len(self.chains)) @property def cell_id(self) -> str: """Unique identifier (barcode) of the cell.""" return self["cell_id"] @property def chains(self) -> List[dict]: """List of chain-dictionaries added to the cell.""" return self._chains @property def fields(self) -> List[str]: """Return a list of all fields (chain-level and cell-level)""" if self._chain_fields is None: return list(self) return list(self) + self._chain_fields def __delitem__(self, key) -> None: del self._cell_attrs[key] def __getitem__(self, key): return self._cell_attrs[key] def __iter__(self) -> Iterator: return iter(self._cell_attrs) def __len__(self) -> int: return len(self._cell_attrs) def __setitem__(self, k, v) -> None: if k == "multi_chain": v = _is_true2(v) try: existing_value = self._cell_attrs[k] if existing_value != v and not _is_na2(existing_value): raise ValueError( "Cell-level attributes differ between different chains. " f"Already present: `{existing_value}`. Tried to add `{v}`." ) except KeyError: self._cell_attrs[k] = v def add_chain(self, chain: Mapping) -> None: """Add a chain to the cell. A chain is a dictionary following the `AIRR Rearrangement Schema <https://docs.airr-community.org/en/latest/datarep/rearrangements.html#productive>`__. """ # ensure consistent ordering chain = dict(sorted(chain.items())) # sanitize NA values chain = {k: None if _is_na2(v) else v for k, v in chain.items()} # TODO this should be `.validate_obj` but currently does not work # because of https://github.com/airr-community/airr-standards/issues/508 RearrangementSchema.validate_header(chain.keys()) RearrangementSchema.validate_row(chain) for tmp_field in self._cell_attribute_fields: # It is ok if a field specified as cell attribute is not present in the chain try: self[tmp_field] = chain.pop(tmp_field) except KeyError: pass if self._chain_fields is None: self._chain_fields = list(chain.keys()) elif self._chain_fields != list(chain.keys()): raise ValueError("All chains must have the same fields!") if "locus" not in chain: self._logger.warning( "`locus` field not specified, but required for most scirpy functionality. " ) # type: ignore elif chain["locus"] not in self.VALID_LOCI: # TODO seems this isn't actually ignored. Chain will just be moved to `extra chains`. self._logger.warning(f"Non-standard locus name ignored: {chain['locus']} ") # type: ignore self.chains.append(chain) def add_serialized_chains(self, serialized_chains: str) -> None: """Add chains serialized as JSON. The JSON object needs to be a list of dicts. If `serialized_chains` is a value interpreted as NA, the function passes silently and does nothing.""" if not _is_na2(serialized_chains): tmp_chains = json.loads(serialized_chains) for chain in tmp_chains: tmp_chain = AirrCell.empty_chain_dict() tmp_chain.update(chain) self.add_chain(tmp_chain) def _split_chains(self) -> Tuple[bool, dict]: """ Splits the chains into productive VJ, productive VDJ, and extra chains. Returns ------- is_multichain Boolean that indicates if the current cell is a multichain split_chains dictionary with the following entries: * `vj_chains`: The (up to) two most highly expressed, productive VJ-chains * `vdj_chains`: The (up to) two most highly expressed, productive VDJ chains * `extra_chains`: All remaining chains """ is_multichain = self["multi_chain"] split_chains = {"VJ": list(), "VDJ": list(), "extra": list()} for tmp_chain in self.chains: if "locus" not in tmp_chain: split_chains["extra"].append(tmp_chain) elif ( tmp_chain["locus"] in self.VJ_LOCI and tmp_chain["productive"] and not _is_na2(tmp_chain["junction_aa"]) ): split_chains["VJ"].append(tmp_chain) elif ( tmp_chain["locus"] in self.VDJ_LOCI and tmp_chain["productive"] and not _is_na2(tmp_chain["junction_aa"]) ): split_chains["VDJ"].append(tmp_chain) else: split_chains["extra"].append(tmp_chain) if ( "duplicate_count" not in self.fields and "consensus_count" not in self.fields and len(self.chains) # don't warn for empty cells ): self._logger.warning( "No expression information available. Cannot rank chains by expression. " ) # type: ignore for junction_type in ["VJ", "VDJ"]: split_chains[junction_type] = sorted( split_chains[junction_type], key=self._key_sort_chains, reverse=True ) # only keep the (up to) two most highly expressed chains tmp_extra_chains = split_chains[junction_type][2:] # if productive chains are appended to extra chains, it's a multichain cell! is_multichain = is_multichain or len(tmp_extra_chains) split_chains["extra"].extend(tmp_extra_chains) split_chains[junction_type] = split_chains[junction_type][:2] return bool(is_multichain), split_chains @staticmethod def _key_sort_chains(chain) -> Tuple: """Get key to sort chains by expression""" sort_tuple = ( chain.get("duplicate_count", 0), chain.get("consensus_count", 0), chain.get("junction", ""), chain.get("junction_aa", ""), ) # replace None by -1 to make sure it comes in last return tuple(-1 if x is None else x for x in sort_tuple) @staticmethod def _serialize_chains( chains: List[MutableMapping], include_fields: Optional[Collection[str]] = None ) -> str: """Serialize chains into a JSON object. This is useful for storing an arbitrary number of extra chains in a single column of a dataframe.""" # convert numpy dtypes to python types # https://stackoverflow.com/questions/9452775/converting-numpy-dtypes-to-native-python-types for chain in chains: for k, v in chain.items(): try: chain[k] = chain[k].item() except AttributeError: pass # Filter chains for `include_fields` chains_filtered = [ {k: v for k, v in chain.items() if k in include_fields} for chain in chains ] return json.dumps(chains_filtered) def to_airr_records(self) -> Iterable[dict]: """Iterate over chains as AIRR-Rearrangent compliant dictonaries. Each dictionary will also include the cell-level information. Yields ------ Dictionary representing one row of a AIRR rearrangement table """ for tmp_chain in self.chains: chain = AirrCell.empty_chain_dict() # add the actual data chain.update(tmp_chain) # add cell-level attributes chain.update(self) yield chain @_doc_params(doc_working_model=doc_working_model) def to_scirpy_record( self, include_fields: Optional[Collection[str]] = None ) -> dict: """\ Convert the cell to a scirpy record (i.e. one row of `adata.obs`) according to our working model of adaptive immune receptors. {doc_working_model} Parameters ---------- include_fields AIRR fields to include into `adata.obs` (to save space and to not clutter `obs`). Set to `None` to include all fields. Returns ------- Dictionary representing one row of scirpy's `adata.obs`. """ res_dict = dict() if include_fields is None: include_fields = self.fields # ensure cell_id is always added include_fields = set(include_fields) include_fields.add("cell_id") res_dict["multi_chain"], chain_dict = self._split_chains() res_dict["extra_chains"] = self._serialize_chains( chain_dict.pop("extra"), include_fields=include_fields ) # add cell-level attributes for key in self: if key in include_fields: res_dict[key] = self[key] # add chain-level attributes, do nothing when cell with no chains if self._chain_fields is not None: for key in self._chain_fields: if key in include_fields: for junction_type, tmp_chains in chain_dict.items(): for i in range(2): try: tmp_chain = tmp_chains[i] except IndexError: tmp_chain = dict() res_dict[ "IR_{}_{}_{}".format(junction_type, i + 1, key) ] = tmp_chain.get(key, None) # use this check instead of `is None`, as the fields are missing in an empty cell. def _is_nan_or_missing(col): return col not in res_dict or res_dict[col] is None # in some weird reasons, it can happen that a cell has been called from # TCR-seq but no TCR seqs have been found. `has_ir` should be equal # to "at least one productive chain" res_dict["has_ir"] = not ( _is_nan_or_missing("IR_VJ_1_junction_aa") and _is_nan_or_missing("IR_VDJ_1_junction_aa") ) # if there are no chains at all, we want multi-chain to be nan # This is to be consistent with what happens when turning an anndata object into # airr_cells and converting it back to anndata. if not len(self.chains): res_dict["multi_chain"] = np.nan if _is_nan_or_missing("IR_VJ_1_junction_aa"): assert _is_nan_or_missing( "IR_VJ_2_junction_aa" ), f"There can't be a secondary chain if there is no primary one: {res_dict}" if _is_nan_or_missing("IR_VDJ_1_junction_aa"): assert _is_nan_or_missing( "IR_VDJ_2_junction_aa" ), f"There can't be a secondary chain if there is no primary one: {res_dict}" return res_dict @staticmethod def empty_chain_dict() -> dict: """Generate an empty chain dictionary, containing all required AIRR columns, but set to `None`""" return {field: None for field in RearrangementSchema.required}
import os from spirl.models.closed_loop_spirl_mdl import ClSPiRLMdl from spirl.models.skill_prior_mdl import SkillSpaceLogger from spirl.utils.general_utils import AttrDict from spirl.configs.default_data_configs.maze import data_spec from spirl.components.evaluator import TopOfNSequenceEvaluator from spirl.data.maze.src.maze_data_loader import MazeStateSequenceDataset from spirl.components.fsil import FewshotDataset NUM_IL_DEMO = 10 subseq_len = 10 fewshot_dataset = FewshotDataset( 'data/maze/right/demos.pkl', num_demo=NUM_IL_DEMO, subseq_len=subseq_len, ) current_dir = os.path.dirname(os.path.realpath(__file__)) configuration = { 'model': ClSPiRLMdl, 'logger': SkillSpaceLogger, 'data_dir': '.', 'epoch_cycles_train': 1, 'evaluator': TopOfNSequenceEvaluator, 'top_of_n_eval': 100, 'top_comp_metric': 'mse', 'batch_size': 128, 'num_epochs': 100, 'lr': 1e-4, 'fewshot_data': fewshot_dataset, 'fewshot_batch_size': 128, 'finetune_vae': False, 'rst_data_path': 'data/maze/right/rsts.npy', } configuration = AttrDict(configuration) model_config = AttrDict( state_dim=data_spec.state_dim, action_dim=data_spec.n_actions, n_rollout_steps=subseq_len, kl_div_weight=1e-2, nz_enc=32, nz_mid=32, n_processing_layers=3, cond_decode=True, # checkpt_path=f'{os.environ['EXP_DIR']}/skill_prior_learning/maze_right/hierarchical_cl_state_4M_B1024' ) # Dataset data_config = AttrDict() data_config.dataset_spec = data_spec data_config['dataset_spec']['dataset_class'] = MazeStateSequenceDataset data_config['dataset_spec']['env_name'] = 'maze2d-large-v1' data_config['dataset_spec']['dataset_path'] = './data/maze/right/blocked-4M.hdf5' data_config.dataset_spec.subseq_len = model_config.n_rollout_steps + 1
import os from spirl.models.closed_loop_spirl_mdl import ClSPiRLMdl from spirl.models.skill_prior_mdl import SkillSpaceLogger from spirl.utils.general_utils import AttrDict from spirl.configs.default_data_configs.maze import data_spec from spirl.components.evaluator import TopOfNSequenceEvaluator from spirl.data.maze.src.maze_data_loader import MazeStateSequenceDataset from spirl.components.fsil import FewshotDataset NUM_IL_DEMO = 10 subseq_len = 10 fewshot_dataset = FewshotDataset( 'data/maze/right/demos.pkl', num_demo=NUM_IL_DEMO, subseq_len=subseq_len, ) current_dir = os.path.dirname(os.path.realpath(__file__)) configuration = { 'model': ClSPiRLMdl, 'logger': SkillSpaceLogger, 'data_dir': '.', 'epoch_cycles_train': 1, 'evaluator': TopOfNSequenceEvaluator, 'top_of_n_eval': 100, 'top_comp_metric': 'mse', 'batch_size': 128, 'num_epochs': 100, 'lr': 1e-4, 'fewshot_data': fewshot_dataset, 'fewshot_batch_size': 128, 'finetune_vae': False, 'rst_data_path': 'data/maze/right/rsts.npy', } configuration = AttrDict(configuration) model_config = AttrDict( state_dim=data_spec.state_dim, action_dim=data_spec.n_actions, n_rollout_steps=subseq_len, kl_div_weight=1e-2, nz_enc=32, nz_mid=32, n_processing_layers=3, cond_decode=True, # checkpt_path=f'{os.environ["EXP_DIR"]}/skill_prior_learning/maze_right/hierarchical_cl_state_4M_B1024' ) # Dataset data_config = AttrDict() data_config.dataset_spec = data_spec data_config['dataset_spec']['dataset_class'] = MazeStateSequenceDataset data_config['dataset_spec']['env_name'] = 'maze2d-large-v1' data_config['dataset_spec']['dataset_path'] = './data/maze/right/blocked-4M.hdf5' data_config.dataset_spec.subseq_len = model_config.n_rollout_steps + 1
#!/usr/bin/env python3 import json import math import numpy as np import re import sys from terminaltables import AsciiTable from termcolor import colored from scipy.stats import ttest_ind p_value_significance_threshold = 0.001 min_iterations = 10 min_runtime_ns = 59 * 1000 * 1000 * 1000 min_iterations_disabling_min_runtime = 100 max_lost = 0 max_gain = 0 min_lost = -float('inf') min_gain = float('inf') num_lost = 0 num_gain = 0 num_overall = 0 # threshold for latency gain/loss to be considered (>=) confidence_threshold = 5 def format_diff(diff): diff -= 1 # adapt to show change in percent if diff < 0.0: return f"{diff:.0%}" else: return f"+{diff:.0%}" def color_diff(diff, inverse_colors=False): def select_color(value, color): return color if round(abs(value - 1), 2) >= 0.05 else "white" diff_str = format_diff(diff) color = "green" if (diff_str[0] == "+") != (inverse_colors) else "red" return colored(format_diff(diff), select_color(diff, color)) def geometric_mean(values): product = 1 for value in values: product *= value return product ** (1 / float(len(values))) def calculate_and_format_p_value(old_durations, new_durations): p_value = ttest_ind(old_durations, new_durations)[1] is_significant = p_value < p_value_significance_threshold old_runtime = sum(runtime for runtime in old_durations) new_runtime = sum(runtime for runtime in new_durations) # The results for a query are considered to be statistically not significant if the runtime is too short. However, # if the item has been executed > `min_iterations_disabling_min_runtime` times, it is considered significant. if (old_runtime < min_runtime_ns or new_runtime < min_runtime_ns) and ( len(old_durations) < min_iterations_disabling_min_runtime or len(new_durations) < min_iterations_disabling_min_runtime ): is_significant = False return "(run time too short)" elif len(old_durations) < min_iterations or len(new_durations) < min_iterations: is_significant = False # In case we cannot decide whether the change is significant due to an insufficient number of measurements, the # add_note_for_insufficient_pvalue_runs flag it set, for which a note is later added to the table output. global add_note_for_insufficient_pvalue_runs add_note_for_insufficient_pvalue_runs = True return colored("˅", "yellow", attrs=["bold"]) else: if is_significant: return colored(f"{p_value:.4f}", "white") else: return colored(f"{p_value:.4f}", "yellow", attrs=["bold"]) def create_context_overview(old_config, new_config, github_format): ignore_difference_for = ["GIT-HASH", "date"] old_context_keys = set(old_config["context"].keys()) new_context_keys = set(new_config["context"].keys()) common_context_keys = old_context_keys & new_context_keys table_lines = [["Parameter", sys.argv[1], sys.argv[2]]] for key in sorted(common_context_keys): old_value = old_config["context"][key] new_value = new_config["context"][key] color = "white" marker = " " if old_value != new_value and key not in ignore_difference_for: color = "red" marker = "≠" if key == "build_type" and (old_value == "debug" or new_value == "debug"): # Always warn when non-release builds are benchmarked color = "red" marker = "!" table_lines.append([colored(marker + key, color), old_value, new_value]) # Print keys that are not present in both contexts for key in sorted(old_context_keys - common_context_keys): value = old_config["context"][key] table_lines.append([colored("≠" + key, "red"), value, "undefined"]) for key in sorted(new_context_keys - common_context_keys): value = new_config["context"][key] table_lines.append([colored("≠" + key, "red"), "undefined", value]) table = AsciiTable(table_lines) table.title = "Configuration Overview" table_output = str(table.table) if github_format: # For GitHub, the output is a fake diff, where a leading '-' marks a deletion and causes the line to be printed # in red. We do that for all differing configuration lines. Other lines are prepended with ' '. new_output = "" for line in table_output.splitlines(): marker = "-" if ("≠" in line or "!" in line) else " " new_output += f"{marker}{line}\n" return new_output return table_output # Doubles the separators (can be '|' for normal rows and '+' for horizontal separators within the table) given by the # list vertical_separators_to_duplicate. [0, 3] means that the first and fourth separator are doubled. Table contents # must not contain '|' for this to work. def double_vertical_separators(lines, vertical_separators_to_duplicate): for line_id, line in enumerate(lines): vertical_separator = line[0] # positions might change due to color coding pos_separators = [m.start() for m in re.finditer(re.escape(vertical_separator), line)] # 0 required for splicing pos_splits = [0] + [pos_separators[index] for index in vertical_separators_to_duplicate] new_line = [line[i:j] for i, j in zip(pos_splits, pos_splits[1:] + [None])] lines[line_id] = vertical_separator.join(new_line) return lines if not len(sys.argv) in [3, 4]: exit("Usage: " + sys.argv[0] + " benchmark1.json benchmark2.json [--github]") # Format the output as a diff (prepending - and +) so that Github shows colors github_format = bool(len(sys.argv) == 4 and sys.argv[3] == "--github") with open(sys.argv[1]) as old_file: old_data = json.load(old_file) with open(sys.argv[2]) as new_file: new_data = json.load(new_file) if old_data["context"]["benchmark_mode"] != new_data["context"]["benchmark_mode"]: exit("Benchmark runs with different modes (ordered/shuffled) are not comparable") diffs_throughput = [] total_runtime_old = 0 total_runtime_new = 0 add_note_for_capped_runs = False # Flag set when max query runs was set for benchmark run add_note_for_insufficient_pvalue_runs = False # Flag set when runs was insufficient for p-value calculation # Create table header: # $latency and $thrghpt (abbreviated to keep the column at a max width of 8 chars) will later be replaced with a title # spanning two columns table_data = [] table_data.append(["Item", "$latency", "", "Change", "$thrghpt", "", "Change", "p-value"]) table_data.append(["", "old", "new", "", "old", "new", "", ""]) for old, new in zip(old_data["benchmarks"], new_data["benchmarks"]): name = old["name"] if name == "95": continue if old["name"] != new["name"]: name += " -> " + new["name"] num_overall += 1 # Create numpy arrays for old/new successful/unsuccessful runs from benchmark dictionary old_successful_durations = np.array([run["duration"] for run in old["successful_runs"]], dtype=np.float64) new_successful_durations = np.array([run["duration"] for run in new["successful_runs"]], dtype=np.float64) old_unsuccessful_durations = np.array([run["duration"] for run in old["unsuccessful_runs"]], dtype=np.float64) new_unsuccessful_durations = np.array([run["duration"] for run in new["unsuccessful_runs"]], dtype=np.float64) old_avg_successful_duration = np.mean(old_successful_durations) # defaults to np.float64 for int input new_avg_successful_duration = np.mean(new_successful_durations) total_runtime_old += old_avg_successful_duration if not math.isnan(old_avg_successful_duration) else 0.0 total_runtime_new += new_avg_successful_duration if not math.isnan(new_avg_successful_duration) else 0.0 # Check for duration==0 to avoid div/0 if float(old_avg_successful_duration) > 0.0: diff_duration = float(new_avg_successful_duration / old_avg_successful_duration) change = int(format_diff(diff_duration).replace("%", "")) max_lost = min(change, max_lost) max_gain = max(change, max_gain) if abs(change) >= confidence_threshold: if change < 0: num_lost += 1 min_lost = max(change, min_lost) elif change > 0: num_gain += 1 min_gain = min(change, min_gain) else: diff_duration = float("nan") if float(old["items_per_second"]) > 0.0: diff_throughput = float(new["items_per_second"]) / float(old["items_per_second"]) diffs_throughput.append(diff_throughput) else: diff_throughput = float("nan") # Format the diffs (add colors and percentage output) and calculate p-value diff_duration_formatted = color_diff(diff_duration, True) diff_throughput_formatted = color_diff(diff_throughput) p_value_formatted = calculate_and_format_p_value(old_successful_durations, new_successful_durations) old_iteration_count = len(old_successful_durations) + len(old_unsuccessful_durations) new_iteration_count = len(new_successful_durations) + len(new_unsuccessful_durations) # Check if number of runs reached max_runs if (old_data["context"]["max_runs"] > 0 or new_data["context"]["max_runs"] > 0) and ( old_iteration_count == old_data["context"]["max_runs"] or new_iteration_count == new_data["context"]["max_runs"] ): note = colored("˄", "yellow", attrs=["bold"]) add_note_for_capped_runs = True else: note = " " # Add table row for succesful executions. We use column widths of 7 (latency) and 8 (throughput) for printing to # ensure that we have enough space to replace the latency/throughput marker with a column header spanning multiple # columns. table_data.append( [ name, f"{(old_avg_successful_duration / 1e6):>7.1f}" if old_avg_successful_duration else "nan", f"{(new_avg_successful_duration / 1e6):>7.1f}" if new_avg_successful_duration else "nan", diff_duration_formatted + note if not math.isnan(diff_duration) else "", f'{old['items_per_second']:>8.2f}', f'{new['items_per_second']:>8.2f}', diff_throughput_formatted + note, p_value_formatted, ] ) if len(old["unsuccessful_runs"]) > 0 or len(new["unsuccessful_runs"]) > 0: if old_data["context"]["benchmark_mode"] == "Ordered": old_unsuccessful_per_second = float(len(old_unsuccessful_durations)) / (float(old["duration"]) / 1e9) new_unsuccessful_per_second = float(len(new_unsuccessful_durations)) / (float(new["duration"]) / 1e9) else: old_unsuccessful_per_second = float(len(old_unsuccessful_durations)) / ( float(old_data["summary"]["total_duration"]) / 1e9 ) new_unsuccessful_per_second = float(len(new_unsuccessful_durations)) / ( float(new_data["summary"]["total_duration"]) / 1e9 ) old_avg_unsuccessful_duration = np.mean(old_unsuccessful_durations) new_avg_unsuccessful_duration = np.mean(new_unsuccessful_durations) if len(old_unsuccessful_durations) > 0 and len(new_unsuccessful_durations) > 0: diff_throughput_unsuccessful = float(new_unsuccessful_per_second / old_unsuccessful_per_second) diff_duration_unsuccessful = new_avg_unsuccessful_duration / old_avg_unsuccessful_duration else: diff_throughput_unsuccessful = float("nan") diff_duration_unsuccessful = float("nan") unsuccessful_info = [ " unsucc.:", f"{(old_avg_unsuccessful_duration / 1e6):>7.1f}" if not math.isnan(old_avg_unsuccessful_duration) else "nan", f"{(new_avg_unsuccessful_duration / 1e6):>7.1f}" if not math.isnan(new_avg_unsuccessful_duration) else "nan", format_diff(diff_duration_unsuccessful) + " " if not math.isnan(diff_duration_unsuccessful) else " ", f"{old_unsuccessful_per_second:>.2f}", f"{new_unsuccessful_per_second:>.2f}", format_diff(diff_throughput_unsuccessful) + " " if not math.isnan(diff_throughput_unsuccessful) else " ", ] unsuccessful_info_colored = [colored(text, attrs=["dark"]) for text in unsuccessful_info] table_data.append(unsuccessful_info_colored) # Add a summary of all benchmark items to the final table, including (1) the change of the accumulated sum of all # queries' average runtimes and (2) the geometric mean of the percentage changes. table_data.append( [ "Sum", f"{(total_runtime_old / 1e6):>7.1f}", f"{(total_runtime_new / 1e6):>7.1f}", color_diff(total_runtime_new / total_runtime_old, True) + " ", ] ) table_data.append(["Geomean", "", "", "", "", "", color_diff(geometric_mean(diffs_throughput)) + " "]) table = AsciiTable(table_data) for column_index in range(1, len(table_data[0])): # all columns justified to right, except for item name table.justify_columns[column_index] = "right" table_string = str(table.table) table_string_reformatted = "" lines = table_string.splitlines() # Double the vertical line between the item names and the two major measurements. lines = double_vertical_separators(lines, [1, 4]) # As the used terminaltables module does not support cells that span multiple columns, we do that manually for latency # and throughput in the header. We used two place holders that are narrow enough to not grow the column any wider than # necessary for the actual values. After manually changing the column title to span two column, we replace the place # holder with the actual full descriptions. for (placeholder, final) in [ ("$thrghpt", "Throughput (iter/s)"), ("$latency", "Latency (ms/iter)"), ]: header_strings = lines[1].split("|") for column_id, text in enumerate(header_strings): if placeholder in text: title_column = header_strings[column_id] unit_column = header_strings[column_id + 1] previous_length = len(title_column) + len(unit_column) + 1 new_title = f" {final} ".ljust(previous_length, " ") lines[1] = "|".join(header_strings[:column_id] + [new_title] + header_strings[column_id + 2 :]) # Swap second line of header with automatically added separator. Terminaltables does not support multi-line headers. So # we have the second header line as part of the results after a separator line. We need to swap these. lines[2], lines[3] = lines[3], lines[2] for (line_number, line) in enumerate(lines): if line_number == len(table_data): # Add another separation between benchmark items and aggregates table_string_reformatted += lines[-1] + "\n" table_string_reformatted += line + "\n" # In case the runs for the executed benchmark have been cut or the number of runs was insufficient for the p-value # calcution, we add notes to the end of the table. if add_note_for_capped_runs or add_note_for_insufficient_pvalue_runs: first_column_width = len(lines[1].split("|")[1]) width_for_note = len(lines[0]) - first_column_width - 5 # 5 for seperators and spaces if add_note_for_capped_runs: note = "˄ Execution stopped due to max runs reached" table_string_reformatted += "|" + (" Notes ".rjust(first_column_width, " ")) table_string_reformatted += "|| " + note.ljust(width_for_note, " ") + "|\n" if add_note_for_insufficient_pvalue_runs: note = "˅" + " Insufficient number of runs for p-value calculation" table_string_reformatted += "|" + (" " * first_column_width) + "|| " + note.ljust(width_for_note, " ") + "|\n" table_string_reformatted += lines[-1] + "\n" table_string = table_string_reformatted # If github_format is set, format the output in the style of a diff file where added lines (starting with +) are # colored green, removed lines (starting with -) are red, and others (starting with an empty space) are black. # Because terminaltables (unsurprisingly) does not support this hack, we need to post-process the result string, # searching for the control codes that define text to be formatted as green or red. if github_format: green_control_sequence = colored("", "green")[0:5] red_control_sequence = colored("", "red")[0:5] table_string_reformatted = ( "<details>\n" + "<summary>Configuration Overview - click to expand</summary>\n\n" + "```diff\n" + create_context_overview(old_data, new_data, github_format) + "```\n" + "</details>\n\n" + "```diff\n" ) for line in table_string.splitlines(): if green_control_sequence in line: table_string_reformatted += "+" elif red_control_sequence in line: table_string_reformatted += "-" else: table_string_reformatted += " " table_string_reformatted += line + "\n" table_string_reformatted += "```" table_string = table_string_reformatted else: table_string = create_context_overview(old_data, new_data, github_format) + "\n\n" + table_string print(table_string) print() print("loss --> latency now lower, gain --> latency now higher") print(f"baseline: {round(total_runtime_old / 10**9, 1)}s") print(f"abs. change: {round((total_runtime_new - total_runtime_old) / 10**9, 1)}s") print(f"rel. change: {round(((total_runtime_new / total_runtime_old) - 1) * 100)}%") print(f"max loss: {max_lost}%") print(f"min loss: {min_lost}%") print(f"max gain: {max_gain}%") print(f"min gain: {min_gain}%") print(f"# overall: {num_overall}") print(f"# losses >= {confidence_threshold}%: {num_lost}") print(f"# gains >= {confidence_threshold}%: {num_gain}")
#!/usr/bin/env python3 import json import math import numpy as np import re import sys from terminaltables import AsciiTable from termcolor import colored from scipy.stats import ttest_ind p_value_significance_threshold = 0.001 min_iterations = 10 min_runtime_ns = 59 * 1000 * 1000 * 1000 min_iterations_disabling_min_runtime = 100 max_lost = 0 max_gain = 0 min_lost = -float('inf') min_gain = float('inf') num_lost = 0 num_gain = 0 num_overall = 0 # threshold for latency gain/loss to be considered (>=) confidence_threshold = 5 def format_diff(diff): diff -= 1 # adapt to show change in percent if diff < 0.0: return f"{diff:.0%}" else: return f"+{diff:.0%}" def color_diff(diff, inverse_colors=False): def select_color(value, color): return color if round(abs(value - 1), 2) >= 0.05 else "white" diff_str = format_diff(diff) color = "green" if (diff_str[0] == "+") != (inverse_colors) else "red" return colored(format_diff(diff), select_color(diff, color)) def geometric_mean(values): product = 1 for value in values: product *= value return product ** (1 / float(len(values))) def calculate_and_format_p_value(old_durations, new_durations): p_value = ttest_ind(old_durations, new_durations)[1] is_significant = p_value < p_value_significance_threshold old_runtime = sum(runtime for runtime in old_durations) new_runtime = sum(runtime for runtime in new_durations) # The results for a query are considered to be statistically not significant if the runtime is too short. However, # if the item has been executed > `min_iterations_disabling_min_runtime` times, it is considered significant. if (old_runtime < min_runtime_ns or new_runtime < min_runtime_ns) and ( len(old_durations) < min_iterations_disabling_min_runtime or len(new_durations) < min_iterations_disabling_min_runtime ): is_significant = False return "(run time too short)" elif len(old_durations) < min_iterations or len(new_durations) < min_iterations: is_significant = False # In case we cannot decide whether the change is significant due to an insufficient number of measurements, the # add_note_for_insufficient_pvalue_runs flag it set, for which a note is later added to the table output. global add_note_for_insufficient_pvalue_runs add_note_for_insufficient_pvalue_runs = True return colored("˅", "yellow", attrs=["bold"]) else: if is_significant: return colored(f"{p_value:.4f}", "white") else: return colored(f"{p_value:.4f}", "yellow", attrs=["bold"]) def create_context_overview(old_config, new_config, github_format): ignore_difference_for = ["GIT-HASH", "date"] old_context_keys = set(old_config["context"].keys()) new_context_keys = set(new_config["context"].keys()) common_context_keys = old_context_keys & new_context_keys table_lines = [["Parameter", sys.argv[1], sys.argv[2]]] for key in sorted(common_context_keys): old_value = old_config["context"][key] new_value = new_config["context"][key] color = "white" marker = " " if old_value != new_value and key not in ignore_difference_for: color = "red" marker = "≠" if key == "build_type" and (old_value == "debug" or new_value == "debug"): # Always warn when non-release builds are benchmarked color = "red" marker = "!" table_lines.append([colored(marker + key, color), old_value, new_value]) # Print keys that are not present in both contexts for key in sorted(old_context_keys - common_context_keys): value = old_config["context"][key] table_lines.append([colored("≠" + key, "red"), value, "undefined"]) for key in sorted(new_context_keys - common_context_keys): value = new_config["context"][key] table_lines.append([colored("≠" + key, "red"), "undefined", value]) table = AsciiTable(table_lines) table.title = "Configuration Overview" table_output = str(table.table) if github_format: # For GitHub, the output is a fake diff, where a leading '-' marks a deletion and causes the line to be printed # in red. We do that for all differing configuration lines. Other lines are prepended with ' '. new_output = "" for line in table_output.splitlines(): marker = "-" if ("≠" in line or "!" in line) else " " new_output += f"{marker}{line}\n" return new_output return table_output # Doubles the separators (can be '|' for normal rows and '+' for horizontal separators within the table) given by the # list vertical_separators_to_duplicate. [0, 3] means that the first and fourth separator are doubled. Table contents # must not contain '|' for this to work. def double_vertical_separators(lines, vertical_separators_to_duplicate): for line_id, line in enumerate(lines): vertical_separator = line[0] # positions might change due to color coding pos_separators = [m.start() for m in re.finditer(re.escape(vertical_separator), line)] # 0 required for splicing pos_splits = [0] + [pos_separators[index] for index in vertical_separators_to_duplicate] new_line = [line[i:j] for i, j in zip(pos_splits, pos_splits[1:] + [None])] lines[line_id] = vertical_separator.join(new_line) return lines if not len(sys.argv) in [3, 4]: exit("Usage: " + sys.argv[0] + " benchmark1.json benchmark2.json [--github]") # Format the output as a diff (prepending - and +) so that Github shows colors github_format = bool(len(sys.argv) == 4 and sys.argv[3] == "--github") with open(sys.argv[1]) as old_file: old_data = json.load(old_file) with open(sys.argv[2]) as new_file: new_data = json.load(new_file) if old_data["context"]["benchmark_mode"] != new_data["context"]["benchmark_mode"]: exit("Benchmark runs with different modes (ordered/shuffled) are not comparable") diffs_throughput = [] total_runtime_old = 0 total_runtime_new = 0 add_note_for_capped_runs = False # Flag set when max query runs was set for benchmark run add_note_for_insufficient_pvalue_runs = False # Flag set when runs was insufficient for p-value calculation # Create table header: # $latency and $thrghpt (abbreviated to keep the column at a max width of 8 chars) will later be replaced with a title # spanning two columns table_data = [] table_data.append(["Item", "$latency", "", "Change", "$thrghpt", "", "Change", "p-value"]) table_data.append(["", "old", "new", "", "old", "new", "", ""]) for old, new in zip(old_data["benchmarks"], new_data["benchmarks"]): name = old["name"] if name == "95": continue if old["name"] != new["name"]: name += " -> " + new["name"] num_overall += 1 # Create numpy arrays for old/new successful/unsuccessful runs from benchmark dictionary old_successful_durations = np.array([run["duration"] for run in old["successful_runs"]], dtype=np.float64) new_successful_durations = np.array([run["duration"] for run in new["successful_runs"]], dtype=np.float64) old_unsuccessful_durations = np.array([run["duration"] for run in old["unsuccessful_runs"]], dtype=np.float64) new_unsuccessful_durations = np.array([run["duration"] for run in new["unsuccessful_runs"]], dtype=np.float64) old_avg_successful_duration = np.mean(old_successful_durations) # defaults to np.float64 for int input new_avg_successful_duration = np.mean(new_successful_durations) total_runtime_old += old_avg_successful_duration if not math.isnan(old_avg_successful_duration) else 0.0 total_runtime_new += new_avg_successful_duration if not math.isnan(new_avg_successful_duration) else 0.0 # Check for duration==0 to avoid div/0 if float(old_avg_successful_duration) > 0.0: diff_duration = float(new_avg_successful_duration / old_avg_successful_duration) change = int(format_diff(diff_duration).replace("%", "")) max_lost = min(change, max_lost) max_gain = max(change, max_gain) if abs(change) >= confidence_threshold: if change < 0: num_lost += 1 min_lost = max(change, min_lost) elif change > 0: num_gain += 1 min_gain = min(change, min_gain) else: diff_duration = float("nan") if float(old["items_per_second"]) > 0.0: diff_throughput = float(new["items_per_second"]) / float(old["items_per_second"]) diffs_throughput.append(diff_throughput) else: diff_throughput = float("nan") # Format the diffs (add colors and percentage output) and calculate p-value diff_duration_formatted = color_diff(diff_duration, True) diff_throughput_formatted = color_diff(diff_throughput) p_value_formatted = calculate_and_format_p_value(old_successful_durations, new_successful_durations) old_iteration_count = len(old_successful_durations) + len(old_unsuccessful_durations) new_iteration_count = len(new_successful_durations) + len(new_unsuccessful_durations) # Check if number of runs reached max_runs if (old_data["context"]["max_runs"] > 0 or new_data["context"]["max_runs"] > 0) and ( old_iteration_count == old_data["context"]["max_runs"] or new_iteration_count == new_data["context"]["max_runs"] ): note = colored("˄", "yellow", attrs=["bold"]) add_note_for_capped_runs = True else: note = " " # Add table row for succesful executions. We use column widths of 7 (latency) and 8 (throughput) for printing to # ensure that we have enough space to replace the latency/throughput marker with a column header spanning multiple # columns. table_data.append( [ name, f"{(old_avg_successful_duration / 1e6):>7.1f}" if old_avg_successful_duration else "nan", f"{(new_avg_successful_duration / 1e6):>7.1f}" if new_avg_successful_duration else "nan", diff_duration_formatted + note if not math.isnan(diff_duration) else "", f'{old["items_per_second"]:>8.2f}', f'{new["items_per_second"]:>8.2f}', diff_throughput_formatted + note, p_value_formatted, ] ) if len(old["unsuccessful_runs"]) > 0 or len(new["unsuccessful_runs"]) > 0: if old_data["context"]["benchmark_mode"] == "Ordered": old_unsuccessful_per_second = float(len(old_unsuccessful_durations)) / (float(old["duration"]) / 1e9) new_unsuccessful_per_second = float(len(new_unsuccessful_durations)) / (float(new["duration"]) / 1e9) else: old_unsuccessful_per_second = float(len(old_unsuccessful_durations)) / ( float(old_data["summary"]["total_duration"]) / 1e9 ) new_unsuccessful_per_second = float(len(new_unsuccessful_durations)) / ( float(new_data["summary"]["total_duration"]) / 1e9 ) old_avg_unsuccessful_duration = np.mean(old_unsuccessful_durations) new_avg_unsuccessful_duration = np.mean(new_unsuccessful_durations) if len(old_unsuccessful_durations) > 0 and len(new_unsuccessful_durations) > 0: diff_throughput_unsuccessful = float(new_unsuccessful_per_second / old_unsuccessful_per_second) diff_duration_unsuccessful = new_avg_unsuccessful_duration / old_avg_unsuccessful_duration else: diff_throughput_unsuccessful = float("nan") diff_duration_unsuccessful = float("nan") unsuccessful_info = [ " unsucc.:", f"{(old_avg_unsuccessful_duration / 1e6):>7.1f}" if not math.isnan(old_avg_unsuccessful_duration) else "nan", f"{(new_avg_unsuccessful_duration / 1e6):>7.1f}" if not math.isnan(new_avg_unsuccessful_duration) else "nan", format_diff(diff_duration_unsuccessful) + " " if not math.isnan(diff_duration_unsuccessful) else " ", f"{old_unsuccessful_per_second:>.2f}", f"{new_unsuccessful_per_second:>.2f}", format_diff(diff_throughput_unsuccessful) + " " if not math.isnan(diff_throughput_unsuccessful) else " ", ] unsuccessful_info_colored = [colored(text, attrs=["dark"]) for text in unsuccessful_info] table_data.append(unsuccessful_info_colored) # Add a summary of all benchmark items to the final table, including (1) the change of the accumulated sum of all # queries' average runtimes and (2) the geometric mean of the percentage changes. table_data.append( [ "Sum", f"{(total_runtime_old / 1e6):>7.1f}", f"{(total_runtime_new / 1e6):>7.1f}", color_diff(total_runtime_new / total_runtime_old, True) + " ", ] ) table_data.append(["Geomean", "", "", "", "", "", color_diff(geometric_mean(diffs_throughput)) + " "]) table = AsciiTable(table_data) for column_index in range(1, len(table_data[0])): # all columns justified to right, except for item name table.justify_columns[column_index] = "right" table_string = str(table.table) table_string_reformatted = "" lines = table_string.splitlines() # Double the vertical line between the item names and the two major measurements. lines = double_vertical_separators(lines, [1, 4]) # As the used terminaltables module does not support cells that span multiple columns, we do that manually for latency # and throughput in the header. We used two place holders that are narrow enough to not grow the column any wider than # necessary for the actual values. After manually changing the column title to span two column, we replace the place # holder with the actual full descriptions. for (placeholder, final) in [ ("$thrghpt", "Throughput (iter/s)"), ("$latency", "Latency (ms/iter)"), ]: header_strings = lines[1].split("|") for column_id, text in enumerate(header_strings): if placeholder in text: title_column = header_strings[column_id] unit_column = header_strings[column_id + 1] previous_length = len(title_column) + len(unit_column) + 1 new_title = f" {final} ".ljust(previous_length, " ") lines[1] = "|".join(header_strings[:column_id] + [new_title] + header_strings[column_id + 2 :]) # Swap second line of header with automatically added separator. Terminaltables does not support multi-line headers. So # we have the second header line as part of the results after a separator line. We need to swap these. lines[2], lines[3] = lines[3], lines[2] for (line_number, line) in enumerate(lines): if line_number == len(table_data): # Add another separation between benchmark items and aggregates table_string_reformatted += lines[-1] + "\n" table_string_reformatted += line + "\n" # In case the runs for the executed benchmark have been cut or the number of runs was insufficient for the p-value # calcution, we add notes to the end of the table. if add_note_for_capped_runs or add_note_for_insufficient_pvalue_runs: first_column_width = len(lines[1].split("|")[1]) width_for_note = len(lines[0]) - first_column_width - 5 # 5 for seperators and spaces if add_note_for_capped_runs: note = "˄ Execution stopped due to max runs reached" table_string_reformatted += "|" + (" Notes ".rjust(first_column_width, " ")) table_string_reformatted += "|| " + note.ljust(width_for_note, " ") + "|\n" if add_note_for_insufficient_pvalue_runs: note = "˅" + " Insufficient number of runs for p-value calculation" table_string_reformatted += "|" + (" " * first_column_width) + "|| " + note.ljust(width_for_note, " ") + "|\n" table_string_reformatted += lines[-1] + "\n" table_string = table_string_reformatted # If github_format is set, format the output in the style of a diff file where added lines (starting with +) are # colored green, removed lines (starting with -) are red, and others (starting with an empty space) are black. # Because terminaltables (unsurprisingly) does not support this hack, we need to post-process the result string, # searching for the control codes that define text to be formatted as green or red. if github_format: green_control_sequence = colored("", "green")[0:5] red_control_sequence = colored("", "red")[0:5] table_string_reformatted = ( "<details>\n" + "<summary>Configuration Overview - click to expand</summary>\n\n" + "```diff\n" + create_context_overview(old_data, new_data, github_format) + "```\n" + "</details>\n\n" + "```diff\n" ) for line in table_string.splitlines(): if green_control_sequence in line: table_string_reformatted += "+" elif red_control_sequence in line: table_string_reformatted += "-" else: table_string_reformatted += " " table_string_reformatted += line + "\n" table_string_reformatted += "```" table_string = table_string_reformatted else: table_string = create_context_overview(old_data, new_data, github_format) + "\n\n" + table_string print(table_string) print() print("loss --> latency now lower, gain --> latency now higher") print(f"baseline: {round(total_runtime_old / 10**9, 1)}s") print(f"abs. change: {round((total_runtime_new - total_runtime_old) / 10**9, 1)}s") print(f"rel. change: {round(((total_runtime_new / total_runtime_old) - 1) * 100)}%") print(f"max loss: {max_lost}%") print(f"min loss: {min_lost}%") print(f"max gain: {max_gain}%") print(f"min gain: {min_gain}%") print(f"# overall: {num_overall}") print(f"# losses >= {confidence_threshold}%: {num_lost}") print(f"# gains >= {confidence_threshold}%: {num_gain}")
# pylint: disable=too-many-lines # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- import base64 import binascii import datetime import errno import json import os import os.path import platform import re import ssl import stat import subprocess import sys import tempfile import threading import time import uuid import webbrowser from math import isnan import colorama # pylint: disable=import-error import yaml # pylint: disable=import-error from azure.cli.core.api import get_config_dir from azure.cli.core.azclierror import ( ArgumentUsageError, InvalidArgumentValueError, ) from azure.cli.core.commands import LongRunningOperation from azure.cli.core.commands.client_factory import ( get_mgmt_service_client, get_subscription_id, ) from azure.cli.core.util import ( get_file_json, in_cloud_console, read_file_content, sdk_no_wait, shell_safe_json_parse, ) from azure.graphrbac.models import ( ApplicationCreateParameters, KeyCredential, PasswordCredential, ServicePrincipalCreateParameters, ) from dateutil.parser import parse # pylint: disable=import-error from dateutil.relativedelta import relativedelta # pylint: disable=import-error from knack.log import get_logger from knack.prompting import NoTTYException, prompt_pass, prompt_y_n from knack.util import CLIError from msrestazure.azure_exceptions import CloudError from six.moves.urllib.error import URLError # pylint: disable=import-error from six.moves.urllib.request import urlopen # pylint: disable=import-error from tabulate import tabulate # pylint: disable=import-error from azext_aks_preview._client_factory import CUSTOM_MGMT_AKS_PREVIEW from ._client_factory import ( cf_agent_pools, cf_container_registry_service, cf_nodepool_snapshots_client, cf_mc_snapshots_client, cf_storage, get_auth_management_client, get_graph_rbac_management_client, get_msi_client, get_resource_by_name, ) from ._consts import ( ADDONS, ADDONS_DESCRIPTIONS, CONST_ACC_SGX_QUOTE_HELPER_ENABLED, CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME, CONST_AZURE_POLICY_ADDON_NAME, CONST_CONFCOM_ADDON_NAME, CONST_HTTP_APPLICATION_ROUTING_ADDON_NAME, CONST_INGRESS_APPGW_ADDON_NAME, CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID, CONST_INGRESS_APPGW_APPLICATION_GATEWAY_NAME, CONST_INGRESS_APPGW_SUBNET_CIDR, CONST_INGRESS_APPGW_SUBNET_ID, CONST_INGRESS_APPGW_WATCH_NAMESPACE, CONST_KUBE_DASHBOARD_ADDON_NAME, CONST_MANAGED_IDENTITY_OPERATOR_ROLE, CONST_MANAGED_IDENTITY_OPERATOR_ROLE_ID, CONST_MONITORING_ADDON_NAME, CONST_MONITORING_LOG_ANALYTICS_WORKSPACE_RESOURCE_ID, CONST_MONITORING_USING_AAD_MSI_AUTH, CONST_OPEN_SERVICE_MESH_ADDON_NAME, CONST_ROTATION_POLL_INTERVAL, CONST_SCALE_DOWN_MODE_DELETE, CONST_SCALE_SET_PRIORITY_REGULAR, CONST_SCALE_SET_PRIORITY_SPOT, CONST_SECRET_ROTATION_ENABLED, CONST_SPOT_EVICTION_POLICY_DELETE, CONST_VIRTUAL_NODE_ADDON_NAME, CONST_VIRTUAL_NODE_SUBNET_NAME, ) from ._helpers import ( _trim_fqdn_name_containing_hcp, ) from ._podidentity import ( _ensure_managed_identity_operator_permission, _ensure_pod_identity_addon_is_enabled, _fill_defaults_for_pod_identity_profile, _update_addon_pod_identity, ) from ._resourcegroup import get_rg_location from ._roleassignments import ( add_role_assignment, build_role_scope, create_role_assignment, resolve_object_id, resolve_role_id, ) from .addonconfiguration import ( add_ingress_appgw_addon_role_assignment, add_monitoring_role_assignment, add_virtual_node_role_assignment, enable_addons, ensure_container_insights_for_monitoring, ensure_default_log_analytics_workspace_for_monitoring, sanitize_loganalytics_ws_resource_id, ) from .maintenanceconfiguration import ( aks_maintenanceconfiguration_update_internal, ) from .vendored_sdks.azure_mgmt_preview_aks.v2022_04_02_preview.models import ( AgentPool, AgentPoolUpgradeSettings, ContainerServiceStorageProfileTypes, CreationData, KubeletConfig, LinuxOSConfig, ManagedClusterAddonProfile, ManagedClusterHTTPProxyConfig, ManagedClusterPodIdentity, ManagedClusterPodIdentityException, PowerState, Snapshot, ManagedClusterSnapshot, SysctlConfig, UserAssignedIdentity, ) logger = get_logger(__name__) def which(binary): path_var = os.getenv('PATH') if platform.system() == 'Windows': binary = binary + '.exe' parts = path_var.split(';') else: parts = path_var.split(':') for part in parts: bin_path = os.path.join(part, binary) if os.path.exists(bin_path) and os.path.isfile(bin_path) and os.access(bin_path, os.X_OK): return bin_path return None def wait_then_open(url): """ Waits for a bit then opens a URL. Useful for waiting for a proxy to come up, and then open the URL. """ for _ in range(1, 10): try: urlopen(url, context=_ssl_context()) except URLError: time.sleep(1) break webbrowser.open_new_tab(url) def wait_then_open_async(url): """ Spawns a thread that waits for a bit then opens a URL. """ t = threading.Thread(target=wait_then_open, args=({url})) t.daemon = True t.start() def _ssl_context(): if sys.version_info < (3, 4) or (in_cloud_console() and platform.system() == 'Windows'): try: # added in python 2.7.13 and 3.6 return ssl.SSLContext(ssl.PROTOCOL_TLS) except AttributeError: return ssl.SSLContext(ssl.PROTOCOL_TLSv1) return ssl.create_default_context() def _build_service_principal(rbac_client, cli_ctx, name, url, client_secret): # use get_progress_controller hook = cli_ctx.get_progress_controller(True) hook.add(messsage='Creating service principal', value=0, total_val=1.0) logger.info('Creating service principal') # always create application with 5 years expiration start_date = datetime.datetime.utcnow() end_date = start_date + relativedelta(years=5) result = create_application(rbac_client.applications, name, url, [url], password=client_secret, start_date=start_date, end_date=end_date) service_principal = result.app_id # pylint: disable=no-member for x in range(0, 10): hook.add(message='Creating service principal', value=0.1 * x, total_val=1.0) try: create_service_principal( cli_ctx, service_principal, rbac_client=rbac_client) break # TODO figure out what exception AAD throws here sometimes. except Exception as ex: # pylint: disable=broad-except logger.info(ex) time.sleep(2 + 2 * x) else: return False hook.add(message='Finished service principal creation', value=1.0, total_val=1.0) logger.info('Finished service principal creation') return service_principal def _delete_role_assignments(cli_ctx, role, service_principal, delay=2, scope=None): # AAD can have delays in propagating data, so sleep and retry hook = cli_ctx.get_progress_controller(True) hook.add(message='Waiting for AAD role to delete', value=0, total_val=1.0) logger.info('Waiting for AAD role to delete') for x in range(0, 10): hook.add(message='Waiting for AAD role to delete', value=0.1 * x, total_val=1.0) try: delete_role_assignments(cli_ctx, role=role, assignee=service_principal, scope=scope) break except CLIError as ex: raise ex except CloudError as ex: logger.info(ex) time.sleep(delay + delay * x) else: return False hook.add(message='AAD role deletion done', value=1.0, total_val=1.0) logger.info('AAD role deletion done') return True def _get_default_dns_prefix(name, resource_group_name, subscription_id): # Use subscription id to provide uniqueness and prevent DNS name clashes name_part = re.sub('[^A-Za-z0-9-]', '', name)[0:10] if not name_part[0].isalpha(): name_part = (str('a') + name_part)[0:10] resource_group_part = re.sub( '[^A-Za-z0-9-]', '', resource_group_name)[0:16] return '{}-{}-{}'.format(name_part, resource_group_part, subscription_id[0:6]) # pylint: disable=too-many-locals def store_acs_service_principal(subscription_id, client_secret, service_principal, file_name='acsServicePrincipal.json'): obj = {} if client_secret: obj['client_secret'] = client_secret if service_principal: obj['service_principal'] = service_principal config_path = os.path.join(get_config_dir(), file_name) full_config = load_service_principals(config_path=config_path) if not full_config: full_config = {} full_config[subscription_id] = obj with os.fdopen(os.open(config_path, os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o600), 'w+') as spFile: json.dump(full_config, spFile) def load_acs_service_principal(subscription_id, file_name='acsServicePrincipal.json'): config_path = os.path.join(get_config_dir(), file_name) config = load_service_principals(config_path) if not config: return None return config.get(subscription_id) def load_service_principals(config_path): if not os.path.exists(config_path): return None fd = os.open(config_path, os.O_RDONLY) try: with os.fdopen(fd) as f: return shell_safe_json_parse(f.read()) except: # pylint: disable=bare-except return None def create_application(client, display_name, homepage, identifier_uris, available_to_other_tenants=False, password=None, reply_urls=None, key_value=None, key_type=None, key_usage=None, start_date=None, end_date=None): from azure.graphrbac.models import GraphErrorException password_creds, key_creds = _build_application_creds(password=password, key_value=key_value, key_type=key_type, key_usage=key_usage, start_date=start_date, end_date=end_date) app_create_param = ApplicationCreateParameters(available_to_other_tenants=available_to_other_tenants, display_name=display_name, identifier_uris=identifier_uris, homepage=homepage, reply_urls=reply_urls, key_credentials=key_creds, password_credentials=password_creds) try: return client.create(app_create_param) except GraphErrorException as ex: if 'insufficient privileges' in str(ex).lower(): link = 'https://docs.microsoft.com/azure/azure-resource-manager/resource-group-create-service-principal-portal' # pylint: disable=line-too-long raise CLIError("Directory permission is needed for the current user to register the application. " "For how to configure, please refer '{}'. Original error: {}".format(link, ex)) raise def _build_application_creds(password=None, key_value=None, key_type=None, key_usage=None, start_date=None, end_date=None): if password and key_value: raise CLIError( 'specify either --password or --key-value, but not both.') if not start_date: start_date = datetime.datetime.utcnow() elif isinstance(start_date, str): start_date = parse(start_date) if not end_date: end_date = start_date + relativedelta(years=1) elif isinstance(end_date, str): end_date = parse(end_date) key_type = key_type or 'AsymmetricX509Cert' key_usage = key_usage or 'Verify' password_creds = None key_creds = None if password: password_creds = [PasswordCredential(start_date=start_date, end_date=end_date, key_id=str(uuid.uuid4()), value=password)] elif key_value: key_creds = [KeyCredential(start_date=start_date, end_date=end_date, value=key_value, key_id=str(uuid.uuid4()), usage=key_usage, type=key_type)] return (password_creds, key_creds) def create_service_principal(cli_ctx, identifier, resolve_app=True, rbac_client=None): if rbac_client is None: rbac_client = get_graph_rbac_management_client(cli_ctx) if resolve_app: try: uuid.UUID(identifier) result = list(rbac_client.applications.list( filter="appId eq '{}'".format(identifier))) except ValueError: result = list(rbac_client.applications.list( filter="identifierUris/any(s:s eq '{}')".format(identifier))) if not result: # assume we get an object id result = [rbac_client.applications.get(identifier)] app_id = result[0].app_id else: app_id = identifier return rbac_client.service_principals.create(ServicePrincipalCreateParameters(app_id=app_id, account_enabled=True)) def delete_role_assignments(cli_ctx, ids=None, assignee=None, role=None, resource_group_name=None, scope=None, include_inherited=False, yes=None): factory = get_auth_management_client(cli_ctx, scope) assignments_client = factory.role_assignments definitions_client = factory.role_definitions ids = ids or [] if ids: if assignee or role or resource_group_name or scope or include_inherited: raise CLIError( 'When assignment ids are used, other parameter values are not required') for i in ids: assignments_client.delete_by_id(i) return if not any([ids, assignee, role, resource_group_name, scope, assignee, yes]): msg = 'This will delete all role assignments under the subscription. Are you sure?' if not prompt_y_n(msg, default="n"): return scope = build_role_scope(resource_group_name, scope, assignments_client.config.subscription_id) assignments = _search_role_assignments(cli_ctx, assignments_client, definitions_client, scope, assignee, role, include_inherited, include_groups=False) if assignments: for a in assignments: assignments_client.delete_by_id(a.id) def _delete_role_assignments(cli_ctx, role, service_principal, delay=2, scope=None): # AAD can have delays in propagating data, so sleep and retry hook = cli_ctx.get_progress_controller(True) hook.add(message='Waiting for AAD role to delete', value=0, total_val=1.0) logger.info('Waiting for AAD role to delete') for x in range(0, 10): hook.add(message='Waiting for AAD role to delete', value=0.1 * x, total_val=1.0) try: delete_role_assignments(cli_ctx, role=role, assignee=service_principal, scope=scope) break except CLIError as ex: raise ex except CloudError as ex: logger.info(ex) time.sleep(delay + delay * x) else: return False hook.add(message='AAD role deletion done', value=1.0, total_val=1.0) logger.info('AAD role deletion done') return True def _search_role_assignments(cli_ctx, assignments_client, definitions_client, scope, assignee, role, include_inherited, include_groups): assignee_object_id = None if assignee: assignee_object_id = resolve_object_id(cli_ctx, assignee) # always use "scope" if provided, so we can get assignments beyond subscription e.g. management groups if scope: assignments = list(assignments_client.list_for_scope( scope=scope, filter='atScope()')) elif assignee_object_id: if include_groups: f = "assignedTo('{}')".format(assignee_object_id) else: f = "principalId eq '{}'".format(assignee_object_id) assignments = list(assignments_client.list(filter=f)) else: assignments = list(assignments_client.list()) if assignments: assignments = [a for a in assignments if ( not scope or include_inherited and re.match(_get_role_property(a, 'scope'), scope, re.I) or _get_role_property(a, 'scope').lower() == scope.lower() )] if role: role_id = resolve_role_id(role, scope, definitions_client) assignments = [i for i in assignments if _get_role_property( i, 'role_definition_id') == role_id] if assignee_object_id: assignments = [i for i in assignments if _get_role_property( i, 'principal_id') == assignee_object_id] return assignments def _get_role_property(obj, property_name): if isinstance(obj, dict): return obj[property_name] return getattr(obj, property_name) def subnet_role_assignment_exists(cli_ctx, scope): network_contributor_role_id = "4d97b98b-1d4f-4787-a291-c67834d212e7" factory = get_auth_management_client(cli_ctx, scope) assignments_client = factory.role_assignments for i in assignments_client.list_for_scope(scope=scope, filter='atScope()'): if i.scope == scope and i.role_definition_id.endswith(network_contributor_role_id): return True return False _re_user_assigned_identity_resource_id = re.compile( r'/subscriptions/(.*?)/resourcegroups/(.*?)/providers/microsoft.managedidentity/userassignedidentities/(.*)', flags=re.IGNORECASE) def _get_user_assigned_identity(cli_ctx, resource_id): resource_id = resource_id.lower() match = _re_user_assigned_identity_resource_id.search(resource_id) if match: subscription_id = match.group(1) resource_group_name = match.group(2) identity_name = match.group(3) msi_client = get_msi_client(cli_ctx, subscription_id) try: identity = msi_client.user_assigned_identities.get(resource_group_name=resource_group_name, resource_name=identity_name) except CloudError as ex: if 'was not found' in ex.message: raise CLIError("Identity {} not found.".format(resource_id)) raise CLIError(ex.message) return identity raise CLIError( "Cannot parse identity name from provided resource id {}.".format(resource_id)) _re_snapshot_resource_id = re.compile( r'/subscriptions/(.*?)/resourcegroups/(.*?)/providers/microsoft.containerservice/snapshots/(.*)', flags=re.IGNORECASE) _re_mc_snapshot_resource_id = re.compile( r'/subscriptions/(.*?)/resourcegroups/(.*?)/providers/microsoft.containerservice/managedclustersnapshots/(.*)', flags=re.IGNORECASE) def _get_snapshot(cli_ctx, snapshot_id): snapshot_id = snapshot_id.lower() match = _re_snapshot_resource_id.search(snapshot_id) if match: subscription_id = match.group(1) resource_group_name = match.group(2) snapshot_name = match.group(3) snapshot_client = cf_nodepool_snapshots_client( cli_ctx, subscription_id=subscription_id) try: snapshot = snapshot_client.get(resource_group_name, snapshot_name) except CloudError as ex: if 'was not found' in ex.message: raise InvalidArgumentValueError( "Snapshot {} not found.".format(snapshot_id)) raise CLIError(ex.message) return snapshot raise InvalidArgumentValueError( "Cannot parse snapshot name from provided resource id {}.".format(snapshot_id)) def _get_cluster_snapshot(cli_ctx, snapshot_id): snapshot_id = snapshot_id.lower() match = _re_mc_snapshot_resource_id.search(snapshot_id) if match: subscription_id = match.group(1) resource_group_name = match.group(2) snapshot_name = match.group(3) snapshot_client = cf_mc_snapshots_client( cli_ctx, subscription_id=subscription_id) try: snapshot = snapshot_client.get(resource_group_name, snapshot_name) except CloudError as ex: if 'was not found' in ex.message: raise InvalidArgumentValueError( "Managed cluster snapshot {} not found.".format(snapshot_id)) raise CLIError(ex.message) return snapshot raise InvalidArgumentValueError( "Cannot parse snapshot name from provided resource id {}.".format(snapshot_id)) def aks_browse( cmd, client, resource_group_name, name, disable_browser=False, listen_address="127.0.0.1", listen_port="8001", ): from azure.cli.command_modules.acs.custom import _aks_browse return _aks_browse( cmd, client, resource_group_name, name, disable_browser, listen_address, listen_port, CUSTOM_MGMT_AKS_PREVIEW, ) def _trim_nodepoolname(nodepool_name): if not nodepool_name: return "nodepool1" return nodepool_name[:12] def aks_maintenanceconfiguration_list( cmd, client, resource_group_name, cluster_name ): return client.list_by_managed_cluster(resource_group_name, cluster_name) def aks_maintenanceconfiguration_show( cmd, client, resource_group_name, cluster_name, config_name ): logger.warning('resource_group_name: %s, cluster_name: %s, config_name: %s ', resource_group_name, cluster_name, config_name) return client.get(resource_group_name, cluster_name, config_name) def aks_maintenanceconfiguration_delete( cmd, client, resource_group_name, cluster_name, config_name ): logger.warning('resource_group_name: %s, cluster_name: %s, config_name: %s ', resource_group_name, cluster_name, config_name) return client.delete(resource_group_name, cluster_name, config_name) def aks_maintenanceconfiguration_add( cmd, client, resource_group_name, cluster_name, config_name, config_file, weekday, start_hour ): configs = client.list_by_managed_cluster(resource_group_name, cluster_name) for config in configs: if config.name == config_name: raise CLIError("Maintenance configuration '{}' already exists, please try a different name, " "use 'aks maintenanceconfiguration list' to get current list of maitenance configurations".format(config_name)) return aks_maintenanceconfiguration_update_internal(cmd, client, resource_group_name, cluster_name, config_name, config_file, weekday, start_hour) def aks_maintenanceconfiguration_update( cmd, client, resource_group_name, cluster_name, config_name, config_file, weekday, start_hour ): configs = client.list_by_managed_cluster(resource_group_name, cluster_name) found = False for config in configs: if config.name == config_name: found = True break if not found: raise CLIError("Maintenance configuration '{}' doesn't exist." "use 'aks maintenanceconfiguration list' to get current list of maitenance configurations".format(config_name)) return aks_maintenanceconfiguration_update_internal(cmd, client, resource_group_name, cluster_name, config_name, config_file, weekday, start_hour) # pylint: disable=unused-argument,too-many-locals def aks_create(cmd, client, resource_group_name, name, ssh_key_value, dns_name_prefix=None, location=None, admin_username="azureuser", windows_admin_username=None, windows_admin_password=None, enable_ahub=False, kubernetes_version='', node_vm_size=None, node_osdisk_type=None, node_osdisk_size=0, node_osdisk_diskencryptionset_id=None, node_count=3, nodepool_name="nodepool1", nodepool_tags=None, nodepool_labels=None, service_principal=None, client_secret=None, no_ssh_key=False, disable_rbac=None, enable_rbac=None, enable_vmss=None, vm_set_type=None, skip_subnet_role_assignment=False, os_sku=None, enable_fips_image=False, enable_cluster_autoscaler=False, cluster_autoscaler_profile=None, network_plugin=None, network_policy=None, pod_cidr=None, service_cidr=None, pod_cidrs=None, service_cidrs=None, ip_families=None, dns_service_ip=None, docker_bridge_address=None, load_balancer_sku=None, load_balancer_managed_outbound_ip_count=None, load_balancer_managed_outbound_ipv6_count=None, load_balancer_outbound_ips=None, load_balancer_outbound_ip_prefixes=None, load_balancer_outbound_ports=None, load_balancer_idle_timeout=None, nat_gateway_managed_outbound_ip_count=None, nat_gateway_idle_timeout=None, outbound_type=None, enable_addons=None, workspace_resource_id=None, enable_msi_auth_for_monitoring=False, min_count=None, max_count=None, vnet_subnet_id=None, pod_subnet_id=None, ppg=None, max_pods=0, aad_client_app_id=None, aad_server_app_id=None, aad_server_app_secret=None, aad_tenant_id=None, tags=None, node_zones=None, zones=None, enable_node_public_ip=False, node_public_ip_prefix_id=None, generate_ssh_keys=False, # pylint: disable=unused-argument enable_pod_security_policy=False, node_resource_group=None, uptime_sla=False, attach_acr=None, enable_private_cluster=False, private_dns_zone=None, enable_managed_identity=True, fqdn_subdomain=None, disable_public_fqdn=False, api_server_authorized_ip_ranges=None, aks_custom_headers=None, appgw_name=None, appgw_subnet_prefix=None, appgw_subnet_cidr=None, appgw_id=None, appgw_subnet_id=None, appgw_watch_namespace=None, enable_aad=False, enable_azure_rbac=False, aad_admin_group_object_ids=None, aci_subnet_name=None, enable_sgxquotehelper=False, kubelet_config=None, linux_os_config=None, http_proxy_config=None, assign_identity=None, auto_upgrade_channel=None, enable_pod_identity=False, enable_pod_identity_with_kubenet=False, # NOTE: for workload identity flags, we need to know if it's set to True/False or not set (None) enable_workload_identity=None, enable_encryption_at_host=False, enable_ultra_ssd=False, edge_zone=None, enable_secret_rotation=False, disable_disk_driver=None, disable_file_driver=None, disable_snapshot_controller=None, rotation_poll_interval=None, disable_local_accounts=False, no_wait=False, assign_kubelet_identity=None, workload_runtime=None, gpu_instance_profile=None, enable_windows_gmsa=False, gmsa_dns_server=None, gmsa_root_domain_name=None, snapshot_id=None, cluster_snapshot_id=None, enable_oidc_issuer=False, host_group_id=None, crg_id=None, message_of_the_day=None, enable_azure_keyvault_kms=False, azure_keyvault_kms_key_id=None, enable_apiserver_vnet_integration=False, apiserver_subnet_id=None, yes=False): # DO NOT MOVE: get all the original parameters and save them as a dictionary raw_parameters = locals() from azure.cli.command_modules.acs._consts import DecoratorEarlyExitException from azure.cli.command_modules.acs.decorator import AKSParamDict from .decorator import AKSPreviewCreateDecorator # decorator pattern aks_create_decorator = AKSPreviewCreateDecorator( cmd=cmd, client=client, raw_parameters=AKSParamDict(raw_parameters), resource_type=CUSTOM_MGMT_AKS_PREVIEW, ) try: # construct mc profile mc = aks_create_decorator.construct_mc_preview_profile() except DecoratorEarlyExitException: # exit gracefully return None # send request to create a real managed cluster return aks_create_decorator.create_mc_preview(mc) def aks_update(cmd, # pylint: disable=too-many-statements,too-many-branches,too-many-locals client, resource_group_name, name, enable_cluster_autoscaler=False, disable_cluster_autoscaler=False, update_cluster_autoscaler=False, cluster_autoscaler_profile=None, min_count=None, max_count=None, no_wait=False, load_balancer_managed_outbound_ip_count=None, load_balancer_managed_outbound_ipv6_count=None, load_balancer_outbound_ips=None, load_balancer_outbound_ip_prefixes=None, load_balancer_outbound_ports=None, load_balancer_idle_timeout=None, nat_gateway_managed_outbound_ip_count=None, nat_gateway_idle_timeout=None, api_server_authorized_ip_ranges=None, enable_pod_security_policy=False, disable_pod_security_policy=False, attach_acr=None, detach_acr=None, uptime_sla=False, no_uptime_sla=False, enable_aad=False, aad_tenant_id=None, aad_admin_group_object_ids=None, enable_ahub=False, disable_ahub=False, aks_custom_headers=None, auto_upgrade_channel=None, enable_managed_identity=False, assign_identity=None, assign_kubelet_identity=None, enable_pod_identity=False, enable_pod_identity_with_kubenet=False, disable_pod_identity=False, # NOTE: for workload identity flags, we need to know if it's set to True/False or not set (None) enable_workload_identity=None, disable_workload_identity=None, enable_secret_rotation=False, disable_secret_rotation=False, rotation_poll_interval=None, enable_disk_driver=None, disable_disk_driver=None, enable_file_driver=None, disable_file_driver=None, enable_snapshot_controller=None, disable_snapshot_controller=None, disable_local_accounts=False, enable_local_accounts=False, enable_public_fqdn=False, disable_public_fqdn=False, yes=False, tags=None, nodepool_labels=None, windows_admin_password=None, enable_azure_rbac=False, disable_azure_rbac=False, enable_windows_gmsa=False, gmsa_dns_server=None, gmsa_root_domain_name=None, enable_oidc_issuer=False, http_proxy_config=None, enable_azure_keyvault_kms=False, azure_keyvault_kms_key_id=None, enable_apiserver_vnet_integration=False, apiserver_subnet_id=None): # DO NOT MOVE: get all the original parameters and save them as a dictionary raw_parameters = locals() from azure.cli.command_modules.acs._consts import DecoratorEarlyExitException from azure.cli.command_modules.acs.decorator import AKSParamDict from .decorator import AKSPreviewUpdateDecorator # decorator pattern aks_update_decorator = AKSPreviewUpdateDecorator( cmd=cmd, client=client, raw_parameters=AKSParamDict(raw_parameters), resource_type=CUSTOM_MGMT_AKS_PREVIEW, ) try: # update mc profile mc = aks_update_decorator.update_mc_preview_profile() except DecoratorEarlyExitException: # exit gracefully return None # send request to update the real managed cluster return aks_update_decorator.update_mc_preview(mc) # pylint: disable=unused-argument def aks_show(cmd, client, resource_group_name, name): mc = client.get(resource_group_name, name) return _remove_nulls([mc])[0] def _remove_nulls(managed_clusters): """ Remove some often-empty fields from a list of ManagedClusters, so the JSON representation doesn't contain distracting null fields. This works around a quirk of the SDK for python behavior. These fields are not sent by the server, but get recreated by the CLI's own "to_dict" serialization. """ attrs = ['tags'] ap_attrs = ['os_disk_size_gb', 'vnet_subnet_id'] sp_attrs = ['secret'] for managed_cluster in managed_clusters: for attr in attrs: if getattr(managed_cluster, attr, None) is None: delattr(managed_cluster, attr) if managed_cluster.agent_pool_profiles is not None: for ap_profile in managed_cluster.agent_pool_profiles: for attr in ap_attrs: if getattr(ap_profile, attr, None) is None: delattr(ap_profile, attr) for attr in sp_attrs: if getattr(managed_cluster.service_principal_profile, attr, None) is None: delattr(managed_cluster.service_principal_profile, attr) return managed_clusters def aks_get_credentials(cmd, # pylint: disable=unused-argument client, resource_group_name, name, admin=False, user='clusterUser', path=os.path.join(os.path.expanduser( '~'), '.kube', 'config'), overwrite_existing=False, context_name=None, public_fqdn=False, credential_format=None): credentialResults = None serverType = None if public_fqdn: serverType = 'public' if credential_format: credential_format = credential_format.lower() if admin: raise InvalidArgumentValueError("--format can only be specified when requesting clusterUser credential.") if admin: credentialResults = client.list_cluster_admin_credentials( resource_group_name, name, serverType) else: if user.lower() == 'clusteruser': credentialResults = client.list_cluster_user_credentials( resource_group_name, name, serverType, credential_format) elif user.lower() == 'clustermonitoringuser': credentialResults = client.list_cluster_monitoring_user_credentials( resource_group_name, name, serverType) else: raise CLIError("The user is invalid.") if not credentialResults: raise CLIError("No Kubernetes credentials found.") try: kubeconfig = credentialResults.kubeconfigs[0].value.decode( encoding='UTF-8') _print_or_merge_credentials( path, kubeconfig, overwrite_existing, context_name) except (IndexError, ValueError): raise CLIError("Fail to find kubeconfig file.") # pylint: disable=line-too-long def aks_kollect(cmd, # pylint: disable=too-many-statements,too-many-locals client, resource_group_name, name, storage_account=None, sas_token=None, container_logs=None, kube_objects=None, node_logs=None): colorama.init() mc = client.get(resource_group_name, name) if not which('kubectl'): raise CLIError('Can not find kubectl executable in PATH') storage_account_id = None if storage_account is None: print("No storage account specified. Try getting storage account from diagnostic settings") storage_account_id = get_storage_account_from_diag_settings( cmd.cli_ctx, resource_group_name, name) if storage_account_id is None: raise CLIError( "A storage account must be specified, since there isn't one in the diagnostic settings.") from msrestazure.tools import (is_valid_resource_id, parse_resource_id, resource_id) if storage_account_id is None: if not is_valid_resource_id(storage_account): storage_account_id = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=resource_group_name, namespace='Microsoft.Storage', type='storageAccounts', name=storage_account ) else: storage_account_id = storage_account if is_valid_resource_id(storage_account_id): try: parsed_storage_account = parse_resource_id(storage_account_id) except CloudError as ex: raise CLIError(ex.message) else: raise CLIError("Invalid storage account id %s" % storage_account_id) storage_account_name = parsed_storage_account['name'] readonly_sas_token = None if sas_token is None: storage_client = cf_storage( cmd.cli_ctx, parsed_storage_account['subscription']) storage_account_keys = storage_client.storage_accounts.list_keys(parsed_storage_account['resource_group'], storage_account_name) kwargs = { 'account_name': storage_account_name, 'account_key': storage_account_keys.keys[0].value } cloud_storage_client = cloud_storage_account_service_factory( cmd.cli_ctx, kwargs) sas_token = cloud_storage_client.generate_shared_access_signature( 'b', 'sco', 'rwdlacup', datetime.datetime.utcnow() + datetime.timedelta(days=1)) readonly_sas_token = cloud_storage_client.generate_shared_access_signature( 'b', 'sco', 'rl', datetime.datetime.utcnow() + datetime.timedelta(days=1)) readonly_sas_token = readonly_sas_token.strip('?') print() print('This will deploy a daemon set to your cluster to collect logs and diagnostic information and ' f'save them to the storage account ' f'{colorama.Style.BRIGHT}{colorama.Fore.GREEN}{storage_account_name}{colorama.Style.RESET_ALL} as ' f'outlined in {format_hyperlink('http://aka.ms/AKSPeriscope')}.') print() print('If you share access to that storage account to Azure support, you consent to the terms outlined' f' in {format_hyperlink('http://aka.ms/DiagConsent')}.') print() if not prompt_y_n('Do you confirm?', default="n"): return print() print("Getting credentials for cluster %s " % name) _, temp_kubeconfig_path = tempfile.mkstemp() aks_get_credentials(cmd, client, resource_group_name, name, admin=True, path=temp_kubeconfig_path) print() print("Starts collecting diag info for cluster %s " % name) # Form containerName from fqdn, as it was previously jsut the location of code is changed. # https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata#container-names maxContainerNameLength = 63 fqdn = mc.fqdn if mc.fqdn is not None else mc.private_fqdn normalized_container_name = fqdn.replace('.', '-') len_of_container_name = normalized_container_name.index("-hcp-") if len_of_container_name == -1: len_of_container_name = maxContainerNameLength container_name = normalized_container_name[:len_of_container_name] sas_token = sas_token.strip('?') deployment_yaml = _read_periscope_yaml() deployment_yaml = deployment_yaml.replace( "# <accountName, string>", storage_account_name) deployment_yaml = deployment_yaml.replace("# <saskey, base64 encoded>", (base64.b64encode(bytes("?" + sas_token, 'ascii'))).decode('ascii')) deployment_yaml = deployment_yaml.replace( "# <containerName, string>", container_name) yaml_lines = deployment_yaml.splitlines() for index, line in enumerate(yaml_lines): if "DIAGNOSTIC_CONTAINERLOGS_LIST" in line and container_logs is not None: yaml_lines[index] = line + ' ' + container_logs if "DIAGNOSTIC_KUBEOBJECTS_LIST" in line and kube_objects is not None: yaml_lines[index] = line + ' ' + kube_objects if "DIAGNOSTIC_NODELOGS_LIST" in line and node_logs is not None: yaml_lines[index] = line + ' ' + node_logs deployment_yaml = '\n'.join(yaml_lines) fd, temp_yaml_path = tempfile.mkstemp() temp_yaml_file = os.fdopen(fd, 'w+t') try: temp_yaml_file.write(deployment_yaml) temp_yaml_file.flush() temp_yaml_file.close() try: print() print("Cleaning up aks-periscope resources if existing") subprocess.call(["kubectl", "--kubeconfig", temp_kubeconfig_path, "delete", "serviceaccount,configmap,daemonset,secret", "--all", "-n", "aks-periscope", "--ignore-not-found"], stderr=subprocess.STDOUT) subprocess.call(["kubectl", "--kubeconfig", temp_kubeconfig_path, "delete", "ClusterRoleBinding", "aks-periscope-role-binding", "--ignore-not-found"], stderr=subprocess.STDOUT) subprocess.call(["kubectl", "--kubeconfig", temp_kubeconfig_path, "delete", "ClusterRoleBinding", "aks-periscope-role-binding-view", "--ignore-not-found"], stderr=subprocess.STDOUT) subprocess.call(["kubectl", "--kubeconfig", temp_kubeconfig_path, "delete", "ClusterRole", "aks-periscope-role", "--ignore-not-found"], stderr=subprocess.STDOUT) subprocess.call(["kubectl", "--kubeconfig", temp_kubeconfig_path, "delete", "--all", "apd", "-n", "aks-periscope", "--ignore-not-found"], stderr=subprocess.DEVNULL) subprocess.call(["kubectl", "--kubeconfig", temp_kubeconfig_path, "delete", "CustomResourceDefinition", "diagnostics.aks-periscope.azure.github.com", "--ignore-not-found"], stderr=subprocess.STDOUT) print() print("Deploying aks-periscope") subprocess.check_output(["kubectl", "--kubeconfig", temp_kubeconfig_path, "apply", "-f", temp_yaml_path, "-n", "aks-periscope"], stderr=subprocess.STDOUT) except subprocess.CalledProcessError as err: raise CLIError(err.output) finally: os.remove(temp_yaml_path) print() token_in_storage_account_url = readonly_sas_token if readonly_sas_token is not None else sas_token log_storage_account_url = f"https://{storage_account_name}.blob.core.windows.net/" \ f"{_trim_fqdn_name_containing_hcp(container_name)}?{token_in_storage_account_url}" print(f'{colorama.Fore.GREEN}Your logs are being uploaded to storage account {format_bright(storage_account_name)}') print() print(f'You can download Azure Storage Explorer here ' f'{format_hyperlink('https://azure.microsoft.com/en-us/features/storage-explorer/')}' f' to check the logs by adding the storage account using the following URL:') print(f'{format_hyperlink(log_storage_account_url)}') print() if not prompt_y_n('Do you want to see analysis results now?', default="n"): print(f"You can run 'az aks kanalyze -g {resource_group_name} -n {name}' " f"anytime to check the analysis results.") else: display_diagnostics_report(temp_kubeconfig_path) def _read_periscope_yaml(): curr_dir = os.path.dirname(os.path.realpath(__file__)) periscope_yaml_file = os.path.join( curr_dir, "deploymentyaml", "aks-periscope.yaml") yaml_file = open(periscope_yaml_file, "r") data_loaded = yaml_file.read() return data_loaded def aks_kanalyze(cmd, client, resource_group_name, name): colorama.init() client.get(resource_group_name, name) _, temp_kubeconfig_path = tempfile.mkstemp() aks_get_credentials(cmd, client, resource_group_name, name, admin=True, path=temp_kubeconfig_path) display_diagnostics_report(temp_kubeconfig_path) def aks_scale(cmd, # pylint: disable=unused-argument client, resource_group_name, name, node_count, nodepool_name="", no_wait=False): instance = client.get(resource_group_name, name) _fill_defaults_for_pod_identity_profile(instance.pod_identity_profile) if len(instance.agent_pool_profiles) > 1 and nodepool_name == "": raise CLIError('There are more than one node pool in the cluster. ' 'Please specify nodepool name or use az aks nodepool command to scale node pool') for agent_profile in instance.agent_pool_profiles: if agent_profile.name == nodepool_name or (nodepool_name == "" and len(instance.agent_pool_profiles) == 1): if agent_profile.enable_auto_scaling: raise CLIError( "Cannot scale cluster autoscaler enabled node pool.") agent_profile.count = int(node_count) # pylint: disable=no-member # null out the SP profile because otherwise validation complains instance.service_principal_profile = None return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, name, instance) raise CLIError('The nodepool "{}" was not found.'.format(nodepool_name)) def aks_upgrade(cmd, # pylint: disable=unused-argument, too-many-return-statements client, resource_group_name, name, kubernetes_version='', control_plane_only=False, no_wait=False, node_image_only=False, aks_custom_headers=None, yes=False): msg = 'Kubernetes may be unavailable during cluster upgrades.\n Are you sure you want to perform this operation?' if not yes and not prompt_y_n(msg, default="n"): return None instance = client.get(resource_group_name, name) _fill_defaults_for_pod_identity_profile(instance.pod_identity_profile) vmas_cluster = False for agent_profile in instance.agent_pool_profiles: if agent_profile.type.lower() == "availabilityset": vmas_cluster = True break if kubernetes_version != '' and node_image_only: raise CLIError('Conflicting flags. Upgrading the Kubernetes version will also upgrade node image version. ' 'If you only want to upgrade the node version please use the "--node-image-only" option only.') if node_image_only: msg = "This node image upgrade operation will run across every node pool in the cluster " \ "and might take a while. Do you wish to continue?" if not yes and not prompt_y_n(msg, default="n"): return None # This only provide convenience for customer at client side so they can run az aks upgrade to upgrade all # nodepools of a cluster. The SDK only support upgrade single nodepool at a time. for agent_pool_profile in instance.agent_pool_profiles: if vmas_cluster: raise CLIError('This cluster is not using VirtualMachineScaleSets. Node image upgrade only operation ' 'can only be applied on VirtualMachineScaleSets cluster.') agent_pool_client = cf_agent_pools(cmd.cli_ctx) _upgrade_single_nodepool_image_version( True, agent_pool_client, resource_group_name, name, agent_pool_profile.name, None) mc = client.get(resource_group_name, name) return _remove_nulls([mc])[0] if instance.kubernetes_version == kubernetes_version: if instance.provisioning_state == "Succeeded": logger.warning("The cluster is already on version %s and is not in a failed state. No operations " "will occur when upgrading to the same version if the cluster is not in a failed state.", instance.kubernetes_version) elif instance.provisioning_state == "Failed": logger.warning("Cluster currently in failed state. Proceeding with upgrade to existing version %s to " "attempt resolution of failed cluster state.", instance.kubernetes_version) upgrade_all = False instance.kubernetes_version = kubernetes_version # for legacy clusters, we always upgrade node pools with CCP. if instance.max_agent_pools < 8 or vmas_cluster: if control_plane_only: msg = ("Legacy clusters do not support control plane only upgrade. All node pools will be " "upgraded to {} as well. Continue?").format(instance.kubernetes_version) if not yes and not prompt_y_n(msg, default="n"): return None upgrade_all = True else: if not control_plane_only: msg = ("Since control-plane-only argument is not specified, this will upgrade the control plane " "AND all nodepools to version {}. Continue?").format(instance.kubernetes_version) if not yes and not prompt_y_n(msg, default="n"): return None upgrade_all = True else: msg = ("Since control-plane-only argument is specified, this will upgrade only the control plane to {}. " "Node pool will not change. Continue?").format(instance.kubernetes_version) if not yes and not prompt_y_n(msg, default="n"): return None if upgrade_all: for agent_profile in instance.agent_pool_profiles: agent_profile.orchestrator_version = kubernetes_version agent_profile.creation_data = None # null out the SP profile because otherwise validation complains instance.service_principal_profile = None headers = get_aks_custom_headers(aks_custom_headers) return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, name, instance, headers=headers) def _upgrade_single_nodepool_image_version(no_wait, client, resource_group_name, cluster_name, nodepool_name, snapshot_id=None): headers = {} if snapshot_id: headers["AKSSnapshotId"] = snapshot_id return sdk_no_wait(no_wait, client.begin_upgrade_node_image_version, resource_group_name, cluster_name, nodepool_name, headers=headers) def _handle_addons_args(cmd, # pylint: disable=too-many-statements addons_str, subscription_id, resource_group_name, addon_profiles=None, workspace_resource_id=None, enable_msi_auth_for_monitoring=False, appgw_name=None, appgw_subnet_prefix=None, appgw_subnet_cidr=None, appgw_id=None, appgw_subnet_id=None, appgw_watch_namespace=None, enable_sgxquotehelper=False, aci_subnet_name=None, vnet_subnet_id=None, enable_secret_rotation=False, rotation_poll_interval=None,): if not addon_profiles: addon_profiles = {} addons = addons_str.split(',') if addons_str else [] if 'http_application_routing' in addons: addon_profiles[CONST_HTTP_APPLICATION_ROUTING_ADDON_NAME] = ManagedClusterAddonProfile( enabled=True) addons.remove('http_application_routing') if 'kube-dashboard' in addons: addon_profiles[CONST_KUBE_DASHBOARD_ADDON_NAME] = ManagedClusterAddonProfile( enabled=True) addons.remove('kube-dashboard') # TODO: can we help the user find a workspace resource ID? if 'monitoring' in addons: if not workspace_resource_id: # use default workspace if exists else create default workspace workspace_resource_id = ensure_default_log_analytics_workspace_for_monitoring( cmd, subscription_id, resource_group_name) workspace_resource_id = sanitize_loganalytics_ws_resource_id( workspace_resource_id) addon_profiles[CONST_MONITORING_ADDON_NAME] = ManagedClusterAddonProfile(enabled=True, config={CONST_MONITORING_LOG_ANALYTICS_WORKSPACE_RESOURCE_ID: workspace_resource_id, CONST_MONITORING_USING_AAD_MSI_AUTH: enable_msi_auth_for_monitoring}) addons.remove('monitoring') elif workspace_resource_id: raise CLIError( '"--workspace-resource-id" requires "--enable-addons monitoring".') if 'azure-policy' in addons: addon_profiles[CONST_AZURE_POLICY_ADDON_NAME] = ManagedClusterAddonProfile( enabled=True) addons.remove('azure-policy') if 'gitops' in addons: addon_profiles['gitops'] = ManagedClusterAddonProfile(enabled=True) addons.remove('gitops') if 'ingress-appgw' in addons: addon_profile = ManagedClusterAddonProfile(enabled=True, config={}) if appgw_name is not None: addon_profile.config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_NAME] = appgw_name if appgw_subnet_prefix is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_CIDR] = appgw_subnet_prefix if appgw_subnet_cidr is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_CIDR] = appgw_subnet_cidr if appgw_id is not None: addon_profile.config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID] = appgw_id if appgw_subnet_id is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_ID] = appgw_subnet_id if appgw_watch_namespace is not None: addon_profile.config[CONST_INGRESS_APPGW_WATCH_NAMESPACE] = appgw_watch_namespace addon_profiles[CONST_INGRESS_APPGW_ADDON_NAME] = addon_profile addons.remove('ingress-appgw') if 'open-service-mesh' in addons: addon_profile = ManagedClusterAddonProfile(enabled=True, config={}) addon_profiles[CONST_OPEN_SERVICE_MESH_ADDON_NAME] = addon_profile addons.remove('open-service-mesh') if 'azure-keyvault-secrets-provider' in addons: addon_profile = ManagedClusterAddonProfile(enabled=True, config={ CONST_SECRET_ROTATION_ENABLED: "false", CONST_ROTATION_POLL_INTERVAL: "2m"}) if enable_secret_rotation: addon_profile.config[CONST_SECRET_ROTATION_ENABLED] = "true" if rotation_poll_interval is not None: addon_profile.config[CONST_ROTATION_POLL_INTERVAL] = rotation_poll_interval addon_profiles[CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME] = addon_profile addons.remove('azure-keyvault-secrets-provider') if 'confcom' in addons: addon_profile = ManagedClusterAddonProfile( enabled=True, config={CONST_ACC_SGX_QUOTE_HELPER_ENABLED: "false"}) if enable_sgxquotehelper: addon_profile.config[CONST_ACC_SGX_QUOTE_HELPER_ENABLED] = "true" addon_profiles[CONST_CONFCOM_ADDON_NAME] = addon_profile addons.remove('confcom') if 'virtual-node' in addons: if not aci_subnet_name or not vnet_subnet_id: raise CLIError( '"--enable-addons virtual-node" requires "--aci-subnet-name" and "--vnet-subnet-id".') # TODO: how about aciConnectorwindows, what is its addon name? os_type = 'Linux' addon_profiles[CONST_VIRTUAL_NODE_ADDON_NAME + os_type] = ManagedClusterAddonProfile( enabled=True, config={CONST_VIRTUAL_NODE_SUBNET_NAME: aci_subnet_name} ) addons.remove('virtual-node') # error out if any (unrecognized) addons remain if addons: raise CLIError('"{}" {} not recognized by the --enable-addons argument.'.format( ",".join(addons), "are" if len(addons) > 1 else "is")) return addon_profiles def _ensure_aks_service_principal(cli_ctx, service_principal=None, client_secret=None, subscription_id=None, dns_name_prefix=None, fqdn_subdomain=None, location=None, name=None): file_name_aks = 'aksServicePrincipal.json' # TODO: This really needs to be unit tested. rbac_client = get_graph_rbac_management_client(cli_ctx) if not service_principal: # --service-principal not specified, try to load it from local disk principal_obj = load_acs_service_principal( subscription_id, file_name=file_name_aks) if principal_obj: service_principal = principal_obj.get('service_principal') client_secret = principal_obj.get('client_secret') else: # Nothing to load, make one. if not client_secret: client_secret = _create_client_secret() salt = binascii.b2a_hex(os.urandom(3)).decode('utf-8') if dns_name_prefix: url = 'http://{}.{}.{}.cloudapp.azure.com'.format( salt, dns_name_prefix, location) else: url = 'http://{}.{}.{}.cloudapp.azure.com'.format( salt, fqdn_subdomain, location) service_principal = _build_service_principal( rbac_client, cli_ctx, name, url, client_secret) if not service_principal: raise CLIError('Could not create a service principal with the right permissions. ' 'Are you an Owner on this project?') logger.info('Created a service principal: %s', service_principal) # We don't need to add role assignment for this created SPN else: # --service-principal specfied, validate --client-secret was too if not client_secret: raise CLIError( '--client-secret is required if --service-principal is specified') store_acs_service_principal( subscription_id, client_secret, service_principal, file_name=file_name_aks) return load_acs_service_principal(subscription_id, file_name=file_name_aks) def _check_cluster_autoscaler_flag(enable_cluster_autoscaler, min_count, max_count, node_count, agent_pool_profile): if enable_cluster_autoscaler: if min_count is None or max_count is None: raise CLIError( 'Please specify both min-count and max-count when --enable-cluster-autoscaler enabled') if int(min_count) > int(max_count): raise CLIError( 'value of min-count should be less than or equal to value of max-count') if int(node_count) < int(min_count) or int(node_count) > int(max_count): raise CLIError( 'node-count is not in the range of min-count and max-count') agent_pool_profile.min_count = int(min_count) agent_pool_profile.max_count = int(max_count) agent_pool_profile.enable_auto_scaling = True else: if min_count is not None or max_count is not None: raise CLIError( 'min-count and max-count are required for --enable-cluster-autoscaler, please use the flag') def _create_client_secret(): # Add a special character to satsify AAD SP secret requirements special_char = '$' client_secret = binascii.b2a_hex( os.urandom(10)).decode('utf-8') + special_char return client_secret def _ensure_aks_acr(cli_ctx, client_id, acr_name_or_id, subscription_id, # pylint: disable=unused-argument detach=False): from msrestazure.tools import is_valid_resource_id, parse_resource_id # Check if the ACR exists by resource ID. if is_valid_resource_id(acr_name_or_id): try: parsed_registry = parse_resource_id(acr_name_or_id) acr_client = cf_container_registry_service( cli_ctx, subscription_id=parsed_registry['subscription']) registry = acr_client.registries.get( parsed_registry['resource_group'], parsed_registry['name']) except CloudError as ex: raise CLIError(ex.message) _ensure_aks_acr_role_assignment( cli_ctx, client_id, registry.id, detach) return # Check if the ACR exists by name accross all resource groups. registry_name = acr_name_or_id registry_resource = 'Microsoft.ContainerRegistry/registries' try: registry = get_resource_by_name( cli_ctx, registry_name, registry_resource) except CloudError as ex: if 'was not found' in ex.message: raise CLIError( "ACR {} not found. Have you provided the right ACR name?".format(registry_name)) raise CLIError(ex.message) _ensure_aks_acr_role_assignment(cli_ctx, client_id, registry.id, detach) return def _ensure_aks_acr_role_assignment(cli_ctx, client_id, registry_id, detach=False): if detach: if not _delete_role_assignments(cli_ctx, 'acrpull', client_id, scope=registry_id): raise CLIError('Could not delete role assignments for ACR. ' 'Are you an Owner on this subscription?') return if not add_role_assignment(cli_ctx, 'acrpull', client_id, scope=registry_id): raise CLIError('Could not create a role assignment for ACR. ' 'Are you an Owner on this subscription?') return def aks_agentpool_show(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name): instance = client.get(resource_group_name, cluster_name, nodepool_name) return instance def aks_agentpool_list(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name): return client.list(resource_group_name, cluster_name) def aks_agentpool_add(cmd, # pylint: disable=unused-argument,too-many-locals client, resource_group_name, cluster_name, nodepool_name, tags=None, kubernetes_version=None, node_zones=None, zones=None, enable_node_public_ip=False, node_public_ip_prefix_id=None, node_vm_size=None, node_osdisk_type=None, node_osdisk_size=0, node_count=3, vnet_subnet_id=None, pod_subnet_id=None, ppg=None, max_pods=0, os_type=None, os_sku=None, enable_fips_image=False, min_count=None, max_count=None, enable_cluster_autoscaler=False, scale_down_mode=CONST_SCALE_DOWN_MODE_DELETE, node_taints=None, priority=CONST_SCALE_SET_PRIORITY_REGULAR, eviction_policy=CONST_SPOT_EVICTION_POLICY_DELETE, spot_max_price=float('nan'), labels=None, max_surge=None, mode="User", aks_custom_headers=None, kubelet_config=None, linux_os_config=None, enable_encryption_at_host=False, enable_ultra_ssd=False, workload_runtime=None, gpu_instance_profile=None, snapshot_id=None, host_group_id=None, crg_id=None, message_of_the_day=None, no_wait=False): instances = client.list(resource_group_name, cluster_name) for agentpool_profile in instances: if agentpool_profile.name == nodepool_name: raise CLIError("Node pool {} already exists, please try a different name, " "use 'aks nodepool list' to get current list of node pool".format(nodepool_name)) upgradeSettings = AgentPoolUpgradeSettings() taints_array = [] creationData = None if snapshot_id: snapshot = _get_snapshot(cmd.cli_ctx, snapshot_id) if not kubernetes_version: kubernetes_version = snapshot.kubernetes_version if not os_type: os_type = snapshot.os_type if not os_sku: os_sku = snapshot.os_sku if not node_vm_size: node_vm_size = snapshot.vm_size creationData = CreationData( source_resource_id=snapshot_id ) if not os_type: os_type = "Linux" if node_taints is not None: for taint in node_taints.split(','): try: taint = taint.strip() taints_array.append(taint) except ValueError: raise CLIError( 'Taint does not match allowed values. Expect value such as "special=true:NoSchedule".') if node_vm_size is None: if os_type == "Windows": node_vm_size = "Standard_D2s_v3" else: node_vm_size = "Standard_DS2_v2" if max_surge: upgradeSettings.max_surge = max_surge agent_pool = AgentPool( name=nodepool_name, tags=tags, node_labels=labels, count=int(node_count), vm_size=node_vm_size, os_type=os_type, os_sku=os_sku, enable_fips=enable_fips_image, storage_profile=ContainerServiceStorageProfileTypes.managed_disks, vnet_subnet_id=vnet_subnet_id, pod_subnet_id=pod_subnet_id, proximity_placement_group_id=ppg, agent_pool_type="VirtualMachineScaleSets", max_pods=int(max_pods) if max_pods else None, orchestrator_version=kubernetes_version, availability_zones=node_zones, enable_node_public_ip=enable_node_public_ip, node_public_ip_prefix_id=node_public_ip_prefix_id, node_taints=taints_array, scale_set_priority=priority, scale_down_mode=scale_down_mode, upgrade_settings=upgradeSettings, enable_encryption_at_host=enable_encryption_at_host, enable_ultra_ssd=enable_ultra_ssd, mode=mode, workload_runtime=workload_runtime, gpu_instance_profile=gpu_instance_profile, creation_data=creationData, host_group_id=host_group_id, capacity_reservation_group_id=crg_id ) if priority == CONST_SCALE_SET_PRIORITY_SPOT: agent_pool.scale_set_eviction_policy = eviction_policy if isnan(spot_max_price): spot_max_price = -1 agent_pool.spot_max_price = spot_max_price _check_cluster_autoscaler_flag( enable_cluster_autoscaler, min_count, max_count, node_count, agent_pool) if node_osdisk_size: agent_pool.os_disk_size_gb = int(node_osdisk_size) if node_osdisk_type: agent_pool.os_disk_type = node_osdisk_type if kubelet_config: agent_pool.kubelet_config = _get_kubelet_config(kubelet_config) if linux_os_config: agent_pool.linux_os_config = _get_linux_os_config(linux_os_config) if message_of_the_day: agent_pool.message_of_the_day = _get_message_of_the_day( message_of_the_day) headers = get_aks_custom_headers(aks_custom_headers) return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, nodepool_name, agent_pool, headers=headers) def aks_agentpool_scale(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name, node_count=3, no_wait=False): instance = client.get(resource_group_name, cluster_name, nodepool_name) new_node_count = int(node_count) if instance.enable_auto_scaling: raise CLIError("Cannot scale cluster autoscaler enabled node pool.") if new_node_count == instance.count: raise CLIError( "The new node count is the same as the current node count.") instance.count = new_node_count # pylint: disable=no-member return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, nodepool_name, instance) def aks_agentpool_upgrade(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name, kubernetes_version='', no_wait=False, node_image_only=False, max_surge=None, aks_custom_headers=None, snapshot_id=None): if kubernetes_version != '' and node_image_only: raise CLIError('Conflicting flags. Upgrading the Kubernetes version will also upgrade node image version.' 'If you only want to upgrade the node version please use the "--node-image-only" option only.') if node_image_only: return _upgrade_single_nodepool_image_version(no_wait, client, resource_group_name, cluster_name, nodepool_name, snapshot_id) creationData = None if snapshot_id: snapshot = _get_snapshot(cmd.cli_ctx, snapshot_id) if not kubernetes_version and not node_image_only: kubernetes_version = snapshot.kubernetes_version creationData = CreationData( source_resource_id=snapshot_id ) instance = client.get(resource_group_name, cluster_name, nodepool_name) instance.orchestrator_version = kubernetes_version instance.creation_data = creationData if not instance.upgrade_settings: instance.upgrade_settings = AgentPoolUpgradeSettings() if max_surge: instance.upgrade_settings.max_surge = max_surge headers = get_aks_custom_headers(aks_custom_headers) return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, nodepool_name, instance, headers=headers) def aks_agentpool_get_upgrade_profile(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name): return client.get_upgrade_profile(resource_group_name, cluster_name, nodepool_name) def aks_agentpool_update(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name, tags=None, enable_cluster_autoscaler=False, disable_cluster_autoscaler=False, update_cluster_autoscaler=False, scale_down_mode=None, min_count=None, max_count=None, max_surge=None, mode=None, labels=None, node_taints=None, no_wait=False): update_autoscaler = enable_cluster_autoscaler + \ disable_cluster_autoscaler + update_cluster_autoscaler if (update_autoscaler != 1 and not tags and not scale_down_mode and not mode and not max_surge and labels is None and node_taints is None): reconcilePrompt = 'no argument specified to update would you like to reconcile to current settings?' if not prompt_y_n(reconcilePrompt, default="n"): raise CLIError('Please specify one or more of "--enable-cluster-autoscaler" or ' '"--disable-cluster-autoscaler" or ' '"--update-cluster-autoscaler" or ' '"--tags" or "--mode" or "--max-surge" or "--scale-down-mode" or "--labels" or "--node-taints') instance = client.get(resource_group_name, cluster_name, nodepool_name) if node_taints is not None: taints_array = [] if node_taints != '': for taint in node_taints.split(','): try: taint = taint.strip() taints_array.append(taint) except ValueError: raise InvalidArgumentValueError( 'Taint does not match allowed values. Expect value such as "special=true:NoSchedule".') instance.node_taints = taints_array if min_count is None or max_count is None: if enable_cluster_autoscaler or update_cluster_autoscaler: raise CLIError('Please specify both min-count and max-count when --enable-cluster-autoscaler or ' '--update-cluster-autoscaler set.') if min_count is not None and max_count is not None: if int(min_count) > int(max_count): raise CLIError( 'value of min-count should be less than or equal to value of max-count.') if enable_cluster_autoscaler: if instance.enable_auto_scaling: logger.warning('Autoscaler is already enabled for this node pool.\n' 'Please run "az aks nodepool update --update-cluster-autoscaler" ' 'if you want to update min-count or max-count.') return None instance.min_count = int(min_count) instance.max_count = int(max_count) instance.enable_auto_scaling = True if update_cluster_autoscaler: if not instance.enable_auto_scaling: raise CLIError('Autoscaler is not enabled for this node pool.\n' 'Run "az aks nodepool update --enable-cluster-autoscaler" ' 'to enable cluster with min-count and max-count.') instance.min_count = int(min_count) instance.max_count = int(max_count) if not instance.upgrade_settings: instance.upgrade_settings = AgentPoolUpgradeSettings() if max_surge: instance.upgrade_settings.max_surge = max_surge if disable_cluster_autoscaler: if not instance.enable_auto_scaling: logger.warning( 'Autoscaler is already disabled for this node pool.') return None instance.enable_auto_scaling = False instance.min_count = None instance.max_count = None instance.tags = tags if scale_down_mode is not None: instance.scale_down_mode = scale_down_mode if mode is not None: instance.mode = mode if labels is not None: instance.node_labels = labels return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, nodepool_name, instance) def aks_agentpool_stop(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name, aks_custom_headers=None, no_wait=False): agentpool_exists = False instances = client.list(resource_group_name, cluster_name) for agentpool_profile in instances: if agentpool_profile.name.lower() == nodepool_name.lower(): agentpool_exists = True break if not agentpool_exists: raise InvalidArgumentValueError( "Node pool {} doesnt exist, use 'aks nodepool list' to get current node pool list".format(nodepool_name)) instance = client.get(resource_group_name, cluster_name, nodepool_name) power_state = PowerState(code="Stopped") instance.power_state = power_state headers = get_aks_custom_headers(aks_custom_headers) return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, nodepool_name, instance, headers=headers) def aks_agentpool_start(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name, aks_custom_headers=None, no_wait=False): agentpool_exists = False instances = client.list(resource_group_name, cluster_name) for agentpool_profile in instances: if agentpool_profile.name.lower() == nodepool_name.lower(): agentpool_exists = True break if not agentpool_exists: raise InvalidArgumentValueError( "Node pool {} doesnt exist, use 'aks nodepool list' to get current node pool list".format(nodepool_name)) instance = client.get(resource_group_name, cluster_name, nodepool_name) power_state = PowerState(code="Running") instance.power_state = power_state headers = get_aks_custom_headers(aks_custom_headers) return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, nodepool_name, instance, headers=headers) def aks_agentpool_delete(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name, ignore_pod_disruption_budget=None, no_wait=False): agentpool_exists = False instances = client.list(resource_group_name, cluster_name) for agentpool_profile in instances: if agentpool_profile.name.lower() == nodepool_name.lower(): agentpool_exists = True break if not agentpool_exists: raise CLIError("Node pool {} doesnt exist, " "use 'aks nodepool list' to get current node pool list".format(nodepool_name)) return sdk_no_wait(no_wait, client.begin_delete, resource_group_name, cluster_name, nodepool_name, ignore_pod_disruption_budget=ignore_pod_disruption_budget) def aks_addon_list_available(): available_addons = [] for k, v in ADDONS.items(): available_addons.append({ "name": k, "description": ADDONS_DESCRIPTIONS[v] }) return available_addons def aks_addon_list(cmd, client, resource_group_name, name): # pylint: disable=unused-argument addon_profiles = client.get(resource_group_name, name).addon_profiles current_addons = [] for name, addon in ADDONS.items(): if not addon_profiles or addon not in addon_profiles: current_addons.append({ "name": name, "api_key": addon, "enabled": False }) else: current_addons.append({ "name": name, "api_key": addon, "enabled": addon_profiles[addon].enabled }) return current_addons def aks_addon_show(cmd, client, resource_group_name, name, addon): # pylint: disable=unused-argument addon_profiles = client.get(resource_group_name, name).addon_profiles addon_key = ADDONS[addon] if not addon_profiles or addon_key not in addon_profiles or not addon_profiles[addon_key].enabled: raise CLIError(f'Addon "{addon}" is not enabled in this cluster.') return { "name": addon, "api_key": addon_key, "config": addon_profiles[addon_key].config, "identity": addon_profiles[addon_key].identity } def aks_addon_enable(cmd, client, resource_group_name, name, addon, workspace_resource_id=None, subnet_name=None, appgw_name=None, appgw_subnet_prefix=None, appgw_subnet_cidr=None, appgw_id=None, appgw_subnet_id=None, appgw_watch_namespace=None, enable_sgxquotehelper=False, enable_secret_rotation=False, rotation_poll_interval=None, no_wait=False, enable_msi_auth_for_monitoring=False): return enable_addons(cmd, client, resource_group_name, name, addon, workspace_resource_id=workspace_resource_id, subnet_name=subnet_name, appgw_name=appgw_name, appgw_subnet_prefix=appgw_subnet_prefix, appgw_subnet_cidr=appgw_subnet_cidr, appgw_id=appgw_id, appgw_subnet_id=appgw_subnet_id, appgw_watch_namespace=appgw_watch_namespace, enable_sgxquotehelper=enable_sgxquotehelper, enable_secret_rotation=enable_secret_rotation, rotation_poll_interval=rotation_poll_interval, no_wait=no_wait, enable_msi_auth_for_monitoring=enable_msi_auth_for_monitoring) def aks_addon_disable(cmd, client, resource_group_name, name, addon, no_wait=False): return aks_disable_addons(cmd, client, resource_group_name, name, addon, no_wait) def aks_addon_update(cmd, client, resource_group_name, name, addon, workspace_resource_id=None, subnet_name=None, appgw_name=None, appgw_subnet_prefix=None, appgw_subnet_cidr=None, appgw_id=None, appgw_subnet_id=None, appgw_watch_namespace=None, enable_sgxquotehelper=False, enable_secret_rotation=False, rotation_poll_interval=None, no_wait=False, enable_msi_auth_for_monitoring=False): addon_profiles = client.get(resource_group_name, name).addon_profiles addon_key = ADDONS[addon] if not addon_profiles or addon_key not in addon_profiles or not addon_profiles[addon_key].enabled: raise CLIError(f'Addon "{addon}" is not enabled in this cluster.') return enable_addons(cmd, client, resource_group_name, name, addon, check_enabled=False, workspace_resource_id=workspace_resource_id, subnet_name=subnet_name, appgw_name=appgw_name, appgw_subnet_prefix=appgw_subnet_prefix, appgw_subnet_cidr=appgw_subnet_cidr, appgw_id=appgw_id, appgw_subnet_id=appgw_subnet_id, appgw_watch_namespace=appgw_watch_namespace, enable_sgxquotehelper=enable_sgxquotehelper, enable_secret_rotation=enable_secret_rotation, rotation_poll_interval=rotation_poll_interval, no_wait=no_wait, enable_msi_auth_for_monitoring=enable_msi_auth_for_monitoring) def aks_disable_addons(cmd, client, resource_group_name, name, addons, no_wait=False): instance = client.get(resource_group_name, name) subscription_id = get_subscription_id(cmd.cli_ctx) try: if addons == "monitoring" and CONST_MONITORING_ADDON_NAME in instance.addon_profiles and \ instance.addon_profiles[CONST_MONITORING_ADDON_NAME].enabled and \ CONST_MONITORING_USING_AAD_MSI_AUTH in instance.addon_profiles[CONST_MONITORING_ADDON_NAME].config and \ str(instance.addon_profiles[CONST_MONITORING_ADDON_NAME].config[CONST_MONITORING_USING_AAD_MSI_AUTH]).lower() == 'true': # remove the DCR association because otherwise the DCR can't be deleted ensure_container_insights_for_monitoring( cmd, instance.addon_profiles[CONST_MONITORING_ADDON_NAME], subscription_id, resource_group_name, name, instance.location, remove_monitoring=True, aad_route=True, create_dcr=False, create_dcra=True ) except TypeError: pass instance = _update_addons( cmd, instance, subscription_id, resource_group_name, name, addons, enable=False, no_wait=no_wait ) # send the managed cluster representation to update the addon profiles return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, name, instance) def aks_enable_addons(cmd, client, resource_group_name, name, addons, workspace_resource_id=None, subnet_name=None, appgw_name=None, appgw_subnet_prefix=None, appgw_subnet_cidr=None, appgw_id=None, appgw_subnet_id=None, appgw_watch_namespace=None, enable_sgxquotehelper=False, enable_secret_rotation=False, rotation_poll_interval=None, no_wait=False, enable_msi_auth_for_monitoring=False): instance = client.get(resource_group_name, name) # this is overwritten by _update_addons(), so the value needs to be recorded here msi_auth = True if instance.service_principal_profile.client_id == "msi" else False subscription_id = get_subscription_id(cmd.cli_ctx) instance = _update_addons(cmd, instance, subscription_id, resource_group_name, name, addons, enable=True, workspace_resource_id=workspace_resource_id, enable_msi_auth_for_monitoring=enable_msi_auth_for_monitoring, subnet_name=subnet_name, appgw_name=appgw_name, appgw_subnet_prefix=appgw_subnet_prefix, appgw_subnet_cidr=appgw_subnet_cidr, appgw_id=appgw_id, appgw_subnet_id=appgw_subnet_id, appgw_watch_namespace=appgw_watch_namespace, enable_sgxquotehelper=enable_sgxquotehelper, enable_secret_rotation=enable_secret_rotation, rotation_poll_interval=rotation_poll_interval, no_wait=no_wait) if CONST_MONITORING_ADDON_NAME in instance.addon_profiles and instance.addon_profiles[CONST_MONITORING_ADDON_NAME].enabled: if CONST_MONITORING_USING_AAD_MSI_AUTH in instance.addon_profiles[CONST_MONITORING_ADDON_NAME].config and \ str(instance.addon_profiles[CONST_MONITORING_ADDON_NAME].config[CONST_MONITORING_USING_AAD_MSI_AUTH]).lower() == 'true': if not msi_auth: raise ArgumentUsageError( "--enable-msi-auth-for-monitoring can not be used on clusters with service principal auth.") else: # create a Data Collection Rule (DCR) and associate it with the cluster ensure_container_insights_for_monitoring( cmd, instance.addon_profiles[CONST_MONITORING_ADDON_NAME], subscription_id, resource_group_name, name, instance.location, aad_route=True, create_dcr=True, create_dcra=True) else: # monitoring addon will use legacy path ensure_container_insights_for_monitoring( cmd, instance.addon_profiles[CONST_MONITORING_ADDON_NAME], subscription_id, resource_group_name, name, instance.location, aad_route=False) monitoring = CONST_MONITORING_ADDON_NAME in instance.addon_profiles and instance.addon_profiles[ CONST_MONITORING_ADDON_NAME].enabled ingress_appgw_addon_enabled = CONST_INGRESS_APPGW_ADDON_NAME in instance.addon_profiles and instance.addon_profiles[ CONST_INGRESS_APPGW_ADDON_NAME].enabled os_type = 'Linux' enable_virtual_node = False if CONST_VIRTUAL_NODE_ADDON_NAME + os_type in instance.addon_profiles: enable_virtual_node = True need_post_creation_role_assignment = monitoring or ingress_appgw_addon_enabled or enable_virtual_node if need_post_creation_role_assignment: # adding a wait here since we rely on the result for role assignment result = LongRunningOperation(cmd.cli_ctx)( client.begin_create_or_update(resource_group_name, name, instance)) cloud_name = cmd.cli_ctx.cloud.name # mdm metrics supported only in Azure Public cloud so add the role assignment only in this cloud if monitoring and cloud_name.lower() == 'azurecloud': from msrestazure.tools import resource_id cluster_resource_id = resource_id( subscription=subscription_id, resource_group=resource_group_name, namespace='Microsoft.ContainerService', type='managedClusters', name=name ) add_monitoring_role_assignment(result, cluster_resource_id, cmd) if ingress_appgw_addon_enabled: add_ingress_appgw_addon_role_assignment(result, cmd) if enable_virtual_node: # All agent pool will reside in the same vnet, we will grant vnet level Contributor role # in later function, so using a random agent pool here is OK random_agent_pool = result.agent_pool_profiles[0] if random_agent_pool.vnet_subnet_id != "": add_virtual_node_role_assignment( cmd, result, random_agent_pool.vnet_subnet_id) # Else, the cluster is not using custom VNet, the permission is already granted in AKS RP, # we don't need to handle it in client side in this case. else: result = sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, name, instance) return result def aks_rotate_certs(cmd, client, resource_group_name, name, no_wait=True): # pylint: disable=unused-argument return sdk_no_wait(no_wait, client.begin_rotate_cluster_certificates, resource_group_name, name) def _update_addons(cmd, # pylint: disable=too-many-branches,too-many-statements instance, subscription_id, resource_group_name, name, addons, enable, workspace_resource_id=None, enable_msi_auth_for_monitoring=False, subnet_name=None, appgw_name=None, appgw_subnet_prefix=None, appgw_subnet_cidr=None, appgw_id=None, appgw_subnet_id=None, appgw_watch_namespace=None, enable_sgxquotehelper=False, enable_secret_rotation=False, disable_secret_rotation=False, rotation_poll_interval=None, no_wait=False): # pylint: disable=unused-argument # parse the comma-separated addons argument addon_args = addons.split(',') addon_profiles = instance.addon_profiles or {} os_type = 'Linux' # for each addons argument for addon_arg in addon_args: if addon_arg not in ADDONS: raise CLIError("Invalid addon name: {}.".format(addon_arg)) addon = ADDONS[addon_arg] if addon == CONST_VIRTUAL_NODE_ADDON_NAME: # only linux is supported for now, in the future this will be a user flag addon += os_type # honor addon names defined in Azure CLI for key in list(addon_profiles): if key.lower() == addon.lower() and key != addon: addon_profiles[addon] = addon_profiles.pop(key) if enable: # add new addons or update existing ones and enable them addon_profile = addon_profiles.get( addon, ManagedClusterAddonProfile(enabled=False)) # special config handling for certain addons if addon == CONST_MONITORING_ADDON_NAME: logAnalyticsConstName = CONST_MONITORING_LOG_ANALYTICS_WORKSPACE_RESOURCE_ID if addon_profile.enabled: raise CLIError('The monitoring addon is already enabled for this managed cluster.\n' 'To change monitoring configuration, run "az aks disable-addons -a monitoring"' 'before enabling it again.') if not workspace_resource_id: workspace_resource_id = ensure_default_log_analytics_workspace_for_monitoring( cmd, subscription_id, resource_group_name) workspace_resource_id = sanitize_loganalytics_ws_resource_id( workspace_resource_id) addon_profile.config = { logAnalyticsConstName: workspace_resource_id} addon_profile.config[CONST_MONITORING_USING_AAD_MSI_AUTH] = enable_msi_auth_for_monitoring elif addon == (CONST_VIRTUAL_NODE_ADDON_NAME + os_type): if addon_profile.enabled: raise CLIError('The virtual-node addon is already enabled for this managed cluster.\n' 'To change virtual-node configuration, run ' '"az aks disable-addons -a virtual-node -g {resource_group_name}" ' 'before enabling it again.') if not subnet_name: raise CLIError( 'The aci-connector addon requires setting a subnet name.') addon_profile.config = { CONST_VIRTUAL_NODE_SUBNET_NAME: subnet_name} elif addon == CONST_INGRESS_APPGW_ADDON_NAME: if addon_profile.enabled: raise CLIError('The ingress-appgw addon is already enabled for this managed cluster.\n' 'To change ingress-appgw configuration, run ' f'"az aks disable-addons -a ingress-appgw -n {name} -g {resource_group_name}" ' 'before enabling it again.') addon_profile = ManagedClusterAddonProfile( enabled=True, config={}) if appgw_name is not None: addon_profile.config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_NAME] = appgw_name if appgw_subnet_prefix is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_CIDR] = appgw_subnet_prefix if appgw_subnet_cidr is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_CIDR] = appgw_subnet_cidr if appgw_id is not None: addon_profile.config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID] = appgw_id if appgw_subnet_id is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_ID] = appgw_subnet_id if appgw_watch_namespace is not None: addon_profile.config[CONST_INGRESS_APPGW_WATCH_NAMESPACE] = appgw_watch_namespace elif addon == CONST_OPEN_SERVICE_MESH_ADDON_NAME: if addon_profile.enabled: raise CLIError('The open-service-mesh addon is already enabled for this managed cluster.\n' 'To change open-service-mesh configuration, run ' f'"az aks disable-addons -a open-service-mesh -n {name} -g {resource_group_name}" ' 'before enabling it again.') addon_profile = ManagedClusterAddonProfile( enabled=True, config={}) elif addon == CONST_CONFCOM_ADDON_NAME: if addon_profile.enabled: raise CLIError('The confcom addon is already enabled for this managed cluster.\n' 'To change confcom configuration, run ' f'"az aks disable-addons -a confcom -n {name} -g {resource_group_name}" ' 'before enabling it again.') addon_profile = ManagedClusterAddonProfile( enabled=True, config={CONST_ACC_SGX_QUOTE_HELPER_ENABLED: "false"}) if enable_sgxquotehelper: addon_profile.config[CONST_ACC_SGX_QUOTE_HELPER_ENABLED] = "true" elif addon == CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME: if addon_profile.enabled: raise CLIError('The azure-keyvault-secrets-provider addon is already enabled for this managed cluster.\n' 'To change azure-keyvault-secrets-provider configuration, run ' f'"az aks disable-addons -a azure-keyvault-secrets-provider -n {name} -g {resource_group_name}" ' 'before enabling it again.') addon_profile = ManagedClusterAddonProfile( enabled=True, config={CONST_SECRET_ROTATION_ENABLED: "false", CONST_ROTATION_POLL_INTERVAL: "2m"}) if enable_secret_rotation: addon_profile.config[CONST_SECRET_ROTATION_ENABLED] = "true" if disable_secret_rotation: addon_profile.config[CONST_SECRET_ROTATION_ENABLED] = "false" if rotation_poll_interval is not None: addon_profile.config[CONST_ROTATION_POLL_INTERVAL] = rotation_poll_interval addon_profiles[CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME] = addon_profile addon_profiles[addon] = addon_profile else: if addon not in addon_profiles: if addon == CONST_KUBE_DASHBOARD_ADDON_NAME: addon_profiles[addon] = ManagedClusterAddonProfile( enabled=False) else: raise CLIError( "The addon {} is not installed.".format(addon)) addon_profiles[addon].config = None addon_profiles[addon].enabled = enable instance.addon_profiles = addon_profiles # null out the SP profile because otherwise validation complains instance.service_principal_profile = None return instance def aks_get_versions(cmd, client, location): # pylint: disable=unused-argument return client.list_orchestrators(location, resource_type='managedClusters') def aks_get_os_options(cmd, client, location): # pylint: disable=unused-argument return client.get_os_options(location, resource_type='managedClusters') def _print_or_merge_credentials(path, kubeconfig, overwrite_existing, context_name): """Merge an unencrypted kubeconfig into the file at the specified path, or print it to stdout if the path is "-". """ # Special case for printing to stdout if path == "-": print(kubeconfig) return # ensure that at least an empty ~/.kube/config exists directory = os.path.dirname(path) if directory and not os.path.exists(directory): try: os.makedirs(directory) except OSError as ex: if ex.errno != errno.EEXIST: raise if not os.path.exists(path): with os.fdopen(os.open(path, os.O_CREAT | os.O_WRONLY, 0o600), 'wt'): pass # merge the new kubeconfig into the existing one fd, temp_path = tempfile.mkstemp() additional_file = os.fdopen(fd, 'w+t') try: additional_file.write(kubeconfig) additional_file.flush() merge_kubernetes_configurations( path, temp_path, overwrite_existing, context_name) except yaml.YAMLError as ex: logger.warning( 'Failed to merge credentials to kube config file: %s', ex) finally: additional_file.close() os.remove(temp_path) def _handle_merge(existing, addition, key, replace): if not addition[key]: return if existing[key] is None: existing[key] = addition[key] return for i in addition[key]: for j in existing[key]: if i['name'] == j['name']: if replace or i == j: existing[key].remove(j) else: from knack.prompting import prompt_y_n msg = 'A different object named {} already exists in your kubeconfig file.\nOverwrite?' overwrite = False try: overwrite = prompt_y_n(msg.format(i['name'])) except NoTTYException: pass if overwrite: existing[key].remove(j) else: msg = 'A different object named {} already exists in {} in your kubeconfig file.' raise CLIError(msg.format(i['name'], key)) existing[key].append(i) def load_kubernetes_configuration(filename): try: with open(filename) as stream: return yaml.safe_load(stream) except (IOError, OSError) as ex: if getattr(ex, 'errno', 0) == errno.ENOENT: raise CLIError('{} does not exist'.format(filename)) except (yaml.parser.ParserError, UnicodeDecodeError) as ex: raise CLIError('Error parsing {} ({})'.format(filename, str(ex))) def merge_kubernetes_configurations(existing_file, addition_file, replace, context_name=None): existing = load_kubernetes_configuration(existing_file) addition = load_kubernetes_configuration(addition_file) if context_name is not None: addition['contexts'][0]['name'] = context_name addition['contexts'][0]['context']['cluster'] = context_name addition['clusters'][0]['name'] = context_name addition['current-context'] = context_name # rename the admin context so it doesn't overwrite the user context for ctx in addition.get('contexts', []): try: if ctx['context']['user'].startswith('clusterAdmin'): admin_name = ctx['name'] + '-admin' addition['current-context'] = ctx['name'] = admin_name break except (KeyError, TypeError): continue if addition is None: raise CLIError( 'failed to load additional configuration from {}'.format(addition_file)) if existing is None: existing = addition else: _handle_merge(existing, addition, 'clusters', replace) _handle_merge(existing, addition, 'users', replace) _handle_merge(existing, addition, 'contexts', replace) existing['current-context'] = addition['current-context'] # check that ~/.kube/config is only read- and writable by its owner if platform.system() != 'Windows': existing_file_perms = "{:o}".format( stat.S_IMODE(os.lstat(existing_file).st_mode)) if not existing_file_perms.endswith('600'): logger.warning('%s has permissions "%s".\nIt should be readable and writable only by its owner.', existing_file, existing_file_perms) with open(existing_file, 'w+') as stream: yaml.safe_dump(existing, stream, default_flow_style=False) current_context = addition.get('current-context', 'UNKNOWN') msg = 'Merged "{}" as current context in {}'.format( current_context, existing_file) print(msg) def cloud_storage_account_service_factory(cli_ctx, kwargs): from azure.cli.core.profiles import ResourceType, get_sdk t_cloud_storage_account = get_sdk( cli_ctx, ResourceType.DATA_STORAGE, 'common#CloudStorageAccount') account_name = kwargs.pop('account_name', None) account_key = kwargs.pop('account_key', None) sas_token = kwargs.pop('sas_token', None) kwargs.pop('connection_string', None) return t_cloud_storage_account(account_name, account_key, sas_token) def get_storage_account_from_diag_settings(cli_ctx, resource_group_name, name): from azure.mgmt.monitor import MonitorManagementClient diag_settings_client = get_mgmt_service_client( cli_ctx, MonitorManagementClient).diagnostic_settings subscription_id = get_subscription_id(cli_ctx) aks_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.ContainerService' \ '/managedClusters/{2}'.format(subscription_id, resource_group_name, name) diag_settings = diag_settings_client.list(aks_resource_id) for _, diag_setting in enumerate(diag_settings): if diag_setting: return diag_setting.storage_account_id print("No diag settings specified") return None def display_diagnostics_report(temp_kubeconfig_path): # pylint: disable=too-many-statements if not which('kubectl'): raise CLIError('Can not find kubectl executable in PATH') nodes = subprocess.check_output( ["kubectl", "--kubeconfig", temp_kubeconfig_path, "get", "node", "--no-headers"], universal_newlines=True) logger.debug(nodes) node_lines = nodes.splitlines() ready_nodes = {} for node_line in node_lines: columns = node_line.split() logger.debug(node_line) if columns[1] != "Ready": logger.warning( "Node %s is not Ready. Current state is: %s.", columns[0], columns[1]) else: ready_nodes[columns[0]] = False logger.debug('There are %s ready nodes in the cluster', str(len(ready_nodes))) if not ready_nodes: logger.warning( 'No nodes are ready in the current cluster. Diagnostics info might not be available.') network_config_array = [] network_status_array = [] apds_created = False max_retry = 10 for retry in range(0, max_retry): if not apds_created: apd = subprocess.check_output( ["kubectl", "--kubeconfig", temp_kubeconfig_path, "get", "apd", "-n", "aks-periscope", "--no-headers"], universal_newlines=True ) apd_lines = apd.splitlines() if apd_lines and 'No resources found' in apd_lines[0]: apd_lines.pop(0) print("Got {} diagnostic results for {} ready nodes{}\r".format(len(apd_lines), len(ready_nodes), '.' * retry), end='') if len(apd_lines) < len(ready_nodes): time.sleep(3) else: apds_created = True print() else: for node_name in ready_nodes: if ready_nodes[node_name]: continue apdName = "aks-periscope-diagnostic-" + node_name try: network_config = subprocess.check_output( ["kubectl", "--kubeconfig", temp_kubeconfig_path, "get", "apd", apdName, "-n", "aks-periscope", "-o=jsonpath={.spec.networkconfig}"], universal_newlines=True) logger.debug('Dns status for node %s is %s', node_name, network_config) network_status = subprocess.check_output( ["kubectl", "--kubeconfig", temp_kubeconfig_path, "get", "apd", apdName, "-n", "aks-periscope", "-o=jsonpath={.spec.networkoutbound}"], universal_newlines=True) logger.debug('Network status for node %s is %s', node_name, network_status) if not network_config or not network_status: print("The diagnostics information for node {} is not ready yet. " "Will try again in 10 seconds.".format(node_name)) time.sleep(10) break network_config_array += json.loads( '[' + network_config + ']') network_status_object = json.loads(network_status) network_status_array += format_diag_status( network_status_object) ready_nodes[node_name] = True except subprocess.CalledProcessError as err: raise CLIError(err.output) print() if network_config_array: print("Below are the network configuration for each node: ") print() print(tabulate(network_config_array, headers="keys", tablefmt='simple')) print() else: logger.warning("Could not get network config. " "Please run 'az aks kanalyze' command later to get the analysis results.") if network_status_array: print("Below are the network connectivity results for each node:") print() print(tabulate(network_status_array, headers="keys", tablefmt='simple')) else: logger.warning("Could not get networking status. " "Please run 'az aks kanalyze' command later to get the analysis results.") def format_diag_status(diag_status): for diag in diag_status: if diag["Status"]: if "Error:" in diag["Status"]: diag["Status"] = f'{colorama.Fore.RED}{diag['Status']}{colorama.Style.RESET_ALL}' else: diag["Status"] = f'{colorama.Fore.GREEN}{diag['Status']}{colorama.Style.RESET_ALL}' return diag_status def format_bright(msg): return f'\033[1m{colorama.Style.BRIGHT}{msg}{colorama.Style.RESET_ALL}' def format_hyperlink(the_link): return f'\033[1m{colorama.Style.BRIGHT}{colorama.Fore.BLUE}{the_link}{colorama.Style.RESET_ALL}' def get_aks_custom_headers(aks_custom_headers=None): headers = {} if aks_custom_headers is not None: if aks_custom_headers != "": for pair in aks_custom_headers.split(','): parts = pair.split('=') if len(parts) != 2: raise CLIError('custom headers format is incorrect') headers[parts[0]] = parts[1] return headers def _put_managed_cluster_ensuring_permission( cmd, # pylint: disable=too-many-locals,too-many-statements,too-many-branches client, subscription_id, resource_group_name, name, managed_cluster, monitoring_addon_enabled, ingress_appgw_addon_enabled, virtual_node_addon_enabled, need_grant_vnet_permission_to_cluster_identity, vnet_subnet_id, enable_managed_identity, attach_acr, headers, no_wait ): # some addons require post cluster creation role assigment need_post_creation_role_assignment = (monitoring_addon_enabled or ingress_appgw_addon_enabled or (enable_managed_identity and attach_acr) or virtual_node_addon_enabled or need_grant_vnet_permission_to_cluster_identity) if need_post_creation_role_assignment: # adding a wait here since we rely on the result for role assignment cluster = LongRunningOperation(cmd.cli_ctx)(client.begin_create_or_update( resource_group_name=resource_group_name, resource_name=name, parameters=managed_cluster, headers=headers)) cloud_name = cmd.cli_ctx.cloud.name # add cluster spn/msi Monitoring Metrics Publisher role assignment to publish metrics to MDM # mdm metrics is supported only in azure public cloud, so add the role assignment only in this cloud if monitoring_addon_enabled and cloud_name.lower() == 'azurecloud': from msrestazure.tools import resource_id cluster_resource_id = resource_id( subscription=subscription_id, resource_group=resource_group_name, namespace='Microsoft.ContainerService', type='managedClusters', name=name ) add_monitoring_role_assignment(cluster, cluster_resource_id, cmd) if ingress_appgw_addon_enabled: add_ingress_appgw_addon_role_assignment(cluster, cmd) if virtual_node_addon_enabled: add_virtual_node_role_assignment(cmd, cluster, vnet_subnet_id) if need_grant_vnet_permission_to_cluster_identity: if not create_role_assignment(cmd.cli_ctx, 'Network Contributor', cluster.identity.principal_id, scope=vnet_subnet_id, resolve_assignee=False): logger.warning('Could not create a role assignment for subnet. ' 'Are you an Owner on this subscription?') if enable_managed_identity and attach_acr: # Attach ACR to cluster enabled managed identity if cluster.identity_profile is None or \ cluster.identity_profile["kubeletidentity"] is None: logger.warning('Your cluster is successfully created, but we failed to attach ' 'acr to it, you can manually grant permission to the identity ' 'named <ClUSTER_NAME>-agentpool in MC_ resource group to give ' 'it permission to pull from ACR.') else: kubelet_identity_client_id = cluster.identity_profile["kubeletidentity"].client_id _ensure_aks_acr(cmd.cli_ctx, client_id=kubelet_identity_client_id, acr_name_or_id=attach_acr, subscription_id=subscription_id) else: cluster = sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name=resource_group_name, resource_name=name, parameters=managed_cluster, headers=headers) return cluster def _is_msi_cluster(managed_cluster): return (managed_cluster and managed_cluster.identity and (managed_cluster.identity.type.casefold() == "systemassigned" or managed_cluster.identity.type.casefold() == "userassigned")) def _get_message_of_the_day(file_path): if not os.path.isfile(file_path): raise CLIError( "{} is not valid file, or not accessable.".format(file_path)) content = read_file_content(file_path) if not content: raise ArgumentUsageError( "message of the day should point to a non-empty file if specified.") content = base64.b64encode(bytes(content, 'ascii')).decode('ascii') return content def _get_kubelet_config(file_path): if not os.path.isfile(file_path): raise CLIError( "{} is not valid file, or not accessable.".format(file_path)) kubelet_config = get_file_json(file_path) if not isinstance(kubelet_config, dict): raise CLIError( "Error reading kubelet configuration at {}. Please see https://aka.ms/CustomNodeConfig for correct format.".format(file_path)) config_object = KubeletConfig() config_object.cpu_manager_policy = kubelet_config.get( "cpuManagerPolicy", None) config_object.cpu_cfs_quota = kubelet_config.get("cpuCfsQuota", None) config_object.cpu_cfs_quota_period = kubelet_config.get( "cpuCfsQuotaPeriod", None) config_object.image_gc_high_threshold = kubelet_config.get( "imageGcHighThreshold", None) config_object.image_gc_low_threshold = kubelet_config.get( "imageGcLowThreshold", None) config_object.topology_manager_policy = kubelet_config.get( "topologyManagerPolicy", None) config_object.allowed_unsafe_sysctls = kubelet_config.get( "allowedUnsafeSysctls", None) config_object.fail_swap_on = kubelet_config.get("failSwapOn", None) config_object.container_log_max_files = kubelet_config.get( "containerLogMaxFiles", None) config_object.container_log_max_size_mb = kubelet_config.get( "containerLogMaxSizeMB", None) config_object.pod_max_pids = kubelet_config.get( "podMaxPids", None) return config_object def _get_linux_os_config(file_path): if not os.path.isfile(file_path): raise CLIError( "{} is not valid file, or not accessable.".format(file_path)) os_config = get_file_json(file_path) if not isinstance(os_config, dict): raise CLIError( "Error reading Linux OS configuration at {}. Please see https://aka.ms/CustomNodeConfig for correct format.".format(file_path)) config_object = LinuxOSConfig() config_object.transparent_huge_page_enabled = os_config.get( "transparentHugePageEnabled", None) config_object.transparent_huge_page_defrag = os_config.get( "transparentHugePageDefrag", None) config_object.swap_file_size_mb = os_config.get("swapFileSizeMB", None) # sysctl settings sysctls = os_config.get("sysctls", None) if not isinstance(sysctls, dict): raise CLIError( "Error reading Sysctl settings at {}. Please see https://aka.ms/CustomNodeConfig for correct format.".format(file_path)) config_object.sysctls = SysctlConfig() config_object.sysctls.net_core_somaxconn = sysctls.get( "netCoreSomaxconn", None) config_object.sysctls.net_core_netdev_max_backlog = sysctls.get( "netCoreNetdevMaxBacklog", None) config_object.sysctls.net_core_rmem_max = sysctls.get( "netCoreRmemMax", None) config_object.sysctls.net_core_wmem_max = sysctls.get( "netCoreWmemMax", None) config_object.sysctls.net_core_optmem_max = sysctls.get( "netCoreOptmemMax", None) config_object.sysctls.net_ipv4_tcp_max_syn_backlog = sysctls.get( "netIpv4TcpMaxSynBacklog", None) config_object.sysctls.net_ipv4_tcp_max_tw_buckets = sysctls.get( "netIpv4TcpMaxTwBuckets", None) config_object.sysctls.net_ipv4_tcp_fin_timeout = sysctls.get( "netIpv4TcpFinTimeout", None) config_object.sysctls.net_ipv4_tcp_keepalive_time = sysctls.get( "netIpv4TcpKeepaliveTime", None) config_object.sysctls.net_ipv4_tcp_keepalive_probes = sysctls.get( "netIpv4TcpKeepaliveProbes", None) config_object.sysctls.net_ipv4_tcpkeepalive_intvl = sysctls.get( "netIpv4TcpkeepaliveIntvl", None) config_object.sysctls.net_ipv4_tcp_rmem = sysctls.get( "netIpv4TcpRmem", None) config_object.sysctls.net_ipv4_tcp_wmem = sysctls.get( "netIpv4TcpWmem", None) config_object.sysctls.net_ipv4_tcp_tw_reuse = sysctls.get( "netIpv4TcpTwReuse", None) config_object.sysctls.net_ipv4_ip_local_port_range = sysctls.get( "netIpv4IpLocalPortRange", None) config_object.sysctls.net_ipv4_neigh_default_gc_thresh1 = sysctls.get( "netIpv4NeighDefaultGcThresh1", None) config_object.sysctls.net_ipv4_neigh_default_gc_thresh2 = sysctls.get( "netIpv4NeighDefaultGcThresh2", None) config_object.sysctls.net_ipv4_neigh_default_gc_thresh3 = sysctls.get( "netIpv4NeighDefaultGcThresh3", None) config_object.sysctls.net_netfilter_nf_conntrack_max = sysctls.get( "netNetfilterNfConntrackMax", None) config_object.sysctls.net_netfilter_nf_conntrack_buckets = sysctls.get( "netNetfilterNfConntrackBuckets", None) config_object.sysctls.fs_inotify_max_user_watches = sysctls.get( "fsInotifyMaxUserWatches", None) config_object.sysctls.fs_file_max = sysctls.get("fsFileMax", None) config_object.sysctls.fs_aio_max_nr = sysctls.get("fsAioMaxNr", None) config_object.sysctls.fs_nr_open = sysctls.get("fsNrOpen", None) config_object.sysctls.kernel_threads_max = sysctls.get( "kernelThreadsMax", None) config_object.sysctls.vm_max_map_count = sysctls.get("vmMaxMapCount", None) config_object.sysctls.vm_swappiness = sysctls.get("vmSwappiness", None) config_object.sysctls.vm_vfs_cache_pressure = sysctls.get( "vmVfsCachePressure", None) return config_object def _get_http_proxy_config(file_path): if not os.path.isfile(file_path): raise CLIError( "{} is not valid file, or not accessable.".format(file_path)) hp_config = get_file_json(file_path) if not isinstance(hp_config, dict): raise CLIError( "Error reading Http Proxy Config at {}. Please see https://aka.ms/HttpProxyConfig for correct format.".format(file_path)) config_object = ManagedClusterHTTPProxyConfig() config_object.http_proxy = hp_config.get("httpProxy", None) config_object.https_proxy = hp_config.get("httpsProxy", None) config_object.no_proxy = hp_config.get("noProxy", None) config_object.trusted_ca = hp_config.get("trustedCa", None) return config_object def aks_pod_identity_add(cmd, client, resource_group_name, cluster_name, identity_name, identity_namespace, identity_resource_id, binding_selector=None, no_wait=False): # pylint: disable=unused-argument instance = client.get(resource_group_name, cluster_name) _ensure_pod_identity_addon_is_enabled(instance) user_assigned_identity = _get_user_assigned_identity( cmd.cli_ctx, identity_resource_id) _ensure_managed_identity_operator_permission( cmd.cli_ctx, instance, user_assigned_identity.id) pod_identities = [] if instance.pod_identity_profile.user_assigned_identities: pod_identities = instance.pod_identity_profile.user_assigned_identities pod_identity = ManagedClusterPodIdentity( name=identity_name, namespace=identity_namespace, identity=UserAssignedIdentity( resource_id=user_assigned_identity.id, client_id=user_assigned_identity.client_id, object_id=user_assigned_identity.principal_id, ) ) if binding_selector is not None: pod_identity.binding_selector = binding_selector pod_identities.append(pod_identity) from azext_aks_preview.decorator import AKSPreviewModels # store all the models used by pod identity pod_identity_models = AKSPreviewModels( cmd, CUSTOM_MGMT_AKS_PREVIEW).pod_identity_models _update_addon_pod_identity( instance, enable=True, pod_identities=pod_identities, pod_identity_exceptions=instance.pod_identity_profile.user_assigned_identity_exceptions, models=pod_identity_models ) # send the managed cluster represeentation to update the pod identity addon return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, instance) def aks_pod_identity_delete(cmd, client, resource_group_name, cluster_name, identity_name, identity_namespace, no_wait=False): # pylint: disable=unused-argument instance = client.get(resource_group_name, cluster_name) _ensure_pod_identity_addon_is_enabled(instance) pod_identities = [] if instance.pod_identity_profile.user_assigned_identities: for pod_identity in instance.pod_identity_profile.user_assigned_identities: if pod_identity.name == identity_name and pod_identity.namespace == identity_namespace: # to remove continue pod_identities.append(pod_identity) from azext_aks_preview.decorator import AKSPreviewModels # store all the models used by pod identity pod_identity_models = AKSPreviewModels( cmd, CUSTOM_MGMT_AKS_PREVIEW).pod_identity_models _update_addon_pod_identity( instance, enable=True, pod_identities=pod_identities, pod_identity_exceptions=instance.pod_identity_profile.user_assigned_identity_exceptions, models=pod_identity_models ) # send the managed cluster represeentation to update the pod identity addon return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, instance) def aks_pod_identity_list(cmd, client, resource_group_name, cluster_name): # pylint: disable=unused-argument instance = client.get(resource_group_name, cluster_name) return _remove_nulls([instance])[0] def aks_pod_identity_exception_add(cmd, client, resource_group_name, cluster_name, exc_name, exc_namespace, pod_labels, no_wait=False): # pylint: disable=unused-argument instance = client.get(resource_group_name, cluster_name) _ensure_pod_identity_addon_is_enabled(instance) pod_identity_exceptions = [] if instance.pod_identity_profile.user_assigned_identity_exceptions: pod_identity_exceptions = instance.pod_identity_profile.user_assigned_identity_exceptions exc = ManagedClusterPodIdentityException( name=exc_name, namespace=exc_namespace, pod_labels=pod_labels) pod_identity_exceptions.append(exc) from azext_aks_preview.decorator import AKSPreviewModels # store all the models used by pod identity pod_identity_models = AKSPreviewModels( cmd, CUSTOM_MGMT_AKS_PREVIEW).pod_identity_models _update_addon_pod_identity( instance, enable=True, pod_identities=instance.pod_identity_profile.user_assigned_identities, pod_identity_exceptions=pod_identity_exceptions, models=pod_identity_models ) # send the managed cluster represeentation to update the pod identity addon return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, instance) def aks_pod_identity_exception_delete(cmd, client, resource_group_name, cluster_name, exc_name, exc_namespace, no_wait=False): # pylint: disable=unused-argument instance = client.get(resource_group_name, cluster_name) _ensure_pod_identity_addon_is_enabled(instance) pod_identity_exceptions = [] if instance.pod_identity_profile.user_assigned_identity_exceptions: for exc in instance.pod_identity_profile.user_assigned_identity_exceptions: if exc.name == exc_name and exc.namespace == exc_namespace: # to remove continue pod_identity_exceptions.append(exc) from azext_aks_preview.decorator import AKSPreviewModels # store all the models used by pod identity pod_identity_models = AKSPreviewModels( cmd, CUSTOM_MGMT_AKS_PREVIEW).pod_identity_models _update_addon_pod_identity( instance, enable=True, pod_identities=instance.pod_identity_profile.user_assigned_identities, pod_identity_exceptions=pod_identity_exceptions, models=pod_identity_models ) # send the managed cluster represeentation to update the pod identity addon return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, instance) def aks_pod_identity_exception_update(cmd, client, resource_group_name, cluster_name, exc_name, exc_namespace, pod_labels, no_wait=False): # pylint: disable=unused-argument instance = client.get(resource_group_name, cluster_name) _ensure_pod_identity_addon_is_enabled(instance) found_target = False updated_exc = ManagedClusterPodIdentityException( name=exc_name, namespace=exc_namespace, pod_labels=pod_labels) pod_identity_exceptions = [] if instance.pod_identity_profile.user_assigned_identity_exceptions: for exc in instance.pod_identity_profile.user_assigned_identity_exceptions: if exc.name == exc_name and exc.namespace == exc_namespace: found_target = True pod_identity_exceptions.append(updated_exc) else: pod_identity_exceptions.append(exc) if not found_target: raise CLIError( 'pod identity exception {}/{} not found'.format(exc_namespace, exc_name)) from azext_aks_preview.decorator import AKSPreviewModels # store all the models used by pod identity pod_identity_models = AKSPreviewModels( cmd, CUSTOM_MGMT_AKS_PREVIEW).pod_identity_models _update_addon_pod_identity( instance, enable=True, pod_identities=instance.pod_identity_profile.user_assigned_identities, pod_identity_exceptions=pod_identity_exceptions, models=pod_identity_models ) # send the managed cluster represeentation to update the pod identity addon return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, instance) def aks_pod_identity_exception_list(cmd, client, resource_group_name, cluster_name): instance = client.get(resource_group_name, cluster_name) return _remove_nulls([instance])[0] def _ensure_cluster_identity_permission_on_kubelet_identity(cli_ctx, cluster_identity_object_id, scope): factory = get_auth_management_client(cli_ctx, scope) assignments_client = factory.role_assignments for i in assignments_client.list_for_scope(scope=scope, filter='atScope()'): if i.scope.lower() != scope.lower(): continue if not i.role_definition_id.lower().endswith(CONST_MANAGED_IDENTITY_OPERATOR_ROLE_ID): continue if i.principal_id.lower() != cluster_identity_object_id.lower(): continue # already assigned return if not add_role_assignment(cli_ctx, CONST_MANAGED_IDENTITY_OPERATOR_ROLE, cluster_identity_object_id, is_service_principal=False, scope=scope): raise CLIError( 'Could not grant Managed Identity Operator permission to cluster identity at scope {}'.format(scope)) def aks_egress_endpoints_list(cmd, client, resource_group_name, name): # pylint: disable=unused-argument return client.list_outbound_network_dependencies_endpoints(resource_group_name, name) def aks_snapshot_create(cmd, # pylint: disable=too-many-locals,too-many-statements,too-many-branches client, resource_group_name, name, cluster_id, location=None, tags=None, aks_custom_headers=None, no_wait=False): rg_location = get_rg_location(cmd.cli_ctx, resource_group_name) if location is None: location = rg_location creationData = CreationData( source_resource_id=cluster_id ) snapshot = ManagedClusterSnapshot( name=name, tags=tags, location=location, creation_data=creationData, snapshot_type="ManagedCluster", ) headers = get_aks_custom_headers(aks_custom_headers) return client.create_or_update(resource_group_name, name, snapshot, headers=headers) def aks_snapshot_show(cmd, client, resource_group_name, name): # pylint: disable=unused-argument snapshot = client.get(resource_group_name, name) return snapshot def aks_snapshot_delete(cmd, # pylint: disable=unused-argument client, resource_group_name, name, no_wait=False, yes=False): from knack.prompting import prompt_y_n msg = 'This will delete the cluster snapshot "{}" in resource group "{}", Are you sure?'.format( name, resource_group_name) if not yes and not prompt_y_n(msg, default="n"): return None return client.delete(resource_group_name, name) def aks_snapshot_list(cmd, client, resource_group_name=None): # pylint: disable=unused-argument if resource_group_name is None or resource_group_name == '': return client.list() return client.list_by_resource_group(resource_group_name) def aks_nodepool_snapshot_create(cmd, # pylint: disable=too-many-locals,too-many-statements,too-many-branches client, resource_group_name, snapshot_name, nodepool_id, location=None, tags=None, aks_custom_headers=None, no_wait=False): rg_location = get_rg_location(cmd.cli_ctx, resource_group_name) if location is None: location = rg_location creationData = CreationData( source_resource_id=nodepool_id ) snapshot = Snapshot( name=snapshot_name, tags=tags, location=location, creation_data=creationData ) headers = get_aks_custom_headers(aks_custom_headers) return client.create_or_update(resource_group_name, snapshot_name, snapshot, headers=headers) def aks_nodepool_snapshot_show(cmd, client, resource_group_name, snapshot_name): # pylint: disable=unused-argument snapshot = client.get(resource_group_name, snapshot_name) return snapshot def aks_nodepool_snapshot_delete(cmd, # pylint: disable=unused-argument client, resource_group_name, snapshot_name, no_wait=False, yes=False): from knack.prompting import prompt_y_n msg = 'This will delete the nodepool snapshot "{}" in resource group "{}", Are you sure?'.format( snapshot_name, resource_group_name) if not yes and not prompt_y_n(msg, default="n"): return None return client.delete(resource_group_name, snapshot_name) def aks_nodepool_snapshot_list(cmd, client, resource_group_name=None): # pylint: disable=unused-argument if resource_group_name is None or resource_group_name == '': return client.list() return client.list_by_resource_group(resource_group_name)
# pylint: disable=too-many-lines # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- import base64 import binascii import datetime import errno import json import os import os.path import platform import re import ssl import stat import subprocess import sys import tempfile import threading import time import uuid import webbrowser from math import isnan import colorama # pylint: disable=import-error import yaml # pylint: disable=import-error from azure.cli.core.api import get_config_dir from azure.cli.core.azclierror import ( ArgumentUsageError, InvalidArgumentValueError, ) from azure.cli.core.commands import LongRunningOperation from azure.cli.core.commands.client_factory import ( get_mgmt_service_client, get_subscription_id, ) from azure.cli.core.util import ( get_file_json, in_cloud_console, read_file_content, sdk_no_wait, shell_safe_json_parse, ) from azure.graphrbac.models import ( ApplicationCreateParameters, KeyCredential, PasswordCredential, ServicePrincipalCreateParameters, ) from dateutil.parser import parse # pylint: disable=import-error from dateutil.relativedelta import relativedelta # pylint: disable=import-error from knack.log import get_logger from knack.prompting import NoTTYException, prompt_pass, prompt_y_n from knack.util import CLIError from msrestazure.azure_exceptions import CloudError from six.moves.urllib.error import URLError # pylint: disable=import-error from six.moves.urllib.request import urlopen # pylint: disable=import-error from tabulate import tabulate # pylint: disable=import-error from azext_aks_preview._client_factory import CUSTOM_MGMT_AKS_PREVIEW from ._client_factory import ( cf_agent_pools, cf_container_registry_service, cf_nodepool_snapshots_client, cf_mc_snapshots_client, cf_storage, get_auth_management_client, get_graph_rbac_management_client, get_msi_client, get_resource_by_name, ) from ._consts import ( ADDONS, ADDONS_DESCRIPTIONS, CONST_ACC_SGX_QUOTE_HELPER_ENABLED, CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME, CONST_AZURE_POLICY_ADDON_NAME, CONST_CONFCOM_ADDON_NAME, CONST_HTTP_APPLICATION_ROUTING_ADDON_NAME, CONST_INGRESS_APPGW_ADDON_NAME, CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID, CONST_INGRESS_APPGW_APPLICATION_GATEWAY_NAME, CONST_INGRESS_APPGW_SUBNET_CIDR, CONST_INGRESS_APPGW_SUBNET_ID, CONST_INGRESS_APPGW_WATCH_NAMESPACE, CONST_KUBE_DASHBOARD_ADDON_NAME, CONST_MANAGED_IDENTITY_OPERATOR_ROLE, CONST_MANAGED_IDENTITY_OPERATOR_ROLE_ID, CONST_MONITORING_ADDON_NAME, CONST_MONITORING_LOG_ANALYTICS_WORKSPACE_RESOURCE_ID, CONST_MONITORING_USING_AAD_MSI_AUTH, CONST_OPEN_SERVICE_MESH_ADDON_NAME, CONST_ROTATION_POLL_INTERVAL, CONST_SCALE_DOWN_MODE_DELETE, CONST_SCALE_SET_PRIORITY_REGULAR, CONST_SCALE_SET_PRIORITY_SPOT, CONST_SECRET_ROTATION_ENABLED, CONST_SPOT_EVICTION_POLICY_DELETE, CONST_VIRTUAL_NODE_ADDON_NAME, CONST_VIRTUAL_NODE_SUBNET_NAME, ) from ._helpers import ( _trim_fqdn_name_containing_hcp, ) from ._podidentity import ( _ensure_managed_identity_operator_permission, _ensure_pod_identity_addon_is_enabled, _fill_defaults_for_pod_identity_profile, _update_addon_pod_identity, ) from ._resourcegroup import get_rg_location from ._roleassignments import ( add_role_assignment, build_role_scope, create_role_assignment, resolve_object_id, resolve_role_id, ) from .addonconfiguration import ( add_ingress_appgw_addon_role_assignment, add_monitoring_role_assignment, add_virtual_node_role_assignment, enable_addons, ensure_container_insights_for_monitoring, ensure_default_log_analytics_workspace_for_monitoring, sanitize_loganalytics_ws_resource_id, ) from .maintenanceconfiguration import ( aks_maintenanceconfiguration_update_internal, ) from .vendored_sdks.azure_mgmt_preview_aks.v2022_04_02_preview.models import ( AgentPool, AgentPoolUpgradeSettings, ContainerServiceStorageProfileTypes, CreationData, KubeletConfig, LinuxOSConfig, ManagedClusterAddonProfile, ManagedClusterHTTPProxyConfig, ManagedClusterPodIdentity, ManagedClusterPodIdentityException, PowerState, Snapshot, ManagedClusterSnapshot, SysctlConfig, UserAssignedIdentity, ) logger = get_logger(__name__) def which(binary): path_var = os.getenv('PATH') if platform.system() == 'Windows': binary = binary + '.exe' parts = path_var.split(';') else: parts = path_var.split(':') for part in parts: bin_path = os.path.join(part, binary) if os.path.exists(bin_path) and os.path.isfile(bin_path) and os.access(bin_path, os.X_OK): return bin_path return None def wait_then_open(url): """ Waits for a bit then opens a URL. Useful for waiting for a proxy to come up, and then open the URL. """ for _ in range(1, 10): try: urlopen(url, context=_ssl_context()) except URLError: time.sleep(1) break webbrowser.open_new_tab(url) def wait_then_open_async(url): """ Spawns a thread that waits for a bit then opens a URL. """ t = threading.Thread(target=wait_then_open, args=({url})) t.daemon = True t.start() def _ssl_context(): if sys.version_info < (3, 4) or (in_cloud_console() and platform.system() == 'Windows'): try: # added in python 2.7.13 and 3.6 return ssl.SSLContext(ssl.PROTOCOL_TLS) except AttributeError: return ssl.SSLContext(ssl.PROTOCOL_TLSv1) return ssl.create_default_context() def _build_service_principal(rbac_client, cli_ctx, name, url, client_secret): # use get_progress_controller hook = cli_ctx.get_progress_controller(True) hook.add(messsage='Creating service principal', value=0, total_val=1.0) logger.info('Creating service principal') # always create application with 5 years expiration start_date = datetime.datetime.utcnow() end_date = start_date + relativedelta(years=5) result = create_application(rbac_client.applications, name, url, [url], password=client_secret, start_date=start_date, end_date=end_date) service_principal = result.app_id # pylint: disable=no-member for x in range(0, 10): hook.add(message='Creating service principal', value=0.1 * x, total_val=1.0) try: create_service_principal( cli_ctx, service_principal, rbac_client=rbac_client) break # TODO figure out what exception AAD throws here sometimes. except Exception as ex: # pylint: disable=broad-except logger.info(ex) time.sleep(2 + 2 * x) else: return False hook.add(message='Finished service principal creation', value=1.0, total_val=1.0) logger.info('Finished service principal creation') return service_principal def _delete_role_assignments(cli_ctx, role, service_principal, delay=2, scope=None): # AAD can have delays in propagating data, so sleep and retry hook = cli_ctx.get_progress_controller(True) hook.add(message='Waiting for AAD role to delete', value=0, total_val=1.0) logger.info('Waiting for AAD role to delete') for x in range(0, 10): hook.add(message='Waiting for AAD role to delete', value=0.1 * x, total_val=1.0) try: delete_role_assignments(cli_ctx, role=role, assignee=service_principal, scope=scope) break except CLIError as ex: raise ex except CloudError as ex: logger.info(ex) time.sleep(delay + delay * x) else: return False hook.add(message='AAD role deletion done', value=1.0, total_val=1.0) logger.info('AAD role deletion done') return True def _get_default_dns_prefix(name, resource_group_name, subscription_id): # Use subscription id to provide uniqueness and prevent DNS name clashes name_part = re.sub('[^A-Za-z0-9-]', '', name)[0:10] if not name_part[0].isalpha(): name_part = (str('a') + name_part)[0:10] resource_group_part = re.sub( '[^A-Za-z0-9-]', '', resource_group_name)[0:16] return '{}-{}-{}'.format(name_part, resource_group_part, subscription_id[0:6]) # pylint: disable=too-many-locals def store_acs_service_principal(subscription_id, client_secret, service_principal, file_name='acsServicePrincipal.json'): obj = {} if client_secret: obj['client_secret'] = client_secret if service_principal: obj['service_principal'] = service_principal config_path = os.path.join(get_config_dir(), file_name) full_config = load_service_principals(config_path=config_path) if not full_config: full_config = {} full_config[subscription_id] = obj with os.fdopen(os.open(config_path, os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o600), 'w+') as spFile: json.dump(full_config, spFile) def load_acs_service_principal(subscription_id, file_name='acsServicePrincipal.json'): config_path = os.path.join(get_config_dir(), file_name) config = load_service_principals(config_path) if not config: return None return config.get(subscription_id) def load_service_principals(config_path): if not os.path.exists(config_path): return None fd = os.open(config_path, os.O_RDONLY) try: with os.fdopen(fd) as f: return shell_safe_json_parse(f.read()) except: # pylint: disable=bare-except return None def create_application(client, display_name, homepage, identifier_uris, available_to_other_tenants=False, password=None, reply_urls=None, key_value=None, key_type=None, key_usage=None, start_date=None, end_date=None): from azure.graphrbac.models import GraphErrorException password_creds, key_creds = _build_application_creds(password=password, key_value=key_value, key_type=key_type, key_usage=key_usage, start_date=start_date, end_date=end_date) app_create_param = ApplicationCreateParameters(available_to_other_tenants=available_to_other_tenants, display_name=display_name, identifier_uris=identifier_uris, homepage=homepage, reply_urls=reply_urls, key_credentials=key_creds, password_credentials=password_creds) try: return client.create(app_create_param) except GraphErrorException as ex: if 'insufficient privileges' in str(ex).lower(): link = 'https://docs.microsoft.com/azure/azure-resource-manager/resource-group-create-service-principal-portal' # pylint: disable=line-too-long raise CLIError("Directory permission is needed for the current user to register the application. " "For how to configure, please refer '{}'. Original error: {}".format(link, ex)) raise def _build_application_creds(password=None, key_value=None, key_type=None, key_usage=None, start_date=None, end_date=None): if password and key_value: raise CLIError( 'specify either --password or --key-value, but not both.') if not start_date: start_date = datetime.datetime.utcnow() elif isinstance(start_date, str): start_date = parse(start_date) if not end_date: end_date = start_date + relativedelta(years=1) elif isinstance(end_date, str): end_date = parse(end_date) key_type = key_type or 'AsymmetricX509Cert' key_usage = key_usage or 'Verify' password_creds = None key_creds = None if password: password_creds = [PasswordCredential(start_date=start_date, end_date=end_date, key_id=str(uuid.uuid4()), value=password)] elif key_value: key_creds = [KeyCredential(start_date=start_date, end_date=end_date, value=key_value, key_id=str(uuid.uuid4()), usage=key_usage, type=key_type)] return (password_creds, key_creds) def create_service_principal(cli_ctx, identifier, resolve_app=True, rbac_client=None): if rbac_client is None: rbac_client = get_graph_rbac_management_client(cli_ctx) if resolve_app: try: uuid.UUID(identifier) result = list(rbac_client.applications.list( filter="appId eq '{}'".format(identifier))) except ValueError: result = list(rbac_client.applications.list( filter="identifierUris/any(s:s eq '{}')".format(identifier))) if not result: # assume we get an object id result = [rbac_client.applications.get(identifier)] app_id = result[0].app_id else: app_id = identifier return rbac_client.service_principals.create(ServicePrincipalCreateParameters(app_id=app_id, account_enabled=True)) def delete_role_assignments(cli_ctx, ids=None, assignee=None, role=None, resource_group_name=None, scope=None, include_inherited=False, yes=None): factory = get_auth_management_client(cli_ctx, scope) assignments_client = factory.role_assignments definitions_client = factory.role_definitions ids = ids or [] if ids: if assignee or role or resource_group_name or scope or include_inherited: raise CLIError( 'When assignment ids are used, other parameter values are not required') for i in ids: assignments_client.delete_by_id(i) return if not any([ids, assignee, role, resource_group_name, scope, assignee, yes]): msg = 'This will delete all role assignments under the subscription. Are you sure?' if not prompt_y_n(msg, default="n"): return scope = build_role_scope(resource_group_name, scope, assignments_client.config.subscription_id) assignments = _search_role_assignments(cli_ctx, assignments_client, definitions_client, scope, assignee, role, include_inherited, include_groups=False) if assignments: for a in assignments: assignments_client.delete_by_id(a.id) def _delete_role_assignments(cli_ctx, role, service_principal, delay=2, scope=None): # AAD can have delays in propagating data, so sleep and retry hook = cli_ctx.get_progress_controller(True) hook.add(message='Waiting for AAD role to delete', value=0, total_val=1.0) logger.info('Waiting for AAD role to delete') for x in range(0, 10): hook.add(message='Waiting for AAD role to delete', value=0.1 * x, total_val=1.0) try: delete_role_assignments(cli_ctx, role=role, assignee=service_principal, scope=scope) break except CLIError as ex: raise ex except CloudError as ex: logger.info(ex) time.sleep(delay + delay * x) else: return False hook.add(message='AAD role deletion done', value=1.0, total_val=1.0) logger.info('AAD role deletion done') return True def _search_role_assignments(cli_ctx, assignments_client, definitions_client, scope, assignee, role, include_inherited, include_groups): assignee_object_id = None if assignee: assignee_object_id = resolve_object_id(cli_ctx, assignee) # always use "scope" if provided, so we can get assignments beyond subscription e.g. management groups if scope: assignments = list(assignments_client.list_for_scope( scope=scope, filter='atScope()')) elif assignee_object_id: if include_groups: f = "assignedTo('{}')".format(assignee_object_id) else: f = "principalId eq '{}'".format(assignee_object_id) assignments = list(assignments_client.list(filter=f)) else: assignments = list(assignments_client.list()) if assignments: assignments = [a for a in assignments if ( not scope or include_inherited and re.match(_get_role_property(a, 'scope'), scope, re.I) or _get_role_property(a, 'scope').lower() == scope.lower() )] if role: role_id = resolve_role_id(role, scope, definitions_client) assignments = [i for i in assignments if _get_role_property( i, 'role_definition_id') == role_id] if assignee_object_id: assignments = [i for i in assignments if _get_role_property( i, 'principal_id') == assignee_object_id] return assignments def _get_role_property(obj, property_name): if isinstance(obj, dict): return obj[property_name] return getattr(obj, property_name) def subnet_role_assignment_exists(cli_ctx, scope): network_contributor_role_id = "4d97b98b-1d4f-4787-a291-c67834d212e7" factory = get_auth_management_client(cli_ctx, scope) assignments_client = factory.role_assignments for i in assignments_client.list_for_scope(scope=scope, filter='atScope()'): if i.scope == scope and i.role_definition_id.endswith(network_contributor_role_id): return True return False _re_user_assigned_identity_resource_id = re.compile( r'/subscriptions/(.*?)/resourcegroups/(.*?)/providers/microsoft.managedidentity/userassignedidentities/(.*)', flags=re.IGNORECASE) def _get_user_assigned_identity(cli_ctx, resource_id): resource_id = resource_id.lower() match = _re_user_assigned_identity_resource_id.search(resource_id) if match: subscription_id = match.group(1) resource_group_name = match.group(2) identity_name = match.group(3) msi_client = get_msi_client(cli_ctx, subscription_id) try: identity = msi_client.user_assigned_identities.get(resource_group_name=resource_group_name, resource_name=identity_name) except CloudError as ex: if 'was not found' in ex.message: raise CLIError("Identity {} not found.".format(resource_id)) raise CLIError(ex.message) return identity raise CLIError( "Cannot parse identity name from provided resource id {}.".format(resource_id)) _re_snapshot_resource_id = re.compile( r'/subscriptions/(.*?)/resourcegroups/(.*?)/providers/microsoft.containerservice/snapshots/(.*)', flags=re.IGNORECASE) _re_mc_snapshot_resource_id = re.compile( r'/subscriptions/(.*?)/resourcegroups/(.*?)/providers/microsoft.containerservice/managedclustersnapshots/(.*)', flags=re.IGNORECASE) def _get_snapshot(cli_ctx, snapshot_id): snapshot_id = snapshot_id.lower() match = _re_snapshot_resource_id.search(snapshot_id) if match: subscription_id = match.group(1) resource_group_name = match.group(2) snapshot_name = match.group(3) snapshot_client = cf_nodepool_snapshots_client( cli_ctx, subscription_id=subscription_id) try: snapshot = snapshot_client.get(resource_group_name, snapshot_name) except CloudError as ex: if 'was not found' in ex.message: raise InvalidArgumentValueError( "Snapshot {} not found.".format(snapshot_id)) raise CLIError(ex.message) return snapshot raise InvalidArgumentValueError( "Cannot parse snapshot name from provided resource id {}.".format(snapshot_id)) def _get_cluster_snapshot(cli_ctx, snapshot_id): snapshot_id = snapshot_id.lower() match = _re_mc_snapshot_resource_id.search(snapshot_id) if match: subscription_id = match.group(1) resource_group_name = match.group(2) snapshot_name = match.group(3) snapshot_client = cf_mc_snapshots_client( cli_ctx, subscription_id=subscription_id) try: snapshot = snapshot_client.get(resource_group_name, snapshot_name) except CloudError as ex: if 'was not found' in ex.message: raise InvalidArgumentValueError( "Managed cluster snapshot {} not found.".format(snapshot_id)) raise CLIError(ex.message) return snapshot raise InvalidArgumentValueError( "Cannot parse snapshot name from provided resource id {}.".format(snapshot_id)) def aks_browse( cmd, client, resource_group_name, name, disable_browser=False, listen_address="127.0.0.1", listen_port="8001", ): from azure.cli.command_modules.acs.custom import _aks_browse return _aks_browse( cmd, client, resource_group_name, name, disable_browser, listen_address, listen_port, CUSTOM_MGMT_AKS_PREVIEW, ) def _trim_nodepoolname(nodepool_name): if not nodepool_name: return "nodepool1" return nodepool_name[:12] def aks_maintenanceconfiguration_list( cmd, client, resource_group_name, cluster_name ): return client.list_by_managed_cluster(resource_group_name, cluster_name) def aks_maintenanceconfiguration_show( cmd, client, resource_group_name, cluster_name, config_name ): logger.warning('resource_group_name: %s, cluster_name: %s, config_name: %s ', resource_group_name, cluster_name, config_name) return client.get(resource_group_name, cluster_name, config_name) def aks_maintenanceconfiguration_delete( cmd, client, resource_group_name, cluster_name, config_name ): logger.warning('resource_group_name: %s, cluster_name: %s, config_name: %s ', resource_group_name, cluster_name, config_name) return client.delete(resource_group_name, cluster_name, config_name) def aks_maintenanceconfiguration_add( cmd, client, resource_group_name, cluster_name, config_name, config_file, weekday, start_hour ): configs = client.list_by_managed_cluster(resource_group_name, cluster_name) for config in configs: if config.name == config_name: raise CLIError("Maintenance configuration '{}' already exists, please try a different name, " "use 'aks maintenanceconfiguration list' to get current list of maitenance configurations".format(config_name)) return aks_maintenanceconfiguration_update_internal(cmd, client, resource_group_name, cluster_name, config_name, config_file, weekday, start_hour) def aks_maintenanceconfiguration_update( cmd, client, resource_group_name, cluster_name, config_name, config_file, weekday, start_hour ): configs = client.list_by_managed_cluster(resource_group_name, cluster_name) found = False for config in configs: if config.name == config_name: found = True break if not found: raise CLIError("Maintenance configuration '{}' doesn't exist." "use 'aks maintenanceconfiguration list' to get current list of maitenance configurations".format(config_name)) return aks_maintenanceconfiguration_update_internal(cmd, client, resource_group_name, cluster_name, config_name, config_file, weekday, start_hour) # pylint: disable=unused-argument,too-many-locals def aks_create(cmd, client, resource_group_name, name, ssh_key_value, dns_name_prefix=None, location=None, admin_username="azureuser", windows_admin_username=None, windows_admin_password=None, enable_ahub=False, kubernetes_version='', node_vm_size=None, node_osdisk_type=None, node_osdisk_size=0, node_osdisk_diskencryptionset_id=None, node_count=3, nodepool_name="nodepool1", nodepool_tags=None, nodepool_labels=None, service_principal=None, client_secret=None, no_ssh_key=False, disable_rbac=None, enable_rbac=None, enable_vmss=None, vm_set_type=None, skip_subnet_role_assignment=False, os_sku=None, enable_fips_image=False, enable_cluster_autoscaler=False, cluster_autoscaler_profile=None, network_plugin=None, network_policy=None, pod_cidr=None, service_cidr=None, pod_cidrs=None, service_cidrs=None, ip_families=None, dns_service_ip=None, docker_bridge_address=None, load_balancer_sku=None, load_balancer_managed_outbound_ip_count=None, load_balancer_managed_outbound_ipv6_count=None, load_balancer_outbound_ips=None, load_balancer_outbound_ip_prefixes=None, load_balancer_outbound_ports=None, load_balancer_idle_timeout=None, nat_gateway_managed_outbound_ip_count=None, nat_gateway_idle_timeout=None, outbound_type=None, enable_addons=None, workspace_resource_id=None, enable_msi_auth_for_monitoring=False, min_count=None, max_count=None, vnet_subnet_id=None, pod_subnet_id=None, ppg=None, max_pods=0, aad_client_app_id=None, aad_server_app_id=None, aad_server_app_secret=None, aad_tenant_id=None, tags=None, node_zones=None, zones=None, enable_node_public_ip=False, node_public_ip_prefix_id=None, generate_ssh_keys=False, # pylint: disable=unused-argument enable_pod_security_policy=False, node_resource_group=None, uptime_sla=False, attach_acr=None, enable_private_cluster=False, private_dns_zone=None, enable_managed_identity=True, fqdn_subdomain=None, disable_public_fqdn=False, api_server_authorized_ip_ranges=None, aks_custom_headers=None, appgw_name=None, appgw_subnet_prefix=None, appgw_subnet_cidr=None, appgw_id=None, appgw_subnet_id=None, appgw_watch_namespace=None, enable_aad=False, enable_azure_rbac=False, aad_admin_group_object_ids=None, aci_subnet_name=None, enable_sgxquotehelper=False, kubelet_config=None, linux_os_config=None, http_proxy_config=None, assign_identity=None, auto_upgrade_channel=None, enable_pod_identity=False, enable_pod_identity_with_kubenet=False, # NOTE: for workload identity flags, we need to know if it's set to True/False or not set (None) enable_workload_identity=None, enable_encryption_at_host=False, enable_ultra_ssd=False, edge_zone=None, enable_secret_rotation=False, disable_disk_driver=None, disable_file_driver=None, disable_snapshot_controller=None, rotation_poll_interval=None, disable_local_accounts=False, no_wait=False, assign_kubelet_identity=None, workload_runtime=None, gpu_instance_profile=None, enable_windows_gmsa=False, gmsa_dns_server=None, gmsa_root_domain_name=None, snapshot_id=None, cluster_snapshot_id=None, enable_oidc_issuer=False, host_group_id=None, crg_id=None, message_of_the_day=None, enable_azure_keyvault_kms=False, azure_keyvault_kms_key_id=None, enable_apiserver_vnet_integration=False, apiserver_subnet_id=None, yes=False): # DO NOT MOVE: get all the original parameters and save them as a dictionary raw_parameters = locals() from azure.cli.command_modules.acs._consts import DecoratorEarlyExitException from azure.cli.command_modules.acs.decorator import AKSParamDict from .decorator import AKSPreviewCreateDecorator # decorator pattern aks_create_decorator = AKSPreviewCreateDecorator( cmd=cmd, client=client, raw_parameters=AKSParamDict(raw_parameters), resource_type=CUSTOM_MGMT_AKS_PREVIEW, ) try: # construct mc profile mc = aks_create_decorator.construct_mc_preview_profile() except DecoratorEarlyExitException: # exit gracefully return None # send request to create a real managed cluster return aks_create_decorator.create_mc_preview(mc) def aks_update(cmd, # pylint: disable=too-many-statements,too-many-branches,too-many-locals client, resource_group_name, name, enable_cluster_autoscaler=False, disable_cluster_autoscaler=False, update_cluster_autoscaler=False, cluster_autoscaler_profile=None, min_count=None, max_count=None, no_wait=False, load_balancer_managed_outbound_ip_count=None, load_balancer_managed_outbound_ipv6_count=None, load_balancer_outbound_ips=None, load_balancer_outbound_ip_prefixes=None, load_balancer_outbound_ports=None, load_balancer_idle_timeout=None, nat_gateway_managed_outbound_ip_count=None, nat_gateway_idle_timeout=None, api_server_authorized_ip_ranges=None, enable_pod_security_policy=False, disable_pod_security_policy=False, attach_acr=None, detach_acr=None, uptime_sla=False, no_uptime_sla=False, enable_aad=False, aad_tenant_id=None, aad_admin_group_object_ids=None, enable_ahub=False, disable_ahub=False, aks_custom_headers=None, auto_upgrade_channel=None, enable_managed_identity=False, assign_identity=None, assign_kubelet_identity=None, enable_pod_identity=False, enable_pod_identity_with_kubenet=False, disable_pod_identity=False, # NOTE: for workload identity flags, we need to know if it's set to True/False or not set (None) enable_workload_identity=None, disable_workload_identity=None, enable_secret_rotation=False, disable_secret_rotation=False, rotation_poll_interval=None, enable_disk_driver=None, disable_disk_driver=None, enable_file_driver=None, disable_file_driver=None, enable_snapshot_controller=None, disable_snapshot_controller=None, disable_local_accounts=False, enable_local_accounts=False, enable_public_fqdn=False, disable_public_fqdn=False, yes=False, tags=None, nodepool_labels=None, windows_admin_password=None, enable_azure_rbac=False, disable_azure_rbac=False, enable_windows_gmsa=False, gmsa_dns_server=None, gmsa_root_domain_name=None, enable_oidc_issuer=False, http_proxy_config=None, enable_azure_keyvault_kms=False, azure_keyvault_kms_key_id=None, enable_apiserver_vnet_integration=False, apiserver_subnet_id=None): # DO NOT MOVE: get all the original parameters and save them as a dictionary raw_parameters = locals() from azure.cli.command_modules.acs._consts import DecoratorEarlyExitException from azure.cli.command_modules.acs.decorator import AKSParamDict from .decorator import AKSPreviewUpdateDecorator # decorator pattern aks_update_decorator = AKSPreviewUpdateDecorator( cmd=cmd, client=client, raw_parameters=AKSParamDict(raw_parameters), resource_type=CUSTOM_MGMT_AKS_PREVIEW, ) try: # update mc profile mc = aks_update_decorator.update_mc_preview_profile() except DecoratorEarlyExitException: # exit gracefully return None # send request to update the real managed cluster return aks_update_decorator.update_mc_preview(mc) # pylint: disable=unused-argument def aks_show(cmd, client, resource_group_name, name): mc = client.get(resource_group_name, name) return _remove_nulls([mc])[0] def _remove_nulls(managed_clusters): """ Remove some often-empty fields from a list of ManagedClusters, so the JSON representation doesn't contain distracting null fields. This works around a quirk of the SDK for python behavior. These fields are not sent by the server, but get recreated by the CLI's own "to_dict" serialization. """ attrs = ['tags'] ap_attrs = ['os_disk_size_gb', 'vnet_subnet_id'] sp_attrs = ['secret'] for managed_cluster in managed_clusters: for attr in attrs: if getattr(managed_cluster, attr, None) is None: delattr(managed_cluster, attr) if managed_cluster.agent_pool_profiles is not None: for ap_profile in managed_cluster.agent_pool_profiles: for attr in ap_attrs: if getattr(ap_profile, attr, None) is None: delattr(ap_profile, attr) for attr in sp_attrs: if getattr(managed_cluster.service_principal_profile, attr, None) is None: delattr(managed_cluster.service_principal_profile, attr) return managed_clusters def aks_get_credentials(cmd, # pylint: disable=unused-argument client, resource_group_name, name, admin=False, user='clusterUser', path=os.path.join(os.path.expanduser( '~'), '.kube', 'config'), overwrite_existing=False, context_name=None, public_fqdn=False, credential_format=None): credentialResults = None serverType = None if public_fqdn: serverType = 'public' if credential_format: credential_format = credential_format.lower() if admin: raise InvalidArgumentValueError("--format can only be specified when requesting clusterUser credential.") if admin: credentialResults = client.list_cluster_admin_credentials( resource_group_name, name, serverType) else: if user.lower() == 'clusteruser': credentialResults = client.list_cluster_user_credentials( resource_group_name, name, serverType, credential_format) elif user.lower() == 'clustermonitoringuser': credentialResults = client.list_cluster_monitoring_user_credentials( resource_group_name, name, serverType) else: raise CLIError("The user is invalid.") if not credentialResults: raise CLIError("No Kubernetes credentials found.") try: kubeconfig = credentialResults.kubeconfigs[0].value.decode( encoding='UTF-8') _print_or_merge_credentials( path, kubeconfig, overwrite_existing, context_name) except (IndexError, ValueError): raise CLIError("Fail to find kubeconfig file.") # pylint: disable=line-too-long def aks_kollect(cmd, # pylint: disable=too-many-statements,too-many-locals client, resource_group_name, name, storage_account=None, sas_token=None, container_logs=None, kube_objects=None, node_logs=None): colorama.init() mc = client.get(resource_group_name, name) if not which('kubectl'): raise CLIError('Can not find kubectl executable in PATH') storage_account_id = None if storage_account is None: print("No storage account specified. Try getting storage account from diagnostic settings") storage_account_id = get_storage_account_from_diag_settings( cmd.cli_ctx, resource_group_name, name) if storage_account_id is None: raise CLIError( "A storage account must be specified, since there isn't one in the diagnostic settings.") from msrestazure.tools import (is_valid_resource_id, parse_resource_id, resource_id) if storage_account_id is None: if not is_valid_resource_id(storage_account): storage_account_id = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=resource_group_name, namespace='Microsoft.Storage', type='storageAccounts', name=storage_account ) else: storage_account_id = storage_account if is_valid_resource_id(storage_account_id): try: parsed_storage_account = parse_resource_id(storage_account_id) except CloudError as ex: raise CLIError(ex.message) else: raise CLIError("Invalid storage account id %s" % storage_account_id) storage_account_name = parsed_storage_account['name'] readonly_sas_token = None if sas_token is None: storage_client = cf_storage( cmd.cli_ctx, parsed_storage_account['subscription']) storage_account_keys = storage_client.storage_accounts.list_keys(parsed_storage_account['resource_group'], storage_account_name) kwargs = { 'account_name': storage_account_name, 'account_key': storage_account_keys.keys[0].value } cloud_storage_client = cloud_storage_account_service_factory( cmd.cli_ctx, kwargs) sas_token = cloud_storage_client.generate_shared_access_signature( 'b', 'sco', 'rwdlacup', datetime.datetime.utcnow() + datetime.timedelta(days=1)) readonly_sas_token = cloud_storage_client.generate_shared_access_signature( 'b', 'sco', 'rl', datetime.datetime.utcnow() + datetime.timedelta(days=1)) readonly_sas_token = readonly_sas_token.strip('?') print() print('This will deploy a daemon set to your cluster to collect logs and diagnostic information and ' f'save them to the storage account ' f'{colorama.Style.BRIGHT}{colorama.Fore.GREEN}{storage_account_name}{colorama.Style.RESET_ALL} as ' f'outlined in {format_hyperlink("http://aka.ms/AKSPeriscope")}.') print() print('If you share access to that storage account to Azure support, you consent to the terms outlined' f' in {format_hyperlink("http://aka.ms/DiagConsent")}.') print() if not prompt_y_n('Do you confirm?', default="n"): return print() print("Getting credentials for cluster %s " % name) _, temp_kubeconfig_path = tempfile.mkstemp() aks_get_credentials(cmd, client, resource_group_name, name, admin=True, path=temp_kubeconfig_path) print() print("Starts collecting diag info for cluster %s " % name) # Form containerName from fqdn, as it was previously jsut the location of code is changed. # https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata#container-names maxContainerNameLength = 63 fqdn = mc.fqdn if mc.fqdn is not None else mc.private_fqdn normalized_container_name = fqdn.replace('.', '-') len_of_container_name = normalized_container_name.index("-hcp-") if len_of_container_name == -1: len_of_container_name = maxContainerNameLength container_name = normalized_container_name[:len_of_container_name] sas_token = sas_token.strip('?') deployment_yaml = _read_periscope_yaml() deployment_yaml = deployment_yaml.replace( "# <accountName, string>", storage_account_name) deployment_yaml = deployment_yaml.replace("# <saskey, base64 encoded>", (base64.b64encode(bytes("?" + sas_token, 'ascii'))).decode('ascii')) deployment_yaml = deployment_yaml.replace( "# <containerName, string>", container_name) yaml_lines = deployment_yaml.splitlines() for index, line in enumerate(yaml_lines): if "DIAGNOSTIC_CONTAINERLOGS_LIST" in line and container_logs is not None: yaml_lines[index] = line + ' ' + container_logs if "DIAGNOSTIC_KUBEOBJECTS_LIST" in line and kube_objects is not None: yaml_lines[index] = line + ' ' + kube_objects if "DIAGNOSTIC_NODELOGS_LIST" in line and node_logs is not None: yaml_lines[index] = line + ' ' + node_logs deployment_yaml = '\n'.join(yaml_lines) fd, temp_yaml_path = tempfile.mkstemp() temp_yaml_file = os.fdopen(fd, 'w+t') try: temp_yaml_file.write(deployment_yaml) temp_yaml_file.flush() temp_yaml_file.close() try: print() print("Cleaning up aks-periscope resources if existing") subprocess.call(["kubectl", "--kubeconfig", temp_kubeconfig_path, "delete", "serviceaccount,configmap,daemonset,secret", "--all", "-n", "aks-periscope", "--ignore-not-found"], stderr=subprocess.STDOUT) subprocess.call(["kubectl", "--kubeconfig", temp_kubeconfig_path, "delete", "ClusterRoleBinding", "aks-periscope-role-binding", "--ignore-not-found"], stderr=subprocess.STDOUT) subprocess.call(["kubectl", "--kubeconfig", temp_kubeconfig_path, "delete", "ClusterRoleBinding", "aks-periscope-role-binding-view", "--ignore-not-found"], stderr=subprocess.STDOUT) subprocess.call(["kubectl", "--kubeconfig", temp_kubeconfig_path, "delete", "ClusterRole", "aks-periscope-role", "--ignore-not-found"], stderr=subprocess.STDOUT) subprocess.call(["kubectl", "--kubeconfig", temp_kubeconfig_path, "delete", "--all", "apd", "-n", "aks-periscope", "--ignore-not-found"], stderr=subprocess.DEVNULL) subprocess.call(["kubectl", "--kubeconfig", temp_kubeconfig_path, "delete", "CustomResourceDefinition", "diagnostics.aks-periscope.azure.github.com", "--ignore-not-found"], stderr=subprocess.STDOUT) print() print("Deploying aks-periscope") subprocess.check_output(["kubectl", "--kubeconfig", temp_kubeconfig_path, "apply", "-f", temp_yaml_path, "-n", "aks-periscope"], stderr=subprocess.STDOUT) except subprocess.CalledProcessError as err: raise CLIError(err.output) finally: os.remove(temp_yaml_path) print() token_in_storage_account_url = readonly_sas_token if readonly_sas_token is not None else sas_token log_storage_account_url = f"https://{storage_account_name}.blob.core.windows.net/" \ f"{_trim_fqdn_name_containing_hcp(container_name)}?{token_in_storage_account_url}" print(f'{colorama.Fore.GREEN}Your logs are being uploaded to storage account {format_bright(storage_account_name)}') print() print(f'You can download Azure Storage Explorer here ' f'{format_hyperlink("https://azure.microsoft.com/en-us/features/storage-explorer/")}' f' to check the logs by adding the storage account using the following URL:') print(f'{format_hyperlink(log_storage_account_url)}') print() if not prompt_y_n('Do you want to see analysis results now?', default="n"): print(f"You can run 'az aks kanalyze -g {resource_group_name} -n {name}' " f"anytime to check the analysis results.") else: display_diagnostics_report(temp_kubeconfig_path) def _read_periscope_yaml(): curr_dir = os.path.dirname(os.path.realpath(__file__)) periscope_yaml_file = os.path.join( curr_dir, "deploymentyaml", "aks-periscope.yaml") yaml_file = open(periscope_yaml_file, "r") data_loaded = yaml_file.read() return data_loaded def aks_kanalyze(cmd, client, resource_group_name, name): colorama.init() client.get(resource_group_name, name) _, temp_kubeconfig_path = tempfile.mkstemp() aks_get_credentials(cmd, client, resource_group_name, name, admin=True, path=temp_kubeconfig_path) display_diagnostics_report(temp_kubeconfig_path) def aks_scale(cmd, # pylint: disable=unused-argument client, resource_group_name, name, node_count, nodepool_name="", no_wait=False): instance = client.get(resource_group_name, name) _fill_defaults_for_pod_identity_profile(instance.pod_identity_profile) if len(instance.agent_pool_profiles) > 1 and nodepool_name == "": raise CLIError('There are more than one node pool in the cluster. ' 'Please specify nodepool name or use az aks nodepool command to scale node pool') for agent_profile in instance.agent_pool_profiles: if agent_profile.name == nodepool_name or (nodepool_name == "" and len(instance.agent_pool_profiles) == 1): if agent_profile.enable_auto_scaling: raise CLIError( "Cannot scale cluster autoscaler enabled node pool.") agent_profile.count = int(node_count) # pylint: disable=no-member # null out the SP profile because otherwise validation complains instance.service_principal_profile = None return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, name, instance) raise CLIError('The nodepool "{}" was not found.'.format(nodepool_name)) def aks_upgrade(cmd, # pylint: disable=unused-argument, too-many-return-statements client, resource_group_name, name, kubernetes_version='', control_plane_only=False, no_wait=False, node_image_only=False, aks_custom_headers=None, yes=False): msg = 'Kubernetes may be unavailable during cluster upgrades.\n Are you sure you want to perform this operation?' if not yes and not prompt_y_n(msg, default="n"): return None instance = client.get(resource_group_name, name) _fill_defaults_for_pod_identity_profile(instance.pod_identity_profile) vmas_cluster = False for agent_profile in instance.agent_pool_profiles: if agent_profile.type.lower() == "availabilityset": vmas_cluster = True break if kubernetes_version != '' and node_image_only: raise CLIError('Conflicting flags. Upgrading the Kubernetes version will also upgrade node image version. ' 'If you only want to upgrade the node version please use the "--node-image-only" option only.') if node_image_only: msg = "This node image upgrade operation will run across every node pool in the cluster " \ "and might take a while. Do you wish to continue?" if not yes and not prompt_y_n(msg, default="n"): return None # This only provide convenience for customer at client side so they can run az aks upgrade to upgrade all # nodepools of a cluster. The SDK only support upgrade single nodepool at a time. for agent_pool_profile in instance.agent_pool_profiles: if vmas_cluster: raise CLIError('This cluster is not using VirtualMachineScaleSets. Node image upgrade only operation ' 'can only be applied on VirtualMachineScaleSets cluster.') agent_pool_client = cf_agent_pools(cmd.cli_ctx) _upgrade_single_nodepool_image_version( True, agent_pool_client, resource_group_name, name, agent_pool_profile.name, None) mc = client.get(resource_group_name, name) return _remove_nulls([mc])[0] if instance.kubernetes_version == kubernetes_version: if instance.provisioning_state == "Succeeded": logger.warning("The cluster is already on version %s and is not in a failed state. No operations " "will occur when upgrading to the same version if the cluster is not in a failed state.", instance.kubernetes_version) elif instance.provisioning_state == "Failed": logger.warning("Cluster currently in failed state. Proceeding with upgrade to existing version %s to " "attempt resolution of failed cluster state.", instance.kubernetes_version) upgrade_all = False instance.kubernetes_version = kubernetes_version # for legacy clusters, we always upgrade node pools with CCP. if instance.max_agent_pools < 8 or vmas_cluster: if control_plane_only: msg = ("Legacy clusters do not support control plane only upgrade. All node pools will be " "upgraded to {} as well. Continue?").format(instance.kubernetes_version) if not yes and not prompt_y_n(msg, default="n"): return None upgrade_all = True else: if not control_plane_only: msg = ("Since control-plane-only argument is not specified, this will upgrade the control plane " "AND all nodepools to version {}. Continue?").format(instance.kubernetes_version) if not yes and not prompt_y_n(msg, default="n"): return None upgrade_all = True else: msg = ("Since control-plane-only argument is specified, this will upgrade only the control plane to {}. " "Node pool will not change. Continue?").format(instance.kubernetes_version) if not yes and not prompt_y_n(msg, default="n"): return None if upgrade_all: for agent_profile in instance.agent_pool_profiles: agent_profile.orchestrator_version = kubernetes_version agent_profile.creation_data = None # null out the SP profile because otherwise validation complains instance.service_principal_profile = None headers = get_aks_custom_headers(aks_custom_headers) return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, name, instance, headers=headers) def _upgrade_single_nodepool_image_version(no_wait, client, resource_group_name, cluster_name, nodepool_name, snapshot_id=None): headers = {} if snapshot_id: headers["AKSSnapshotId"] = snapshot_id return sdk_no_wait(no_wait, client.begin_upgrade_node_image_version, resource_group_name, cluster_name, nodepool_name, headers=headers) def _handle_addons_args(cmd, # pylint: disable=too-many-statements addons_str, subscription_id, resource_group_name, addon_profiles=None, workspace_resource_id=None, enable_msi_auth_for_monitoring=False, appgw_name=None, appgw_subnet_prefix=None, appgw_subnet_cidr=None, appgw_id=None, appgw_subnet_id=None, appgw_watch_namespace=None, enable_sgxquotehelper=False, aci_subnet_name=None, vnet_subnet_id=None, enable_secret_rotation=False, rotation_poll_interval=None,): if not addon_profiles: addon_profiles = {} addons = addons_str.split(',') if addons_str else [] if 'http_application_routing' in addons: addon_profiles[CONST_HTTP_APPLICATION_ROUTING_ADDON_NAME] = ManagedClusterAddonProfile( enabled=True) addons.remove('http_application_routing') if 'kube-dashboard' in addons: addon_profiles[CONST_KUBE_DASHBOARD_ADDON_NAME] = ManagedClusterAddonProfile( enabled=True) addons.remove('kube-dashboard') # TODO: can we help the user find a workspace resource ID? if 'monitoring' in addons: if not workspace_resource_id: # use default workspace if exists else create default workspace workspace_resource_id = ensure_default_log_analytics_workspace_for_monitoring( cmd, subscription_id, resource_group_name) workspace_resource_id = sanitize_loganalytics_ws_resource_id( workspace_resource_id) addon_profiles[CONST_MONITORING_ADDON_NAME] = ManagedClusterAddonProfile(enabled=True, config={CONST_MONITORING_LOG_ANALYTICS_WORKSPACE_RESOURCE_ID: workspace_resource_id, CONST_MONITORING_USING_AAD_MSI_AUTH: enable_msi_auth_for_monitoring}) addons.remove('monitoring') elif workspace_resource_id: raise CLIError( '"--workspace-resource-id" requires "--enable-addons monitoring".') if 'azure-policy' in addons: addon_profiles[CONST_AZURE_POLICY_ADDON_NAME] = ManagedClusterAddonProfile( enabled=True) addons.remove('azure-policy') if 'gitops' in addons: addon_profiles['gitops'] = ManagedClusterAddonProfile(enabled=True) addons.remove('gitops') if 'ingress-appgw' in addons: addon_profile = ManagedClusterAddonProfile(enabled=True, config={}) if appgw_name is not None: addon_profile.config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_NAME] = appgw_name if appgw_subnet_prefix is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_CIDR] = appgw_subnet_prefix if appgw_subnet_cidr is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_CIDR] = appgw_subnet_cidr if appgw_id is not None: addon_profile.config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID] = appgw_id if appgw_subnet_id is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_ID] = appgw_subnet_id if appgw_watch_namespace is not None: addon_profile.config[CONST_INGRESS_APPGW_WATCH_NAMESPACE] = appgw_watch_namespace addon_profiles[CONST_INGRESS_APPGW_ADDON_NAME] = addon_profile addons.remove('ingress-appgw') if 'open-service-mesh' in addons: addon_profile = ManagedClusterAddonProfile(enabled=True, config={}) addon_profiles[CONST_OPEN_SERVICE_MESH_ADDON_NAME] = addon_profile addons.remove('open-service-mesh') if 'azure-keyvault-secrets-provider' in addons: addon_profile = ManagedClusterAddonProfile(enabled=True, config={ CONST_SECRET_ROTATION_ENABLED: "false", CONST_ROTATION_POLL_INTERVAL: "2m"}) if enable_secret_rotation: addon_profile.config[CONST_SECRET_ROTATION_ENABLED] = "true" if rotation_poll_interval is not None: addon_profile.config[CONST_ROTATION_POLL_INTERVAL] = rotation_poll_interval addon_profiles[CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME] = addon_profile addons.remove('azure-keyvault-secrets-provider') if 'confcom' in addons: addon_profile = ManagedClusterAddonProfile( enabled=True, config={CONST_ACC_SGX_QUOTE_HELPER_ENABLED: "false"}) if enable_sgxquotehelper: addon_profile.config[CONST_ACC_SGX_QUOTE_HELPER_ENABLED] = "true" addon_profiles[CONST_CONFCOM_ADDON_NAME] = addon_profile addons.remove('confcom') if 'virtual-node' in addons: if not aci_subnet_name or not vnet_subnet_id: raise CLIError( '"--enable-addons virtual-node" requires "--aci-subnet-name" and "--vnet-subnet-id".') # TODO: how about aciConnectorwindows, what is its addon name? os_type = 'Linux' addon_profiles[CONST_VIRTUAL_NODE_ADDON_NAME + os_type] = ManagedClusterAddonProfile( enabled=True, config={CONST_VIRTUAL_NODE_SUBNET_NAME: aci_subnet_name} ) addons.remove('virtual-node') # error out if any (unrecognized) addons remain if addons: raise CLIError('"{}" {} not recognized by the --enable-addons argument.'.format( ",".join(addons), "are" if len(addons) > 1 else "is")) return addon_profiles def _ensure_aks_service_principal(cli_ctx, service_principal=None, client_secret=None, subscription_id=None, dns_name_prefix=None, fqdn_subdomain=None, location=None, name=None): file_name_aks = 'aksServicePrincipal.json' # TODO: This really needs to be unit tested. rbac_client = get_graph_rbac_management_client(cli_ctx) if not service_principal: # --service-principal not specified, try to load it from local disk principal_obj = load_acs_service_principal( subscription_id, file_name=file_name_aks) if principal_obj: service_principal = principal_obj.get('service_principal') client_secret = principal_obj.get('client_secret') else: # Nothing to load, make one. if not client_secret: client_secret = _create_client_secret() salt = binascii.b2a_hex(os.urandom(3)).decode('utf-8') if dns_name_prefix: url = 'http://{}.{}.{}.cloudapp.azure.com'.format( salt, dns_name_prefix, location) else: url = 'http://{}.{}.{}.cloudapp.azure.com'.format( salt, fqdn_subdomain, location) service_principal = _build_service_principal( rbac_client, cli_ctx, name, url, client_secret) if not service_principal: raise CLIError('Could not create a service principal with the right permissions. ' 'Are you an Owner on this project?') logger.info('Created a service principal: %s', service_principal) # We don't need to add role assignment for this created SPN else: # --service-principal specfied, validate --client-secret was too if not client_secret: raise CLIError( '--client-secret is required if --service-principal is specified') store_acs_service_principal( subscription_id, client_secret, service_principal, file_name=file_name_aks) return load_acs_service_principal(subscription_id, file_name=file_name_aks) def _check_cluster_autoscaler_flag(enable_cluster_autoscaler, min_count, max_count, node_count, agent_pool_profile): if enable_cluster_autoscaler: if min_count is None or max_count is None: raise CLIError( 'Please specify both min-count and max-count when --enable-cluster-autoscaler enabled') if int(min_count) > int(max_count): raise CLIError( 'value of min-count should be less than or equal to value of max-count') if int(node_count) < int(min_count) or int(node_count) > int(max_count): raise CLIError( 'node-count is not in the range of min-count and max-count') agent_pool_profile.min_count = int(min_count) agent_pool_profile.max_count = int(max_count) agent_pool_profile.enable_auto_scaling = True else: if min_count is not None or max_count is not None: raise CLIError( 'min-count and max-count are required for --enable-cluster-autoscaler, please use the flag') def _create_client_secret(): # Add a special character to satsify AAD SP secret requirements special_char = '$' client_secret = binascii.b2a_hex( os.urandom(10)).decode('utf-8') + special_char return client_secret def _ensure_aks_acr(cli_ctx, client_id, acr_name_or_id, subscription_id, # pylint: disable=unused-argument detach=False): from msrestazure.tools import is_valid_resource_id, parse_resource_id # Check if the ACR exists by resource ID. if is_valid_resource_id(acr_name_or_id): try: parsed_registry = parse_resource_id(acr_name_or_id) acr_client = cf_container_registry_service( cli_ctx, subscription_id=parsed_registry['subscription']) registry = acr_client.registries.get( parsed_registry['resource_group'], parsed_registry['name']) except CloudError as ex: raise CLIError(ex.message) _ensure_aks_acr_role_assignment( cli_ctx, client_id, registry.id, detach) return # Check if the ACR exists by name accross all resource groups. registry_name = acr_name_or_id registry_resource = 'Microsoft.ContainerRegistry/registries' try: registry = get_resource_by_name( cli_ctx, registry_name, registry_resource) except CloudError as ex: if 'was not found' in ex.message: raise CLIError( "ACR {} not found. Have you provided the right ACR name?".format(registry_name)) raise CLIError(ex.message) _ensure_aks_acr_role_assignment(cli_ctx, client_id, registry.id, detach) return def _ensure_aks_acr_role_assignment(cli_ctx, client_id, registry_id, detach=False): if detach: if not _delete_role_assignments(cli_ctx, 'acrpull', client_id, scope=registry_id): raise CLIError('Could not delete role assignments for ACR. ' 'Are you an Owner on this subscription?') return if not add_role_assignment(cli_ctx, 'acrpull', client_id, scope=registry_id): raise CLIError('Could not create a role assignment for ACR. ' 'Are you an Owner on this subscription?') return def aks_agentpool_show(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name): instance = client.get(resource_group_name, cluster_name, nodepool_name) return instance def aks_agentpool_list(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name): return client.list(resource_group_name, cluster_name) def aks_agentpool_add(cmd, # pylint: disable=unused-argument,too-many-locals client, resource_group_name, cluster_name, nodepool_name, tags=None, kubernetes_version=None, node_zones=None, zones=None, enable_node_public_ip=False, node_public_ip_prefix_id=None, node_vm_size=None, node_osdisk_type=None, node_osdisk_size=0, node_count=3, vnet_subnet_id=None, pod_subnet_id=None, ppg=None, max_pods=0, os_type=None, os_sku=None, enable_fips_image=False, min_count=None, max_count=None, enable_cluster_autoscaler=False, scale_down_mode=CONST_SCALE_DOWN_MODE_DELETE, node_taints=None, priority=CONST_SCALE_SET_PRIORITY_REGULAR, eviction_policy=CONST_SPOT_EVICTION_POLICY_DELETE, spot_max_price=float('nan'), labels=None, max_surge=None, mode="User", aks_custom_headers=None, kubelet_config=None, linux_os_config=None, enable_encryption_at_host=False, enable_ultra_ssd=False, workload_runtime=None, gpu_instance_profile=None, snapshot_id=None, host_group_id=None, crg_id=None, message_of_the_day=None, no_wait=False): instances = client.list(resource_group_name, cluster_name) for agentpool_profile in instances: if agentpool_profile.name == nodepool_name: raise CLIError("Node pool {} already exists, please try a different name, " "use 'aks nodepool list' to get current list of node pool".format(nodepool_name)) upgradeSettings = AgentPoolUpgradeSettings() taints_array = [] creationData = None if snapshot_id: snapshot = _get_snapshot(cmd.cli_ctx, snapshot_id) if not kubernetes_version: kubernetes_version = snapshot.kubernetes_version if not os_type: os_type = snapshot.os_type if not os_sku: os_sku = snapshot.os_sku if not node_vm_size: node_vm_size = snapshot.vm_size creationData = CreationData( source_resource_id=snapshot_id ) if not os_type: os_type = "Linux" if node_taints is not None: for taint in node_taints.split(','): try: taint = taint.strip() taints_array.append(taint) except ValueError: raise CLIError( 'Taint does not match allowed values. Expect value such as "special=true:NoSchedule".') if node_vm_size is None: if os_type == "Windows": node_vm_size = "Standard_D2s_v3" else: node_vm_size = "Standard_DS2_v2" if max_surge: upgradeSettings.max_surge = max_surge agent_pool = AgentPool( name=nodepool_name, tags=tags, node_labels=labels, count=int(node_count), vm_size=node_vm_size, os_type=os_type, os_sku=os_sku, enable_fips=enable_fips_image, storage_profile=ContainerServiceStorageProfileTypes.managed_disks, vnet_subnet_id=vnet_subnet_id, pod_subnet_id=pod_subnet_id, proximity_placement_group_id=ppg, agent_pool_type="VirtualMachineScaleSets", max_pods=int(max_pods) if max_pods else None, orchestrator_version=kubernetes_version, availability_zones=node_zones, enable_node_public_ip=enable_node_public_ip, node_public_ip_prefix_id=node_public_ip_prefix_id, node_taints=taints_array, scale_set_priority=priority, scale_down_mode=scale_down_mode, upgrade_settings=upgradeSettings, enable_encryption_at_host=enable_encryption_at_host, enable_ultra_ssd=enable_ultra_ssd, mode=mode, workload_runtime=workload_runtime, gpu_instance_profile=gpu_instance_profile, creation_data=creationData, host_group_id=host_group_id, capacity_reservation_group_id=crg_id ) if priority == CONST_SCALE_SET_PRIORITY_SPOT: agent_pool.scale_set_eviction_policy = eviction_policy if isnan(spot_max_price): spot_max_price = -1 agent_pool.spot_max_price = spot_max_price _check_cluster_autoscaler_flag( enable_cluster_autoscaler, min_count, max_count, node_count, agent_pool) if node_osdisk_size: agent_pool.os_disk_size_gb = int(node_osdisk_size) if node_osdisk_type: agent_pool.os_disk_type = node_osdisk_type if kubelet_config: agent_pool.kubelet_config = _get_kubelet_config(kubelet_config) if linux_os_config: agent_pool.linux_os_config = _get_linux_os_config(linux_os_config) if message_of_the_day: agent_pool.message_of_the_day = _get_message_of_the_day( message_of_the_day) headers = get_aks_custom_headers(aks_custom_headers) return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, nodepool_name, agent_pool, headers=headers) def aks_agentpool_scale(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name, node_count=3, no_wait=False): instance = client.get(resource_group_name, cluster_name, nodepool_name) new_node_count = int(node_count) if instance.enable_auto_scaling: raise CLIError("Cannot scale cluster autoscaler enabled node pool.") if new_node_count == instance.count: raise CLIError( "The new node count is the same as the current node count.") instance.count = new_node_count # pylint: disable=no-member return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, nodepool_name, instance) def aks_agentpool_upgrade(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name, kubernetes_version='', no_wait=False, node_image_only=False, max_surge=None, aks_custom_headers=None, snapshot_id=None): if kubernetes_version != '' and node_image_only: raise CLIError('Conflicting flags. Upgrading the Kubernetes version will also upgrade node image version.' 'If you only want to upgrade the node version please use the "--node-image-only" option only.') if node_image_only: return _upgrade_single_nodepool_image_version(no_wait, client, resource_group_name, cluster_name, nodepool_name, snapshot_id) creationData = None if snapshot_id: snapshot = _get_snapshot(cmd.cli_ctx, snapshot_id) if not kubernetes_version and not node_image_only: kubernetes_version = snapshot.kubernetes_version creationData = CreationData( source_resource_id=snapshot_id ) instance = client.get(resource_group_name, cluster_name, nodepool_name) instance.orchestrator_version = kubernetes_version instance.creation_data = creationData if not instance.upgrade_settings: instance.upgrade_settings = AgentPoolUpgradeSettings() if max_surge: instance.upgrade_settings.max_surge = max_surge headers = get_aks_custom_headers(aks_custom_headers) return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, nodepool_name, instance, headers=headers) def aks_agentpool_get_upgrade_profile(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name): return client.get_upgrade_profile(resource_group_name, cluster_name, nodepool_name) def aks_agentpool_update(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name, tags=None, enable_cluster_autoscaler=False, disable_cluster_autoscaler=False, update_cluster_autoscaler=False, scale_down_mode=None, min_count=None, max_count=None, max_surge=None, mode=None, labels=None, node_taints=None, no_wait=False): update_autoscaler = enable_cluster_autoscaler + \ disable_cluster_autoscaler + update_cluster_autoscaler if (update_autoscaler != 1 and not tags and not scale_down_mode and not mode and not max_surge and labels is None and node_taints is None): reconcilePrompt = 'no argument specified to update would you like to reconcile to current settings?' if not prompt_y_n(reconcilePrompt, default="n"): raise CLIError('Please specify one or more of "--enable-cluster-autoscaler" or ' '"--disable-cluster-autoscaler" or ' '"--update-cluster-autoscaler" or ' '"--tags" or "--mode" or "--max-surge" or "--scale-down-mode" or "--labels" or "--node-taints') instance = client.get(resource_group_name, cluster_name, nodepool_name) if node_taints is not None: taints_array = [] if node_taints != '': for taint in node_taints.split(','): try: taint = taint.strip() taints_array.append(taint) except ValueError: raise InvalidArgumentValueError( 'Taint does not match allowed values. Expect value such as "special=true:NoSchedule".') instance.node_taints = taints_array if min_count is None or max_count is None: if enable_cluster_autoscaler or update_cluster_autoscaler: raise CLIError('Please specify both min-count and max-count when --enable-cluster-autoscaler or ' '--update-cluster-autoscaler set.') if min_count is not None and max_count is not None: if int(min_count) > int(max_count): raise CLIError( 'value of min-count should be less than or equal to value of max-count.') if enable_cluster_autoscaler: if instance.enable_auto_scaling: logger.warning('Autoscaler is already enabled for this node pool.\n' 'Please run "az aks nodepool update --update-cluster-autoscaler" ' 'if you want to update min-count or max-count.') return None instance.min_count = int(min_count) instance.max_count = int(max_count) instance.enable_auto_scaling = True if update_cluster_autoscaler: if not instance.enable_auto_scaling: raise CLIError('Autoscaler is not enabled for this node pool.\n' 'Run "az aks nodepool update --enable-cluster-autoscaler" ' 'to enable cluster with min-count and max-count.') instance.min_count = int(min_count) instance.max_count = int(max_count) if not instance.upgrade_settings: instance.upgrade_settings = AgentPoolUpgradeSettings() if max_surge: instance.upgrade_settings.max_surge = max_surge if disable_cluster_autoscaler: if not instance.enable_auto_scaling: logger.warning( 'Autoscaler is already disabled for this node pool.') return None instance.enable_auto_scaling = False instance.min_count = None instance.max_count = None instance.tags = tags if scale_down_mode is not None: instance.scale_down_mode = scale_down_mode if mode is not None: instance.mode = mode if labels is not None: instance.node_labels = labels return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, nodepool_name, instance) def aks_agentpool_stop(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name, aks_custom_headers=None, no_wait=False): agentpool_exists = False instances = client.list(resource_group_name, cluster_name) for agentpool_profile in instances: if agentpool_profile.name.lower() == nodepool_name.lower(): agentpool_exists = True break if not agentpool_exists: raise InvalidArgumentValueError( "Node pool {} doesnt exist, use 'aks nodepool list' to get current node pool list".format(nodepool_name)) instance = client.get(resource_group_name, cluster_name, nodepool_name) power_state = PowerState(code="Stopped") instance.power_state = power_state headers = get_aks_custom_headers(aks_custom_headers) return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, nodepool_name, instance, headers=headers) def aks_agentpool_start(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name, aks_custom_headers=None, no_wait=False): agentpool_exists = False instances = client.list(resource_group_name, cluster_name) for agentpool_profile in instances: if agentpool_profile.name.lower() == nodepool_name.lower(): agentpool_exists = True break if not agentpool_exists: raise InvalidArgumentValueError( "Node pool {} doesnt exist, use 'aks nodepool list' to get current node pool list".format(nodepool_name)) instance = client.get(resource_group_name, cluster_name, nodepool_name) power_state = PowerState(code="Running") instance.power_state = power_state headers = get_aks_custom_headers(aks_custom_headers) return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, nodepool_name, instance, headers=headers) def aks_agentpool_delete(cmd, # pylint: disable=unused-argument client, resource_group_name, cluster_name, nodepool_name, ignore_pod_disruption_budget=None, no_wait=False): agentpool_exists = False instances = client.list(resource_group_name, cluster_name) for agentpool_profile in instances: if agentpool_profile.name.lower() == nodepool_name.lower(): agentpool_exists = True break if not agentpool_exists: raise CLIError("Node pool {} doesnt exist, " "use 'aks nodepool list' to get current node pool list".format(nodepool_name)) return sdk_no_wait(no_wait, client.begin_delete, resource_group_name, cluster_name, nodepool_name, ignore_pod_disruption_budget=ignore_pod_disruption_budget) def aks_addon_list_available(): available_addons = [] for k, v in ADDONS.items(): available_addons.append({ "name": k, "description": ADDONS_DESCRIPTIONS[v] }) return available_addons def aks_addon_list(cmd, client, resource_group_name, name): # pylint: disable=unused-argument addon_profiles = client.get(resource_group_name, name).addon_profiles current_addons = [] for name, addon in ADDONS.items(): if not addon_profiles or addon not in addon_profiles: current_addons.append({ "name": name, "api_key": addon, "enabled": False }) else: current_addons.append({ "name": name, "api_key": addon, "enabled": addon_profiles[addon].enabled }) return current_addons def aks_addon_show(cmd, client, resource_group_name, name, addon): # pylint: disable=unused-argument addon_profiles = client.get(resource_group_name, name).addon_profiles addon_key = ADDONS[addon] if not addon_profiles or addon_key not in addon_profiles or not addon_profiles[addon_key].enabled: raise CLIError(f'Addon "{addon}" is not enabled in this cluster.') return { "name": addon, "api_key": addon_key, "config": addon_profiles[addon_key].config, "identity": addon_profiles[addon_key].identity } def aks_addon_enable(cmd, client, resource_group_name, name, addon, workspace_resource_id=None, subnet_name=None, appgw_name=None, appgw_subnet_prefix=None, appgw_subnet_cidr=None, appgw_id=None, appgw_subnet_id=None, appgw_watch_namespace=None, enable_sgxquotehelper=False, enable_secret_rotation=False, rotation_poll_interval=None, no_wait=False, enable_msi_auth_for_monitoring=False): return enable_addons(cmd, client, resource_group_name, name, addon, workspace_resource_id=workspace_resource_id, subnet_name=subnet_name, appgw_name=appgw_name, appgw_subnet_prefix=appgw_subnet_prefix, appgw_subnet_cidr=appgw_subnet_cidr, appgw_id=appgw_id, appgw_subnet_id=appgw_subnet_id, appgw_watch_namespace=appgw_watch_namespace, enable_sgxquotehelper=enable_sgxquotehelper, enable_secret_rotation=enable_secret_rotation, rotation_poll_interval=rotation_poll_interval, no_wait=no_wait, enable_msi_auth_for_monitoring=enable_msi_auth_for_monitoring) def aks_addon_disable(cmd, client, resource_group_name, name, addon, no_wait=False): return aks_disable_addons(cmd, client, resource_group_name, name, addon, no_wait) def aks_addon_update(cmd, client, resource_group_name, name, addon, workspace_resource_id=None, subnet_name=None, appgw_name=None, appgw_subnet_prefix=None, appgw_subnet_cidr=None, appgw_id=None, appgw_subnet_id=None, appgw_watch_namespace=None, enable_sgxquotehelper=False, enable_secret_rotation=False, rotation_poll_interval=None, no_wait=False, enable_msi_auth_for_monitoring=False): addon_profiles = client.get(resource_group_name, name).addon_profiles addon_key = ADDONS[addon] if not addon_profiles or addon_key not in addon_profiles or not addon_profiles[addon_key].enabled: raise CLIError(f'Addon "{addon}" is not enabled in this cluster.') return enable_addons(cmd, client, resource_group_name, name, addon, check_enabled=False, workspace_resource_id=workspace_resource_id, subnet_name=subnet_name, appgw_name=appgw_name, appgw_subnet_prefix=appgw_subnet_prefix, appgw_subnet_cidr=appgw_subnet_cidr, appgw_id=appgw_id, appgw_subnet_id=appgw_subnet_id, appgw_watch_namespace=appgw_watch_namespace, enable_sgxquotehelper=enable_sgxquotehelper, enable_secret_rotation=enable_secret_rotation, rotation_poll_interval=rotation_poll_interval, no_wait=no_wait, enable_msi_auth_for_monitoring=enable_msi_auth_for_monitoring) def aks_disable_addons(cmd, client, resource_group_name, name, addons, no_wait=False): instance = client.get(resource_group_name, name) subscription_id = get_subscription_id(cmd.cli_ctx) try: if addons == "monitoring" and CONST_MONITORING_ADDON_NAME in instance.addon_profiles and \ instance.addon_profiles[CONST_MONITORING_ADDON_NAME].enabled and \ CONST_MONITORING_USING_AAD_MSI_AUTH in instance.addon_profiles[CONST_MONITORING_ADDON_NAME].config and \ str(instance.addon_profiles[CONST_MONITORING_ADDON_NAME].config[CONST_MONITORING_USING_AAD_MSI_AUTH]).lower() == 'true': # remove the DCR association because otherwise the DCR can't be deleted ensure_container_insights_for_monitoring( cmd, instance.addon_profiles[CONST_MONITORING_ADDON_NAME], subscription_id, resource_group_name, name, instance.location, remove_monitoring=True, aad_route=True, create_dcr=False, create_dcra=True ) except TypeError: pass instance = _update_addons( cmd, instance, subscription_id, resource_group_name, name, addons, enable=False, no_wait=no_wait ) # send the managed cluster representation to update the addon profiles return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, name, instance) def aks_enable_addons(cmd, client, resource_group_name, name, addons, workspace_resource_id=None, subnet_name=None, appgw_name=None, appgw_subnet_prefix=None, appgw_subnet_cidr=None, appgw_id=None, appgw_subnet_id=None, appgw_watch_namespace=None, enable_sgxquotehelper=False, enable_secret_rotation=False, rotation_poll_interval=None, no_wait=False, enable_msi_auth_for_monitoring=False): instance = client.get(resource_group_name, name) # this is overwritten by _update_addons(), so the value needs to be recorded here msi_auth = True if instance.service_principal_profile.client_id == "msi" else False subscription_id = get_subscription_id(cmd.cli_ctx) instance = _update_addons(cmd, instance, subscription_id, resource_group_name, name, addons, enable=True, workspace_resource_id=workspace_resource_id, enable_msi_auth_for_monitoring=enable_msi_auth_for_monitoring, subnet_name=subnet_name, appgw_name=appgw_name, appgw_subnet_prefix=appgw_subnet_prefix, appgw_subnet_cidr=appgw_subnet_cidr, appgw_id=appgw_id, appgw_subnet_id=appgw_subnet_id, appgw_watch_namespace=appgw_watch_namespace, enable_sgxquotehelper=enable_sgxquotehelper, enable_secret_rotation=enable_secret_rotation, rotation_poll_interval=rotation_poll_interval, no_wait=no_wait) if CONST_MONITORING_ADDON_NAME in instance.addon_profiles and instance.addon_profiles[CONST_MONITORING_ADDON_NAME].enabled: if CONST_MONITORING_USING_AAD_MSI_AUTH in instance.addon_profiles[CONST_MONITORING_ADDON_NAME].config and \ str(instance.addon_profiles[CONST_MONITORING_ADDON_NAME].config[CONST_MONITORING_USING_AAD_MSI_AUTH]).lower() == 'true': if not msi_auth: raise ArgumentUsageError( "--enable-msi-auth-for-monitoring can not be used on clusters with service principal auth.") else: # create a Data Collection Rule (DCR) and associate it with the cluster ensure_container_insights_for_monitoring( cmd, instance.addon_profiles[CONST_MONITORING_ADDON_NAME], subscription_id, resource_group_name, name, instance.location, aad_route=True, create_dcr=True, create_dcra=True) else: # monitoring addon will use legacy path ensure_container_insights_for_monitoring( cmd, instance.addon_profiles[CONST_MONITORING_ADDON_NAME], subscription_id, resource_group_name, name, instance.location, aad_route=False) monitoring = CONST_MONITORING_ADDON_NAME in instance.addon_profiles and instance.addon_profiles[ CONST_MONITORING_ADDON_NAME].enabled ingress_appgw_addon_enabled = CONST_INGRESS_APPGW_ADDON_NAME in instance.addon_profiles and instance.addon_profiles[ CONST_INGRESS_APPGW_ADDON_NAME].enabled os_type = 'Linux' enable_virtual_node = False if CONST_VIRTUAL_NODE_ADDON_NAME + os_type in instance.addon_profiles: enable_virtual_node = True need_post_creation_role_assignment = monitoring or ingress_appgw_addon_enabled or enable_virtual_node if need_post_creation_role_assignment: # adding a wait here since we rely on the result for role assignment result = LongRunningOperation(cmd.cli_ctx)( client.begin_create_or_update(resource_group_name, name, instance)) cloud_name = cmd.cli_ctx.cloud.name # mdm metrics supported only in Azure Public cloud so add the role assignment only in this cloud if monitoring and cloud_name.lower() == 'azurecloud': from msrestazure.tools import resource_id cluster_resource_id = resource_id( subscription=subscription_id, resource_group=resource_group_name, namespace='Microsoft.ContainerService', type='managedClusters', name=name ) add_monitoring_role_assignment(result, cluster_resource_id, cmd) if ingress_appgw_addon_enabled: add_ingress_appgw_addon_role_assignment(result, cmd) if enable_virtual_node: # All agent pool will reside in the same vnet, we will grant vnet level Contributor role # in later function, so using a random agent pool here is OK random_agent_pool = result.agent_pool_profiles[0] if random_agent_pool.vnet_subnet_id != "": add_virtual_node_role_assignment( cmd, result, random_agent_pool.vnet_subnet_id) # Else, the cluster is not using custom VNet, the permission is already granted in AKS RP, # we don't need to handle it in client side in this case. else: result = sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, name, instance) return result def aks_rotate_certs(cmd, client, resource_group_name, name, no_wait=True): # pylint: disable=unused-argument return sdk_no_wait(no_wait, client.begin_rotate_cluster_certificates, resource_group_name, name) def _update_addons(cmd, # pylint: disable=too-many-branches,too-many-statements instance, subscription_id, resource_group_name, name, addons, enable, workspace_resource_id=None, enable_msi_auth_for_monitoring=False, subnet_name=None, appgw_name=None, appgw_subnet_prefix=None, appgw_subnet_cidr=None, appgw_id=None, appgw_subnet_id=None, appgw_watch_namespace=None, enable_sgxquotehelper=False, enable_secret_rotation=False, disable_secret_rotation=False, rotation_poll_interval=None, no_wait=False): # pylint: disable=unused-argument # parse the comma-separated addons argument addon_args = addons.split(',') addon_profiles = instance.addon_profiles or {} os_type = 'Linux' # for each addons argument for addon_arg in addon_args: if addon_arg not in ADDONS: raise CLIError("Invalid addon name: {}.".format(addon_arg)) addon = ADDONS[addon_arg] if addon == CONST_VIRTUAL_NODE_ADDON_NAME: # only linux is supported for now, in the future this will be a user flag addon += os_type # honor addon names defined in Azure CLI for key in list(addon_profiles): if key.lower() == addon.lower() and key != addon: addon_profiles[addon] = addon_profiles.pop(key) if enable: # add new addons or update existing ones and enable them addon_profile = addon_profiles.get( addon, ManagedClusterAddonProfile(enabled=False)) # special config handling for certain addons if addon == CONST_MONITORING_ADDON_NAME: logAnalyticsConstName = CONST_MONITORING_LOG_ANALYTICS_WORKSPACE_RESOURCE_ID if addon_profile.enabled: raise CLIError('The monitoring addon is already enabled for this managed cluster.\n' 'To change monitoring configuration, run "az aks disable-addons -a monitoring"' 'before enabling it again.') if not workspace_resource_id: workspace_resource_id = ensure_default_log_analytics_workspace_for_monitoring( cmd, subscription_id, resource_group_name) workspace_resource_id = sanitize_loganalytics_ws_resource_id( workspace_resource_id) addon_profile.config = { logAnalyticsConstName: workspace_resource_id} addon_profile.config[CONST_MONITORING_USING_AAD_MSI_AUTH] = enable_msi_auth_for_monitoring elif addon == (CONST_VIRTUAL_NODE_ADDON_NAME + os_type): if addon_profile.enabled: raise CLIError('The virtual-node addon is already enabled for this managed cluster.\n' 'To change virtual-node configuration, run ' '"az aks disable-addons -a virtual-node -g {resource_group_name}" ' 'before enabling it again.') if not subnet_name: raise CLIError( 'The aci-connector addon requires setting a subnet name.') addon_profile.config = { CONST_VIRTUAL_NODE_SUBNET_NAME: subnet_name} elif addon == CONST_INGRESS_APPGW_ADDON_NAME: if addon_profile.enabled: raise CLIError('The ingress-appgw addon is already enabled for this managed cluster.\n' 'To change ingress-appgw configuration, run ' f'"az aks disable-addons -a ingress-appgw -n {name} -g {resource_group_name}" ' 'before enabling it again.') addon_profile = ManagedClusterAddonProfile( enabled=True, config={}) if appgw_name is not None: addon_profile.config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_NAME] = appgw_name if appgw_subnet_prefix is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_CIDR] = appgw_subnet_prefix if appgw_subnet_cidr is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_CIDR] = appgw_subnet_cidr if appgw_id is not None: addon_profile.config[CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID] = appgw_id if appgw_subnet_id is not None: addon_profile.config[CONST_INGRESS_APPGW_SUBNET_ID] = appgw_subnet_id if appgw_watch_namespace is not None: addon_profile.config[CONST_INGRESS_APPGW_WATCH_NAMESPACE] = appgw_watch_namespace elif addon == CONST_OPEN_SERVICE_MESH_ADDON_NAME: if addon_profile.enabled: raise CLIError('The open-service-mesh addon is already enabled for this managed cluster.\n' 'To change open-service-mesh configuration, run ' f'"az aks disable-addons -a open-service-mesh -n {name} -g {resource_group_name}" ' 'before enabling it again.') addon_profile = ManagedClusterAddonProfile( enabled=True, config={}) elif addon == CONST_CONFCOM_ADDON_NAME: if addon_profile.enabled: raise CLIError('The confcom addon is already enabled for this managed cluster.\n' 'To change confcom configuration, run ' f'"az aks disable-addons -a confcom -n {name} -g {resource_group_name}" ' 'before enabling it again.') addon_profile = ManagedClusterAddonProfile( enabled=True, config={CONST_ACC_SGX_QUOTE_HELPER_ENABLED: "false"}) if enable_sgxquotehelper: addon_profile.config[CONST_ACC_SGX_QUOTE_HELPER_ENABLED] = "true" elif addon == CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME: if addon_profile.enabled: raise CLIError('The azure-keyvault-secrets-provider addon is already enabled for this managed cluster.\n' 'To change azure-keyvault-secrets-provider configuration, run ' f'"az aks disable-addons -a azure-keyvault-secrets-provider -n {name} -g {resource_group_name}" ' 'before enabling it again.') addon_profile = ManagedClusterAddonProfile( enabled=True, config={CONST_SECRET_ROTATION_ENABLED: "false", CONST_ROTATION_POLL_INTERVAL: "2m"}) if enable_secret_rotation: addon_profile.config[CONST_SECRET_ROTATION_ENABLED] = "true" if disable_secret_rotation: addon_profile.config[CONST_SECRET_ROTATION_ENABLED] = "false" if rotation_poll_interval is not None: addon_profile.config[CONST_ROTATION_POLL_INTERVAL] = rotation_poll_interval addon_profiles[CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME] = addon_profile addon_profiles[addon] = addon_profile else: if addon not in addon_profiles: if addon == CONST_KUBE_DASHBOARD_ADDON_NAME: addon_profiles[addon] = ManagedClusterAddonProfile( enabled=False) else: raise CLIError( "The addon {} is not installed.".format(addon)) addon_profiles[addon].config = None addon_profiles[addon].enabled = enable instance.addon_profiles = addon_profiles # null out the SP profile because otherwise validation complains instance.service_principal_profile = None return instance def aks_get_versions(cmd, client, location): # pylint: disable=unused-argument return client.list_orchestrators(location, resource_type='managedClusters') def aks_get_os_options(cmd, client, location): # pylint: disable=unused-argument return client.get_os_options(location, resource_type='managedClusters') def _print_or_merge_credentials(path, kubeconfig, overwrite_existing, context_name): """Merge an unencrypted kubeconfig into the file at the specified path, or print it to stdout if the path is "-". """ # Special case for printing to stdout if path == "-": print(kubeconfig) return # ensure that at least an empty ~/.kube/config exists directory = os.path.dirname(path) if directory and not os.path.exists(directory): try: os.makedirs(directory) except OSError as ex: if ex.errno != errno.EEXIST: raise if not os.path.exists(path): with os.fdopen(os.open(path, os.O_CREAT | os.O_WRONLY, 0o600), 'wt'): pass # merge the new kubeconfig into the existing one fd, temp_path = tempfile.mkstemp() additional_file = os.fdopen(fd, 'w+t') try: additional_file.write(kubeconfig) additional_file.flush() merge_kubernetes_configurations( path, temp_path, overwrite_existing, context_name) except yaml.YAMLError as ex: logger.warning( 'Failed to merge credentials to kube config file: %s', ex) finally: additional_file.close() os.remove(temp_path) def _handle_merge(existing, addition, key, replace): if not addition[key]: return if existing[key] is None: existing[key] = addition[key] return for i in addition[key]: for j in existing[key]: if i['name'] == j['name']: if replace or i == j: existing[key].remove(j) else: from knack.prompting import prompt_y_n msg = 'A different object named {} already exists in your kubeconfig file.\nOverwrite?' overwrite = False try: overwrite = prompt_y_n(msg.format(i['name'])) except NoTTYException: pass if overwrite: existing[key].remove(j) else: msg = 'A different object named {} already exists in {} in your kubeconfig file.' raise CLIError(msg.format(i['name'], key)) existing[key].append(i) def load_kubernetes_configuration(filename): try: with open(filename) as stream: return yaml.safe_load(stream) except (IOError, OSError) as ex: if getattr(ex, 'errno', 0) == errno.ENOENT: raise CLIError('{} does not exist'.format(filename)) except (yaml.parser.ParserError, UnicodeDecodeError) as ex: raise CLIError('Error parsing {} ({})'.format(filename, str(ex))) def merge_kubernetes_configurations(existing_file, addition_file, replace, context_name=None): existing = load_kubernetes_configuration(existing_file) addition = load_kubernetes_configuration(addition_file) if context_name is not None: addition['contexts'][0]['name'] = context_name addition['contexts'][0]['context']['cluster'] = context_name addition['clusters'][0]['name'] = context_name addition['current-context'] = context_name # rename the admin context so it doesn't overwrite the user context for ctx in addition.get('contexts', []): try: if ctx['context']['user'].startswith('clusterAdmin'): admin_name = ctx['name'] + '-admin' addition['current-context'] = ctx['name'] = admin_name break except (KeyError, TypeError): continue if addition is None: raise CLIError( 'failed to load additional configuration from {}'.format(addition_file)) if existing is None: existing = addition else: _handle_merge(existing, addition, 'clusters', replace) _handle_merge(existing, addition, 'users', replace) _handle_merge(existing, addition, 'contexts', replace) existing['current-context'] = addition['current-context'] # check that ~/.kube/config is only read- and writable by its owner if platform.system() != 'Windows': existing_file_perms = "{:o}".format( stat.S_IMODE(os.lstat(existing_file).st_mode)) if not existing_file_perms.endswith('600'): logger.warning('%s has permissions "%s".\nIt should be readable and writable only by its owner.', existing_file, existing_file_perms) with open(existing_file, 'w+') as stream: yaml.safe_dump(existing, stream, default_flow_style=False) current_context = addition.get('current-context', 'UNKNOWN') msg = 'Merged "{}" as current context in {}'.format( current_context, existing_file) print(msg) def cloud_storage_account_service_factory(cli_ctx, kwargs): from azure.cli.core.profiles import ResourceType, get_sdk t_cloud_storage_account = get_sdk( cli_ctx, ResourceType.DATA_STORAGE, 'common#CloudStorageAccount') account_name = kwargs.pop('account_name', None) account_key = kwargs.pop('account_key', None) sas_token = kwargs.pop('sas_token', None) kwargs.pop('connection_string', None) return t_cloud_storage_account(account_name, account_key, sas_token) def get_storage_account_from_diag_settings(cli_ctx, resource_group_name, name): from azure.mgmt.monitor import MonitorManagementClient diag_settings_client = get_mgmt_service_client( cli_ctx, MonitorManagementClient).diagnostic_settings subscription_id = get_subscription_id(cli_ctx) aks_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.ContainerService' \ '/managedClusters/{2}'.format(subscription_id, resource_group_name, name) diag_settings = diag_settings_client.list(aks_resource_id) for _, diag_setting in enumerate(diag_settings): if diag_setting: return diag_setting.storage_account_id print("No diag settings specified") return None def display_diagnostics_report(temp_kubeconfig_path): # pylint: disable=too-many-statements if not which('kubectl'): raise CLIError('Can not find kubectl executable in PATH') nodes = subprocess.check_output( ["kubectl", "--kubeconfig", temp_kubeconfig_path, "get", "node", "--no-headers"], universal_newlines=True) logger.debug(nodes) node_lines = nodes.splitlines() ready_nodes = {} for node_line in node_lines: columns = node_line.split() logger.debug(node_line) if columns[1] != "Ready": logger.warning( "Node %s is not Ready. Current state is: %s.", columns[0], columns[1]) else: ready_nodes[columns[0]] = False logger.debug('There are %s ready nodes in the cluster', str(len(ready_nodes))) if not ready_nodes: logger.warning( 'No nodes are ready in the current cluster. Diagnostics info might not be available.') network_config_array = [] network_status_array = [] apds_created = False max_retry = 10 for retry in range(0, max_retry): if not apds_created: apd = subprocess.check_output( ["kubectl", "--kubeconfig", temp_kubeconfig_path, "get", "apd", "-n", "aks-periscope", "--no-headers"], universal_newlines=True ) apd_lines = apd.splitlines() if apd_lines and 'No resources found' in apd_lines[0]: apd_lines.pop(0) print("Got {} diagnostic results for {} ready nodes{}\r".format(len(apd_lines), len(ready_nodes), '.' * retry), end='') if len(apd_lines) < len(ready_nodes): time.sleep(3) else: apds_created = True print() else: for node_name in ready_nodes: if ready_nodes[node_name]: continue apdName = "aks-periscope-diagnostic-" + node_name try: network_config = subprocess.check_output( ["kubectl", "--kubeconfig", temp_kubeconfig_path, "get", "apd", apdName, "-n", "aks-periscope", "-o=jsonpath={.spec.networkconfig}"], universal_newlines=True) logger.debug('Dns status for node %s is %s', node_name, network_config) network_status = subprocess.check_output( ["kubectl", "--kubeconfig", temp_kubeconfig_path, "get", "apd", apdName, "-n", "aks-periscope", "-o=jsonpath={.spec.networkoutbound}"], universal_newlines=True) logger.debug('Network status for node %s is %s', node_name, network_status) if not network_config or not network_status: print("The diagnostics information for node {} is not ready yet. " "Will try again in 10 seconds.".format(node_name)) time.sleep(10) break network_config_array += json.loads( '[' + network_config + ']') network_status_object = json.loads(network_status) network_status_array += format_diag_status( network_status_object) ready_nodes[node_name] = True except subprocess.CalledProcessError as err: raise CLIError(err.output) print() if network_config_array: print("Below are the network configuration for each node: ") print() print(tabulate(network_config_array, headers="keys", tablefmt='simple')) print() else: logger.warning("Could not get network config. " "Please run 'az aks kanalyze' command later to get the analysis results.") if network_status_array: print("Below are the network connectivity results for each node:") print() print(tabulate(network_status_array, headers="keys", tablefmt='simple')) else: logger.warning("Could not get networking status. " "Please run 'az aks kanalyze' command later to get the analysis results.") def format_diag_status(diag_status): for diag in diag_status: if diag["Status"]: if "Error:" in diag["Status"]: diag["Status"] = f'{colorama.Fore.RED}{diag["Status"]}{colorama.Style.RESET_ALL}' else: diag["Status"] = f'{colorama.Fore.GREEN}{diag["Status"]}{colorama.Style.RESET_ALL}' return diag_status def format_bright(msg): return f'\033[1m{colorama.Style.BRIGHT}{msg}{colorama.Style.RESET_ALL}' def format_hyperlink(the_link): return f'\033[1m{colorama.Style.BRIGHT}{colorama.Fore.BLUE}{the_link}{colorama.Style.RESET_ALL}' def get_aks_custom_headers(aks_custom_headers=None): headers = {} if aks_custom_headers is not None: if aks_custom_headers != "": for pair in aks_custom_headers.split(','): parts = pair.split('=') if len(parts) != 2: raise CLIError('custom headers format is incorrect') headers[parts[0]] = parts[1] return headers def _put_managed_cluster_ensuring_permission( cmd, # pylint: disable=too-many-locals,too-many-statements,too-many-branches client, subscription_id, resource_group_name, name, managed_cluster, monitoring_addon_enabled, ingress_appgw_addon_enabled, virtual_node_addon_enabled, need_grant_vnet_permission_to_cluster_identity, vnet_subnet_id, enable_managed_identity, attach_acr, headers, no_wait ): # some addons require post cluster creation role assigment need_post_creation_role_assignment = (monitoring_addon_enabled or ingress_appgw_addon_enabled or (enable_managed_identity and attach_acr) or virtual_node_addon_enabled or need_grant_vnet_permission_to_cluster_identity) if need_post_creation_role_assignment: # adding a wait here since we rely on the result for role assignment cluster = LongRunningOperation(cmd.cli_ctx)(client.begin_create_or_update( resource_group_name=resource_group_name, resource_name=name, parameters=managed_cluster, headers=headers)) cloud_name = cmd.cli_ctx.cloud.name # add cluster spn/msi Monitoring Metrics Publisher role assignment to publish metrics to MDM # mdm metrics is supported only in azure public cloud, so add the role assignment only in this cloud if monitoring_addon_enabled and cloud_name.lower() == 'azurecloud': from msrestazure.tools import resource_id cluster_resource_id = resource_id( subscription=subscription_id, resource_group=resource_group_name, namespace='Microsoft.ContainerService', type='managedClusters', name=name ) add_monitoring_role_assignment(cluster, cluster_resource_id, cmd) if ingress_appgw_addon_enabled: add_ingress_appgw_addon_role_assignment(cluster, cmd) if virtual_node_addon_enabled: add_virtual_node_role_assignment(cmd, cluster, vnet_subnet_id) if need_grant_vnet_permission_to_cluster_identity: if not create_role_assignment(cmd.cli_ctx, 'Network Contributor', cluster.identity.principal_id, scope=vnet_subnet_id, resolve_assignee=False): logger.warning('Could not create a role assignment for subnet. ' 'Are you an Owner on this subscription?') if enable_managed_identity and attach_acr: # Attach ACR to cluster enabled managed identity if cluster.identity_profile is None or \ cluster.identity_profile["kubeletidentity"] is None: logger.warning('Your cluster is successfully created, but we failed to attach ' 'acr to it, you can manually grant permission to the identity ' 'named <ClUSTER_NAME>-agentpool in MC_ resource group to give ' 'it permission to pull from ACR.') else: kubelet_identity_client_id = cluster.identity_profile["kubeletidentity"].client_id _ensure_aks_acr(cmd.cli_ctx, client_id=kubelet_identity_client_id, acr_name_or_id=attach_acr, subscription_id=subscription_id) else: cluster = sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name=resource_group_name, resource_name=name, parameters=managed_cluster, headers=headers) return cluster def _is_msi_cluster(managed_cluster): return (managed_cluster and managed_cluster.identity and (managed_cluster.identity.type.casefold() == "systemassigned" or managed_cluster.identity.type.casefold() == "userassigned")) def _get_message_of_the_day(file_path): if not os.path.isfile(file_path): raise CLIError( "{} is not valid file, or not accessable.".format(file_path)) content = read_file_content(file_path) if not content: raise ArgumentUsageError( "message of the day should point to a non-empty file if specified.") content = base64.b64encode(bytes(content, 'ascii')).decode('ascii') return content def _get_kubelet_config(file_path): if not os.path.isfile(file_path): raise CLIError( "{} is not valid file, or not accessable.".format(file_path)) kubelet_config = get_file_json(file_path) if not isinstance(kubelet_config, dict): raise CLIError( "Error reading kubelet configuration at {}. Please see https://aka.ms/CustomNodeConfig for correct format.".format(file_path)) config_object = KubeletConfig() config_object.cpu_manager_policy = kubelet_config.get( "cpuManagerPolicy", None) config_object.cpu_cfs_quota = kubelet_config.get("cpuCfsQuota", None) config_object.cpu_cfs_quota_period = kubelet_config.get( "cpuCfsQuotaPeriod", None) config_object.image_gc_high_threshold = kubelet_config.get( "imageGcHighThreshold", None) config_object.image_gc_low_threshold = kubelet_config.get( "imageGcLowThreshold", None) config_object.topology_manager_policy = kubelet_config.get( "topologyManagerPolicy", None) config_object.allowed_unsafe_sysctls = kubelet_config.get( "allowedUnsafeSysctls", None) config_object.fail_swap_on = kubelet_config.get("failSwapOn", None) config_object.container_log_max_files = kubelet_config.get( "containerLogMaxFiles", None) config_object.container_log_max_size_mb = kubelet_config.get( "containerLogMaxSizeMB", None) config_object.pod_max_pids = kubelet_config.get( "podMaxPids", None) return config_object def _get_linux_os_config(file_path): if not os.path.isfile(file_path): raise CLIError( "{} is not valid file, or not accessable.".format(file_path)) os_config = get_file_json(file_path) if not isinstance(os_config, dict): raise CLIError( "Error reading Linux OS configuration at {}. Please see https://aka.ms/CustomNodeConfig for correct format.".format(file_path)) config_object = LinuxOSConfig() config_object.transparent_huge_page_enabled = os_config.get( "transparentHugePageEnabled", None) config_object.transparent_huge_page_defrag = os_config.get( "transparentHugePageDefrag", None) config_object.swap_file_size_mb = os_config.get("swapFileSizeMB", None) # sysctl settings sysctls = os_config.get("sysctls", None) if not isinstance(sysctls, dict): raise CLIError( "Error reading Sysctl settings at {}. Please see https://aka.ms/CustomNodeConfig for correct format.".format(file_path)) config_object.sysctls = SysctlConfig() config_object.sysctls.net_core_somaxconn = sysctls.get( "netCoreSomaxconn", None) config_object.sysctls.net_core_netdev_max_backlog = sysctls.get( "netCoreNetdevMaxBacklog", None) config_object.sysctls.net_core_rmem_max = sysctls.get( "netCoreRmemMax", None) config_object.sysctls.net_core_wmem_max = sysctls.get( "netCoreWmemMax", None) config_object.sysctls.net_core_optmem_max = sysctls.get( "netCoreOptmemMax", None) config_object.sysctls.net_ipv4_tcp_max_syn_backlog = sysctls.get( "netIpv4TcpMaxSynBacklog", None) config_object.sysctls.net_ipv4_tcp_max_tw_buckets = sysctls.get( "netIpv4TcpMaxTwBuckets", None) config_object.sysctls.net_ipv4_tcp_fin_timeout = sysctls.get( "netIpv4TcpFinTimeout", None) config_object.sysctls.net_ipv4_tcp_keepalive_time = sysctls.get( "netIpv4TcpKeepaliveTime", None) config_object.sysctls.net_ipv4_tcp_keepalive_probes = sysctls.get( "netIpv4TcpKeepaliveProbes", None) config_object.sysctls.net_ipv4_tcpkeepalive_intvl = sysctls.get( "netIpv4TcpkeepaliveIntvl", None) config_object.sysctls.net_ipv4_tcp_rmem = sysctls.get( "netIpv4TcpRmem", None) config_object.sysctls.net_ipv4_tcp_wmem = sysctls.get( "netIpv4TcpWmem", None) config_object.sysctls.net_ipv4_tcp_tw_reuse = sysctls.get( "netIpv4TcpTwReuse", None) config_object.sysctls.net_ipv4_ip_local_port_range = sysctls.get( "netIpv4IpLocalPortRange", None) config_object.sysctls.net_ipv4_neigh_default_gc_thresh1 = sysctls.get( "netIpv4NeighDefaultGcThresh1", None) config_object.sysctls.net_ipv4_neigh_default_gc_thresh2 = sysctls.get( "netIpv4NeighDefaultGcThresh2", None) config_object.sysctls.net_ipv4_neigh_default_gc_thresh3 = sysctls.get( "netIpv4NeighDefaultGcThresh3", None) config_object.sysctls.net_netfilter_nf_conntrack_max = sysctls.get( "netNetfilterNfConntrackMax", None) config_object.sysctls.net_netfilter_nf_conntrack_buckets = sysctls.get( "netNetfilterNfConntrackBuckets", None) config_object.sysctls.fs_inotify_max_user_watches = sysctls.get( "fsInotifyMaxUserWatches", None) config_object.sysctls.fs_file_max = sysctls.get("fsFileMax", None) config_object.sysctls.fs_aio_max_nr = sysctls.get("fsAioMaxNr", None) config_object.sysctls.fs_nr_open = sysctls.get("fsNrOpen", None) config_object.sysctls.kernel_threads_max = sysctls.get( "kernelThreadsMax", None) config_object.sysctls.vm_max_map_count = sysctls.get("vmMaxMapCount", None) config_object.sysctls.vm_swappiness = sysctls.get("vmSwappiness", None) config_object.sysctls.vm_vfs_cache_pressure = sysctls.get( "vmVfsCachePressure", None) return config_object def _get_http_proxy_config(file_path): if not os.path.isfile(file_path): raise CLIError( "{} is not valid file, or not accessable.".format(file_path)) hp_config = get_file_json(file_path) if not isinstance(hp_config, dict): raise CLIError( "Error reading Http Proxy Config at {}. Please see https://aka.ms/HttpProxyConfig for correct format.".format(file_path)) config_object = ManagedClusterHTTPProxyConfig() config_object.http_proxy = hp_config.get("httpProxy", None) config_object.https_proxy = hp_config.get("httpsProxy", None) config_object.no_proxy = hp_config.get("noProxy", None) config_object.trusted_ca = hp_config.get("trustedCa", None) return config_object def aks_pod_identity_add(cmd, client, resource_group_name, cluster_name, identity_name, identity_namespace, identity_resource_id, binding_selector=None, no_wait=False): # pylint: disable=unused-argument instance = client.get(resource_group_name, cluster_name) _ensure_pod_identity_addon_is_enabled(instance) user_assigned_identity = _get_user_assigned_identity( cmd.cli_ctx, identity_resource_id) _ensure_managed_identity_operator_permission( cmd.cli_ctx, instance, user_assigned_identity.id) pod_identities = [] if instance.pod_identity_profile.user_assigned_identities: pod_identities = instance.pod_identity_profile.user_assigned_identities pod_identity = ManagedClusterPodIdentity( name=identity_name, namespace=identity_namespace, identity=UserAssignedIdentity( resource_id=user_assigned_identity.id, client_id=user_assigned_identity.client_id, object_id=user_assigned_identity.principal_id, ) ) if binding_selector is not None: pod_identity.binding_selector = binding_selector pod_identities.append(pod_identity) from azext_aks_preview.decorator import AKSPreviewModels # store all the models used by pod identity pod_identity_models = AKSPreviewModels( cmd, CUSTOM_MGMT_AKS_PREVIEW).pod_identity_models _update_addon_pod_identity( instance, enable=True, pod_identities=pod_identities, pod_identity_exceptions=instance.pod_identity_profile.user_assigned_identity_exceptions, models=pod_identity_models ) # send the managed cluster represeentation to update the pod identity addon return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, instance) def aks_pod_identity_delete(cmd, client, resource_group_name, cluster_name, identity_name, identity_namespace, no_wait=False): # pylint: disable=unused-argument instance = client.get(resource_group_name, cluster_name) _ensure_pod_identity_addon_is_enabled(instance) pod_identities = [] if instance.pod_identity_profile.user_assigned_identities: for pod_identity in instance.pod_identity_profile.user_assigned_identities: if pod_identity.name == identity_name and pod_identity.namespace == identity_namespace: # to remove continue pod_identities.append(pod_identity) from azext_aks_preview.decorator import AKSPreviewModels # store all the models used by pod identity pod_identity_models = AKSPreviewModels( cmd, CUSTOM_MGMT_AKS_PREVIEW).pod_identity_models _update_addon_pod_identity( instance, enable=True, pod_identities=pod_identities, pod_identity_exceptions=instance.pod_identity_profile.user_assigned_identity_exceptions, models=pod_identity_models ) # send the managed cluster represeentation to update the pod identity addon return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, instance) def aks_pod_identity_list(cmd, client, resource_group_name, cluster_name): # pylint: disable=unused-argument instance = client.get(resource_group_name, cluster_name) return _remove_nulls([instance])[0] def aks_pod_identity_exception_add(cmd, client, resource_group_name, cluster_name, exc_name, exc_namespace, pod_labels, no_wait=False): # pylint: disable=unused-argument instance = client.get(resource_group_name, cluster_name) _ensure_pod_identity_addon_is_enabled(instance) pod_identity_exceptions = [] if instance.pod_identity_profile.user_assigned_identity_exceptions: pod_identity_exceptions = instance.pod_identity_profile.user_assigned_identity_exceptions exc = ManagedClusterPodIdentityException( name=exc_name, namespace=exc_namespace, pod_labels=pod_labels) pod_identity_exceptions.append(exc) from azext_aks_preview.decorator import AKSPreviewModels # store all the models used by pod identity pod_identity_models = AKSPreviewModels( cmd, CUSTOM_MGMT_AKS_PREVIEW).pod_identity_models _update_addon_pod_identity( instance, enable=True, pod_identities=instance.pod_identity_profile.user_assigned_identities, pod_identity_exceptions=pod_identity_exceptions, models=pod_identity_models ) # send the managed cluster represeentation to update the pod identity addon return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, instance) def aks_pod_identity_exception_delete(cmd, client, resource_group_name, cluster_name, exc_name, exc_namespace, no_wait=False): # pylint: disable=unused-argument instance = client.get(resource_group_name, cluster_name) _ensure_pod_identity_addon_is_enabled(instance) pod_identity_exceptions = [] if instance.pod_identity_profile.user_assigned_identity_exceptions: for exc in instance.pod_identity_profile.user_assigned_identity_exceptions: if exc.name == exc_name and exc.namespace == exc_namespace: # to remove continue pod_identity_exceptions.append(exc) from azext_aks_preview.decorator import AKSPreviewModels # store all the models used by pod identity pod_identity_models = AKSPreviewModels( cmd, CUSTOM_MGMT_AKS_PREVIEW).pod_identity_models _update_addon_pod_identity( instance, enable=True, pod_identities=instance.pod_identity_profile.user_assigned_identities, pod_identity_exceptions=pod_identity_exceptions, models=pod_identity_models ) # send the managed cluster represeentation to update the pod identity addon return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, instance) def aks_pod_identity_exception_update(cmd, client, resource_group_name, cluster_name, exc_name, exc_namespace, pod_labels, no_wait=False): # pylint: disable=unused-argument instance = client.get(resource_group_name, cluster_name) _ensure_pod_identity_addon_is_enabled(instance) found_target = False updated_exc = ManagedClusterPodIdentityException( name=exc_name, namespace=exc_namespace, pod_labels=pod_labels) pod_identity_exceptions = [] if instance.pod_identity_profile.user_assigned_identity_exceptions: for exc in instance.pod_identity_profile.user_assigned_identity_exceptions: if exc.name == exc_name and exc.namespace == exc_namespace: found_target = True pod_identity_exceptions.append(updated_exc) else: pod_identity_exceptions.append(exc) if not found_target: raise CLIError( 'pod identity exception {}/{} not found'.format(exc_namespace, exc_name)) from azext_aks_preview.decorator import AKSPreviewModels # store all the models used by pod identity pod_identity_models = AKSPreviewModels( cmd, CUSTOM_MGMT_AKS_PREVIEW).pod_identity_models _update_addon_pod_identity( instance, enable=True, pod_identities=instance.pod_identity_profile.user_assigned_identities, pod_identity_exceptions=pod_identity_exceptions, models=pod_identity_models ) # send the managed cluster represeentation to update the pod identity addon return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, cluster_name, instance) def aks_pod_identity_exception_list(cmd, client, resource_group_name, cluster_name): instance = client.get(resource_group_name, cluster_name) return _remove_nulls([instance])[0] def _ensure_cluster_identity_permission_on_kubelet_identity(cli_ctx, cluster_identity_object_id, scope): factory = get_auth_management_client(cli_ctx, scope) assignments_client = factory.role_assignments for i in assignments_client.list_for_scope(scope=scope, filter='atScope()'): if i.scope.lower() != scope.lower(): continue if not i.role_definition_id.lower().endswith(CONST_MANAGED_IDENTITY_OPERATOR_ROLE_ID): continue if i.principal_id.lower() != cluster_identity_object_id.lower(): continue # already assigned return if not add_role_assignment(cli_ctx, CONST_MANAGED_IDENTITY_OPERATOR_ROLE, cluster_identity_object_id, is_service_principal=False, scope=scope): raise CLIError( 'Could not grant Managed Identity Operator permission to cluster identity at scope {}'.format(scope)) def aks_egress_endpoints_list(cmd, client, resource_group_name, name): # pylint: disable=unused-argument return client.list_outbound_network_dependencies_endpoints(resource_group_name, name) def aks_snapshot_create(cmd, # pylint: disable=too-many-locals,too-many-statements,too-many-branches client, resource_group_name, name, cluster_id, location=None, tags=None, aks_custom_headers=None, no_wait=False): rg_location = get_rg_location(cmd.cli_ctx, resource_group_name) if location is None: location = rg_location creationData = CreationData( source_resource_id=cluster_id ) snapshot = ManagedClusterSnapshot( name=name, tags=tags, location=location, creation_data=creationData, snapshot_type="ManagedCluster", ) headers = get_aks_custom_headers(aks_custom_headers) return client.create_or_update(resource_group_name, name, snapshot, headers=headers) def aks_snapshot_show(cmd, client, resource_group_name, name): # pylint: disable=unused-argument snapshot = client.get(resource_group_name, name) return snapshot def aks_snapshot_delete(cmd, # pylint: disable=unused-argument client, resource_group_name, name, no_wait=False, yes=False): from knack.prompting import prompt_y_n msg = 'This will delete the cluster snapshot "{}" in resource group "{}", Are you sure?'.format( name, resource_group_name) if not yes and not prompt_y_n(msg, default="n"): return None return client.delete(resource_group_name, name) def aks_snapshot_list(cmd, client, resource_group_name=None): # pylint: disable=unused-argument if resource_group_name is None or resource_group_name == '': return client.list() return client.list_by_resource_group(resource_group_name) def aks_nodepool_snapshot_create(cmd, # pylint: disable=too-many-locals,too-many-statements,too-many-branches client, resource_group_name, snapshot_name, nodepool_id, location=None, tags=None, aks_custom_headers=None, no_wait=False): rg_location = get_rg_location(cmd.cli_ctx, resource_group_name) if location is None: location = rg_location creationData = CreationData( source_resource_id=nodepool_id ) snapshot = Snapshot( name=snapshot_name, tags=tags, location=location, creation_data=creationData ) headers = get_aks_custom_headers(aks_custom_headers) return client.create_or_update(resource_group_name, snapshot_name, snapshot, headers=headers) def aks_nodepool_snapshot_show(cmd, client, resource_group_name, snapshot_name): # pylint: disable=unused-argument snapshot = client.get(resource_group_name, snapshot_name) return snapshot def aks_nodepool_snapshot_delete(cmd, # pylint: disable=unused-argument client, resource_group_name, snapshot_name, no_wait=False, yes=False): from knack.prompting import prompt_y_n msg = 'This will delete the nodepool snapshot "{}" in resource group "{}", Are you sure?'.format( snapshot_name, resource_group_name) if not yes and not prompt_y_n(msg, default="n"): return None return client.delete(resource_group_name, snapshot_name) def aks_nodepool_snapshot_list(cmd, client, resource_group_name=None): # pylint: disable=unused-argument if resource_group_name is None or resource_group_name == '': return client.list() return client.list_by_resource_group(resource_group_name)
"""CoronaVirus LookUp Syntax: .covid <country>""" from covid import Covid from uniborg.util import admin_cmd @borg.on(admin_cmd(pattern="covid ?(.*)", allow_sudo=True)) async def corona(event): await event.edit("`Processing...`") if event.pattern_match.group(1): country = event.pattern_match.group(1) else: country = "World" covid = Covid(source="worldometers") country_data = covid.get_status_by_country_name(country) ####country_data['confirmed'] + country_data['new_cases'] #####country_data['deaths'] + country_data['new_deaths'] if country_data: output_text = f"😷 **Confirmed** : `{country_data["confirmed"]}`\n" output_text += f"🤒 **Active** : `{country_data["active"]}`\n" output_text += f"🤕 **Critical** : `{country_data["critical"]}`\n" output_text += f"⚰️ **Deaths** : `{country_data["deaths"]}`\n" output_text += f"😇 **Recovered** : `{country_data["recovered"]}`\n" output_text += f"🧪 **Total tests** : `{country_data["total_tests"]}`\n\n" output_text += ( "Data provided by [Johns Hopkins University](https://j.mp/2xf6oxF)" ) else: output_text = "No information yet about this country!" await event.edit(f"Corona Virus Info in **{country}**:\n\n{output_text}")
"""CoronaVirus LookUp Syntax: .covid <country>""" from covid import Covid from uniborg.util import admin_cmd @borg.on(admin_cmd(pattern="covid ?(.*)", allow_sudo=True)) async def corona(event): await event.edit("`Processing...`") if event.pattern_match.group(1): country = event.pattern_match.group(1) else: country = "World" covid = Covid(source="worldometers") country_data = covid.get_status_by_country_name(country) ####country_data['confirmed'] + country_data['new_cases'] #####country_data['deaths'] + country_data['new_deaths'] if country_data: output_text = f"😷 **Confirmed** : `{country_data['confirmed']}`\n" output_text += f"🤒 **Active** : `{country_data['active']}`\n" output_text += f"🤕 **Critical** : `{country_data['critical']}`\n" output_text += f"⚰️ **Deaths** : `{country_data['deaths']}`\n" output_text += f"😇 **Recovered** : `{country_data['recovered']}`\n" output_text += f"🧪 **Total tests** : `{country_data['total_tests']}`\n\n" output_text += ( "Data provided by [Johns Hopkins University](https://j.mp/2xf6oxF)" ) else: output_text = "No information yet about this country!" await event.edit(f"Corona Virus Info in **{country}**:\n\n{output_text}")
from multiprocessing import Pool from cfg import UNKNOWN_ERROR, TIMED_OUT try: from python.make_dir import make_dir from python.get_this_url import get_this_url from python.pic_format import pic_format except (ImportError, FileNotFoundError, ModuleNotFoundError) as e: from make_dir import make_dir from get_this_url import get_this_url from pic_format import pic_format class ImageDl: def __init__(self, url_list: list, headers: dict, worker_size=3, dynamic_adjust_worker_size=False): """ A downloader for img using multiprocessing. \n :param worker_size: Initial thread num. Default to 3. :param url_list: A list consists of url_dict which consists of "url", "content_name", "saving_path". url_list = [ {"url": "url_1", "saving_path": "./data/1.jpg"}, {"url": "url_2", "saving_path": "./data/2.jpg"}, ... ] :param headers: requests headers. :param dynamic_adjust_worker_size: Adjust worker size dynamically if set to True. """ self.url_list = url_list self.headers = headers self.worker_size = worker_size if worker_size > 0 else 3 self.MAX_WORKER_SIZE = 10 self.adjust_worker_size() if dynamic_adjust_worker_size else True def saver(self, msg: dict): # print("----callback func --pid=%d" % os.getpid()) content, url = msg["content"], msg["url"] if content != UNKNOWN_ERROR: # jpg or png. content_format = pic_format(content[:8]) saving_path = f'{msg['saving_path']}{content_format}' content_name = '/'.join(saving_path.split("/")[-2:]) print(f"Saving '{content_name}' to '{saving_path}'...", end='') parent_dir = '/'.join(saving_path.split('/')[:-1]) make_dir(parent_dir) with open(saving_path, "wb") as fp: fp.write(content) print(" Done. ") elif content == TIMED_OUT: print(f"\"{url}\" failed due to {TIMED_OUT}. ") elif content == UNKNOWN_ERROR: print(f"\"{url}\" failed due to {UNKNOWN_ERROR}. ") def get(self, url, headers): print(f"Getting '{url}' with '{headers}'... ", end='') print("Done") return url def worker(self, url_dict: dict, headers: dict) -> dict: """ A step of img_dl. \n :param url_dict: A dict consists of "content_name", "saving_path". :param headers: requests headers. :return: Downloaded content. """ # test # print("pid: {}, ppid: {}".format(os.getpid(), os.getppid())) # content = self.get(url_dict["url"], headers) # test to print the global variables in the Pool. # print(a, end='') url = url_dict["url"] content = get_this_url(url, headers, text_mode=False) return {"content": content, "saving_path": url_dict["saving_path"], "url": url} def adjust_worker_size(self): worker_size = len(self.url_list) // 10 self.worker_size = worker_size + 1 if worker_size % 10 else worker_size self.worker_size = self.worker_size if self.worker_size < self.MAX_WORKER_SIZE else self.MAX_WORKER_SIZE def set_max_worker_size(self, size): self.MAX_WORKER_SIZE = size def run(self): print(f"worker_size: {self.worker_size}") my_pool = Pool(self.worker_size) for url_dict in self.url_list: args = (url_dict, self.headers) my_pool.apply_async(func=self.worker, args=args, callback=self.saver) print("=== start downloading ===") my_pool.close() my_pool.join() print("=== end downloading ===") if __name__ == "__main__": # for testing purpose. target_urls = [ {"url": "url_1", "saving_path": "./data/1.jpg"}, {"url": "url_2", "saving_path": "./data/2.jpg"}, {"url": "url_3", "saving_path": "./data/3.jpg"}, ] img_dl = ImageDl(target_urls, {"headers": "I am headers. "}) img_dl.run()
from multiprocessing import Pool from cfg import UNKNOWN_ERROR, TIMED_OUT try: from python.make_dir import make_dir from python.get_this_url import get_this_url from python.pic_format import pic_format except (ImportError, FileNotFoundError, ModuleNotFoundError) as e: from make_dir import make_dir from get_this_url import get_this_url from pic_format import pic_format class ImageDl: def __init__(self, url_list: list, headers: dict, worker_size=3, dynamic_adjust_worker_size=False): """ A downloader for img using multiprocessing. \n :param worker_size: Initial thread num. Default to 3. :param url_list: A list consists of url_dict which consists of "url", "content_name", "saving_path". url_list = [ {"url": "url_1", "saving_path": "./data/1.jpg"}, {"url": "url_2", "saving_path": "./data/2.jpg"}, ... ] :param headers: requests headers. :param dynamic_adjust_worker_size: Adjust worker size dynamically if set to True. """ self.url_list = url_list self.headers = headers self.worker_size = worker_size if worker_size > 0 else 3 self.MAX_WORKER_SIZE = 10 self.adjust_worker_size() if dynamic_adjust_worker_size else True def saver(self, msg: dict): # print("----callback func --pid=%d" % os.getpid()) content, url = msg["content"], msg["url"] if content != UNKNOWN_ERROR: # jpg or png. content_format = pic_format(content[:8]) saving_path = f'{msg["saving_path"]}{content_format}' content_name = '/'.join(saving_path.split("/")[-2:]) print(f"Saving '{content_name}' to '{saving_path}'...", end='') parent_dir = '/'.join(saving_path.split('/')[:-1]) make_dir(parent_dir) with open(saving_path, "wb") as fp: fp.write(content) print(" Done. ") elif content == TIMED_OUT: print(f"\"{url}\" failed due to {TIMED_OUT}. ") elif content == UNKNOWN_ERROR: print(f"\"{url}\" failed due to {UNKNOWN_ERROR}. ") def get(self, url, headers): print(f"Getting '{url}' with '{headers}'... ", end='') print("Done") return url def worker(self, url_dict: dict, headers: dict) -> dict: """ A step of img_dl. \n :param url_dict: A dict consists of "content_name", "saving_path". :param headers: requests headers. :return: Downloaded content. """ # test # print("pid: {}, ppid: {}".format(os.getpid(), os.getppid())) # content = self.get(url_dict["url"], headers) # test to print the global variables in the Pool. # print(a, end='') url = url_dict["url"] content = get_this_url(url, headers, text_mode=False) return {"content": content, "saving_path": url_dict["saving_path"], "url": url} def adjust_worker_size(self): worker_size = len(self.url_list) // 10 self.worker_size = worker_size + 1 if worker_size % 10 else worker_size self.worker_size = self.worker_size if self.worker_size < self.MAX_WORKER_SIZE else self.MAX_WORKER_SIZE def set_max_worker_size(self, size): self.MAX_WORKER_SIZE = size def run(self): print(f"worker_size: {self.worker_size}") my_pool = Pool(self.worker_size) for url_dict in self.url_list: args = (url_dict, self.headers) my_pool.apply_async(func=self.worker, args=args, callback=self.saver) print("=== start downloading ===") my_pool.close() my_pool.join() print("=== end downloading ===") if __name__ == "__main__": # for testing purpose. target_urls = [ {"url": "url_1", "saving_path": "./data/1.jpg"}, {"url": "url_2", "saving_path": "./data/2.jpg"}, {"url": "url_3", "saving_path": "./data/3.jpg"}, ] img_dl = ImageDl(target_urls, {"headers": "I am headers. "}) img_dl.run()
from asyncdbus import Message, MessageBus from asyncdbus._private.address import parse_address import anyio import pytest import os @pytest.mark.anyio async def test_tcp_connection_with_forwarding(): async with anyio.create_task_group() as tg: closables = [] host = '127.0.0.1' port = '55556' addr_info = parse_address(os.environ.get('DBUS_SESSION_BUS_ADDRESS')) assert addr_info assert 'abstract' in addr_info[0][1] path = f'\0{addr_info[0][1]['abstract']}' async def handle_connection(tcp_sock): async with await anyio.connect_unix(path) as unix_sock: async with anyio.create_task_group() as tg: async def handle_read(): try: while True: data = await tcp_sock.receive() await unix_sock.send(data) except (anyio.ClosedResourceError, anyio.EndOfStream): return async def handle_write(): try: while True: data = await unix_sock.receive() await tcp_sock.send(data) except (anyio.ClosedResourceError, anyio.EndOfStream): return tg.spawn(handle_read) tg.spawn(handle_write) listener = await anyio.create_tcp_listener(local_port=port, local_host=host) tg.spawn(listener.serve, handle_connection) await anyio.sleep(0.1) try: async with MessageBus(bus_address=f'tcp:host={host},port={port}').connect() as bus: # basic tests to see if it works result = await bus.call( Message( destination='org.freedesktop.DBus', path='/org/freedesktop/DBus', interface='org.freedesktop.DBus.Peer', member='Ping')) assert result intr = await bus.introspect('org.freedesktop.DBus', '/org/freedesktop/DBus') obj = await bus.get_proxy_object('org.freedesktop.DBus', '/org/freedesktop/DBus', intr) iface = await obj.get_interface('org.freedesktop.DBus.Peer') await iface.call_ping() sock = bus._sock.extra(anyio.abc.SocketAttribute.raw_socket) \ if hasattr(bus._sock,'extra') else bus._sock assert sock.getpeername()[0] == host assert sock.getsockname()[0] == host assert sock.gettimeout() == 0 pass # A finally: tg.cancel_scope.cancel()
from asyncdbus import Message, MessageBus from asyncdbus._private.address import parse_address import anyio import pytest import os @pytest.mark.anyio async def test_tcp_connection_with_forwarding(): async with anyio.create_task_group() as tg: closables = [] host = '127.0.0.1' port = '55556' addr_info = parse_address(os.environ.get('DBUS_SESSION_BUS_ADDRESS')) assert addr_info assert 'abstract' in addr_info[0][1] path = f'\0{addr_info[0][1]["abstract"]}' async def handle_connection(tcp_sock): async with await anyio.connect_unix(path) as unix_sock: async with anyio.create_task_group() as tg: async def handle_read(): try: while True: data = await tcp_sock.receive() await unix_sock.send(data) except (anyio.ClosedResourceError, anyio.EndOfStream): return async def handle_write(): try: while True: data = await unix_sock.receive() await tcp_sock.send(data) except (anyio.ClosedResourceError, anyio.EndOfStream): return tg.spawn(handle_read) tg.spawn(handle_write) listener = await anyio.create_tcp_listener(local_port=port, local_host=host) tg.spawn(listener.serve, handle_connection) await anyio.sleep(0.1) try: async with MessageBus(bus_address=f'tcp:host={host},port={port}').connect() as bus: # basic tests to see if it works result = await bus.call( Message( destination='org.freedesktop.DBus', path='/org/freedesktop/DBus', interface='org.freedesktop.DBus.Peer', member='Ping')) assert result intr = await bus.introspect('org.freedesktop.DBus', '/org/freedesktop/DBus') obj = await bus.get_proxy_object('org.freedesktop.DBus', '/org/freedesktop/DBus', intr) iface = await obj.get_interface('org.freedesktop.DBus.Peer') await iface.call_ping() sock = bus._sock.extra(anyio.abc.SocketAttribute.raw_socket) \ if hasattr(bus._sock,'extra') else bus._sock assert sock.getpeername()[0] == host assert sock.getsockname()[0] == host assert sock.gettimeout() == 0 pass # A finally: tg.cancel_scope.cancel()
""" The main tytg module. """ import telegram.ext import argparse, logging import os, os.path, subprocess import json, ast, random from glob import glob from telegram import ReplyKeyboardMarkup as RKM from telegram import KeyboardButton as KB class User: """ This class represent an user that's using the bot. """ extensions = ('.txt', '.html', '.jpg', '.png', '.bmp', '.mp4', '.mp3', '.gif', '.tgfile', '.py', '.tgfile') def __init__(self, user): """ Check if the userfile already exists. If so, read the data. Otherwise, create a new file with data. """ # start with standard values # mess_to_file is a map from a message to the filename # that contains that content self.data = {'id': user.id, 'username': user.username, 'path': args['root'], 'mess_to_file': {}} self.file_path = os.path.join(args['root'], f'.{user.id}.user') if os.path.exists(self.file_path): # Read the json data from the file. with open(self.file_path, 'r') as file: # Update with data from the file self.data.update(json.loads(file.read())) # Write data about user to the file. self.save_data() def save_data(self): """ This saves the current data on the userfile. """ with open(self.file_path, 'w') as file: json.dump(self.data, file) def cd(self, directory, bot): """ Manage the file that has been selected, according to the filetype. """ # If the back_label, such as "Back" is clicked, # we're expected to change directory to .. path = os.path.join(self.data['path'], directory) # Directories sorted using {*} at the end, gets # their {*} removed. Glob checks if a dir that # ends with {*} exists, and if so, replaces path. if glob(path+' {*}/'): path = glob(path+' {*}')[0] if (directory == args['back_label'] and self.data['path'] != args['root']): # The first element of os.path.split is the .. directory self.data['path'] = os.path.split(self.data['path'])[0] # If file is a directoy, open it elif os.path.exists(path): self.data['path'] = path self.ls(bot) self.save_data() def ls(self, bot): """ Send all the text, images and files on the current directory. """ # Put a back button if not in root back = [[KB(args['back_label'])] * (not os.path.samefile(self.data['path'], args['root']))] dirs = smartsort(glob(self.data['path']+'/*/')) keyboard = RKM([[KB(a)] for a in dirs] + back) files = [*filter(os.path.isfile, glob(self.data['path']+'/*.*'))] pars = {'chat_id': self.data['id'], 'reply_markup': keyboard} for filepath in files: self.send(filepath, bot, pars) if not files: # No file has been sent. Standard message here. bot.send_message(text=args['standard-message'], **pars) def send(self, filepath, bot, pars): # If file is a .txt, send the content if filepath.endswith('.txt'): mess = open(filepath, 'r', encoding="UTF-8").read() bot.send_message(text=mess, **pars) self.data['mess_to_file'][mess] = filepath # If file is a .html, send the content as html elif filepath.endswith('.html'): mess = text=open(filepath, 'r', encoding="UTF-8").read() bot.send_message(text=mess, parse_mode='HTML', **pars) self.data['mess_to_file'][mess] = filepath # If file is in .png, .jpg, .bmp send the image elif filepath[-4:] in ('.jpg', '.png', '.bmp'): bot.send_photo(photo=open(filepath, 'rb'), **pars) # If file is a .mp4 send it as video elif filepath.endswith('.mp4'): bot.send_video(video=open(filepath, 'rb'), **pars) # If file is a .mp3 send it as audio elif filepath.endswith('.mp3'): bot.send_voice(voice=open(filepath, 'rb'), **pars) # If file is a .gif, send it as file (it will display as a gif) elif filepath.endswith('.gif'): bot.send_document(document=open(filepath, 'rb'), **pars) # If file is a .tgfile, it contains the telegram file id: elif filepath.endswith('.tgfile'): ext, sep, file_id = open(filepath, 'r').read().partition('@') if ext == 'document': bot.send_document(document=file_id, **pars) elif ext == 'audio': bot.send_audio(audio=file_id, **pars) elif ext == 'photo': bot.send_photo(photo=file_id, **pars) elif ext == 'video': bot.send_video(video=file_id, **pars) elif ext == 'voice': bot.send_voice(voice=file_id, **pars) else: print(f'Unsupported telegram id file {ext}') elif filepath.endswith('.py'): mess = filepath.replace('.py', '') code = open(filepath, 'r').read() if get_docstring(code): mess = get_docstring(code) bot.send_message(text=mess, **pars) self.data['mess_to_file'][mess] = filepath else: raise TypeError(f'Cannot send file {filepath} due to ' 'unknow extension') def call(self, message, args, update, bot): """ Call a file with some arguments, e.g. replying "-rf /" to the message sent from the file "/bin/rm" """ if message not in self.data['mess_to_file']: # Calls are not supported on this file. ignore print(f'Did not understand {message!r}') return # Check to what file is the reply referring to file = self.data['mess_to_file'][message] # Call the python file, and write the output back if file.endswith('.py'): cmd = f'python3 "{os.path.abspath(file)}" "{args}"' else: return self.send(file, bot, {'chat_id': update.message.chat_id}) # Saves the current directory, in order to return to it cwd = os.getcwd() # Enter the path, to execute the script in the right directory os.chdir(self.data['path']) out = subprocess.check_output(cmd, shell=True) out = out.decode().split('\n') # Get back to the working directory os.chdir(cwd) for line in [*out]: # If any line output is a filename, send it if any(line.endswith(ext) for ext in self.extensions) and \ os.path.exists(os.path.join(self.data['path'], line)): out.remove(line) line = os.path.join(self.data['path'], line) self.send(line, bot, {'chat_id': update.message.chat_id}) # If any line is a path, open it elif line.endswith('/'): out.remove(line) self.cd(line, bot) if out and '\n'.join(out).strip(): out = '\n'.join(out).strip() update.message.reply_text(out, parse_mode='HTML') self.data['mess_to_file'][out] = file self.save_data() def run_bin(self, message, update, bot): """ Search for a bin* directory in main/, and call the command* file inside it with the arguments. Example could be: /rm . Will search for main/bin*/rm*, and find main/bin {-1}/rm.py, and call it with argument . """ command, sep, arguments = message.partition(' ') # remove the / command = command[1:] script = glob(f"{args["root"]}/bin*/{command}*") # No script found? That's the end. if not script: return print(f"Command not recognized: {command}") # Otherwise, get first result script = script[0] # Save the script name inside the 'mess_to_file' dictionary # in order to make it recognizable to User.call self.data['mess_to_file'][script] = script self.call(script, arguments, update, bot) def download(self, message, file_id=None, text=''): if message.text: text = message.text if message.caption: text = message.caption if message.audio: file_id = message.audio.file_id ext = 'audio' if message.document: file_id = message.document.file_id ext = 'document' if message.photo: file_id = message.photo[0].file_id ext = 'photo' if message.video: file_id = message.video.file_id ext = 'video' if message.voice: file_id = message.voice.file_id ext = 'voice' if file_id: filename = f'{str(random.random())[1:]}.tgfile' with open(os.path.join(self.data['path'], filename), 'w') as file: file.write(f'{ext}@{file_id}') text += f'\n{filename}' return text def get_docstring(source): for node in ast.walk(ast.parse(source)): if isinstance(node, ast.Module): docstring = ast.get_docstring(node) return docstring def smartsort(names): """ Sort a list of names. It will check for: - Alphabetical order (a, b, c) - Numeric order (1, 2, 3) - Specified order (b {0}, c {1}, a {2}) """ def curly(string): "Extract the string inside the curly brackets." return string[string.index('{')+1:string.index('}')] def isnum(string): "Is this string a number?" return string.replace('-', '', 1).isdigit() numbers, specified, words = [], [], [] for name in names: *dir, name, end = name.split('/') if isnum(name.split(' ')[-1]): numbers.append(name) elif '{' in name and isnum(curly(name)): specified.append(name) else: words.append(name) numbers.sort(key=lambda x: int(x.split(' ')[-1])) specified.sort(key=lambda x: int(curly(x))) words.sort(); specified = [word[:word.index('{')-1] for word in specified if int(curly(word))>0] return specified + numbers + words def on_message(bot, update): """ Answer to a message sent to the bot. """ print("Message received") user = User(update.message.from_user) text = user.download(update.message) # Command, tell the user to execute it if text.startswith('/'): user.run_bin(text, update, bot) # It's a call to an older message elif update.message.reply_to_message: user.call(update.message.reply_to_message.text, text, update, bot) # What else? Just a directory name to open else: user.cd(text, bot) print("Message handled") if __name__ == '__main__': # Set up logging. logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) # Getting root and token from argument in a very verbose way. parser = argparse.ArgumentParser(description='Run the tytg server.') parser.add_argument('root', help='The path to the root folder.') parser.add_argument('token', help='The bot token given by botfather.', default=None, nargs='?') parser.add_argument('--back-label', metavar='TEXT', dest='back_label', default=None, help='Text in the button representing ..') parser.add_argument('--standard-message', metavar='TEXT', dest='standard-message', default=None, help='Standard message if no file is found in a directory') # Get all the specified values args = vars(parser.parse_args()) # Does root exist? if not os.path.exists(args['root']): print(f"{args["root"]} does not exist!") print("Please indicate an existing folder.") exit(1) # Create .args.json file with standard data if it doesn't exist if not os.path.exists(os.path.join(args['root'], '.args.json')): with open(os.path.join(args['root'], '.args.json'), 'w') as file: json.dump({'back_label': 'Back', 'standard-message': 'Choose one:'}, file) # Load data from .args file inside main/ if os.path.exists(os.path.join(args['root'], '.args.json')): with open(os.path.join(args['root'], '.args.json'), 'r') as file: file_args = json.load(file) else: file_args = {} # Update the standard values with the file file_args.update({a: b for a,b in args.items() if b}) args = file_args #args.update(file_args) # Save data to file, in order to avoid putting token every time with open(os.path.join(args['root'], '.args.json'), 'w') as file: json.dump(args, file) # No token, no party if not args['token']: print("A token is needed to run the bot. Get one from @botfather.") print("Either insert the token as an argument after main/, or") print("create a file called .args.json, containing:") print("{'token': 'TOKEN HERE'}") exit(1) # Get the updater using te token, and set up the message handler, # in a quite verbose way. updater = telegram.ext.Updater(token=args['token']) updater.dispatcher.add_handler(telegram.ext.MessageHandler( telegram.ext.Filters.all, on_message)) # Actually start the bot. updater.start_polling() print("Bot started.")
""" The main tytg module. """ import telegram.ext import argparse, logging import os, os.path, subprocess import json, ast, random from glob import glob from telegram import ReplyKeyboardMarkup as RKM from telegram import KeyboardButton as KB class User: """ This class represent an user that's using the bot. """ extensions = ('.txt', '.html', '.jpg', '.png', '.bmp', '.mp4', '.mp3', '.gif', '.tgfile', '.py', '.tgfile') def __init__(self, user): """ Check if the userfile already exists. If so, read the data. Otherwise, create a new file with data. """ # start with standard values # mess_to_file is a map from a message to the filename # that contains that content self.data = {'id': user.id, 'username': user.username, 'path': args['root'], 'mess_to_file': {}} self.file_path = os.path.join(args['root'], f'.{user.id}.user') if os.path.exists(self.file_path): # Read the json data from the file. with open(self.file_path, 'r') as file: # Update with data from the file self.data.update(json.loads(file.read())) # Write data about user to the file. self.save_data() def save_data(self): """ This saves the current data on the userfile. """ with open(self.file_path, 'w') as file: json.dump(self.data, file) def cd(self, directory, bot): """ Manage the file that has been selected, according to the filetype. """ # If the back_label, such as "Back" is clicked, # we're expected to change directory to .. path = os.path.join(self.data['path'], directory) # Directories sorted using {*} at the end, gets # their {*} removed. Glob checks if a dir that # ends with {*} exists, and if so, replaces path. if glob(path+' {*}/'): path = glob(path+' {*}')[0] if (directory == args['back_label'] and self.data['path'] != args['root']): # The first element of os.path.split is the .. directory self.data['path'] = os.path.split(self.data['path'])[0] # If file is a directoy, open it elif os.path.exists(path): self.data['path'] = path self.ls(bot) self.save_data() def ls(self, bot): """ Send all the text, images and files on the current directory. """ # Put a back button if not in root back = [[KB(args['back_label'])] * (not os.path.samefile(self.data['path'], args['root']))] dirs = smartsort(glob(self.data['path']+'/*/')) keyboard = RKM([[KB(a)] for a in dirs] + back) files = [*filter(os.path.isfile, glob(self.data['path']+'/*.*'))] pars = {'chat_id': self.data['id'], 'reply_markup': keyboard} for filepath in files: self.send(filepath, bot, pars) if not files: # No file has been sent. Standard message here. bot.send_message(text=args['standard-message'], **pars) def send(self, filepath, bot, pars): # If file is a .txt, send the content if filepath.endswith('.txt'): mess = open(filepath, 'r', encoding="UTF-8").read() bot.send_message(text=mess, **pars) self.data['mess_to_file'][mess] = filepath # If file is a .html, send the content as html elif filepath.endswith('.html'): mess = text=open(filepath, 'r', encoding="UTF-8").read() bot.send_message(text=mess, parse_mode='HTML', **pars) self.data['mess_to_file'][mess] = filepath # If file is in .png, .jpg, .bmp send the image elif filepath[-4:] in ('.jpg', '.png', '.bmp'): bot.send_photo(photo=open(filepath, 'rb'), **pars) # If file is a .mp4 send it as video elif filepath.endswith('.mp4'): bot.send_video(video=open(filepath, 'rb'), **pars) # If file is a .mp3 send it as audio elif filepath.endswith('.mp3'): bot.send_voice(voice=open(filepath, 'rb'), **pars) # If file is a .gif, send it as file (it will display as a gif) elif filepath.endswith('.gif'): bot.send_document(document=open(filepath, 'rb'), **pars) # If file is a .tgfile, it contains the telegram file id: elif filepath.endswith('.tgfile'): ext, sep, file_id = open(filepath, 'r').read().partition('@') if ext == 'document': bot.send_document(document=file_id, **pars) elif ext == 'audio': bot.send_audio(audio=file_id, **pars) elif ext == 'photo': bot.send_photo(photo=file_id, **pars) elif ext == 'video': bot.send_video(video=file_id, **pars) elif ext == 'voice': bot.send_voice(voice=file_id, **pars) else: print(f'Unsupported telegram id file {ext}') elif filepath.endswith('.py'): mess = filepath.replace('.py', '') code = open(filepath, 'r').read() if get_docstring(code): mess = get_docstring(code) bot.send_message(text=mess, **pars) self.data['mess_to_file'][mess] = filepath else: raise TypeError(f'Cannot send file {filepath} due to ' 'unknow extension') def call(self, message, args, update, bot): """ Call a file with some arguments, e.g. replying "-rf /" to the message sent from the file "/bin/rm" """ if message not in self.data['mess_to_file']: # Calls are not supported on this file. ignore print(f'Did not understand {message!r}') return # Check to what file is the reply referring to file = self.data['mess_to_file'][message] # Call the python file, and write the output back if file.endswith('.py'): cmd = f'python3 "{os.path.abspath(file)}" "{args}"' else: return self.send(file, bot, {'chat_id': update.message.chat_id}) # Saves the current directory, in order to return to it cwd = os.getcwd() # Enter the path, to execute the script in the right directory os.chdir(self.data['path']) out = subprocess.check_output(cmd, shell=True) out = out.decode().split('\n') # Get back to the working directory os.chdir(cwd) for line in [*out]: # If any line output is a filename, send it if any(line.endswith(ext) for ext in self.extensions) and \ os.path.exists(os.path.join(self.data['path'], line)): out.remove(line) line = os.path.join(self.data['path'], line) self.send(line, bot, {'chat_id': update.message.chat_id}) # If any line is a path, open it elif line.endswith('/'): out.remove(line) self.cd(line, bot) if out and '\n'.join(out).strip(): out = '\n'.join(out).strip() update.message.reply_text(out, parse_mode='HTML') self.data['mess_to_file'][out] = file self.save_data() def run_bin(self, message, update, bot): """ Search for a bin* directory in main/, and call the command* file inside it with the arguments. Example could be: /rm . Will search for main/bin*/rm*, and find main/bin {-1}/rm.py, and call it with argument . """ command, sep, arguments = message.partition(' ') # remove the / command = command[1:] script = glob(f"{args['root']}/bin*/{command}*") # No script found? That's the end. if not script: return print(f"Command not recognized: {command}") # Otherwise, get first result script = script[0] # Save the script name inside the 'mess_to_file' dictionary # in order to make it recognizable to User.call self.data['mess_to_file'][script] = script self.call(script, arguments, update, bot) def download(self, message, file_id=None, text=''): if message.text: text = message.text if message.caption: text = message.caption if message.audio: file_id = message.audio.file_id ext = 'audio' if message.document: file_id = message.document.file_id ext = 'document' if message.photo: file_id = message.photo[0].file_id ext = 'photo' if message.video: file_id = message.video.file_id ext = 'video' if message.voice: file_id = message.voice.file_id ext = 'voice' if file_id: filename = f'{str(random.random())[1:]}.tgfile' with open(os.path.join(self.data['path'], filename), 'w') as file: file.write(f'{ext}@{file_id}') text += f'\n{filename}' return text def get_docstring(source): for node in ast.walk(ast.parse(source)): if isinstance(node, ast.Module): docstring = ast.get_docstring(node) return docstring def smartsort(names): """ Sort a list of names. It will check for: - Alphabetical order (a, b, c) - Numeric order (1, 2, 3) - Specified order (b {0}, c {1}, a {2}) """ def curly(string): "Extract the string inside the curly brackets." return string[string.index('{')+1:string.index('}')] def isnum(string): "Is this string a number?" return string.replace('-', '', 1).isdigit() numbers, specified, words = [], [], [] for name in names: *dir, name, end = name.split('/') if isnum(name.split(' ')[-1]): numbers.append(name) elif '{' in name and isnum(curly(name)): specified.append(name) else: words.append(name) numbers.sort(key=lambda x: int(x.split(' ')[-1])) specified.sort(key=lambda x: int(curly(x))) words.sort(); specified = [word[:word.index('{')-1] for word in specified if int(curly(word))>0] return specified + numbers + words def on_message(bot, update): """ Answer to a message sent to the bot. """ print("Message received") user = User(update.message.from_user) text = user.download(update.message) # Command, tell the user to execute it if text.startswith('/'): user.run_bin(text, update, bot) # It's a call to an older message elif update.message.reply_to_message: user.call(update.message.reply_to_message.text, text, update, bot) # What else? Just a directory name to open else: user.cd(text, bot) print("Message handled") if __name__ == '__main__': # Set up logging. logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) # Getting root and token from argument in a very verbose way. parser = argparse.ArgumentParser(description='Run the tytg server.') parser.add_argument('root', help='The path to the root folder.') parser.add_argument('token', help='The bot token given by botfather.', default=None, nargs='?') parser.add_argument('--back-label', metavar='TEXT', dest='back_label', default=None, help='Text in the button representing ..') parser.add_argument('--standard-message', metavar='TEXT', dest='standard-message', default=None, help='Standard message if no file is found in a directory') # Get all the specified values args = vars(parser.parse_args()) # Does root exist? if not os.path.exists(args['root']): print(f"{args['root']} does not exist!") print("Please indicate an existing folder.") exit(1) # Create .args.json file with standard data if it doesn't exist if not os.path.exists(os.path.join(args['root'], '.args.json')): with open(os.path.join(args['root'], '.args.json'), 'w') as file: json.dump({'back_label': 'Back', 'standard-message': 'Choose one:'}, file) # Load data from .args file inside main/ if os.path.exists(os.path.join(args['root'], '.args.json')): with open(os.path.join(args['root'], '.args.json'), 'r') as file: file_args = json.load(file) else: file_args = {} # Update the standard values with the file file_args.update({a: b for a,b in args.items() if b}) args = file_args #args.update(file_args) # Save data to file, in order to avoid putting token every time with open(os.path.join(args['root'], '.args.json'), 'w') as file: json.dump(args, file) # No token, no party if not args['token']: print("A token is needed to run the bot. Get one from @botfather.") print("Either insert the token as an argument after main/, or") print("create a file called .args.json, containing:") print("{'token': 'TOKEN HERE'}") exit(1) # Get the updater using te token, and set up the message handler, # in a quite verbose way. updater = telegram.ext.Updater(token=args['token']) updater.dispatcher.add_handler(telegram.ext.MessageHandler( telegram.ext.Filters.all, on_message)) # Actually start the bot. updater.start_polling() print("Bot started.")
'''Shows the stats of a NT team.''' from discord.ext import commands from packages.utils import Embed, ImproperType from packages.nitrotype import Team, Racer import json, os, requests from datetime import datetime from mongoclient import DBClient class Command(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def team(self, ctx, team_name=''): #return await ctx.send('This command is currently under maintenance. The developers will try to get it up again as soon as possible. In the meantime feel free to use `n.help` to get the other commands. Thank you for your understanding!') #thedata = json.loads(requests.get('https://test-db.nitrotypers.repl.co', data={'key': os.getenv('DB_KEY')}).text) dbclient = DBClient() collection = dbclient.db.NT_to_discord thedata = await dbclient.get_array(collection, {}) if team_name == '': async for player in thedata: if player['userID'] == str(ctx.author.id): racer = await Racer(player['NTuser']) tname = ''.join(list(racer.tag)[1:-1]) team = await Team(tname) if tname == '': return await Embed('Error!', 'Couldn\'t find that team', 'warning').send(ctx) break else: team = await Team(team_name) if team.data == {} or team.success == False: userid = str(''.join(list(team_name)[3:-1])) async for elem in thedata: if userid == elem['userID']: racer = await Racer(elem['NTuser']) team_name = racer.tag team = await Team(team_name) if team_name == '': return await Embed('Error!', 'Couldn\'t find that team', 'warning').send(ctx) break if str(''.join(list(team_name)[2:-1])) == elem['userID']: racer = await Racer(elem['NTuser']) team_name = racer.tag team = await Team(team_name) if team_name == '': return await Embed('Error!', 'Couldn\'t find that team', 'warning').send(ctx) break else: async for elem in thedata: if str(team_name) == elem['userID']: racer = await Racer(elem['NTuser']) team_name = racer.tag team = await Team(team_name) if team_name == '': return await Embed('Error!', 'Couldn\'t find that team', 'warning').send(ctx) break else: return await Embed('Error!', 'Couldn\'t find that team', 'warning').send(ctx) if team.data == {} or team.success == False: await Embed('Error!', 'Couldn\'t find that team', 'warning').send(ctx) return info = team.info data = team.data #info section of embed embed = Embed(f"[{info["tag"]}] {info["name"]}", team.tag_and_name, 'race car') createdstamp = info['createdStamp'] birthday = datetime.fromtimestamp(int(createdstamp)) embed.field('Info', f" :busts_in_silhouette: Members: {str(len(data["members"]))}\n:eyes: Team Views: {info["profileViews"]}\n:birthday: Birthday: {birthday}") #requirements to be able to join/apply for the team embed.field('Requirements', f":stopwatch: Min Speed: {info["minSpeed"]}\n:checkered_flag: Min Races: {info["minRaces"]}") #officers/captain of team leaders = f":tools: **{team.captain[1]}**[:link:](https://www.nitrotype.com/racer/{team.captain[0]})\n" for elem in team.leaders: if elem[1] is None: leaders += ':man_police_officer: **'+elem[0]+'**[:link:](https://www.nitrotype.com/racer/'+elem[0]+')\n' else: leaders += ':man_police_officer: **'+elem[1]+'**[:link:](https://www.nitrotype.com/racer/'+elem[0]+')\n' embed.field('Leaders', leaders) #Team Description embed.field('Description', f" {info["otherRequirements"]}") #team stats embed.field('Stats', f":trophy: **Daily**\n{team.daily_races} races ({round(int(team.daily_speed), 2)} wpm, {round(team.daily_accuracy, 2)}% acc)\n{round(team.daily_points, 2)} points\n:trophy: **Season**\n{team.season_races} races ({round(int(team.season_speed), 2)} wpm, {round(team.season_accuracy, 2)}% acc)\n{round(team.season_points, 2)} points\n:trophy: **All-Time**\n{team.alltime_races} races ({round(int(team.alltime_speed), 2)} wpm, {round(team.alltime_accuracy, 2)}% acc)\n{round(team.alltime_points, 2)} points") #send the embed await embed.send(ctx) def setup(client): client.add_cog(Command(client))
'''Shows the stats of a NT team.''' from discord.ext import commands from packages.utils import Embed, ImproperType from packages.nitrotype import Team, Racer import json, os, requests from datetime import datetime from mongoclient import DBClient class Command(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def team(self, ctx, team_name=''): #return await ctx.send('This command is currently under maintenance. The developers will try to get it up again as soon as possible. In the meantime feel free to use `n.help` to get the other commands. Thank you for your understanding!') #thedata = json.loads(requests.get('https://test-db.nitrotypers.repl.co', data={'key': os.getenv('DB_KEY')}).text) dbclient = DBClient() collection = dbclient.db.NT_to_discord thedata = await dbclient.get_array(collection, {}) if team_name == '': async for player in thedata: if player['userID'] == str(ctx.author.id): racer = await Racer(player['NTuser']) tname = ''.join(list(racer.tag)[1:-1]) team = await Team(tname) if tname == '': return await Embed('Error!', 'Couldn\'t find that team', 'warning').send(ctx) break else: team = await Team(team_name) if team.data == {} or team.success == False: userid = str(''.join(list(team_name)[3:-1])) async for elem in thedata: if userid == elem['userID']: racer = await Racer(elem['NTuser']) team_name = racer.tag team = await Team(team_name) if team_name == '': return await Embed('Error!', 'Couldn\'t find that team', 'warning').send(ctx) break if str(''.join(list(team_name)[2:-1])) == elem['userID']: racer = await Racer(elem['NTuser']) team_name = racer.tag team = await Team(team_name) if team_name == '': return await Embed('Error!', 'Couldn\'t find that team', 'warning').send(ctx) break else: async for elem in thedata: if str(team_name) == elem['userID']: racer = await Racer(elem['NTuser']) team_name = racer.tag team = await Team(team_name) if team_name == '': return await Embed('Error!', 'Couldn\'t find that team', 'warning').send(ctx) break else: return await Embed('Error!', 'Couldn\'t find that team', 'warning').send(ctx) if team.data == {} or team.success == False: await Embed('Error!', 'Couldn\'t find that team', 'warning').send(ctx) return info = team.info data = team.data #info section of embed embed = Embed(f"[{info['tag']}] {info['name']}", team.tag_and_name, 'race car') createdstamp = info['createdStamp'] birthday = datetime.fromtimestamp(int(createdstamp)) embed.field('Info', f" :busts_in_silhouette: Members: {str(len(data['members']))}\n:eyes: Team Views: {info['profileViews']}\n:birthday: Birthday: {birthday}") #requirements to be able to join/apply for the team embed.field('Requirements', f":stopwatch: Min Speed: {info['minSpeed']}\n:checkered_flag: Min Races: {info['minRaces']}") #officers/captain of team leaders = f":tools: **{team.captain[1]}**[:link:](https://www.nitrotype.com/racer/{team.captain[0]})\n" for elem in team.leaders: if elem[1] is None: leaders += ':man_police_officer: **'+elem[0]+'**[:link:](https://www.nitrotype.com/racer/'+elem[0]+')\n' else: leaders += ':man_police_officer: **'+elem[1]+'**[:link:](https://www.nitrotype.com/racer/'+elem[0]+')\n' embed.field('Leaders', leaders) #Team Description embed.field('Description', f" {info['otherRequirements']}") #team stats embed.field('Stats', f":trophy: **Daily**\n{team.daily_races} races ({round(int(team.daily_speed), 2)} wpm, {round(team.daily_accuracy, 2)}% acc)\n{round(team.daily_points, 2)} points\n:trophy: **Season**\n{team.season_races} races ({round(int(team.season_speed), 2)} wpm, {round(team.season_accuracy, 2)}% acc)\n{round(team.season_points, 2)} points\n:trophy: **All-Time**\n{team.alltime_races} races ({round(int(team.alltime_speed), 2)} wpm, {round(team.alltime_accuracy, 2)}% acc)\n{round(team.alltime_points, 2)} points") #send the embed await embed.send(ctx) def setup(client): client.add_cog(Command(client))
import fnmatch import mimetypes import os from datetime import datetime, timedelta, timezone from threading import Thread from time import sleep, time import requests from dateutil import parser from requests import auth import config from db_handler import db_queue from frameioclient.utils import calculate_hash from logger import logger from main import authenticated_client class SyncLoop(Thread): def __init__(self, db, project, asset, ignore_folder, **kwargs): super().__init__(**kwargs) self.daemon = True self.db = db self.Project = project self.Asset = asset self.IgnoreFolder = ignore_folder @staticmethod def wildcard_match(name, ignore_list): for ignore in ignore_list: if fnmatch.fnmatch(name, ignore): return True return False def update_projects(self): """Get all projects from Frame.io and add new to DB.""" projects = [] try: for team in authenticated_client().get_all_teams(): # print(f"{team["name"]}: {team["id"]}") projects += authenticated_client().get_projects(team['id']) except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError): raise # try: # projects += authenticated_client().get_shared_projects() # could take a while to run # except (requests.exceptions.ConnectionError, # requests.exceptions.HTTPError): # raise for project in projects: try: db_project = self.Project.get( self.Project.project_id == project['id']) # Check if project has been renamed if db_project.name != project['name']: db_project.name = project['name'] db_queue.put([db_project, 'save']) logger.info( 'Renamed project {} to {}'.format(db_project.name, project['name'])) except self.Project.DoesNotExist: logger.info('New project found: {}'.format(project['name'])) new_project = self.Project(name=project['name'], project_id=project['id'], root_asset_id=project['root_asset_id'], team_id=project['team_id'], on_frameio=True) db_queue.put([new_project, 'save']) # Check if any projects have been deleted active_projects = [project['id'] for project in projects] for db_project in self.Project.select().where( self.Project.deleted_from_frameio == False): if db_project.project_id not in active_projects: db_project.deleted_from_frameio = True db_project.sync = False db_queue.put([db_project, 'save']) logger.info( "Project {} has been deleted, " "turning off sync.".format(db_project.name)) def calculate_missing_paths(self, project, parent_id, parent_path, ignore_folders, ignore): """Recurse through DB and add missing paths and if folder should be ignored. """ children = self.Asset.select().where( (self.Asset.project_id == project.project_id) & (self.Asset.is_file == False) & (self.Asset.parent_id == parent_id)) for child in children: if child.name in ignore_folders or ignore or self.wildcard_match( child.name, ignore_folders): ignore = True if child.path == '': child.path = os.path.join(parent_path, child.name) child.ignore = ignore db_queue.put([child, 'save']) logger.info('Added path to folder {}'.format(child.path)) self.calculate_missing_paths(project, child.asset_id, child.path, ignore_folders, ignore) def update_frameio_assets(self, project, ignore_folders): """Fetch assets that've been added since last scan and add them to DB. :Args: project (DB Project) ignore_folders (List) """ # Always overscan by 10 minutes to help avoid missing assets. new_scan_timestamp = ( datetime.now(timezone.utc) - timedelta(minutes=10)).isoformat() try: account_id = authenticated_client().get_project(project.project_id)['root_asset']['account_id'] updated_assets = authenticated_client().get_updated_assets( account_id, project.project_id, project.last_frameio_scan) except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError): raise # Find assets not already in DB. new_assets = [] for asset in updated_assets: try: self.Asset.get(self.Asset.asset_id == asset['id']) except self.Asset.DoesNotExist: new_assets.append(asset) new_folders = [a for a in new_assets if a['type'] == 'folder'] new_folders.sort(key=lambda a: a['inserted_at']) # Oldest first new_files = [a for a in new_assets if a['type'] == 'file'] added_folders = 0 added_files = 0 duplicates_folders = 0 duplicates_files = 0 # Filter out duplicate folders with same name/path new_folders_filtered = [] for folder in new_folders: if (folder['name'] + folder['parent_id']) not in [ f['name'] + f['parent_id'] for f in new_folders_filtered]: new_folders_filtered.append(folder) for folder in new_folders_filtered: ignore = False path = '' if folder['name'] in ignore_folders or self.wildcard_match( folder['name'], ignore_folders): ignore = True if folder['parent_id'] == project.root_asset_id: path = folder['name'] else: try: parent = self.Asset.get( self.Asset.asset_id == folder['parent_id']) if parent.path != '': path = os.path.join(parent.path, folder['name']) if parent.ignore: ignore = True except self.Asset.DoesNotExist: pass # If folder has the same path/name as an existing one, ignore it try: self.Asset.get(self.Asset.path == path, self.Asset.project_id == project.project_id) ignore = True duplicates_folders += 1 except self.Asset.DoesNotExist: pass new_asset = self.Asset(name=folder['name'], project_id=project.project_id, path=path, asset_id=folder['id'], parent_id=folder['parent_id'], ignore=ignore, on_frameio=True) db_queue.put([new_asset, 'save']) added_folders += 1 # If folders are out of order from Frame.io we need to calc paths. if self.Asset.select().where(self.Asset.path == ''): self.calculate_missing_paths(project=project, parent_id=project.root_asset_id, parent_path='', ignore_folders=ignore_folders, ignore=False) for file in new_files: if file['upload_completed_at'] is not None: ignore = False if file['parent_id'] == project.root_asset_id: parent_path = '' else: try: parent = self.Asset.get( self.Asset.asset_id == file['parent_id']) if parent.path == '': logger.info( "Parent to {} path is not set, retry".format( file['name'])) continue parent_path = parent.path if parent.ignore: ignore = True except self.Asset.DoesNotExist: logger.info('Parent to {} not found, retry'.format( file['name'])) continue # Only add files with unique path and name. asset_path = os.path.join(parent_path, file['name']) try: self.Asset.get(self.Asset.path == asset_path, self.Asset.project_id == project.project_id) duplicates_files += 1 except self.Asset.DoesNotExist: new_asset = self.Asset(name=file['name'], project_id=project.project_id, path=asset_path, is_file=True, asset_id=file['id'], parent_id=file['parent_id'], original=file['original'], ignore=ignore, on_frameio=True) db_queue.put([new_asset, 'save']) added_files += 1 if added_folders - duplicates_folders != 0: logger.info( 'New folders on Frame.io for project {}'.format(project.name)) if added_files - duplicates_files != 0: logger.info( 'New files on Frame.io for project {}'.format(project.name)) if len(new_files) == added_files: # All done. Moving up timestamp. project.last_frameio_scan = new_scan_timestamp db_queue.put([project, 'save']) def update_local_assets(self, project, ignore_folders): """Scan local storage for assets and creates new ones in DB. :Args: project (DB project) ignore_folders (List) """ abs_project_path = os.path.abspath(project.local_path) if not os.path.isdir(abs_project_path): logger.info( 'Local folder for {} not found, turning off sync'.format( project.name)) self.delete_db_project(project) return new_scan_time = int(time()) - 500 # Overscan to avoid missing assets. all_assets_ready = True new_folders = False new_files = False for root, dirs, files in os.walk(abs_project_path, topdown=True): dirs[:] = [d for d in dirs if d not in ignore_folders and not d.startswith( ".") and not self.wildcard_match(d, ignore_folders)] for name in files: full_path = os.path.join(root, name) if not name.startswith('.'): try: create_time = os.path.getctime(full_path) except FileNotFoundError: all_assets_ready = False continue # Add new file criteria # - Created since last complete scan (all_assets_ready) # - Not changed in the last 60 secs # - Size not 0 if create_time > project.last_local_scan: if (time() - create_time) < 60 or os.path.getsize( full_path) == 0: all_assets_ready = False continue path = os.path.relpath(full_path, abs_project_path) try: db_asset = self.Asset.get( self.Asset.project_id == project.project_id, self.Asset.path == path) # Already synced if db_asset.on_local_storage is False: db_asset.on_local_storage = True db_queue.put([db_asset, 'save']) # New file except self.Asset.DoesNotExist: try: file_hash = calculate_hash(full_path) except FileNotFoundError: all_assets_ready = False continue new_files = True new_asset = self.Asset(name=name, project_id=project.project_id, path=path, is_file=True, on_local_storage=True, local_xxhash=file_hash) db_queue.put([new_asset, 'save']) for name in dirs: full_path = os.path.join(root, name) try: create_time = os.path.getctime(full_path) except FileNotFoundError: all_assets_ready = False continue if create_time > project.last_local_scan: path = os.path.relpath(full_path, abs_project_path) try: db_asset = self.Asset.get( self.Asset.project_id == project.project_id, self.Asset.path == path) # Already synced if db_asset.on_local_storage is False: db_asset.on_local_storage = True db_queue.put([db_asset, 'save']) except self.Asset.DoesNotExist: new_folders = True new_asset = self.Asset(name=name, project_id=project.project_id, on_local_storage=True, path=path) db_queue.put([new_asset, 'save']) if all_assets_ready: project.last_local_scan = new_scan_time db_queue.put([project, 'save']) if new_folders: logger.info( 'New local folders for project {}'.format(project.name)) if new_files: logger.info( 'New local files for project {}'.format(project.name)) def download_new_assets(self, project): """Get new assets from DB and download them""" new_folders = self.Asset.select().where( (self.Asset.on_local_storage == False) & (self.Asset.is_file == False) & (self.Asset.project_id == project.project_id) & (self.Asset.ignore == False) & (self.Asset.path != '')) new_files = self.Asset.select().where( (self.Asset.on_local_storage == False) & (self.Asset.is_file == True) & (self.Asset.project_id == project.project_id) & (self.Asset.ignore == False)) if len(new_folders) == 0 and len(new_files) == 0: return for folder in new_folders: logger.info('Creating local folder: {}'.format( os.path.join(project.local_path, folder.path))) os.makedirs(os.path.join( project.local_path, folder.path), exist_ok=True) folder.on_local_storage = True db_queue.put([folder, 'save']) for file in new_files: try: asset = authenticated_client().get_asset(file.asset_id) except requests.exceptions.HTTPError: logger.info('File removed from Frame.io') db_queue.put(file, 'delete') continue if asset['checksums'] is None: logger.info('No checksum for {}'.format(file.name)) # Allow Frame.io some time to calculate hash, retry next loop asset_uploaded_epoch = parser.parse( asset['upload_completed_at']).timestamp() if time() - asset_uploaded_epoch < 300: logger.info('Waiting for checksum'.format(file.name)) continue download_folder = os.path.join(project.local_path, os.path.dirname(file.path)) if os.path.isdir(download_folder): logger.info('Downloading: {}'.format(file.path)) try: authenticated_client().download(asset, download_folder=download_folder, replace=False) except FileExistsError: logger.info('{} already exists.'.format(file.path)) # Add local props to new file file.on_local_storage = True db_queue.put([file, 'save']) else: logger.info('Download folder not found: {}'.format(file.path)) db_queue.put([file, 'delete']) @staticmethod def new_frameio_folder(name, parent_asset_id): """Create single folder on Frame.io""" logger.info('Creating Frame.io folder: {}'.format(name)) asset = authenticated_client().create_asset( parent_asset_id=parent_asset_id, name=name, type="folder", ) return asset['id'] def create_frameio_folder_tree(self, project, new_folder_path): """Step up folder tree in DB to find the closest parent folder on Frame.io. Then creates new folders on Frame.io down to the new folder and save all new asset_ids to DB. :Args: project (Project): In what project to create new_folder (string): Path to folder to create """ current_path = os.path.dirname(new_folder_path) while current_path != '': # While not at root try: db_asset = self.Asset.get( self.Asset.project_id == project.project_id, self.Asset.path == current_path, self.Asset.on_frameio == True) break except self.Asset.DoesNotExist: # Not found, continue up in tree current_path = os.path.dirname(current_path) # Parent folder was found try: parent_asset_id = db_asset.asset_id parent_path = db_asset.path # No parent folder found, root is closest except NameError: parent_asset_id = project.root_asset_id parent_path = '' new_tree = os.path.relpath(new_folder_path, parent_path) for folder in new_tree.split('/'): asset_id = self.new_frameio_folder(folder, parent_asset_id) path = os.path.join(parent_path, folder) asset = self.Asset.get(self.Asset.path == path, self.Asset.project_id == project.project_id) asset.asset_id = asset_id asset.on_frameio = True db_queue.put([asset, 'save']) parent_asset_id = asset_id parent_path = path @staticmethod def upload_asset(abs_path, parent_asset_id): """Upload single asset to Frame.io.""" file_mime = mimetypes.guess_type(abs_path)[0] new_asset = authenticated_client().create_asset( parent_asset_id=parent_asset_id, name=os.path.basename(abs_path), type="file", filetype=file_mime, filesize=os.path.getsize(abs_path) ) with open(abs_path, "rb") as ul_file: authenticated_client().upload(new_asset, ul_file) return new_asset def upload_new_assets(self, project): """Upload new local assets to Frame.io and save new asset ids to DB.""" new_folders = self.Asset.select().where( (self.Asset.on_frameio == False) & (self.Asset.is_file == False) & (self.Asset.project_id == project.project_id)) new_files = self.Asset.select().where( (self.Asset.on_frameio == False) & (self.Asset.is_file == True) & (self.Asset.project_id == project.project_id)) if len(new_folders) == 0 and len(new_files) == 0: return for folder in new_folders: if not os.path.isdir( os.path.join(project.local_path, folder.path)): logger.info("Can't find {}, skipping.".format(folder.name)) db_queue.put([folder, 'delete']) continue self.create_frameio_folder_tree(project=project, new_folder_path=folder.path) for file in new_files: if not os.path.isfile(os.path.join(project.local_path, file.path)): logger.info("Can't find {}".format(file.name)) db_queue.put([file, 'delete']) continue logger.info('Uploading asset: {}'.format(file.path)) abs_path = os.path.abspath( os.path.join(project.local_path, file.path)) if os.path.dirname(file.path) == '': parent_asset_id = project.root_asset_id else: parent_asset_id = self.Asset.get( self.Asset.project_id == project.project_id, self.Asset.path == os.path.dirname( file.path)).asset_id new_asset = self.upload_asset(abs_path, parent_asset_id) logger.info('Upload done') file.asset_id = new_asset['id'] file.original = new_asset['original'] file.uploaded_at = int(time()) file.on_frameio = True file.upload_verified = False db_queue.put([file, 'save']) def delete_and_reupload(self, project, asset): """Delete and re-upload asset to Frame.io. Max attempts: 3.""" logger.info('Deleting and re-uploading: {}'.format(asset.name)) if asset.upload_retries == 2: logger.info( 'Asset already uploaded 3 times. Marking as successful anyway') asset.upload_verified = True db_queue.put([asset, 'save']) return try: authenticated_client().delete_asset(asset.asset_id) except requests.exceptions.HTTPError: # Deleted by user already. pass abs_path = os.path.abspath( os.path.join(project.local_path, asset.path)) if not os.path.isfile(abs_path): logger.info('{} not found'.format(asset.name)) db_queue.put([asset, 'delete']) return if os.path.dirname(asset.path) == '': parent_asset_id = project.root_asset_id else: parent_asset_id = self.Asset.get( self.Asset.project_id == project.project_id, self.Asset.path == os.path.dirname( asset.path)).asset_id new_asset = self.upload_asset(abs_path, parent_asset_id) asset.asset_id = new_asset['id'] asset.original = new_asset['original'] asset.uploaded_at = int(time()) asset.on_frameio = True asset.upload_verified = False asset.upload_retries += 1 db_queue.put([asset, 'save']) def verify_new_uploads(self): """Get xxhash from Frame.io and compare it to local hash in DB. Call delete and re-upload if hashes don't match. """ new_assets = self.Asset.select().where( (self.Asset.upload_verified == False)) if len(new_assets) == 0: return for asset in new_assets: if int(time()) - asset.uploaded_at < 100: continue # Giving Frame.io time to calculate hash. logger.info('New upload to verify: {}'.format(asset.path)) project = self.Project.get( self.Project.project_id == asset.project_id) try: frameio_asset = authenticated_client().get_asset( asset.asset_id) except requests.exceptions.HTTPError: logger.info('Asset deleted from Frame.io, skipping') asset.upload_verified = True db_queue.put([asset, 'save']) continue if frameio_asset.get('upload_completed_at') is None: logger.info('Upload failed') self.delete_and_reupload(project=project, asset=asset) else: try: frameio_hash = frameio_asset['checksums']['xx_hash'] if frameio_hash != asset.local_xxhash: logger.info('Hash mismatch') self.delete_and_reupload(project=project, asset=asset) else: logger.info('Upload succeeded') asset.frameio_xxhash = frameio_hash asset.upload_verified = True db_queue.put([asset, 'save']) except (KeyError, TypeError): logger.info('No calculated checksum yet') # Edge cases where Frame.io fails to calculate a checksum. # Mark as successful anyway. if (time() - asset.uploaded_at) > 1800: logger.info( """30 mins since upload and no checksum on Frame.io, marking as successful anyway""") asset.upload_verified = True db_queue.put([asset, 'save']) def delete_db_project(self, project): """Delete project and its associated assets from DB.""" logger.info('Deleting project {} from DB.'.format(project.name)) for asset in self.Asset.select().where( self.Asset.project_id == project.project_id): db_queue.put([asset, 'delete']) db_queue.put([project, 'delete']) def delete_assets_from_db(self, project): """Delete all assets from DB.""" for asset in self.Asset.select().where( self.Asset.project_id == project.project_id): db_queue.put([asset, 'delete']) def remove_ignore_flag(self, assets, ignore_folders): for asset in assets: if asset.is_file: asset.ignore = False db_queue.put([asset, 'save']) if not asset.is_file: if asset.name not in ignore_folders and not self.wildcard_match( asset.name, ignore_folders): asset.ignore = False db_queue.put([asset, 'save']) children = self.Asset.select().where( self.Asset.parent_id == asset.asset_id) self.remove_ignore_flag(children, ignore_folders) def update_ignored_assets(self): """Find changes to ignore folders and un-flag blocked assets. Frame.io assets are added to DB even if they match an ignore folder. Remove the ignore flag, and download_new_assets will pick them up. Local assets are not added to DB if they match an ignore folder, just skipped. Reset last_scan will add/upload them. """ removed_ignore_folders = self.IgnoreFolder.select().where( self.IgnoreFolder.removed == True) active_ignore_folders = [folder.name for folder in self.IgnoreFolder.select().where( self.IgnoreFolder.removed == False)] all_blocked_folders = self.Asset.select().where( (self.Asset.ignore == True) & (self.Asset.is_file == False)) for ignore_folder in removed_ignore_folders: logger.info('Removing ignore folder {}'.format(ignore_folder.name)) blocked_folders = [f for f in all_blocked_folders if f.name == ignore_folder.name or self.wildcard_match( f.name, [ignore_folder.name])] self.remove_ignore_flag(blocked_folders, active_ignore_folders) db_queue.put([ignore_folder, 'delete']) for project in self.Project.select(): # Trigger re-scan of all project.last_local_scan = 0 db_queue.put([project, 'save']) def run(self): while True: if authenticated_client(): try: logger.info('Checking for updates') self.update_projects() ignore_folders = [folder.name for folder in self.IgnoreFolder.select().where( self.IgnoreFolder.removed == False)] for project in self.Project.select().where( self.Project.sync == True): self.update_frameio_assets( project=project, ignore_folders=ignore_folders) self.update_local_assets( project=project, ignore_folders=ignore_folders) if config.SyncSetting.ASSETS_LOCAL_TO_FRAME: self.upload_new_assets(project) if config.SyncSetting.ASSETS_FRAMEIO_TO_LOCAL: self.download_new_assets(project) self.verify_new_uploads() except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError): logger.info('Could not connect, retrying in {}'.format( config.SCAN_INTERVAL)) # Delete project from DB if requested by user. for project in self.Project.select().where( self.Project.db_delete_requested == True): self.delete_db_project(project) # Delete assets to redo sync from scratch if path has been changed. for project in self.Project.select().where( self.Project.local_path_changed == True): logger.info('Path changed, deleting and recreating assets in db') self.delete_assets_from_db(project) project.local_path_changed = False project.last_local_scan = 0 project.last_frameio_scan = '2014-02-07T00:00:01.000000+00:00' db_queue.put([project, 'save']) # Updated ignored assets if an ignore folder has been removed. if self.IgnoreFolder.select().where( self.IgnoreFolder.removed == True): self.update_ignored_assets() self.db.close() sleep(config.SCAN_INTERVAL)
import fnmatch import mimetypes import os from datetime import datetime, timedelta, timezone from threading import Thread from time import sleep, time import requests from dateutil import parser from requests import auth import config from db_handler import db_queue from frameioclient.utils import calculate_hash from logger import logger from main import authenticated_client class SyncLoop(Thread): def __init__(self, db, project, asset, ignore_folder, **kwargs): super().__init__(**kwargs) self.daemon = True self.db = db self.Project = project self.Asset = asset self.IgnoreFolder = ignore_folder @staticmethod def wildcard_match(name, ignore_list): for ignore in ignore_list: if fnmatch.fnmatch(name, ignore): return True return False def update_projects(self): """Get all projects from Frame.io and add new to DB.""" projects = [] try: for team in authenticated_client().get_all_teams(): # print(f"{team['name']}: {team['id']}") projects += authenticated_client().get_projects(team['id']) except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError): raise # try: # projects += authenticated_client().get_shared_projects() # could take a while to run # except (requests.exceptions.ConnectionError, # requests.exceptions.HTTPError): # raise for project in projects: try: db_project = self.Project.get( self.Project.project_id == project['id']) # Check if project has been renamed if db_project.name != project['name']: db_project.name = project['name'] db_queue.put([db_project, 'save']) logger.info( 'Renamed project {} to {}'.format(db_project.name, project['name'])) except self.Project.DoesNotExist: logger.info('New project found: {}'.format(project['name'])) new_project = self.Project(name=project['name'], project_id=project['id'], root_asset_id=project['root_asset_id'], team_id=project['team_id'], on_frameio=True) db_queue.put([new_project, 'save']) # Check if any projects have been deleted active_projects = [project['id'] for project in projects] for db_project in self.Project.select().where( self.Project.deleted_from_frameio == False): if db_project.project_id not in active_projects: db_project.deleted_from_frameio = True db_project.sync = False db_queue.put([db_project, 'save']) logger.info( "Project {} has been deleted, " "turning off sync.".format(db_project.name)) def calculate_missing_paths(self, project, parent_id, parent_path, ignore_folders, ignore): """Recurse through DB and add missing paths and if folder should be ignored. """ children = self.Asset.select().where( (self.Asset.project_id == project.project_id) & (self.Asset.is_file == False) & (self.Asset.parent_id == parent_id)) for child in children: if child.name in ignore_folders or ignore or self.wildcard_match( child.name, ignore_folders): ignore = True if child.path == '': child.path = os.path.join(parent_path, child.name) child.ignore = ignore db_queue.put([child, 'save']) logger.info('Added path to folder {}'.format(child.path)) self.calculate_missing_paths(project, child.asset_id, child.path, ignore_folders, ignore) def update_frameio_assets(self, project, ignore_folders): """Fetch assets that've been added since last scan and add them to DB. :Args: project (DB Project) ignore_folders (List) """ # Always overscan by 10 minutes to help avoid missing assets. new_scan_timestamp = ( datetime.now(timezone.utc) - timedelta(minutes=10)).isoformat() try: account_id = authenticated_client().get_project(project.project_id)['root_asset']['account_id'] updated_assets = authenticated_client().get_updated_assets( account_id, project.project_id, project.last_frameio_scan) except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError): raise # Find assets not already in DB. new_assets = [] for asset in updated_assets: try: self.Asset.get(self.Asset.asset_id == asset['id']) except self.Asset.DoesNotExist: new_assets.append(asset) new_folders = [a for a in new_assets if a['type'] == 'folder'] new_folders.sort(key=lambda a: a['inserted_at']) # Oldest first new_files = [a for a in new_assets if a['type'] == 'file'] added_folders = 0 added_files = 0 duplicates_folders = 0 duplicates_files = 0 # Filter out duplicate folders with same name/path new_folders_filtered = [] for folder in new_folders: if (folder['name'] + folder['parent_id']) not in [ f['name'] + f['parent_id'] for f in new_folders_filtered]: new_folders_filtered.append(folder) for folder in new_folders_filtered: ignore = False path = '' if folder['name'] in ignore_folders or self.wildcard_match( folder['name'], ignore_folders): ignore = True if folder['parent_id'] == project.root_asset_id: path = folder['name'] else: try: parent = self.Asset.get( self.Asset.asset_id == folder['parent_id']) if parent.path != '': path = os.path.join(parent.path, folder['name']) if parent.ignore: ignore = True except self.Asset.DoesNotExist: pass # If folder has the same path/name as an existing one, ignore it try: self.Asset.get(self.Asset.path == path, self.Asset.project_id == project.project_id) ignore = True duplicates_folders += 1 except self.Asset.DoesNotExist: pass new_asset = self.Asset(name=folder['name'], project_id=project.project_id, path=path, asset_id=folder['id'], parent_id=folder['parent_id'], ignore=ignore, on_frameio=True) db_queue.put([new_asset, 'save']) added_folders += 1 # If folders are out of order from Frame.io we need to calc paths. if self.Asset.select().where(self.Asset.path == ''): self.calculate_missing_paths(project=project, parent_id=project.root_asset_id, parent_path='', ignore_folders=ignore_folders, ignore=False) for file in new_files: if file['upload_completed_at'] is not None: ignore = False if file['parent_id'] == project.root_asset_id: parent_path = '' else: try: parent = self.Asset.get( self.Asset.asset_id == file['parent_id']) if parent.path == '': logger.info( "Parent to {} path is not set, retry".format( file['name'])) continue parent_path = parent.path if parent.ignore: ignore = True except self.Asset.DoesNotExist: logger.info('Parent to {} not found, retry'.format( file['name'])) continue # Only add files with unique path and name. asset_path = os.path.join(parent_path, file['name']) try: self.Asset.get(self.Asset.path == asset_path, self.Asset.project_id == project.project_id) duplicates_files += 1 except self.Asset.DoesNotExist: new_asset = self.Asset(name=file['name'], project_id=project.project_id, path=asset_path, is_file=True, asset_id=file['id'], parent_id=file['parent_id'], original=file['original'], ignore=ignore, on_frameio=True) db_queue.put([new_asset, 'save']) added_files += 1 if added_folders - duplicates_folders != 0: logger.info( 'New folders on Frame.io for project {}'.format(project.name)) if added_files - duplicates_files != 0: logger.info( 'New files on Frame.io for project {}'.format(project.name)) if len(new_files) == added_files: # All done. Moving up timestamp. project.last_frameio_scan = new_scan_timestamp db_queue.put([project, 'save']) def update_local_assets(self, project, ignore_folders): """Scan local storage for assets and creates new ones in DB. :Args: project (DB project) ignore_folders (List) """ abs_project_path = os.path.abspath(project.local_path) if not os.path.isdir(abs_project_path): logger.info( 'Local folder for {} not found, turning off sync'.format( project.name)) self.delete_db_project(project) return new_scan_time = int(time()) - 500 # Overscan to avoid missing assets. all_assets_ready = True new_folders = False new_files = False for root, dirs, files in os.walk(abs_project_path, topdown=True): dirs[:] = [d for d in dirs if d not in ignore_folders and not d.startswith( ".") and not self.wildcard_match(d, ignore_folders)] for name in files: full_path = os.path.join(root, name) if not name.startswith('.'): try: create_time = os.path.getctime(full_path) except FileNotFoundError: all_assets_ready = False continue # Add new file criteria # - Created since last complete scan (all_assets_ready) # - Not changed in the last 60 secs # - Size not 0 if create_time > project.last_local_scan: if (time() - create_time) < 60 or os.path.getsize( full_path) == 0: all_assets_ready = False continue path = os.path.relpath(full_path, abs_project_path) try: db_asset = self.Asset.get( self.Asset.project_id == project.project_id, self.Asset.path == path) # Already synced if db_asset.on_local_storage is False: db_asset.on_local_storage = True db_queue.put([db_asset, 'save']) # New file except self.Asset.DoesNotExist: try: file_hash = calculate_hash(full_path) except FileNotFoundError: all_assets_ready = False continue new_files = True new_asset = self.Asset(name=name, project_id=project.project_id, path=path, is_file=True, on_local_storage=True, local_xxhash=file_hash) db_queue.put([new_asset, 'save']) for name in dirs: full_path = os.path.join(root, name) try: create_time = os.path.getctime(full_path) except FileNotFoundError: all_assets_ready = False continue if create_time > project.last_local_scan: path = os.path.relpath(full_path, abs_project_path) try: db_asset = self.Asset.get( self.Asset.project_id == project.project_id, self.Asset.path == path) # Already synced if db_asset.on_local_storage is False: db_asset.on_local_storage = True db_queue.put([db_asset, 'save']) except self.Asset.DoesNotExist: new_folders = True new_asset = self.Asset(name=name, project_id=project.project_id, on_local_storage=True, path=path) db_queue.put([new_asset, 'save']) if all_assets_ready: project.last_local_scan = new_scan_time db_queue.put([project, 'save']) if new_folders: logger.info( 'New local folders for project {}'.format(project.name)) if new_files: logger.info( 'New local files for project {}'.format(project.name)) def download_new_assets(self, project): """Get new assets from DB and download them""" new_folders = self.Asset.select().where( (self.Asset.on_local_storage == False) & (self.Asset.is_file == False) & (self.Asset.project_id == project.project_id) & (self.Asset.ignore == False) & (self.Asset.path != '')) new_files = self.Asset.select().where( (self.Asset.on_local_storage == False) & (self.Asset.is_file == True) & (self.Asset.project_id == project.project_id) & (self.Asset.ignore == False)) if len(new_folders) == 0 and len(new_files) == 0: return for folder in new_folders: logger.info('Creating local folder: {}'.format( os.path.join(project.local_path, folder.path))) os.makedirs(os.path.join( project.local_path, folder.path), exist_ok=True) folder.on_local_storage = True db_queue.put([folder, 'save']) for file in new_files: try: asset = authenticated_client().get_asset(file.asset_id) except requests.exceptions.HTTPError: logger.info('File removed from Frame.io') db_queue.put(file, 'delete') continue if asset['checksums'] is None: logger.info('No checksum for {}'.format(file.name)) # Allow Frame.io some time to calculate hash, retry next loop asset_uploaded_epoch = parser.parse( asset['upload_completed_at']).timestamp() if time() - asset_uploaded_epoch < 300: logger.info('Waiting for checksum'.format(file.name)) continue download_folder = os.path.join(project.local_path, os.path.dirname(file.path)) if os.path.isdir(download_folder): logger.info('Downloading: {}'.format(file.path)) try: authenticated_client().download(asset, download_folder=download_folder, replace=False) except FileExistsError: logger.info('{} already exists.'.format(file.path)) # Add local props to new file file.on_local_storage = True db_queue.put([file, 'save']) else: logger.info('Download folder not found: {}'.format(file.path)) db_queue.put([file, 'delete']) @staticmethod def new_frameio_folder(name, parent_asset_id): """Create single folder on Frame.io""" logger.info('Creating Frame.io folder: {}'.format(name)) asset = authenticated_client().create_asset( parent_asset_id=parent_asset_id, name=name, type="folder", ) return asset['id'] def create_frameio_folder_tree(self, project, new_folder_path): """Step up folder tree in DB to find the closest parent folder on Frame.io. Then creates new folders on Frame.io down to the new folder and save all new asset_ids to DB. :Args: project (Project): In what project to create new_folder (string): Path to folder to create """ current_path = os.path.dirname(new_folder_path) while current_path != '': # While not at root try: db_asset = self.Asset.get( self.Asset.project_id == project.project_id, self.Asset.path == current_path, self.Asset.on_frameio == True) break except self.Asset.DoesNotExist: # Not found, continue up in tree current_path = os.path.dirname(current_path) # Parent folder was found try: parent_asset_id = db_asset.asset_id parent_path = db_asset.path # No parent folder found, root is closest except NameError: parent_asset_id = project.root_asset_id parent_path = '' new_tree = os.path.relpath(new_folder_path, parent_path) for folder in new_tree.split('/'): asset_id = self.new_frameio_folder(folder, parent_asset_id) path = os.path.join(parent_path, folder) asset = self.Asset.get(self.Asset.path == path, self.Asset.project_id == project.project_id) asset.asset_id = asset_id asset.on_frameio = True db_queue.put([asset, 'save']) parent_asset_id = asset_id parent_path = path @staticmethod def upload_asset(abs_path, parent_asset_id): """Upload single asset to Frame.io.""" file_mime = mimetypes.guess_type(abs_path)[0] new_asset = authenticated_client().create_asset( parent_asset_id=parent_asset_id, name=os.path.basename(abs_path), type="file", filetype=file_mime, filesize=os.path.getsize(abs_path) ) with open(abs_path, "rb") as ul_file: authenticated_client().upload(new_asset, ul_file) return new_asset def upload_new_assets(self, project): """Upload new local assets to Frame.io and save new asset ids to DB.""" new_folders = self.Asset.select().where( (self.Asset.on_frameio == False) & (self.Asset.is_file == False) & (self.Asset.project_id == project.project_id)) new_files = self.Asset.select().where( (self.Asset.on_frameio == False) & (self.Asset.is_file == True) & (self.Asset.project_id == project.project_id)) if len(new_folders) == 0 and len(new_files) == 0: return for folder in new_folders: if not os.path.isdir( os.path.join(project.local_path, folder.path)): logger.info("Can't find {}, skipping.".format(folder.name)) db_queue.put([folder, 'delete']) continue self.create_frameio_folder_tree(project=project, new_folder_path=folder.path) for file in new_files: if not os.path.isfile(os.path.join(project.local_path, file.path)): logger.info("Can't find {}".format(file.name)) db_queue.put([file, 'delete']) continue logger.info('Uploading asset: {}'.format(file.path)) abs_path = os.path.abspath( os.path.join(project.local_path, file.path)) if os.path.dirname(file.path) == '': parent_asset_id = project.root_asset_id else: parent_asset_id = self.Asset.get( self.Asset.project_id == project.project_id, self.Asset.path == os.path.dirname( file.path)).asset_id new_asset = self.upload_asset(abs_path, parent_asset_id) logger.info('Upload done') file.asset_id = new_asset['id'] file.original = new_asset['original'] file.uploaded_at = int(time()) file.on_frameio = True file.upload_verified = False db_queue.put([file, 'save']) def delete_and_reupload(self, project, asset): """Delete and re-upload asset to Frame.io. Max attempts: 3.""" logger.info('Deleting and re-uploading: {}'.format(asset.name)) if asset.upload_retries == 2: logger.info( 'Asset already uploaded 3 times. Marking as successful anyway') asset.upload_verified = True db_queue.put([asset, 'save']) return try: authenticated_client().delete_asset(asset.asset_id) except requests.exceptions.HTTPError: # Deleted by user already. pass abs_path = os.path.abspath( os.path.join(project.local_path, asset.path)) if not os.path.isfile(abs_path): logger.info('{} not found'.format(asset.name)) db_queue.put([asset, 'delete']) return if os.path.dirname(asset.path) == '': parent_asset_id = project.root_asset_id else: parent_asset_id = self.Asset.get( self.Asset.project_id == project.project_id, self.Asset.path == os.path.dirname( asset.path)).asset_id new_asset = self.upload_asset(abs_path, parent_asset_id) asset.asset_id = new_asset['id'] asset.original = new_asset['original'] asset.uploaded_at = int(time()) asset.on_frameio = True asset.upload_verified = False asset.upload_retries += 1 db_queue.put([asset, 'save']) def verify_new_uploads(self): """Get xxhash from Frame.io and compare it to local hash in DB. Call delete and re-upload if hashes don't match. """ new_assets = self.Asset.select().where( (self.Asset.upload_verified == False)) if len(new_assets) == 0: return for asset in new_assets: if int(time()) - asset.uploaded_at < 100: continue # Giving Frame.io time to calculate hash. logger.info('New upload to verify: {}'.format(asset.path)) project = self.Project.get( self.Project.project_id == asset.project_id) try: frameio_asset = authenticated_client().get_asset( asset.asset_id) except requests.exceptions.HTTPError: logger.info('Asset deleted from Frame.io, skipping') asset.upload_verified = True db_queue.put([asset, 'save']) continue if frameio_asset.get('upload_completed_at') is None: logger.info('Upload failed') self.delete_and_reupload(project=project, asset=asset) else: try: frameio_hash = frameio_asset['checksums']['xx_hash'] if frameio_hash != asset.local_xxhash: logger.info('Hash mismatch') self.delete_and_reupload(project=project, asset=asset) else: logger.info('Upload succeeded') asset.frameio_xxhash = frameio_hash asset.upload_verified = True db_queue.put([asset, 'save']) except (KeyError, TypeError): logger.info('No calculated checksum yet') # Edge cases where Frame.io fails to calculate a checksum. # Mark as successful anyway. if (time() - asset.uploaded_at) > 1800: logger.info( """30 mins since upload and no checksum on Frame.io, marking as successful anyway""") asset.upload_verified = True db_queue.put([asset, 'save']) def delete_db_project(self, project): """Delete project and its associated assets from DB.""" logger.info('Deleting project {} from DB.'.format(project.name)) for asset in self.Asset.select().where( self.Asset.project_id == project.project_id): db_queue.put([asset, 'delete']) db_queue.put([project, 'delete']) def delete_assets_from_db(self, project): """Delete all assets from DB.""" for asset in self.Asset.select().where( self.Asset.project_id == project.project_id): db_queue.put([asset, 'delete']) def remove_ignore_flag(self, assets, ignore_folders): for asset in assets: if asset.is_file: asset.ignore = False db_queue.put([asset, 'save']) if not asset.is_file: if asset.name not in ignore_folders and not self.wildcard_match( asset.name, ignore_folders): asset.ignore = False db_queue.put([asset, 'save']) children = self.Asset.select().where( self.Asset.parent_id == asset.asset_id) self.remove_ignore_flag(children, ignore_folders) def update_ignored_assets(self): """Find changes to ignore folders and un-flag blocked assets. Frame.io assets are added to DB even if they match an ignore folder. Remove the ignore flag, and download_new_assets will pick them up. Local assets are not added to DB if they match an ignore folder, just skipped. Reset last_scan will add/upload them. """ removed_ignore_folders = self.IgnoreFolder.select().where( self.IgnoreFolder.removed == True) active_ignore_folders = [folder.name for folder in self.IgnoreFolder.select().where( self.IgnoreFolder.removed == False)] all_blocked_folders = self.Asset.select().where( (self.Asset.ignore == True) & (self.Asset.is_file == False)) for ignore_folder in removed_ignore_folders: logger.info('Removing ignore folder {}'.format(ignore_folder.name)) blocked_folders = [f for f in all_blocked_folders if f.name == ignore_folder.name or self.wildcard_match( f.name, [ignore_folder.name])] self.remove_ignore_flag(blocked_folders, active_ignore_folders) db_queue.put([ignore_folder, 'delete']) for project in self.Project.select(): # Trigger re-scan of all project.last_local_scan = 0 db_queue.put([project, 'save']) def run(self): while True: if authenticated_client(): try: logger.info('Checking for updates') self.update_projects() ignore_folders = [folder.name for folder in self.IgnoreFolder.select().where( self.IgnoreFolder.removed == False)] for project in self.Project.select().where( self.Project.sync == True): self.update_frameio_assets( project=project, ignore_folders=ignore_folders) self.update_local_assets( project=project, ignore_folders=ignore_folders) if config.SyncSetting.ASSETS_LOCAL_TO_FRAME: self.upload_new_assets(project) if config.SyncSetting.ASSETS_FRAMEIO_TO_LOCAL: self.download_new_assets(project) self.verify_new_uploads() except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError): logger.info('Could not connect, retrying in {}'.format( config.SCAN_INTERVAL)) # Delete project from DB if requested by user. for project in self.Project.select().where( self.Project.db_delete_requested == True): self.delete_db_project(project) # Delete assets to redo sync from scratch if path has been changed. for project in self.Project.select().where( self.Project.local_path_changed == True): logger.info('Path changed, deleting and recreating assets in db') self.delete_assets_from_db(project) project.local_path_changed = False project.last_local_scan = 0 project.last_frameio_scan = '2014-02-07T00:00:01.000000+00:00' db_queue.put([project, 'save']) # Updated ignored assets if an ignore folder has been removed. if self.IgnoreFolder.select().where( self.IgnoreFolder.removed == True): self.update_ignored_assets() self.db.close() sleep(config.SCAN_INTERVAL)
''' This tool provides a method to lookup constants to easily decode, for instance, ErrorCodes. ''' import argparse from pathlib import Path from collections import Counter from tinydb import TinyDB, where from rich.console import Console from rich.padding import Padding def const_lookup(search, const_type=None): ''' Read the const_db.json TinyDB to look for the given value or module name. Additionally if the type of the constant is known narrow down the search. ''' # Get the root directory root_dir = Path(__file__).parent.parent.parent.absolute() # Open database db = open_database(root_dir) # See if the search is a constant or is a module name try: search = int(search, 0) except ValueError: pass # Matches dictionary tab_matches = {table:[] for table in db.tables()} # Search if const_type is None: for table_name in db.tables(): # Match for constants if isinstance(search, int): table_matches = db.table(table_name).search(where('value') == search) else: table_matches = db.table(table_name).search(where('module') == search) table_matches.extend(db.table(table_name).search(where('symbol') == search)) if len(table_matches) > 0: tab_matches[table_name].extend(table_matches) else: # Match for constants if search is not None: tab_matches = db.table(const_type).search(where('value') == search) else: tab_matches = db.table(const_type).search(where('module') == search) return tab_matches def open_database(root_dir): ''' Attempt to open the database by searching the root_dir for known locations ''' # First try the build dir try: return TinyDB( root_dir.joinpath('builds/const_db.json'), access_mode='r' ) except FileNotFoundError: pass # Last resort is the tools dir return TinyDB( root_dir.joinpath('src/tools/const_db.json'), access_mode='r' ) def print_matches(matches): ''' Format the matches in a nice way ''' console = Console(highlight=False) # Print events console.print('[bold u]Events[/bold u]') if len(matches['events']) == 0: console.print(' [i]None[/i]') else: _print_duplicate_warnings(console, matches['events'], 'Events') for event in matches['events']: _print_const(console, event) console.print('') # Print errors console.print('[bold u]Errors[/bold u]') if len(matches['errors']) == 0: console.print(' [i]None[/i]') else: _print_duplicate_warnings(console, matches['errors'], 'Errors') for error in matches['errors']: _print_const(console, error) console.print('') # Print datapools console.print('[bold u]DataPool Parameters[/bold u]') if len(matches['datapool']) == 0: console.print(' [i]None[/i]') else: _print_duplicate_warnings(console, matches['datapool'], 'DataPool') for dp in matches['datapool']: _print_const(console, dp) console.print('') def _print_const(console, const): ''' Print an individual constant to the given console. ''' console.print(f' [bold][cyan]{const['symbol']}[/cyan]:[/bold] 0x{const['value']:04X} ({const['value']}, 0b{const['value']:016b})') desc = Padding(const['description'], (0, 0, 0, 8)) console.print(desc) def _print_duplicate_warnings(console, const_list, const_name): ''' Searches const_list for repeated values and prints a warning highlighting them. ''' counts = dict(Counter([c['value'] for c in const_list])) duplicates = {const:count for (const, count) in counts.items() if count > 1} if len(duplicates) > 0: console.print(f' [red][bold]WARNING[/bold] Multiple {const_name} parameters with the same value detected![/red]') console.print(' [red]This must be corrected in the header definition so there is no conflict![/red]') for (const, count) in duplicates.items(): console.print(f' [red]0x{const:04X} is duplicated {count} times') console.print('') def _parse_args(): ''' Parse arguments for the command-line version of const_lookup ''' parser = argparse.ArgumentParser( description='Lookup constant values in the software' ) parser.add_argument( 'const_type', help='The type of constant, either "error", "event", "datapool"', nargs='?' ) parser.add_argument( 'search', help='The search term to lookup. Numeric values (inlcuind hex prepended with 0x) will be interpreted as constants, strings as module names', nargs=1 ) return parser.parse_args() if __name__ == '__main__': args = _parse_args() matches = const_lookup(args.search[0], const_type=args.const_type) print_matches(matches)
''' This tool provides a method to lookup constants to easily decode, for instance, ErrorCodes. ''' import argparse from pathlib import Path from collections import Counter from tinydb import TinyDB, where from rich.console import Console from rich.padding import Padding def const_lookup(search, const_type=None): ''' Read the const_db.json TinyDB to look for the given value or module name. Additionally if the type of the constant is known narrow down the search. ''' # Get the root directory root_dir = Path(__file__).parent.parent.parent.absolute() # Open database db = open_database(root_dir) # See if the search is a constant or is a module name try: search = int(search, 0) except ValueError: pass # Matches dictionary tab_matches = {table:[] for table in db.tables()} # Search if const_type is None: for table_name in db.tables(): # Match for constants if isinstance(search, int): table_matches = db.table(table_name).search(where('value') == search) else: table_matches = db.table(table_name).search(where('module') == search) table_matches.extend(db.table(table_name).search(where('symbol') == search)) if len(table_matches) > 0: tab_matches[table_name].extend(table_matches) else: # Match for constants if search is not None: tab_matches = db.table(const_type).search(where('value') == search) else: tab_matches = db.table(const_type).search(where('module') == search) return tab_matches def open_database(root_dir): ''' Attempt to open the database by searching the root_dir for known locations ''' # First try the build dir try: return TinyDB( root_dir.joinpath('builds/const_db.json'), access_mode='r' ) except FileNotFoundError: pass # Last resort is the tools dir return TinyDB( root_dir.joinpath('src/tools/const_db.json'), access_mode='r' ) def print_matches(matches): ''' Format the matches in a nice way ''' console = Console(highlight=False) # Print events console.print('[bold u]Events[/bold u]') if len(matches['events']) == 0: console.print(' [i]None[/i]') else: _print_duplicate_warnings(console, matches['events'], 'Events') for event in matches['events']: _print_const(console, event) console.print('') # Print errors console.print('[bold u]Errors[/bold u]') if len(matches['errors']) == 0: console.print(' [i]None[/i]') else: _print_duplicate_warnings(console, matches['errors'], 'Errors') for error in matches['errors']: _print_const(console, error) console.print('') # Print datapools console.print('[bold u]DataPool Parameters[/bold u]') if len(matches['datapool']) == 0: console.print(' [i]None[/i]') else: _print_duplicate_warnings(console, matches['datapool'], 'DataPool') for dp in matches['datapool']: _print_const(console, dp) console.print('') def _print_const(console, const): ''' Print an individual constant to the given console. ''' console.print(f' [bold][cyan]{const["symbol"]}[/cyan]:[/bold] 0x{const["value"]:04X} ({const["value"]}, 0b{const["value"]:016b})') desc = Padding(const['description'], (0, 0, 0, 8)) console.print(desc) def _print_duplicate_warnings(console, const_list, const_name): ''' Searches const_list for repeated values and prints a warning highlighting them. ''' counts = dict(Counter([c['value'] for c in const_list])) duplicates = {const:count for (const, count) in counts.items() if count > 1} if len(duplicates) > 0: console.print(f' [red][bold]WARNING[/bold] Multiple {const_name} parameters with the same value detected![/red]') console.print(' [red]This must be corrected in the header definition so there is no conflict![/red]') for (const, count) in duplicates.items(): console.print(f' [red]0x{const:04X} is duplicated {count} times') console.print('') def _parse_args(): ''' Parse arguments for the command-line version of const_lookup ''' parser = argparse.ArgumentParser( description='Lookup constant values in the software' ) parser.add_argument( 'const_type', help='The type of constant, either "error", "event", "datapool"', nargs='?' ) parser.add_argument( 'search', help='The search term to lookup. Numeric values (inlcuind hex prepended with 0x) will be interpreted as constants, strings as module names', nargs=1 ) return parser.parse_args() if __name__ == '__main__': args = _parse_args() matches = const_lookup(args.search[0], const_type=args.const_type) print_matches(matches)
""" by Caio Madeira see hexadecimal colors in: https://htmlcolorcodes.com/ bug splash screen and main solved: https://stackoverflow.com/questions/38676617/tkinter-show-splash-screen-and-hide-main-screen-until-init-has-finished """ import random import time from tkinter import * from tkinter import ttk import tkinter as tk from functionalities import Functionalities from reports import Reports_pdf import socket from PIL import ImageTk, Image from config import hex_colors, custom_size from splash_screen import SplashLoop import ctypes user32 = ctypes.windll.user32 screensize = f"{user32.GetSystemMetrics(0)}x{user32.GetSystemMetrics(1)}" get_user_width = user32.GetSystemMetrics(0) get_user_height = user32.GetSystemMetrics(1) # splash_root = Tk() class WindowLoop(Functionalities, Reports_pdf, tk.Tk): def __init__(self): tk.Tk.__init__(self) self.withdraw() splash = SplashLoop(self) # init_screen = Tk() # self.window = init_screen self.screen() self.screen_frames() self.widgets_frame_1() self.frame_2_list() self.create_tables() self.select_list() self.Menus() time.sleep(6) splash.destroy() ## show window again self.deiconify() def switch(self): self.btnState = False if self.btnState: # off self.btn.config(image=self.onImg, bg='#2B2B2B', activebackground="#2B2B2B") self.dark_mode() self.img = ImageTk.PhotoImage(Image.open("img/consuela_logo_dark.png")) self.configure(background=self.BACKGROUND) self.screen_frames() self.widgets_frame_1() self.frame_2_list() self.btnState = True else: # on self.btn.config(image=self.onImg, bg='#2B2B2B', activebackground="#2B2B2B") self.dark_mode() self.img = ImageTk.PhotoImage(Image.open("img/consuela_logo_dark.png")) self.configure(background=self.BACKGROUND) self.screen_frames() self.widgets_frame_1() self.frame_2_list() self.btnState = True def screen(self): w = self.winfo_reqwidth() print(w) h = self.winfo_reqheight() print(h) ws = self.winfo_screenwidth() print(ws) hs = self.winfo_screenheight() print(hs) x = (ws / 2) - (w / 2) - 600 y = (hs / 2) - (h / 2) - 300 print(x, y) # BUTTON SWITCH DARK OR LIGHT self.light_mode() self.PC_NAME = socket.gethostname() self.title(f"Consuela - Welcome {self.PC_NAME}") self.geometry(f"{custom_size["init_width"]}x{custom_size["init_height"]}") self.geometry('+%d+%d' % (x, y)) self.resizable(True, True) self.maxsize(width=get_user_width, height=get_user_height) self.minsize(width=custom_size['min_width'], height=custom_size['min_height']) self.iconbitmap('img/favicon.ico') self.img = ImageTk.PhotoImage(Image.open("img/consuela_logo_light.png")) self.onImg = ImageTk.PhotoImage(Image.open("img/on.png")) self.offImg = ImageTk.PhotoImage(Image.open("img/off.png")) def screen_frames(self): self.frame_1 = Frame(self) self.frame_1.place(relx=0.01, rely=0.01, relwidth=0.3, relheight=0.97) self.frame_1.configure(background=self.FRAME_1_COLOR) # ==================================================== self.frame_2 = Frame(self, highlightbackground=hex_colors["BACKGROUND"], highlightthickness=1) self.frame_2.place(relx=0.350, rely=0.050, relwidth=0.63, relheight=0.850) self.frame_2.configure(background=self.FRAME_1_COLOR) def widgets_frame_1(self): # =========== BUTTON ================ # BUTTON SWITCH DARK OR LIGHT self.btn = Button(self.frame_1, text='Dark Mode', borderwidth=0, command=self.switch) self.btn.place(relx=0.9, rely=0.03, anchor="center") # =============== # entrar self.btn_enter = Button(self.frame_1, text="Salvar", fg=self.TEXT_BUTTON, bd=2, bg=self.BUTTON_COLOR, font=('consolas', 12, 'bold'), command=self.add_logins) self.btn_enter.place(relx=0.1, rely=0.830, relwidth=0.30, relheight=0.050) # limpar self.btn_clear = Button(self.frame_1, text="Limpar", fg=self.TEXT_BUTTON, bg=self.BUTTON_COLOR, bd=2, font=('consolas', 12, 'bold'), command=self.clean_screen_login) self.btn_clear.place(relx=0.1, rely=0.900, relwidth=0.30, relheight=0.050) # apagar self.btn_erase = Button(self.frame_1, text="Apagar", fg=self.TEXT_BUTTON, bg=self.BUTTON_COLOR, bd=2, font=('consolas', 12, 'bold'), command=self.delet_login) self.btn_erase.place(relx=0.5, rely=0.830, relwidth=0.30, relheight=0.050) # alterar self.btn_edit = Button(self.frame_1, text="Editar", fg=self.TEXT_BUTTON, bg=self.BUTTON_COLOR, bd=2, font=('consolas', 12, 'bold'), command=self.edit_client) self.btn_edit.place(relx=0.1, rely=0.900, relwidth=0.30, relheight=0.050) # ========= LABELS ============ self.panel = Label(self.frame_1, image=self.img) self.panel.pack(side="bottom", fill="both", expand="yes") self.panel.place(relx=0.25, rely=0.1, width=197, height=190) self.label_credits = Label(self.frame_1, text="Por Caio Madeira", bg=self.FRAME_1_COLOR, fg=self.LABEL_COLOR_TEXT, font=('helvetica', 7, 'bold')) self.label_credits.place(x=10, y=5, width=100, height=20) self.label_account = Label(self.frame_1, text="Conta:", bg=self.FRAME_1_COLOR,fg=self.LABEL_COLOR_TEXT, font=('consolas', 15, 'bold')) self.label_account.place(relx=0.01, rely=0.40, relwidth=0.45, relheight=0.05) self.label_user = Label(self.frame_1, text="Usuário/E-mail:", bg=self.FRAME_1_COLOR, fg=self.LABEL_COLOR_TEXT, font=('consolas', 12, 'bold')) self.label_user.place(relx=0.10, rely=0.50, relwidth=0.45, relheight=0.05) self.label_pass = Label(self.frame_1, text="Senha:", bg=self.FRAME_1_COLOR, fg=self.LABEL_COLOR_TEXT, font=('consolas', 15, 'bold')) self.label_pass.place(relx=0.01, rely=0.60, relwidth=0.45, relheight=0.05) # ========= ENTRYS ============ self.entry_account = Entry(self.frame_1, font=('consolas', 12, 'bold')) self.entry_account.place(relx=0.15, rely=0.45, relwidth=0.60, relheight=0.05) self.entry_user = Entry(self.frame_1, font=('consolas', 12, 'bold')) self.entry_user.place(relx=0.15, rely=0.55, relwidth=0.60, relheight=0.05) self.entry_pass = Entry(self.frame_1, font=('consolas', 12, 'bold')) self.entry_pass.place(relx=0.15, rely=0.65, relwidth=0.60, relheight=0.05) def frame_2_list(self): self.list_logins = ttk.Treeview(self.frame_2, height=3, column=("col2", "col3", "col4")) self.list_logins.heading("#0", text="") self.list_logins.heading("#1", text="Conta") self.list_logins.heading("#2", text="Usuário") self.list_logins.heading("#3", text="Senha") self.list_logins.column("#0", width=1) self.list_logins.column("#1", width=100) self.list_logins.column("#2", width=150) self.list_logins.column("#3", width=150) self.list_logins.place(relx=0.02, rely=0.1, relwidth=0.96, relheight=0.850) # === BARRA DE ROLAGEM self.scroollList = Scrollbar(self.frame_2, orient='vertical') self.list_logins.configure(yscroll=self.scroollList.set) self.scroollList.place(relx=0.96, rely=0.1, relwidth=0.02, relheight=0.850) self.list_logins.bind("<Double-1>", self.OnDoubleClick) # ==== BOTAO BUSCAR self.btn_search = Button(self.frame_2, text="Buscar", fg=self.TEXT_BUTTON, bg=self.BUTTON_COLOR, bd=2, font=('consolas', 12, 'bold'), command=self.search_logins) self.btn_search.place(relx=0.01, rely=0.01, relwidth=0.1, relheight=0.050) self.entry_search = Entry(self.frame_2, font=('consolas', 12, 'bold')) self.entry_search.place(relx=0.3, rely=0.01, relwidth=0.60, relheight=0.05) def Menus(self): menu_bar = Menu(self) self.config(menu=menu_bar) menu_file_sair = Menu(menu_bar) # menu_file_limpar = Menu(menu_bar) menu_file_sobre = Menu(menu_bar) menu_file_reports = Menu(menu_bar) menu_file_dark_mode = Menu(menu_bar) def Quit(): self.destroy() menu_bar.add_cascade(label="Sobre", menu=menu_file_sobre) menu_bar.add_cascade(label="Exportar para...", menu=menu_file_reports) menu_bar.add_cascade(label="Opções", menu=menu_file_sair) menu_bar.add_cascade(label="Mais", menu=menu_file_dark_mode) menu_file_sair.add_command(label="Sair", command=Quit) # menu_file_limpar.add_command(label="Limpar a Tela", command=self.clean_screen_login) menu_file_reports.add_command(label="PDF", command=self.generateReport) menu_file_dark_mode.add_command(label="Modo Escuro", command=self.dark_mode) if __name__ == '__main__': mainWindow = WindowLoop() mainWindow.mainloop()
""" by Caio Madeira see hexadecimal colors in: https://htmlcolorcodes.com/ bug splash screen and main solved: https://stackoverflow.com/questions/38676617/tkinter-show-splash-screen-and-hide-main-screen-until-init-has-finished """ import random import time from tkinter import * from tkinter import ttk import tkinter as tk from functionalities import Functionalities from reports import Reports_pdf import socket from PIL import ImageTk, Image from config import hex_colors, custom_size from splash_screen import SplashLoop import ctypes user32 = ctypes.windll.user32 screensize = f"{user32.GetSystemMetrics(0)}x{user32.GetSystemMetrics(1)}" get_user_width = user32.GetSystemMetrics(0) get_user_height = user32.GetSystemMetrics(1) # splash_root = Tk() class WindowLoop(Functionalities, Reports_pdf, tk.Tk): def __init__(self): tk.Tk.__init__(self) self.withdraw() splash = SplashLoop(self) # init_screen = Tk() # self.window = init_screen self.screen() self.screen_frames() self.widgets_frame_1() self.frame_2_list() self.create_tables() self.select_list() self.Menus() time.sleep(6) splash.destroy() ## show window again self.deiconify() def switch(self): self.btnState = False if self.btnState: # off self.btn.config(image=self.onImg, bg='#2B2B2B', activebackground="#2B2B2B") self.dark_mode() self.img = ImageTk.PhotoImage(Image.open("img/consuela_logo_dark.png")) self.configure(background=self.BACKGROUND) self.screen_frames() self.widgets_frame_1() self.frame_2_list() self.btnState = True else: # on self.btn.config(image=self.onImg, bg='#2B2B2B', activebackground="#2B2B2B") self.dark_mode() self.img = ImageTk.PhotoImage(Image.open("img/consuela_logo_dark.png")) self.configure(background=self.BACKGROUND) self.screen_frames() self.widgets_frame_1() self.frame_2_list() self.btnState = True def screen(self): w = self.winfo_reqwidth() print(w) h = self.winfo_reqheight() print(h) ws = self.winfo_screenwidth() print(ws) hs = self.winfo_screenheight() print(hs) x = (ws / 2) - (w / 2) - 600 y = (hs / 2) - (h / 2) - 300 print(x, y) # BUTTON SWITCH DARK OR LIGHT self.light_mode() self.PC_NAME = socket.gethostname() self.title(f"Consuela - Welcome {self.PC_NAME}") self.geometry(f"{custom_size['init_width']}x{custom_size['init_height']}") self.geometry('+%d+%d' % (x, y)) self.resizable(True, True) self.maxsize(width=get_user_width, height=get_user_height) self.minsize(width=custom_size['min_width'], height=custom_size['min_height']) self.iconbitmap('img/favicon.ico') self.img = ImageTk.PhotoImage(Image.open("img/consuela_logo_light.png")) self.onImg = ImageTk.PhotoImage(Image.open("img/on.png")) self.offImg = ImageTk.PhotoImage(Image.open("img/off.png")) def screen_frames(self): self.frame_1 = Frame(self) self.frame_1.place(relx=0.01, rely=0.01, relwidth=0.3, relheight=0.97) self.frame_1.configure(background=self.FRAME_1_COLOR) # ==================================================== self.frame_2 = Frame(self, highlightbackground=hex_colors["BACKGROUND"], highlightthickness=1) self.frame_2.place(relx=0.350, rely=0.050, relwidth=0.63, relheight=0.850) self.frame_2.configure(background=self.FRAME_1_COLOR) def widgets_frame_1(self): # =========== BUTTON ================ # BUTTON SWITCH DARK OR LIGHT self.btn = Button(self.frame_1, text='Dark Mode', borderwidth=0, command=self.switch) self.btn.place(relx=0.9, rely=0.03, anchor="center") # =============== # entrar self.btn_enter = Button(self.frame_1, text="Salvar", fg=self.TEXT_BUTTON, bd=2, bg=self.BUTTON_COLOR, font=('consolas', 12, 'bold'), command=self.add_logins) self.btn_enter.place(relx=0.1, rely=0.830, relwidth=0.30, relheight=0.050) # limpar self.btn_clear = Button(self.frame_1, text="Limpar", fg=self.TEXT_BUTTON, bg=self.BUTTON_COLOR, bd=2, font=('consolas', 12, 'bold'), command=self.clean_screen_login) self.btn_clear.place(relx=0.1, rely=0.900, relwidth=0.30, relheight=0.050) # apagar self.btn_erase = Button(self.frame_1, text="Apagar", fg=self.TEXT_BUTTON, bg=self.BUTTON_COLOR, bd=2, font=('consolas', 12, 'bold'), command=self.delet_login) self.btn_erase.place(relx=0.5, rely=0.830, relwidth=0.30, relheight=0.050) # alterar self.btn_edit = Button(self.frame_1, text="Editar", fg=self.TEXT_BUTTON, bg=self.BUTTON_COLOR, bd=2, font=('consolas', 12, 'bold'), command=self.edit_client) self.btn_edit.place(relx=0.1, rely=0.900, relwidth=0.30, relheight=0.050) # ========= LABELS ============ self.panel = Label(self.frame_1, image=self.img) self.panel.pack(side="bottom", fill="both", expand="yes") self.panel.place(relx=0.25, rely=0.1, width=197, height=190) self.label_credits = Label(self.frame_1, text="Por Caio Madeira", bg=self.FRAME_1_COLOR, fg=self.LABEL_COLOR_TEXT, font=('helvetica', 7, 'bold')) self.label_credits.place(x=10, y=5, width=100, height=20) self.label_account = Label(self.frame_1, text="Conta:", bg=self.FRAME_1_COLOR,fg=self.LABEL_COLOR_TEXT, font=('consolas', 15, 'bold')) self.label_account.place(relx=0.01, rely=0.40, relwidth=0.45, relheight=0.05) self.label_user = Label(self.frame_1, text="Usuário/E-mail:", bg=self.FRAME_1_COLOR, fg=self.LABEL_COLOR_TEXT, font=('consolas', 12, 'bold')) self.label_user.place(relx=0.10, rely=0.50, relwidth=0.45, relheight=0.05) self.label_pass = Label(self.frame_1, text="Senha:", bg=self.FRAME_1_COLOR, fg=self.LABEL_COLOR_TEXT, font=('consolas', 15, 'bold')) self.label_pass.place(relx=0.01, rely=0.60, relwidth=0.45, relheight=0.05) # ========= ENTRYS ============ self.entry_account = Entry(self.frame_1, font=('consolas', 12, 'bold')) self.entry_account.place(relx=0.15, rely=0.45, relwidth=0.60, relheight=0.05) self.entry_user = Entry(self.frame_1, font=('consolas', 12, 'bold')) self.entry_user.place(relx=0.15, rely=0.55, relwidth=0.60, relheight=0.05) self.entry_pass = Entry(self.frame_1, font=('consolas', 12, 'bold')) self.entry_pass.place(relx=0.15, rely=0.65, relwidth=0.60, relheight=0.05) def frame_2_list(self): self.list_logins = ttk.Treeview(self.frame_2, height=3, column=("col2", "col3", "col4")) self.list_logins.heading("#0", text="") self.list_logins.heading("#1", text="Conta") self.list_logins.heading("#2", text="Usuário") self.list_logins.heading("#3", text="Senha") self.list_logins.column("#0", width=1) self.list_logins.column("#1", width=100) self.list_logins.column("#2", width=150) self.list_logins.column("#3", width=150) self.list_logins.place(relx=0.02, rely=0.1, relwidth=0.96, relheight=0.850) # === BARRA DE ROLAGEM self.scroollList = Scrollbar(self.frame_2, orient='vertical') self.list_logins.configure(yscroll=self.scroollList.set) self.scroollList.place(relx=0.96, rely=0.1, relwidth=0.02, relheight=0.850) self.list_logins.bind("<Double-1>", self.OnDoubleClick) # ==== BOTAO BUSCAR self.btn_search = Button(self.frame_2, text="Buscar", fg=self.TEXT_BUTTON, bg=self.BUTTON_COLOR, bd=2, font=('consolas', 12, 'bold'), command=self.search_logins) self.btn_search.place(relx=0.01, rely=0.01, relwidth=0.1, relheight=0.050) self.entry_search = Entry(self.frame_2, font=('consolas', 12, 'bold')) self.entry_search.place(relx=0.3, rely=0.01, relwidth=0.60, relheight=0.05) def Menus(self): menu_bar = Menu(self) self.config(menu=menu_bar) menu_file_sair = Menu(menu_bar) # menu_file_limpar = Menu(menu_bar) menu_file_sobre = Menu(menu_bar) menu_file_reports = Menu(menu_bar) menu_file_dark_mode = Menu(menu_bar) def Quit(): self.destroy() menu_bar.add_cascade(label="Sobre", menu=menu_file_sobre) menu_bar.add_cascade(label="Exportar para...", menu=menu_file_reports) menu_bar.add_cascade(label="Opções", menu=menu_file_sair) menu_bar.add_cascade(label="Mais", menu=menu_file_dark_mode) menu_file_sair.add_command(label="Sair", command=Quit) # menu_file_limpar.add_command(label="Limpar a Tela", command=self.clean_screen_login) menu_file_reports.add_command(label="PDF", command=self.generateReport) menu_file_dark_mode.add_command(label="Modo Escuro", command=self.dark_mode) if __name__ == '__main__': mainWindow = WindowLoop() mainWindow.mainloop()
from __future__ import unicode_literals import re import sys import types from django.conf import settings from django.core.urlresolvers import Resolver404, resolve from django.http import HttpResponse, HttpResponseNotFound from django.template import Context, Engine, TemplateDoesNotExist from django.template.defaultfilters import force_escape, pprint from django.utils import lru_cache, six, timezone from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_bytes, smart_text from django.utils.module_loading import import_string from django.utils.translation import ugettext as _ # Minimal Django templates engine to render the error templates # regardless of the project's TEMPLATES setting. DEBUG_ENGINE = Engine(debug=True) HIDDEN_SETTINGS = re.compile('API|TOKEN|KEY|SECRET|PASS|SIGNATURE') CLEANSED_SUBSTITUTE = '********************' class CallableSettingWrapper(object): """ Object to wrap callable appearing in settings * Not to call in the debug page (#21345). * Not to break the debug page if the callable forbidding to set attributes (#23070). """ def __init__(self, callable_setting): self._wrapped = callable_setting def __repr__(self): return repr(self._wrapped) def cleanse_setting(key, value): """Cleanse an individual setting key/value of sensitive content. If the value is a dictionary, recursively cleanse the keys in that dictionary. """ try: if HIDDEN_SETTINGS.search(key): cleansed = CLEANSED_SUBSTITUTE else: if isinstance(value, dict): cleansed = {k: cleanse_setting(k, v) for k, v in value.items()} else: cleansed = value except TypeError: # If the key isn't regex-able, just return as-is. cleansed = value if callable(cleansed): # For fixing #21345 and #23070 cleansed = CallableSettingWrapper(cleansed) return cleansed def get_safe_settings(): "Returns a dictionary of the settings module, with sensitive settings blurred out." settings_dict = {} for k in dir(settings): if k.isupper(): settings_dict[k] = cleanse_setting(k, getattr(settings, k)) return settings_dict def technical_500_response(request, exc_type, exc_value, tb, status_code=500): """ Create a technical server error response. The last three arguments are the values returned from sys.exc_info() and friends. """ reporter = ExceptionReporter(request, exc_type, exc_value, tb) if request.is_ajax(): text = reporter.get_traceback_text() return HttpResponse(text, status=status_code, content_type='text/plain') else: html = reporter.get_traceback_html() return HttpResponse(html, status=status_code, content_type='text/html') @lru_cache.lru_cache() def get_default_exception_reporter_filter(): # Instantiate the default filter for the first time and cache it. return import_string(settings.DEFAULT_EXCEPTION_REPORTER_FILTER)() def get_exception_reporter_filter(request): default_filter = get_default_exception_reporter_filter() return getattr(request, 'exception_reporter_filter', default_filter) class ExceptionReporterFilter(object): """ Base for all exception reporter filter classes. All overridable hooks contain lenient default behaviors. """ def get_post_parameters(self, request): if request is None: return {} else: return request.POST def get_traceback_frame_variables(self, request, tb_frame): return list(tb_frame.f_locals.items()) class SafeExceptionReporterFilter(ExceptionReporterFilter): """ Use annotations made by the sensitive_post_parameters and sensitive_variables decorators to filter out sensitive information. """ def is_active(self, request): """ This filter is to add safety in production environments (i.e. DEBUG is False). If DEBUG is True then your site is not safe anyway. This hook is provided as a convenience to easily activate or deactivate the filter on a per request basis. """ return settings.DEBUG is False def get_cleansed_multivaluedict(self, request, multivaluedict): """ Replaces the keys in a MultiValueDict marked as sensitive with stars. This mitigates leaking sensitive POST parameters if something like request.POST['nonexistent_key'] throws an exception (#21098). """ sensitive_post_parameters = getattr(request, 'sensitive_post_parameters', []) if self.is_active(request) and sensitive_post_parameters: multivaluedict = multivaluedict.copy() for param in sensitive_post_parameters: if param in multivaluedict: multivaluedict[param] = CLEANSED_SUBSTITUTE return multivaluedict def get_post_parameters(self, request): """ Replaces the values of POST parameters marked as sensitive with stars (*********). """ if request is None: return {} else: sensitive_post_parameters = getattr(request, 'sensitive_post_parameters', []) if self.is_active(request) and sensitive_post_parameters: cleansed = request.POST.copy() if sensitive_post_parameters == '__ALL__': # Cleanse all parameters. for k, v in cleansed.items(): cleansed[k] = CLEANSED_SUBSTITUTE return cleansed else: # Cleanse only the specified parameters. for param in sensitive_post_parameters: if param in cleansed: cleansed[param] = CLEANSED_SUBSTITUTE return cleansed else: return request.POST def cleanse_special_types(self, request, value): try: # If value is lazy or a complex object of another kind, this check # might raise an exception. isinstance checks that lazy # MultiValueDicts will have a return value. is_multivalue_dict = isinstance(value, MultiValueDict) except Exception as e: return '{!r} while evaluating {!r}'.format(e, value) if is_multivalue_dict: # Cleanse MultiValueDicts (request.POST is the one we usually care about) value = self.get_cleansed_multivaluedict(request, value) return value def get_traceback_frame_variables(self, request, tb_frame): """ Replaces the values of variables marked as sensitive with stars (*********). """ # Loop through the frame's callers to see if the sensitive_variables # decorator was used. current_frame = tb_frame.f_back sensitive_variables = None while current_frame is not None: if (current_frame.f_code.co_name == 'sensitive_variables_wrapper' and 'sensitive_variables_wrapper' in current_frame.f_locals): # The sensitive_variables decorator was used, so we take note # of the sensitive variables' names. wrapper = current_frame.f_locals['sensitive_variables_wrapper'] sensitive_variables = getattr(wrapper, 'sensitive_variables', None) break current_frame = current_frame.f_back cleansed = {} if self.is_active(request) and sensitive_variables: if sensitive_variables == '__ALL__': # Cleanse all variables for name, value in tb_frame.f_locals.items(): cleansed[name] = CLEANSED_SUBSTITUTE else: # Cleanse specified variables for name, value in tb_frame.f_locals.items(): if name in sensitive_variables: value = CLEANSED_SUBSTITUTE else: value = self.cleanse_special_types(request, value) cleansed[name] = value else: # Potentially cleanse the request and any MultiValueDicts if they # are one of the frame variables. for name, value in tb_frame.f_locals.items(): cleansed[name] = self.cleanse_special_types(request, value) if (tb_frame.f_code.co_name == 'sensitive_variables_wrapper' and 'sensitive_variables_wrapper' in tb_frame.f_locals): # For good measure, obfuscate the decorated function's arguments in # the sensitive_variables decorator's frame, in case the variables # associated with those arguments were meant to be obfuscated from # the decorated function's frame. cleansed['func_args'] = CLEANSED_SUBSTITUTE cleansed['func_kwargs'] = CLEANSED_SUBSTITUTE return cleansed.items() class ExceptionReporter(object): """ A class to organize and coordinate reporting on exceptions. """ def __init__(self, request, exc_type, exc_value, tb, is_email=False): self.request = request self.filter = get_exception_reporter_filter(self.request) self.exc_type = exc_type self.exc_value = exc_value self.tb = tb self.is_email = is_email self.template_info = getattr(self.exc_value, 'template_debug', None) self.template_does_not_exist = False self.postmortem = None # Handle deprecated string exceptions if isinstance(self.exc_type, six.string_types): self.exc_value = Exception('Deprecated String Exception: %r' % self.exc_type) self.exc_type = type(self.exc_value) def get_traceback_data(self): """Return a dictionary containing traceback information.""" if self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist): self.template_does_not_exist = True self.postmortem = self.exc_value.chain or [self.exc_value] frames = self.get_traceback_frames() for i, frame in enumerate(frames): if 'vars' in frame: frame_vars = [] for k, v in frame['vars']: v = pprint(v) # The force_escape filter assume unicode, make sure that works if isinstance(v, six.binary_type): v = v.decode('utf-8', 'replace') # don't choke on non-utf-8 input # Trim large blobs of data if len(v) > 4096: v = '%s... <trimmed %d bytes string>' % (v[0:4096], len(v)) frame_vars.append((k, force_escape(v))) frame['vars'] = frame_vars frames[i] = frame unicode_hint = '' if self.exc_type and issubclass(self.exc_type, UnicodeError): start = getattr(self.exc_value, 'start', None) end = getattr(self.exc_value, 'end', None) if start is not None and end is not None: unicode_str = self.exc_value.args[1] unicode_hint = smart_text( unicode_str[max(start - 5, 0):min(end + 5, len(unicode_str))], 'ascii', errors='replace' ) from django import get_version c = { 'is_email': self.is_email, 'unicode_hint': unicode_hint, 'frames': frames, 'request': self.request, 'filtered_POST': self.filter.get_post_parameters(self.request), 'settings': get_safe_settings(), 'sys_executable': sys.executable, 'sys_version_info': '%d.%d.%d' % sys.version_info[0:3], 'server_time': timezone.now(), 'django_version_info': get_version(), 'sys_path': sys.path, 'template_info': self.template_info, 'template_does_not_exist': self.template_does_not_exist, 'postmortem': self.postmortem, } # Check whether exception info is available if self.exc_type: c['exception_type'] = self.exc_type.__name__ if self.exc_value: c['exception_value'] = smart_text(self.exc_value, errors='replace') if frames: c['lastframe'] = frames[-1] return c def get_traceback_html(self): "Return HTML version of debug 500 HTTP error page." t = DEBUG_ENGINE.from_string(TECHNICAL_500_TEMPLATE) c = Context(self.get_traceback_data(), use_l10n=False) return t.render(c) def get_traceback_text(self): "Return plain text version of debug 500 HTTP error page." t = DEBUG_ENGINE.from_string(TECHNICAL_500_TEXT_TEMPLATE) c = Context(self.get_traceback_data(), autoescape=False, use_l10n=False) return t.render(c) def _get_lines_from_file(self, filename, lineno, context_lines, loader=None, module_name=None): """ Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context). """ source = None if loader is not None and hasattr(loader, "get_source"): try: source = loader.get_source(module_name) except ImportError: pass if source is not None: source = source.splitlines() if source is None: try: with open(filename, 'rb') as fp: source = fp.read().splitlines() except (OSError, IOError): pass if source is None: return None, [], None, [] # If we just read the source from a file, or if the loader did not # apply tokenize.detect_encoding to decode the source into a Unicode # string, then we should do that ourselves. if isinstance(source[0], six.binary_type): encoding = 'ascii' for line in source[:2]: # File coding may be specified. Match pattern from PEP-263 # (http://www.python.org/dev/peps/pep-0263/) match = re.search(br'coding[:=]\s*([-\w.]+)', line) if match: encoding = match.group(1).decode('ascii') break source = [six.text_type(sline, encoding, 'replace') for sline in source] lower_bound = max(0, lineno - context_lines) upper_bound = lineno + context_lines pre_context = source[lower_bound:lineno] context_line = source[lineno] post_context = source[lineno + 1:upper_bound] return lower_bound, pre_context, context_line, post_context def get_traceback_frames(self): def explicit_or_implicit_cause(exc_value): explicit = getattr(exc_value, '__cause__', None) implicit = getattr(exc_value, '__context__', None) return explicit or implicit # Get the exception and all its causes exceptions = [] exc_value = self.exc_value while exc_value: exceptions.append(exc_value) exc_value = explicit_or_implicit_cause(exc_value) frames = [] # No exceptions were supplied to ExceptionReporter if not exceptions: return frames # In case there's just one exception (always in Python 2, # sometimes in Python 3), take the traceback from self.tb (Python 2 # doesn't have a __traceback__ attribute on Exception) exc_value = exceptions.pop() tb = self.tb if six.PY2 or not exceptions else exc_value.__traceback__ while tb is not None: # Support for __traceback_hide__ which is used by a few libraries # to hide internal frames. if tb.tb_frame.f_locals.get('__traceback_hide__'): tb = tb.tb_next continue filename = tb.tb_frame.f_code.co_filename function = tb.tb_frame.f_code.co_name lineno = tb.tb_lineno - 1 loader = tb.tb_frame.f_globals.get('__loader__') module_name = tb.tb_frame.f_globals.get('__name__') or '' pre_context_lineno, pre_context, context_line, post_context = self._get_lines_from_file( filename, lineno, 7, loader, module_name, ) if pre_context_lineno is not None: frames.append({ 'exc_cause': explicit_or_implicit_cause(exc_value), 'exc_cause_explicit': getattr(exc_value, '__cause__', True), 'tb': tb, 'type': 'django' if module_name.startswith('django.') else 'user', 'filename': filename, 'function': function, 'lineno': lineno + 1, 'vars': self.filter.get_traceback_frame_variables(self.request, tb.tb_frame), 'id': id(tb), 'pre_context': pre_context, 'context_line': context_line, 'post_context': post_context, 'pre_context_lineno': pre_context_lineno + 1, }) # If the traceback for current exception is consumed, try the # other exception. if six.PY2: tb = tb.tb_next elif not tb.tb_next and exceptions: exc_value = exceptions.pop() tb = exc_value.__traceback__ else: tb = tb.tb_next return frames def format_exception(self): """ Return the same data as from traceback.format_exception. """ import traceback frames = self.get_traceback_frames() tb = [(f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames] list = ['Traceback (most recent call last):\n'] list += traceback.format_list(tb) list += traceback.format_exception_only(self.exc_type, self.exc_value) return list def technical_404_response(request, exception): "Create a technical 404 error response. The exception should be the Http404." try: error_url = exception.args[0]['path'] except (IndexError, TypeError, KeyError): error_url = request.path_info[1:] # Trim leading slash try: tried = exception.args[0]['tried'] except (IndexError, TypeError, KeyError): tried = [] else: if (not tried # empty URLconf or (request.path == '/' and len(tried) == 1 # default URLconf and len(tried[0]) == 1 and getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin')): return default_urlconf(request) urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF) if isinstance(urlconf, types.ModuleType): urlconf = urlconf.__name__ caller = '' try: resolver_match = resolve(request.path) except Resolver404: pass else: obj = resolver_match.func if hasattr(obj, '__name__'): caller = obj.__name__ elif hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'): caller = obj.__class__.__name__ if hasattr(obj, '__module__'): module = obj.__module__ caller = '%s.%s' % (module, caller) t = DEBUG_ENGINE.from_string(TECHNICAL_404_TEMPLATE) c = Context({ 'urlconf': urlconf, 'root_urlconf': settings.ROOT_URLCONF, 'request_path': error_url, 'urlpatterns': tried, 'reason': force_bytes(exception, errors='replace'), 'request': request, 'settings': get_safe_settings(), 'raising_view_name': caller, }) return HttpResponseNotFound(t.render(c), content_type='text/html') def default_urlconf(request): 'Create an empty URLconf 404 error response.' t = DEBUG_ENGINE.from_string(DEFAULT_URLCONF_TEMPLATE) c = Context({ 'title': _('Welcome to Django'), 'heading': _('It worked!'), 'subheading': _('Congratulations on your first Django-powered page.'), 'instructions': _('Of course, you haven't actually done any work yet. ' 'Next, start your first app by running <code>python manage.py startapp [app_label]</code>.'), 'explanation': _('You're seeing this message because you have <code>DEBUG = True</code> in your ' 'Django settings file and you haven't configured any URLs. Get to work!'), }) return HttpResponse(t.render(c), content_type='text/html') # # Templates are embedded in the file so that we know the error handler will # always work even if the template loader is broken. # TECHNICAL_500_TEMPLATE = (""" <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>{% if exception_type %}{{ exception_type }}{% else %}Report{% endif %}''' '''{% if request %} at {{ request.path_info|escape }}{% endif %}</title> <style type='text/css'> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; } h2 { margin-bottom:.8em; } h2 span { font-size:80%; color:#666; font-weight:normal; } h3 { margin:1em 0 .5em 0; } h4 { margin:0 0 .5em 0; font-weight: normal; } code, pre { font-size: 100%; white-space: pre-wrap; } table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; } tbody td, tbody th { vertical-align:top; padding:2px 3px; } thead th { padding:1px 6px 1px 3px; background:#fefefe; text-align:left; font-weight:normal; font-size:11px; border:1px solid #ddd; } tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; } table.vars { margin:5px 0 2px 40px; } table.vars td, table.req td { font-family:monospace; } table td.code { width:100%; } table td.code pre { overflow:hidden; } table.source th { color:#666; } table.source td { font-family:monospace; white-space:pre; border-bottom:1px solid #eee; } ul.traceback { list-style-type:none; color: #222; } ul.traceback li.frame { padding-bottom:1em; color:#666; } ul.traceback li.user { background-color:#e0e0e0; color:#000 } div.context { padding:10px 0; overflow:hidden; } div.context ol { padding-left:30px; margin:0 10px; list-style-position: inside; } div.context ol li { font-family:monospace; white-space:pre; color:#777; cursor:pointer; padding-left: 2px; } div.context ol li pre { display:inline; } div.context ol.context-line li { color:#505050; background-color:#dfdfdf; padding: 3px 2px; } div.context ol.context-line li span { position:absolute; right:32px; } .user div.context ol.context-line li { background-color:#bbb; color:#000; } .user div.context ol li { color:#666; } div.commands { margin-left: 40px; } div.commands a { color:#555; text-decoration:none; } .user div.commands a { color: black; } #summary { background: #ffc; } #summary h2 { font-weight: normal; color: #666; } #explanation { background:#eee; } #template, #template-not-exist { background:#f6f6f6; } #template-not-exist ul { margin: 0 0 10px 20px; } #template-not-exist .postmortem-section { margin-bottom: 3px; } #unicode-hint { background:#eee; } #traceback { background:#eee; } #requestinfo { background:#f6f6f6; padding-left:120px; } #summary table { border:none; background:transparent; } #requestinfo h2, #requestinfo h3 { position:relative; margin-left:-100px; } #requestinfo h3 { margin-bottom:-1em; } .error { background: #ffc; } .specific { color:#cc3300; font-weight:bold; } h2 span.commands { font-size:.7em;} span.commands a:link {color:#5E5694;} pre.exception_value { font-family: sans-serif; color: #666; font-size: 1.5em; margin: 10px 0 10px 0; } .append-bottom { margin-bottom: 10px; } </style> {% if not is_email %} <script type='text/javascript'> //<!-- function getElementsByClassName(oElm, strTagName, strClassName){ // Written by Jonathan Snook, http://www.snook.ca/jon; Add-ons by Robert Nyman, http://www.robertnyman.com var arrElements = (strTagName == '*' && document.all)? document.all : oElm.getElementsByTagName(strTagName); var arrReturnElements = new Array(); strClassName = strClassName.replace(/\-/g, '\\-'); var oRegExp = new RegExp('(^|\\s)' + strClassName + '(\\s|$)'); var oElement; for(var i=0; i<arrElements.length; i++){ oElement = arrElements[i]; if(oRegExp.test(oElement.className)){ arrReturnElements.push(oElement); } } return (arrReturnElements) } function hideAll(elems) { for (var e = 0; e < elems.length; e++) { elems[e].style.display = 'none'; } } window.onload = function() { hideAll(getElementsByClassName(document, 'table', 'vars')); hideAll(getElementsByClassName(document, 'ol', 'pre-context')); hideAll(getElementsByClassName(document, 'ol', 'post-context')); hideAll(getElementsByClassName(document, 'div', 'pastebin')); } function toggle() { for (var i = 0; i < arguments.length; i++) { var e = document.getElementById(arguments[i]); if (e) { e.style.display = e.style.display == 'none' ? 'block': 'none'; } } return false; } function varToggle(link, id) { toggle('v' + id); var s = link.getElementsByTagName('span')[0]; var uarr = String.fromCharCode(0x25b6); var darr = String.fromCharCode(0x25bc); s.textContent = s.textContent == uarr ? darr : uarr; return false; } function switchPastebinFriendly(link) { s1 = 'Switch to copy-and-paste view'; s2 = 'Switch back to interactive view'; link.textContent = link.textContent.trim() == s1 ? s2: s1; toggle('browserTraceback', 'pastebinTraceback'); return false; } //--> </script> {% endif %} </head> <body> <div id='summary'> <h1>{% if exception_type %}{{ exception_type }}{% else %}Report{% endif %}''' '''{% if request %} at {{ request.path_info|escape }}{% endif %}</h1> <pre class='exception_value'>''' '''{% if exception_value %}{{ exception_value|force_escape }}{% else %}No exception message supplied{% endif %}''' '''</pre> <table class='meta'> {% if request %} <tr> <th>Request Method:</th> <td>{{ request.META.REQUEST_METHOD }}</td> </tr> <tr> <th>Request URL:</th> <td>{{ request.get_raw_uri|escape }}</td> </tr> {% endif %} <tr> <th>Django Version:</th> <td>{{ django_version_info }}</td> </tr> {% if exception_type %} <tr> <th>Exception Type:</th> <td>{{ exception_type }}</td> </tr> {% endif %} {% if exception_type and exception_value %} <tr> <th>Exception Value:</th> <td><pre>{{ exception_value|force_escape }}</pre></td> </tr> {% endif %} {% if lastframe %} <tr> <th>Exception Location:</th> <td>{{ lastframe.filename|escape }} in {{ lastframe.function|escape }}, line {{ lastframe.lineno }}</td> </tr> {% endif %} <tr> <th>Python Executable:</th> <td>{{ sys_executable|escape }}</td> </tr> <tr> <th>Python Version:</th> <td>{{ sys_version_info }}</td> </tr> <tr> <th>Python Path:</th> <td><pre>{{ sys_path|pprint }}</pre></td> </tr> <tr> <th>Server time:</th> <td>{{server_time|date:'r'}}</td> </tr> </table> </div> {% if unicode_hint %} <div id='unicode-hint'> <h2>Unicode error hint</h2> <p>The string that could not be encoded/decoded was: <strong>{{ unicode_hint|force_escape }}</strong></p> </div> {% endif %} {% if template_does_not_exist %} <div id='template-not-exist'> <h2>Template-loader postmortem</h2> {% if postmortem %} <p class="append-bottom">Django tried loading these templates, in this order:</p> {% for entry in postmortem %} <p class='postmortem-section'>Using engine <code>{{ entry.backend.name }}</code>:</p> <ul> {% if entry.tried %} {% for attempt in entry.tried %} <li><code>{{ attempt.0.loader_name }}</code>: {{ attempt.0.name }} ({{ attempt.1 }})</li> {% endfor %} </ul> {% else %} <li>This engine did not provide a list of tried templates.</li> {% endif %} </ul> {% endfor %} {% else %} <p>No templates were found because your 'TEMPLATES' setting is not configured.</p> {% endif %} </div> {% endif %} {% if template_info %} <div id='template'> <h2>Error during template rendering</h2> <p>In template <code>{{ template_info.name }}</code>, error at line <strong>{{ template_info.line }}</strong></p> <h3>{{ template_info.message }}</h3> <table class='source{% if template_info.top %} cut-top{% endif %} {% if template_info.bottom != template_info.total %} cut-bottom{% endif %}'> {% for source_line in template_info.source_lines %} {% if source_line.0 == template_info.line %} <tr class='error'><th>{{ source_line.0 }}</th> <td>{{ template_info.before }}''' '''<span class='specific'>{{ template_info.during }}</span>""" """{{ template_info.after }}</td> </tr> {% else %} <tr><th>{{ source_line.0 }}</th> <td>{{ source_line.1 }}</td></tr> {% endif %} {% endfor %} </table> </div> {% endif %} {% if frames %} <div id='traceback'> <h2>Traceback <span class='commands'>{% if not is_email %}<a href="#" onclick="return switchPastebinFriendly(this);"> Switch to copy-and-paste view</a></span>{% endif %} </h2> {% autoescape off %} <div id='browserTraceback'> <ul class='traceback'> {% for frame in frames %} {% ifchanged frame.exc_cause %}{% if frame.exc_cause %} <li><h3> {% if frame.exc_cause_explicit %} The above exception ({{ frame.exc_cause }}) was the direct cause of the following exception: {% else %} During handling of the above exception ({{ frame.exc_cause }}), another exception occurred: {% endif %} </h3></li> {% endif %}{% endifchanged %} <li class='frame {{ frame.type }}'> <code>{{ frame.filename|escape }}</code> in <code>{{ frame.function|escape }}</code> {% if frame.context_line %} <div class='context' id='c{{ frame.id }}"> {% if frame.pre_context and not is_email %} <ol start='{{ frame.pre_context_lineno }}' class='pre-context' id='pre{{ frame.id }}"> {% for line in frame.pre_context %} <li onclick='toggle('pre{{ frame.id }}', 'post{{ frame.id }}')'><pre>{{ line|escape }}</pre></li> {% endfor %} </ol> {% endif %} <ol start='{{ frame.lineno }}' class='context-line'> <li onclick='toggle('pre{{ frame.id }}', 'post{{ frame.id }}')'><pre> ''' '''{{ frame.context_line|escape }}</pre>{% if not is_email %} <span>...</span>{% endif %}</li></ol> {% if frame.post_context and not is_email %} <ol start='{{ frame.lineno|add:'1' }}' class="post-context" id="post{{ frame.id }}'> {% for line in frame.post_context %} <li onclick='toggle('pre{{ frame.id }}', 'post{{ frame.id }}')'><pre>{{ line|escape }}</pre></li> {% endfor %} </ol> {% endif %} </div> {% endif %} {% if frame.vars %} <div class='commands'> {% if is_email %} <h2>Local Vars</h2> {% else %} <a href='#' onclick='return varToggle(this, '{{ frame.id }}')"><span>&#x25b6;</span> Local vars</a> {% endif %} </div> <table class='vars' id='v{{ frame.id }}"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in frame.vars|dictsort:'0' %} <tr> <td>{{ var.0|force_escape }}</td> <td class='code'><pre>{{ var.1 }}</pre></td> </tr> {% endfor %} </tbody> </table> {% endif %} </li> {% endfor %} </ul> </div> {% endautoescape %} <form action='http://dpaste.com/' name='pasteform' id='pasteform' method='post'> {% if not is_email %} <div id="pastebinTraceback" class="pastebin"> <input type="hidden" name="language" value="PythonConsole"> <input type="hidden" name="title" value="{{ exception_type|escape }}{% if request %} at {{ request.path_info|escape }}{% endif %}'> <input type='hidden' name='source' value='Django Dpaste Agent'> <input type='hidden' name='poster' value='Django'> <textarea name='content' id='traceback_area' cols='140' rows='25'> Environment: {% if request %} Request Method: {{ request.META.REQUEST_METHOD }} Request URL: {{ request.get_raw_uri|escape }} {% endif %} Django Version: {{ django_version_info }} Python Version: {{ sys_version_info }} Installed Applications: {{ settings.INSTALLED_APPS|pprint }} Installed Middleware: {{ settings.MIDDLEWARE_CLASSES|pprint }} {% if template_does_not_exist %}Template loader postmortem {% if postmortem %}Django tried loading these templates, in this order: {% for entry in postmortem %} Using engine {{ entry.backend.name }}: {% if entry.tried %}{% for attempt in entry.tried %}''' ''' * {{ attempt.0.loader_name }}: {{ attempt.0.name }} ({{ attempt.1 }}) {% endfor %}{% else %} This engine did not provide a list of tried templates. {% endif %}{% endfor %} {% else %}No templates were found because your 'TEMPLATES' setting is not configured. {% endif %}{% endif %}{% if template_info %} Template error: In template {{ template_info.name }}, error at line {{ template_info.line }} {{ template_info.message }}''' '{% for source_line in template_info.source_lines %}" "{% if source_line.0 == template_info.line %}' ' {{ source_line.0 }} : {{ template_info.before }} {{ template_info.during }} {{ template_info.after }}' '{% else %}" " {{ source_line.0 }} : {{ source_line.1 }}' '''{% endif %}{% endfor %}{% endif %} Traceback:{% for frame in frames %} {% ifchanged frame.exc_cause %}{% if frame.exc_cause %}{% if frame.exc_cause_explicit %} The above exception ({{ frame.exc_cause }}) was the direct cause of the following exception: {% else %} During handling of the above exception ({{ frame.exc_cause }}), another exception occurred: {% endif %}{% endif %}{% endifchanged %} File '{{ frame.filename|escape }}' in {{ frame.function|escape }} {% if frame.context_line %} {{ frame.lineno }}. {{ frame.context_line|escape }}{% endif %}{% endfor %} Exception Type: {{ exception_type|escape }}{% if request %} at {{ request.path_info|escape }}{% endif %} Exception Value: {{ exception_value|force_escape }} </textarea> <br><br> <input type='submit' value='Share this traceback on a public website'> </div> </form> </div> {% endif %} {% endif %} <div id='requestinfo'> <h2>Request information</h2> {% if request %} <h3 id="get-info">GET</h3> {% if request.GET %} <table class='req'> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in request.GET.items %} <tr> <td>{{ var.0 }}</td> <td class='code'><pre>{{ var.1|pprint }}</pre></td> </tr> {% endfor %} </tbody> </table> {% else %} <p>No GET data</p> {% endif %} <h3 id='post-info'>POST</h3> {% if filtered_POST %} <table class="req"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in filtered_POST.items %} <tr> <td>{{ var.0 }}</td> <td class='code'><pre>{{ var.1|pprint }}</pre></td> </tr> {% endfor %} </tbody> </table> {% else %} <p>No POST data</p> {% endif %} <h3 id='files-info'>FILES</h3> {% if request.FILES %} <table class="req"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in request.FILES.items %} <tr> <td>{{ var.0 }}</td> <td class='code'><pre>{{ var.1|pprint }}</pre></td> </tr> {% endfor %} </tbody> </table> {% else %} <p>No FILES data</p> {% endif %} <h3 id='cookie-info'>COOKIES</h3> {% if request.COOKIES %} <table class="req"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in request.COOKIES.items %} <tr> <td>{{ var.0 }}</td> <td class='code'><pre>{{ var.1|pprint }}</pre></td> </tr> {% endfor %} </tbody> </table> {% else %} <p>No cookie data</p> {% endif %} <h3 id='meta-info'>META</h3> <table class='req'> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in request.META.items|dictsort:'0' %} <tr> <td>{{ var.0 }}</td> <td class='code'><pre>{{ var.1|pprint }}</pre></td> </tr> {% endfor %} </tbody> </table> {% else %} <p>Request data not supplied</p> {% endif %} <h3 id='settings-info'>Settings</h3> <h4>Using settings module <code>{{ settings.SETTINGS_MODULE }}</code></h4> <table class="req"> <thead> <tr> <th>Setting</th> <th>Value</th> </tr> </thead> <tbody> {% for var in settings.items|dictsort:'0' %} <tr> <td>{{ var.0 }}</td> <td class='code'><pre>{{ var.1|pprint }}</pre></td> </tr> {% endfor %} </tbody> </table> </div> {% if not is_email %} <div id='explanation'> <p> You're seeing this error because you have <code>DEBUG = True</code> in your Django settings file. Change that to <code>False</code>, and Django will display a standard page generated by the handler for this status code. </p> </div> {% endif %} </body> </html> """) TECHNICAL_500_TEXT_TEMPLATE = ("""""" """{% firstof exception_type 'Report' %}{% if request %} at {{ request.path_info }}{% endif %} {% firstof exception_value 'No exception message supplied' %} {% if request %} Request Method: {{ request.META.REQUEST_METHOD }} Request URL: {{ request.get_raw_uri }}{% endif %} Django Version: {{ django_version_info }} Python Executable: {{ sys_executable }} Python Version: {{ sys_version_info }} Python Path: {{ sys_path }} Server time: {{server_time|date:'r'}} Installed Applications: {{ settings.INSTALLED_APPS|pprint }} Installed Middleware: {{ settings.MIDDLEWARE_CLASSES|pprint }} {% if template_does_not_exist %}Template loader postmortem {% if postmortem %}Django tried loading these templates, in this order: {% for entry in postmortem %} Using engine {{ entry.backend.name }}: {% if entry.tried %}{% for attempt in entry.tried %}''' ''' * {{ attempt.0.loader_name }}: {{ attempt.0.name }} ({{ attempt.1 }}) {% endfor %}{% else %} This engine did not provide a list of tried templates. {% endif %}{% endfor %} {% else %}No templates were found because your 'TEMPLATES' setting is not configured. {% endif %} {% endif %}{% if template_info %} Template error: In template {{ template_info.name }}, error at line {{ template_info.line }} {{ template_info.message }} {% for source_line in template_info.source_lines %}''' '{% if source_line.0 == template_info.line %}" " {{ source_line.0 }} : {{ template_info.before }} {{ template_info.during }} {{ template_info.after }}' '{% else %}" " {{ source_line.0 }} : {{ source_line.1 }}' '''{% endif %}{% endfor %}{% endif %}{% if frames %} Traceback:''' '{% for frame in frames %}" "{% ifchanged frame.exc_cause %}' ' {% if frame.exc_cause %}" """ {% if frame.exc_cause_explicit %} The above exception ({{ frame.exc_cause }}) was the direct cause of the following exception: {% else %} During handling of the above exception ({{ frame.exc_cause }}), another exception occurred: {% endif %} {% endif %} {% endifchanged %} File '{{ frame.filename }}' in {{ frame.function }} {% if frame.context_line %} {{ frame.lineno }}. {{ frame.context_line }}{% endif %} {% endfor %} {% if exception_type %}Exception Type: {{ exception_type }}{% if request %} at {{ request.path_info }}{% endif %} {% if exception_value %}Exception Value: {{ exception_value }}{% endif %}{% endif %}{% endif %} {% if request %}Request information: GET:{% for k, v in request.GET.items %} {{ k }} = {{ v|stringformat:'r' }}{% empty %} No GET data{% endfor %} POST:{% for k, v in filtered_POST.items %} {{ k }} = {{ v|stringformat:'r' }}{% empty %} No POST data{% endfor %} FILES:{% for k, v in request.FILES.items %} {{ k }} = {{ v|stringformat:'r' }}{% empty %} No FILES data{% endfor %} COOKIES:{% for k, v in request.COOKIES.items %} {{ k }} = {{ v|stringformat:'r' }}{% empty %} No cookie data{% endfor %} META:{% for k, v in request.META.items|dictsort:'0' %} {{ k }} = {{ v|stringformat:'r' }}{% endfor %} {% else %}Request data not supplied {% endif %} Settings: Using settings module {{ settings.SETTINGS_MODULE }}{% for k, v in settings.items|dictsort:'0' %} {{ k }} = {{ v|stringformat:'r' }}{% endfor %} {% if not is_email %} You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard page generated by the handler for this status code. {% endif %} ''') TECHNICAL_404_TEMPLATE = ''' <!DOCTYPE html> <html lang='en'> <head> <meta http-equiv='content-type' content='text/html; charset=utf-8'> <title>Page not found at {{ request.path_info|escape }}</title> <meta name="robots" content="NONE,NOARCHIVE"> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; margin-bottom:.4em; } h1 span { font-size:60%; color:#666; font-weight:normal; } table { border:none; border-collapse: collapse; width:100%; } td, th { vertical-align:top; padding:2px 3px; } th { width:12em; text-align:right; color:#666; padding-right:.5em; } #info { background:#f6f6f6; } #info ol { margin: 0.5em 4em; } #info ol li { font-family: monospace; } #summary { background: #ffc; } #explanation { background:#eee; border-bottom: 0px none; } </style> </head> <body> <div id='summary'> <h1>Page not found <span>(404)</span></h1> <table class='meta'> <tr> <th>Request Method:</th> <td>{{ request.META.REQUEST_METHOD }}</td> </tr> <tr> <th>Request URL:</th> <td>{{ request.build_absolute_uri|escape }}</td> </tr> {% if raising_view_name %} <tr> <th>Raised by:</th> <td>{{ raising_view_name }}</td> </tr> {% endif %} </table> </div> <div id='info'> {% if urlpatterns %} <p> Using the URLconf defined in <code>{{ urlconf }}</code>, Django tried these URL patterns, in this order: </p> <ol> {% for pattern in urlpatterns %} <li> {% for pat in pattern %} {{ pat.regex.pattern }} {% if forloop.last and pat.name %}[name='{{ pat.name }}']{% endif %} {% endfor %} </li> {% endfor %} </ol> <p>The current URL, <code>{{ request_path|escape }}</code>, didn't match any of these.</p> {% else %} <p>{{ reason }}</p> {% endif %} </div> <div id="explanation"> <p> You're seeing this error because you have <code>DEBUG = True</code> in your Django settings file. Change that to <code>False</code>, and Django will display a standard 404 page. </p> </div> </body> </html> """ DEFAULT_URLCONF_TEMPLATE = """ <!DOCTYPE html> <html lang="en"><head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"><title>{{ title }}</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; } h2 { margin-bottom:.8em; } h2 span { font-size:80%; color:#666; font-weight:normal; } h3 { margin:1em 0 .5em 0; } h4 { margin:0 0 .5em 0; font-weight: normal; } table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; } tbody td, tbody th { vertical-align:top; padding:2px 3px; } thead th { padding:1px 6px 1px 3px; background:#fefefe; text-align:left; font-weight:normal; font-size:11px; border:1px solid #ddd; } tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; } #summary { background: #e0ebff; } #summary h2 { font-weight: normal; color: #666; } #explanation { background:#eee; } #instructions { background:#f6f6f6; } #summary table { border:none; background:transparent; } </style> </head> <body> <div id="summary"> <h1>{{ heading }}</h1> <h2>{{ subheading }}</h2> </div> <div id="instructions"> <p> {{ instructions|safe }} </p> </div> <div id="explanation"> <p> {{ explanation|safe }} </p> </div> </body></html> """
from __future__ import unicode_literals import re import sys import types from django.conf import settings from django.core.urlresolvers import Resolver404, resolve from django.http import HttpResponse, HttpResponseNotFound from django.template import Context, Engine, TemplateDoesNotExist from django.template.defaultfilters import force_escape, pprint from django.utils import lru_cache, six, timezone from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_bytes, smart_text from django.utils.module_loading import import_string from django.utils.translation import ugettext as _ # Minimal Django templates engine to render the error templates # regardless of the project's TEMPLATES setting. DEBUG_ENGINE = Engine(debug=True) HIDDEN_SETTINGS = re.compile('API|TOKEN|KEY|SECRET|PASS|SIGNATURE') CLEANSED_SUBSTITUTE = '********************' class CallableSettingWrapper(object): """ Object to wrap callable appearing in settings * Not to call in the debug page (#21345). * Not to break the debug page if the callable forbidding to set attributes (#23070). """ def __init__(self, callable_setting): self._wrapped = callable_setting def __repr__(self): return repr(self._wrapped) def cleanse_setting(key, value): """Cleanse an individual setting key/value of sensitive content. If the value is a dictionary, recursively cleanse the keys in that dictionary. """ try: if HIDDEN_SETTINGS.search(key): cleansed = CLEANSED_SUBSTITUTE else: if isinstance(value, dict): cleansed = {k: cleanse_setting(k, v) for k, v in value.items()} else: cleansed = value except TypeError: # If the key isn't regex-able, just return as-is. cleansed = value if callable(cleansed): # For fixing #21345 and #23070 cleansed = CallableSettingWrapper(cleansed) return cleansed def get_safe_settings(): "Returns a dictionary of the settings module, with sensitive settings blurred out." settings_dict = {} for k in dir(settings): if k.isupper(): settings_dict[k] = cleanse_setting(k, getattr(settings, k)) return settings_dict def technical_500_response(request, exc_type, exc_value, tb, status_code=500): """ Create a technical server error response. The last three arguments are the values returned from sys.exc_info() and friends. """ reporter = ExceptionReporter(request, exc_type, exc_value, tb) if request.is_ajax(): text = reporter.get_traceback_text() return HttpResponse(text, status=status_code, content_type='text/plain') else: html = reporter.get_traceback_html() return HttpResponse(html, status=status_code, content_type='text/html') @lru_cache.lru_cache() def get_default_exception_reporter_filter(): # Instantiate the default filter for the first time and cache it. return import_string(settings.DEFAULT_EXCEPTION_REPORTER_FILTER)() def get_exception_reporter_filter(request): default_filter = get_default_exception_reporter_filter() return getattr(request, 'exception_reporter_filter', default_filter) class ExceptionReporterFilter(object): """ Base for all exception reporter filter classes. All overridable hooks contain lenient default behaviors. """ def get_post_parameters(self, request): if request is None: return {} else: return request.POST def get_traceback_frame_variables(self, request, tb_frame): return list(tb_frame.f_locals.items()) class SafeExceptionReporterFilter(ExceptionReporterFilter): """ Use annotations made by the sensitive_post_parameters and sensitive_variables decorators to filter out sensitive information. """ def is_active(self, request): """ This filter is to add safety in production environments (i.e. DEBUG is False). If DEBUG is True then your site is not safe anyway. This hook is provided as a convenience to easily activate or deactivate the filter on a per request basis. """ return settings.DEBUG is False def get_cleansed_multivaluedict(self, request, multivaluedict): """ Replaces the keys in a MultiValueDict marked as sensitive with stars. This mitigates leaking sensitive POST parameters if something like request.POST['nonexistent_key'] throws an exception (#21098). """ sensitive_post_parameters = getattr(request, 'sensitive_post_parameters', []) if self.is_active(request) and sensitive_post_parameters: multivaluedict = multivaluedict.copy() for param in sensitive_post_parameters: if param in multivaluedict: multivaluedict[param] = CLEANSED_SUBSTITUTE return multivaluedict def get_post_parameters(self, request): """ Replaces the values of POST parameters marked as sensitive with stars (*********). """ if request is None: return {} else: sensitive_post_parameters = getattr(request, 'sensitive_post_parameters', []) if self.is_active(request) and sensitive_post_parameters: cleansed = request.POST.copy() if sensitive_post_parameters == '__ALL__': # Cleanse all parameters. for k, v in cleansed.items(): cleansed[k] = CLEANSED_SUBSTITUTE return cleansed else: # Cleanse only the specified parameters. for param in sensitive_post_parameters: if param in cleansed: cleansed[param] = CLEANSED_SUBSTITUTE return cleansed else: return request.POST def cleanse_special_types(self, request, value): try: # If value is lazy or a complex object of another kind, this check # might raise an exception. isinstance checks that lazy # MultiValueDicts will have a return value. is_multivalue_dict = isinstance(value, MultiValueDict) except Exception as e: return '{!r} while evaluating {!r}'.format(e, value) if is_multivalue_dict: # Cleanse MultiValueDicts (request.POST is the one we usually care about) value = self.get_cleansed_multivaluedict(request, value) return value def get_traceback_frame_variables(self, request, tb_frame): """ Replaces the values of variables marked as sensitive with stars (*********). """ # Loop through the frame's callers to see if the sensitive_variables # decorator was used. current_frame = tb_frame.f_back sensitive_variables = None while current_frame is not None: if (current_frame.f_code.co_name == 'sensitive_variables_wrapper' and 'sensitive_variables_wrapper' in current_frame.f_locals): # The sensitive_variables decorator was used, so we take note # of the sensitive variables' names. wrapper = current_frame.f_locals['sensitive_variables_wrapper'] sensitive_variables = getattr(wrapper, 'sensitive_variables', None) break current_frame = current_frame.f_back cleansed = {} if self.is_active(request) and sensitive_variables: if sensitive_variables == '__ALL__': # Cleanse all variables for name, value in tb_frame.f_locals.items(): cleansed[name] = CLEANSED_SUBSTITUTE else: # Cleanse specified variables for name, value in tb_frame.f_locals.items(): if name in sensitive_variables: value = CLEANSED_SUBSTITUTE else: value = self.cleanse_special_types(request, value) cleansed[name] = value else: # Potentially cleanse the request and any MultiValueDicts if they # are one of the frame variables. for name, value in tb_frame.f_locals.items(): cleansed[name] = self.cleanse_special_types(request, value) if (tb_frame.f_code.co_name == 'sensitive_variables_wrapper' and 'sensitive_variables_wrapper' in tb_frame.f_locals): # For good measure, obfuscate the decorated function's arguments in # the sensitive_variables decorator's frame, in case the variables # associated with those arguments were meant to be obfuscated from # the decorated function's frame. cleansed['func_args'] = CLEANSED_SUBSTITUTE cleansed['func_kwargs'] = CLEANSED_SUBSTITUTE return cleansed.items() class ExceptionReporter(object): """ A class to organize and coordinate reporting on exceptions. """ def __init__(self, request, exc_type, exc_value, tb, is_email=False): self.request = request self.filter = get_exception_reporter_filter(self.request) self.exc_type = exc_type self.exc_value = exc_value self.tb = tb self.is_email = is_email self.template_info = getattr(self.exc_value, 'template_debug', None) self.template_does_not_exist = False self.postmortem = None # Handle deprecated string exceptions if isinstance(self.exc_type, six.string_types): self.exc_value = Exception('Deprecated String Exception: %r' % self.exc_type) self.exc_type = type(self.exc_value) def get_traceback_data(self): """Return a dictionary containing traceback information.""" if self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist): self.template_does_not_exist = True self.postmortem = self.exc_value.chain or [self.exc_value] frames = self.get_traceback_frames() for i, frame in enumerate(frames): if 'vars' in frame: frame_vars = [] for k, v in frame['vars']: v = pprint(v) # The force_escape filter assume unicode, make sure that works if isinstance(v, six.binary_type): v = v.decode('utf-8', 'replace') # don't choke on non-utf-8 input # Trim large blobs of data if len(v) > 4096: v = '%s... <trimmed %d bytes string>' % (v[0:4096], len(v)) frame_vars.append((k, force_escape(v))) frame['vars'] = frame_vars frames[i] = frame unicode_hint = '' if self.exc_type and issubclass(self.exc_type, UnicodeError): start = getattr(self.exc_value, 'start', None) end = getattr(self.exc_value, 'end', None) if start is not None and end is not None: unicode_str = self.exc_value.args[1] unicode_hint = smart_text( unicode_str[max(start - 5, 0):min(end + 5, len(unicode_str))], 'ascii', errors='replace' ) from django import get_version c = { 'is_email': self.is_email, 'unicode_hint': unicode_hint, 'frames': frames, 'request': self.request, 'filtered_POST': self.filter.get_post_parameters(self.request), 'settings': get_safe_settings(), 'sys_executable': sys.executable, 'sys_version_info': '%d.%d.%d' % sys.version_info[0:3], 'server_time': timezone.now(), 'django_version_info': get_version(), 'sys_path': sys.path, 'template_info': self.template_info, 'template_does_not_exist': self.template_does_not_exist, 'postmortem': self.postmortem, } # Check whether exception info is available if self.exc_type: c['exception_type'] = self.exc_type.__name__ if self.exc_value: c['exception_value'] = smart_text(self.exc_value, errors='replace') if frames: c['lastframe'] = frames[-1] return c def get_traceback_html(self): "Return HTML version of debug 500 HTTP error page." t = DEBUG_ENGINE.from_string(TECHNICAL_500_TEMPLATE) c = Context(self.get_traceback_data(), use_l10n=False) return t.render(c) def get_traceback_text(self): "Return plain text version of debug 500 HTTP error page." t = DEBUG_ENGINE.from_string(TECHNICAL_500_TEXT_TEMPLATE) c = Context(self.get_traceback_data(), autoescape=False, use_l10n=False) return t.render(c) def _get_lines_from_file(self, filename, lineno, context_lines, loader=None, module_name=None): """ Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context). """ source = None if loader is not None and hasattr(loader, "get_source"): try: source = loader.get_source(module_name) except ImportError: pass if source is not None: source = source.splitlines() if source is None: try: with open(filename, 'rb') as fp: source = fp.read().splitlines() except (OSError, IOError): pass if source is None: return None, [], None, [] # If we just read the source from a file, or if the loader did not # apply tokenize.detect_encoding to decode the source into a Unicode # string, then we should do that ourselves. if isinstance(source[0], six.binary_type): encoding = 'ascii' for line in source[:2]: # File coding may be specified. Match pattern from PEP-263 # (http://www.python.org/dev/peps/pep-0263/) match = re.search(br'coding[:=]\s*([-\w.]+)', line) if match: encoding = match.group(1).decode('ascii') break source = [six.text_type(sline, encoding, 'replace') for sline in source] lower_bound = max(0, lineno - context_lines) upper_bound = lineno + context_lines pre_context = source[lower_bound:lineno] context_line = source[lineno] post_context = source[lineno + 1:upper_bound] return lower_bound, pre_context, context_line, post_context def get_traceback_frames(self): def explicit_or_implicit_cause(exc_value): explicit = getattr(exc_value, '__cause__', None) implicit = getattr(exc_value, '__context__', None) return explicit or implicit # Get the exception and all its causes exceptions = [] exc_value = self.exc_value while exc_value: exceptions.append(exc_value) exc_value = explicit_or_implicit_cause(exc_value) frames = [] # No exceptions were supplied to ExceptionReporter if not exceptions: return frames # In case there's just one exception (always in Python 2, # sometimes in Python 3), take the traceback from self.tb (Python 2 # doesn't have a __traceback__ attribute on Exception) exc_value = exceptions.pop() tb = self.tb if six.PY2 or not exceptions else exc_value.__traceback__ while tb is not None: # Support for __traceback_hide__ which is used by a few libraries # to hide internal frames. if tb.tb_frame.f_locals.get('__traceback_hide__'): tb = tb.tb_next continue filename = tb.tb_frame.f_code.co_filename function = tb.tb_frame.f_code.co_name lineno = tb.tb_lineno - 1 loader = tb.tb_frame.f_globals.get('__loader__') module_name = tb.tb_frame.f_globals.get('__name__') or '' pre_context_lineno, pre_context, context_line, post_context = self._get_lines_from_file( filename, lineno, 7, loader, module_name, ) if pre_context_lineno is not None: frames.append({ 'exc_cause': explicit_or_implicit_cause(exc_value), 'exc_cause_explicit': getattr(exc_value, '__cause__', True), 'tb': tb, 'type': 'django' if module_name.startswith('django.') else 'user', 'filename': filename, 'function': function, 'lineno': lineno + 1, 'vars': self.filter.get_traceback_frame_variables(self.request, tb.tb_frame), 'id': id(tb), 'pre_context': pre_context, 'context_line': context_line, 'post_context': post_context, 'pre_context_lineno': pre_context_lineno + 1, }) # If the traceback for current exception is consumed, try the # other exception. if six.PY2: tb = tb.tb_next elif not tb.tb_next and exceptions: exc_value = exceptions.pop() tb = exc_value.__traceback__ else: tb = tb.tb_next return frames def format_exception(self): """ Return the same data as from traceback.format_exception. """ import traceback frames = self.get_traceback_frames() tb = [(f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames] list = ['Traceback (most recent call last):\n'] list += traceback.format_list(tb) list += traceback.format_exception_only(self.exc_type, self.exc_value) return list def technical_404_response(request, exception): "Create a technical 404 error response. The exception should be the Http404." try: error_url = exception.args[0]['path'] except (IndexError, TypeError, KeyError): error_url = request.path_info[1:] # Trim leading slash try: tried = exception.args[0]['tried'] except (IndexError, TypeError, KeyError): tried = [] else: if (not tried # empty URLconf or (request.path == '/' and len(tried) == 1 # default URLconf and len(tried[0]) == 1 and getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin')): return default_urlconf(request) urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF) if isinstance(urlconf, types.ModuleType): urlconf = urlconf.__name__ caller = '' try: resolver_match = resolve(request.path) except Resolver404: pass else: obj = resolver_match.func if hasattr(obj, '__name__'): caller = obj.__name__ elif hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'): caller = obj.__class__.__name__ if hasattr(obj, '__module__'): module = obj.__module__ caller = '%s.%s' % (module, caller) t = DEBUG_ENGINE.from_string(TECHNICAL_404_TEMPLATE) c = Context({ 'urlconf': urlconf, 'root_urlconf': settings.ROOT_URLCONF, 'request_path': error_url, 'urlpatterns': tried, 'reason': force_bytes(exception, errors='replace'), 'request': request, 'settings': get_safe_settings(), 'raising_view_name': caller, }) return HttpResponseNotFound(t.render(c), content_type='text/html') def default_urlconf(request): "Create an empty URLconf 404 error response." t = DEBUG_ENGINE.from_string(DEFAULT_URLCONF_TEMPLATE) c = Context({ "title": _("Welcome to Django"), "heading": _("It worked!"), "subheading": _("Congratulations on your first Django-powered page."), "instructions": _("Of course, you haven't actually done any work yet. " "Next, start your first app by running <code>python manage.py startapp [app_label]</code>."), "explanation": _("You're seeing this message because you have <code>DEBUG = True</code> in your " "Django settings file and you haven't configured any URLs. Get to work!"), }) return HttpResponse(t.render(c), content_type='text/html') # # Templates are embedded in the file so that we know the error handler will # always work even if the template loader is broken. # TECHNICAL_500_TEMPLATE = (""" <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>{% if exception_type %}{{ exception_type }}{% else %}Report{% endif %}""" """{% if request %} at {{ request.path_info|escape }}{% endif %}</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; } h2 { margin-bottom:.8em; } h2 span { font-size:80%; color:#666; font-weight:normal; } h3 { margin:1em 0 .5em 0; } h4 { margin:0 0 .5em 0; font-weight: normal; } code, pre { font-size: 100%; white-space: pre-wrap; } table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; } tbody td, tbody th { vertical-align:top; padding:2px 3px; } thead th { padding:1px 6px 1px 3px; background:#fefefe; text-align:left; font-weight:normal; font-size:11px; border:1px solid #ddd; } tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; } table.vars { margin:5px 0 2px 40px; } table.vars td, table.req td { font-family:monospace; } table td.code { width:100%; } table td.code pre { overflow:hidden; } table.source th { color:#666; } table.source td { font-family:monospace; white-space:pre; border-bottom:1px solid #eee; } ul.traceback { list-style-type:none; color: #222; } ul.traceback li.frame { padding-bottom:1em; color:#666; } ul.traceback li.user { background-color:#e0e0e0; color:#000 } div.context { padding:10px 0; overflow:hidden; } div.context ol { padding-left:30px; margin:0 10px; list-style-position: inside; } div.context ol li { font-family:monospace; white-space:pre; color:#777; cursor:pointer; padding-left: 2px; } div.context ol li pre { display:inline; } div.context ol.context-line li { color:#505050; background-color:#dfdfdf; padding: 3px 2px; } div.context ol.context-line li span { position:absolute; right:32px; } .user div.context ol.context-line li { background-color:#bbb; color:#000; } .user div.context ol li { color:#666; } div.commands { margin-left: 40px; } div.commands a { color:#555; text-decoration:none; } .user div.commands a { color: black; } #summary { background: #ffc; } #summary h2 { font-weight: normal; color: #666; } #explanation { background:#eee; } #template, #template-not-exist { background:#f6f6f6; } #template-not-exist ul { margin: 0 0 10px 20px; } #template-not-exist .postmortem-section { margin-bottom: 3px; } #unicode-hint { background:#eee; } #traceback { background:#eee; } #requestinfo { background:#f6f6f6; padding-left:120px; } #summary table { border:none; background:transparent; } #requestinfo h2, #requestinfo h3 { position:relative; margin-left:-100px; } #requestinfo h3 { margin-bottom:-1em; } .error { background: #ffc; } .specific { color:#cc3300; font-weight:bold; } h2 span.commands { font-size:.7em;} span.commands a:link {color:#5E5694;} pre.exception_value { font-family: sans-serif; color: #666; font-size: 1.5em; margin: 10px 0 10px 0; } .append-bottom { margin-bottom: 10px; } </style> {% if not is_email %} <script type="text/javascript"> //<!-- function getElementsByClassName(oElm, strTagName, strClassName){ // Written by Jonathan Snook, http://www.snook.ca/jon; Add-ons by Robert Nyman, http://www.robertnyman.com var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName); var arrReturnElements = new Array(); strClassName = strClassName.replace(/\-/g, "\\-"); var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)"); var oElement; for(var i=0; i<arrElements.length; i++){ oElement = arrElements[i]; if(oRegExp.test(oElement.className)){ arrReturnElements.push(oElement); } } return (arrReturnElements) } function hideAll(elems) { for (var e = 0; e < elems.length; e++) { elems[e].style.display = 'none'; } } window.onload = function() { hideAll(getElementsByClassName(document, 'table', 'vars')); hideAll(getElementsByClassName(document, 'ol', 'pre-context')); hideAll(getElementsByClassName(document, 'ol', 'post-context')); hideAll(getElementsByClassName(document, 'div', 'pastebin')); } function toggle() { for (var i = 0; i < arguments.length; i++) { var e = document.getElementById(arguments[i]); if (e) { e.style.display = e.style.display == 'none' ? 'block': 'none'; } } return false; } function varToggle(link, id) { toggle('v' + id); var s = link.getElementsByTagName('span')[0]; var uarr = String.fromCharCode(0x25b6); var darr = String.fromCharCode(0x25bc); s.textContent = s.textContent == uarr ? darr : uarr; return false; } function switchPastebinFriendly(link) { s1 = "Switch to copy-and-paste view"; s2 = "Switch back to interactive view"; link.textContent = link.textContent.trim() == s1 ? s2: s1; toggle('browserTraceback', 'pastebinTraceback'); return false; } //--> </script> {% endif %} </head> <body> <div id="summary"> <h1>{% if exception_type %}{{ exception_type }}{% else %}Report{% endif %}""" """{% if request %} at {{ request.path_info|escape }}{% endif %}</h1> <pre class="exception_value">""" """{% if exception_value %}{{ exception_value|force_escape }}{% else %}No exception message supplied{% endif %}""" """</pre> <table class="meta"> {% if request %} <tr> <th>Request Method:</th> <td>{{ request.META.REQUEST_METHOD }}</td> </tr> <tr> <th>Request URL:</th> <td>{{ request.get_raw_uri|escape }}</td> </tr> {% endif %} <tr> <th>Django Version:</th> <td>{{ django_version_info }}</td> </tr> {% if exception_type %} <tr> <th>Exception Type:</th> <td>{{ exception_type }}</td> </tr> {% endif %} {% if exception_type and exception_value %} <tr> <th>Exception Value:</th> <td><pre>{{ exception_value|force_escape }}</pre></td> </tr> {% endif %} {% if lastframe %} <tr> <th>Exception Location:</th> <td>{{ lastframe.filename|escape }} in {{ lastframe.function|escape }}, line {{ lastframe.lineno }}</td> </tr> {% endif %} <tr> <th>Python Executable:</th> <td>{{ sys_executable|escape }}</td> </tr> <tr> <th>Python Version:</th> <td>{{ sys_version_info }}</td> </tr> <tr> <th>Python Path:</th> <td><pre>{{ sys_path|pprint }}</pre></td> </tr> <tr> <th>Server time:</th> <td>{{server_time|date:"r"}}</td> </tr> </table> </div> {% if unicode_hint %} <div id="unicode-hint"> <h2>Unicode error hint</h2> <p>The string that could not be encoded/decoded was: <strong>{{ unicode_hint|force_escape }}</strong></p> </div> {% endif %} {% if template_does_not_exist %} <div id="template-not-exist"> <h2>Template-loader postmortem</h2> {% if postmortem %} <p class="append-bottom">Django tried loading these templates, in this order:</p> {% for entry in postmortem %} <p class="postmortem-section">Using engine <code>{{ entry.backend.name }}</code>:</p> <ul> {% if entry.tried %} {% for attempt in entry.tried %} <li><code>{{ attempt.0.loader_name }}</code>: {{ attempt.0.name }} ({{ attempt.1 }})</li> {% endfor %} </ul> {% else %} <li>This engine did not provide a list of tried templates.</li> {% endif %} </ul> {% endfor %} {% else %} <p>No templates were found because your 'TEMPLATES' setting is not configured.</p> {% endif %} </div> {% endif %} {% if template_info %} <div id="template"> <h2>Error during template rendering</h2> <p>In template <code>{{ template_info.name }}</code>, error at line <strong>{{ template_info.line }}</strong></p> <h3>{{ template_info.message }}</h3> <table class="source{% if template_info.top %} cut-top{% endif %} {% if template_info.bottom != template_info.total %} cut-bottom{% endif %}"> {% for source_line in template_info.source_lines %} {% if source_line.0 == template_info.line %} <tr class="error"><th>{{ source_line.0 }}</th> <td>{{ template_info.before }}""" """<span class="specific">{{ template_info.during }}</span>""" """{{ template_info.after }}</td> </tr> {% else %} <tr><th>{{ source_line.0 }}</th> <td>{{ source_line.1 }}</td></tr> {% endif %} {% endfor %} </table> </div> {% endif %} {% if frames %} <div id="traceback"> <h2>Traceback <span class="commands">{% if not is_email %}<a href="#" onclick="return switchPastebinFriendly(this);"> Switch to copy-and-paste view</a></span>{% endif %} </h2> {% autoescape off %} <div id="browserTraceback"> <ul class="traceback"> {% for frame in frames %} {% ifchanged frame.exc_cause %}{% if frame.exc_cause %} <li><h3> {% if frame.exc_cause_explicit %} The above exception ({{ frame.exc_cause }}) was the direct cause of the following exception: {% else %} During handling of the above exception ({{ frame.exc_cause }}), another exception occurred: {% endif %} </h3></li> {% endif %}{% endifchanged %} <li class="frame {{ frame.type }}"> <code>{{ frame.filename|escape }}</code> in <code>{{ frame.function|escape }}</code> {% if frame.context_line %} <div class="context" id="c{{ frame.id }}"> {% if frame.pre_context and not is_email %} <ol start="{{ frame.pre_context_lineno }}" class="pre-context" id="pre{{ frame.id }}"> {% for line in frame.pre_context %} <li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')"><pre>{{ line|escape }}</pre></li> {% endfor %} </ol> {% endif %} <ol start="{{ frame.lineno }}" class="context-line"> <li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')"><pre> """ """{{ frame.context_line|escape }}</pre>{% if not is_email %} <span>...</span>{% endif %}</li></ol> {% if frame.post_context and not is_email %} <ol start='{{ frame.lineno|add:"1" }}' class="post-context" id="post{{ frame.id }}"> {% for line in frame.post_context %} <li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')"><pre>{{ line|escape }}</pre></li> {% endfor %} </ol> {% endif %} </div> {% endif %} {% if frame.vars %} <div class="commands"> {% if is_email %} <h2>Local Vars</h2> {% else %} <a href="#" onclick="return varToggle(this, '{{ frame.id }}')"><span>&#x25b6;</span> Local vars</a> {% endif %} </div> <table class="vars" id="v{{ frame.id }}"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in frame.vars|dictsort:"0" %} <tr> <td>{{ var.0|force_escape }}</td> <td class="code"><pre>{{ var.1 }}</pre></td> </tr> {% endfor %} </tbody> </table> {% endif %} </li> {% endfor %} </ul> </div> {% endautoescape %} <form action="http://dpaste.com/" name="pasteform" id="pasteform" method="post"> {% if not is_email %} <div id="pastebinTraceback" class="pastebin"> <input type="hidden" name="language" value="PythonConsole"> <input type="hidden" name="title" value="{{ exception_type|escape }}{% if request %} at {{ request.path_info|escape }}{% endif %}"> <input type="hidden" name="source" value="Django Dpaste Agent"> <input type="hidden" name="poster" value="Django"> <textarea name="content" id="traceback_area" cols="140" rows="25"> Environment: {% if request %} Request Method: {{ request.META.REQUEST_METHOD }} Request URL: {{ request.get_raw_uri|escape }} {% endif %} Django Version: {{ django_version_info }} Python Version: {{ sys_version_info }} Installed Applications: {{ settings.INSTALLED_APPS|pprint }} Installed Middleware: {{ settings.MIDDLEWARE_CLASSES|pprint }} {% if template_does_not_exist %}Template loader postmortem {% if postmortem %}Django tried loading these templates, in this order: {% for entry in postmortem %} Using engine {{ entry.backend.name }}: {% if entry.tried %}{% for attempt in entry.tried %}""" """ * {{ attempt.0.loader_name }}: {{ attempt.0.name }} ({{ attempt.1 }}) {% endfor %}{% else %} This engine did not provide a list of tried templates. {% endif %}{% endfor %} {% else %}No templates were found because your 'TEMPLATES' setting is not configured. {% endif %}{% endif %}{% if template_info %} Template error: In template {{ template_info.name }}, error at line {{ template_info.line }} {{ template_info.message }}""" "{% for source_line in template_info.source_lines %}" "{% if source_line.0 == template_info.line %}" " {{ source_line.0 }} : {{ template_info.before }} {{ template_info.during }} {{ template_info.after }}" "{% else %}" " {{ source_line.0 }} : {{ source_line.1 }}" """{% endif %}{% endfor %}{% endif %} Traceback:{% for frame in frames %} {% ifchanged frame.exc_cause %}{% if frame.exc_cause %}{% if frame.exc_cause_explicit %} The above exception ({{ frame.exc_cause }}) was the direct cause of the following exception: {% else %} During handling of the above exception ({{ frame.exc_cause }}), another exception occurred: {% endif %}{% endif %}{% endifchanged %} File "{{ frame.filename|escape }}" in {{ frame.function|escape }} {% if frame.context_line %} {{ frame.lineno }}. {{ frame.context_line|escape }}{% endif %}{% endfor %} Exception Type: {{ exception_type|escape }}{% if request %} at {{ request.path_info|escape }}{% endif %} Exception Value: {{ exception_value|force_escape }} </textarea> <br><br> <input type="submit" value="Share this traceback on a public website"> </div> </form> </div> {% endif %} {% endif %} <div id="requestinfo"> <h2>Request information</h2> {% if request %} <h3 id="get-info">GET</h3> {% if request.GET %} <table class="req"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in request.GET.items %} <tr> <td>{{ var.0 }}</td> <td class="code"><pre>{{ var.1|pprint }}</pre></td> </tr> {% endfor %} </tbody> </table> {% else %} <p>No GET data</p> {% endif %} <h3 id="post-info">POST</h3> {% if filtered_POST %} <table class="req"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in filtered_POST.items %} <tr> <td>{{ var.0 }}</td> <td class="code"><pre>{{ var.1|pprint }}</pre></td> </tr> {% endfor %} </tbody> </table> {% else %} <p>No POST data</p> {% endif %} <h3 id="files-info">FILES</h3> {% if request.FILES %} <table class="req"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in request.FILES.items %} <tr> <td>{{ var.0 }}</td> <td class="code"><pre>{{ var.1|pprint }}</pre></td> </tr> {% endfor %} </tbody> </table> {% else %} <p>No FILES data</p> {% endif %} <h3 id="cookie-info">COOKIES</h3> {% if request.COOKIES %} <table class="req"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in request.COOKIES.items %} <tr> <td>{{ var.0 }}</td> <td class="code"><pre>{{ var.1|pprint }}</pre></td> </tr> {% endfor %} </tbody> </table> {% else %} <p>No cookie data</p> {% endif %} <h3 id="meta-info">META</h3> <table class="req"> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> {% for var in request.META.items|dictsort:"0" %} <tr> <td>{{ var.0 }}</td> <td class="code"><pre>{{ var.1|pprint }}</pre></td> </tr> {% endfor %} </tbody> </table> {% else %} <p>Request data not supplied</p> {% endif %} <h3 id="settings-info">Settings</h3> <h4>Using settings module <code>{{ settings.SETTINGS_MODULE }}</code></h4> <table class="req"> <thead> <tr> <th>Setting</th> <th>Value</th> </tr> </thead> <tbody> {% for var in settings.items|dictsort:"0" %} <tr> <td>{{ var.0 }}</td> <td class="code"><pre>{{ var.1|pprint }}</pre></td> </tr> {% endfor %} </tbody> </table> </div> {% if not is_email %} <div id="explanation"> <p> You're seeing this error because you have <code>DEBUG = True</code> in your Django settings file. Change that to <code>False</code>, and Django will display a standard page generated by the handler for this status code. </p> </div> {% endif %} </body> </html> """) TECHNICAL_500_TEXT_TEMPLATE = ("""""" """{% firstof exception_type 'Report' %}{% if request %} at {{ request.path_info }}{% endif %} {% firstof exception_value 'No exception message supplied' %} {% if request %} Request Method: {{ request.META.REQUEST_METHOD }} Request URL: {{ request.get_raw_uri }}{% endif %} Django Version: {{ django_version_info }} Python Executable: {{ sys_executable }} Python Version: {{ sys_version_info }} Python Path: {{ sys_path }} Server time: {{server_time|date:"r"}} Installed Applications: {{ settings.INSTALLED_APPS|pprint }} Installed Middleware: {{ settings.MIDDLEWARE_CLASSES|pprint }} {% if template_does_not_exist %}Template loader postmortem {% if postmortem %}Django tried loading these templates, in this order: {% for entry in postmortem %} Using engine {{ entry.backend.name }}: {% if entry.tried %}{% for attempt in entry.tried %}""" """ * {{ attempt.0.loader_name }}: {{ attempt.0.name }} ({{ attempt.1 }}) {% endfor %}{% else %} This engine did not provide a list of tried templates. {% endif %}{% endfor %} {% else %}No templates were found because your 'TEMPLATES' setting is not configured. {% endif %} {% endif %}{% if template_info %} Template error: In template {{ template_info.name }}, error at line {{ template_info.line }} {{ template_info.message }} {% for source_line in template_info.source_lines %}""" "{% if source_line.0 == template_info.line %}" " {{ source_line.0 }} : {{ template_info.before }} {{ template_info.during }} {{ template_info.after }}" "{% else %}" " {{ source_line.0 }} : {{ source_line.1 }}" """{% endif %}{% endfor %}{% endif %}{% if frames %} Traceback:""" "{% for frame in frames %}" "{% ifchanged frame.exc_cause %}" " {% if frame.exc_cause %}" """ {% if frame.exc_cause_explicit %} The above exception ({{ frame.exc_cause }}) was the direct cause of the following exception: {% else %} During handling of the above exception ({{ frame.exc_cause }}), another exception occurred: {% endif %} {% endif %} {% endifchanged %} File "{{ frame.filename }}" in {{ frame.function }} {% if frame.context_line %} {{ frame.lineno }}. {{ frame.context_line }}{% endif %} {% endfor %} {% if exception_type %}Exception Type: {{ exception_type }}{% if request %} at {{ request.path_info }}{% endif %} {% if exception_value %}Exception Value: {{ exception_value }}{% endif %}{% endif %}{% endif %} {% if request %}Request information: GET:{% for k, v in request.GET.items %} {{ k }} = {{ v|stringformat:"r" }}{% empty %} No GET data{% endfor %} POST:{% for k, v in filtered_POST.items %} {{ k }} = {{ v|stringformat:"r" }}{% empty %} No POST data{% endfor %} FILES:{% for k, v in request.FILES.items %} {{ k }} = {{ v|stringformat:"r" }}{% empty %} No FILES data{% endfor %} COOKIES:{% for k, v in request.COOKIES.items %} {{ k }} = {{ v|stringformat:"r" }}{% empty %} No cookie data{% endfor %} META:{% for k, v in request.META.items|dictsort:"0" %} {{ k }} = {{ v|stringformat:"r" }}{% endfor %} {% else %}Request data not supplied {% endif %} Settings: Using settings module {{ settings.SETTINGS_MODULE }}{% for k, v in settings.items|dictsort:"0" %} {{ k }} = {{ v|stringformat:"r" }}{% endfor %} {% if not is_email %} You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard page generated by the handler for this status code. {% endif %} """) TECHNICAL_404_TEMPLATE = """ <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Page not found at {{ request.path_info|escape }}</title> <meta name="robots" content="NONE,NOARCHIVE"> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; margin-bottom:.4em; } h1 span { font-size:60%; color:#666; font-weight:normal; } table { border:none; border-collapse: collapse; width:100%; } td, th { vertical-align:top; padding:2px 3px; } th { width:12em; text-align:right; color:#666; padding-right:.5em; } #info { background:#f6f6f6; } #info ol { margin: 0.5em 4em; } #info ol li { font-family: monospace; } #summary { background: #ffc; } #explanation { background:#eee; border-bottom: 0px none; } </style> </head> <body> <div id="summary"> <h1>Page not found <span>(404)</span></h1> <table class="meta"> <tr> <th>Request Method:</th> <td>{{ request.META.REQUEST_METHOD }}</td> </tr> <tr> <th>Request URL:</th> <td>{{ request.build_absolute_uri|escape }}</td> </tr> {% if raising_view_name %} <tr> <th>Raised by:</th> <td>{{ raising_view_name }}</td> </tr> {% endif %} </table> </div> <div id="info"> {% if urlpatterns %} <p> Using the URLconf defined in <code>{{ urlconf }}</code>, Django tried these URL patterns, in this order: </p> <ol> {% for pattern in urlpatterns %} <li> {% for pat in pattern %} {{ pat.regex.pattern }} {% if forloop.last and pat.name %}[name='{{ pat.name }}']{% endif %} {% endfor %} </li> {% endfor %} </ol> <p>The current URL, <code>{{ request_path|escape }}</code>, didn't match any of these.</p> {% else %} <p>{{ reason }}</p> {% endif %} </div> <div id="explanation"> <p> You're seeing this error because you have <code>DEBUG = True</code> in your Django settings file. Change that to <code>False</code>, and Django will display a standard 404 page. </p> </div> </body> </html> """ DEFAULT_URLCONF_TEMPLATE = """ <!DOCTYPE html> <html lang="en"><head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"><title>{{ title }}</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; } h2 { margin-bottom:.8em; } h2 span { font-size:80%; color:#666; font-weight:normal; } h3 { margin:1em 0 .5em 0; } h4 { margin:0 0 .5em 0; font-weight: normal; } table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; } tbody td, tbody th { vertical-align:top; padding:2px 3px; } thead th { padding:1px 6px 1px 3px; background:#fefefe; text-align:left; font-weight:normal; font-size:11px; border:1px solid #ddd; } tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; } #summary { background: #e0ebff; } #summary h2 { font-weight: normal; color: #666; } #explanation { background:#eee; } #instructions { background:#f6f6f6; } #summary table { border:none; background:transparent; } </style> </head> <body> <div id="summary"> <h1>{{ heading }}</h1> <h2>{{ subheading }}</h2> </div> <div id="instructions"> <p> {{ instructions|safe }} </p> </div> <div id="explanation"> <p> {{ explanation|safe }} </p> </div> </body></html> """
# Copyright (C) 2018-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np import os import pytest import threading from datetime import datetime import time from openvino.inference_engine import ie_api as ie from conftest import model_path, image_path, create_encoder import ngraph as ng from ngraph.impl import Function, Type is_myriad = os.environ.get("TEST_DEVICE") == "MYRIAD" test_net_xml, test_net_bin = model_path(is_myriad) path_to_img = image_path() def create_function_with_memory(input_shape, data_type): input_data = ng.parameter(input_shape, name="input_data", dtype=data_type) rv = ng.read_value(input_data, "var_id_667") add = ng.add(rv, input_data, name="MemoryAdd") node = ng.assign(add, "var_id_667") res = ng.result(add, "res") func = Function(results=[res], sinks=[node], parameters=[input_data], name="name") caps = Function.to_capsule(func) return caps def read_image(): import cv2 n, c, h, w = (1, 3, 32, 32) image = cv2.imread(path_to_img) if image is None: raise FileNotFoundError("Input image not found") image = cv2.resize(image, (h, w)) / 255 image = image.transpose((2, 0, 1)).astype(np.float32) image = image.reshape((n, c, h, w)) return image def load_sample_model(device, num_requests=1): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) executable_network = ie_core.load_network(net, device, num_requests=num_requests) return executable_network def test_input_blobs(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) executable_network = ie_core.load_network(net, device, num_requests=2) td = ie.TensorDesc("FP32", (1, 3, 32, 32), "NCHW") assert executable_network.requests[0].input_blobs['data'].tensor_desc == td def test_output_blobs(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) executable_network = ie_core.load_network(net, device, num_requests=2) td = ie.TensorDesc("FP32", (1, 10), "NC") assert executable_network.requests[0].output_blobs['fc_out'].tensor_desc == td def test_inputs_list(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) executable_network = ie_core.load_network(net, device, num_requests=2) for req in executable_network.requests: assert len(req._inputs_list) == 1 assert "data" in req._inputs_list del ie_core def test_outputs_list(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) executable_network = ie_core.load_network(net, device, num_requests=2) for req in executable_network.requests: assert len(req._outputs_list) == 1 assert "fc_out" in req._outputs_list del ie_core def test_access_input_buffer(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) executable_network = ie_core.load_network(net, device, num_requests=1) buffer = executable_network.requests[0]._get_blob_buffer("data".encode()).to_numpy() assert buffer.shape == (1, 3, 32, 32) assert buffer.strides == (12288, 4096, 128, 4) assert buffer.dtype == np.float32 del executable_network del ie_core del net def test_access_output_buffer(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) executable_network = ie_core.load_network(net, device, num_requests=1) buffer = executable_network.requests[0]._get_blob_buffer("fc_out".encode()).to_numpy() assert buffer.shape == (1, 10) assert buffer.strides == (40, 4) assert buffer.dtype == np.float32 del executable_network del ie_core del net def test_write_to_input_blobs_directly(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) executable_network = ie_core.load_network(net, device, num_requests=1) img = read_image() request = executable_network.requests[0] input_data = request.input_blobs["data"] input_data.buffer[:] = img assert np.array_equal(executable_network.requests[0].input_blobs["data"].buffer, img) del executable_network del ie_core del net def test_write_to_input_blobs_copy(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) executable_network = ie_core.load_network(net, device, num_requests=1) img = read_image() request = executable_network.requests[0] request.input_blobs["data"].buffer[:] = img assert np.allclose(executable_network.requests[0].input_blobs["data"].buffer, img) del executable_network del ie_core del net def test_infer(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) img = read_image() request = exec_net.requests[0] request.infer({'data': img}) res = request.output_blobs['fc_out'].buffer assert np.argmax(res) == 2 del exec_net del ie_core del net def test_async_infer_default_timeout(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) img = read_image() request = exec_net.requests[0] request.async_infer({'data': img}) request.wait() res = request.output_blobs['fc_out'].buffer assert np.argmax(res) == 2 del exec_net del ie_core del net def test_async_infer_wait_finish(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) img = read_image() request = exec_net.requests[0] request.async_infer({'data': img}) request.wait(ie.WaitMode.RESULT_READY) res = request.output_blobs['fc_out'].buffer assert np.argmax(res) == 2 del exec_net del ie_core del net def test_async_infer_wait_time(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=2) img = read_image() request = exec_net.requests[0] request.async_infer({'data': img}) start_time = datetime.utcnow() status = request.wait(ie.WaitMode.RESULT_READY) assert status == ie.StatusCode.OK time_delta = datetime.utcnow() - start_time latency_ms = (time_delta.microseconds / 1000) + (time_delta.seconds * 1000) timeout = max(100, latency_ms) request = exec_net.requests[1] request.async_infer({'data': img}) max_repeat = 10 status = ie.StatusCode.REQUEST_BUSY i = 0 while i < max_repeat and status != ie.StatusCode.OK: status = request.wait(timeout) i += 1 assert status == ie.StatusCode.OK res = request.output_blobs['fc_out'].buffer assert np.argmax(res) == 2 del exec_net del ie_core del net def test_async_infer_wait_status(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) img = read_image() request = exec_net.requests[0] request.async_infer({'data': img}) request.wait(ie.WaitMode.RESULT_READY) res = request.output_blobs['fc_out'].buffer assert np.argmax(res) == 2 status = request.wait(ie.WaitMode.STATUS_ONLY) assert status == ie.StatusCode.OK del exec_net del ie_core del net def test_async_infer_fill_inputs(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) img = read_image() request = exec_net.requests[0] request.input_blobs['data'].buffer[:] = img request.async_infer() status_end = request.wait() assert status_end == ie.StatusCode.OK res = request.output_blobs['fc_out'].buffer assert np.argmax(res[0]) == 2 del exec_net del ie_core del net def test_infer_modify_outputs(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) img = read_image() request = exec_net.requests[0] outputs0 = exec_net.infer({'data': img}) status_end = request.wait() assert status_end == ie.StatusCode.OK assert np.argmax(outputs0['fc_out']) == 2 outputs0['fc_out'][:] = np.zeros(shape=(1, 10), dtype=np.float32) outputs1 = request.output_blobs assert np.argmax(outputs1['fc_out'].buffer) == 2 outputs1['fc_out'].buffer[:] = np.ones(shape=(1, 10), dtype=np.float32) outputs2 = request.output_blobs assert np.argmax(outputs2['fc_out'].buffer) == 2 del exec_net del ie_core del net def test_async_infer_callback(device): def static_vars(**kwargs): def decorate(func): for k in kwargs: setattr(func, k, kwargs[k]) return func return decorate @static_vars(callback_called=0) def callback(self, status): callback.callback_called = 1 ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) img = read_image() request = exec_net.requests[0] request.set_completion_callback(callback) request.async_infer({'data': img}) status = request.wait() assert status == ie.StatusCode.OK res = request.output_blobs['fc_out'].buffer assert np.argmax(res) == 2 assert callback.callback_called == 1 del exec_net del ie_core def test_async_infer_callback_wait_before_start(device): def static_vars(**kwargs): def decorate(func): for k in kwargs: setattr(func, k, kwargs[k]) return func return decorate @static_vars(callback_called=0) def callback(self, status): callback.callback_called = 1 ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) img = read_image() request = exec_net.requests[0] request.set_completion_callback(callback) status = request.wait() assert status == ie.StatusCode.INFER_NOT_STARTED request.async_infer({'data': img}) status = request.wait() assert status == ie.StatusCode.OK res = request.output_blobs['fc_out'].buffer assert np.argmax(res) == 2 assert callback.callback_called == 1 del exec_net del ie_core def test_async_infer_callback_wait_in_callback(device): class InferReqWrap: def __init__(self, request): self.request = request self.cv = threading.Condition() self.request.set_completion_callback(self.callback) self.status_code = self.request.wait(ie.WaitMode.STATUS_ONLY) assert self.status_code == ie.StatusCode.INFER_NOT_STARTED def callback(self, statusCode, userdata): self.status_code = self.request.wait(ie.WaitMode.STATUS_ONLY) self.cv.acquire() self.cv.notify() self.cv.release() def execute(self, input_data): self.request.async_infer(input_data) self.cv.acquire() self.cv.wait() self.cv.release() status = self.request.wait(ie.WaitMode.RESULT_READY) assert status == ie.StatusCode.OK assert self.status_code == ie.StatusCode.RESULT_NOT_READY ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) img = read_image() request_wrap = InferReqWrap(exec_net.requests[0]) request_wrap.execute({'data': img}) del exec_net del ie_core def test_async_infer_wait_while_callback_will_not_finish(device): def callback(status, callback_status): time.sleep(0.01) callback_status['finished'] = True ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) callback_status = {} callback_status['finished'] = False request = exec_net.requests[0] request.set_completion_callback(callback, py_data=callback_status) img = read_image() request.async_infer({'data': img}) request.wait() assert callback_status['finished'] == True def test_get_perf_counts(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) ie_core.set_config({"PERF_COUNT": "YES"}, device) exec_net = ie_core.load_network(net, device) img = read_image() request = exec_net.requests[0] request.infer({'data': img}) pc = request.get_perf_counts() assert pc['29']["status"] == "EXECUTED" del exec_net del ie_core del net @pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU", reason=f"Can't run test on device {os.environ.get("TEST_DEVICE", "CPU")}, " "Dynamic batch fully supported only on CPU") def test_set_batch_size(device): ie_core = ie.IECore() if ie_core.get_metric(device, "FULL_DEVICE_NAME") == "arm_compute::NEON": pytest.skip("Can't run on ARM plugin due-to dynamic batch isn't supported") ie_core.set_config({"DYN_BATCH_ENABLED": "YES"}, device) net = ie_core.read_network(test_net_xml, test_net_bin) net.batch_size = 10 data = np.zeros(shape=net.input_info['data'].input_data.shape) exec_net = ie_core.load_network(net, device) data[0] = read_image()[0] request = exec_net.requests[0] request.set_batch(1) request.infer({'data': data}) assert np.allclose(int(round(request.output_blobs['fc_out'].buffer[0][2])), 1), "Incorrect data for 1st batch" del exec_net del ie_core del net def test_set_zero_batch_size(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) request = exec_net.requests[0] with pytest.raises(ValueError) as e: request.set_batch(0) assert "Batch size should be positive integer number but 0 specified" in str(e.value) del exec_net del ie_core del net def test_set_negative_batch_size(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) request = exec_net.requests[0] with pytest.raises(ValueError) as e: request.set_batch(-1) assert "Batch size should be positive integer number but -1 specified" in str(e.value) del exec_net del ie_core del net def test_blob_setter(device): ie_core = ie.IECore() if device == "CPU": if ie_core.get_metric(device, "FULL_DEVICE_NAME") == "arm_compute::NEON": pytest.skip("Can't run on ARM plugin") net = ie_core.read_network(test_net_xml, test_net_bin) exec_net_1 = ie_core.load_network(network=net, device_name=device, num_requests=1) net.input_info['data'].layout = "NHWC" exec_net_2 = ie_core.load_network(network=net, device_name=device, num_requests=1) img = read_image() res_1 = np.sort(exec_net_1.infer({"data": img})['fc_out']) img = np.transpose(img, axes=(0, 2, 3, 1)).astype(np.float32) tensor_desc = ie.TensorDesc("FP32", [1, 3, 32, 32], "NHWC") img_blob = ie.Blob(tensor_desc, img) request = exec_net_2.requests[0] request.set_blob('data', img_blob) request.infer() res_2 = np.sort(request.output_blobs['fc_out'].buffer) assert np.allclose(res_1, res_2, atol=1e-2, rtol=1e-2) def test_blob_setter_with_preprocess(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(network=net, device_name=device, num_requests=1) img = read_image() tensor_desc = ie.TensorDesc("FP32", [1, 3, 32, 32], "NCHW") img_blob = ie.Blob(tensor_desc, img) preprocess_info = ie.PreProcessInfo() preprocess_info.mean_variant = ie.MeanVariant.MEAN_IMAGE request = exec_net.requests[0] request.set_blob('data', img_blob, preprocess_info) pp = request.preprocess_info["data"] assert pp.mean_variant == ie.MeanVariant.MEAN_IMAGE def test_getting_preprocess(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(network=net, device_name=device, num_requests=1) request = exec_net.requests[0] preprocess_info = request.preprocess_info["data"] assert isinstance(preprocess_info, ie.PreProcessInfo) assert preprocess_info.mean_variant == ie.MeanVariant.NONE def test_resize_algorithm_work(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net_1 = ie_core.load_network(network=net, device_name=device, num_requests=1) img = read_image() res_1 = np.sort(exec_net_1.infer({"data": img})['fc_out']) net.input_info['data'].preprocess_info.resize_algorithm = ie.ResizeAlgorithm.RESIZE_BILINEAR exec_net_2 = ie_core.load_network(net, device) import cv2 image = cv2.imread(path_to_img) if image is None: raise FileNotFoundError("Input image not found") image = image / 255 image = image.transpose((2, 0, 1)).astype(np.float32) image = np.expand_dims(image, 0) tensor_desc = ie.TensorDesc("FP32", [1, 3, image.shape[2], image.shape[3]], "NCHW") img_blob = ie.Blob(tensor_desc, image) request = exec_net_2.requests[0] assert request.preprocess_info["data"].resize_algorithm == ie.ResizeAlgorithm.RESIZE_BILINEAR request.set_blob('data', img_blob) request.infer() res_2 = np.sort(request.output_blobs['fc_out'].buffer) assert np.allclose(res_1, res_2, atol=1e-2, rtol=1e-2) @pytest.mark.parametrize("mode", ["set_init_memory_state", "reset_memory_state", "normal"]) @pytest.mark.parametrize("data_type", ["FP32", "FP16", "I32"]) @pytest.mark.parametrize("input_shape", [[10], [10, 10], [10, 10, 10], [2, 10, 10, 10]]) @pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU", reason=f"Can't run test on device {os.environ.get("TEST_DEVICE", "CPU")}, " "Memory layers fully supported only on CPU") def test_query_state_write_buffer(device, input_shape, data_type, mode): ie_core = ie.IECore() if device == "CPU": if ie_core.get_metric(device, "FULL_DEVICE_NAME") == "arm_compute::NEON": pytest.skip("Can't run on ARM plugin") layout = ["C", "HW", "CHW", "NCHW"] from openvino.inference_engine import TensorDesc, Blob, format_map net = ie.IENetwork(create_function_with_memory(input_shape, format_map[data_type])) ie_core = ie.IECore() exec_net = ie_core.load_network(network=net, device_name=device, num_requests=1) request = exec_net.requests[0] mem_states = request.query_state() mem_state = mem_states[0] assert mem_state.name == 'var_id_667' # todo: Uncomment after fix 45611, # CPU plugin returns outputs and memory state in FP32 in case of FP16 original precision #assert mem_state.state.tensor_desc.precision == data_type for i in range(1, 10): if mode == "set_init_memory_state": # create initial value const_init = 5 init_array = np.full(input_shape, const_init, dtype=format_map[mem_state.state.tensor_desc.precision]) tensor_desc = TensorDesc(mem_state.state.tensor_desc.precision, input_shape, layout[len(input_shape) - 1]) blob = Blob(tensor_desc, init_array) mem_state.state = blob res = exec_net.infer({"input_data": np.full(input_shape, 1, dtype=format_map[data_type])}) expected_res = np.full(input_shape, 1 + const_init, dtype=format_map[data_type]) elif mode == "reset_memory_state": # reset initial state of ReadValue to zero mem_state.reset() res = exec_net.infer({"input_data": np.full(input_shape, 1, dtype=format_map[data_type])}) # always ones expected_res = np.full(input_shape, 1, dtype=format_map[data_type]) else: res = exec_net.infer({"input_data": np.full(input_shape, 1, dtype=format_map[data_type])}) expected_res = np.full(input_shape, i, dtype=format_map[data_type]) assert np.allclose(res['MemoryAdd'], expected_res, atol=1e-6), \ "Expected values: {} \n Actual values: {} \n".format(expected_res, res) @pytest.mark.template_plugin @pytest.mark.parametrize("shape, p_shape, ref_shape", [ ([1, 4, 20, 20], [-1, 4, 20, 20], [5, 4, 20, 20]), ([1, 4, 20, 20], [(0,5), 4, 20, 20], [3, 4, 20, 20]), ([1, 4, 20, 20], [(3,5), 4, 20, 20], [2, 4, 20, 20]), ([1, 4, 20, 20], [(3,5), 4, 20, 20], [6, 4, 20, 20]), ]) def test_infer_dynamic_network_with_set_shape(shape, p_shape, ref_shape): function = create_encoder(shape) net = ng.function_to_cnn(function) net.reshape({"data": p_shape}) ie_core = ie.IECore() ie_core.register_plugin("ov_template_plugin", "TEMPLATE") exec_net = ie_core.load_network(net, "TEMPLATE") exec_net.requests[0].input_blobs["data"].set_shape(ref_shape) assert exec_net.requests[0].input_blobs["data"].tensor_desc.dims == ref_shape exec_net.infer({"data": np.ones(ref_shape)}) request = exec_net.requests[0] request.async_infer({"data": np.ones(ref_shape)}) status = request.wait(ie.WaitMode.RESULT_READY) assert status == ie.StatusCode.OK assert request.output_blobs['out'].tensor_desc.dims == ref_shape @pytest.mark.template_plugin @pytest.mark.parametrize("shape, p_shape, ref_shape", [ ([1, 4, 20, 20], [-1, 4, 20, 20], [5, 4, 20, 20]), ([1, 4, 20, 20], [(0,5), 4, 20, 20], [3, 4, 20, 20]), ([1, 4, 20, 20], [(3,5), 4, 20, 20], [2, 4, 20, 20]), ([1, 4, 20, 20], [(3,5), 4, 20, 20], [6, 4, 20, 20]), ]) def test_infer_dynamic_network_without_set_shape(shape, p_shape, ref_shape): function = create_encoder(shape) net = ng.function_to_cnn(function) net.reshape({"data": p_shape}) ie_core = ie.IECore() ie_core.register_plugin("ov_template_plugin", "TEMPLATE") exec_net = ie_core.load_network(net, "TEMPLATE") exec_net.infer({"data": np.ones(ref_shape)}) assert exec_net.requests[0].input_blobs["data"].tensor_desc.dims == ref_shape request = exec_net.requests[0] request.async_infer({"data": np.ones(ref_shape)}) status = request.wait(ie.WaitMode.RESULT_READY) assert status == ie.StatusCode.OK assert request.output_blobs['out'].tensor_desc.dims == ref_shape @pytest.mark.template_plugin @pytest.mark.parametrize("shape, p_shape, ref_shape", [ ([1, 4, 20, 20], [-1, 4, 20, 20], [5, 4, 20, 20]), ([1, 4, 20, 20], [(0,5), 4, 20, 20], [3, 4, 20, 20]), ([1, 4, 20, 20], [(3,5), 4, 20, 20], [2, 4, 20, 20]), ([1, 4, 20, 20], [(3,5), 4, 20, 20], [6, 4, 20, 20]), ]) def test_infer_dynamic_network_with_set_blob(shape, p_shape, ref_shape): function = create_encoder(shape) net = ng.function_to_cnn(function) net.reshape({"data": p_shape}) ie_core = ie.IECore() ie_core.register_plugin("ov_template_plugin", "TEMPLATE") exec_net = ie_core.load_network(net, "TEMPLATE") tensor_desc = exec_net.requests[0].input_blobs["data"].tensor_desc tensor_desc.dims = ref_shape blob = ie.Blob(tensor_desc) exec_net.requests[0].set_blob("data", blob) assert exec_net.requests[0].input_blobs["data"].tensor_desc.dims == ref_shape request = exec_net.requests[0] request.infer({"data": np.ones(ref_shape)}) request.async_infer({"data": np.ones(ref_shape)}) status = request.wait(ie.WaitMode.RESULT_READY) assert status == ie.StatusCode.OK assert request.output_blobs["out"].tensor_desc.dims == ref_shape @pytest.mark.template_plugin def test_infer_dynamic_network_twice(): shape, p_shape = [1, 4, 20, 20], [(0,5), 4, 20, 20] ref_shape1, ref_shape2 = [2, 4, 20, 20], [3, 4, 20, 20] function = create_encoder(shape) net = ng.function_to_cnn(function) net.reshape({"data": p_shape}) ie_core = ie.IECore() ie_core.register_plugin("ov_template_plugin", "TEMPLATE") exec_net = ie_core.load_network(net, "TEMPLATE") request = exec_net.requests[0] request.infer({"data": np.ones(ref_shape1)}) assert exec_net.requests[0].input_blobs["data"].tensor_desc.dims == ref_shape1 assert request.output_blobs['out'].tensor_desc.dims == ref_shape1 request.infer({"data": np.ones(ref_shape2)}) assert exec_net.requests[0].input_blobs["data"].tensor_desc.dims == ref_shape2 assert request.output_blobs['out'].tensor_desc.dims == ref_shape2 @pytest.mark.template_plugin def test_infer_dynamic_network_with_set_blob_twice(): shape, p_shape = [1, 4, 20, 20], [(0,5), 4, 20, 20] ref_shape1, ref_shape2 = [2, 4, 20, 20], [3, 4, 20, 20] function = create_encoder(shape) net = ng.function_to_cnn(function) net.reshape({"data": p_shape}) ie_core = ie.IECore() ie_core.register_plugin("ov_template_plugin", "TEMPLATE") exec_net = ie_core.load_network(net, "TEMPLATE") request = exec_net.requests[0] td = request.input_blobs['data'].tensor_desc td.dims = ref_shape1 blob = ie.Blob(td) request.set_blob("data", blob) request.infer({"data": np.ones(ref_shape1)}) assert exec_net.requests[0].input_blobs["data"].tensor_desc.dims == ref_shape1 assert request.output_blobs['out'].tensor_desc.dims == ref_shape1 td = request.input_blobs['data'].tensor_desc td.dims = ref_shape2 blob = ie.Blob(td) request.set_blob("data", blob) request.infer({"data": np.ones(ref_shape2)}) assert exec_net.requests[0].input_blobs["data"].tensor_desc.dims == ref_shape2 assert request.output_blobs['out'].tensor_desc.dims == ref_shape2 @pytest.mark.template_plugin @pytest.mark.parametrize("shapes", [ ([3, 4, 20, 20], [3, 4, 20, 20], [3, 4, 20, 20]), ([3, 4, 20, 20], [3, 4, 28, 28], [3, 4, 45, 45]), ]) def test_async_infer_dynamic_network_3_requests(shapes): function = create_encoder([3, 4, 20, 20]) net = ng.function_to_cnn(function) net.reshape({"data": [3, 4, (20, 50), (20, 50)]}) ie_core = ie.IECore() ie_core.register_plugin("ov_template_plugin", "TEMPLATE") exec_net = ie_core.load_network(net, "TEMPLATE", num_requests=3) for i,request in enumerate(exec_net.requests): request.async_infer({"data": np.ones(shapes[i])}) for i,request in enumerate(exec_net.requests): status = request.wait(ie.WaitMode.RESULT_READY) assert status == ie.StatusCode.OK assert request.output_blobs['out'].tensor_desc.dims == shapes[i] @pytest.mark.template_plugin def test_set_blob_with_incorrect_name(): function = create_encoder([4, 4, 20, 20]) net = ng.function_to_cnn(function) ie_core = ie.IECore() ie_core.register_plugin("ov_template_plugin", "TEMPLATE") exec_net = ie_core.load_network(net, "TEMPLATE") tensor_desc = exec_net.requests[0].input_blobs["data"].tensor_desc tensor_desc.dims = [4, 4, 20, 20] blob = ie.Blob(tensor_desc) with pytest.raises(RuntimeError) as e: exec_net.requests[0].set_blob("incorrect_name", blob) assert f"Failed to find input or output with name: 'incorrect_name'" in str(e.value) @pytest.mark.template_plugin def test_set_blob_with_incorrect_size(): function = create_encoder([4, 4, 20, 20]) net = ng.function_to_cnn(function) ie_core = ie.IECore() ie_core.register_plugin("ov_template_plugin", "TEMPLATE") exec_net = ie_core.load_network(net, "TEMPLATE") tensor_desc = exec_net.requests[0].input_blobs["data"].tensor_desc tensor_desc.dims = [tensor_desc.dims[0]*2, 4, 20, 20] blob = ie.Blob(tensor_desc) print(exec_net.requests[0].output_blobs) with pytest.raises(RuntimeError) as e: exec_net.requests[0].set_blob("data", blob) assert f"Input blob size is not equal network input size" in str(e.value) with pytest.raises(RuntimeError) as e: exec_net.requests[0].set_blob("out", blob) assert f"Output blob size is not equal network output size" in str(e.value) @pytest.mark.template_plugin def test_set_blob_after_async_infer(): function = create_encoder([1, 4, 20, 20]) net = ng.function_to_cnn(function) net.reshape({"data": [(0, 5), 4, 20, 20]}) ie_core = ie.IECore() ie_core.register_plugin("ov_template_plugin", "TEMPLATE") exec_net = ie_core.load_network(net, "TEMPLATE") request = exec_net.requests[0] tensor_desc = request.input_blobs['data'].tensor_desc tensor_desc.dims = [2, 4, 20, 20] blob = ie.Blob(tensor_desc) request.async_infer({"data": np.ones([4, 4, 20, 20])}) with pytest.raises(RuntimeError) as e: request.set_blob("data", blob) assert "REQUEST_BUSY" in str(e.value) request.wait()
# Copyright (C) 2018-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np import os import pytest import threading from datetime import datetime import time from openvino.inference_engine import ie_api as ie from conftest import model_path, image_path, create_encoder import ngraph as ng from ngraph.impl import Function, Type is_myriad = os.environ.get("TEST_DEVICE") == "MYRIAD" test_net_xml, test_net_bin = model_path(is_myriad) path_to_img = image_path() def create_function_with_memory(input_shape, data_type): input_data = ng.parameter(input_shape, name="input_data", dtype=data_type) rv = ng.read_value(input_data, "var_id_667") add = ng.add(rv, input_data, name="MemoryAdd") node = ng.assign(add, "var_id_667") res = ng.result(add, "res") func = Function(results=[res], sinks=[node], parameters=[input_data], name="name") caps = Function.to_capsule(func) return caps def read_image(): import cv2 n, c, h, w = (1, 3, 32, 32) image = cv2.imread(path_to_img) if image is None: raise FileNotFoundError("Input image not found") image = cv2.resize(image, (h, w)) / 255 image = image.transpose((2, 0, 1)).astype(np.float32) image = image.reshape((n, c, h, w)) return image def load_sample_model(device, num_requests=1): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) executable_network = ie_core.load_network(net, device, num_requests=num_requests) return executable_network def test_input_blobs(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) executable_network = ie_core.load_network(net, device, num_requests=2) td = ie.TensorDesc("FP32", (1, 3, 32, 32), "NCHW") assert executable_network.requests[0].input_blobs['data'].tensor_desc == td def test_output_blobs(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) executable_network = ie_core.load_network(net, device, num_requests=2) td = ie.TensorDesc("FP32", (1, 10), "NC") assert executable_network.requests[0].output_blobs['fc_out'].tensor_desc == td def test_inputs_list(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) executable_network = ie_core.load_network(net, device, num_requests=2) for req in executable_network.requests: assert len(req._inputs_list) == 1 assert "data" in req._inputs_list del ie_core def test_outputs_list(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) executable_network = ie_core.load_network(net, device, num_requests=2) for req in executable_network.requests: assert len(req._outputs_list) == 1 assert "fc_out" in req._outputs_list del ie_core def test_access_input_buffer(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) executable_network = ie_core.load_network(net, device, num_requests=1) buffer = executable_network.requests[0]._get_blob_buffer("data".encode()).to_numpy() assert buffer.shape == (1, 3, 32, 32) assert buffer.strides == (12288, 4096, 128, 4) assert buffer.dtype == np.float32 del executable_network del ie_core del net def test_access_output_buffer(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) executable_network = ie_core.load_network(net, device, num_requests=1) buffer = executable_network.requests[0]._get_blob_buffer("fc_out".encode()).to_numpy() assert buffer.shape == (1, 10) assert buffer.strides == (40, 4) assert buffer.dtype == np.float32 del executable_network del ie_core del net def test_write_to_input_blobs_directly(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) executable_network = ie_core.load_network(net, device, num_requests=1) img = read_image() request = executable_network.requests[0] input_data = request.input_blobs["data"] input_data.buffer[:] = img assert np.array_equal(executable_network.requests[0].input_blobs["data"].buffer, img) del executable_network del ie_core del net def test_write_to_input_blobs_copy(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) executable_network = ie_core.load_network(net, device, num_requests=1) img = read_image() request = executable_network.requests[0] request.input_blobs["data"].buffer[:] = img assert np.allclose(executable_network.requests[0].input_blobs["data"].buffer, img) del executable_network del ie_core del net def test_infer(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) img = read_image() request = exec_net.requests[0] request.infer({'data': img}) res = request.output_blobs['fc_out'].buffer assert np.argmax(res) == 2 del exec_net del ie_core del net def test_async_infer_default_timeout(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) img = read_image() request = exec_net.requests[0] request.async_infer({'data': img}) request.wait() res = request.output_blobs['fc_out'].buffer assert np.argmax(res) == 2 del exec_net del ie_core del net def test_async_infer_wait_finish(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) img = read_image() request = exec_net.requests[0] request.async_infer({'data': img}) request.wait(ie.WaitMode.RESULT_READY) res = request.output_blobs['fc_out'].buffer assert np.argmax(res) == 2 del exec_net del ie_core del net def test_async_infer_wait_time(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=2) img = read_image() request = exec_net.requests[0] request.async_infer({'data': img}) start_time = datetime.utcnow() status = request.wait(ie.WaitMode.RESULT_READY) assert status == ie.StatusCode.OK time_delta = datetime.utcnow() - start_time latency_ms = (time_delta.microseconds / 1000) + (time_delta.seconds * 1000) timeout = max(100, latency_ms) request = exec_net.requests[1] request.async_infer({'data': img}) max_repeat = 10 status = ie.StatusCode.REQUEST_BUSY i = 0 while i < max_repeat and status != ie.StatusCode.OK: status = request.wait(timeout) i += 1 assert status == ie.StatusCode.OK res = request.output_blobs['fc_out'].buffer assert np.argmax(res) == 2 del exec_net del ie_core del net def test_async_infer_wait_status(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) img = read_image() request = exec_net.requests[0] request.async_infer({'data': img}) request.wait(ie.WaitMode.RESULT_READY) res = request.output_blobs['fc_out'].buffer assert np.argmax(res) == 2 status = request.wait(ie.WaitMode.STATUS_ONLY) assert status == ie.StatusCode.OK del exec_net del ie_core del net def test_async_infer_fill_inputs(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) img = read_image() request = exec_net.requests[0] request.input_blobs['data'].buffer[:] = img request.async_infer() status_end = request.wait() assert status_end == ie.StatusCode.OK res = request.output_blobs['fc_out'].buffer assert np.argmax(res[0]) == 2 del exec_net del ie_core del net def test_infer_modify_outputs(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) img = read_image() request = exec_net.requests[0] outputs0 = exec_net.infer({'data': img}) status_end = request.wait() assert status_end == ie.StatusCode.OK assert np.argmax(outputs0['fc_out']) == 2 outputs0['fc_out'][:] = np.zeros(shape=(1, 10), dtype=np.float32) outputs1 = request.output_blobs assert np.argmax(outputs1['fc_out'].buffer) == 2 outputs1['fc_out'].buffer[:] = np.ones(shape=(1, 10), dtype=np.float32) outputs2 = request.output_blobs assert np.argmax(outputs2['fc_out'].buffer) == 2 del exec_net del ie_core del net def test_async_infer_callback(device): def static_vars(**kwargs): def decorate(func): for k in kwargs: setattr(func, k, kwargs[k]) return func return decorate @static_vars(callback_called=0) def callback(self, status): callback.callback_called = 1 ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) img = read_image() request = exec_net.requests[0] request.set_completion_callback(callback) request.async_infer({'data': img}) status = request.wait() assert status == ie.StatusCode.OK res = request.output_blobs['fc_out'].buffer assert np.argmax(res) == 2 assert callback.callback_called == 1 del exec_net del ie_core def test_async_infer_callback_wait_before_start(device): def static_vars(**kwargs): def decorate(func): for k in kwargs: setattr(func, k, kwargs[k]) return func return decorate @static_vars(callback_called=0) def callback(self, status): callback.callback_called = 1 ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) img = read_image() request = exec_net.requests[0] request.set_completion_callback(callback) status = request.wait() assert status == ie.StatusCode.INFER_NOT_STARTED request.async_infer({'data': img}) status = request.wait() assert status == ie.StatusCode.OK res = request.output_blobs['fc_out'].buffer assert np.argmax(res) == 2 assert callback.callback_called == 1 del exec_net del ie_core def test_async_infer_callback_wait_in_callback(device): class InferReqWrap: def __init__(self, request): self.request = request self.cv = threading.Condition() self.request.set_completion_callback(self.callback) self.status_code = self.request.wait(ie.WaitMode.STATUS_ONLY) assert self.status_code == ie.StatusCode.INFER_NOT_STARTED def callback(self, statusCode, userdata): self.status_code = self.request.wait(ie.WaitMode.STATUS_ONLY) self.cv.acquire() self.cv.notify() self.cv.release() def execute(self, input_data): self.request.async_infer(input_data) self.cv.acquire() self.cv.wait() self.cv.release() status = self.request.wait(ie.WaitMode.RESULT_READY) assert status == ie.StatusCode.OK assert self.status_code == ie.StatusCode.RESULT_NOT_READY ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) img = read_image() request_wrap = InferReqWrap(exec_net.requests[0]) request_wrap.execute({'data': img}) del exec_net del ie_core def test_async_infer_wait_while_callback_will_not_finish(device): def callback(status, callback_status): time.sleep(0.01) callback_status['finished'] = True ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) callback_status = {} callback_status['finished'] = False request = exec_net.requests[0] request.set_completion_callback(callback, py_data=callback_status) img = read_image() request.async_infer({'data': img}) request.wait() assert callback_status['finished'] == True def test_get_perf_counts(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) ie_core.set_config({"PERF_COUNT": "YES"}, device) exec_net = ie_core.load_network(net, device) img = read_image() request = exec_net.requests[0] request.infer({'data': img}) pc = request.get_perf_counts() assert pc['29']["status"] == "EXECUTED" del exec_net del ie_core del net @pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU", reason=f"Can't run test on device {os.environ.get('TEST_DEVICE', 'CPU')}, " "Dynamic batch fully supported only on CPU") def test_set_batch_size(device): ie_core = ie.IECore() if ie_core.get_metric(device, "FULL_DEVICE_NAME") == "arm_compute::NEON": pytest.skip("Can't run on ARM plugin due-to dynamic batch isn't supported") ie_core.set_config({"DYN_BATCH_ENABLED": "YES"}, device) net = ie_core.read_network(test_net_xml, test_net_bin) net.batch_size = 10 data = np.zeros(shape=net.input_info['data'].input_data.shape) exec_net = ie_core.load_network(net, device) data[0] = read_image()[0] request = exec_net.requests[0] request.set_batch(1) request.infer({'data': data}) assert np.allclose(int(round(request.output_blobs['fc_out'].buffer[0][2])), 1), "Incorrect data for 1st batch" del exec_net del ie_core del net def test_set_zero_batch_size(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) request = exec_net.requests[0] with pytest.raises(ValueError) as e: request.set_batch(0) assert "Batch size should be positive integer number but 0 specified" in str(e.value) del exec_net del ie_core del net def test_set_negative_batch_size(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(net, device, num_requests=1) request = exec_net.requests[0] with pytest.raises(ValueError) as e: request.set_batch(-1) assert "Batch size should be positive integer number but -1 specified" in str(e.value) del exec_net del ie_core del net def test_blob_setter(device): ie_core = ie.IECore() if device == "CPU": if ie_core.get_metric(device, "FULL_DEVICE_NAME") == "arm_compute::NEON": pytest.skip("Can't run on ARM plugin") net = ie_core.read_network(test_net_xml, test_net_bin) exec_net_1 = ie_core.load_network(network=net, device_name=device, num_requests=1) net.input_info['data'].layout = "NHWC" exec_net_2 = ie_core.load_network(network=net, device_name=device, num_requests=1) img = read_image() res_1 = np.sort(exec_net_1.infer({"data": img})['fc_out']) img = np.transpose(img, axes=(0, 2, 3, 1)).astype(np.float32) tensor_desc = ie.TensorDesc("FP32", [1, 3, 32, 32], "NHWC") img_blob = ie.Blob(tensor_desc, img) request = exec_net_2.requests[0] request.set_blob('data', img_blob) request.infer() res_2 = np.sort(request.output_blobs['fc_out'].buffer) assert np.allclose(res_1, res_2, atol=1e-2, rtol=1e-2) def test_blob_setter_with_preprocess(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(network=net, device_name=device, num_requests=1) img = read_image() tensor_desc = ie.TensorDesc("FP32", [1, 3, 32, 32], "NCHW") img_blob = ie.Blob(tensor_desc, img) preprocess_info = ie.PreProcessInfo() preprocess_info.mean_variant = ie.MeanVariant.MEAN_IMAGE request = exec_net.requests[0] request.set_blob('data', img_blob, preprocess_info) pp = request.preprocess_info["data"] assert pp.mean_variant == ie.MeanVariant.MEAN_IMAGE def test_getting_preprocess(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net = ie_core.load_network(network=net, device_name=device, num_requests=1) request = exec_net.requests[0] preprocess_info = request.preprocess_info["data"] assert isinstance(preprocess_info, ie.PreProcessInfo) assert preprocess_info.mean_variant == ie.MeanVariant.NONE def test_resize_algorithm_work(device): ie_core = ie.IECore() net = ie_core.read_network(test_net_xml, test_net_bin) exec_net_1 = ie_core.load_network(network=net, device_name=device, num_requests=1) img = read_image() res_1 = np.sort(exec_net_1.infer({"data": img})['fc_out']) net.input_info['data'].preprocess_info.resize_algorithm = ie.ResizeAlgorithm.RESIZE_BILINEAR exec_net_2 = ie_core.load_network(net, device) import cv2 image = cv2.imread(path_to_img) if image is None: raise FileNotFoundError("Input image not found") image = image / 255 image = image.transpose((2, 0, 1)).astype(np.float32) image = np.expand_dims(image, 0) tensor_desc = ie.TensorDesc("FP32", [1, 3, image.shape[2], image.shape[3]], "NCHW") img_blob = ie.Blob(tensor_desc, image) request = exec_net_2.requests[0] assert request.preprocess_info["data"].resize_algorithm == ie.ResizeAlgorithm.RESIZE_BILINEAR request.set_blob('data', img_blob) request.infer() res_2 = np.sort(request.output_blobs['fc_out'].buffer) assert np.allclose(res_1, res_2, atol=1e-2, rtol=1e-2) @pytest.mark.parametrize("mode", ["set_init_memory_state", "reset_memory_state", "normal"]) @pytest.mark.parametrize("data_type", ["FP32", "FP16", "I32"]) @pytest.mark.parametrize("input_shape", [[10], [10, 10], [10, 10, 10], [2, 10, 10, 10]]) @pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU", reason=f"Can't run test on device {os.environ.get('TEST_DEVICE', 'CPU')}, " "Memory layers fully supported only on CPU") def test_query_state_write_buffer(device, input_shape, data_type, mode): ie_core = ie.IECore() if device == "CPU": if ie_core.get_metric(device, "FULL_DEVICE_NAME") == "arm_compute::NEON": pytest.skip("Can't run on ARM plugin") layout = ["C", "HW", "CHW", "NCHW"] from openvino.inference_engine import TensorDesc, Blob, format_map net = ie.IENetwork(create_function_with_memory(input_shape, format_map[data_type])) ie_core = ie.IECore() exec_net = ie_core.load_network(network=net, device_name=device, num_requests=1) request = exec_net.requests[0] mem_states = request.query_state() mem_state = mem_states[0] assert mem_state.name == 'var_id_667' # todo: Uncomment after fix 45611, # CPU plugin returns outputs and memory state in FP32 in case of FP16 original precision #assert mem_state.state.tensor_desc.precision == data_type for i in range(1, 10): if mode == "set_init_memory_state": # create initial value const_init = 5 init_array = np.full(input_shape, const_init, dtype=format_map[mem_state.state.tensor_desc.precision]) tensor_desc = TensorDesc(mem_state.state.tensor_desc.precision, input_shape, layout[len(input_shape) - 1]) blob = Blob(tensor_desc, init_array) mem_state.state = blob res = exec_net.infer({"input_data": np.full(input_shape, 1, dtype=format_map[data_type])}) expected_res = np.full(input_shape, 1 + const_init, dtype=format_map[data_type]) elif mode == "reset_memory_state": # reset initial state of ReadValue to zero mem_state.reset() res = exec_net.infer({"input_data": np.full(input_shape, 1, dtype=format_map[data_type])}) # always ones expected_res = np.full(input_shape, 1, dtype=format_map[data_type]) else: res = exec_net.infer({"input_data": np.full(input_shape, 1, dtype=format_map[data_type])}) expected_res = np.full(input_shape, i, dtype=format_map[data_type]) assert np.allclose(res['MemoryAdd'], expected_res, atol=1e-6), \ "Expected values: {} \n Actual values: {} \n".format(expected_res, res) @pytest.mark.template_plugin @pytest.mark.parametrize("shape, p_shape, ref_shape", [ ([1, 4, 20, 20], [-1, 4, 20, 20], [5, 4, 20, 20]), ([1, 4, 20, 20], [(0,5), 4, 20, 20], [3, 4, 20, 20]), ([1, 4, 20, 20], [(3,5), 4, 20, 20], [2, 4, 20, 20]), ([1, 4, 20, 20], [(3,5), 4, 20, 20], [6, 4, 20, 20]), ]) def test_infer_dynamic_network_with_set_shape(shape, p_shape, ref_shape): function = create_encoder(shape) net = ng.function_to_cnn(function) net.reshape({"data": p_shape}) ie_core = ie.IECore() ie_core.register_plugin("ov_template_plugin", "TEMPLATE") exec_net = ie_core.load_network(net, "TEMPLATE") exec_net.requests[0].input_blobs["data"].set_shape(ref_shape) assert exec_net.requests[0].input_blobs["data"].tensor_desc.dims == ref_shape exec_net.infer({"data": np.ones(ref_shape)}) request = exec_net.requests[0] request.async_infer({"data": np.ones(ref_shape)}) status = request.wait(ie.WaitMode.RESULT_READY) assert status == ie.StatusCode.OK assert request.output_blobs['out'].tensor_desc.dims == ref_shape @pytest.mark.template_plugin @pytest.mark.parametrize("shape, p_shape, ref_shape", [ ([1, 4, 20, 20], [-1, 4, 20, 20], [5, 4, 20, 20]), ([1, 4, 20, 20], [(0,5), 4, 20, 20], [3, 4, 20, 20]), ([1, 4, 20, 20], [(3,5), 4, 20, 20], [2, 4, 20, 20]), ([1, 4, 20, 20], [(3,5), 4, 20, 20], [6, 4, 20, 20]), ]) def test_infer_dynamic_network_without_set_shape(shape, p_shape, ref_shape): function = create_encoder(shape) net = ng.function_to_cnn(function) net.reshape({"data": p_shape}) ie_core = ie.IECore() ie_core.register_plugin("ov_template_plugin", "TEMPLATE") exec_net = ie_core.load_network(net, "TEMPLATE") exec_net.infer({"data": np.ones(ref_shape)}) assert exec_net.requests[0].input_blobs["data"].tensor_desc.dims == ref_shape request = exec_net.requests[0] request.async_infer({"data": np.ones(ref_shape)}) status = request.wait(ie.WaitMode.RESULT_READY) assert status == ie.StatusCode.OK assert request.output_blobs['out'].tensor_desc.dims == ref_shape @pytest.mark.template_plugin @pytest.mark.parametrize("shape, p_shape, ref_shape", [ ([1, 4, 20, 20], [-1, 4, 20, 20], [5, 4, 20, 20]), ([1, 4, 20, 20], [(0,5), 4, 20, 20], [3, 4, 20, 20]), ([1, 4, 20, 20], [(3,5), 4, 20, 20], [2, 4, 20, 20]), ([1, 4, 20, 20], [(3,5), 4, 20, 20], [6, 4, 20, 20]), ]) def test_infer_dynamic_network_with_set_blob(shape, p_shape, ref_shape): function = create_encoder(shape) net = ng.function_to_cnn(function) net.reshape({"data": p_shape}) ie_core = ie.IECore() ie_core.register_plugin("ov_template_plugin", "TEMPLATE") exec_net = ie_core.load_network(net, "TEMPLATE") tensor_desc = exec_net.requests[0].input_blobs["data"].tensor_desc tensor_desc.dims = ref_shape blob = ie.Blob(tensor_desc) exec_net.requests[0].set_blob("data", blob) assert exec_net.requests[0].input_blobs["data"].tensor_desc.dims == ref_shape request = exec_net.requests[0] request.infer({"data": np.ones(ref_shape)}) request.async_infer({"data": np.ones(ref_shape)}) status = request.wait(ie.WaitMode.RESULT_READY) assert status == ie.StatusCode.OK assert request.output_blobs["out"].tensor_desc.dims == ref_shape @pytest.mark.template_plugin def test_infer_dynamic_network_twice(): shape, p_shape = [1, 4, 20, 20], [(0,5), 4, 20, 20] ref_shape1, ref_shape2 = [2, 4, 20, 20], [3, 4, 20, 20] function = create_encoder(shape) net = ng.function_to_cnn(function) net.reshape({"data": p_shape}) ie_core = ie.IECore() ie_core.register_plugin("ov_template_plugin", "TEMPLATE") exec_net = ie_core.load_network(net, "TEMPLATE") request = exec_net.requests[0] request.infer({"data": np.ones(ref_shape1)}) assert exec_net.requests[0].input_blobs["data"].tensor_desc.dims == ref_shape1 assert request.output_blobs['out'].tensor_desc.dims == ref_shape1 request.infer({"data": np.ones(ref_shape2)}) assert exec_net.requests[0].input_blobs["data"].tensor_desc.dims == ref_shape2 assert request.output_blobs['out'].tensor_desc.dims == ref_shape2 @pytest.mark.template_plugin def test_infer_dynamic_network_with_set_blob_twice(): shape, p_shape = [1, 4, 20, 20], [(0,5), 4, 20, 20] ref_shape1, ref_shape2 = [2, 4, 20, 20], [3, 4, 20, 20] function = create_encoder(shape) net = ng.function_to_cnn(function) net.reshape({"data": p_shape}) ie_core = ie.IECore() ie_core.register_plugin("ov_template_plugin", "TEMPLATE") exec_net = ie_core.load_network(net, "TEMPLATE") request = exec_net.requests[0] td = request.input_blobs['data'].tensor_desc td.dims = ref_shape1 blob = ie.Blob(td) request.set_blob("data", blob) request.infer({"data": np.ones(ref_shape1)}) assert exec_net.requests[0].input_blobs["data"].tensor_desc.dims == ref_shape1 assert request.output_blobs['out'].tensor_desc.dims == ref_shape1 td = request.input_blobs['data'].tensor_desc td.dims = ref_shape2 blob = ie.Blob(td) request.set_blob("data", blob) request.infer({"data": np.ones(ref_shape2)}) assert exec_net.requests[0].input_blobs["data"].tensor_desc.dims == ref_shape2 assert request.output_blobs['out'].tensor_desc.dims == ref_shape2 @pytest.mark.template_plugin @pytest.mark.parametrize("shapes", [ ([3, 4, 20, 20], [3, 4, 20, 20], [3, 4, 20, 20]), ([3, 4, 20, 20], [3, 4, 28, 28], [3, 4, 45, 45]), ]) def test_async_infer_dynamic_network_3_requests(shapes): function = create_encoder([3, 4, 20, 20]) net = ng.function_to_cnn(function) net.reshape({"data": [3, 4, (20, 50), (20, 50)]}) ie_core = ie.IECore() ie_core.register_plugin("ov_template_plugin", "TEMPLATE") exec_net = ie_core.load_network(net, "TEMPLATE", num_requests=3) for i,request in enumerate(exec_net.requests): request.async_infer({"data": np.ones(shapes[i])}) for i,request in enumerate(exec_net.requests): status = request.wait(ie.WaitMode.RESULT_READY) assert status == ie.StatusCode.OK assert request.output_blobs['out'].tensor_desc.dims == shapes[i] @pytest.mark.template_plugin def test_set_blob_with_incorrect_name(): function = create_encoder([4, 4, 20, 20]) net = ng.function_to_cnn(function) ie_core = ie.IECore() ie_core.register_plugin("ov_template_plugin", "TEMPLATE") exec_net = ie_core.load_network(net, "TEMPLATE") tensor_desc = exec_net.requests[0].input_blobs["data"].tensor_desc tensor_desc.dims = [4, 4, 20, 20] blob = ie.Blob(tensor_desc) with pytest.raises(RuntimeError) as e: exec_net.requests[0].set_blob("incorrect_name", blob) assert f"Failed to find input or output with name: 'incorrect_name'" in str(e.value) @pytest.mark.template_plugin def test_set_blob_with_incorrect_size(): function = create_encoder([4, 4, 20, 20]) net = ng.function_to_cnn(function) ie_core = ie.IECore() ie_core.register_plugin("ov_template_plugin", "TEMPLATE") exec_net = ie_core.load_network(net, "TEMPLATE") tensor_desc = exec_net.requests[0].input_blobs["data"].tensor_desc tensor_desc.dims = [tensor_desc.dims[0]*2, 4, 20, 20] blob = ie.Blob(tensor_desc) print(exec_net.requests[0].output_blobs) with pytest.raises(RuntimeError) as e: exec_net.requests[0].set_blob("data", blob) assert f"Input blob size is not equal network input size" in str(e.value) with pytest.raises(RuntimeError) as e: exec_net.requests[0].set_blob("out", blob) assert f"Output blob size is not equal network output size" in str(e.value) @pytest.mark.template_plugin def test_set_blob_after_async_infer(): function = create_encoder([1, 4, 20, 20]) net = ng.function_to_cnn(function) net.reshape({"data": [(0, 5), 4, 20, 20]}) ie_core = ie.IECore() ie_core.register_plugin("ov_template_plugin", "TEMPLATE") exec_net = ie_core.load_network(net, "TEMPLATE") request = exec_net.requests[0] tensor_desc = request.input_blobs['data'].tensor_desc tensor_desc.dims = [2, 4, 20, 20] blob = ie.Blob(tensor_desc) request.async_infer({"data": np.ones([4, 4, 20, 20])}) with pytest.raises(RuntimeError) as e: request.set_blob("data", blob) assert "REQUEST_BUSY" in str(e.value) request.wait()
import os from typing import Optional from grapl_common.utils.primitive_convertors import to_bool IS_LOCAL = to_bool(os.getenv("IS_LOCAL", default=False)) def endpoint_url(suffix: Optional[str]) -> str: """Builds the URL for the Grapl API endpoint corresponding to the given suffix. This function expects that GRAPL_API_HOST is set, and if running locally, that GRAPL_HTTP_FRONTEND_PORT is set also. """ port = int(os.environ["GRAPL_HTTP_FRONTEND_PORT"]) if IS_LOCAL else 443 protocol = "http" if IS_LOCAL else "https" stage = "" if IS_LOCAL else "/prod" return f'{protocol}://{os.environ['GRAPL_API_HOST']}:{port}{stage}{suffix}'
import os from typing import Optional from grapl_common.utils.primitive_convertors import to_bool IS_LOCAL = to_bool(os.getenv("IS_LOCAL", default=False)) def endpoint_url(suffix: Optional[str]) -> str: """Builds the URL for the Grapl API endpoint corresponding to the given suffix. This function expects that GRAPL_API_HOST is set, and if running locally, that GRAPL_HTTP_FRONTEND_PORT is set also. """ port = int(os.environ["GRAPL_HTTP_FRONTEND_PORT"]) if IS_LOCAL else 443 protocol = "http" if IS_LOCAL else "https" stage = "" if IS_LOCAL else "/prod" return f'{protocol}://{os.environ["GRAPL_API_HOST"]}:{port}{stage}{suffix}'
""" dayong.utils ~~~~~~~~~~~~ This module provides useful functions that facilitate some of Dayong's routine operations. """ import asyncio import functools from typing import Any, Awaitable, Callable SUPPORTED_DB = ("postgres://",) def format_db_url(database_url: str) -> str: """Format the default database URL to support async requests/transactions. One case this is useful is when the hosting provider automatically provisions the database and changing the database URL isn't simple. Args: database_url (str): The default url of a supported database. Returns: str: A unique sequence of characters that identifies the database. """ db_scheme = next( se_scheme if se_scheme in database_url else "" for se_scheme in SUPPORTED_DB ) if not db_scheme: return database_url if db_scheme == "postgres://": db_name = "postgresql://" else: db_name = db_scheme return database_url.replace( db_scheme, f"""{db_name.replace("://", "+asyncpg://")}""" ) def run_in_executor(blocking_fn: Callable[..., Any]) -> Callable[..., Awaitable[Any]]: """Decorator for executing blocking code asynchronously. Args: blocking_fn (Callable[..., Any]): A blocking function or method. Returns: Callable[..., Awaitable[Any]]: An awaitable object. """ @functools.wraps(blocking_fn) async def inner(*args: Any, **kwargs: Any): loop = asyncio.get_running_loop() return await loop.run_in_executor(None, lambda: blocking_fn(*args, **kwargs)) return inner def validate_cfg(config: dict[str, Any], valid: dict[str, Any]) -> None: """Check configuration accuracy. Args: config (dict[str, Any]): Parsed JSON file. valid (dict[str, Any]): Representation of a valid configuration. Raises: KeyError: Raised if the key in the config is invalid. TypeError: If a config value is an incompatible data type. """ for key, value in list(config.items()): if isinstance(value, dict): try: validate_cfg(config[key], valid[key]) except KeyError as key_err: raise KeyError( f"""key "{key}" is not a valid configuration""" ) from key_err elif not isinstance(value, valid[key]): raise TypeError( f""""{value}" in key {key} is the incorrect type """ f"{type(value)}, must be {valid[key]}", ) if __name__ == "__main__": pass
""" dayong.utils ~~~~~~~~~~~~ This module provides useful functions that facilitate some of Dayong's routine operations. """ import asyncio import functools from typing import Any, Awaitable, Callable SUPPORTED_DB = ("postgres://",) def format_db_url(database_url: str) -> str: """Format the default database URL to support async requests/transactions. One case this is useful is when the hosting provider automatically provisions the database and changing the database URL isn't simple. Args: database_url (str): The default url of a supported database. Returns: str: A unique sequence of characters that identifies the database. """ db_scheme = next( se_scheme if se_scheme in database_url else "" for se_scheme in SUPPORTED_DB ) if not db_scheme: return database_url if db_scheme == "postgres://": db_name = "postgresql://" else: db_name = db_scheme return database_url.replace( db_scheme, f"""{db_name.replace("://", "+asyncpg://")}""" ) def run_in_executor(blocking_fn: Callable[..., Any]) -> Callable[..., Awaitable[Any]]: """Decorator for executing blocking code asynchronously. Args: blocking_fn (Callable[..., Any]): A blocking function or method. Returns: Callable[..., Awaitable[Any]]: An awaitable object. """ @functools.wraps(blocking_fn) async def inner(*args: Any, **kwargs: Any): loop = asyncio.get_running_loop() return await loop.run_in_executor(None, lambda: blocking_fn(*args, **kwargs)) return inner def validate_cfg(config: dict[str, Any], valid: dict[str, Any]) -> None: """Check configuration accuracy. Args: config (dict[str, Any]): Parsed JSON file. valid (dict[str, Any]): Representation of a valid configuration. Raises: KeyError: Raised if the key in the config is invalid. TypeError: If a config value is an incompatible data type. """ for key, value in list(config.items()): if isinstance(value, dict): try: validate_cfg(config[key], valid[key]) except KeyError as key_err: raise KeyError( f"""key "{key}" is not a valid configuration""" ) from key_err elif not isinstance(value, valid[key]): raise TypeError( f""""{value}" in key {key} is the incorrect type """ f"{type(value)}, must be {valid[key]}", ) if __name__ == "__main__": pass
import logging import sys from tonguetwister.lib.helper import grouper class LastPartFilter(logging.Filter): def filter(self, record): record.name_last = record.name.rsplit('.', 1)[-1] return True def setup_logger(log_level=None): if log_level is None: log_level = logging.DEBUG formatter = logging.Formatter( '%(name_last)s [%(levelname)s] %(message)s' ) handler = logging.StreamHandler(sys.stdout) handler.setLevel(log_level) handler.setFormatter(formatter) handler.addFilter(LastPartFilter()) logger = logging.getLogger('tonguetwister') logger.setLevel(log_level) logger.addHandler(handler) def log_expected_trailing_bytes(logger, _bytes, prefix=''): logger.info( f'{f'{prefix}: ' if len(prefix) > 0 else ''}' f'Trailing bytes [{grouper(_bytes, 2)}] found. Probably nothing to worry about.' )
import logging import sys from tonguetwister.lib.helper import grouper class LastPartFilter(logging.Filter): def filter(self, record): record.name_last = record.name.rsplit('.', 1)[-1] return True def setup_logger(log_level=None): if log_level is None: log_level = logging.DEBUG formatter = logging.Formatter( '%(name_last)s [%(levelname)s] %(message)s' ) handler = logging.StreamHandler(sys.stdout) handler.setLevel(log_level) handler.setFormatter(formatter) handler.addFilter(LastPartFilter()) logger = logging.getLogger('tonguetwister') logger.setLevel(log_level) logger.addHandler(handler) def log_expected_trailing_bytes(logger, _bytes, prefix=''): logger.info( f'{f"{prefix}: " if len(prefix) > 0 else ""}' f'Trailing bytes [{grouper(_bytes, 2)}] found. Probably nothing to worry about.' )
#!/usr/bin/env python from argparse import ArgumentParser from models import UNet import torch from ignite.contrib.handlers import ProgressBar from ignite.engine import Events from ignite.utils import manual_seed from pathlib import Path from models import SegNet import json import numpy as np from coteaching import kept_ratio_schedules as coteaching_kept_ratio_schedules from trainer import Trainer, TrainerOptions from datetime import datetime from utils import TensorboardLogger, key_to_tuple from torch.utils.data import Subset from data import HDF5Dataset from evaluator import EvaluatorOptions, TrainingValidationEvaluator def create_log_dir(log_dir): if isinstance(log_dir, str): log_dir = Path(log_dir) if (log_dir / "checkpoints").exists(): old_log_dir = log_dir suffix = datetime.now().strftime("%Y%m%d-%H-%M-%S-%f") log_dir = old_log_dir.parent / f"{old_log_dir.name}_{suffix}" print(f"WARN: Log dir {old_log_dir} exists. Writing to {log_dir} instead to avoid overwriting useful files.") log_dir.mkdir(exist_ok=True, parents=True) return log_dir def assert_keys_exist(keys, datasets): # Check that X,y keys exist in data loaders for split, dataset in datasets.items(): item = dataset[0] for k in keys: assert k in item, f"Key '{k}' not found in dataloader for split '{split}'. Available keys are {item.keys()}" def setup_tb_loggers(log_dir: Path, split, trainer_or_evaluator, log_event_name): def extract_logs_from_metrics(metrics, model): logs = {} if model.name == 0: if "kept_ratio" in metrics: logs["kept_ratio"] = metrics["kept_ratio"] logs[f"kept_loss"] = metrics["kept_loss"][model.name] logs[f"rej_loss"] = metrics["rejected_loss"][model.name] return logs loggers = [] for model in trainer_or_evaluator.models: logger = TensorboardLogger(log_dir / str(model.name) / split) def engine_transform(e): return extract_logs_from_metrics(e.state.output[1], model) logger.attach( trainer_or_evaluator.engine, event_name=log_event_name, engine_transform=engine_transform, global_step_transform=lambda *_: trainer_or_evaluator.samples_seen ) loggers += [logger] return loggers def get_datasets(data_path, batch_size, eval_batch_size, splits, in_memory: bool, batches_per_epoch=None): path = Path(data_path) datasets = { k: HDF5Dataset(path, split=k, in_memory=in_memory, load_as_tensor=True, filter_keys=lambda ds: "metadata" not in ds.name) for k in splits } if batches_per_epoch is not None: for split, dataset in datasets.items(): sample_limit = batches_per_epoch * (batch_size if split == "train" else eval_batch_size) sample_limit = min(sample_limit, len(dataset)) datasets[split] = Subset(dataset, indices=range(sample_limit)) return datasets def pbar_log_metrics(pbar, engine, split): messages = [f"Epoch {engine.state.epoch} Results for '{split}'"] for k, v in engine.state.metrics.items(): messages.append(f"\t{k}: {v:.4f}" if type(v) == float or type(v) == int else f"\t{k}: {v}") pbar.log_message("\n".join(messages)) def create_models(model_key: str, num_models, device, imagenet_pretrained: bool): if not imagenet_pretrained: print(f"ImageNet pretraining disabled") models_map = { "unet_resnet18": lambda: UNet(encoder_architecture="resnet18", imagenet_pretrained=imagenet_pretrained, input_shape=None, device=device, auto_resize_in=False, auto_resize_out=False), "basic_segnet": lambda: SegNet(input_channels=3, output_channels=1, output_activation=torch.sigmoid).to(device) } models = [models_map[model_key]() for _ in range(num_models)] return models def setup_train_pbar_logger(trainer, models, log_event_name): pbar = ProgressBar(persist=True) pbar.attach(trainer, event_name=log_event_name) return pbar def run(args): gt_x_key = key_to_tuple(args.gt_x_key) gt_y_train_key = key_to_tuple(args.gt_y_train_key) gt_y_eval_keys = [ key_to_tuple(k) for k in args.gt_y_eval_key ] if args.eval_batch_size is None: args.eval_batch_size = args.batch_size device = "cuda" if torch.cuda.is_available() else "cpu" if device == "cpu": print(f"WARNING: Running on CPU. This will be slow...") log_dir = create_log_dir(args.log_dir) if args.seed is not None: manual_seed(args.seed) # Serialize arguments to json (log_dir / "train_args.json").write_text(json.dumps(vars(args))) # Data Loaders & model splits = ["train", "val", "test"] eval_batch_size = args.eval_batch_size or args.batch_size datasets = get_datasets(args.data_path, args.batch_size, eval_batch_size, splits, in_memory=False, batches_per_epoch=args.batches_per_epoch) assert_keys_exist(gt_y_eval_keys + [gt_y_train_key, gt_x_key], datasets) # Initialize training loop #print(f"Running a total of {training_iterations_per_epoch} training epochs", flush=True) num_models = 1 if args.training_mode == "standard" else 2 models = create_models(args.model, num_models, device, args.imagenet_pretrained) coteaching_schedule = None if args.training_mode == "standard" else coteaching_kept_ratio_schedules[args.coteaching_schedule](args.epochs) trainer_options = TrainerOptions(device, args.optimizer, args.lr, args.epochs, args.batch_size, args.input_shape, gt_x_key, gt_y_train_key, args.training_mode, args.num_workers) trainer = Trainer(models, datasets["train"], trainer_options, coteaching_schedule, None) # Tensorboard and progress bar Logging for training approximate_training_iterations_per_epoch = len(datasets["train"]) / eval_batch_size tensorboard_log_event_name = Events.ITERATION_COMPLETED(every=int(np.ceil(approximate_training_iterations_per_epoch / 10))) loggers = setup_tb_loggers(log_dir, "training", trainer, log_event_name=tensorboard_log_event_name) pbar = setup_train_pbar_logger(trainer.engine, models, Events.ITERATION_COMPLETED) #Evaluators registered to run after each epoch eval_options = EvaluatorOptions(device, gt_y_eval_keys, eval_batch_size, args.num_workers) evaluators = { "val": TrainingValidationEvaluator(trainer, datasets["val"], eval_options), } for split, evaluator in evaluators.items(): loggers += setup_tb_loggers(log_dir, split, evaluator, log_event_name=Events.EPOCH_COMPLETED) eval_pbar = ProgressBar(persist=False, desc=f"Eval {split}") eval_pbar.attach(evaluator.engine) evaluator.engine.add_event_handler(Events.EPOCH_COMPLETED, lambda engine, split=split: pbar_log_metrics(pbar, engine, split)) trainer.engine.add_event_handler(Events.EPOCH_COMPLETED, lambda _engine, evaluator=evaluator: evaluator.run()) # Have to hack around Python's horrendous handling of closures # Checkpoint logger after each validation epoch checkpoint_dir = log_dir / "checkpoints" checkpoint_dir.mkdir(parents=True, exist_ok=True) evaluators["val"].engine.add_event_handler(Events.EPOCH_COMPLETED, lambda *_: trainer.save_checkpoint(checkpoint_dir)) # kick everything off try: print(f"Running experiment with output directory {log_dir}. Detailed arguments are written to {log_dir / "train_args.json"}") trainer.run() finally: for logger in loggers: logger.close() if __name__ == "__main__": parser = ArgumentParser() parser.add_argument("--data_path", type=str, help="Path to the HDF5 dataset obtained through the data preparation script.", required=True) parser.add_argument("--gt_y_train_key", type=str, required=True) parser.add_argument("--gt_y_eval_key", nargs='+', required=True) parser.add_argument("--gt_x_key", type=str, default="rgb") parser.add_argument("--training_mode", type=str, choices=["standard", "coteaching", "coteaching_plus", "stochastic_coteaching"]) parser.add_argument("--log_dir", type=str, help="Folder to output logs, model checkpoints etc. If it already exists, a unique suffix will be appended to avoid overwriting useful data.", required=True) parser.add_argument("--batch_size", type=int, default=12, help="input batch size for training (default: 64)") parser.add_argument("--eval_batch_size", type=int, default=None, help="input batch size for validation. Defaults to training batch size") parser.add_argument("--epochs", type=int, default=10, help="number of epochs to train. Defaults to 10.") parser.add_argument("--lr", type=float, default=0.001, help="learning rate") parser.add_argument("--batches_per_epoch", type=int, default=None, help="Allows to run smaller epochs. This is mostly useful when debugging.") parser.add_argument("--model", choices=["unet_resnet18", "basic_segnet"]) parser.add_argument("--in_memory", action="store_true", help="Whether to load the whole dataset in memory. Speeds things up, but requires a large amount of RAM.") parser.add_argument("--seed", type=int, help="Random seed for torch, numpy and Python's random", default=0) parser.add_argument("--num_workers", type=int, help="Number of parallel processes used to fetch the data from disk", default=4) parser.add_argument('--input_shape', type=int, nargs=2, default=[512, 1024]) parser.add_argument('--eval_shape', type=int, nargs=2, default=[1024, 2048]) parser.add_argument("--coteaching_schedule", type=str) parser.add_argument("--imagenet_pretrained", default=True) parser.add_argument("--optimizer", choices=["adam", "sgd"], default="adam") args = parser.parse_args() run(args)
#!/usr/bin/env python from argparse import ArgumentParser from models import UNet import torch from ignite.contrib.handlers import ProgressBar from ignite.engine import Events from ignite.utils import manual_seed from pathlib import Path from models import SegNet import json import numpy as np from coteaching import kept_ratio_schedules as coteaching_kept_ratio_schedules from trainer import Trainer, TrainerOptions from datetime import datetime from utils import TensorboardLogger, key_to_tuple from torch.utils.data import Subset from data import HDF5Dataset from evaluator import EvaluatorOptions, TrainingValidationEvaluator def create_log_dir(log_dir): if isinstance(log_dir, str): log_dir = Path(log_dir) if (log_dir / "checkpoints").exists(): old_log_dir = log_dir suffix = datetime.now().strftime("%Y%m%d-%H-%M-%S-%f") log_dir = old_log_dir.parent / f"{old_log_dir.name}_{suffix}" print(f"WARN: Log dir {old_log_dir} exists. Writing to {log_dir} instead to avoid overwriting useful files.") log_dir.mkdir(exist_ok=True, parents=True) return log_dir def assert_keys_exist(keys, datasets): # Check that X,y keys exist in data loaders for split, dataset in datasets.items(): item = dataset[0] for k in keys: assert k in item, f"Key '{k}' not found in dataloader for split '{split}'. Available keys are {item.keys()}" def setup_tb_loggers(log_dir: Path, split, trainer_or_evaluator, log_event_name): def extract_logs_from_metrics(metrics, model): logs = {} if model.name == 0: if "kept_ratio" in metrics: logs["kept_ratio"] = metrics["kept_ratio"] logs[f"kept_loss"] = metrics["kept_loss"][model.name] logs[f"rej_loss"] = metrics["rejected_loss"][model.name] return logs loggers = [] for model in trainer_or_evaluator.models: logger = TensorboardLogger(log_dir / str(model.name) / split) def engine_transform(e): return extract_logs_from_metrics(e.state.output[1], model) logger.attach( trainer_or_evaluator.engine, event_name=log_event_name, engine_transform=engine_transform, global_step_transform=lambda *_: trainer_or_evaluator.samples_seen ) loggers += [logger] return loggers def get_datasets(data_path, batch_size, eval_batch_size, splits, in_memory: bool, batches_per_epoch=None): path = Path(data_path) datasets = { k: HDF5Dataset(path, split=k, in_memory=in_memory, load_as_tensor=True, filter_keys=lambda ds: "metadata" not in ds.name) for k in splits } if batches_per_epoch is not None: for split, dataset in datasets.items(): sample_limit = batches_per_epoch * (batch_size if split == "train" else eval_batch_size) sample_limit = min(sample_limit, len(dataset)) datasets[split] = Subset(dataset, indices=range(sample_limit)) return datasets def pbar_log_metrics(pbar, engine, split): messages = [f"Epoch {engine.state.epoch} Results for '{split}'"] for k, v in engine.state.metrics.items(): messages.append(f"\t{k}: {v:.4f}" if type(v) == float or type(v) == int else f"\t{k}: {v}") pbar.log_message("\n".join(messages)) def create_models(model_key: str, num_models, device, imagenet_pretrained: bool): if not imagenet_pretrained: print(f"ImageNet pretraining disabled") models_map = { "unet_resnet18": lambda: UNet(encoder_architecture="resnet18", imagenet_pretrained=imagenet_pretrained, input_shape=None, device=device, auto_resize_in=False, auto_resize_out=False), "basic_segnet": lambda: SegNet(input_channels=3, output_channels=1, output_activation=torch.sigmoid).to(device) } models = [models_map[model_key]() for _ in range(num_models)] return models def setup_train_pbar_logger(trainer, models, log_event_name): pbar = ProgressBar(persist=True) pbar.attach(trainer, event_name=log_event_name) return pbar def run(args): gt_x_key = key_to_tuple(args.gt_x_key) gt_y_train_key = key_to_tuple(args.gt_y_train_key) gt_y_eval_keys = [ key_to_tuple(k) for k in args.gt_y_eval_key ] if args.eval_batch_size is None: args.eval_batch_size = args.batch_size device = "cuda" if torch.cuda.is_available() else "cpu" if device == "cpu": print(f"WARNING: Running on CPU. This will be slow...") log_dir = create_log_dir(args.log_dir) if args.seed is not None: manual_seed(args.seed) # Serialize arguments to json (log_dir / "train_args.json").write_text(json.dumps(vars(args))) # Data Loaders & model splits = ["train", "val", "test"] eval_batch_size = args.eval_batch_size or args.batch_size datasets = get_datasets(args.data_path, args.batch_size, eval_batch_size, splits, in_memory=False, batches_per_epoch=args.batches_per_epoch) assert_keys_exist(gt_y_eval_keys + [gt_y_train_key, gt_x_key], datasets) # Initialize training loop #print(f"Running a total of {training_iterations_per_epoch} training epochs", flush=True) num_models = 1 if args.training_mode == "standard" else 2 models = create_models(args.model, num_models, device, args.imagenet_pretrained) coteaching_schedule = None if args.training_mode == "standard" else coteaching_kept_ratio_schedules[args.coteaching_schedule](args.epochs) trainer_options = TrainerOptions(device, args.optimizer, args.lr, args.epochs, args.batch_size, args.input_shape, gt_x_key, gt_y_train_key, args.training_mode, args.num_workers) trainer = Trainer(models, datasets["train"], trainer_options, coteaching_schedule, None) # Tensorboard and progress bar Logging for training approximate_training_iterations_per_epoch = len(datasets["train"]) / eval_batch_size tensorboard_log_event_name = Events.ITERATION_COMPLETED(every=int(np.ceil(approximate_training_iterations_per_epoch / 10))) loggers = setup_tb_loggers(log_dir, "training", trainer, log_event_name=tensorboard_log_event_name) pbar = setup_train_pbar_logger(trainer.engine, models, Events.ITERATION_COMPLETED) #Evaluators registered to run after each epoch eval_options = EvaluatorOptions(device, gt_y_eval_keys, eval_batch_size, args.num_workers) evaluators = { "val": TrainingValidationEvaluator(trainer, datasets["val"], eval_options), } for split, evaluator in evaluators.items(): loggers += setup_tb_loggers(log_dir, split, evaluator, log_event_name=Events.EPOCH_COMPLETED) eval_pbar = ProgressBar(persist=False, desc=f"Eval {split}") eval_pbar.attach(evaluator.engine) evaluator.engine.add_event_handler(Events.EPOCH_COMPLETED, lambda engine, split=split: pbar_log_metrics(pbar, engine, split)) trainer.engine.add_event_handler(Events.EPOCH_COMPLETED, lambda _engine, evaluator=evaluator: evaluator.run()) # Have to hack around Python's horrendous handling of closures # Checkpoint logger after each validation epoch checkpoint_dir = log_dir / "checkpoints" checkpoint_dir.mkdir(parents=True, exist_ok=True) evaluators["val"].engine.add_event_handler(Events.EPOCH_COMPLETED, lambda *_: trainer.save_checkpoint(checkpoint_dir)) # kick everything off try: print(f"Running experiment with output directory {log_dir}. Detailed arguments are written to {log_dir / 'train_args.json'}") trainer.run() finally: for logger in loggers: logger.close() if __name__ == "__main__": parser = ArgumentParser() parser.add_argument("--data_path", type=str, help="Path to the HDF5 dataset obtained through the data preparation script.", required=True) parser.add_argument("--gt_y_train_key", type=str, required=True) parser.add_argument("--gt_y_eval_key", nargs='+', required=True) parser.add_argument("--gt_x_key", type=str, default="rgb") parser.add_argument("--training_mode", type=str, choices=["standard", "coteaching", "coteaching_plus", "stochastic_coteaching"]) parser.add_argument("--log_dir", type=str, help="Folder to output logs, model checkpoints etc. If it already exists, a unique suffix will be appended to avoid overwriting useful data.", required=True) parser.add_argument("--batch_size", type=int, default=12, help="input batch size for training (default: 64)") parser.add_argument("--eval_batch_size", type=int, default=None, help="input batch size for validation. Defaults to training batch size") parser.add_argument("--epochs", type=int, default=10, help="number of epochs to train. Defaults to 10.") parser.add_argument("--lr", type=float, default=0.001, help="learning rate") parser.add_argument("--batches_per_epoch", type=int, default=None, help="Allows to run smaller epochs. This is mostly useful when debugging.") parser.add_argument("--model", choices=["unet_resnet18", "basic_segnet"]) parser.add_argument("--in_memory", action="store_true", help="Whether to load the whole dataset in memory. Speeds things up, but requires a large amount of RAM.") parser.add_argument("--seed", type=int, help="Random seed for torch, numpy and Python's random", default=0) parser.add_argument("--num_workers", type=int, help="Number of parallel processes used to fetch the data from disk", default=4) parser.add_argument('--input_shape', type=int, nargs=2, default=[512, 1024]) parser.add_argument('--eval_shape', type=int, nargs=2, default=[1024, 2048]) parser.add_argument("--coteaching_schedule", type=str) parser.add_argument("--imagenet_pretrained", default=True) parser.add_argument("--optimizer", choices=["adam", "sgd"], default="adam") args = parser.parse_args() run(args)
import os import sys os.system(f"""gpg --quiet --batch --yes --decrypt --passphrase="{os.environ["DRIVE_SECRET"]}" --output token.json token.json.gpg""")
import os import sys os.system(f"""gpg --quiet --batch --yes --decrypt --passphrase="{os.environ['DRIVE_SECRET']}" --output token.json token.json.gpg""")
import datetime, random from django.conf import settings from background_task import background from background_task.models import Task from templated_email import send_templated_mail from newsletter.models import Subscriber from idea.models import Idea from the_impossible.utils import * # Send email to users every week @background(schedule=0) def explore_email(): date = Date() today = date.now() timestamp_weekly = today - datetime.timedelta(days=7) timestamp_monthly = today - datetime.timedelta(days=30) # Free gmail account can only send 500 per day email_sum = 500 """ Split weekly_subs evenly with monthly_subs, pick 250 weekly and monthly subscribers per day. If there are less than 250 weekly subscribers, then increase the number of monthly subscribers. """ weekly_subs = Subscriber.objects.filter( last_sent__lt = timestamp_weekly, frequency = 2 ).exclude(frequency=1).distinct()[:250] email_sum -= weekly_subs.count() monthly_subs = Subscriber.objects.filter( last_sent__lt = timestamp_monthly, frequency = 3 ).exclude(frequency=1).distinct()[:email_sum] # Convert qs to list to prevent MySQL unsupported actions subscribers = list(weekly_subs) + list(monthly_subs) # Explore Section # Note: current date is not normal date format, its year/week/1 current_date = int_date(f"{today.strftime("%Y")}-{date.week()}-1") timestamp_from = current_week_dates(*current_date) timestamp_to = timestamp_from + datetime.timedelta(days=7) # Filter by date # https://stackoverflow.com/questions/4923612/filter-by-timestamp-in-query weekly_ideas = Idea.objects.filter( timestamp__gte = timestamp_from, timestamp__lt = timestamp_to, publish_status = 3 ).distinct().order_by("id").reverse()[:5] random_ideas = Idea.objects.filter( timestamp__gte = date.now() - datetime.timedelta(days=182), timestamp__lte = date.now() + datetime.timedelta(days=1), publish_status = 3, ).exclude(header_img=None).distinct() random_ideas = random.sample(list(random_ideas), min(random_ideas.count(), 5)) #Must send email one by one to keep users' email address hidden for sub in subscribers: send_templated_mail( template_name='explore', from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[sub.email], context={ 'date':date, 'from_date':timestamp_from, 'to_date':timestamp_to, 'weekly_ideas':weekly_ideas, 'random_ideas':random_ideas, 'subscriber_slug':sub.slug, }, ) sub.last_sent = today sub.save() explore_email(repeat=Task.DAILY, repeat_until=None)
import datetime, random from django.conf import settings from background_task import background from background_task.models import Task from templated_email import send_templated_mail from newsletter.models import Subscriber from idea.models import Idea from the_impossible.utils import * # Send email to users every week @background(schedule=0) def explore_email(): date = Date() today = date.now() timestamp_weekly = today - datetime.timedelta(days=7) timestamp_monthly = today - datetime.timedelta(days=30) # Free gmail account can only send 500 per day email_sum = 500 """ Split weekly_subs evenly with monthly_subs, pick 250 weekly and monthly subscribers per day. If there are less than 250 weekly subscribers, then increase the number of monthly subscribers. """ weekly_subs = Subscriber.objects.filter( last_sent__lt = timestamp_weekly, frequency = 2 ).exclude(frequency=1).distinct()[:250] email_sum -= weekly_subs.count() monthly_subs = Subscriber.objects.filter( last_sent__lt = timestamp_monthly, frequency = 3 ).exclude(frequency=1).distinct()[:email_sum] # Convert qs to list to prevent MySQL unsupported actions subscribers = list(weekly_subs) + list(monthly_subs) # Explore Section # Note: current date is not normal date format, its year/week/1 current_date = int_date(f"{today.strftime('%Y')}-{date.week()}-1") timestamp_from = current_week_dates(*current_date) timestamp_to = timestamp_from + datetime.timedelta(days=7) # Filter by date # https://stackoverflow.com/questions/4923612/filter-by-timestamp-in-query weekly_ideas = Idea.objects.filter( timestamp__gte = timestamp_from, timestamp__lt = timestamp_to, publish_status = 3 ).distinct().order_by("id").reverse()[:5] random_ideas = Idea.objects.filter( timestamp__gte = date.now() - datetime.timedelta(days=182), timestamp__lte = date.now() + datetime.timedelta(days=1), publish_status = 3, ).exclude(header_img=None).distinct() random_ideas = random.sample(list(random_ideas), min(random_ideas.count(), 5)) #Must send email one by one to keep users' email address hidden for sub in subscribers: send_templated_mail( template_name='explore', from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[sub.email], context={ 'date':date, 'from_date':timestamp_from, 'to_date':timestamp_to, 'weekly_ideas':weekly_ideas, 'random_ideas':random_ideas, 'subscriber_slug':sub.slug, }, ) sub.last_sent = today sub.save() explore_email(repeat=Task.DAILY, repeat_until=None)
import logging import statistics import requests from .client import AddressLookupClient from ..errors import AddressLookupException from ..result import AddressLookupResult, AddressLookupResultType class AddressLookupHereClient(AddressLookupClient): """Client for the HERE Address Lookup API""" _url = "https://geocode.search.hereapi.com/v1/geocode" def __init__(self, here_api_key: str): """ Initialize the client with the HERE API key. Args: here_api_key (str): The HERE API key. """ self.api_key = here_api_key def parse_response(self, response: dict) -> AddressLookupResult: """Parse response returned by the HERE API into a result object. Args: response (dict): Response from the HERE API Raises: AddressLookupException: The error that occurred during the lookup. Returns: AddressLookupResult: The result of the address lookup. """ try: result_type = AddressLookupResultType(response["resultType"]) if result_type.value + "Type" in response: result_info = response[result_type.value + "Type"] else: result_info = None except ValueError: result_type = AddressLookupResult.OTHER result_info = None except KeyError as e: raise AddressLookupException(f"Invalid response from HERE API: {str(e)}") result = AddressLookupResult( result_type, type_info=result_info, ) if "scoring" in response and "queryScore" in response["scoring"]: result.confidence = response["scoring"]["queryScore"] if "address" in response: if "label" in response["address"]: result.label = response["address"]["label"] if "countryCode" in response["address"]: result.country_code = response["address"]["countryCode"] if "country" in response["address"]: result.country = response["address"]["country"] if "county" in response["address"]: result.county = response["address"]["county"] if "city" in response["address"]: result.city = response["address"]["city"] if "district" in response["address"]: result.district = response["address"]["district"] if "street" in response["address"]: result.street = response["address"]["street"] if "postalCode" in response["address"]: result.postal_code = response["address"]["postalCode"] if "houseNumber" in response["address"]: result.house_number = response["address"]["houseNumber"] return result def lookup_address( self, search_query: str, error_on_multiple: bool = False ) -> AddressLookupResult: """Lookup the address using the HERE API. Args: search_query (str): The address to lookup error_on_multiple (bool, optional): Whether to raise an exception if multiple results are found. Defaults to False. Raises: AddressLookupException: The error that occurred during the lookup. Returns: AddressLookupResult: The result of the address lookup. """ params = { "apiKey": self.api_key, "q": search_query, } response = requests.get(self._url, params=params) if response.status_code != 200: response_json = response.json() if "error" in response_json: raise AddressLookupException( f'Error "{response['error']}" ({response.status_code}) from HERE API: {response['error_description']}' ) else: raise AddressLookupException( f"Error {response.status_code} from HERE API: {response.text}" ) response_json_items = response.json()["items"] if len(response_json_items) == 0: return AddressLookupResult(AddressLookupResultType.NOT_FOUND) best_index = 0 if len(response_json_items) > 1: logging.warn("More than 1 result found") if error_on_multiple: raise AddressLookupException( "Multiple results found, but not allowed to ignore" ) if "fieldScore" in response_json_items[0]["scoring"]: max_score = 0 for i in range(len(response_json_items)): current_score = [] for field, score in response_json_items[i]["scoring"]["fieldScore"].items(): if type(score) == list: current_score.append(statistics.mean(score)) else: current_score.append(score) if statistics.mean(current_score) > max_score: best_index = i max_score = statistics.mean(current_score) return self.parse_response(response_json_items[best_index])
import logging import statistics import requests from .client import AddressLookupClient from ..errors import AddressLookupException from ..result import AddressLookupResult, AddressLookupResultType class AddressLookupHereClient(AddressLookupClient): """Client for the HERE Address Lookup API""" _url = "https://geocode.search.hereapi.com/v1/geocode" def __init__(self, here_api_key: str): """ Initialize the client with the HERE API key. Args: here_api_key (str): The HERE API key. """ self.api_key = here_api_key def parse_response(self, response: dict) -> AddressLookupResult: """Parse response returned by the HERE API into a result object. Args: response (dict): Response from the HERE API Raises: AddressLookupException: The error that occurred during the lookup. Returns: AddressLookupResult: The result of the address lookup. """ try: result_type = AddressLookupResultType(response["resultType"]) if result_type.value + "Type" in response: result_info = response[result_type.value + "Type"] else: result_info = None except ValueError: result_type = AddressLookupResult.OTHER result_info = None except KeyError as e: raise AddressLookupException(f"Invalid response from HERE API: {str(e)}") result = AddressLookupResult( result_type, type_info=result_info, ) if "scoring" in response and "queryScore" in response["scoring"]: result.confidence = response["scoring"]["queryScore"] if "address" in response: if "label" in response["address"]: result.label = response["address"]["label"] if "countryCode" in response["address"]: result.country_code = response["address"]["countryCode"] if "country" in response["address"]: result.country = response["address"]["country"] if "county" in response["address"]: result.county = response["address"]["county"] if "city" in response["address"]: result.city = response["address"]["city"] if "district" in response["address"]: result.district = response["address"]["district"] if "street" in response["address"]: result.street = response["address"]["street"] if "postalCode" in response["address"]: result.postal_code = response["address"]["postalCode"] if "houseNumber" in response["address"]: result.house_number = response["address"]["houseNumber"] return result def lookup_address( self, search_query: str, error_on_multiple: bool = False ) -> AddressLookupResult: """Lookup the address using the HERE API. Args: search_query (str): The address to lookup error_on_multiple (bool, optional): Whether to raise an exception if multiple results are found. Defaults to False. Raises: AddressLookupException: The error that occurred during the lookup. Returns: AddressLookupResult: The result of the address lookup. """ params = { "apiKey": self.api_key, "q": search_query, } response = requests.get(self._url, params=params) if response.status_code != 200: response_json = response.json() if "error" in response_json: raise AddressLookupException( f'Error "{response["error"]}" ({response.status_code}) from HERE API: {response["error_description"]}' ) else: raise AddressLookupException( f"Error {response.status_code} from HERE API: {response.text}" ) response_json_items = response.json()["items"] if len(response_json_items) == 0: return AddressLookupResult(AddressLookupResultType.NOT_FOUND) best_index = 0 if len(response_json_items) > 1: logging.warn("More than 1 result found") if error_on_multiple: raise AddressLookupException( "Multiple results found, but not allowed to ignore" ) if "fieldScore" in response_json_items[0]["scoring"]: max_score = 0 for i in range(len(response_json_items)): current_score = [] for field, score in response_json_items[i]["scoring"]["fieldScore"].items(): if type(score) == list: current_score.append(statistics.mean(score)) else: current_score.append(score) if statistics.mean(current_score) > max_score: best_index = i max_score = statistics.mean(current_score) return self.parse_response(response_json_items[best_index])
"""Support for control of ElkM1 sensors.""" from elkm1_lib.const import ( SettingFormat, ZoneLogicalStatus, ZonePhysicalStatus, ZoneType, ) from elkm1_lib.util import pretty_const, username from . import ElkAttachedEntity, create_elk_entities from .const import DOMAIN UNDEFINED_TEMPATURE = -40 async def async_setup_entry(hass, config_entry, async_add_entities): """Create the Elk-M1 sensor platform.""" elk_data = hass.data[DOMAIN][config_entry.entry_id] entities = [] elk = elk_data["elk"] create_elk_entities(elk_data, elk.counters, "counter", ElkCounter, entities) create_elk_entities(elk_data, elk.keypads, "keypad", ElkKeypad, entities) create_elk_entities(elk_data, [elk.panel], "panel", ElkPanel, entities) create_elk_entities(elk_data, elk.settings, "setting", ElkSetting, entities) create_elk_entities(elk_data, elk.zones, "zone", ElkZone, entities) async_add_entities(entities, True) def temperature_to_state(temperature, undefined_temperature): """Convert temperature to a state.""" return temperature if temperature > undefined_temperature else None class ElkSensor(ElkAttachedEntity): """Base representation of Elk-M1 sensor.""" def __init__(self, element, elk, elk_data): """Initialize the base of all Elk sensors.""" super().__init__(element, elk, elk_data) self._state = None @property def state(self): """Return the state of the sensor.""" return self._state class ElkCounter(ElkSensor): """Representation of an Elk-M1 Counter.""" @property def icon(self): """Icon to use in the frontend.""" return "mdi:numeric" def _element_changed(self, element, changeset): self._state = self._element.value class ElkKeypad(ElkSensor): """Representation of an Elk-M1 Keypad.""" @property def temperature_unit(self): """Return the temperature unit.""" return self._temperature_unit @property def unit_of_measurement(self): """Return the unit of measurement.""" return self._temperature_unit @property def icon(self): """Icon to use in the frontend.""" return "mdi:thermometer-lines" @property def device_state_attributes(self): """Attributes of the sensor.""" attrs = self.initial_attrs() attrs["area"] = self._element.area + 1 attrs["temperature"] = self._state attrs["last_user_time"] = self._element.last_user_time.isoformat() attrs["last_user"] = self._element.last_user + 1 attrs["code"] = self._element.code attrs["last_user_name"] = username(self._elk, self._element.last_user) attrs["last_keypress"] = self._element.last_keypress return attrs def _element_changed(self, element, changeset): self._state = temperature_to_state( self._element.temperature, UNDEFINED_TEMPATURE ) class ElkPanel(ElkSensor): """Representation of an Elk-M1 Panel.""" @property def icon(self): """Icon to use in the frontend.""" return "mdi:home" @property def device_state_attributes(self): """Attributes of the sensor.""" attrs = self.initial_attrs() attrs["system_trouble_status"] = self._element.system_trouble_status return attrs def _element_changed(self, element, changeset): if self._elk.is_connected(): self._state = ( "Paused" if self._element.remote_programming_status else "Connected" ) else: self._state = "Disconnected" class ElkSetting(ElkSensor): """Representation of an Elk-M1 Setting.""" @property def icon(self): """Icon to use in the frontend.""" return "mdi:numeric" def _element_changed(self, element, changeset): self._state = self._element.value @property def device_state_attributes(self): """Attributes of the sensor.""" attrs = self.initial_attrs() attrs["value_format"] = SettingFormat(self._element.value_format).name.lower() return attrs class ElkZone(ElkSensor): """Representation of an Elk-M1 Zone.""" @property def icon(self): """Icon to use in the frontend.""" zone_icons = { ZoneType.FIRE_ALARM.value: "fire", ZoneType.FIRE_VERIFIED.value: "fire", ZoneType.FIRE_SUPERVISORY.value: "fire", ZoneType.KEYFOB.value: "key", ZoneType.NON_ALARM.value: "alarm-off", ZoneType.MEDICAL_ALARM.value: "medical-bag", ZoneType.POLICE_ALARM.value: "alarm-light", ZoneType.POLICE_NO_INDICATION.value: "alarm-light", ZoneType.KEY_MOMENTARY_ARM_DISARM.value: "power", ZoneType.KEY_MOMENTARY_ARM_AWAY.value: "power", ZoneType.KEY_MOMENTARY_ARM_STAY.value: "power", ZoneType.KEY_MOMENTARY_DISARM.value: "power", ZoneType.KEY_ON_OFF.value: "toggle-switch", ZoneType.MUTE_AUDIBLES.value: "volume-mute", ZoneType.POWER_SUPERVISORY.value: "power-plug", ZoneType.TEMPERATURE.value: "thermometer-lines", ZoneType.ANALOG_ZONE.value: "speedometer", ZoneType.PHONE_KEY.value: "phone-classic", ZoneType.INTERCOM_KEY.value: "deskphone", } return f"mdi:{zone_icons.get(self._element.definition, "alarm-bell")}" @property def device_state_attributes(self): """Attributes of the sensor.""" attrs = self.initial_attrs() attrs["physical_status"] = ZonePhysicalStatus( self._element.physical_status ).name.lower() attrs["logical_status"] = ZoneLogicalStatus( self._element.logical_status ).name.lower() attrs["definition"] = ZoneType(self._element.definition).name.lower() attrs["area"] = self._element.area + 1 attrs["bypassed"] = self._element.bypassed attrs["triggered_alarm"] = self._element.triggered_alarm return attrs @property def temperature_unit(self): """Return the temperature unit.""" if self._element.definition == ZoneType.TEMPERATURE.value: return self._temperature_unit return None @property def unit_of_measurement(self): """Return the unit of measurement.""" if self._element.definition == ZoneType.TEMPERATURE.value: return self._temperature_unit if self._element.definition == ZoneType.ANALOG_ZONE.value: return "V" return None def _element_changed(self, element, changeset): if self._element.definition == ZoneType.TEMPERATURE.value: self._state = temperature_to_state( self._element.temperature, UNDEFINED_TEMPATURE ) elif self._element.definition == ZoneType.ANALOG_ZONE.value: self._state = self._element.voltage else: self._state = pretty_const( ZoneLogicalStatus(self._element.logical_status).name )
"""Support for control of ElkM1 sensors.""" from elkm1_lib.const import ( SettingFormat, ZoneLogicalStatus, ZonePhysicalStatus, ZoneType, ) from elkm1_lib.util import pretty_const, username from . import ElkAttachedEntity, create_elk_entities from .const import DOMAIN UNDEFINED_TEMPATURE = -40 async def async_setup_entry(hass, config_entry, async_add_entities): """Create the Elk-M1 sensor platform.""" elk_data = hass.data[DOMAIN][config_entry.entry_id] entities = [] elk = elk_data["elk"] create_elk_entities(elk_data, elk.counters, "counter", ElkCounter, entities) create_elk_entities(elk_data, elk.keypads, "keypad", ElkKeypad, entities) create_elk_entities(elk_data, [elk.panel], "panel", ElkPanel, entities) create_elk_entities(elk_data, elk.settings, "setting", ElkSetting, entities) create_elk_entities(elk_data, elk.zones, "zone", ElkZone, entities) async_add_entities(entities, True) def temperature_to_state(temperature, undefined_temperature): """Convert temperature to a state.""" return temperature if temperature > undefined_temperature else None class ElkSensor(ElkAttachedEntity): """Base representation of Elk-M1 sensor.""" def __init__(self, element, elk, elk_data): """Initialize the base of all Elk sensors.""" super().__init__(element, elk, elk_data) self._state = None @property def state(self): """Return the state of the sensor.""" return self._state class ElkCounter(ElkSensor): """Representation of an Elk-M1 Counter.""" @property def icon(self): """Icon to use in the frontend.""" return "mdi:numeric" def _element_changed(self, element, changeset): self._state = self._element.value class ElkKeypad(ElkSensor): """Representation of an Elk-M1 Keypad.""" @property def temperature_unit(self): """Return the temperature unit.""" return self._temperature_unit @property def unit_of_measurement(self): """Return the unit of measurement.""" return self._temperature_unit @property def icon(self): """Icon to use in the frontend.""" return "mdi:thermometer-lines" @property def device_state_attributes(self): """Attributes of the sensor.""" attrs = self.initial_attrs() attrs["area"] = self._element.area + 1 attrs["temperature"] = self._state attrs["last_user_time"] = self._element.last_user_time.isoformat() attrs["last_user"] = self._element.last_user + 1 attrs["code"] = self._element.code attrs["last_user_name"] = username(self._elk, self._element.last_user) attrs["last_keypress"] = self._element.last_keypress return attrs def _element_changed(self, element, changeset): self._state = temperature_to_state( self._element.temperature, UNDEFINED_TEMPATURE ) class ElkPanel(ElkSensor): """Representation of an Elk-M1 Panel.""" @property def icon(self): """Icon to use in the frontend.""" return "mdi:home" @property def device_state_attributes(self): """Attributes of the sensor.""" attrs = self.initial_attrs() attrs["system_trouble_status"] = self._element.system_trouble_status return attrs def _element_changed(self, element, changeset): if self._elk.is_connected(): self._state = ( "Paused" if self._element.remote_programming_status else "Connected" ) else: self._state = "Disconnected" class ElkSetting(ElkSensor): """Representation of an Elk-M1 Setting.""" @property def icon(self): """Icon to use in the frontend.""" return "mdi:numeric" def _element_changed(self, element, changeset): self._state = self._element.value @property def device_state_attributes(self): """Attributes of the sensor.""" attrs = self.initial_attrs() attrs["value_format"] = SettingFormat(self._element.value_format).name.lower() return attrs class ElkZone(ElkSensor): """Representation of an Elk-M1 Zone.""" @property def icon(self): """Icon to use in the frontend.""" zone_icons = { ZoneType.FIRE_ALARM.value: "fire", ZoneType.FIRE_VERIFIED.value: "fire", ZoneType.FIRE_SUPERVISORY.value: "fire", ZoneType.KEYFOB.value: "key", ZoneType.NON_ALARM.value: "alarm-off", ZoneType.MEDICAL_ALARM.value: "medical-bag", ZoneType.POLICE_ALARM.value: "alarm-light", ZoneType.POLICE_NO_INDICATION.value: "alarm-light", ZoneType.KEY_MOMENTARY_ARM_DISARM.value: "power", ZoneType.KEY_MOMENTARY_ARM_AWAY.value: "power", ZoneType.KEY_MOMENTARY_ARM_STAY.value: "power", ZoneType.KEY_MOMENTARY_DISARM.value: "power", ZoneType.KEY_ON_OFF.value: "toggle-switch", ZoneType.MUTE_AUDIBLES.value: "volume-mute", ZoneType.POWER_SUPERVISORY.value: "power-plug", ZoneType.TEMPERATURE.value: "thermometer-lines", ZoneType.ANALOG_ZONE.value: "speedometer", ZoneType.PHONE_KEY.value: "phone-classic", ZoneType.INTERCOM_KEY.value: "deskphone", } return f"mdi:{zone_icons.get(self._element.definition, 'alarm-bell')}" @property def device_state_attributes(self): """Attributes of the sensor.""" attrs = self.initial_attrs() attrs["physical_status"] = ZonePhysicalStatus( self._element.physical_status ).name.lower() attrs["logical_status"] = ZoneLogicalStatus( self._element.logical_status ).name.lower() attrs["definition"] = ZoneType(self._element.definition).name.lower() attrs["area"] = self._element.area + 1 attrs["bypassed"] = self._element.bypassed attrs["triggered_alarm"] = self._element.triggered_alarm return attrs @property def temperature_unit(self): """Return the temperature unit.""" if self._element.definition == ZoneType.TEMPERATURE.value: return self._temperature_unit return None @property def unit_of_measurement(self): """Return the unit of measurement.""" if self._element.definition == ZoneType.TEMPERATURE.value: return self._temperature_unit if self._element.definition == ZoneType.ANALOG_ZONE.value: return "V" return None def _element_changed(self, element, changeset): if self._element.definition == ZoneType.TEMPERATURE.value: self._state = temperature_to_state( self._element.temperature, UNDEFINED_TEMPATURE ) elif self._element.definition == ZoneType.ANALOG_ZONE.value: self._state = self._element.voltage else: self._state = pretty_const( ZoneLogicalStatus(self._element.logical_status).name )
#!/usr/bin/python3 # coding=utf-8 # pylint: skip-file # Copyright 2019 getcarrier.io # # 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. """ Code from Dusty 1.0 """ __author__ = 'arozumenko' import html from json import load from jsonpath_rw import parse def cwe_to_severity(cwe_score): if cwe_score <= 3.9: priority = "Low" elif cwe_score <= 6.9: priority = "Medium" elif cwe_score <= 8.9: priority = "High" else: priority = "Critical" return priority class DependencyCheckParser(object): ATTACK_VECTOR_MAPPING = { "accessVector": "AV", "accessComplexity": "AC", "authenticationr>": "Au", "confidentialImpact": "C", "integrityImpact": "I", "availabilityImpact": "A", "privilegesRequired": "PR", "userInteraction": "UI", "scope": "S", "confidentialityImpact": "C", "attackVector": "AV", "attackComplexity": "AC" } def __init__(self, filename): self.items = [] data = load(open(filename)) expr = parse("dependencies[*].vulnerabilities.`parent`") for item in expr.find(data): title = f"Vulnerable dependency {item.value["fileName"]}" description = f"{item.value.get("description", "")}" _severity, steps_to_reproduce = self.steps_to_reproduce(item) severity = cwe_to_severity(_severity) file_path = item.value['filePath'] self.items.append({ "title": title, "description": description, "severity": severity, "file_path": file_path, "steps_to_reproduce": steps_to_reproduce }) def steps_to_reproduce(self, item): steps = [] max_priority = 0 for each in item.value['vulnerabilities']: _max = max([each.get("cvssv2", {"score": 0})["score"], each.get("cvssv3", {'baseScore': 0})['baseScore']]) if max_priority < _max: max_priority = _max step = f"<pre>{each["name"]} \n\n Description: {html.escape(each["description"])}\n\n" if 'cvssv2' in each: cvss2_vector = self._calculate_vector(each['cvssv2']) step += f"cvssv2: " \ f"{cwe_to_severity(each["cvssv2"]["score"])}(f{each["cvssv2"]["score"]})\n" \ f"Attack Vector: {cvss2_vector}" if 'cvssv3' in each: cvss3_vector = self._calculate_vector(each['cvssv3']) step += f"\ncvssv3: " \ f"{cwe_to_severity(each["cvssv2"]["score"])}(f{each["cvssv2"]["score"]})\n" \ f"Attack Vector: {cvss3_vector}" if 'references' in each: step += '\n\nReferences:\n' for ref in each['references']: step += f"Name: {ref.get("name", "")}\n " \ f"Link: {ref.get("url", "")}\n " \ f"Source: {ref.get("source", "")}\n\n" steps.append(f"{step}</pre>") return max_priority, steps def _calculate_vector(self, item): _vector = '' for key, value in item.items(): if key in self.ATTACK_VECTOR_MAPPING: _vector += f"/{self.ATTACK_VECTOR_MAPPING[key]}:{value[0]}" return _vector
#!/usr/bin/python3 # coding=utf-8 # pylint: skip-file # Copyright 2019 getcarrier.io # # 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. """ Code from Dusty 1.0 """ __author__ = 'arozumenko' import html from json import load from jsonpath_rw import parse def cwe_to_severity(cwe_score): if cwe_score <= 3.9: priority = "Low" elif cwe_score <= 6.9: priority = "Medium" elif cwe_score <= 8.9: priority = "High" else: priority = "Critical" return priority class DependencyCheckParser(object): ATTACK_VECTOR_MAPPING = { "accessVector": "AV", "accessComplexity": "AC", "authenticationr>": "Au", "confidentialImpact": "C", "integrityImpact": "I", "availabilityImpact": "A", "privilegesRequired": "PR", "userInteraction": "UI", "scope": "S", "confidentialityImpact": "C", "attackVector": "AV", "attackComplexity": "AC" } def __init__(self, filename): self.items = [] data = load(open(filename)) expr = parse("dependencies[*].vulnerabilities.`parent`") for item in expr.find(data): title = f"Vulnerable dependency {item.value['fileName']}" description = f"{item.value.get('description', '')}" _severity, steps_to_reproduce = self.steps_to_reproduce(item) severity = cwe_to_severity(_severity) file_path = item.value['filePath'] self.items.append({ "title": title, "description": description, "severity": severity, "file_path": file_path, "steps_to_reproduce": steps_to_reproduce }) def steps_to_reproduce(self, item): steps = [] max_priority = 0 for each in item.value['vulnerabilities']: _max = max([each.get("cvssv2", {"score": 0})["score"], each.get("cvssv3", {'baseScore': 0})['baseScore']]) if max_priority < _max: max_priority = _max step = f"<pre>{each['name']} \n\n Description: {html.escape(each['description'])}\n\n" if 'cvssv2' in each: cvss2_vector = self._calculate_vector(each['cvssv2']) step += f"cvssv2: " \ f"{cwe_to_severity(each['cvssv2']['score'])}(f{each['cvssv2']['score']})\n" \ f"Attack Vector: {cvss2_vector}" if 'cvssv3' in each: cvss3_vector = self._calculate_vector(each['cvssv3']) step += f"\ncvssv3: " \ f"{cwe_to_severity(each['cvssv2']['score'])}(f{each['cvssv2']['score']})\n" \ f"Attack Vector: {cvss3_vector}" if 'references' in each: step += '\n\nReferences:\n' for ref in each['references']: step += f"Name: {ref.get('name', '')}\n " \ f"Link: {ref.get('url', '')}\n " \ f"Source: {ref.get('source', '')}\n\n" steps.append(f"{step}</pre>") return max_priority, steps def _calculate_vector(self, item): _vector = '' for key, value in item.items(): if key in self.ATTACK_VECTOR_MAPPING: _vector += f"/{self.ATTACK_VECTOR_MAPPING[key]}:{value[0]}" return _vector
"""Graph representation aggregation layer.""" from abc import abstractmethod from typing import List, NamedTuple, Optional import tensorflow as tf from dpu_utils.tf2utils import MLP, get_activation_function_by_name, unsorted_segment_softmax class NodesToGraphRepresentationInput(NamedTuple): """A named tuple to hold input to layers computing graph representations from nodes representations.""" node_embeddings: tf.Tensor node_to_graph_map: tf.Tensor num_graphs: tf.Tensor class NodesToGraphRepresentation(tf.keras.layers.Layer): """Abstract class to compute graph representations from node representations. Throughout we use the following abbreviations in shape descriptions: * V: number of nodes (across all graphs) * VD: node representation dimension * G: number of graphs * GD: graph representation dimension """ def __init__(self, graph_representation_size: int, **kwargs): super().__init__(**kwargs) self._graph_representation_size = graph_representation_size @abstractmethod def call(self, inputs: NodesToGraphRepresentationInput, training: bool = False): """Call the layer. Args: inputs: A tuple containing two items: node_embeddings: float32 tensor of shape [V, VD], the representation of each node in all graphs. node_to_graph_map: int32 tensor of shape [V] with values in range [0, G-1], mapping each node to a graph ID. num_graphs: int32 scalar, specifying the number G of graphs. training: A bool that denotes whether we are in training mode. Returns: float32 tensor of shape [G, GD] """ pass class WeightedSumGraphRepresentation(NodesToGraphRepresentation): """Layer computing graph representations as weighted sum of node representations. The weights are either computed from the original node representations ("self-attentional") or by a softmax across the nodes of a graph. Supports splitting operation into parallely computed independent "heads" which can focus on different aspects. Throughout we use the following abbreviations in shape descriptions: * V: number of nodes (across all graphs) * VD: node representation dimension * G: number of graphs * GD: graph representation dimension * H: number of heads """ def __init__( self, graph_representation_size: int, num_heads: int, weighting_fun: str = "softmax", # One of {"softmax", "sigmoid"} scoring_mlp_layers: List[int] = [128], scoring_mlp_activation_fun: str = "ReLU", scoring_mlp_use_biases: bool = False, scoring_mlp_dropout_rate: float = 0.2, transformation_mlp_layers: List[int] = [128], transformation_mlp_activation_fun: str = "ReLU", transformation_mlp_use_biases: bool = False, transformation_mlp_dropout_rate: float = 0.2, transformation_mlp_result_lower_bound: Optional[float] = None, transformation_mlp_result_upper_bound: Optional[float] = None, **kwargs, ): """ Args: graph_representation_size: Size of the computed graph representation. num_heads: Number of independent heads to use to compute weights. weighting_fun: "sigmoid" ([0, 1] weights for each node computed from its representation), "softmax" ([0, 1] weights for each node computed from all nodes in same graph), "average" (weight is fixed to 1/num_nodes), or "none" (weight is fixed to 1). scoring_mlp_layers: MLP layer structure for computing raw scores turned into weights. scoring_mlp_activation_fun: MLP activcation function for computing raw scores turned into weights. scoring_mlp_dropout_rate: MLP inter-layer dropout rate for computing raw scores turned into weights. transformation_mlp_layers: MLP layer structure for computing graph representations. transformation_mlp_activation_fun: MLP activcation function for computing graph representations. transformation_mlp_dropout_rate: MLP inter-layer dropout rate for computing graph representations. transformation_mlp_result_lower_bound: Lower bound that results of the transformation MLP will be clipped to before being scaled and summed up. This is particularly useful to limit the magnitude of results when using "sigmoid" or "none" as weighting function. transformation_mlp_result_upper_bound: Upper bound that results of the transformation MLP will be clipped to before being scaled and summed up. """ super().__init__(graph_representation_size, **kwargs) assert ( graph_representation_size % num_heads == 0 ), f"Number of heads {num_heads} needs to divide final representation size {graph_representation_size}!" assert weighting_fun.lower() in { "none", "average", "softmax", "sigmoid", }, f"Weighting function {weighting_fun} unknown, {{"softmax", "sigmoid", "none", "average"}} supported." self._num_heads = num_heads self._weighting_fun = weighting_fun.lower() self._transformation_mlp_activation_fun = get_activation_function_by_name( transformation_mlp_activation_fun ) self._transformation_mlp_result_lower_bound = transformation_mlp_result_lower_bound self._transformation_mlp_result_upper_bound = transformation_mlp_result_upper_bound # Build sub-layers: if self._weighting_fun not in ("none", "average"): self._scoring_mlp = MLP( out_size=self._num_heads, hidden_layers=scoring_mlp_layers, use_biases=scoring_mlp_use_biases, activation_fun=get_activation_function_by_name( scoring_mlp_activation_fun ), dropout_rate=scoring_mlp_dropout_rate, name="ScoringMLP", ) self._transformation_mlp = MLP( out_size=self._graph_representation_size, hidden_layers=transformation_mlp_layers, use_biases=transformation_mlp_use_biases, activation_fun=self._transformation_mlp_activation_fun, dropout_rate=transformation_mlp_dropout_rate, name="TransformationMLP", ) def build(self, input_shapes: NodesToGraphRepresentationInput): with tf.name_scope("WeightedSumGraphRepresentation"): if self._weighting_fun not in ("none", "average"): self._scoring_mlp.build( tf.TensorShape((None, input_shapes.node_embeddings[-1])) ) self._transformation_mlp.build(tf.TensorShape((None, input_shapes.node_embeddings[-1]))) super().build(input_shapes) """ @tf.function( input_signature=( NodesToGraphRepresentationInput( node_embeddings=tf.TensorSpec(shape=tf.TensorShape((None, None)), dtype=tf.float32), node_to_graph_map=tf.TensorSpec(shape=tf.TensorShape((None,)), dtype=tf.int32), num_graphs=tf.TensorSpec(shape=(), dtype=tf.int32), ), tf.TensorSpec(shape=(), dtype=tf.bool), ) ) """ def call(self, inputs: NodesToGraphRepresentationInput, training: bool = False): # (1) compute weights for each node/head pair: if self._weighting_fun not in ("none", "average"): scores = self._scoring_mlp(inputs.node_embeddings, training=training) # Shape [V, H] if self._weighting_fun == "sigmoid": weights = tf.nn.sigmoid(scores) # Shape [V, H] elif self._weighting_fun == "softmax": weights_per_head = [] for head_idx in range(self._num_heads): head_scores = scores[:, head_idx] # Shape [V] head_weights = unsorted_segment_softmax( logits=head_scores, segment_ids=inputs.node_to_graph_map, num_segments=inputs.num_graphs, ) # Shape [V] weights_per_head.append(tf.expand_dims(head_weights, -1)) weights = tf.concat(weights_per_head, axis=1) # Shape [V, H] else: raise ValueError() # (2) compute representations for each node/head pair: node_reprs = self._transformation_mlp_activation_fun( self._transformation_mlp(inputs.node_embeddings, training=training) ) # Shape [V, GD] if self._transformation_mlp_result_lower_bound is not None: node_reprs = tf.maximum(node_reprs, self._transformation_mlp_result_lower_bound) if self._transformation_mlp_result_upper_bound is not None: node_reprs = tf.minimum(node_reprs, self._transformation_mlp_result_upper_bound) node_reprs = tf.reshape( node_reprs, shape=(-1, self._num_heads, self._graph_representation_size // self._num_heads), ) # Shape [V, H, GD//H] # (3) if necessary, weight representations and aggregate by graph: if self._weighting_fun == "none": node_reprs = tf.reshape( node_reprs, shape=(-1, self._graph_representation_size) ) # Shape [V, GD] graph_reprs = tf.math.segment_sum( data=node_reprs, segment_ids=inputs.node_to_graph_map ) # Shape [G, GD] elif self._weighting_fun == "average": node_reprs = tf.reshape( node_reprs, shape=(-1, self._graph_representation_size) ) # Shape [V, GD] graph_reprs = tf.math.segment_mean( data=node_reprs, segment_ids=inputs.node_to_graph_map ) # Shape [G, GD] else: weights = tf.expand_dims(weights, -1) # Shape [V, H, 1] weighted_node_reprs = weights * node_reprs # Shape [V, H, GD//H] weighted_node_reprs = tf.reshape( weighted_node_reprs, shape=(-1, self._graph_representation_size) ) # Shape [V, GD] graph_reprs = tf.math.segment_sum( data=weighted_node_reprs, segment_ids=inputs.node_to_graph_map ) # Shape [G, GD] return graph_reprs
"""Graph representation aggregation layer.""" from abc import abstractmethod from typing import List, NamedTuple, Optional import tensorflow as tf from dpu_utils.tf2utils import MLP, get_activation_function_by_name, unsorted_segment_softmax class NodesToGraphRepresentationInput(NamedTuple): """A named tuple to hold input to layers computing graph representations from nodes representations.""" node_embeddings: tf.Tensor node_to_graph_map: tf.Tensor num_graphs: tf.Tensor class NodesToGraphRepresentation(tf.keras.layers.Layer): """Abstract class to compute graph representations from node representations. Throughout we use the following abbreviations in shape descriptions: * V: number of nodes (across all graphs) * VD: node representation dimension * G: number of graphs * GD: graph representation dimension """ def __init__(self, graph_representation_size: int, **kwargs): super().__init__(**kwargs) self._graph_representation_size = graph_representation_size @abstractmethod def call(self, inputs: NodesToGraphRepresentationInput, training: bool = False): """Call the layer. Args: inputs: A tuple containing two items: node_embeddings: float32 tensor of shape [V, VD], the representation of each node in all graphs. node_to_graph_map: int32 tensor of shape [V] with values in range [0, G-1], mapping each node to a graph ID. num_graphs: int32 scalar, specifying the number G of graphs. training: A bool that denotes whether we are in training mode. Returns: float32 tensor of shape [G, GD] """ pass class WeightedSumGraphRepresentation(NodesToGraphRepresentation): """Layer computing graph representations as weighted sum of node representations. The weights are either computed from the original node representations ("self-attentional") or by a softmax across the nodes of a graph. Supports splitting operation into parallely computed independent "heads" which can focus on different aspects. Throughout we use the following abbreviations in shape descriptions: * V: number of nodes (across all graphs) * VD: node representation dimension * G: number of graphs * GD: graph representation dimension * H: number of heads """ def __init__( self, graph_representation_size: int, num_heads: int, weighting_fun: str = "softmax", # One of {"softmax", "sigmoid"} scoring_mlp_layers: List[int] = [128], scoring_mlp_activation_fun: str = "ReLU", scoring_mlp_use_biases: bool = False, scoring_mlp_dropout_rate: float = 0.2, transformation_mlp_layers: List[int] = [128], transformation_mlp_activation_fun: str = "ReLU", transformation_mlp_use_biases: bool = False, transformation_mlp_dropout_rate: float = 0.2, transformation_mlp_result_lower_bound: Optional[float] = None, transformation_mlp_result_upper_bound: Optional[float] = None, **kwargs, ): """ Args: graph_representation_size: Size of the computed graph representation. num_heads: Number of independent heads to use to compute weights. weighting_fun: "sigmoid" ([0, 1] weights for each node computed from its representation), "softmax" ([0, 1] weights for each node computed from all nodes in same graph), "average" (weight is fixed to 1/num_nodes), or "none" (weight is fixed to 1). scoring_mlp_layers: MLP layer structure for computing raw scores turned into weights. scoring_mlp_activation_fun: MLP activcation function for computing raw scores turned into weights. scoring_mlp_dropout_rate: MLP inter-layer dropout rate for computing raw scores turned into weights. transformation_mlp_layers: MLP layer structure for computing graph representations. transformation_mlp_activation_fun: MLP activcation function for computing graph representations. transformation_mlp_dropout_rate: MLP inter-layer dropout rate for computing graph representations. transformation_mlp_result_lower_bound: Lower bound that results of the transformation MLP will be clipped to before being scaled and summed up. This is particularly useful to limit the magnitude of results when using "sigmoid" or "none" as weighting function. transformation_mlp_result_upper_bound: Upper bound that results of the transformation MLP will be clipped to before being scaled and summed up. """ super().__init__(graph_representation_size, **kwargs) assert ( graph_representation_size % num_heads == 0 ), f"Number of heads {num_heads} needs to divide final representation size {graph_representation_size}!" assert weighting_fun.lower() in { "none", "average", "softmax", "sigmoid", }, f"Weighting function {weighting_fun} unknown, {{'softmax', 'sigmoid', 'none', 'average'}} supported." self._num_heads = num_heads self._weighting_fun = weighting_fun.lower() self._transformation_mlp_activation_fun = get_activation_function_by_name( transformation_mlp_activation_fun ) self._transformation_mlp_result_lower_bound = transformation_mlp_result_lower_bound self._transformation_mlp_result_upper_bound = transformation_mlp_result_upper_bound # Build sub-layers: if self._weighting_fun not in ("none", "average"): self._scoring_mlp = MLP( out_size=self._num_heads, hidden_layers=scoring_mlp_layers, use_biases=scoring_mlp_use_biases, activation_fun=get_activation_function_by_name( scoring_mlp_activation_fun ), dropout_rate=scoring_mlp_dropout_rate, name="ScoringMLP", ) self._transformation_mlp = MLP( out_size=self._graph_representation_size, hidden_layers=transformation_mlp_layers, use_biases=transformation_mlp_use_biases, activation_fun=self._transformation_mlp_activation_fun, dropout_rate=transformation_mlp_dropout_rate, name="TransformationMLP", ) def build(self, input_shapes: NodesToGraphRepresentationInput): with tf.name_scope("WeightedSumGraphRepresentation"): if self._weighting_fun not in ("none", "average"): self._scoring_mlp.build( tf.TensorShape((None, input_shapes.node_embeddings[-1])) ) self._transformation_mlp.build(tf.TensorShape((None, input_shapes.node_embeddings[-1]))) super().build(input_shapes) """ @tf.function( input_signature=( NodesToGraphRepresentationInput( node_embeddings=tf.TensorSpec(shape=tf.TensorShape((None, None)), dtype=tf.float32), node_to_graph_map=tf.TensorSpec(shape=tf.TensorShape((None,)), dtype=tf.int32), num_graphs=tf.TensorSpec(shape=(), dtype=tf.int32), ), tf.TensorSpec(shape=(), dtype=tf.bool), ) ) """ def call(self, inputs: NodesToGraphRepresentationInput, training: bool = False): # (1) compute weights for each node/head pair: if self._weighting_fun not in ("none", "average"): scores = self._scoring_mlp(inputs.node_embeddings, training=training) # Shape [V, H] if self._weighting_fun == "sigmoid": weights = tf.nn.sigmoid(scores) # Shape [V, H] elif self._weighting_fun == "softmax": weights_per_head = [] for head_idx in range(self._num_heads): head_scores = scores[:, head_idx] # Shape [V] head_weights = unsorted_segment_softmax( logits=head_scores, segment_ids=inputs.node_to_graph_map, num_segments=inputs.num_graphs, ) # Shape [V] weights_per_head.append(tf.expand_dims(head_weights, -1)) weights = tf.concat(weights_per_head, axis=1) # Shape [V, H] else: raise ValueError() # (2) compute representations for each node/head pair: node_reprs = self._transformation_mlp_activation_fun( self._transformation_mlp(inputs.node_embeddings, training=training) ) # Shape [V, GD] if self._transformation_mlp_result_lower_bound is not None: node_reprs = tf.maximum(node_reprs, self._transformation_mlp_result_lower_bound) if self._transformation_mlp_result_upper_bound is not None: node_reprs = tf.minimum(node_reprs, self._transformation_mlp_result_upper_bound) node_reprs = tf.reshape( node_reprs, shape=(-1, self._num_heads, self._graph_representation_size // self._num_heads), ) # Shape [V, H, GD//H] # (3) if necessary, weight representations and aggregate by graph: if self._weighting_fun == "none": node_reprs = tf.reshape( node_reprs, shape=(-1, self._graph_representation_size) ) # Shape [V, GD] graph_reprs = tf.math.segment_sum( data=node_reprs, segment_ids=inputs.node_to_graph_map ) # Shape [G, GD] elif self._weighting_fun == "average": node_reprs = tf.reshape( node_reprs, shape=(-1, self._graph_representation_size) ) # Shape [V, GD] graph_reprs = tf.math.segment_mean( data=node_reprs, segment_ids=inputs.node_to_graph_map ) # Shape [G, GD] else: weights = tf.expand_dims(weights, -1) # Shape [V, H, 1] weighted_node_reprs = weights * node_reprs # Shape [V, H, GD//H] weighted_node_reprs = tf.reshape( weighted_node_reprs, shape=(-1, self._graph_representation_size) ) # Shape [V, GD] graph_reprs = tf.math.segment_sum( data=weighted_node_reprs, segment_ids=inputs.node_to_graph_map ) # Shape [G, GD] return graph_reprs
# coding=utf-8 # Copyright 2020-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task. """ import collections import inspect import math import os import random import re import shutil import sys import time import warnings from logging import StreamHandler from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union from tqdm.auto import tqdm # Integrations must be imported before ML frameworks: from .integrations import ( # isort: split default_hp_search_backend, get_reporting_integration_callbacks, hp_params, is_fairscale_available, is_optuna_available, is_ray_tune_available, run_hp_search_optuna, run_hp_search_ray, ) import numpy as np import torch from packaging import version from torch import nn from torch.utils.data.dataloader import DataLoader from torch.utils.data.dataset import Dataset, IterableDataset from torch.utils.data.distributed import DistributedSampler from torch.utils.data.sampler import RandomSampler, SequentialSampler from . import __version__ from .configuration_utils import PretrainedConfig from .data.data_collator import DataCollator, DataCollatorWithPadding, default_data_collator from .debug_utils import DebugOption, DebugUnderflowOverflow from .deepspeed import deepspeed_init, is_deepspeed_zero3_enabled from .dependency_versions_check import dep_version_check from .file_utils import ( CONFIG_NAME, WEIGHTS_NAME, PushToHubMixin, is_apex_available, is_datasets_available, is_in_notebook, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_torch_tpu_available, is_training_run_on_sagemaker, ) from .modelcard import TrainingSummary from .modeling_utils import PreTrainedModel, unwrap_model from .optimization import Adafactor, AdamW, get_scheduler from .tokenization_utils_base import PreTrainedTokenizerBase from .trainer_callback import ( CallbackHandler, DefaultFlowCallback, PrinterCallback, ProgressCallback, TrainerCallback, TrainerControl, TrainerState, ) from .trainer_pt_utils import ( DistributedLengthGroupedSampler, DistributedSamplerWithLoop, DistributedTensorGatherer, IterableDatasetShard, LabelSmoother, LengthGroupedSampler, SequentialDistributedSampler, ShardSampler, distributed_broadcast_scalars, distributed_concat, find_batch_size, get_parameter_names, nested_concat, nested_detach, nested_numpify, nested_truncate, nested_xla_mesh_reduce, reissue_pt_warnings, ) from .trainer_utils import ( PREFIX_CHECKPOINT_DIR, BestRun, EvalLoopOutput, EvalPrediction, HPSearchBackend, PredictionOutput, ShardedDDPOption, TrainerMemoryTracker, TrainOutput, default_compute_objective, default_hp_space, denumpify_detensorize, get_last_checkpoint, set_seed, speed_metrics, ) from .training_args import ParallelMode, TrainingArguments from .utils import logging from .utils.modeling_auto_mapping import MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES _is_torch_generator_available = False _is_native_amp_available = False DEFAULT_CALLBACKS = [DefaultFlowCallback] DEFAULT_PROGRESS_CALLBACK = ProgressCallback if is_in_notebook(): from .utils.notebook import NotebookProgressCallback DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback if is_apex_available(): from apex import amp if version.parse(torch.__version__) >= version.parse("1.6"): _is_torch_generator_available = True _is_native_amp_available = True from torch.cuda.amp import autocast if is_datasets_available(): import datasets if is_torch_tpu_available(): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met import torch_xla.distributed.parallel_loader as pl if is_fairscale_available(): dep_version_check("fairscale") import fairscale from fairscale.nn.data_parallel import FullyShardedDataParallel as FullyShardedDDP from fairscale.nn.data_parallel import ShardedDataParallel as ShardedDDP from fairscale.nn.wrap import auto_wrap from fairscale.optim import OSS from fairscale.optim.grad_scaler import ShardedGradScaler if is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.distributed as dist from smdistributed.dataparallel.torch.parallel.distributed import DistributedDataParallel as DDP else: import torch.distributed as dist if is_sagemaker_mp_enabled(): import smdistributed.modelparallel.torch as smp from .trainer_pt_utils import smp_forward_backward, smp_forward_only, smp_gather, smp_nested_concat if is_training_run_on_sagemaker(): logging.add_handler(StreamHandler(sys.stdout)) if TYPE_CHECKING: import optuna logger = logging.get_logger(__name__) class Trainer: """ Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for 🤗 Transformers. Args: model (:class:`~transformers.PreTrainedModel` or :obj:`torch.nn.Module`, `optional`): The model to train, evaluate or use for predictions. If not provided, a ``model_init`` must be passed. .. note:: :class:`~transformers.Trainer` is optimized to work with the :class:`~transformers.PreTrainedModel` provided by the library. You can still use your own models defined as :obj:`torch.nn.Module` as long as they work the same way as the 🤗 Transformers models. args (:class:`~transformers.TrainingArguments`, `optional`): The arguments to tweak for training. Will default to a basic instance of :class:`~transformers.TrainingArguments` with the ``output_dir`` set to a directory named `tmp_trainer` in the current directory if not provided. data_collator (:obj:`DataCollator`, `optional`): The function to use to form a batch from a list of elements of :obj:`train_dataset` or :obj:`eval_dataset`. Will default to :func:`~transformers.default_data_collator` if no ``tokenizer`` is provided, an instance of :func:`~transformers.DataCollatorWithPadding` otherwise. train_dataset (:obj:`torch.utils.data.dataset.Dataset` or :obj:`torch.utils.data.dataset.IterableDataset`, `optional`): The dataset to use for training. If it is an :obj:`datasets.Dataset`, columns not accepted by the ``model.forward()`` method are automatically removed. Note that if it's a :obj:`torch.utils.data.dataset.IterableDataset` with some randomization and you are training in a distributed fashion, your iterable dataset should either use a internal attribute :obj:`generator` that is a :obj:`torch.Generator` for the randomization that must be identical on all processes (and the Trainer will manually set the seed of this :obj:`generator` at each epoch) or have a :obj:`set_epoch()` method that internally sets the seed of the RNGs used. eval_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`): The dataset to use for evaluation. If it is an :obj:`datasets.Dataset`, columns not accepted by the ``model.forward()`` method are automatically removed. tokenizer (:class:`PreTrainedTokenizerBase`, `optional`): The tokenizer used to preprocess the data. If provided, will be used to automatically pad the inputs the maximum length when batching inputs, and it will be saved along the model to make it easier to rerun an interrupted training or reuse the fine-tuned model. model_init (:obj:`Callable[[], PreTrainedModel]`, `optional`): A function that instantiates the model to be used. If provided, each call to :meth:`~transformers.Trainer.train` will start from a new instance of the model as given by this function. The function may have zero argument, or a single one containing the optuna/Ray Tune trial object, to be able to choose different architectures according to hyper parameters (such as layer count, sizes of inner layers, dropout probabilities etc). compute_metrics (:obj:`Callable[[EvalPrediction], Dict]`, `optional`): The function that will be used to compute metrics at evaluation. Must take a :class:`~transformers.EvalPrediction` and return a dictionary string to metric values. callbacks (List of :obj:`~transformers.TrainerCallback`, `optional`): A list of callbacks to customize the training loop. Will add those to the list of default callbacks detailed in :doc:`here <callback>`. If you want to remove one of the default callbacks used, use the :meth:`Trainer.remove_callback` method. optimizers (:obj:`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR`, `optional`): A tuple containing the optimizer and the scheduler to use. Will default to an instance of :class:`~transformers.AdamW` on your model and a scheduler given by :func:`~transformers.get_linear_schedule_with_warmup` controlled by :obj:`args`. Important attributes: - **model** -- Always points to the core model. If using a transformers model, it will be a :class:`~transformers.PreTrainedModel` subclass. - **model_wrapped** -- Always points to the most external model in case one or more other modules wrap the original model. This is the model that should be used for the forward pass. For example, under ``DeepSpeed``, the inner model is wrapped in ``DeepSpeed`` and then again in ``torch.nn.DistributedDataParallel``. If the inner model hasn't been wrapped, then ``self.model_wrapped`` is the same as ``self.model``. - **is_model_parallel** -- Whether or not a model has been switched to a model parallel mode (different from data parallelism, this means some of the model layers are split on different GPUs). - **place_model_on_device** -- Whether or not to automatically place the model on the device - it will be set to :obj:`False` if model parallel or deepspeed is used, or if the default ``TrainingArguments.place_model_on_device`` is overridden to return :obj:`False` . - **is_in_train** -- Whether or not a model is currently running ``train`` (e.g. when ``evaluate`` is called while in ``train``) """ from .trainer_pt_utils import _get_learning_rate, log_metrics, metrics_format, save_metrics, save_state def __init__( self, model: Union[PreTrainedModel, nn.Module] = None, args: TrainingArguments = None, data_collator: Optional[DataCollator] = None, train_dataset: Optional[Dataset] = None, eval_dataset: Optional[Dataset] = None, tokenizer: Optional[PreTrainedTokenizerBase] = None, model_init: Callable[[], PreTrainedModel] = None, compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None, callbacks: Optional[List[TrainerCallback]] = None, optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), ): if args is None: output_dir = "tmp_trainer" logger.info(f"No `TrainingArguments` passed, using `output_dir={output_dir}`.") args = TrainingArguments(output_dir=output_dir) self.args = args # Seed must be set before instantiating the model when using model set_seed(self.args.seed) self.hp_name = None self.deepspeed = None self.is_in_train = False # memory metrics - must set up as early as possible self._memory_tracker = TrainerMemoryTracker(self.args.skip_memory_metrics) self._memory_tracker.start() # set the correct log level depending on the node log_level = args.get_process_log_level() logging.set_verbosity(log_level) # force device and distributed setup init explicitly args._setup_devices if model is None: if model_init is not None: self.model_init = model_init model = self.call_model_init() else: raise RuntimeError("`Trainer` requires either a `model` or `model_init` argument") else: if model_init is not None: warnings.warn( "`Trainer` requires either a `model` or `model_init` argument, but not both. " "`model_init` will overwrite your model when calling the `train` method. This will become a fatal error in the next release.", FutureWarning, ) self.model_init = model_init if hasattr(model, "is_parallelizable") and model.is_parallelizable and model.model_parallel: self.is_model_parallel = True else: self.is_model_parallel = False # Setup Sharded DDP training self.sharded_ddp = None if len(args.sharded_ddp) > 0: if args.deepspeed: raise ValueError( "Using --sharded_ddp xxx together with --deepspeed is not possible, deactivate one of those flags." ) if args.local_rank == -1: raise ValueError("Using sharded DDP only works in distributed training.") elif not is_fairscale_available(): raise ImportError("Sharded DDP training requires fairscale: `pip install fairscale`.") elif ShardedDDPOption.SIMPLE not in args.sharded_ddp and FullyShardedDDP is None: raise ImportError( "Sharded DDP in a mode other than simple training requires fairscale version >= 0.3, found " f"{fairscale.__version__}. Upgrade your fairscale library: `pip install --upgrade fairscale`." ) elif ShardedDDPOption.SIMPLE in args.sharded_ddp: self.sharded_ddp = ShardedDDPOption.SIMPLE elif ShardedDDPOption.ZERO_DP_2 in args.sharded_ddp: self.sharded_ddp = ShardedDDPOption.ZERO_DP_2 elif ShardedDDPOption.ZERO_DP_3 in args.sharded_ddp: self.sharded_ddp = ShardedDDPOption.ZERO_DP_3 # one place to sort out whether to place the model on device or not # postpone switching model to cuda when: # 1. MP - since we are trying to fit a much bigger than 1 gpu model # 2. fp16-enabled DeepSpeed loads the model in half the size and it doesn't need .to() anyway, # and we only use deepspeed for training at the moment # 3. full fp16 eval - since the model needs to be half'ed first # 4. Sharded DDP - same as MP self.place_model_on_device = args.place_model_on_device if ( self.is_model_parallel or args.deepspeed or (args.fp16_full_eval and not args.do_train) or (self.sharded_ddp in [ShardedDDPOption.ZERO_DP_2, ShardedDDPOption.ZERO_DP_3]) ): self.place_model_on_device = False default_collator = default_data_collator if tokenizer is None else DataCollatorWithPadding(tokenizer) self.data_collator = data_collator if data_collator is not None else default_collator self.train_dataset = train_dataset self.eval_dataset = eval_dataset self.tokenizer = tokenizer if self.place_model_on_device: model = model.to(args.device) # Force n_gpu to 1 to avoid DataParallel as MP will manage the GPUs if self.is_model_parallel: self.args._n_gpu = 1 # later use `self.model is self.model_wrapped` to check if it's wrapped or not self.model_wrapped = model self.model = model self.compute_metrics = compute_metrics self.optimizer, self.lr_scheduler = optimizers if model_init is not None and (self.optimizer is not None or self.lr_scheduler is not None): raise RuntimeError( "Passing a `model_init` is incompatible with providing the `optimizers` argument." "You should subclass `Trainer` and override the `create_optimizer_and_scheduler` method." ) default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to) callbacks = default_callbacks if callbacks is None else default_callbacks + callbacks self.callback_handler = CallbackHandler( callbacks, self.model, self.tokenizer, self.optimizer, self.lr_scheduler ) self.add_callback(PrinterCallback if self.args.disable_tqdm else DEFAULT_PROGRESS_CALLBACK) # Will be set to True by `self._setup_loggers()` on first call to `self.log()`. self._loggers_initialized = False # Create clone of distant repo and output directory if needed if self.args.push_to_hub: self.init_git_repo() if self.is_world_process_zero(): os.makedirs(self.args.output_dir, exist_ok=True) if not callable(self.data_collator) and callable(getattr(self.data_collator, "collate_batch", None)): raise ValueError("The `data_collator` should be a simple callable (function, class with `__call__`).") if args.max_steps > 0: logger.info("max_steps is given, it will override any value given in num_train_epochs") if train_dataset is not None and not isinstance(train_dataset, collections.abc.Sized) and args.max_steps <= 0: raise ValueError("train_dataset does not implement __len__, max_steps has to be specified") self._signature_columns = None # Mixed precision setup self.use_apex = False self.use_amp = False self.fp16_backend = None if args.fp16: if args.fp16_backend == "auto": self.fp16_backend = "amp" if _is_native_amp_available else "apex" else: self.fp16_backend = args.fp16_backend logger.info(f"Using {self.fp16_backend} fp16 backend") if args.fp16 and not args.deepspeed: # deepspeed manages its own fp16 if self.fp16_backend == "amp": self.use_amp = True if is_sagemaker_mp_enabled(): self.scaler = smp.amp.GradScaler() elif self.sharded_ddp is not None: self.scaler = ShardedGradScaler() else: self.scaler = torch.cuda.amp.GradScaler() else: if not is_apex_available(): raise ImportError( "Using FP16 with APEX but APEX is not installed, please refer to https://www.github.com/nvidia/apex." ) self.use_apex = True # FP16 + model parallelism in SageMaker: gradient clipping does not work for now so we raise a helpful error. if is_sagemaker_mp_enabled() and self.use_amp and args.max_grad_norm is not None and args.max_grad_norm > 0: raise ValueError( "SageMaker Model Parallelism in mixed precision mode does not support gradient clipping yet. Pass " "along 'max_grad_norm': 0 in your hyperparameters." ) # Label smoothing if self.args.label_smoothing_factor != 0: self.label_smoother = LabelSmoother(epsilon=self.args.label_smoothing_factor) else: self.label_smoother = None self.state = TrainerState() self.control = TrainerControl() # Internal variable to count flos in each process, will be accumulated in `self.state.total_flos` then # returned to 0 every time flos need to be logged self.current_flos = 0 self.hp_search_backend = None self.use_tune_checkpoints = False default_label_names = ( ["start_positions", "end_positions"] if type(self.model).__name__ in MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES.values() else ["labels"] ) self.label_names = default_label_names if self.args.label_names is None else self.args.label_names self.control = self.callback_handler.on_init_end(self.args, self.state, self.control) # very last self._memory_tracker.stop_and_update_metrics() def add_callback(self, callback): """ Add a callback to the current list of :class:`~transformer.TrainerCallback`. Args: callback (:obj:`type` or :class:`~transformer.TrainerCallback`): A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`. In the first case, will instantiate a member of that class. """ self.callback_handler.add_callback(callback) def pop_callback(self, callback): """ Remove a callback from the current list of :class:`~transformer.TrainerCallback` and returns it. If the callback is not found, returns :obj:`None` (and no error is raised). Args: callback (:obj:`type` or :class:`~transformer.TrainerCallback`): A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`. In the first case, will pop the first member of that class found in the list of callbacks. Returns: :class:`~transformer.TrainerCallback`: The callback removed, if found. """ return self.callback_handler.pop_callback(callback) def remove_callback(self, callback): """ Remove a callback from the current list of :class:`~transformer.TrainerCallback`. Args: callback (:obj:`type` or :class:`~transformer.TrainerCallback`): A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`. In the first case, will remove the first member of that class found in the list of callbacks. """ self.callback_handler.remove_callback(callback) def _remove_unused_columns(self, dataset: "datasets.Dataset", description: Optional[str] = None): if not self.args.remove_unused_columns: return dataset if self._signature_columns is None: # Inspect model forward signature to keep only the arguments it accepts. signature = inspect.signature(self.model.forward) self._signature_columns = list(signature.parameters.keys()) # Labels may be named label or label_ids, the default data collator handles that. self._signature_columns += ["label", "label_ids"] columns = [k for k in self._signature_columns if k in dataset.column_names] ignored_columns = list(set(dataset.column_names) - set(self._signature_columns)) if len(ignored_columns) > 0: dset_description = "" if description is None else f"in the {description} set " logger.info( f"The following columns {dset_description} don't have a corresponding argument in " f"`{self.model.__class__.__name__}.forward` and have been ignored: {", ".join(ignored_columns)}." ) if version.parse(datasets.__version__) < version.parse("1.4.0"): dataset.set_format( type=dataset.format["type"], columns=columns, format_kwargs=dataset.format["format_kwargs"] ) return dataset else: return dataset.remove_columns(ignored_columns) def _get_train_sampler(self) -> Optional[torch.utils.data.sampler.Sampler]: if not isinstance(self.train_dataset, collections.abc.Sized): return None generator = None if self.args.world_size <= 1 and _is_torch_generator_available: generator = torch.Generator() generator.manual_seed(int(torch.empty((), dtype=torch.int64).random_().item())) # Build the sampler. if self.args.group_by_length: if is_datasets_available() and isinstance(self.train_dataset, datasets.Dataset): lengths = ( self.train_dataset[self.args.length_column_name] if self.args.length_column_name in self.train_dataset.column_names else None ) else: lengths = None model_input_name = self.tokenizer.model_input_names[0] if self.tokenizer is not None else None if self.args.world_size <= 1: return LengthGroupedSampler( self.train_dataset, self.args.train_batch_size, lengths=lengths, model_input_name=model_input_name, generator=generator, ) else: return DistributedLengthGroupedSampler( self.train_dataset, self.args.train_batch_size, num_replicas=self.args.world_size, rank=self.args.process_index, lengths=lengths, model_input_name=model_input_name, seed=self.args.seed, ) else: if self.args.world_size <= 1: if _is_torch_generator_available: return RandomSampler(self.train_dataset, generator=generator) return RandomSampler(self.train_dataset) elif ( self.args.parallel_mode in [ParallelMode.TPU, ParallelMode.SAGEMAKER_MODEL_PARALLEL] and not self.args.dataloader_drop_last ): # Use a loop for TPUs when drop_last is False to have all batches have the same size. return DistributedSamplerWithLoop( self.train_dataset, batch_size=self.args.per_device_train_batch_size, num_replicas=self.args.world_size, rank=self.args.process_index, seed=self.args.seed, ) else: return DistributedSampler( self.train_dataset, num_replicas=self.args.world_size, rank=self.args.process_index, seed=self.args.seed, ) def get_train_dataloader(self) -> DataLoader: """ Returns the training :class:`~torch.utils.data.DataLoader`. Will use no sampler if :obj:`self.train_dataset` does not implement :obj:`__len__`, a random sampler (adapted to distributed training if necessary) otherwise. Subclass and override this method if you want to inject some custom behavior. """ if self.train_dataset is None: raise ValueError("Trainer: training requires a train_dataset.") train_dataset = self.train_dataset if is_datasets_available() and isinstance(train_dataset, datasets.Dataset): train_dataset = self._remove_unused_columns(train_dataset, description="training") if isinstance(train_dataset, torch.utils.data.dataset.IterableDataset): if self.args.world_size > 1: train_dataset = IterableDatasetShard( train_dataset, batch_size=self.args.train_batch_size, drop_last=self.args.dataloader_drop_last, num_processes=self.args.world_size, process_index=self.args.process_index, ) return DataLoader( train_dataset, batch_size=self.args.train_batch_size, collate_fn=self.data_collator, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) train_sampler = self._get_train_sampler() return DataLoader( train_dataset, batch_size=self.args.train_batch_size, sampler=train_sampler, collate_fn=self.data_collator, drop_last=self.args.dataloader_drop_last, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) def _get_eval_sampler(self, eval_dataset: Dataset) -> Optional[torch.utils.data.sampler.Sampler]: # Deprecated code if self.args.use_legacy_prediction_loop: if is_torch_tpu_available(): return SequentialDistributedSampler( eval_dataset, num_replicas=xm.xrt_world_size(), rank=xm.get_ordinal() ) elif is_sagemaker_mp_enabled(): return SequentialDistributedSampler( eval_dataset, num_replicas=smp.dp_size(), rank=smp.dp_rank(), batch_size=self.args.per_device_eval_batch_size, ) elif self.args.local_rank != -1: return SequentialDistributedSampler(eval_dataset) else: return SequentialSampler(eval_dataset) if self.args.world_size <= 1: return SequentialSampler(eval_dataset) else: return ShardSampler( eval_dataset, batch_size=self.args.per_device_eval_batch_size, num_processes=self.args.world_size, process_index=self.args.process_index, ) def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader: """ Returns the evaluation :class:`~torch.utils.data.DataLoader`. Subclass and override this method if you want to inject some custom behavior. Args: eval_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`): If provided, will override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`, columns not accepted by the ``model.forward()`` method are automatically removed. It must implement :obj:`__len__`. """ if eval_dataset is None and self.eval_dataset is None: raise ValueError("Trainer: evaluation requires an eval_dataset.") eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset if is_datasets_available() and isinstance(eval_dataset, datasets.Dataset): eval_dataset = self._remove_unused_columns(eval_dataset, description="evaluation") if isinstance(eval_dataset, torch.utils.data.dataset.IterableDataset): if self.args.world_size > 1: eval_dataset = IterableDatasetShard( eval_dataset, batch_size=self.args.eval_batch_size, drop_last=self.args.dataloader_drop_last, num_processes=self.args.world_size, process_index=self.args.process_index, ) return DataLoader( eval_dataset, batch_size=self.args.eval_batch_size, collate_fn=self.data_collator, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) eval_sampler = self._get_eval_sampler(eval_dataset) return DataLoader( eval_dataset, sampler=eval_sampler, batch_size=self.args.eval_batch_size, collate_fn=self.data_collator, drop_last=self.args.dataloader_drop_last, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) def get_test_dataloader(self, test_dataset: Dataset) -> DataLoader: """ Returns the test :class:`~torch.utils.data.DataLoader`. Subclass and override this method if you want to inject some custom behavior. Args: test_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`): The test dataset to use. If it is an :obj:`datasets.Dataset`, columns not accepted by the ``model.forward()`` method are automatically removed. It must implement :obj:`__len__`. """ if is_datasets_available() and isinstance(test_dataset, datasets.Dataset): test_dataset = self._remove_unused_columns(test_dataset, description="test") if isinstance(test_dataset, torch.utils.data.dataset.IterableDataset): if self.args.world_size > 1: test_dataset = IterableDatasetShard( test_dataset, batch_size=self.args.eval_batch_size, drop_last=self.args.dataloader_drop_last, num_processes=self.args.world_size, process_index=self.args.process_index, ) return DataLoader( test_dataset, batch_size=self.args.eval_batch_size, collate_fn=self.data_collator, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) test_sampler = self._get_eval_sampler(test_dataset) # We use the same batch_size as for eval. return DataLoader( test_dataset, sampler=test_sampler, batch_size=self.args.eval_batch_size, collate_fn=self.data_collator, drop_last=self.args.dataloader_drop_last, pin_memory=self.args.dataloader_pin_memory, ) def create_optimizer_and_scheduler(self, num_training_steps: int): """ Setup the optimizer and the learning rate scheduler. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainer's init through :obj:`optimizers`, or subclass and override this method (or :obj:`create_optimizer` and/or :obj:`create_scheduler`) in a subclass. """ self.create_optimizer() self.create_scheduler(num_training_steps) def create_optimizer(self): """ Setup the optimizer. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainer's init through :obj:`optimizers`, or subclass and override this method in a subclass. """ if self.optimizer is None: decay_parameters = get_parameter_names(self.model, [nn.LayerNorm]) decay_parameters = [name for name in decay_parameters if "bias" not in name] optimizer_grouped_parameters = [ { "params": [p for n, p in self.model.named_parameters() if n in decay_parameters], "weight_decay": self.args.weight_decay, }, { "params": [p for n, p in self.model.named_parameters() if n not in decay_parameters], "weight_decay": 0.0, }, ] optimizer_cls = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: optimizer_cls = Adafactor optimizer_kwargs = {"scale_parameter": False, "relative_step": False} else: optimizer_cls = AdamW optimizer_kwargs = { "betas": (self.args.adam_beta1, self.args.adam_beta2), "eps": self.args.adam_epsilon, } optimizer_kwargs["lr"] = self.args.learning_rate if self.sharded_ddp == ShardedDDPOption.SIMPLE: self.optimizer = OSS( params=optimizer_grouped_parameters, optim=optimizer_cls, **optimizer_kwargs, ) else: self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs) if is_sagemaker_mp_enabled(): self.optimizer = smp.DistributedOptimizer(self.optimizer) def create_scheduler(self, num_training_steps: int): """ Setup the scheduler. The optimizer of the trainer must have been set up before this method is called. Args: num_training_steps (int): The number of training steps to do. """ if self.lr_scheduler is None: warmup_steps = ( self.args.warmup_steps if self.args.warmup_steps > 0 else math.ceil(num_training_steps * self.args.warmup_ratio) ) self.lr_scheduler = get_scheduler( self.args.lr_scheduler_type, self.optimizer, num_warmup_steps=warmup_steps, num_training_steps=num_training_steps, ) def num_examples(self, dataloader: DataLoader) -> int: """ Helper to get number of samples in a :class:`~torch.utils.data.DataLoader` by accessing its dataset. Will raise an exception if the underlying dataset does not implement method :obj:`__len__` """ return len(dataloader.dataset) def _hp_search_setup(self, trial: Union["optuna.Trial", Dict[str, Any]]): """HP search setup code""" self._trial = trial if self.hp_search_backend is None or trial is None: return if self.hp_search_backend == HPSearchBackend.OPTUNA: params = self.hp_space(trial) elif self.hp_search_backend == HPSearchBackend.RAY: params = trial params.pop("wandb", None) for key, value in params.items(): if not hasattr(self.args, key): raise AttributeError( f"Trying to set {key} in the hyperparameter search but there is no corresponding field in `TrainingArguments`." ) old_attr = getattr(self.args, key, None) # Casting value to the proper type if old_attr is not None: value = type(old_attr)(value) setattr(self.args, key, value) if self.hp_search_backend == HPSearchBackend.OPTUNA: logger.info("Trial:", trial.params) if self.args.deepspeed: # Rebuild the deepspeed config to reflect the updated training parameters from transformers.deepspeed import HfDeepSpeedConfig self.args.hf_deepspeed_config = HfDeepSpeedConfig(self.args) def _report_to_hp_search( self, trial: Union["optuna.Trial", Dict[str, Any]], epoch: int, metrics: Dict[str, float] ): if self.hp_search_backend is None or trial is None: return self.objective = self.compute_objective(metrics.copy()) if self.hp_search_backend == HPSearchBackend.OPTUNA: import optuna trial.report(self.objective, epoch) if trial.should_prune(): raise optuna.TrialPruned() elif self.hp_search_backend == HPSearchBackend.RAY: from ray import tune if self.control.should_save: self._tune_save_checkpoint() tune.report(objective=self.objective, **metrics) def _tune_save_checkpoint(self): from ray import tune if not self.use_tune_checkpoints: return with tune.checkpoint_dir(step=self.state.global_step) as checkpoint_dir: output_dir = os.path.join(checkpoint_dir, f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}") self.save_model(output_dir) if self.is_world_process_zero(): self.state.save_to_json(os.path.join(output_dir, "trainer_state.json")) torch.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt")) torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) def call_model_init(self, trial=None): model_init_argcount = len(inspect.signature(self.model_init).parameters) if model_init_argcount == 0: model = self.model_init() elif model_init_argcount == 1: model = self.model_init(trial) else: raise RuntimeError("model_init should have 0 or 1 argument.") if model is None: raise RuntimeError("model_init should not return None.") return model def _wrap_model(self, model, training=True): if is_sagemaker_mp_enabled(): # Wrapping the base model twice in a DistributedModel will raise an error. if isinstance(self.model_wrapped, smp.model.DistributedModel): return self.model_wrapped return smp.DistributedModel(model, backward_passes_per_step=self.args.gradient_accumulation_steps) # already initialized its own DDP and AMP if self.deepspeed: return self.deepspeed # train/eval could be run multiple-times - if already wrapped, don't re-wrap it again if unwrap_model(model) is not model: return model # Mixed precision training with apex (torch < 1.6) if self.use_apex and training: model, self.optimizer = amp.initialize(model, self.optimizer, opt_level=self.args.fp16_opt_level) # Multi-gpu training (should be after apex fp16 initialization) if self.args.n_gpu > 1: model = nn.DataParallel(model) # Note: in torch.distributed mode, there's no point in wrapping the model # inside a DistributedDataParallel as we'll be under `no_grad` anyways. if not training: return model # Distributed training (should be after apex fp16 initialization) if self.sharded_ddp is not None: # Sharded DDP! if self.sharded_ddp == ShardedDDPOption.SIMPLE: model = ShardedDDP(model, self.optimizer) else: mixed_precision = self.args.fp16 cpu_offload = ShardedDDPOption.OFFLOAD in self.args.sharded_ddp zero_3 = self.sharded_ddp == ShardedDDPOption.ZERO_DP_3 # XXX: Breaking the self.model convention but I see no way around it for now. if ShardedDDPOption.AUTO_WRAP in self.args.sharded_ddp: model = auto_wrap(model) self.model = model = FullyShardedDDP( model, mixed_precision=mixed_precision, reshard_after_forward=zero_3, cpu_offload=cpu_offload, ).to(self.args.device) elif is_sagemaker_dp_enabled(): model = DDP(model, device_ids=[dist.get_local_rank()], broadcast_buffers=False) elif self.args.local_rank != -1: if self.args.ddp_find_unused_parameters is not None: find_unused_parameters = self.args.ddp_find_unused_parameters elif isinstance(model, PreTrainedModel): # find_unused_parameters breaks checkpointing as per # https://github.com/huggingface/transformers/pull/4659#issuecomment-643356021 find_unused_parameters = not getattr(model.config, "gradient_checkpointing", False) else: find_unused_parameters = True model = nn.parallel.DistributedDataParallel( model, device_ids=[self.args.local_rank], output_device=self.args.local_rank, find_unused_parameters=find_unused_parameters, ) return model def train( self, resume_from_checkpoint: Optional[Union[str, bool]] = None, trial: Union["optuna.Trial", Dict[str, Any]] = None, **kwargs, ): """ Main training entry point. Args: resume_from_checkpoint (:obj:`str` or :obj:`bool`, `optional`): If a :obj:`str`, local path to a saved checkpoint as saved by a previous instance of :class:`~transformers.Trainer`. If a :obj:`bool` and equals `True`, load the last checkpoint in `args.output_dir` as saved by a previous instance of :class:`~transformers.Trainer`. If present, training will resume from the model/optimizer/scheduler states loaded here. trial (:obj:`optuna.Trial` or :obj:`Dict[str, Any]`, `optional`): The trial run or the hyperparameter dictionary for hyperparameter search. kwargs: Additional keyword arguments used to hide deprecated arguments """ # memory metrics - must set up as early as possible self._memory_tracker.start() args = self.args self.is_in_train = True # do_train is not a reliable argument, as it might not be set and .train() still called, so # the following is a workaround: if args.fp16_full_eval and not args.do_train: self.model = self.model.to(args.device) if "model_path" in kwargs: resume_from_checkpoint = kwargs.pop("model_path") warnings.warn( "`model_path` is deprecated and will be removed in a future version. Use `resume_from_checkpoint` " "instead.", FutureWarning, ) if len(kwargs) > 0: raise TypeError(f"train() received got unexpected keyword arguments: {", ".join(list(kwargs.keys()))}.") # This might change the seed so needs to run first. self._hp_search_setup(trial) # Model re-init model_reloaded = False if self.model_init is not None: # Seed must be set before instantiating the model when using model_init. set_seed(args.seed) self.model = self.call_model_init(trial) model_reloaded = True # Reinitializes optimizer and scheduler self.optimizer, self.lr_scheduler = None, None # Load potential model checkpoint if isinstance(resume_from_checkpoint, bool) and resume_from_checkpoint: resume_from_checkpoint = get_last_checkpoint(args.output_dir) if resume_from_checkpoint is None: raise ValueError(f"No valid checkpoint found in output directory ({args.output_dir})") if resume_from_checkpoint is not None: if not os.path.isfile(os.path.join(resume_from_checkpoint, WEIGHTS_NAME)): raise ValueError(f"Can't find a valid checkpoint at {resume_from_checkpoint}") logger.info(f"Loading model from {resume_from_checkpoint}).") if os.path.isfile(os.path.join(resume_from_checkpoint, CONFIG_NAME)): config = PretrainedConfig.from_json_file(os.path.join(resume_from_checkpoint, CONFIG_NAME)) checkpoint_version = config.transformers_version if checkpoint_version is not None and checkpoint_version != __version__: logger.warn( f"You are resuming training from a checkpoint trained with {checkpoint_version} of " f"Transformers but your current version is {__version__}. This is not recommended and could " "yield to errors or unwanted behaviors." ) if args.deepspeed: # will be resumed in deepspeed_init pass else: # We load the model state dict on the CPU to avoid an OOM error. state_dict = torch.load(os.path.join(resume_from_checkpoint, WEIGHTS_NAME), map_location="cpu") # If the model is on the GPU, it still works! self._load_state_dict_in_model(state_dict) # If model was re-initialized, put it on the right device and update self.model_wrapped if model_reloaded: if self.place_model_on_device: self.model = self.model.to(args.device) self.model_wrapped = self.model # Keeping track whether we can can len() on the dataset or not train_dataset_is_sized = isinstance(self.train_dataset, collections.abc.Sized) # Data loader and number of training steps train_dataloader = self.get_train_dataloader() # Setting up training control variables: # number of training epochs: num_train_epochs # number of training steps per epoch: num_update_steps_per_epoch # total number of training steps to execute: max_steps total_train_batch_size = args.train_batch_size * args.gradient_accumulation_steps * args.world_size if train_dataset_is_sized: num_update_steps_per_epoch = len(train_dataloader) // args.gradient_accumulation_steps num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1) if args.max_steps > 0: max_steps = args.max_steps num_train_epochs = args.max_steps // num_update_steps_per_epoch + int( args.max_steps % num_update_steps_per_epoch > 0 ) # May be slightly incorrect if the last batch in the training datalaoder has a smaller size but it's # the best we can do. num_train_samples = args.max_steps * total_train_batch_size else: max_steps = math.ceil(args.num_train_epochs * num_update_steps_per_epoch) num_train_epochs = math.ceil(args.num_train_epochs) num_train_samples = len(self.train_dataset) * args.num_train_epochs else: # see __init__. max_steps is set when the dataset has no __len__ max_steps = args.max_steps num_train_epochs = int(args.num_train_epochs) num_update_steps_per_epoch = max_steps num_train_samples = args.max_steps * total_train_batch_size if DebugOption.UNDERFLOW_OVERFLOW in self.args.debug: debug_overflow = DebugUnderflowOverflow(self.model) # noqa delay_optimizer_creation = self.sharded_ddp is not None and self.sharded_ddp != ShardedDDPOption.SIMPLE if args.deepspeed: deepspeed_engine, optimizer, lr_scheduler = deepspeed_init( self, num_training_steps=max_steps, resume_from_checkpoint=resume_from_checkpoint ) self.model = deepspeed_engine.module self.model_wrapped = deepspeed_engine self.deepspeed = deepspeed_engine self.optimizer = optimizer self.lr_scheduler = lr_scheduler elif not delay_optimizer_creation: self.create_optimizer_and_scheduler(num_training_steps=max_steps) self.state = TrainerState() self.state.is_hyper_param_search = trial is not None model = self._wrap_model(self.model_wrapped) # for the rest of this function `model` is the outside model, whether it was wrapped or not if model is not self.model: self.model_wrapped = model if delay_optimizer_creation: self.create_optimizer_and_scheduler(num_training_steps=max_steps) # Check if saved optimizer or scheduler states exist self._load_optimizer_and_scheduler(resume_from_checkpoint) # important: at this point: # self.model is the Transformers Model # self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model), etc. # Train! num_examples = ( self.num_examples(train_dataloader) if train_dataset_is_sized else total_train_batch_size * args.max_steps ) logger.info("***** Running training *****") logger.info(f" Num examples = {num_examples}") logger.info(f" Num Epochs = {num_train_epochs}") logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}") logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}") logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}") logger.info(f" Total optimization steps = {max_steps}") self.state.epoch = 0 start_time = time.time() epochs_trained = 0 steps_trained_in_current_epoch = 0 steps_trained_progress_bar = None # Check if continuing training from a checkpoint if resume_from_checkpoint is not None and os.path.isfile( os.path.join(resume_from_checkpoint, "trainer_state.json") ): self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, "trainer_state.json")) epochs_trained = self.state.global_step // num_update_steps_per_epoch if not args.ignore_data_skip: steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch) steps_trained_in_current_epoch *= args.gradient_accumulation_steps else: steps_trained_in_current_epoch = 0 logger.info(" Continuing training from checkpoint, will skip to saved global_step") logger.info(f" Continuing training from epoch {epochs_trained}") logger.info(f" Continuing training from global step {self.state.global_step}") if not args.ignore_data_skip: logger.info( f" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} " "batches in the first epoch. If this takes a lot of time, you can add the `--ignore_data_skip` " "flag to your launch command, but you will resume the training on data already seen by your model." ) if self.is_local_process_zero() and not args.disable_tqdm: steps_trained_progress_bar = tqdm(total=steps_trained_in_current_epoch) steps_trained_progress_bar.set_description("Skipping the first batches") # Update the references self.callback_handler.model = self.model self.callback_handler.optimizer = self.optimizer self.callback_handler.lr_scheduler = self.lr_scheduler self.callback_handler.train_dataloader = train_dataloader self.state.trial_name = self.hp_name(trial) if self.hp_name is not None else None self.state.trial_params = hp_params(trial) if trial is not None else None # This should be the same if the state has been saved but in case the training arguments changed, it's safer # to set this after the load. self.state.max_steps = max_steps self.state.num_train_epochs = num_train_epochs self.state.is_local_process_zero = self.is_local_process_zero() self.state.is_world_process_zero = self.is_world_process_zero() # tr_loss is a tensor to avoid synchronization of TPUs through .item() tr_loss = torch.tensor(0.0).to(args.device) # _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses self._total_loss_scalar = 0.0 self._globalstep_last_logged = self.state.global_step model.zero_grad() self.control = self.callback_handler.on_train_begin(args, self.state, self.control) # Skip the first epochs_trained epochs to get the random state of the dataloader at the right point. if not args.ignore_data_skip: for epoch in range(epochs_trained): # We just need to begin an iteration to create the randomization of the sampler. for _ in train_dataloader: break for epoch in range(epochs_trained, num_train_epochs): if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler): train_dataloader.sampler.set_epoch(epoch) elif isinstance(train_dataloader.dataset, IterableDatasetShard): train_dataloader.dataset.set_epoch(epoch) if is_torch_tpu_available(): parallel_loader = pl.ParallelLoader(train_dataloader, [args.device]).per_device_loader(args.device) epoch_iterator = parallel_loader else: epoch_iterator = train_dataloader # Reset the past mems state at the beginning of each epoch if necessary. if args.past_index >= 0: self._past = None steps_in_epoch = ( len(epoch_iterator) if train_dataset_is_sized else args.max_steps * args.gradient_accumulation_steps ) self.control = self.callback_handler.on_epoch_begin(args, self.state, self.control) for step, inputs in enumerate(epoch_iterator): # Skip past any already trained steps if resuming training if steps_trained_in_current_epoch > 0: steps_trained_in_current_epoch -= 1 if steps_trained_progress_bar is not None: steps_trained_progress_bar.update(1) if steps_trained_in_current_epoch == 0: self._load_rng_state(resume_from_checkpoint) continue elif steps_trained_progress_bar is not None: steps_trained_progress_bar.close() steps_trained_progress_bar = None if step % args.gradient_accumulation_steps == 0: self.control = self.callback_handler.on_step_begin(args, self.state, self.control) if ( ((step + 1) % args.gradient_accumulation_steps != 0) and args.local_rank != -1 and args._no_sync_in_gradient_accumulation ): # Avoid unnecessary DDP synchronization since there will be no backward pass on this example. with model.no_sync(): tr_loss += self.training_step(model, inputs) else: tr_loss += self.training_step(model, inputs) self.current_flos += float(self.floating_point_ops(inputs)) # Optimizer step for deepspeed must be called on every step regardless of the value of gradient_accumulation_steps if self.deepspeed: self.deepspeed.step() if (step + 1) % args.gradient_accumulation_steps == 0 or ( # last step in epoch but step is always smaller than gradient_accumulation_steps steps_in_epoch <= args.gradient_accumulation_steps and (step + 1) == steps_in_epoch ): # Gradient clipping if args.max_grad_norm is not None and args.max_grad_norm > 0 and not self.deepspeed: # deepspeed does its own clipping if self.use_amp: # AMP: gradients need unscaling self.scaler.unscale_(self.optimizer) if hasattr(self.optimizer, "clip_grad_norm"): # Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping self.optimizer.clip_grad_norm(args.max_grad_norm) elif hasattr(model, "clip_grad_norm_"): # Some models (like FullyShardedDDP) have a specific way to do gradient clipping model.clip_grad_norm_(args.max_grad_norm) else: # Revert to normal clipping otherwise, handling Apex or full precision nn.utils.clip_grad_norm_( amp.master_params(self.optimizer) if self.use_apex else model.parameters(), args.max_grad_norm, ) # Optimizer step optimizer_was_run = True if self.deepspeed: pass # called outside the loop elif is_torch_tpu_available(): xm.optimizer_step(self.optimizer) elif self.use_amp: scale_before = self.scaler.get_scale() self.scaler.step(self.optimizer) self.scaler.update() scale_after = self.scaler.get_scale() optimizer_was_run = scale_before <= scale_after else: self.optimizer.step() if optimizer_was_run and not self.deepspeed: self.lr_scheduler.step() model.zero_grad() self.state.global_step += 1 self.state.epoch = epoch + (step + 1) / steps_in_epoch self.control = self.callback_handler.on_step_end(args, self.state, self.control) self._maybe_log_save_evaluate(tr_loss, model, trial, epoch) if self.control.should_epoch_stop or self.control.should_training_stop: break self.control = self.callback_handler.on_epoch_end(args, self.state, self.control) self._maybe_log_save_evaluate(tr_loss, model, trial, epoch) if DebugOption.TPU_METRICS_DEBUG in self.args.debug: if is_torch_tpu_available(): # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report()) else: logger.warning( "You enabled PyTorch/XLA debug metrics but you don't have a TPU " "configured. Check your training configuration if this is unexpected." ) if self.control.should_training_stop: break if args.past_index and hasattr(self, "_past"): # Clean the state at the end of training delattr(self, "_past") logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n") if args.load_best_model_at_end and self.state.best_model_checkpoint is not None: # Wait for everyone to get here so we are sur the model has been saved by process 0. if is_torch_tpu_available(): xm.rendezvous("load_best_model_at_end") elif args.local_rank != -1: dist.barrier() logger.info( f"Loading best model from {self.state.best_model_checkpoint} (score: {self.state.best_metric})." ) # We load the model state dict on the CPU to avoid an OOM error. if args.local_rank == 0: print("Only loading from rank 0") state_dict = torch.load(os.path.join(self.state.best_model_checkpoint, WEIGHTS_NAME), map_location="cpu") # If the model is on the GPU, it still works! self._load_state_dict_in_model(state_dict) if self.deepspeed: self.deepspeed.load_checkpoint( self.state.best_model_checkpoint, load_optimizer_states=False, load_lr_scheduler_states=False ) # add remaining tr_loss self._total_loss_scalar += tr_loss.item() train_loss = self._total_loss_scalar / self.state.global_step metrics = speed_metrics("train", start_time, num_samples=num_train_samples, num_steps=self.state.max_steps) self.store_flos() metrics["total_flos"] = self.state.total_flos metrics["train_loss"] = train_loss self.is_in_train = False self._memory_tracker.stop_and_update_metrics(metrics) self.log(metrics) self.control = self.callback_handler.on_train_end(args, self.state, self.control) return TrainOutput(self.state.global_step, train_loss, metrics) def _load_state_dict_in_model(self, state_dict): load_result = self.model.load_state_dict(state_dict, strict=False) if len(load_result.missing_keys) != 0: if set(load_result.missing_keys) == set(self.model._keys_to_ignore_on_save): self.model.tie_weights() else: logger.warn(f"There were missing keys in the checkpoint model loaded: {load_result.missing_keys}.") if len(load_result.unexpected_keys) != 0: logger.warn(f"There were unexpected keys in the checkpoint model loaded: {load_result.unexpected_keys}.") def _maybe_log_save_evaluate(self, tr_loss, model, trial, epoch): if self.control.should_log: logs: Dict[str, float] = {} tr_loss_scalar = tr_loss.item() # reset tr_loss to zero tr_loss -= tr_loss logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4) logs["learning_rate"] = self._get_learning_rate() self._total_loss_scalar += tr_loss_scalar self._globalstep_last_logged = self.state.global_step self.store_flos() self.log(logs) metrics = None if self.control.should_evaluate: metrics = self.evaluate() self._report_to_hp_search(trial, epoch, metrics) if self.control.should_save: self._save_checkpoint(model, trial, metrics=metrics) self.control = self.callback_handler.on_save(self.args, self.state, self.control) def _load_rng_state(self, checkpoint): # Load RNG states from `checkpoint` if checkpoint is None: return local_rank = xm.get_local_ordinal() if is_torch_tpu_available() else self.args.local_rank if local_rank != -1: rng_file = os.path.join(checkpoint, f"rng_state_{local_rank}.pth") if not os.path.isfile(os.path.join(checkpoint, rng_file)): logger.info( f"Didn't find an RNG file for process {local_rank}, if you are resuming a training that " "wasn't launched in a distributed fashion, reproducibility is not guaranteed." ) return else: rng_file = os.path.join(checkpoint, "rng_state.pth") if not os.path.isfile(os.path.join(checkpoint, rng_file)): logger.info( "Didn't find an RNG file, if you are resuming a training that was launched in a distributed " "fashion, reproducibility is not guaranteed." ) return checkpoint_rng_state = torch.load(rng_file) random.setstate(checkpoint_rng_state["python"]) np.random.set_state(checkpoint_rng_state["numpy"]) torch.random.set_rng_state(checkpoint_rng_state["cpu"]) if torch.cuda.is_available(): if self.args.local_rank != -1: torch.cuda.random.set_rng_state(checkpoint_rng_state["cuda"]) else: torch.cuda.random.set_rng_state_all(checkpoint_rng_state["cuda"]) if is_torch_tpu_available(): xm.set_rng_state(checkpoint_rng_state["xla"]) def _save_checkpoint(self, model, trial, metrics=None): # In all cases, including ddp/dp/deepspeed, self.model is always a reference to the model we # want to save except FullyShardedDDP. # assert unwrap_model(model) is self.model, "internal model should be a reference to self.model" # Save model checkpoint checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}" if self.hp_search_backend is not None and trial is not None: if self.hp_search_backend == HPSearchBackend.OPTUNA: run_id = trial.number else: from ray import tune run_id = tune.get_trial_id() run_name = self.hp_name(trial) if self.hp_name is not None else f"run-{run_id}" run_dir = os.path.join(self.args.output_dir, run_name) else: run_dir = self.args.output_dir self.store_flos() output_dir = os.path.join(run_dir, checkpoint_folder) self.save_model(output_dir) if self.deepspeed: # under zero3 model file itself doesn't get saved since it's bogus! Unless deepspeed # config `stage3_gather_fp16_weights_on_model_save` is True self.deepspeed.save_checkpoint(output_dir) # Save optimizer and scheduler if self.sharded_ddp == ShardedDDPOption.SIMPLE: self.optimizer.consolidate_state_dict() if is_torch_tpu_available(): xm.rendezvous("saving_optimizer_states") xm.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt")) with warnings.catch_warnings(record=True) as caught_warnings: xm.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) reissue_pt_warnings(caught_warnings) elif is_sagemaker_mp_enabled(): if smp.dp_rank() == 0: # Consolidate the state dict on all processed of dp_rank 0 opt_state_dict = self.optimizer.state_dict() # Save it and the scheduler on the main process if self.is_world_process_zero(): torch.save(opt_state_dict, os.path.join(output_dir, "optimizer.pt")) with warnings.catch_warnings(record=True) as caught_warnings: torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) reissue_pt_warnings(caught_warnings) if self.use_amp: torch.save(self.scaler.state_dict(), os.path.join(output_dir, "scaler.pt")) elif self.is_world_process_zero() and not self.deepspeed: # deepspeed.save_checkpoint above saves model/optim/sched torch.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt")) with warnings.catch_warnings(record=True) as caught_warnings: torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) reissue_pt_warnings(caught_warnings) if self.use_amp: torch.save(self.scaler.state_dict(), os.path.join(output_dir, "scaler.pt")) # Determine the new best metric / best model checkpoint if metrics is not None and self.args.metric_for_best_model is not None: metric_to_check = self.args.metric_for_best_model if not metric_to_check.startswith("eval_"): metric_to_check = f"eval_{metric_to_check}" metric_value = metrics[metric_to_check] operator = np.greater if self.args.greater_is_better else np.less if ( self.state.best_metric is None or self.state.best_model_checkpoint is None or operator(metric_value, self.state.best_metric) ): self.state.best_metric = metric_value self.state.best_model_checkpoint = output_dir # Save the Trainer state if self.is_world_process_zero(): self.state.save_to_json(os.path.join(output_dir, "trainer_state.json")) # Save RNG state in non-distributed training rng_states = { "python": random.getstate(), "numpy": np.random.get_state(), "cpu": torch.random.get_rng_state(), } if torch.cuda.is_available(): if self.args.local_rank == -1: # In non distributed, we save the global CUDA RNG state (will take care of DataParallel) rng_states["cuda"] = torch.cuda.random.get_rng_state_all() else: rng_states["cuda"] = torch.cuda.random.get_rng_state() if is_torch_tpu_available(): rng_states["xla"] = xm.get_rng_state() # A process can arrive here before the process 0 has a chance to save the model, in which case output_dir may # not yet exist. os.makedirs(output_dir, exist_ok=True) local_rank = xm.get_local_ordinal() if is_torch_tpu_available() else self.args.local_rank if local_rank == -1: torch.save(rng_states, os.path.join(output_dir, "rng_state.pth")) else: torch.save(rng_states, os.path.join(output_dir, f"rng_state_{local_rank}.pth")) # Maybe delete some older checkpoints. if self.is_world_process_zero(): self._rotate_checkpoints(use_mtime=True, output_dir=run_dir) def _load_optimizer_and_scheduler(self, checkpoint): """If optimizer and scheduler states exist, load them.""" if checkpoint is None: return if self.deepspeed: # deepspeed loads optimizer/lr_scheduler together with the model in deepspeed_init return if os.path.isfile(os.path.join(checkpoint, "optimizer.pt")) and os.path.isfile( os.path.join(checkpoint, "scheduler.pt") ): # Load in optimizer and scheduler states if is_torch_tpu_available(): # On TPU we have to take some extra precautions to properly load the states on the right device. optimizer_state = torch.load(os.path.join(checkpoint, "optimizer.pt"), map_location="cpu") with warnings.catch_warnings(record=True) as caught_warnings: lr_scheduler_state = torch.load(os.path.join(checkpoint, "scheduler.pt"), map_location="cpu") reissue_pt_warnings(caught_warnings) xm.send_cpu_data_to_device(optimizer_state, self.args.device) xm.send_cpu_data_to_device(lr_scheduler_state, self.args.device) self.optimizer.load_state_dict(optimizer_state) self.lr_scheduler.load_state_dict(lr_scheduler_state) else: map_location = "cpu" if is_sagemaker_mp_enabled() else self.args.device self.optimizer.load_state_dict( torch.load(os.path.join(checkpoint, "optimizer.pt"), map_location=map_location) ) with warnings.catch_warnings(record=True) as caught_warnings: self.lr_scheduler.load_state_dict(torch.load(os.path.join(checkpoint, "scheduler.pt"))) reissue_pt_warnings(caught_warnings) if self.use_amp and os.path.isfile(os.path.join(checkpoint, "scaler.pt")): self.scaler.load_state_dict(torch.load(os.path.join(checkpoint, "scaler.pt"))) def hyperparameter_search( self, hp_space: Optional[Callable[["optuna.Trial"], Dict[str, float]]] = None, compute_objective: Optional[Callable[[Dict[str, float]], float]] = None, n_trials: int = 20, direction: str = "minimize", backend: Optional[Union["str", HPSearchBackend]] = None, hp_name: Optional[Callable[["optuna.Trial"], str]] = None, **kwargs, ) -> BestRun: """ Launch an hyperparameter search using ``optuna`` or ``Ray Tune``. The optimized quantity is determined by :obj:`compute_objective`, which defaults to a function returning the evaluation loss when no metric is provided, the sum of all metrics otherwise. .. warning:: To use this method, you need to have provided a ``model_init`` when initializing your :class:`~transformers.Trainer`: we need to reinitialize the model at each new run. This is incompatible with the ``optimizers`` argument, so you need to subclass :class:`~transformers.Trainer` and override the method :meth:`~transformers.Trainer.create_optimizer_and_scheduler` for custom optimizer/scheduler. Args: hp_space (:obj:`Callable[["optuna.Trial"], Dict[str, float]]`, `optional`): A function that defines the hyperparameter search space. Will default to :func:`~transformers.trainer_utils.default_hp_space_optuna` or :func:`~transformers.trainer_utils.default_hp_space_ray` depending on your backend. compute_objective (:obj:`Callable[[Dict[str, float]], float]`, `optional`): A function computing the objective to minimize or maximize from the metrics returned by the :obj:`evaluate` method. Will default to :func:`~transformers.trainer_utils.default_compute_objective`. n_trials (:obj:`int`, `optional`, defaults to 100): The number of trial runs to test. direction(:obj:`str`, `optional`, defaults to :obj:`"minimize"`): Whether to optimize greater or lower objects. Can be :obj:`"minimize"` or :obj:`"maximize"`, you should pick :obj:`"minimize"` when optimizing the validation loss, :obj:`"maximize"` when optimizing one or several metrics. backend(:obj:`str` or :class:`~transformers.training_utils.HPSearchBackend`, `optional`): The backend to use for hyperparameter search. Will default to optuna or Ray Tune, depending on which one is installed. If both are installed, will default to optuna. kwargs: Additional keyword arguments passed along to :obj:`optuna.create_study` or :obj:`ray.tune.run`. For more information see: - the documentation of `optuna.create_study <https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.create_study.html>`__ - the documentation of `tune.run <https://docs.ray.io/en/latest/tune/api_docs/execution.html#tune-run>`__ Returns: :class:`transformers.trainer_utils.BestRun`: All the information about the best run. """ if backend is None: backend = default_hp_search_backend() if backend is None: raise RuntimeError( "At least one of optuna or ray should be installed. " "To install optuna run `pip install optuna`." "To install ray run `pip install ray[tune]`." ) backend = HPSearchBackend(backend) if backend == HPSearchBackend.OPTUNA and not is_optuna_available(): raise RuntimeError("You picked the optuna backend, but it is not installed. Use `pip install optuna`.") if backend == HPSearchBackend.RAY and not is_ray_tune_available(): raise RuntimeError( "You picked the Ray Tune backend, but it is not installed. Use `pip install 'ray[tune]'`." ) self.hp_search_backend = backend if self.model_init is None: raise RuntimeError( "To use hyperparameter search, you need to pass your model through a model_init function." ) self.hp_space = default_hp_space[backend] if hp_space is None else hp_space self.hp_name = hp_name self.compute_objective = default_compute_objective if compute_objective is None else compute_objective run_hp_search = run_hp_search_optuna if backend == HPSearchBackend.OPTUNA else run_hp_search_ray best_run = run_hp_search(self, n_trials, direction, **kwargs) self.hp_search_backend = None return best_run def log(self, logs: Dict[str, float]) -> None: """ Log :obj:`logs` on the various objects watching training. Subclass and override this method to inject custom behavior. Args: logs (:obj:`Dict[str, float]`): The values to log. """ if self.state.epoch is not None: logs["epoch"] = round(self.state.epoch, 2) output = {**logs, **{"step": self.state.global_step}} self.state.log_history.append(output) self.control = self.callback_handler.on_log(self.args, self.state, self.control, logs) def _prepare_inputs(self, inputs: Dict[str, Union[torch.Tensor, Any]]) -> Dict[str, Union[torch.Tensor, Any]]: """ Prepare :obj:`inputs` before feeding them to the model, converting them to tensors if they are not already and handling potential state. """ for k, v in inputs.items(): if isinstance(v, torch.Tensor): kwargs = dict(device=self.args.device) if self.deepspeed and inputs[k].dtype != torch.int64: # NLP models inputs are int64 and those get adjusted to the right dtype of the # embedding. Other models such as wav2vec2's inputs are already float and thus # may need special handling to match the dtypes of the model kwargs.update(dict(dtype=self.args.hf_deepspeed_config.dtype())) inputs[k] = v.to(**kwargs) if self.args.past_index >= 0 and self._past is not None: inputs["mems"] = self._past return inputs def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor: """ Perform a training step on a batch of inputs. Subclass and override to inject custom behavior. Args: model (:obj:`nn.Module`): The model to train. inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model. The dictionary will be unpacked before being fed to the model. Most models expect the targets under the argument :obj:`labels`. Check your model's documentation for all accepted arguments. Return: :obj:`torch.Tensor`: The tensor with training loss on this batch. """ model.train() inputs = self._prepare_inputs(inputs) if is_sagemaker_mp_enabled(): scaler = self.scaler if self.use_amp else None loss_mb = smp_forward_backward(model, inputs, self.args.gradient_accumulation_steps, scaler=scaler) return loss_mb.reduce_mean().detach().to(self.args.device) if self.use_amp: with autocast(): loss = self.compute_loss(model, inputs) else: loss = self.compute_loss(model, inputs) if self.args.n_gpu > 1: loss = loss.mean() # mean() to average on multi-gpu parallel training if self.args.gradient_accumulation_steps > 1 and not self.deepspeed: # deepspeed handles loss scaling by gradient_accumulation_steps in its `backward` loss = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(loss).backward() elif self.use_apex: with amp.scale_loss(loss, self.optimizer) as scaled_loss: scaled_loss.backward() elif self.deepspeed: # loss gets scaled under gradient_accumulation_steps in deepspeed loss = self.deepspeed.backward(loss) else: loss.backward() return loss.detach() def compute_loss(self, model, inputs, return_outputs=False): """ How the loss is computed by Trainer. By default, all models return the loss in the first element. Subclass and override for custom behavior. """ if self.label_smoother is not None and "labels" in inputs: labels = inputs.pop("labels") else: labels = None outputs = model(**inputs) # Save past state if it exists # TODO: this needs to be fixed and made cleaner later. if self.args.past_index >= 0: self._past = outputs[self.args.past_index] if labels is not None: loss = self.label_smoother(outputs, labels) else: # We don't use .loss here since the model may return tuples instead of ModelOutput. loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0] return (loss, outputs) if return_outputs else loss def is_local_process_zero(self) -> bool: """ Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on several machines) main process. """ return self.args.local_process_index == 0 def is_world_process_zero(self) -> bool: """ Whether or not this process is the global main process (when training in a distributed fashion on several machines, this is only going to be :obj:`True` for one process). """ # Special case for SageMaker ModelParallel since there process_index is dp_process_index, not the global # process index. if is_sagemaker_mp_enabled(): return smp.rank() == 0 else: return self.args.process_index == 0 def save_model(self, output_dir: Optional[str] = None): """ Will save the model, so you can reload it using :obj:`from_pretrained()`. Will only save from the main process. """ if output_dir is None: output_dir = self.args.output_dir if is_torch_tpu_available(): self._save_tpu(output_dir) elif is_sagemaker_mp_enabled(): # Calling the state_dict needs to be done on the wrapped model and on all processes. state_dict = self.model_wrapped.state_dict() if self.is_world_process_zero(): self._save(output_dir, state_dict=state_dict) elif ( ShardedDDPOption.ZERO_DP_2 in self.args.sharded_ddp or ShardedDDPOption.ZERO_DP_3 in self.args.sharded_ddp ): state_dict = self.model.state_dict() if self.is_world_process_zero(): self._save(output_dir, state_dict=state_dict) elif self.deepspeed: # this takes care of everything as long as we aren't under zero3 if self.is_world_process_zero(): self._save(output_dir) if is_deepspeed_zero3_enabled(): # It's too complicated to try to override different places where the weights dump gets # saved, so since under zero3 the file is bogus, simply delete it. The user should # either user deepspeed checkpoint to resume or to recover full weights use # zero_to_fp32.py stored in the checkpoint. if self.is_world_process_zero(): file = os.path.join(output_dir, WEIGHTS_NAME) if os.path.isfile(file): # logger.info(f"deepspeed zero3: removing {file}, see zero_to_fp32.py to recover weights") os.remove(file) # now save the real model if stage3_gather_fp16_weights_on_model_save=True # if false it will not be saved. # This must be called on all ranks self.deepspeed.save_fp16_model(output_dir, WEIGHTS_NAME) elif self.is_world_process_zero(): self._save(output_dir) def _save_tpu(self, output_dir: Optional[str] = None): output_dir = output_dir if output_dir is not None else self.args.output_dir logger.info(f"Saving model checkpoint to {output_dir}") if xm.is_master_ordinal(): os.makedirs(output_dir, exist_ok=True) torch.save(self.args, os.path.join(output_dir, "training_args.bin")) # Save a trained model and configuration using `save_pretrained()`. # They can then be reloaded using `from_pretrained()` xm.rendezvous("saving_checkpoint") if not isinstance(self.model, PreTrainedModel): if isinstance(unwrap_model(self.model), PreTrainedModel): unwrap_model(self.model).save_pretrained( output_dir, save_config=self.is_world_process_zero(), state_dict=self.model.state_dict(), save_function=xm.save, ) else: logger.info("Trainer.model is not a `PreTrainedModel`, only saving its state dict.") state_dict = self.model.state_dict() xm.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME)) else: self.model.save_pretrained(output_dir, save_config=self.is_world_process_zero(), save_function=xm.save) if self.tokenizer is not None and self.is_world_process_zero(): self.tokenizer.save_pretrained(output_dir) def _save(self, output_dir: Optional[str] = None, state_dict=None): # If we are executing this function, we are the process zero, so we don't check for that. output_dir = output_dir if output_dir is not None else self.args.output_dir os.makedirs(output_dir, exist_ok=True) logger.info(f"Saving model checkpoint to {output_dir}") # Save a trained model and configuration using `save_pretrained()`. # They can then be reloaded using `from_pretrained()` if not isinstance(self.model, PreTrainedModel): if isinstance(unwrap_model(self.model), PreTrainedModel): if state_dict is None: state_dict = self.model.state_dict() unwrap_model(self.model).save_pretrained(output_dir, state_dict=state_dict) else: logger.info("Trainer.model is not a `PreTrainedModel`, only saving its state dict.") if state_dict is None: state_dict = self.model.state_dict() torch.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME)) else: self.model.save_pretrained(output_dir, state_dict=state_dict) if self.tokenizer is not None: self.tokenizer.save_pretrained(output_dir) # Good practice: save your training arguments together with the trained model torch.save(self.args, os.path.join(output_dir, "training_args.bin")) def store_flos(self): # Storing the number of floating-point operations that went into the model if self.args.local_rank != -1: self.state.total_flos += distributed_broadcast_scalars([self.current_flos]).sum().item() self.current_flos = 0 else: self.state.total_flos += self.current_flos self.current_flos = 0 def _sorted_checkpoints( self, output_dir=None, checkpoint_prefix=PREFIX_CHECKPOINT_DIR, use_mtime=False ) -> List[str]: ordering_and_checkpoint_path = [] glob_checkpoints = [str(x) for x in Path(output_dir).glob(f"{checkpoint_prefix}-*")] for path in glob_checkpoints: if use_mtime: ordering_and_checkpoint_path.append((os.path.getmtime(path), path)) else: regex_match = re.match(f".*{checkpoint_prefix}-([0-9]+)", path) if regex_match is not None and regex_match.groups() is not None: ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path)) checkpoints_sorted = sorted(ordering_and_checkpoint_path) checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted] # Make sure we don't delete the best model. if self.state.best_model_checkpoint is not None: best_model_index = checkpoints_sorted.index(str(Path(self.state.best_model_checkpoint))) for i in range(best_model_index, len(checkpoints_sorted) - 2): checkpoints_sorted[i], checkpoints_sorted[i + 1] = checkpoints_sorted[i + 1], checkpoints_sorted[i] return checkpoints_sorted def _rotate_checkpoints(self, use_mtime=False, output_dir=None) -> None: if self.args.save_total_limit is None or self.args.save_total_limit <= 0: return # Check if we should delete older checkpoint(s) checkpoints_sorted = self._sorted_checkpoints(use_mtime=use_mtime, output_dir=output_dir) if len(checkpoints_sorted) <= self.args.save_total_limit: return # If save_total_limit=1 with load_best_mode_at_end=True, we could end up deleting the last checkpoint, which # we don't do to allow resuming. save_total_limit = self.args.save_total_limit if ( self.state.best_model_checkpoint is not None and self.args.save_total_limit == 1 and checkpoints_sorted[-1] != self.state.best_model_checkpoint ): save_total_limit = 2 number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - save_total_limit) checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete] for checkpoint in checkpoints_to_be_deleted: logger.info(f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit") shutil.rmtree(checkpoint) def evaluate( self, eval_dataset: Optional[Dataset] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", ) -> Dict[str, float]: """ Run evaluation and returns metrics. The calling script will be responsible for providing a method to compute metrics, as they are task-dependent (pass it to the init :obj:`compute_metrics` argument). You can also subclass and override this method to inject custom behavior. Args: eval_dataset (:obj:`Dataset`, `optional`): Pass a dataset if you wish to override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`, columns not accepted by the ``model.forward()`` method are automatically removed. It must implement the :obj:`__len__` method. ignore_keys (:obj:`Lst[str]`, `optional`): A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions. metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`"eval"`): An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named "eval_bleu" if the prefix is "eval" (default) Returns: A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The dictionary also contains the epoch number which comes from the training state. """ # memory metrics - must set up as early as possible self._memory_tracker.start() eval_dataloader = self.get_eval_dataloader(eval_dataset) start_time = time.time() eval_loop = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop output = eval_loop( eval_dataloader, description="Evaluation", # No point gathering the predictions if there are no metrics, otherwise we defer to # self.args.prediction_loss_only prediction_loss_only=True if self.compute_metrics is None else None, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix, ) total_batch_size = self.args.eval_batch_size * self.args.world_size output.metrics.update( speed_metrics( metric_key_prefix, start_time, num_samples=output.num_samples, num_steps=math.ceil(output.num_samples / total_batch_size), ) ) self.log(output.metrics) if DebugOption.TPU_METRICS_DEBUG in self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report()) self.control = self.callback_handler.on_evaluate(self.args, self.state, self.control, output.metrics) self._memory_tracker.stop_and_update_metrics(output.metrics) return output.metrics def predict( self, test_dataset: Dataset, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "test" ) -> PredictionOutput: """ Run prediction and returns predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method will also return metrics, like in :obj:`evaluate()`. Args: test_dataset (:obj:`Dataset`): Dataset to run the predictions on. If it is an :obj:`datasets.Dataset`, columns not accepted by the ``model.forward()`` method are automatically removed. Has to implement the method :obj:`__len__` ignore_keys (:obj:`Lst[str]`, `optional`): A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions. metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`"test"`): An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named "test_bleu" if the prefix is "test" (default) .. note:: If your predictions or labels have different sequence length (for instance because you're doing dynamic padding in a token classification task) the predictions will be padded (on the right) to allow for concatenation into one array. The padding index is -100. Returns: `NamedTuple` A namedtuple with the following keys: - predictions (:obj:`np.ndarray`): The predictions on :obj:`test_dataset`. - label_ids (:obj:`np.ndarray`, `optional`): The labels (if the dataset contained some). - metrics (:obj:`Dict[str, float]`, `optional`): The potential dictionary of metrics (if the dataset contained labels). """ # memory metrics - must set up as early as possible self._memory_tracker.start() test_dataloader = self.get_test_dataloader(test_dataset) start_time = time.time() eval_loop = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop output = eval_loop( test_dataloader, description="Prediction", ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix ) total_batch_size = self.args.eval_batch_size * self.args.world_size output.metrics.update( speed_metrics( metric_key_prefix, start_time, num_samples=output.num_samples, num_steps=math.ceil(output.num_samples / total_batch_size), ) ) self._memory_tracker.stop_and_update_metrics(output.metrics) return PredictionOutput(predictions=output.predictions, label_ids=output.label_ids, metrics=output.metrics) def evaluation_loop( self, dataloader: DataLoader, description: str, prediction_loss_only: Optional[bool] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", ) -> EvalLoopOutput: """ Prediction/evaluation loop, shared by :obj:`Trainer.evaluate()` and :obj:`Trainer.predict()`. Works both with or without labels. """ prediction_loss_only = ( prediction_loss_only if prediction_loss_only is not None else self.args.prediction_loss_only ) # if eval is called w/o train init deepspeed here if self.args.deepspeed and not self.deepspeed: # XXX: eval doesn't have `resume_from_checkpoint` arg but we should be able to do eval # from the checkpoint eventually deepspeed_engine, _, _ = deepspeed_init(self, num_training_steps=0, resume_from_checkpoint=None) self.model = deepspeed_engine.module self.model_wrapped = deepspeed_engine self.deepspeed = deepspeed_engine # XXX: we don't need optim/sched for inference, but this needs to be sorted out, since # for example the Z3-optimizer is a must for zero3 to work even for inference - what we # don't need is the deepspeed basic optimizer which is self.optimizer.optimizer deepspeed_engine.optimizer.optimizer = None deepspeed_engine.lr_scheduler = None model = self._wrap_model(self.model, training=False) # if full fp16 is wanted on eval and this ``evaluation`` or ``predict`` isn't called while # ``train`` is running, halve it first and then put on device if not self.is_in_train and self.args.fp16_full_eval: model = model.half().to(self.args.device) batch_size = dataloader.batch_size logger.info(f"***** Running {description} *****") if isinstance(dataloader.dataset, collections.abc.Sized): logger.info(f" Num examples = {self.num_examples(dataloader)}") else: logger.info(" Num examples: Unknown") logger.info(f" Batch size = {batch_size}") model.eval() self.callback_handler.eval_dataloader = dataloader # Do this before wrapping. eval_dataset = dataloader.dataset if is_torch_tpu_available(): dataloader = pl.ParallelLoader(dataloader, [self.args.device]).per_device_loader(self.args.device) if self.args.past_index >= 0: self._past = None # Initialize containers # losses/preds/labels on GPU/TPU (accumulated for eval_accumulation_steps) losses_host = None preds_host = None labels_host = None # losses/preds/labels on CPU (final containers) all_losses = None all_preds = None all_labels = None # Will be useful when we have an iterable dataset so don't know its length. observed_num_examples = 0 # Main evaluation loop for step, inputs in enumerate(dataloader): # Update the observed num examples observed_batch_size = find_batch_size(inputs) if observed_batch_size is not None: observed_num_examples += observed_batch_size # Prediction step loss, logits, labels = self.prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys) # Update containers on host if loss is not None: losses = self._nested_gather(loss.repeat(batch_size)) losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0) if logits is not None: logits = self._pad_across_processes(logits) logits = self._nested_gather(logits) preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100) if labels is not None: labels = self._pad_across_processes(labels) labels = self._nested_gather(labels) labels_host = labels if labels_host is None else nested_concat(labels_host, labels, padding_index=-100) self.control = self.callback_handler.on_prediction_step(self.args, self.state, self.control) # Gather all tensors and put them back on the CPU if we have done enough accumulation steps. if self.args.eval_accumulation_steps is not None and (step + 1) % self.args.eval_accumulation_steps == 0: if losses_host is not None: losses = nested_numpify(losses_host) all_losses = losses if all_losses is None else np.concatenate((all_losses, losses), axis=0) if preds_host is not None: logits = nested_numpify(preds_host) all_preds = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100) if labels_host is not None: labels = nested_numpify(labels_host) all_labels = ( labels if all_labels is None else nested_concat(all_labels, labels, padding_index=-100) ) # Set back to None to begin a new accumulation losses_host, preds_host, labels_host = None, None, None if self.args.past_index and hasattr(self, "_past"): # Clean the state at the end of the evaluation loop delattr(self, "_past") # Gather all remaining tensors and put them back on the CPU if losses_host is not None: losses = nested_numpify(losses_host) all_losses = losses if all_losses is None else np.concatenate((all_losses, losses), axis=0) if preds_host is not None: logits = nested_numpify(preds_host) all_preds = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100) if labels_host is not None: labels = nested_numpify(labels_host) all_labels = labels if all_labels is None else nested_concat(all_labels, labels, padding_index=-100) # Number of samples if not isinstance(eval_dataset, IterableDataset): num_samples = len(eval_dataset) elif isinstance(eval_dataset, IterableDatasetShard): num_samples = eval_dataset.num_examples else: num_samples = observed_num_examples # Number of losses has been rounded to a multiple of batch_size and in a distributed training, the number of # samplers has been rounded to a multiple of batch_size, so we truncate. if all_losses is not None: all_losses = all_losses[:num_samples] if all_preds is not None: all_preds = nested_truncate(all_preds, num_samples) if all_labels is not None: all_labels = nested_truncate(all_labels, num_samples) # Metrics! if self.compute_metrics is not None and all_preds is not None and all_labels is not None: metrics = self.compute_metrics(EvalPrediction(predictions=all_preds, label_ids=all_labels)) else: metrics = {} # To be JSON-serializable, we need to remove numpy types or zero-d tensors metrics = denumpify_detensorize(metrics) if all_losses is not None: metrics[f"{metric_key_prefix}_loss"] = all_losses.mean().item() # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f"{metric_key_prefix}_"): metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key) return EvalLoopOutput(predictions=all_preds, label_ids=all_labels, metrics=metrics, num_samples=num_samples) def _nested_gather(self, tensors, name=None): """ Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before concatenating them to `gathered` """ if tensors is None: return if is_torch_tpu_available(): if name is None: name = "nested_gather" tensors = nested_xla_mesh_reduce(tensors, name) elif is_sagemaker_mp_enabled(): tensors = smp_gather(tensors) elif self.args.local_rank != -1: tensors = distributed_concat(tensors) return tensors # Copied from Accelerate. def _pad_across_processes(self, tensor, pad_index=-100): """ Recursively pad the tensors in a nested list/tuple/dictionary of tensors from all devices to the same size so they can safely be gathered. """ if isinstance(tensor, (list, tuple)): return type(tensor)(self._pad_across_processes(t, pad_index=pad_index) for t in tensor) elif isinstance(tensor, dict): return type(tensor)({k: self._pad_across_processes(v, pad_index=pad_index) for k, v in tensor.items()}) elif not isinstance(tensor, torch.Tensor): raise TypeError( f"Can't pad the values of type {type(tensor)}, only of nested list/tuple/dicts of tensors." ) if len(tensor.shape) < 2: return tensor # Gather all sizes size = torch.tensor(tensor.shape, device=tensor.device)[None] sizes = self._nested_gather(size).cpu() max_size = max(s[1] for s in sizes) if tensor.shape[1] == max_size: return tensor # Then pad to the maximum size old_size = tensor.shape new_size = list(old_size) new_size[1] = max_size new_tensor = tensor.new_zeros(tuple(new_size)) + pad_index new_tensor[:, : old_size[1]] = tensor return new_tensor def prediction_step( self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]], prediction_loss_only: bool, ignore_keys: Optional[List[str]] = None, ) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]: """ Perform an evaluation step on :obj:`model` using obj:`inputs`. Subclass and override to inject custom behavior. Args: model (:obj:`nn.Module`): The model to evaluate. inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model. The dictionary will be unpacked before being fed to the model. Most models expect the targets under the argument :obj:`labels`. Check your model's documentation for all accepted arguments. prediction_loss_only (:obj:`bool`): Whether or not to return the loss only. ignore_keys (:obj:`Lst[str]`, `optional`): A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions. Return: Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]: A tuple with the loss, logits and labels (each being optional). """ has_labels = all(inputs.get(k) is not None for k in self.label_names) inputs = self._prepare_inputs(inputs) if ignore_keys is None: if hasattr(self.model, "config"): ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", []) else: ignore_keys = [] # labels may be popped when computing the loss (label smoothing for instance) so we grab them first. if has_labels: labels = nested_detach(tuple(inputs.get(name) for name in self.label_names)) if len(labels) == 1: labels = labels[0] else: labels = None with torch.no_grad(): if is_sagemaker_mp_enabled(): raw_outputs = smp_forward_only(model, inputs) if has_labels: if isinstance(raw_outputs, dict): loss_mb = raw_outputs["loss"] logits_mb = tuple(v for k, v in raw_outputs.items() if k not in ignore_keys + ["loss"]) else: loss_mb = raw_outputs[0] logits_mb = raw_outputs[1:] loss = loss_mb.reduce_mean().detach().cpu() logits = smp_nested_concat(logits_mb) else: loss = None if isinstance(raw_outputs, dict): logits_mb = tuple(v for k, v in raw_outputs.items() if k not in ignore_keys) else: logits_mb = raw_outputs logits = smp_nested_concat(logits_mb) else: if has_labels: loss, outputs = self.compute_loss(model, inputs, return_outputs=True) loss = loss.mean().detach() if isinstance(outputs, dict): logits = tuple(v for k, v in outputs.items() if k not in ignore_keys + ["loss"]) else: logits = outputs[1:] else: loss = None if self.use_amp: with autocast(): outputs = model(**inputs) else: outputs = model(**inputs) if isinstance(outputs, dict): logits = tuple(v for k, v in outputs.items() if k not in ignore_keys) else: logits = outputs # TODO: this needs to be fixed and made cleaner later. if self.args.past_index >= 0: self._past = outputs[self.args.past_index - 1] if prediction_loss_only: return (loss, None, None) logits = nested_detach(logits) if len(logits) == 1: logits = logits[0] return (loss, logits, labels) def floating_point_ops(self, inputs: Dict[str, Union[torch.Tensor, Any]]): """ For models that inherit from :class:`~transformers.PreTrainedModel`, uses that method to compute the number of floating point operations for every backward + forward pass. If using another model, either implement such a method in the model or subclass and override this method. Args: inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model. Returns: :obj:`int`: The number of floating-point operations. """ if hasattr(self.model, "floating_point_ops"): return self.model.floating_point_ops(inputs) else: return 0 def init_git_repo(self): """ Initializes a git repo in :obj:`self.args.push_to_hub_model_id`. """ if not self.is_world_process_zero(): return use_auth_token = True if self.args.push_to_hub_token is None else self.args.push_to_hub_token repo_url = PushToHubMixin._get_repo_url_from_name( self.args.push_to_hub_model_id, organization=self.args.push_to_hub_organization, use_auth_token=use_auth_token, ) self.repo = PushToHubMixin._create_or_get_repo( self.args.output_dir, repo_url=repo_url, use_auth_token=use_auth_token ) # By default, ignore the checkpoint folders if not os.path.exists(os.path.join(self.args.output_dir, ".gitignore")): with open(os.path.join(self.args.output_dir, ".gitignore"), "w", encoding="utf-8") as writer: writer.writelines(["checkpoint-*/"]) def create_model_card( self, language: Optional[str] = None, license: Optional[str] = None, tags: Optional[str] = None, model_name: Optional[str] = None, finetuned_from: Optional[str] = None, tasks: Optional[str] = None, dataset_tags: Optional[Union[str, List[str]]] = None, dataset: Optional[Union[str, List[str]]] = None, dataset_args: Optional[Union[str, List[str]]] = None, ): training_summary = TrainingSummary.from_trainer( self, language=language, license=license, tags=tags, model_name=model_name, finetuned_from=finetuned_from, tasks=tasks, dataset_tags=dataset_tags, dataset=dataset, dataset_args=dataset_args, ) model_card = training_summary.to_model_card() with open(os.path.join(self.args.output_dir, "README.md"), "w") as f: f.write(model_card) def push_to_hub(self, commit_message: Optional[str] = "add model", **kwargs) -> str: """ Upload `self.model` and `self.tokenizer` to the 🤗 model hub on the repo `self.args.push_to_hub_model_id`. Parameters: commit_message (:obj:`str`, `optional`, defaults to :obj:`"add model"`): Message to commit while pushing. kwargs: Additional keyword arguments passed along to :meth:`~transformers.Trainer.create_model_card`. Returns: The url of the commit of your model in the given repository. """ if not self.is_world_process_zero(): return self.create_model_card(model_name=self.args.push_to_hub_model_id, **kwargs) self.save_model() return self.repo.push_to_hub(commit_message=commit_message) # # Deprecated code # def prediction_loop( self, dataloader: DataLoader, description: str, prediction_loss_only: Optional[bool] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", ) -> PredictionOutput: """ Prediction/evaluation loop, shared by :obj:`Trainer.evaluate()` and :obj:`Trainer.predict()`. Works both with or without labels. """ if not isinstance(dataloader.dataset, collections.abc.Sized): raise ValueError("dataset must implement __len__") prediction_loss_only = ( prediction_loss_only if prediction_loss_only is not None else self.args.prediction_loss_only ) # if eval is called w/o train init deepspeed here if self.args.deepspeed and not self.deepspeed: # XXX: eval doesn't have `resume_from_checkpoint` arg but we should be able to do eval # from the checkpoint eventually deepspeed_engine, _, _ = deepspeed_init(self, num_training_steps=0, resume_from_checkpoint=None) self.model = deepspeed_engine.module self.model_wrapped = deepspeed_engine self.deepspeed = deepspeed_engine # XXX: we don't need optim/sched for inference, but this needs to be sorted out, since # for example the Z3-optimizer is a must for zero3 to work even for inference - what we # don't need is the deepspeed basic optimizer which is self.optimizer.optimizer deepspeed_engine.optimizer.optimizer = None deepspeed_engine.lr_scheduler = None model = self._wrap_model(self.model, training=False) # if full fp16 is wanted on eval and this ``evaluation`` or ``predict`` isn't called while # ``train`` is running, halve it first and then put on device if not self.is_in_train and self.args.fp16_full_eval: model = model.half().to(self.args.device) batch_size = dataloader.batch_size num_examples = self.num_examples(dataloader) logger.info(f"***** Running {description} *****") logger.info(f" Num examples = {num_examples}") logger.info(f" Batch size = {batch_size}") losses_host: torch.Tensor = None preds_host: Union[torch.Tensor, List[torch.Tensor]] = None labels_host: Union[torch.Tensor, List[torch.Tensor]] = None world_size = max(1, self.args.world_size) eval_losses_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=batch_size) if not prediction_loss_only: # The actual number of eval_sample can be greater than num_examples in distributed settings (when we pass # a batch size to the sampler) make_multiple_of = None if hasattr(dataloader, "sampler") and isinstance(dataloader.sampler, SequentialDistributedSampler): make_multiple_of = dataloader.sampler.batch_size preds_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=make_multiple_of) labels_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=make_multiple_of) model.eval() if is_torch_tpu_available(): dataloader = pl.ParallelLoader(dataloader, [self.args.device]).per_device_loader(self.args.device) if self.args.past_index >= 0: self._past = None self.callback_handler.eval_dataloader = dataloader for step, inputs in enumerate(dataloader): loss, logits, labels = self.prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys) if loss is not None: losses = loss.repeat(batch_size) losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0) if logits is not None: preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100) if labels is not None: labels_host = labels if labels_host is None else nested_concat(labels_host, labels, padding_index=-100) self.control = self.callback_handler.on_prediction_step(self.args, self.state, self.control) # Gather all tensors and put them back on the CPU if we have done enough accumulation steps. if self.args.eval_accumulation_steps is not None and (step + 1) % self.args.eval_accumulation_steps == 0: eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, "eval_losses")) if not prediction_loss_only: preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, "eval_preds")) labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, "eval_label_ids")) # Set back to None to begin a new accumulation losses_host, preds_host, labels_host = None, None, None if self.args.past_index and hasattr(self, "_past"): # Clean the state at the end of the evaluation loop delattr(self, "_past") # Gather all remaining tensors and put them back on the CPU eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, "eval_losses")) if not prediction_loss_only: preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, "eval_preds")) labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, "eval_label_ids")) eval_loss = eval_losses_gatherer.finalize() preds = preds_gatherer.finalize() if not prediction_loss_only else None label_ids = labels_gatherer.finalize() if not prediction_loss_only else None if self.compute_metrics is not None and preds is not None and label_ids is not None: metrics = self.compute_metrics(EvalPrediction(predictions=preds, label_ids=label_ids)) else: metrics = {} # To be JSON-serializable, we need to remove numpy types or zero-d tensors metrics = denumpify_detensorize(metrics) if eval_loss is not None: metrics[f"{metric_key_prefix}_loss"] = eval_loss.mean().item() # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f"{metric_key_prefix}_"): metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key) return PredictionOutput(predictions=preds, label_ids=label_ids, metrics=metrics) def _gather_and_numpify(self, tensors, name): """ Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before concatenating them to `gathered` """ if tensors is None: return if is_torch_tpu_available(): tensors = nested_xla_mesh_reduce(tensors, name) elif is_sagemaker_mp_enabled(): tensors = smp_gather(tensors) elif self.args.local_rank != -1: tensors = distributed_concat(tensors) return nested_numpify(tensors)
# coding=utf-8 # Copyright 2020-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task. """ import collections import inspect import math import os import random import re import shutil import sys import time import warnings from logging import StreamHandler from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union from tqdm.auto import tqdm # Integrations must be imported before ML frameworks: from .integrations import ( # isort: split default_hp_search_backend, get_reporting_integration_callbacks, hp_params, is_fairscale_available, is_optuna_available, is_ray_tune_available, run_hp_search_optuna, run_hp_search_ray, ) import numpy as np import torch from packaging import version from torch import nn from torch.utils.data.dataloader import DataLoader from torch.utils.data.dataset import Dataset, IterableDataset from torch.utils.data.distributed import DistributedSampler from torch.utils.data.sampler import RandomSampler, SequentialSampler from . import __version__ from .configuration_utils import PretrainedConfig from .data.data_collator import DataCollator, DataCollatorWithPadding, default_data_collator from .debug_utils import DebugOption, DebugUnderflowOverflow from .deepspeed import deepspeed_init, is_deepspeed_zero3_enabled from .dependency_versions_check import dep_version_check from .file_utils import ( CONFIG_NAME, WEIGHTS_NAME, PushToHubMixin, is_apex_available, is_datasets_available, is_in_notebook, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_torch_tpu_available, is_training_run_on_sagemaker, ) from .modelcard import TrainingSummary from .modeling_utils import PreTrainedModel, unwrap_model from .optimization import Adafactor, AdamW, get_scheduler from .tokenization_utils_base import PreTrainedTokenizerBase from .trainer_callback import ( CallbackHandler, DefaultFlowCallback, PrinterCallback, ProgressCallback, TrainerCallback, TrainerControl, TrainerState, ) from .trainer_pt_utils import ( DistributedLengthGroupedSampler, DistributedSamplerWithLoop, DistributedTensorGatherer, IterableDatasetShard, LabelSmoother, LengthGroupedSampler, SequentialDistributedSampler, ShardSampler, distributed_broadcast_scalars, distributed_concat, find_batch_size, get_parameter_names, nested_concat, nested_detach, nested_numpify, nested_truncate, nested_xla_mesh_reduce, reissue_pt_warnings, ) from .trainer_utils import ( PREFIX_CHECKPOINT_DIR, BestRun, EvalLoopOutput, EvalPrediction, HPSearchBackend, PredictionOutput, ShardedDDPOption, TrainerMemoryTracker, TrainOutput, default_compute_objective, default_hp_space, denumpify_detensorize, get_last_checkpoint, set_seed, speed_metrics, ) from .training_args import ParallelMode, TrainingArguments from .utils import logging from .utils.modeling_auto_mapping import MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES _is_torch_generator_available = False _is_native_amp_available = False DEFAULT_CALLBACKS = [DefaultFlowCallback] DEFAULT_PROGRESS_CALLBACK = ProgressCallback if is_in_notebook(): from .utils.notebook import NotebookProgressCallback DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback if is_apex_available(): from apex import amp if version.parse(torch.__version__) >= version.parse("1.6"): _is_torch_generator_available = True _is_native_amp_available = True from torch.cuda.amp import autocast if is_datasets_available(): import datasets if is_torch_tpu_available(): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met import torch_xla.distributed.parallel_loader as pl if is_fairscale_available(): dep_version_check("fairscale") import fairscale from fairscale.nn.data_parallel import FullyShardedDataParallel as FullyShardedDDP from fairscale.nn.data_parallel import ShardedDataParallel as ShardedDDP from fairscale.nn.wrap import auto_wrap from fairscale.optim import OSS from fairscale.optim.grad_scaler import ShardedGradScaler if is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.distributed as dist from smdistributed.dataparallel.torch.parallel.distributed import DistributedDataParallel as DDP else: import torch.distributed as dist if is_sagemaker_mp_enabled(): import smdistributed.modelparallel.torch as smp from .trainer_pt_utils import smp_forward_backward, smp_forward_only, smp_gather, smp_nested_concat if is_training_run_on_sagemaker(): logging.add_handler(StreamHandler(sys.stdout)) if TYPE_CHECKING: import optuna logger = logging.get_logger(__name__) class Trainer: """ Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for 🤗 Transformers. Args: model (:class:`~transformers.PreTrainedModel` or :obj:`torch.nn.Module`, `optional`): The model to train, evaluate or use for predictions. If not provided, a ``model_init`` must be passed. .. note:: :class:`~transformers.Trainer` is optimized to work with the :class:`~transformers.PreTrainedModel` provided by the library. You can still use your own models defined as :obj:`torch.nn.Module` as long as they work the same way as the 🤗 Transformers models. args (:class:`~transformers.TrainingArguments`, `optional`): The arguments to tweak for training. Will default to a basic instance of :class:`~transformers.TrainingArguments` with the ``output_dir`` set to a directory named `tmp_trainer` in the current directory if not provided. data_collator (:obj:`DataCollator`, `optional`): The function to use to form a batch from a list of elements of :obj:`train_dataset` or :obj:`eval_dataset`. Will default to :func:`~transformers.default_data_collator` if no ``tokenizer`` is provided, an instance of :func:`~transformers.DataCollatorWithPadding` otherwise. train_dataset (:obj:`torch.utils.data.dataset.Dataset` or :obj:`torch.utils.data.dataset.IterableDataset`, `optional`): The dataset to use for training. If it is an :obj:`datasets.Dataset`, columns not accepted by the ``model.forward()`` method are automatically removed. Note that if it's a :obj:`torch.utils.data.dataset.IterableDataset` with some randomization and you are training in a distributed fashion, your iterable dataset should either use a internal attribute :obj:`generator` that is a :obj:`torch.Generator` for the randomization that must be identical on all processes (and the Trainer will manually set the seed of this :obj:`generator` at each epoch) or have a :obj:`set_epoch()` method that internally sets the seed of the RNGs used. eval_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`): The dataset to use for evaluation. If it is an :obj:`datasets.Dataset`, columns not accepted by the ``model.forward()`` method are automatically removed. tokenizer (:class:`PreTrainedTokenizerBase`, `optional`): The tokenizer used to preprocess the data. If provided, will be used to automatically pad the inputs the maximum length when batching inputs, and it will be saved along the model to make it easier to rerun an interrupted training or reuse the fine-tuned model. model_init (:obj:`Callable[[], PreTrainedModel]`, `optional`): A function that instantiates the model to be used. If provided, each call to :meth:`~transformers.Trainer.train` will start from a new instance of the model as given by this function. The function may have zero argument, or a single one containing the optuna/Ray Tune trial object, to be able to choose different architectures according to hyper parameters (such as layer count, sizes of inner layers, dropout probabilities etc). compute_metrics (:obj:`Callable[[EvalPrediction], Dict]`, `optional`): The function that will be used to compute metrics at evaluation. Must take a :class:`~transformers.EvalPrediction` and return a dictionary string to metric values. callbacks (List of :obj:`~transformers.TrainerCallback`, `optional`): A list of callbacks to customize the training loop. Will add those to the list of default callbacks detailed in :doc:`here <callback>`. If you want to remove one of the default callbacks used, use the :meth:`Trainer.remove_callback` method. optimizers (:obj:`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR`, `optional`): A tuple containing the optimizer and the scheduler to use. Will default to an instance of :class:`~transformers.AdamW` on your model and a scheduler given by :func:`~transformers.get_linear_schedule_with_warmup` controlled by :obj:`args`. Important attributes: - **model** -- Always points to the core model. If using a transformers model, it will be a :class:`~transformers.PreTrainedModel` subclass. - **model_wrapped** -- Always points to the most external model in case one or more other modules wrap the original model. This is the model that should be used for the forward pass. For example, under ``DeepSpeed``, the inner model is wrapped in ``DeepSpeed`` and then again in ``torch.nn.DistributedDataParallel``. If the inner model hasn't been wrapped, then ``self.model_wrapped`` is the same as ``self.model``. - **is_model_parallel** -- Whether or not a model has been switched to a model parallel mode (different from data parallelism, this means some of the model layers are split on different GPUs). - **place_model_on_device** -- Whether or not to automatically place the model on the device - it will be set to :obj:`False` if model parallel or deepspeed is used, or if the default ``TrainingArguments.place_model_on_device`` is overridden to return :obj:`False` . - **is_in_train** -- Whether or not a model is currently running ``train`` (e.g. when ``evaluate`` is called while in ``train``) """ from .trainer_pt_utils import _get_learning_rate, log_metrics, metrics_format, save_metrics, save_state def __init__( self, model: Union[PreTrainedModel, nn.Module] = None, args: TrainingArguments = None, data_collator: Optional[DataCollator] = None, train_dataset: Optional[Dataset] = None, eval_dataset: Optional[Dataset] = None, tokenizer: Optional[PreTrainedTokenizerBase] = None, model_init: Callable[[], PreTrainedModel] = None, compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None, callbacks: Optional[List[TrainerCallback]] = None, optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), ): if args is None: output_dir = "tmp_trainer" logger.info(f"No `TrainingArguments` passed, using `output_dir={output_dir}`.") args = TrainingArguments(output_dir=output_dir) self.args = args # Seed must be set before instantiating the model when using model set_seed(self.args.seed) self.hp_name = None self.deepspeed = None self.is_in_train = False # memory metrics - must set up as early as possible self._memory_tracker = TrainerMemoryTracker(self.args.skip_memory_metrics) self._memory_tracker.start() # set the correct log level depending on the node log_level = args.get_process_log_level() logging.set_verbosity(log_level) # force device and distributed setup init explicitly args._setup_devices if model is None: if model_init is not None: self.model_init = model_init model = self.call_model_init() else: raise RuntimeError("`Trainer` requires either a `model` or `model_init` argument") else: if model_init is not None: warnings.warn( "`Trainer` requires either a `model` or `model_init` argument, but not both. " "`model_init` will overwrite your model when calling the `train` method. This will become a fatal error in the next release.", FutureWarning, ) self.model_init = model_init if hasattr(model, "is_parallelizable") and model.is_parallelizable and model.model_parallel: self.is_model_parallel = True else: self.is_model_parallel = False # Setup Sharded DDP training self.sharded_ddp = None if len(args.sharded_ddp) > 0: if args.deepspeed: raise ValueError( "Using --sharded_ddp xxx together with --deepspeed is not possible, deactivate one of those flags." ) if args.local_rank == -1: raise ValueError("Using sharded DDP only works in distributed training.") elif not is_fairscale_available(): raise ImportError("Sharded DDP training requires fairscale: `pip install fairscale`.") elif ShardedDDPOption.SIMPLE not in args.sharded_ddp and FullyShardedDDP is None: raise ImportError( "Sharded DDP in a mode other than simple training requires fairscale version >= 0.3, found " f"{fairscale.__version__}. Upgrade your fairscale library: `pip install --upgrade fairscale`." ) elif ShardedDDPOption.SIMPLE in args.sharded_ddp: self.sharded_ddp = ShardedDDPOption.SIMPLE elif ShardedDDPOption.ZERO_DP_2 in args.sharded_ddp: self.sharded_ddp = ShardedDDPOption.ZERO_DP_2 elif ShardedDDPOption.ZERO_DP_3 in args.sharded_ddp: self.sharded_ddp = ShardedDDPOption.ZERO_DP_3 # one place to sort out whether to place the model on device or not # postpone switching model to cuda when: # 1. MP - since we are trying to fit a much bigger than 1 gpu model # 2. fp16-enabled DeepSpeed loads the model in half the size and it doesn't need .to() anyway, # and we only use deepspeed for training at the moment # 3. full fp16 eval - since the model needs to be half'ed first # 4. Sharded DDP - same as MP self.place_model_on_device = args.place_model_on_device if ( self.is_model_parallel or args.deepspeed or (args.fp16_full_eval and not args.do_train) or (self.sharded_ddp in [ShardedDDPOption.ZERO_DP_2, ShardedDDPOption.ZERO_DP_3]) ): self.place_model_on_device = False default_collator = default_data_collator if tokenizer is None else DataCollatorWithPadding(tokenizer) self.data_collator = data_collator if data_collator is not None else default_collator self.train_dataset = train_dataset self.eval_dataset = eval_dataset self.tokenizer = tokenizer if self.place_model_on_device: model = model.to(args.device) # Force n_gpu to 1 to avoid DataParallel as MP will manage the GPUs if self.is_model_parallel: self.args._n_gpu = 1 # later use `self.model is self.model_wrapped` to check if it's wrapped or not self.model_wrapped = model self.model = model self.compute_metrics = compute_metrics self.optimizer, self.lr_scheduler = optimizers if model_init is not None and (self.optimizer is not None or self.lr_scheduler is not None): raise RuntimeError( "Passing a `model_init` is incompatible with providing the `optimizers` argument." "You should subclass `Trainer` and override the `create_optimizer_and_scheduler` method." ) default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to) callbacks = default_callbacks if callbacks is None else default_callbacks + callbacks self.callback_handler = CallbackHandler( callbacks, self.model, self.tokenizer, self.optimizer, self.lr_scheduler ) self.add_callback(PrinterCallback if self.args.disable_tqdm else DEFAULT_PROGRESS_CALLBACK) # Will be set to True by `self._setup_loggers()` on first call to `self.log()`. self._loggers_initialized = False # Create clone of distant repo and output directory if needed if self.args.push_to_hub: self.init_git_repo() if self.is_world_process_zero(): os.makedirs(self.args.output_dir, exist_ok=True) if not callable(self.data_collator) and callable(getattr(self.data_collator, "collate_batch", None)): raise ValueError("The `data_collator` should be a simple callable (function, class with `__call__`).") if args.max_steps > 0: logger.info("max_steps is given, it will override any value given in num_train_epochs") if train_dataset is not None and not isinstance(train_dataset, collections.abc.Sized) and args.max_steps <= 0: raise ValueError("train_dataset does not implement __len__, max_steps has to be specified") self._signature_columns = None # Mixed precision setup self.use_apex = False self.use_amp = False self.fp16_backend = None if args.fp16: if args.fp16_backend == "auto": self.fp16_backend = "amp" if _is_native_amp_available else "apex" else: self.fp16_backend = args.fp16_backend logger.info(f"Using {self.fp16_backend} fp16 backend") if args.fp16 and not args.deepspeed: # deepspeed manages its own fp16 if self.fp16_backend == "amp": self.use_amp = True if is_sagemaker_mp_enabled(): self.scaler = smp.amp.GradScaler() elif self.sharded_ddp is not None: self.scaler = ShardedGradScaler() else: self.scaler = torch.cuda.amp.GradScaler() else: if not is_apex_available(): raise ImportError( "Using FP16 with APEX but APEX is not installed, please refer to https://www.github.com/nvidia/apex." ) self.use_apex = True # FP16 + model parallelism in SageMaker: gradient clipping does not work for now so we raise a helpful error. if is_sagemaker_mp_enabled() and self.use_amp and args.max_grad_norm is not None and args.max_grad_norm > 0: raise ValueError( "SageMaker Model Parallelism in mixed precision mode does not support gradient clipping yet. Pass " "along 'max_grad_norm': 0 in your hyperparameters." ) # Label smoothing if self.args.label_smoothing_factor != 0: self.label_smoother = LabelSmoother(epsilon=self.args.label_smoothing_factor) else: self.label_smoother = None self.state = TrainerState() self.control = TrainerControl() # Internal variable to count flos in each process, will be accumulated in `self.state.total_flos` then # returned to 0 every time flos need to be logged self.current_flos = 0 self.hp_search_backend = None self.use_tune_checkpoints = False default_label_names = ( ["start_positions", "end_positions"] if type(self.model).__name__ in MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES.values() else ["labels"] ) self.label_names = default_label_names if self.args.label_names is None else self.args.label_names self.control = self.callback_handler.on_init_end(self.args, self.state, self.control) # very last self._memory_tracker.stop_and_update_metrics() def add_callback(self, callback): """ Add a callback to the current list of :class:`~transformer.TrainerCallback`. Args: callback (:obj:`type` or :class:`~transformer.TrainerCallback`): A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`. In the first case, will instantiate a member of that class. """ self.callback_handler.add_callback(callback) def pop_callback(self, callback): """ Remove a callback from the current list of :class:`~transformer.TrainerCallback` and returns it. If the callback is not found, returns :obj:`None` (and no error is raised). Args: callback (:obj:`type` or :class:`~transformer.TrainerCallback`): A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`. In the first case, will pop the first member of that class found in the list of callbacks. Returns: :class:`~transformer.TrainerCallback`: The callback removed, if found. """ return self.callback_handler.pop_callback(callback) def remove_callback(self, callback): """ Remove a callback from the current list of :class:`~transformer.TrainerCallback`. Args: callback (:obj:`type` or :class:`~transformer.TrainerCallback`): A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`. In the first case, will remove the first member of that class found in the list of callbacks. """ self.callback_handler.remove_callback(callback) def _remove_unused_columns(self, dataset: "datasets.Dataset", description: Optional[str] = None): if not self.args.remove_unused_columns: return dataset if self._signature_columns is None: # Inspect model forward signature to keep only the arguments it accepts. signature = inspect.signature(self.model.forward) self._signature_columns = list(signature.parameters.keys()) # Labels may be named label or label_ids, the default data collator handles that. self._signature_columns += ["label", "label_ids"] columns = [k for k in self._signature_columns if k in dataset.column_names] ignored_columns = list(set(dataset.column_names) - set(self._signature_columns)) if len(ignored_columns) > 0: dset_description = "" if description is None else f"in the {description} set " logger.info( f"The following columns {dset_description} don't have a corresponding argument in " f"`{self.model.__class__.__name__}.forward` and have been ignored: {', '.join(ignored_columns)}." ) if version.parse(datasets.__version__) < version.parse("1.4.0"): dataset.set_format( type=dataset.format["type"], columns=columns, format_kwargs=dataset.format["format_kwargs"] ) return dataset else: return dataset.remove_columns(ignored_columns) def _get_train_sampler(self) -> Optional[torch.utils.data.sampler.Sampler]: if not isinstance(self.train_dataset, collections.abc.Sized): return None generator = None if self.args.world_size <= 1 and _is_torch_generator_available: generator = torch.Generator() generator.manual_seed(int(torch.empty((), dtype=torch.int64).random_().item())) # Build the sampler. if self.args.group_by_length: if is_datasets_available() and isinstance(self.train_dataset, datasets.Dataset): lengths = ( self.train_dataset[self.args.length_column_name] if self.args.length_column_name in self.train_dataset.column_names else None ) else: lengths = None model_input_name = self.tokenizer.model_input_names[0] if self.tokenizer is not None else None if self.args.world_size <= 1: return LengthGroupedSampler( self.train_dataset, self.args.train_batch_size, lengths=lengths, model_input_name=model_input_name, generator=generator, ) else: return DistributedLengthGroupedSampler( self.train_dataset, self.args.train_batch_size, num_replicas=self.args.world_size, rank=self.args.process_index, lengths=lengths, model_input_name=model_input_name, seed=self.args.seed, ) else: if self.args.world_size <= 1: if _is_torch_generator_available: return RandomSampler(self.train_dataset, generator=generator) return RandomSampler(self.train_dataset) elif ( self.args.parallel_mode in [ParallelMode.TPU, ParallelMode.SAGEMAKER_MODEL_PARALLEL] and not self.args.dataloader_drop_last ): # Use a loop for TPUs when drop_last is False to have all batches have the same size. return DistributedSamplerWithLoop( self.train_dataset, batch_size=self.args.per_device_train_batch_size, num_replicas=self.args.world_size, rank=self.args.process_index, seed=self.args.seed, ) else: return DistributedSampler( self.train_dataset, num_replicas=self.args.world_size, rank=self.args.process_index, seed=self.args.seed, ) def get_train_dataloader(self) -> DataLoader: """ Returns the training :class:`~torch.utils.data.DataLoader`. Will use no sampler if :obj:`self.train_dataset` does not implement :obj:`__len__`, a random sampler (adapted to distributed training if necessary) otherwise. Subclass and override this method if you want to inject some custom behavior. """ if self.train_dataset is None: raise ValueError("Trainer: training requires a train_dataset.") train_dataset = self.train_dataset if is_datasets_available() and isinstance(train_dataset, datasets.Dataset): train_dataset = self._remove_unused_columns(train_dataset, description="training") if isinstance(train_dataset, torch.utils.data.dataset.IterableDataset): if self.args.world_size > 1: train_dataset = IterableDatasetShard( train_dataset, batch_size=self.args.train_batch_size, drop_last=self.args.dataloader_drop_last, num_processes=self.args.world_size, process_index=self.args.process_index, ) return DataLoader( train_dataset, batch_size=self.args.train_batch_size, collate_fn=self.data_collator, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) train_sampler = self._get_train_sampler() return DataLoader( train_dataset, batch_size=self.args.train_batch_size, sampler=train_sampler, collate_fn=self.data_collator, drop_last=self.args.dataloader_drop_last, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) def _get_eval_sampler(self, eval_dataset: Dataset) -> Optional[torch.utils.data.sampler.Sampler]: # Deprecated code if self.args.use_legacy_prediction_loop: if is_torch_tpu_available(): return SequentialDistributedSampler( eval_dataset, num_replicas=xm.xrt_world_size(), rank=xm.get_ordinal() ) elif is_sagemaker_mp_enabled(): return SequentialDistributedSampler( eval_dataset, num_replicas=smp.dp_size(), rank=smp.dp_rank(), batch_size=self.args.per_device_eval_batch_size, ) elif self.args.local_rank != -1: return SequentialDistributedSampler(eval_dataset) else: return SequentialSampler(eval_dataset) if self.args.world_size <= 1: return SequentialSampler(eval_dataset) else: return ShardSampler( eval_dataset, batch_size=self.args.per_device_eval_batch_size, num_processes=self.args.world_size, process_index=self.args.process_index, ) def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader: """ Returns the evaluation :class:`~torch.utils.data.DataLoader`. Subclass and override this method if you want to inject some custom behavior. Args: eval_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`): If provided, will override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`, columns not accepted by the ``model.forward()`` method are automatically removed. It must implement :obj:`__len__`. """ if eval_dataset is None and self.eval_dataset is None: raise ValueError("Trainer: evaluation requires an eval_dataset.") eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset if is_datasets_available() and isinstance(eval_dataset, datasets.Dataset): eval_dataset = self._remove_unused_columns(eval_dataset, description="evaluation") if isinstance(eval_dataset, torch.utils.data.dataset.IterableDataset): if self.args.world_size > 1: eval_dataset = IterableDatasetShard( eval_dataset, batch_size=self.args.eval_batch_size, drop_last=self.args.dataloader_drop_last, num_processes=self.args.world_size, process_index=self.args.process_index, ) return DataLoader( eval_dataset, batch_size=self.args.eval_batch_size, collate_fn=self.data_collator, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) eval_sampler = self._get_eval_sampler(eval_dataset) return DataLoader( eval_dataset, sampler=eval_sampler, batch_size=self.args.eval_batch_size, collate_fn=self.data_collator, drop_last=self.args.dataloader_drop_last, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) def get_test_dataloader(self, test_dataset: Dataset) -> DataLoader: """ Returns the test :class:`~torch.utils.data.DataLoader`. Subclass and override this method if you want to inject some custom behavior. Args: test_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`): The test dataset to use. If it is an :obj:`datasets.Dataset`, columns not accepted by the ``model.forward()`` method are automatically removed. It must implement :obj:`__len__`. """ if is_datasets_available() and isinstance(test_dataset, datasets.Dataset): test_dataset = self._remove_unused_columns(test_dataset, description="test") if isinstance(test_dataset, torch.utils.data.dataset.IterableDataset): if self.args.world_size > 1: test_dataset = IterableDatasetShard( test_dataset, batch_size=self.args.eval_batch_size, drop_last=self.args.dataloader_drop_last, num_processes=self.args.world_size, process_index=self.args.process_index, ) return DataLoader( test_dataset, batch_size=self.args.eval_batch_size, collate_fn=self.data_collator, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) test_sampler = self._get_eval_sampler(test_dataset) # We use the same batch_size as for eval. return DataLoader( test_dataset, sampler=test_sampler, batch_size=self.args.eval_batch_size, collate_fn=self.data_collator, drop_last=self.args.dataloader_drop_last, pin_memory=self.args.dataloader_pin_memory, ) def create_optimizer_and_scheduler(self, num_training_steps: int): """ Setup the optimizer and the learning rate scheduler. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainer's init through :obj:`optimizers`, or subclass and override this method (or :obj:`create_optimizer` and/or :obj:`create_scheduler`) in a subclass. """ self.create_optimizer() self.create_scheduler(num_training_steps) def create_optimizer(self): """ Setup the optimizer. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainer's init through :obj:`optimizers`, or subclass and override this method in a subclass. """ if self.optimizer is None: decay_parameters = get_parameter_names(self.model, [nn.LayerNorm]) decay_parameters = [name for name in decay_parameters if "bias" not in name] optimizer_grouped_parameters = [ { "params": [p for n, p in self.model.named_parameters() if n in decay_parameters], "weight_decay": self.args.weight_decay, }, { "params": [p for n, p in self.model.named_parameters() if n not in decay_parameters], "weight_decay": 0.0, }, ] optimizer_cls = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: optimizer_cls = Adafactor optimizer_kwargs = {"scale_parameter": False, "relative_step": False} else: optimizer_cls = AdamW optimizer_kwargs = { "betas": (self.args.adam_beta1, self.args.adam_beta2), "eps": self.args.adam_epsilon, } optimizer_kwargs["lr"] = self.args.learning_rate if self.sharded_ddp == ShardedDDPOption.SIMPLE: self.optimizer = OSS( params=optimizer_grouped_parameters, optim=optimizer_cls, **optimizer_kwargs, ) else: self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs) if is_sagemaker_mp_enabled(): self.optimizer = smp.DistributedOptimizer(self.optimizer) def create_scheduler(self, num_training_steps: int): """ Setup the scheduler. The optimizer of the trainer must have been set up before this method is called. Args: num_training_steps (int): The number of training steps to do. """ if self.lr_scheduler is None: warmup_steps = ( self.args.warmup_steps if self.args.warmup_steps > 0 else math.ceil(num_training_steps * self.args.warmup_ratio) ) self.lr_scheduler = get_scheduler( self.args.lr_scheduler_type, self.optimizer, num_warmup_steps=warmup_steps, num_training_steps=num_training_steps, ) def num_examples(self, dataloader: DataLoader) -> int: """ Helper to get number of samples in a :class:`~torch.utils.data.DataLoader` by accessing its dataset. Will raise an exception if the underlying dataset does not implement method :obj:`__len__` """ return len(dataloader.dataset) def _hp_search_setup(self, trial: Union["optuna.Trial", Dict[str, Any]]): """HP search setup code""" self._trial = trial if self.hp_search_backend is None or trial is None: return if self.hp_search_backend == HPSearchBackend.OPTUNA: params = self.hp_space(trial) elif self.hp_search_backend == HPSearchBackend.RAY: params = trial params.pop("wandb", None) for key, value in params.items(): if not hasattr(self.args, key): raise AttributeError( f"Trying to set {key} in the hyperparameter search but there is no corresponding field in `TrainingArguments`." ) old_attr = getattr(self.args, key, None) # Casting value to the proper type if old_attr is not None: value = type(old_attr)(value) setattr(self.args, key, value) if self.hp_search_backend == HPSearchBackend.OPTUNA: logger.info("Trial:", trial.params) if self.args.deepspeed: # Rebuild the deepspeed config to reflect the updated training parameters from transformers.deepspeed import HfDeepSpeedConfig self.args.hf_deepspeed_config = HfDeepSpeedConfig(self.args) def _report_to_hp_search( self, trial: Union["optuna.Trial", Dict[str, Any]], epoch: int, metrics: Dict[str, float] ): if self.hp_search_backend is None or trial is None: return self.objective = self.compute_objective(metrics.copy()) if self.hp_search_backend == HPSearchBackend.OPTUNA: import optuna trial.report(self.objective, epoch) if trial.should_prune(): raise optuna.TrialPruned() elif self.hp_search_backend == HPSearchBackend.RAY: from ray import tune if self.control.should_save: self._tune_save_checkpoint() tune.report(objective=self.objective, **metrics) def _tune_save_checkpoint(self): from ray import tune if not self.use_tune_checkpoints: return with tune.checkpoint_dir(step=self.state.global_step) as checkpoint_dir: output_dir = os.path.join(checkpoint_dir, f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}") self.save_model(output_dir) if self.is_world_process_zero(): self.state.save_to_json(os.path.join(output_dir, "trainer_state.json")) torch.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt")) torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) def call_model_init(self, trial=None): model_init_argcount = len(inspect.signature(self.model_init).parameters) if model_init_argcount == 0: model = self.model_init() elif model_init_argcount == 1: model = self.model_init(trial) else: raise RuntimeError("model_init should have 0 or 1 argument.") if model is None: raise RuntimeError("model_init should not return None.") return model def _wrap_model(self, model, training=True): if is_sagemaker_mp_enabled(): # Wrapping the base model twice in a DistributedModel will raise an error. if isinstance(self.model_wrapped, smp.model.DistributedModel): return self.model_wrapped return smp.DistributedModel(model, backward_passes_per_step=self.args.gradient_accumulation_steps) # already initialized its own DDP and AMP if self.deepspeed: return self.deepspeed # train/eval could be run multiple-times - if already wrapped, don't re-wrap it again if unwrap_model(model) is not model: return model # Mixed precision training with apex (torch < 1.6) if self.use_apex and training: model, self.optimizer = amp.initialize(model, self.optimizer, opt_level=self.args.fp16_opt_level) # Multi-gpu training (should be after apex fp16 initialization) if self.args.n_gpu > 1: model = nn.DataParallel(model) # Note: in torch.distributed mode, there's no point in wrapping the model # inside a DistributedDataParallel as we'll be under `no_grad` anyways. if not training: return model # Distributed training (should be after apex fp16 initialization) if self.sharded_ddp is not None: # Sharded DDP! if self.sharded_ddp == ShardedDDPOption.SIMPLE: model = ShardedDDP(model, self.optimizer) else: mixed_precision = self.args.fp16 cpu_offload = ShardedDDPOption.OFFLOAD in self.args.sharded_ddp zero_3 = self.sharded_ddp == ShardedDDPOption.ZERO_DP_3 # XXX: Breaking the self.model convention but I see no way around it for now. if ShardedDDPOption.AUTO_WRAP in self.args.sharded_ddp: model = auto_wrap(model) self.model = model = FullyShardedDDP( model, mixed_precision=mixed_precision, reshard_after_forward=zero_3, cpu_offload=cpu_offload, ).to(self.args.device) elif is_sagemaker_dp_enabled(): model = DDP(model, device_ids=[dist.get_local_rank()], broadcast_buffers=False) elif self.args.local_rank != -1: if self.args.ddp_find_unused_parameters is not None: find_unused_parameters = self.args.ddp_find_unused_parameters elif isinstance(model, PreTrainedModel): # find_unused_parameters breaks checkpointing as per # https://github.com/huggingface/transformers/pull/4659#issuecomment-643356021 find_unused_parameters = not getattr(model.config, "gradient_checkpointing", False) else: find_unused_parameters = True model = nn.parallel.DistributedDataParallel( model, device_ids=[self.args.local_rank], output_device=self.args.local_rank, find_unused_parameters=find_unused_parameters, ) return model def train( self, resume_from_checkpoint: Optional[Union[str, bool]] = None, trial: Union["optuna.Trial", Dict[str, Any]] = None, **kwargs, ): """ Main training entry point. Args: resume_from_checkpoint (:obj:`str` or :obj:`bool`, `optional`): If a :obj:`str`, local path to a saved checkpoint as saved by a previous instance of :class:`~transformers.Trainer`. If a :obj:`bool` and equals `True`, load the last checkpoint in `args.output_dir` as saved by a previous instance of :class:`~transformers.Trainer`. If present, training will resume from the model/optimizer/scheduler states loaded here. trial (:obj:`optuna.Trial` or :obj:`Dict[str, Any]`, `optional`): The trial run or the hyperparameter dictionary for hyperparameter search. kwargs: Additional keyword arguments used to hide deprecated arguments """ # memory metrics - must set up as early as possible self._memory_tracker.start() args = self.args self.is_in_train = True # do_train is not a reliable argument, as it might not be set and .train() still called, so # the following is a workaround: if args.fp16_full_eval and not args.do_train: self.model = self.model.to(args.device) if "model_path" in kwargs: resume_from_checkpoint = kwargs.pop("model_path") warnings.warn( "`model_path` is deprecated and will be removed in a future version. Use `resume_from_checkpoint` " "instead.", FutureWarning, ) if len(kwargs) > 0: raise TypeError(f"train() received got unexpected keyword arguments: {', '.join(list(kwargs.keys()))}.") # This might change the seed so needs to run first. self._hp_search_setup(trial) # Model re-init model_reloaded = False if self.model_init is not None: # Seed must be set before instantiating the model when using model_init. set_seed(args.seed) self.model = self.call_model_init(trial) model_reloaded = True # Reinitializes optimizer and scheduler self.optimizer, self.lr_scheduler = None, None # Load potential model checkpoint if isinstance(resume_from_checkpoint, bool) and resume_from_checkpoint: resume_from_checkpoint = get_last_checkpoint(args.output_dir) if resume_from_checkpoint is None: raise ValueError(f"No valid checkpoint found in output directory ({args.output_dir})") if resume_from_checkpoint is not None: if not os.path.isfile(os.path.join(resume_from_checkpoint, WEIGHTS_NAME)): raise ValueError(f"Can't find a valid checkpoint at {resume_from_checkpoint}") logger.info(f"Loading model from {resume_from_checkpoint}).") if os.path.isfile(os.path.join(resume_from_checkpoint, CONFIG_NAME)): config = PretrainedConfig.from_json_file(os.path.join(resume_from_checkpoint, CONFIG_NAME)) checkpoint_version = config.transformers_version if checkpoint_version is not None and checkpoint_version != __version__: logger.warn( f"You are resuming training from a checkpoint trained with {checkpoint_version} of " f"Transformers but your current version is {__version__}. This is not recommended and could " "yield to errors or unwanted behaviors." ) if args.deepspeed: # will be resumed in deepspeed_init pass else: # We load the model state dict on the CPU to avoid an OOM error. state_dict = torch.load(os.path.join(resume_from_checkpoint, WEIGHTS_NAME), map_location="cpu") # If the model is on the GPU, it still works! self._load_state_dict_in_model(state_dict) # If model was re-initialized, put it on the right device and update self.model_wrapped if model_reloaded: if self.place_model_on_device: self.model = self.model.to(args.device) self.model_wrapped = self.model # Keeping track whether we can can len() on the dataset or not train_dataset_is_sized = isinstance(self.train_dataset, collections.abc.Sized) # Data loader and number of training steps train_dataloader = self.get_train_dataloader() # Setting up training control variables: # number of training epochs: num_train_epochs # number of training steps per epoch: num_update_steps_per_epoch # total number of training steps to execute: max_steps total_train_batch_size = args.train_batch_size * args.gradient_accumulation_steps * args.world_size if train_dataset_is_sized: num_update_steps_per_epoch = len(train_dataloader) // args.gradient_accumulation_steps num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1) if args.max_steps > 0: max_steps = args.max_steps num_train_epochs = args.max_steps // num_update_steps_per_epoch + int( args.max_steps % num_update_steps_per_epoch > 0 ) # May be slightly incorrect if the last batch in the training datalaoder has a smaller size but it's # the best we can do. num_train_samples = args.max_steps * total_train_batch_size else: max_steps = math.ceil(args.num_train_epochs * num_update_steps_per_epoch) num_train_epochs = math.ceil(args.num_train_epochs) num_train_samples = len(self.train_dataset) * args.num_train_epochs else: # see __init__. max_steps is set when the dataset has no __len__ max_steps = args.max_steps num_train_epochs = int(args.num_train_epochs) num_update_steps_per_epoch = max_steps num_train_samples = args.max_steps * total_train_batch_size if DebugOption.UNDERFLOW_OVERFLOW in self.args.debug: debug_overflow = DebugUnderflowOverflow(self.model) # noqa delay_optimizer_creation = self.sharded_ddp is not None and self.sharded_ddp != ShardedDDPOption.SIMPLE if args.deepspeed: deepspeed_engine, optimizer, lr_scheduler = deepspeed_init( self, num_training_steps=max_steps, resume_from_checkpoint=resume_from_checkpoint ) self.model = deepspeed_engine.module self.model_wrapped = deepspeed_engine self.deepspeed = deepspeed_engine self.optimizer = optimizer self.lr_scheduler = lr_scheduler elif not delay_optimizer_creation: self.create_optimizer_and_scheduler(num_training_steps=max_steps) self.state = TrainerState() self.state.is_hyper_param_search = trial is not None model = self._wrap_model(self.model_wrapped) # for the rest of this function `model` is the outside model, whether it was wrapped or not if model is not self.model: self.model_wrapped = model if delay_optimizer_creation: self.create_optimizer_and_scheduler(num_training_steps=max_steps) # Check if saved optimizer or scheduler states exist self._load_optimizer_and_scheduler(resume_from_checkpoint) # important: at this point: # self.model is the Transformers Model # self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model), etc. # Train! num_examples = ( self.num_examples(train_dataloader) if train_dataset_is_sized else total_train_batch_size * args.max_steps ) logger.info("***** Running training *****") logger.info(f" Num examples = {num_examples}") logger.info(f" Num Epochs = {num_train_epochs}") logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}") logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}") logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}") logger.info(f" Total optimization steps = {max_steps}") self.state.epoch = 0 start_time = time.time() epochs_trained = 0 steps_trained_in_current_epoch = 0 steps_trained_progress_bar = None # Check if continuing training from a checkpoint if resume_from_checkpoint is not None and os.path.isfile( os.path.join(resume_from_checkpoint, "trainer_state.json") ): self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, "trainer_state.json")) epochs_trained = self.state.global_step // num_update_steps_per_epoch if not args.ignore_data_skip: steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch) steps_trained_in_current_epoch *= args.gradient_accumulation_steps else: steps_trained_in_current_epoch = 0 logger.info(" Continuing training from checkpoint, will skip to saved global_step") logger.info(f" Continuing training from epoch {epochs_trained}") logger.info(f" Continuing training from global step {self.state.global_step}") if not args.ignore_data_skip: logger.info( f" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} " "batches in the first epoch. If this takes a lot of time, you can add the `--ignore_data_skip` " "flag to your launch command, but you will resume the training on data already seen by your model." ) if self.is_local_process_zero() and not args.disable_tqdm: steps_trained_progress_bar = tqdm(total=steps_trained_in_current_epoch) steps_trained_progress_bar.set_description("Skipping the first batches") # Update the references self.callback_handler.model = self.model self.callback_handler.optimizer = self.optimizer self.callback_handler.lr_scheduler = self.lr_scheduler self.callback_handler.train_dataloader = train_dataloader self.state.trial_name = self.hp_name(trial) if self.hp_name is not None else None self.state.trial_params = hp_params(trial) if trial is not None else None # This should be the same if the state has been saved but in case the training arguments changed, it's safer # to set this after the load. self.state.max_steps = max_steps self.state.num_train_epochs = num_train_epochs self.state.is_local_process_zero = self.is_local_process_zero() self.state.is_world_process_zero = self.is_world_process_zero() # tr_loss is a tensor to avoid synchronization of TPUs through .item() tr_loss = torch.tensor(0.0).to(args.device) # _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses self._total_loss_scalar = 0.0 self._globalstep_last_logged = self.state.global_step model.zero_grad() self.control = self.callback_handler.on_train_begin(args, self.state, self.control) # Skip the first epochs_trained epochs to get the random state of the dataloader at the right point. if not args.ignore_data_skip: for epoch in range(epochs_trained): # We just need to begin an iteration to create the randomization of the sampler. for _ in train_dataloader: break for epoch in range(epochs_trained, num_train_epochs): if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler): train_dataloader.sampler.set_epoch(epoch) elif isinstance(train_dataloader.dataset, IterableDatasetShard): train_dataloader.dataset.set_epoch(epoch) if is_torch_tpu_available(): parallel_loader = pl.ParallelLoader(train_dataloader, [args.device]).per_device_loader(args.device) epoch_iterator = parallel_loader else: epoch_iterator = train_dataloader # Reset the past mems state at the beginning of each epoch if necessary. if args.past_index >= 0: self._past = None steps_in_epoch = ( len(epoch_iterator) if train_dataset_is_sized else args.max_steps * args.gradient_accumulation_steps ) self.control = self.callback_handler.on_epoch_begin(args, self.state, self.control) for step, inputs in enumerate(epoch_iterator): # Skip past any already trained steps if resuming training if steps_trained_in_current_epoch > 0: steps_trained_in_current_epoch -= 1 if steps_trained_progress_bar is not None: steps_trained_progress_bar.update(1) if steps_trained_in_current_epoch == 0: self._load_rng_state(resume_from_checkpoint) continue elif steps_trained_progress_bar is not None: steps_trained_progress_bar.close() steps_trained_progress_bar = None if step % args.gradient_accumulation_steps == 0: self.control = self.callback_handler.on_step_begin(args, self.state, self.control) if ( ((step + 1) % args.gradient_accumulation_steps != 0) and args.local_rank != -1 and args._no_sync_in_gradient_accumulation ): # Avoid unnecessary DDP synchronization since there will be no backward pass on this example. with model.no_sync(): tr_loss += self.training_step(model, inputs) else: tr_loss += self.training_step(model, inputs) self.current_flos += float(self.floating_point_ops(inputs)) # Optimizer step for deepspeed must be called on every step regardless of the value of gradient_accumulation_steps if self.deepspeed: self.deepspeed.step() if (step + 1) % args.gradient_accumulation_steps == 0 or ( # last step in epoch but step is always smaller than gradient_accumulation_steps steps_in_epoch <= args.gradient_accumulation_steps and (step + 1) == steps_in_epoch ): # Gradient clipping if args.max_grad_norm is not None and args.max_grad_norm > 0 and not self.deepspeed: # deepspeed does its own clipping if self.use_amp: # AMP: gradients need unscaling self.scaler.unscale_(self.optimizer) if hasattr(self.optimizer, "clip_grad_norm"): # Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping self.optimizer.clip_grad_norm(args.max_grad_norm) elif hasattr(model, "clip_grad_norm_"): # Some models (like FullyShardedDDP) have a specific way to do gradient clipping model.clip_grad_norm_(args.max_grad_norm) else: # Revert to normal clipping otherwise, handling Apex or full precision nn.utils.clip_grad_norm_( amp.master_params(self.optimizer) if self.use_apex else model.parameters(), args.max_grad_norm, ) # Optimizer step optimizer_was_run = True if self.deepspeed: pass # called outside the loop elif is_torch_tpu_available(): xm.optimizer_step(self.optimizer) elif self.use_amp: scale_before = self.scaler.get_scale() self.scaler.step(self.optimizer) self.scaler.update() scale_after = self.scaler.get_scale() optimizer_was_run = scale_before <= scale_after else: self.optimizer.step() if optimizer_was_run and not self.deepspeed: self.lr_scheduler.step() model.zero_grad() self.state.global_step += 1 self.state.epoch = epoch + (step + 1) / steps_in_epoch self.control = self.callback_handler.on_step_end(args, self.state, self.control) self._maybe_log_save_evaluate(tr_loss, model, trial, epoch) if self.control.should_epoch_stop or self.control.should_training_stop: break self.control = self.callback_handler.on_epoch_end(args, self.state, self.control) self._maybe_log_save_evaluate(tr_loss, model, trial, epoch) if DebugOption.TPU_METRICS_DEBUG in self.args.debug: if is_torch_tpu_available(): # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report()) else: logger.warning( "You enabled PyTorch/XLA debug metrics but you don't have a TPU " "configured. Check your training configuration if this is unexpected." ) if self.control.should_training_stop: break if args.past_index and hasattr(self, "_past"): # Clean the state at the end of training delattr(self, "_past") logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n") if args.load_best_model_at_end and self.state.best_model_checkpoint is not None: # Wait for everyone to get here so we are sur the model has been saved by process 0. if is_torch_tpu_available(): xm.rendezvous("load_best_model_at_end") elif args.local_rank != -1: dist.barrier() logger.info( f"Loading best model from {self.state.best_model_checkpoint} (score: {self.state.best_metric})." ) # We load the model state dict on the CPU to avoid an OOM error. if args.local_rank == 0: print("Only loading from rank 0") state_dict = torch.load(os.path.join(self.state.best_model_checkpoint, WEIGHTS_NAME), map_location="cpu") # If the model is on the GPU, it still works! self._load_state_dict_in_model(state_dict) if self.deepspeed: self.deepspeed.load_checkpoint( self.state.best_model_checkpoint, load_optimizer_states=False, load_lr_scheduler_states=False ) # add remaining tr_loss self._total_loss_scalar += tr_loss.item() train_loss = self._total_loss_scalar / self.state.global_step metrics = speed_metrics("train", start_time, num_samples=num_train_samples, num_steps=self.state.max_steps) self.store_flos() metrics["total_flos"] = self.state.total_flos metrics["train_loss"] = train_loss self.is_in_train = False self._memory_tracker.stop_and_update_metrics(metrics) self.log(metrics) self.control = self.callback_handler.on_train_end(args, self.state, self.control) return TrainOutput(self.state.global_step, train_loss, metrics) def _load_state_dict_in_model(self, state_dict): load_result = self.model.load_state_dict(state_dict, strict=False) if len(load_result.missing_keys) != 0: if set(load_result.missing_keys) == set(self.model._keys_to_ignore_on_save): self.model.tie_weights() else: logger.warn(f"There were missing keys in the checkpoint model loaded: {load_result.missing_keys}.") if len(load_result.unexpected_keys) != 0: logger.warn(f"There were unexpected keys in the checkpoint model loaded: {load_result.unexpected_keys}.") def _maybe_log_save_evaluate(self, tr_loss, model, trial, epoch): if self.control.should_log: logs: Dict[str, float] = {} tr_loss_scalar = tr_loss.item() # reset tr_loss to zero tr_loss -= tr_loss logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4) logs["learning_rate"] = self._get_learning_rate() self._total_loss_scalar += tr_loss_scalar self._globalstep_last_logged = self.state.global_step self.store_flos() self.log(logs) metrics = None if self.control.should_evaluate: metrics = self.evaluate() self._report_to_hp_search(trial, epoch, metrics) if self.control.should_save: self._save_checkpoint(model, trial, metrics=metrics) self.control = self.callback_handler.on_save(self.args, self.state, self.control) def _load_rng_state(self, checkpoint): # Load RNG states from `checkpoint` if checkpoint is None: return local_rank = xm.get_local_ordinal() if is_torch_tpu_available() else self.args.local_rank if local_rank != -1: rng_file = os.path.join(checkpoint, f"rng_state_{local_rank}.pth") if not os.path.isfile(os.path.join(checkpoint, rng_file)): logger.info( f"Didn't find an RNG file for process {local_rank}, if you are resuming a training that " "wasn't launched in a distributed fashion, reproducibility is not guaranteed." ) return else: rng_file = os.path.join(checkpoint, "rng_state.pth") if not os.path.isfile(os.path.join(checkpoint, rng_file)): logger.info( "Didn't find an RNG file, if you are resuming a training that was launched in a distributed " "fashion, reproducibility is not guaranteed." ) return checkpoint_rng_state = torch.load(rng_file) random.setstate(checkpoint_rng_state["python"]) np.random.set_state(checkpoint_rng_state["numpy"]) torch.random.set_rng_state(checkpoint_rng_state["cpu"]) if torch.cuda.is_available(): if self.args.local_rank != -1: torch.cuda.random.set_rng_state(checkpoint_rng_state["cuda"]) else: torch.cuda.random.set_rng_state_all(checkpoint_rng_state["cuda"]) if is_torch_tpu_available(): xm.set_rng_state(checkpoint_rng_state["xla"]) def _save_checkpoint(self, model, trial, metrics=None): # In all cases, including ddp/dp/deepspeed, self.model is always a reference to the model we # want to save except FullyShardedDDP. # assert unwrap_model(model) is self.model, "internal model should be a reference to self.model" # Save model checkpoint checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}" if self.hp_search_backend is not None and trial is not None: if self.hp_search_backend == HPSearchBackend.OPTUNA: run_id = trial.number else: from ray import tune run_id = tune.get_trial_id() run_name = self.hp_name(trial) if self.hp_name is not None else f"run-{run_id}" run_dir = os.path.join(self.args.output_dir, run_name) else: run_dir = self.args.output_dir self.store_flos() output_dir = os.path.join(run_dir, checkpoint_folder) self.save_model(output_dir) if self.deepspeed: # under zero3 model file itself doesn't get saved since it's bogus! Unless deepspeed # config `stage3_gather_fp16_weights_on_model_save` is True self.deepspeed.save_checkpoint(output_dir) # Save optimizer and scheduler if self.sharded_ddp == ShardedDDPOption.SIMPLE: self.optimizer.consolidate_state_dict() if is_torch_tpu_available(): xm.rendezvous("saving_optimizer_states") xm.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt")) with warnings.catch_warnings(record=True) as caught_warnings: xm.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) reissue_pt_warnings(caught_warnings) elif is_sagemaker_mp_enabled(): if smp.dp_rank() == 0: # Consolidate the state dict on all processed of dp_rank 0 opt_state_dict = self.optimizer.state_dict() # Save it and the scheduler on the main process if self.is_world_process_zero(): torch.save(opt_state_dict, os.path.join(output_dir, "optimizer.pt")) with warnings.catch_warnings(record=True) as caught_warnings: torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) reissue_pt_warnings(caught_warnings) if self.use_amp: torch.save(self.scaler.state_dict(), os.path.join(output_dir, "scaler.pt")) elif self.is_world_process_zero() and not self.deepspeed: # deepspeed.save_checkpoint above saves model/optim/sched torch.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt")) with warnings.catch_warnings(record=True) as caught_warnings: torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) reissue_pt_warnings(caught_warnings) if self.use_amp: torch.save(self.scaler.state_dict(), os.path.join(output_dir, "scaler.pt")) # Determine the new best metric / best model checkpoint if metrics is not None and self.args.metric_for_best_model is not None: metric_to_check = self.args.metric_for_best_model if not metric_to_check.startswith("eval_"): metric_to_check = f"eval_{metric_to_check}" metric_value = metrics[metric_to_check] operator = np.greater if self.args.greater_is_better else np.less if ( self.state.best_metric is None or self.state.best_model_checkpoint is None or operator(metric_value, self.state.best_metric) ): self.state.best_metric = metric_value self.state.best_model_checkpoint = output_dir # Save the Trainer state if self.is_world_process_zero(): self.state.save_to_json(os.path.join(output_dir, "trainer_state.json")) # Save RNG state in non-distributed training rng_states = { "python": random.getstate(), "numpy": np.random.get_state(), "cpu": torch.random.get_rng_state(), } if torch.cuda.is_available(): if self.args.local_rank == -1: # In non distributed, we save the global CUDA RNG state (will take care of DataParallel) rng_states["cuda"] = torch.cuda.random.get_rng_state_all() else: rng_states["cuda"] = torch.cuda.random.get_rng_state() if is_torch_tpu_available(): rng_states["xla"] = xm.get_rng_state() # A process can arrive here before the process 0 has a chance to save the model, in which case output_dir may # not yet exist. os.makedirs(output_dir, exist_ok=True) local_rank = xm.get_local_ordinal() if is_torch_tpu_available() else self.args.local_rank if local_rank == -1: torch.save(rng_states, os.path.join(output_dir, "rng_state.pth")) else: torch.save(rng_states, os.path.join(output_dir, f"rng_state_{local_rank}.pth")) # Maybe delete some older checkpoints. if self.is_world_process_zero(): self._rotate_checkpoints(use_mtime=True, output_dir=run_dir) def _load_optimizer_and_scheduler(self, checkpoint): """If optimizer and scheduler states exist, load them.""" if checkpoint is None: return if self.deepspeed: # deepspeed loads optimizer/lr_scheduler together with the model in deepspeed_init return if os.path.isfile(os.path.join(checkpoint, "optimizer.pt")) and os.path.isfile( os.path.join(checkpoint, "scheduler.pt") ): # Load in optimizer and scheduler states if is_torch_tpu_available(): # On TPU we have to take some extra precautions to properly load the states on the right device. optimizer_state = torch.load(os.path.join(checkpoint, "optimizer.pt"), map_location="cpu") with warnings.catch_warnings(record=True) as caught_warnings: lr_scheduler_state = torch.load(os.path.join(checkpoint, "scheduler.pt"), map_location="cpu") reissue_pt_warnings(caught_warnings) xm.send_cpu_data_to_device(optimizer_state, self.args.device) xm.send_cpu_data_to_device(lr_scheduler_state, self.args.device) self.optimizer.load_state_dict(optimizer_state) self.lr_scheduler.load_state_dict(lr_scheduler_state) else: map_location = "cpu" if is_sagemaker_mp_enabled() else self.args.device self.optimizer.load_state_dict( torch.load(os.path.join(checkpoint, "optimizer.pt"), map_location=map_location) ) with warnings.catch_warnings(record=True) as caught_warnings: self.lr_scheduler.load_state_dict(torch.load(os.path.join(checkpoint, "scheduler.pt"))) reissue_pt_warnings(caught_warnings) if self.use_amp and os.path.isfile(os.path.join(checkpoint, "scaler.pt")): self.scaler.load_state_dict(torch.load(os.path.join(checkpoint, "scaler.pt"))) def hyperparameter_search( self, hp_space: Optional[Callable[["optuna.Trial"], Dict[str, float]]] = None, compute_objective: Optional[Callable[[Dict[str, float]], float]] = None, n_trials: int = 20, direction: str = "minimize", backend: Optional[Union["str", HPSearchBackend]] = None, hp_name: Optional[Callable[["optuna.Trial"], str]] = None, **kwargs, ) -> BestRun: """ Launch an hyperparameter search using ``optuna`` or ``Ray Tune``. The optimized quantity is determined by :obj:`compute_objective`, which defaults to a function returning the evaluation loss when no metric is provided, the sum of all metrics otherwise. .. warning:: To use this method, you need to have provided a ``model_init`` when initializing your :class:`~transformers.Trainer`: we need to reinitialize the model at each new run. This is incompatible with the ``optimizers`` argument, so you need to subclass :class:`~transformers.Trainer` and override the method :meth:`~transformers.Trainer.create_optimizer_and_scheduler` for custom optimizer/scheduler. Args: hp_space (:obj:`Callable[["optuna.Trial"], Dict[str, float]]`, `optional`): A function that defines the hyperparameter search space. Will default to :func:`~transformers.trainer_utils.default_hp_space_optuna` or :func:`~transformers.trainer_utils.default_hp_space_ray` depending on your backend. compute_objective (:obj:`Callable[[Dict[str, float]], float]`, `optional`): A function computing the objective to minimize or maximize from the metrics returned by the :obj:`evaluate` method. Will default to :func:`~transformers.trainer_utils.default_compute_objective`. n_trials (:obj:`int`, `optional`, defaults to 100): The number of trial runs to test. direction(:obj:`str`, `optional`, defaults to :obj:`"minimize"`): Whether to optimize greater or lower objects. Can be :obj:`"minimize"` or :obj:`"maximize"`, you should pick :obj:`"minimize"` when optimizing the validation loss, :obj:`"maximize"` when optimizing one or several metrics. backend(:obj:`str` or :class:`~transformers.training_utils.HPSearchBackend`, `optional`): The backend to use for hyperparameter search. Will default to optuna or Ray Tune, depending on which one is installed. If both are installed, will default to optuna. kwargs: Additional keyword arguments passed along to :obj:`optuna.create_study` or :obj:`ray.tune.run`. For more information see: - the documentation of `optuna.create_study <https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.create_study.html>`__ - the documentation of `tune.run <https://docs.ray.io/en/latest/tune/api_docs/execution.html#tune-run>`__ Returns: :class:`transformers.trainer_utils.BestRun`: All the information about the best run. """ if backend is None: backend = default_hp_search_backend() if backend is None: raise RuntimeError( "At least one of optuna or ray should be installed. " "To install optuna run `pip install optuna`." "To install ray run `pip install ray[tune]`." ) backend = HPSearchBackend(backend) if backend == HPSearchBackend.OPTUNA and not is_optuna_available(): raise RuntimeError("You picked the optuna backend, but it is not installed. Use `pip install optuna`.") if backend == HPSearchBackend.RAY and not is_ray_tune_available(): raise RuntimeError( "You picked the Ray Tune backend, but it is not installed. Use `pip install 'ray[tune]'`." ) self.hp_search_backend = backend if self.model_init is None: raise RuntimeError( "To use hyperparameter search, you need to pass your model through a model_init function." ) self.hp_space = default_hp_space[backend] if hp_space is None else hp_space self.hp_name = hp_name self.compute_objective = default_compute_objective if compute_objective is None else compute_objective run_hp_search = run_hp_search_optuna if backend == HPSearchBackend.OPTUNA else run_hp_search_ray best_run = run_hp_search(self, n_trials, direction, **kwargs) self.hp_search_backend = None return best_run def log(self, logs: Dict[str, float]) -> None: """ Log :obj:`logs` on the various objects watching training. Subclass and override this method to inject custom behavior. Args: logs (:obj:`Dict[str, float]`): The values to log. """ if self.state.epoch is not None: logs["epoch"] = round(self.state.epoch, 2) output = {**logs, **{"step": self.state.global_step}} self.state.log_history.append(output) self.control = self.callback_handler.on_log(self.args, self.state, self.control, logs) def _prepare_inputs(self, inputs: Dict[str, Union[torch.Tensor, Any]]) -> Dict[str, Union[torch.Tensor, Any]]: """ Prepare :obj:`inputs` before feeding them to the model, converting them to tensors if they are not already and handling potential state. """ for k, v in inputs.items(): if isinstance(v, torch.Tensor): kwargs = dict(device=self.args.device) if self.deepspeed and inputs[k].dtype != torch.int64: # NLP models inputs are int64 and those get adjusted to the right dtype of the # embedding. Other models such as wav2vec2's inputs are already float and thus # may need special handling to match the dtypes of the model kwargs.update(dict(dtype=self.args.hf_deepspeed_config.dtype())) inputs[k] = v.to(**kwargs) if self.args.past_index >= 0 and self._past is not None: inputs["mems"] = self._past return inputs def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor: """ Perform a training step on a batch of inputs. Subclass and override to inject custom behavior. Args: model (:obj:`nn.Module`): The model to train. inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model. The dictionary will be unpacked before being fed to the model. Most models expect the targets under the argument :obj:`labels`. Check your model's documentation for all accepted arguments. Return: :obj:`torch.Tensor`: The tensor with training loss on this batch. """ model.train() inputs = self._prepare_inputs(inputs) if is_sagemaker_mp_enabled(): scaler = self.scaler if self.use_amp else None loss_mb = smp_forward_backward(model, inputs, self.args.gradient_accumulation_steps, scaler=scaler) return loss_mb.reduce_mean().detach().to(self.args.device) if self.use_amp: with autocast(): loss = self.compute_loss(model, inputs) else: loss = self.compute_loss(model, inputs) if self.args.n_gpu > 1: loss = loss.mean() # mean() to average on multi-gpu parallel training if self.args.gradient_accumulation_steps > 1 and not self.deepspeed: # deepspeed handles loss scaling by gradient_accumulation_steps in its `backward` loss = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(loss).backward() elif self.use_apex: with amp.scale_loss(loss, self.optimizer) as scaled_loss: scaled_loss.backward() elif self.deepspeed: # loss gets scaled under gradient_accumulation_steps in deepspeed loss = self.deepspeed.backward(loss) else: loss.backward() return loss.detach() def compute_loss(self, model, inputs, return_outputs=False): """ How the loss is computed by Trainer. By default, all models return the loss in the first element. Subclass and override for custom behavior. """ if self.label_smoother is not None and "labels" in inputs: labels = inputs.pop("labels") else: labels = None outputs = model(**inputs) # Save past state if it exists # TODO: this needs to be fixed and made cleaner later. if self.args.past_index >= 0: self._past = outputs[self.args.past_index] if labels is not None: loss = self.label_smoother(outputs, labels) else: # We don't use .loss here since the model may return tuples instead of ModelOutput. loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0] return (loss, outputs) if return_outputs else loss def is_local_process_zero(self) -> bool: """ Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on several machines) main process. """ return self.args.local_process_index == 0 def is_world_process_zero(self) -> bool: """ Whether or not this process is the global main process (when training in a distributed fashion on several machines, this is only going to be :obj:`True` for one process). """ # Special case for SageMaker ModelParallel since there process_index is dp_process_index, not the global # process index. if is_sagemaker_mp_enabled(): return smp.rank() == 0 else: return self.args.process_index == 0 def save_model(self, output_dir: Optional[str] = None): """ Will save the model, so you can reload it using :obj:`from_pretrained()`. Will only save from the main process. """ if output_dir is None: output_dir = self.args.output_dir if is_torch_tpu_available(): self._save_tpu(output_dir) elif is_sagemaker_mp_enabled(): # Calling the state_dict needs to be done on the wrapped model and on all processes. state_dict = self.model_wrapped.state_dict() if self.is_world_process_zero(): self._save(output_dir, state_dict=state_dict) elif ( ShardedDDPOption.ZERO_DP_2 in self.args.sharded_ddp or ShardedDDPOption.ZERO_DP_3 in self.args.sharded_ddp ): state_dict = self.model.state_dict() if self.is_world_process_zero(): self._save(output_dir, state_dict=state_dict) elif self.deepspeed: # this takes care of everything as long as we aren't under zero3 if self.is_world_process_zero(): self._save(output_dir) if is_deepspeed_zero3_enabled(): # It's too complicated to try to override different places where the weights dump gets # saved, so since under zero3 the file is bogus, simply delete it. The user should # either user deepspeed checkpoint to resume or to recover full weights use # zero_to_fp32.py stored in the checkpoint. if self.is_world_process_zero(): file = os.path.join(output_dir, WEIGHTS_NAME) if os.path.isfile(file): # logger.info(f"deepspeed zero3: removing {file}, see zero_to_fp32.py to recover weights") os.remove(file) # now save the real model if stage3_gather_fp16_weights_on_model_save=True # if false it will not be saved. # This must be called on all ranks self.deepspeed.save_fp16_model(output_dir, WEIGHTS_NAME) elif self.is_world_process_zero(): self._save(output_dir) def _save_tpu(self, output_dir: Optional[str] = None): output_dir = output_dir if output_dir is not None else self.args.output_dir logger.info(f"Saving model checkpoint to {output_dir}") if xm.is_master_ordinal(): os.makedirs(output_dir, exist_ok=True) torch.save(self.args, os.path.join(output_dir, "training_args.bin")) # Save a trained model and configuration using `save_pretrained()`. # They can then be reloaded using `from_pretrained()` xm.rendezvous("saving_checkpoint") if not isinstance(self.model, PreTrainedModel): if isinstance(unwrap_model(self.model), PreTrainedModel): unwrap_model(self.model).save_pretrained( output_dir, save_config=self.is_world_process_zero(), state_dict=self.model.state_dict(), save_function=xm.save, ) else: logger.info("Trainer.model is not a `PreTrainedModel`, only saving its state dict.") state_dict = self.model.state_dict() xm.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME)) else: self.model.save_pretrained(output_dir, save_config=self.is_world_process_zero(), save_function=xm.save) if self.tokenizer is not None and self.is_world_process_zero(): self.tokenizer.save_pretrained(output_dir) def _save(self, output_dir: Optional[str] = None, state_dict=None): # If we are executing this function, we are the process zero, so we don't check for that. output_dir = output_dir if output_dir is not None else self.args.output_dir os.makedirs(output_dir, exist_ok=True) logger.info(f"Saving model checkpoint to {output_dir}") # Save a trained model and configuration using `save_pretrained()`. # They can then be reloaded using `from_pretrained()` if not isinstance(self.model, PreTrainedModel): if isinstance(unwrap_model(self.model), PreTrainedModel): if state_dict is None: state_dict = self.model.state_dict() unwrap_model(self.model).save_pretrained(output_dir, state_dict=state_dict) else: logger.info("Trainer.model is not a `PreTrainedModel`, only saving its state dict.") if state_dict is None: state_dict = self.model.state_dict() torch.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME)) else: self.model.save_pretrained(output_dir, state_dict=state_dict) if self.tokenizer is not None: self.tokenizer.save_pretrained(output_dir) # Good practice: save your training arguments together with the trained model torch.save(self.args, os.path.join(output_dir, "training_args.bin")) def store_flos(self): # Storing the number of floating-point operations that went into the model if self.args.local_rank != -1: self.state.total_flos += distributed_broadcast_scalars([self.current_flos]).sum().item() self.current_flos = 0 else: self.state.total_flos += self.current_flos self.current_flos = 0 def _sorted_checkpoints( self, output_dir=None, checkpoint_prefix=PREFIX_CHECKPOINT_DIR, use_mtime=False ) -> List[str]: ordering_and_checkpoint_path = [] glob_checkpoints = [str(x) for x in Path(output_dir).glob(f"{checkpoint_prefix}-*")] for path in glob_checkpoints: if use_mtime: ordering_and_checkpoint_path.append((os.path.getmtime(path), path)) else: regex_match = re.match(f".*{checkpoint_prefix}-([0-9]+)", path) if regex_match is not None and regex_match.groups() is not None: ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path)) checkpoints_sorted = sorted(ordering_and_checkpoint_path) checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted] # Make sure we don't delete the best model. if self.state.best_model_checkpoint is not None: best_model_index = checkpoints_sorted.index(str(Path(self.state.best_model_checkpoint))) for i in range(best_model_index, len(checkpoints_sorted) - 2): checkpoints_sorted[i], checkpoints_sorted[i + 1] = checkpoints_sorted[i + 1], checkpoints_sorted[i] return checkpoints_sorted def _rotate_checkpoints(self, use_mtime=False, output_dir=None) -> None: if self.args.save_total_limit is None or self.args.save_total_limit <= 0: return # Check if we should delete older checkpoint(s) checkpoints_sorted = self._sorted_checkpoints(use_mtime=use_mtime, output_dir=output_dir) if len(checkpoints_sorted) <= self.args.save_total_limit: return # If save_total_limit=1 with load_best_mode_at_end=True, we could end up deleting the last checkpoint, which # we don't do to allow resuming. save_total_limit = self.args.save_total_limit if ( self.state.best_model_checkpoint is not None and self.args.save_total_limit == 1 and checkpoints_sorted[-1] != self.state.best_model_checkpoint ): save_total_limit = 2 number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - save_total_limit) checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete] for checkpoint in checkpoints_to_be_deleted: logger.info(f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit") shutil.rmtree(checkpoint) def evaluate( self, eval_dataset: Optional[Dataset] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", ) -> Dict[str, float]: """ Run evaluation and returns metrics. The calling script will be responsible for providing a method to compute metrics, as they are task-dependent (pass it to the init :obj:`compute_metrics` argument). You can also subclass and override this method to inject custom behavior. Args: eval_dataset (:obj:`Dataset`, `optional`): Pass a dataset if you wish to override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`, columns not accepted by the ``model.forward()`` method are automatically removed. It must implement the :obj:`__len__` method. ignore_keys (:obj:`Lst[str]`, `optional`): A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions. metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`"eval"`): An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named "eval_bleu" if the prefix is "eval" (default) Returns: A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The dictionary also contains the epoch number which comes from the training state. """ # memory metrics - must set up as early as possible self._memory_tracker.start() eval_dataloader = self.get_eval_dataloader(eval_dataset) start_time = time.time() eval_loop = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop output = eval_loop( eval_dataloader, description="Evaluation", # No point gathering the predictions if there are no metrics, otherwise we defer to # self.args.prediction_loss_only prediction_loss_only=True if self.compute_metrics is None else None, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix, ) total_batch_size = self.args.eval_batch_size * self.args.world_size output.metrics.update( speed_metrics( metric_key_prefix, start_time, num_samples=output.num_samples, num_steps=math.ceil(output.num_samples / total_batch_size), ) ) self.log(output.metrics) if DebugOption.TPU_METRICS_DEBUG in self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report()) self.control = self.callback_handler.on_evaluate(self.args, self.state, self.control, output.metrics) self._memory_tracker.stop_and_update_metrics(output.metrics) return output.metrics def predict( self, test_dataset: Dataset, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "test" ) -> PredictionOutput: """ Run prediction and returns predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method will also return metrics, like in :obj:`evaluate()`. Args: test_dataset (:obj:`Dataset`): Dataset to run the predictions on. If it is an :obj:`datasets.Dataset`, columns not accepted by the ``model.forward()`` method are automatically removed. Has to implement the method :obj:`__len__` ignore_keys (:obj:`Lst[str]`, `optional`): A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions. metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`"test"`): An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named "test_bleu" if the prefix is "test" (default) .. note:: If your predictions or labels have different sequence length (for instance because you're doing dynamic padding in a token classification task) the predictions will be padded (on the right) to allow for concatenation into one array. The padding index is -100. Returns: `NamedTuple` A namedtuple with the following keys: - predictions (:obj:`np.ndarray`): The predictions on :obj:`test_dataset`. - label_ids (:obj:`np.ndarray`, `optional`): The labels (if the dataset contained some). - metrics (:obj:`Dict[str, float]`, `optional`): The potential dictionary of metrics (if the dataset contained labels). """ # memory metrics - must set up as early as possible self._memory_tracker.start() test_dataloader = self.get_test_dataloader(test_dataset) start_time = time.time() eval_loop = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop output = eval_loop( test_dataloader, description="Prediction", ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix ) total_batch_size = self.args.eval_batch_size * self.args.world_size output.metrics.update( speed_metrics( metric_key_prefix, start_time, num_samples=output.num_samples, num_steps=math.ceil(output.num_samples / total_batch_size), ) ) self._memory_tracker.stop_and_update_metrics(output.metrics) return PredictionOutput(predictions=output.predictions, label_ids=output.label_ids, metrics=output.metrics) def evaluation_loop( self, dataloader: DataLoader, description: str, prediction_loss_only: Optional[bool] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", ) -> EvalLoopOutput: """ Prediction/evaluation loop, shared by :obj:`Trainer.evaluate()` and :obj:`Trainer.predict()`. Works both with or without labels. """ prediction_loss_only = ( prediction_loss_only if prediction_loss_only is not None else self.args.prediction_loss_only ) # if eval is called w/o train init deepspeed here if self.args.deepspeed and not self.deepspeed: # XXX: eval doesn't have `resume_from_checkpoint` arg but we should be able to do eval # from the checkpoint eventually deepspeed_engine, _, _ = deepspeed_init(self, num_training_steps=0, resume_from_checkpoint=None) self.model = deepspeed_engine.module self.model_wrapped = deepspeed_engine self.deepspeed = deepspeed_engine # XXX: we don't need optim/sched for inference, but this needs to be sorted out, since # for example the Z3-optimizer is a must for zero3 to work even for inference - what we # don't need is the deepspeed basic optimizer which is self.optimizer.optimizer deepspeed_engine.optimizer.optimizer = None deepspeed_engine.lr_scheduler = None model = self._wrap_model(self.model, training=False) # if full fp16 is wanted on eval and this ``evaluation`` or ``predict`` isn't called while # ``train`` is running, halve it first and then put on device if not self.is_in_train and self.args.fp16_full_eval: model = model.half().to(self.args.device) batch_size = dataloader.batch_size logger.info(f"***** Running {description} *****") if isinstance(dataloader.dataset, collections.abc.Sized): logger.info(f" Num examples = {self.num_examples(dataloader)}") else: logger.info(" Num examples: Unknown") logger.info(f" Batch size = {batch_size}") model.eval() self.callback_handler.eval_dataloader = dataloader # Do this before wrapping. eval_dataset = dataloader.dataset if is_torch_tpu_available(): dataloader = pl.ParallelLoader(dataloader, [self.args.device]).per_device_loader(self.args.device) if self.args.past_index >= 0: self._past = None # Initialize containers # losses/preds/labels on GPU/TPU (accumulated for eval_accumulation_steps) losses_host = None preds_host = None labels_host = None # losses/preds/labels on CPU (final containers) all_losses = None all_preds = None all_labels = None # Will be useful when we have an iterable dataset so don't know its length. observed_num_examples = 0 # Main evaluation loop for step, inputs in enumerate(dataloader): # Update the observed num examples observed_batch_size = find_batch_size(inputs) if observed_batch_size is not None: observed_num_examples += observed_batch_size # Prediction step loss, logits, labels = self.prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys) # Update containers on host if loss is not None: losses = self._nested_gather(loss.repeat(batch_size)) losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0) if logits is not None: logits = self._pad_across_processes(logits) logits = self._nested_gather(logits) preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100) if labels is not None: labels = self._pad_across_processes(labels) labels = self._nested_gather(labels) labels_host = labels if labels_host is None else nested_concat(labels_host, labels, padding_index=-100) self.control = self.callback_handler.on_prediction_step(self.args, self.state, self.control) # Gather all tensors and put them back on the CPU if we have done enough accumulation steps. if self.args.eval_accumulation_steps is not None and (step + 1) % self.args.eval_accumulation_steps == 0: if losses_host is not None: losses = nested_numpify(losses_host) all_losses = losses if all_losses is None else np.concatenate((all_losses, losses), axis=0) if preds_host is not None: logits = nested_numpify(preds_host) all_preds = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100) if labels_host is not None: labels = nested_numpify(labels_host) all_labels = ( labels if all_labels is None else nested_concat(all_labels, labels, padding_index=-100) ) # Set back to None to begin a new accumulation losses_host, preds_host, labels_host = None, None, None if self.args.past_index and hasattr(self, "_past"): # Clean the state at the end of the evaluation loop delattr(self, "_past") # Gather all remaining tensors and put them back on the CPU if losses_host is not None: losses = nested_numpify(losses_host) all_losses = losses if all_losses is None else np.concatenate((all_losses, losses), axis=0) if preds_host is not None: logits = nested_numpify(preds_host) all_preds = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100) if labels_host is not None: labels = nested_numpify(labels_host) all_labels = labels if all_labels is None else nested_concat(all_labels, labels, padding_index=-100) # Number of samples if not isinstance(eval_dataset, IterableDataset): num_samples = len(eval_dataset) elif isinstance(eval_dataset, IterableDatasetShard): num_samples = eval_dataset.num_examples else: num_samples = observed_num_examples # Number of losses has been rounded to a multiple of batch_size and in a distributed training, the number of # samplers has been rounded to a multiple of batch_size, so we truncate. if all_losses is not None: all_losses = all_losses[:num_samples] if all_preds is not None: all_preds = nested_truncate(all_preds, num_samples) if all_labels is not None: all_labels = nested_truncate(all_labels, num_samples) # Metrics! if self.compute_metrics is not None and all_preds is not None and all_labels is not None: metrics = self.compute_metrics(EvalPrediction(predictions=all_preds, label_ids=all_labels)) else: metrics = {} # To be JSON-serializable, we need to remove numpy types or zero-d tensors metrics = denumpify_detensorize(metrics) if all_losses is not None: metrics[f"{metric_key_prefix}_loss"] = all_losses.mean().item() # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f"{metric_key_prefix}_"): metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key) return EvalLoopOutput(predictions=all_preds, label_ids=all_labels, metrics=metrics, num_samples=num_samples) def _nested_gather(self, tensors, name=None): """ Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before concatenating them to `gathered` """ if tensors is None: return if is_torch_tpu_available(): if name is None: name = "nested_gather" tensors = nested_xla_mesh_reduce(tensors, name) elif is_sagemaker_mp_enabled(): tensors = smp_gather(tensors) elif self.args.local_rank != -1: tensors = distributed_concat(tensors) return tensors # Copied from Accelerate. def _pad_across_processes(self, tensor, pad_index=-100): """ Recursively pad the tensors in a nested list/tuple/dictionary of tensors from all devices to the same size so they can safely be gathered. """ if isinstance(tensor, (list, tuple)): return type(tensor)(self._pad_across_processes(t, pad_index=pad_index) for t in tensor) elif isinstance(tensor, dict): return type(tensor)({k: self._pad_across_processes(v, pad_index=pad_index) for k, v in tensor.items()}) elif not isinstance(tensor, torch.Tensor): raise TypeError( f"Can't pad the values of type {type(tensor)}, only of nested list/tuple/dicts of tensors." ) if len(tensor.shape) < 2: return tensor # Gather all sizes size = torch.tensor(tensor.shape, device=tensor.device)[None] sizes = self._nested_gather(size).cpu() max_size = max(s[1] for s in sizes) if tensor.shape[1] == max_size: return tensor # Then pad to the maximum size old_size = tensor.shape new_size = list(old_size) new_size[1] = max_size new_tensor = tensor.new_zeros(tuple(new_size)) + pad_index new_tensor[:, : old_size[1]] = tensor return new_tensor def prediction_step( self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]], prediction_loss_only: bool, ignore_keys: Optional[List[str]] = None, ) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]: """ Perform an evaluation step on :obj:`model` using obj:`inputs`. Subclass and override to inject custom behavior. Args: model (:obj:`nn.Module`): The model to evaluate. inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model. The dictionary will be unpacked before being fed to the model. Most models expect the targets under the argument :obj:`labels`. Check your model's documentation for all accepted arguments. prediction_loss_only (:obj:`bool`): Whether or not to return the loss only. ignore_keys (:obj:`Lst[str]`, `optional`): A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions. Return: Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]: A tuple with the loss, logits and labels (each being optional). """ has_labels = all(inputs.get(k) is not None for k in self.label_names) inputs = self._prepare_inputs(inputs) if ignore_keys is None: if hasattr(self.model, "config"): ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", []) else: ignore_keys = [] # labels may be popped when computing the loss (label smoothing for instance) so we grab them first. if has_labels: labels = nested_detach(tuple(inputs.get(name) for name in self.label_names)) if len(labels) == 1: labels = labels[0] else: labels = None with torch.no_grad(): if is_sagemaker_mp_enabled(): raw_outputs = smp_forward_only(model, inputs) if has_labels: if isinstance(raw_outputs, dict): loss_mb = raw_outputs["loss"] logits_mb = tuple(v for k, v in raw_outputs.items() if k not in ignore_keys + ["loss"]) else: loss_mb = raw_outputs[0] logits_mb = raw_outputs[1:] loss = loss_mb.reduce_mean().detach().cpu() logits = smp_nested_concat(logits_mb) else: loss = None if isinstance(raw_outputs, dict): logits_mb = tuple(v for k, v in raw_outputs.items() if k not in ignore_keys) else: logits_mb = raw_outputs logits = smp_nested_concat(logits_mb) else: if has_labels: loss, outputs = self.compute_loss(model, inputs, return_outputs=True) loss = loss.mean().detach() if isinstance(outputs, dict): logits = tuple(v for k, v in outputs.items() if k not in ignore_keys + ["loss"]) else: logits = outputs[1:] else: loss = None if self.use_amp: with autocast(): outputs = model(**inputs) else: outputs = model(**inputs) if isinstance(outputs, dict): logits = tuple(v for k, v in outputs.items() if k not in ignore_keys) else: logits = outputs # TODO: this needs to be fixed and made cleaner later. if self.args.past_index >= 0: self._past = outputs[self.args.past_index - 1] if prediction_loss_only: return (loss, None, None) logits = nested_detach(logits) if len(logits) == 1: logits = logits[0] return (loss, logits, labels) def floating_point_ops(self, inputs: Dict[str, Union[torch.Tensor, Any]]): """ For models that inherit from :class:`~transformers.PreTrainedModel`, uses that method to compute the number of floating point operations for every backward + forward pass. If using another model, either implement such a method in the model or subclass and override this method. Args: inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model. Returns: :obj:`int`: The number of floating-point operations. """ if hasattr(self.model, "floating_point_ops"): return self.model.floating_point_ops(inputs) else: return 0 def init_git_repo(self): """ Initializes a git repo in :obj:`self.args.push_to_hub_model_id`. """ if not self.is_world_process_zero(): return use_auth_token = True if self.args.push_to_hub_token is None else self.args.push_to_hub_token repo_url = PushToHubMixin._get_repo_url_from_name( self.args.push_to_hub_model_id, organization=self.args.push_to_hub_organization, use_auth_token=use_auth_token, ) self.repo = PushToHubMixin._create_or_get_repo( self.args.output_dir, repo_url=repo_url, use_auth_token=use_auth_token ) # By default, ignore the checkpoint folders if not os.path.exists(os.path.join(self.args.output_dir, ".gitignore")): with open(os.path.join(self.args.output_dir, ".gitignore"), "w", encoding="utf-8") as writer: writer.writelines(["checkpoint-*/"]) def create_model_card( self, language: Optional[str] = None, license: Optional[str] = None, tags: Optional[str] = None, model_name: Optional[str] = None, finetuned_from: Optional[str] = None, tasks: Optional[str] = None, dataset_tags: Optional[Union[str, List[str]]] = None, dataset: Optional[Union[str, List[str]]] = None, dataset_args: Optional[Union[str, List[str]]] = None, ): training_summary = TrainingSummary.from_trainer( self, language=language, license=license, tags=tags, model_name=model_name, finetuned_from=finetuned_from, tasks=tasks, dataset_tags=dataset_tags, dataset=dataset, dataset_args=dataset_args, ) model_card = training_summary.to_model_card() with open(os.path.join(self.args.output_dir, "README.md"), "w") as f: f.write(model_card) def push_to_hub(self, commit_message: Optional[str] = "add model", **kwargs) -> str: """ Upload `self.model` and `self.tokenizer` to the 🤗 model hub on the repo `self.args.push_to_hub_model_id`. Parameters: commit_message (:obj:`str`, `optional`, defaults to :obj:`"add model"`): Message to commit while pushing. kwargs: Additional keyword arguments passed along to :meth:`~transformers.Trainer.create_model_card`. Returns: The url of the commit of your model in the given repository. """ if not self.is_world_process_zero(): return self.create_model_card(model_name=self.args.push_to_hub_model_id, **kwargs) self.save_model() return self.repo.push_to_hub(commit_message=commit_message) # # Deprecated code # def prediction_loop( self, dataloader: DataLoader, description: str, prediction_loss_only: Optional[bool] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", ) -> PredictionOutput: """ Prediction/evaluation loop, shared by :obj:`Trainer.evaluate()` and :obj:`Trainer.predict()`. Works both with or without labels. """ if not isinstance(dataloader.dataset, collections.abc.Sized): raise ValueError("dataset must implement __len__") prediction_loss_only = ( prediction_loss_only if prediction_loss_only is not None else self.args.prediction_loss_only ) # if eval is called w/o train init deepspeed here if self.args.deepspeed and not self.deepspeed: # XXX: eval doesn't have `resume_from_checkpoint` arg but we should be able to do eval # from the checkpoint eventually deepspeed_engine, _, _ = deepspeed_init(self, num_training_steps=0, resume_from_checkpoint=None) self.model = deepspeed_engine.module self.model_wrapped = deepspeed_engine self.deepspeed = deepspeed_engine # XXX: we don't need optim/sched for inference, but this needs to be sorted out, since # for example the Z3-optimizer is a must for zero3 to work even for inference - what we # don't need is the deepspeed basic optimizer which is self.optimizer.optimizer deepspeed_engine.optimizer.optimizer = None deepspeed_engine.lr_scheduler = None model = self._wrap_model(self.model, training=False) # if full fp16 is wanted on eval and this ``evaluation`` or ``predict`` isn't called while # ``train`` is running, halve it first and then put on device if not self.is_in_train and self.args.fp16_full_eval: model = model.half().to(self.args.device) batch_size = dataloader.batch_size num_examples = self.num_examples(dataloader) logger.info(f"***** Running {description} *****") logger.info(f" Num examples = {num_examples}") logger.info(f" Batch size = {batch_size}") losses_host: torch.Tensor = None preds_host: Union[torch.Tensor, List[torch.Tensor]] = None labels_host: Union[torch.Tensor, List[torch.Tensor]] = None world_size = max(1, self.args.world_size) eval_losses_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=batch_size) if not prediction_loss_only: # The actual number of eval_sample can be greater than num_examples in distributed settings (when we pass # a batch size to the sampler) make_multiple_of = None if hasattr(dataloader, "sampler") and isinstance(dataloader.sampler, SequentialDistributedSampler): make_multiple_of = dataloader.sampler.batch_size preds_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=make_multiple_of) labels_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=make_multiple_of) model.eval() if is_torch_tpu_available(): dataloader = pl.ParallelLoader(dataloader, [self.args.device]).per_device_loader(self.args.device) if self.args.past_index >= 0: self._past = None self.callback_handler.eval_dataloader = dataloader for step, inputs in enumerate(dataloader): loss, logits, labels = self.prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys) if loss is not None: losses = loss.repeat(batch_size) losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0) if logits is not None: preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100) if labels is not None: labels_host = labels if labels_host is None else nested_concat(labels_host, labels, padding_index=-100) self.control = self.callback_handler.on_prediction_step(self.args, self.state, self.control) # Gather all tensors and put them back on the CPU if we have done enough accumulation steps. if self.args.eval_accumulation_steps is not None and (step + 1) % self.args.eval_accumulation_steps == 0: eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, "eval_losses")) if not prediction_loss_only: preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, "eval_preds")) labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, "eval_label_ids")) # Set back to None to begin a new accumulation losses_host, preds_host, labels_host = None, None, None if self.args.past_index and hasattr(self, "_past"): # Clean the state at the end of the evaluation loop delattr(self, "_past") # Gather all remaining tensors and put them back on the CPU eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, "eval_losses")) if not prediction_loss_only: preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, "eval_preds")) labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, "eval_label_ids")) eval_loss = eval_losses_gatherer.finalize() preds = preds_gatherer.finalize() if not prediction_loss_only else None label_ids = labels_gatherer.finalize() if not prediction_loss_only else None if self.compute_metrics is not None and preds is not None and label_ids is not None: metrics = self.compute_metrics(EvalPrediction(predictions=preds, label_ids=label_ids)) else: metrics = {} # To be JSON-serializable, we need to remove numpy types or zero-d tensors metrics = denumpify_detensorize(metrics) if eval_loss is not None: metrics[f"{metric_key_prefix}_loss"] = eval_loss.mean().item() # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f"{metric_key_prefix}_"): metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key) return PredictionOutput(predictions=preds, label_ids=label_ids, metrics=metrics) def _gather_and_numpify(self, tensors, name): """ Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before concatenating them to `gathered` """ if tensors is None: return if is_torch_tpu_available(): tensors = nested_xla_mesh_reduce(tensors, name) elif is_sagemaker_mp_enabled(): tensors = smp_gather(tensors) elif self.args.local_rank != -1: tensors = distributed_concat(tensors) return nested_numpify(tensors)
#!/usr/bin/python3 import logging logging.basicConfig(level=logging.WARNING) import xmlrpc.client import requests, datetime, os, sys from json import dumps, loads from PyQt5 import QtCore, QtWidgets from PyQt5 import uic from PyQt5.QtCore import QDir from PyQt5.QtGui import QFontDatabase def relpath(filename): try: base_path = sys._MEIPASS # pylint: disable=no-member except: base_path = os.path.abspath(".") return os.path.join(base_path, filename) def load_fonts_from_dir(directory): families = set() for fi in QDir(directory).entryInfoList(["*.ttf", "*.woff", "*.woff2"]): _id = QFontDatabase.addApplicationFont(fi.absoluteFilePath()) families |= set(QFontDatabase.applicationFontFamilies(_id)) return families class MainWindow(QtWidgets.QMainWindow): oldfreq = '0' oldmode = 'none' newfreq = '0' newmode = 'none' s=False settings_dict ={ "key": "yourAPIkey", "cloudurl": "http://www.youraddress.com/index.php/api/radio", "radio_name": "IC-7300", "host": "localhost", "port": 12345 } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) uic.loadUi(self.relpath("main.ui"), self) self.settingsbutton.clicked.connect(self.settingspressed) self.server = xmlrpc.client.ServerProxy(f"http://{self.settings_dict["host"]}:{self.settings_dict["port"]}") def relpath(self, filename): """ lets the program know where the temp execution location is. """ try: base_path = sys._MEIPASS # pylint: disable=no-member except: base_path = os.path.abspath(".") return os.path.join(base_path, filename) def loadsaved(self): """ load saved defaults if they exist. otherwise write some sane defaults as a json text file in the users home directory. """ home = os.path.expanduser("~") if os.path.exists(home+"/.cloudlogpycat.json"): with open(home+"/.cloudlogpycat.json", "rt") as f: self.settings_dict = loads(f.read()) else: with open(home+"/.cloudlogpycat.json", "wt") as f: f.write(dumps(self.settings_dict)) self.server = xmlrpc.client.ServerProxy(f"http://{self.settings_dict["host"]}:{self.settings_dict["port"]}") def savestuff(self): """ save state as a json file in the home directory """ home = os.path.expanduser("~") with open(home+"/.cloudlogpycat.json", "wt") as f: f.write(dumps(self.settings_dict)) def settingspressed(self): settingsdialog = settings(self) settingsdialog.exec() self.loadsaved() def rigconnect(self): try: self.newfreq = self.server.rig.get_vfo() self.newmode = self.server.rig.get_mode() self.errorline_label.setText("") except Exception as e: self.errorline_label.setText(f"{e}") def mainloop(self): self.rigconnect() if self.newfreq != self.oldfreq or self.newmode != self.oldmode: self.freq_label.setText(self.newfreq) self.mode_label.setText(self.newmode) ts=datetime.datetime.utcnow().strftime("%Y/%m/%d %H:%M") payload = {'key':self.settings_dict["key"],'radio':self.settings_dict["radio_name"],'frequency':self.newfreq,'mode':self.newmode,'timestamp':ts} r = requests.post(self.settings_dict['cloudurl'], json=payload) self.response_label.setText(str(r.status_code)) self.oldfreq = self.newfreq self.oldmode = self.newmode class settings(QtWidgets.QDialog): settings_dict = {} def __init__(self, parent=None): super().__init__(parent) uic.loadUi(self.relpath("settings.ui"), self) self.buttonBox.accepted.connect(self.saveChanges) self.loadsettings() def relpath(self, filename): """ lets the program know where the temp execution location is. """ try: base_path = sys._MEIPASS # pylint: disable=no-member except: base_path = os.path.abspath(".") return os.path.join(base_path, filename) def loadsettings(self): home = os.path.expanduser("~") if os.path.exists(home+"/.cloudlogpycat.json"): with open(home+"/.cloudlogpycat.json", "rt") as f: self.settings_dict = loads(f.read()) self.radioname_field.setText(self.settings_dict['radio_name']) self.cloudlogapi_field.setText(self.settings_dict['key']) self.cloudlogurl_field.setText(self.settings_dict['cloudurl']) self.rigcontrolip_field.setText(self.settings_dict['host']) self.rigcontrolport_field.setText(str(self.settings_dict['port'])) def saveChanges(self): self.settings_dict['radio_name'] = self.radioname_field.text() self.settings_dict['key'] = self.cloudlogapi_field.text() self.settings_dict['cloudurl'] =self.cloudlogurl_field.text() self.settings_dict['host'] = self.rigcontrolip_field.text() self.settings_dict['port'] = int(self.rigcontrolport_field.text()) home = os.path.expanduser("~") with open(home+"/.cloudlogpycat.json", "wt") as f: f.write(dumps(self.settings_dict)) app = QtWidgets.QApplication(sys.argv) app.setStyle('Fusion') font_dir = relpath("font") families = load_fonts_from_dir(os.fspath(font_dir)) logging.info(families) window = MainWindow() window.show() window.loadsaved() #window.rigconnect() timer = QtCore.QTimer() timer.timeout.connect(window.mainloop) timer.start(1000) app.exec()
#!/usr/bin/python3 import logging logging.basicConfig(level=logging.WARNING) import xmlrpc.client import requests, datetime, os, sys from json import dumps, loads from PyQt5 import QtCore, QtWidgets from PyQt5 import uic from PyQt5.QtCore import QDir from PyQt5.QtGui import QFontDatabase def relpath(filename): try: base_path = sys._MEIPASS # pylint: disable=no-member except: base_path = os.path.abspath(".") return os.path.join(base_path, filename) def load_fonts_from_dir(directory): families = set() for fi in QDir(directory).entryInfoList(["*.ttf", "*.woff", "*.woff2"]): _id = QFontDatabase.addApplicationFont(fi.absoluteFilePath()) families |= set(QFontDatabase.applicationFontFamilies(_id)) return families class MainWindow(QtWidgets.QMainWindow): oldfreq = '0' oldmode = 'none' newfreq = '0' newmode = 'none' s=False settings_dict ={ "key": "yourAPIkey", "cloudurl": "http://www.youraddress.com/index.php/api/radio", "radio_name": "IC-7300", "host": "localhost", "port": 12345 } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) uic.loadUi(self.relpath("main.ui"), self) self.settingsbutton.clicked.connect(self.settingspressed) self.server = xmlrpc.client.ServerProxy(f"http://{self.settings_dict['host']}:{self.settings_dict['port']}") def relpath(self, filename): """ lets the program know where the temp execution location is. """ try: base_path = sys._MEIPASS # pylint: disable=no-member except: base_path = os.path.abspath(".") return os.path.join(base_path, filename) def loadsaved(self): """ load saved defaults if they exist. otherwise write some sane defaults as a json text file in the users home directory. """ home = os.path.expanduser("~") if os.path.exists(home+"/.cloudlogpycat.json"): with open(home+"/.cloudlogpycat.json", "rt") as f: self.settings_dict = loads(f.read()) else: with open(home+"/.cloudlogpycat.json", "wt") as f: f.write(dumps(self.settings_dict)) self.server = xmlrpc.client.ServerProxy(f"http://{self.settings_dict['host']}:{self.settings_dict['port']}") def savestuff(self): """ save state as a json file in the home directory """ home = os.path.expanduser("~") with open(home+"/.cloudlogpycat.json", "wt") as f: f.write(dumps(self.settings_dict)) def settingspressed(self): settingsdialog = settings(self) settingsdialog.exec() self.loadsaved() def rigconnect(self): try: self.newfreq = self.server.rig.get_vfo() self.newmode = self.server.rig.get_mode() self.errorline_label.setText("") except Exception as e: self.errorline_label.setText(f"{e}") def mainloop(self): self.rigconnect() if self.newfreq != self.oldfreq or self.newmode != self.oldmode: self.freq_label.setText(self.newfreq) self.mode_label.setText(self.newmode) ts=datetime.datetime.utcnow().strftime("%Y/%m/%d %H:%M") payload = {'key':self.settings_dict["key"],'radio':self.settings_dict["radio_name"],'frequency':self.newfreq,'mode':self.newmode,'timestamp':ts} r = requests.post(self.settings_dict['cloudurl'], json=payload) self.response_label.setText(str(r.status_code)) self.oldfreq = self.newfreq self.oldmode = self.newmode class settings(QtWidgets.QDialog): settings_dict = {} def __init__(self, parent=None): super().__init__(parent) uic.loadUi(self.relpath("settings.ui"), self) self.buttonBox.accepted.connect(self.saveChanges) self.loadsettings() def relpath(self, filename): """ lets the program know where the temp execution location is. """ try: base_path = sys._MEIPASS # pylint: disable=no-member except: base_path = os.path.abspath(".") return os.path.join(base_path, filename) def loadsettings(self): home = os.path.expanduser("~") if os.path.exists(home+"/.cloudlogpycat.json"): with open(home+"/.cloudlogpycat.json", "rt") as f: self.settings_dict = loads(f.read()) self.radioname_field.setText(self.settings_dict['radio_name']) self.cloudlogapi_field.setText(self.settings_dict['key']) self.cloudlogurl_field.setText(self.settings_dict['cloudurl']) self.rigcontrolip_field.setText(self.settings_dict['host']) self.rigcontrolport_field.setText(str(self.settings_dict['port'])) def saveChanges(self): self.settings_dict['radio_name'] = self.radioname_field.text() self.settings_dict['key'] = self.cloudlogapi_field.text() self.settings_dict['cloudurl'] =self.cloudlogurl_field.text() self.settings_dict['host'] = self.rigcontrolip_field.text() self.settings_dict['port'] = int(self.rigcontrolport_field.text()) home = os.path.expanduser("~") with open(home+"/.cloudlogpycat.json", "wt") as f: f.write(dumps(self.settings_dict)) app = QtWidgets.QApplication(sys.argv) app.setStyle('Fusion') font_dir = relpath("font") families = load_fonts_from_dir(os.fspath(font_dir)) logging.info(families) window = MainWindow() window.show() window.loadsaved() #window.rigconnect() timer = QtCore.QTimer() timer.timeout.connect(window.mainloop) timer.start(1000) app.exec()
from json import JSONDecodeError from urllib.parse import urljoin from uuid import UUID from django.conf import settings from requests import RequestException from requests import get as _get from ..constants import REQUEST_TIMEOUT_SECONDS from .exceptions import GetPaymentError, ParsePaymentError from .types import Payment def get_payment(order_id: UUID, namespace: str, get=_get) -> Payment: try: response = get( url=urljoin(settings.VERKKOKAUPPA_PAYMENT_API_URL, f"admin/{order_id}"), headers={"api-key": settings.VERKKOKAUPPA_API_KEY, "namespace": namespace}, timeout=REQUEST_TIMEOUT_SECONDS, ) json = response.json() if response.status_code != 200: raise GetPaymentError(f"Order creation failed: {json.get("errors")}") return Payment.from_json(json) except (RequestException, JSONDecodeError, ParsePaymentError) as e: raise GetPaymentError("Payment retrieval failed") from e
from json import JSONDecodeError from urllib.parse import urljoin from uuid import UUID from django.conf import settings from requests import RequestException from requests import get as _get from ..constants import REQUEST_TIMEOUT_SECONDS from .exceptions import GetPaymentError, ParsePaymentError from .types import Payment def get_payment(order_id: UUID, namespace: str, get=_get) -> Payment: try: response = get( url=urljoin(settings.VERKKOKAUPPA_PAYMENT_API_URL, f"admin/{order_id}"), headers={"api-key": settings.VERKKOKAUPPA_API_KEY, "namespace": namespace}, timeout=REQUEST_TIMEOUT_SECONDS, ) json = response.json() if response.status_code != 200: raise GetPaymentError(f"Order creation failed: {json.get('errors')}") return Payment.from_json(json) except (RequestException, JSONDecodeError, ParsePaymentError) as e: raise GetPaymentError("Payment retrieval failed") from e
import sys import reconcile.utils.gql as gql import reconcile.queries as queries import reconcile.openshift_base as ob from reconcile.utils.semver_helper import make_semver from reconcile.utils.openshift_resource import (OpenshiftResource as OR, ResourceKeyExistsError) from reconcile.utils.defer import defer from reconcile.utils.sharding import is_in_shard ROLES_QUERY = """ { roles: roles_v1 { name users { github_username } bots { github_username openshift_serviceaccount } access { namespace { name managedRoles cluster { name } } role } } } """ QONTRACT_INTEGRATION = 'openshift-rolebindings' QONTRACT_INTEGRATION_VERSION = make_semver(0, 3, 0) def construct_user_oc_resource(role, user): name = f"{role}-{user}" body = { "apiVersion": "authorization.openshift.io/v1", "kind": "RoleBinding", "metadata": { "name": name }, "roleRef": { "name": role }, "subjects": [ {"kind": "User", "name": user} ] } return OR(body, QONTRACT_INTEGRATION, QONTRACT_INTEGRATION_VERSION, error_details=name), name def construct_sa_oc_resource(role, namespace, sa_name): name = f"{role}-{namespace}-{sa_name}" body = { "apiVersion": "authorization.openshift.io/v1", "kind": "RoleBinding", "metadata": { "name": name }, "roleRef": { "name": role }, "subjects": [ {"kind": "ServiceAccount", "name": sa_name, "namespace": namespace} ], "userNames": [ f"system:serviceaccount:{namespace}:{sa_name}" ] } return OR(body, QONTRACT_INTEGRATION, QONTRACT_INTEGRATION_VERSION, error_details=name), name def fetch_desired_state(ri, oc_map): gqlapi = gql.get_api() roles = gqlapi.query(ROLES_QUERY)['roles'] users_desired_state = [] for role in roles: permissions = [{'cluster': a['namespace']['cluster']['name'], 'namespace': a['namespace']['name'], 'role': a['role']} for a in role['access'] or [] if None not in [a['namespace'], a['role']] and a['namespace'].get('managedRoles')] if not permissions: continue users = [user['github_username'] for user in role['users']] bot_users = [bot['github_username'] for bot in role['bots'] if bot.get('github_username')] users.extend(bot_users) service_accounts = [bot['openshift_serviceaccount'] for bot in role['bots'] if bot.get('openshift_serviceaccount')] for permission in permissions: cluster = permission['cluster'] namespace = permission['namespace'] if not is_in_shard(f"{cluster}/{namespace}"): continue if oc_map and not oc_map.get(cluster): continue for user in users: # used by openshift-users and github integrations # this is just to simplify things a bit on the their side users_desired_state.append({ 'cluster': cluster, 'user': user }) if ri is None: continue oc_resource, resource_name = \ construct_user_oc_resource(permission['role'], user) try: ri.add_desired( cluster, permission['namespace'], 'RoleBinding', resource_name, oc_resource ) except ResourceKeyExistsError: # a user may have a Role assigned to them # from multiple app-interface roles pass for sa in service_accounts: if ri is None: continue namespace, sa_name = sa.split('/') oc_resource, resource_name = \ construct_sa_oc_resource( permission['role'], namespace, sa_name) try: ri.add_desired( permission['cluster'], permission['namespace'], 'RoleBinding', resource_name, oc_resource ) except ResourceKeyExistsError: # a ServiceAccount may have a Role assigned to it # from multiple app-interface roles pass return users_desired_state @defer def run(dry_run, thread_pool_size=10, internal=None, use_jump_host=True, defer=None): namespaces = [namespace_info for namespace_info in queries.get_namespaces() if namespace_info.get('managedRoles') and is_in_shard( f"{namespace_info["cluster"]["name"]}/" + f"{namespace_info["name"]}")] ri, oc_map = ob.fetch_current_state( namespaces=namespaces, thread_pool_size=thread_pool_size, integration=QONTRACT_INTEGRATION, integration_version=QONTRACT_INTEGRATION_VERSION, override_managed_types=['RoleBinding'], internal=internal, use_jump_host=use_jump_host) defer(lambda: oc_map.cleanup()) fetch_desired_state(ri, oc_map) ob.realize_data(dry_run, oc_map, ri) if ri.has_error_registered(): sys.exit(1)
import sys import reconcile.utils.gql as gql import reconcile.queries as queries import reconcile.openshift_base as ob from reconcile.utils.semver_helper import make_semver from reconcile.utils.openshift_resource import (OpenshiftResource as OR, ResourceKeyExistsError) from reconcile.utils.defer import defer from reconcile.utils.sharding import is_in_shard ROLES_QUERY = """ { roles: roles_v1 { name users { github_username } bots { github_username openshift_serviceaccount } access { namespace { name managedRoles cluster { name } } role } } } """ QONTRACT_INTEGRATION = 'openshift-rolebindings' QONTRACT_INTEGRATION_VERSION = make_semver(0, 3, 0) def construct_user_oc_resource(role, user): name = f"{role}-{user}" body = { "apiVersion": "authorization.openshift.io/v1", "kind": "RoleBinding", "metadata": { "name": name }, "roleRef": { "name": role }, "subjects": [ {"kind": "User", "name": user} ] } return OR(body, QONTRACT_INTEGRATION, QONTRACT_INTEGRATION_VERSION, error_details=name), name def construct_sa_oc_resource(role, namespace, sa_name): name = f"{role}-{namespace}-{sa_name}" body = { "apiVersion": "authorization.openshift.io/v1", "kind": "RoleBinding", "metadata": { "name": name }, "roleRef": { "name": role }, "subjects": [ {"kind": "ServiceAccount", "name": sa_name, "namespace": namespace} ], "userNames": [ f"system:serviceaccount:{namespace}:{sa_name}" ] } return OR(body, QONTRACT_INTEGRATION, QONTRACT_INTEGRATION_VERSION, error_details=name), name def fetch_desired_state(ri, oc_map): gqlapi = gql.get_api() roles = gqlapi.query(ROLES_QUERY)['roles'] users_desired_state = [] for role in roles: permissions = [{'cluster': a['namespace']['cluster']['name'], 'namespace': a['namespace']['name'], 'role': a['role']} for a in role['access'] or [] if None not in [a['namespace'], a['role']] and a['namespace'].get('managedRoles')] if not permissions: continue users = [user['github_username'] for user in role['users']] bot_users = [bot['github_username'] for bot in role['bots'] if bot.get('github_username')] users.extend(bot_users) service_accounts = [bot['openshift_serviceaccount'] for bot in role['bots'] if bot.get('openshift_serviceaccount')] for permission in permissions: cluster = permission['cluster'] namespace = permission['namespace'] if not is_in_shard(f"{cluster}/{namespace}"): continue if oc_map and not oc_map.get(cluster): continue for user in users: # used by openshift-users and github integrations # this is just to simplify things a bit on the their side users_desired_state.append({ 'cluster': cluster, 'user': user }) if ri is None: continue oc_resource, resource_name = \ construct_user_oc_resource(permission['role'], user) try: ri.add_desired( cluster, permission['namespace'], 'RoleBinding', resource_name, oc_resource ) except ResourceKeyExistsError: # a user may have a Role assigned to them # from multiple app-interface roles pass for sa in service_accounts: if ri is None: continue namespace, sa_name = sa.split('/') oc_resource, resource_name = \ construct_sa_oc_resource( permission['role'], namespace, sa_name) try: ri.add_desired( permission['cluster'], permission['namespace'], 'RoleBinding', resource_name, oc_resource ) except ResourceKeyExistsError: # a ServiceAccount may have a Role assigned to it # from multiple app-interface roles pass return users_desired_state @defer def run(dry_run, thread_pool_size=10, internal=None, use_jump_host=True, defer=None): namespaces = [namespace_info for namespace_info in queries.get_namespaces() if namespace_info.get('managedRoles') and is_in_shard( f"{namespace_info['cluster']['name']}/" + f"{namespace_info['name']}")] ri, oc_map = ob.fetch_current_state( namespaces=namespaces, thread_pool_size=thread_pool_size, integration=QONTRACT_INTEGRATION, integration_version=QONTRACT_INTEGRATION_VERSION, override_managed_types=['RoleBinding'], internal=internal, use_jump_host=use_jump_host) defer(lambda: oc_map.cleanup()) fetch_desired_state(ri, oc_map) ob.realize_data(dry_run, oc_map, ri) if ri.has_error_registered(): sys.exit(1)
import uuid import time import requests import urllib3 import boto3 import cfnresponse from log_mechanism import LogMechanism from pvwa_integration import PvwaIntegration from dynamo_lock import LockerClient urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) DEBUG_LEVEL_DEBUG = 'debug' # Outputs all information DEFAULT_HEADER = {"content-type": "application/json"} IS_SAFE_HANDLER = True logger = LogMechanism() def lambda_handler(event, context): logger.trace(event, context, caller_name='lambda_handler') try: physical_resource_id = str(uuid.uuid4()) if 'PhysicalResourceId' in event: physical_resource_id = event['PhysicalResourceId'] # only deleting the vault_pass from parameter store if event['RequestType'] == 'Delete': aob_mode = get_aob_mode() logger.info('Delete request received') delete_params = delete_password_from_param_store(aob_mode) if not delete_params: return cfnresponse.send(event, context, cfnresponse.FAILED, "Failed to delete 'AOB_Vault_Pass' from parameter store, see detailed error in logs", {}, physical_resource_id) delete_sessions_table() return cfnresponse.send(event, context, cfnresponse.SUCCESS, None, {}, physical_resource_id) if event['RequestType'] == 'Create': logger.info('Create request received') request_unix_cpm_name = event['ResourceProperties']['CPMUnix'] request_windows_cpm_name = event['ResourceProperties']['CPMWindows'] request_username = event['ResourceProperties']['Username'] request_unix_safe_name = event['ResourceProperties']['UnixSafeName'] request_windows_safe_name = event['ResourceProperties']['WindowsSafeName'] request_pvwa_ip = event['ResourceProperties']['PVWAIP'] request_password = event['ResourceProperties']['Password'] request_key_pair_safe = event['ResourceProperties']['KeyPairSafe'] request_key_pair_name = event['ResourceProperties']['KeyPairName'] request_aws_region_name = event['ResourceProperties']['AWSRegionName'] request_aws_account_id = event['ResourceProperties']['AWSAccountId'] request_s3_bucket_name = event['ResourceProperties']['S3BucketName'] request_verification_key_name = event['ResourceProperties']['PVWAVerificationKeyFileName'] aob_mode = event['ResourceProperties']['Environment'] logger.info('Adding AOB_Vault_Pass to parameter store', DEBUG_LEVEL_DEBUG) is_password_saved = add_param_to_parameter_store(request_password, "AOB_Vault_Pass", "Vault Password") if not is_password_saved: # if password failed to be saved return cfnresponse.send(event, context, cfnresponse.FAILED, "Failed to create Vault user's password in Parameter Store", {}, physical_resource_id) if request_s3_bucket_name == '' and request_verification_key_name != '': raise Exception('Verification Key cannot be empty if S3 Bucket is provided') elif request_s3_bucket_name != '' and request_verification_key_name == '': raise Exception('S3 Bucket cannot be empty if Verification Key is provided') else: logger.info('Adding AOB_mode to parameter store', DEBUG_LEVEL_DEBUG) is_aob_mode_saved = add_param_to_parameter_store(aob_mode, 'AOB_mode', 'Dictates if the solution will work in POC(no SSL) or ' \ 'Production(with SSL) mode') if not is_aob_mode_saved: # if password failed to be saved return cfnresponse.send(event, context, cfnresponse.FAILED, "Failed to create AOB_mode parameter in Parameter Store", {}, physical_resource_id) if aob_mode == 'Production': logger.info('Adding verification key to Parameter Store', DEBUG_LEVEL_DEBUG) is_verification_key_saved = save_verification_key_to_param_store(request_s3_bucket_name, request_verification_key_name) if not is_verification_key_saved: # if password failed to be saved return cfnresponse.send(event, context, cfnresponse.FAILED, "Failed to create PVWA Verification Key in Parameter Store", {}, physical_resource_id) pvwa_integration_class = PvwaIntegration(IS_SAFE_HANDLER, aob_mode) pvwa_url = f"https://{request_pvwa_ip}/PasswordVault" pvwa_session_id = pvwa_integration_class.logon_pvwa(request_username, request_password, pvwa_url, "1") if not pvwa_session_id: return cfnresponse.send(event, context, cfnresponse.FAILED, "Failed to connect to PVWA, see detailed error in logs", {}, physical_resource_id) is_safe_created = create_safe(pvwa_integration_class, request_unix_safe_name, request_unix_cpm_name, request_pvwa_ip, pvwa_session_id, 1) if not is_safe_created: return cfnresponse.send(event, context, cfnresponse.FAILED, f"Failed to create the Safe {request_unix_safe_name}, see detailed error in logs", {}, physical_resource_id) is_safe_created = create_safe(pvwa_integration_class, request_windows_safe_name, request_windows_cpm_name, request_pvwa_ip, pvwa_session_id, 1) if not is_safe_created: return cfnresponse.send(event, context, cfnresponse.FAILED, f"Failed to create the Safe {request_windows_safe_name}, see detailed error in logs", {}, physical_resource_id) if not create_session_table(): return cfnresponse.send(event, context, cfnresponse.FAILED, "Failed to create 'Sessions' table in DynamoDB, see detailed error in logs", {}, physical_resource_id) # Creating KeyPair Safe is_safe_created = create_safe(pvwa_integration_class, request_key_pair_safe, "", request_pvwa_ip, pvwa_session_id) if not is_safe_created: return cfnresponse.send(event, context, cfnresponse.FAILED, f"Failed to create the Key Pairs safe: {request_key_pair_safe}, " \ "see detailed error in logs", {}, physical_resource_id) # key pair is optional parameter if not request_key_pair_name: logger.info("Key Pair name parameter is empty, the solution will not create a new Key Pair") return cfnresponse.send(event, context, cfnresponse.SUCCESS, None, {}, physical_resource_id) aws_key_pair = create_new_key_pair_on_aws(request_key_pair_name) if aws_key_pair is False: # Account already exist, no need to create it, can't insert it to the vault return cfnresponse.send(event, context, cfnresponse.FAILED, f"Failed to create Key Pair {request_key_pair_name} in AWS", {}, physical_resource_id) if aws_key_pair is True: return cfnresponse.send(event, context, cfnresponse.FAILED, f"Key Pair {request_key_pair_name} already exists in AWS", {}, physical_resource_id) # Create the key pair account on KeyPairs vault is_aws_account_created = create_key_pair_in_vault(pvwa_integration_class, pvwa_session_id, request_key_pair_name, aws_key_pair, request_pvwa_ip, request_key_pair_safe, request_aws_account_id, request_aws_region_name) if not is_aws_account_created: return cfnresponse.send(event, context, cfnresponse.FAILED, f"Failed to create Key Pair {request_key_pair_name} in safe " \ f"{request_key_pair_safe}. see detailed error in logs", {}, physical_resource_id) return cfnresponse.send(event, context, cfnresponse.SUCCESS, None, {}, physical_resource_id) except Exception as e: logger.error(f"Exception occurred:{str(e)}:") return cfnresponse.send(event, context, cfnresponse.FAILED, f"Exception occurred: {str(e)}", {}) finally: if 'pvwa_session_id' in locals(): # pvwa_session_id has been declared if pvwa_session_id: # Logging off the session in case of successful logon pvwa_integration_class.logoff_pvwa(pvwa_url, pvwa_session_id) # Creating a safe, if a failure occur, retry 3 time, wait 10 sec. between retries def create_safe(pvwa_integration_class, safe_name, cpm_name, pvwa_ip, session_id, number_of_days_retention=7): logger.trace(pvwa_integration_class, safe_name, cpm_name, pvwa_ip, session_id, number_of_days_retention, caller_name='create_safe') header = DEFAULT_HEADER header.update({"Authorization": session_id}) create_safe_url = f"https://{pvwa_ip}/PasswordVault/WebServices/PIMServices.svc/Safes" # Create new safe, default number of days retention is 7, unless specified otherwise data = f""" {{ "safe":{{ "SafeName":"{safe_name}", "Description":"", "OLACEnabled":false, "ManagingCPM":"{cpm_name}", "NumberOfDaysRetention":"{number_of_days_retention}" }} }} """ for i in range(0, 3): create_safe_rest_response = pvwa_integration_class.call_rest_api_post(create_safe_url, data, header) if create_safe_rest_response.status_code == requests.codes.conflict: logger.info(f"The Safe {safe_name} already exists") return True elif create_safe_rest_response.status_code == requests.codes.bad_request: logger.error(f"Failed to create Safe {safe_name}, error 400: bad request") return False elif create_safe_rest_response.status_code == requests.codes.created: # safe created logger.info(f"Safe {safe_name} was successfully created") return True else: # Error creating safe, retry for 3 times, with 10 seconds between retries logger.error(f"Error creating Safe, status code:{create_safe_rest_response.status_code}, will retry in 10 seconds") if i == 3: logger.error(f"Failed to create safe after several retries, status code:{create_safe_rest_response.status_code}") return False time.sleep(10) # Search if Key pair exist, if not - create it, return the pem key, False for error def create_new_key_pair_on_aws(key_pair_name): logger.trace(key_pair_name, caller_name='create_new_key_pair_on_aws') ec2_client = boto3.client('ec2') # throws exception if key not found, if exception is InvalidKeyPair.Duplicate return True try: logger.info('Creating key pair') key_pair_response = ec2_client.create_key_pair( KeyName=key_pair_name, DryRun=False ) except Exception as e: if e.response["Error"]["Code"] == "InvalidKeyPair.Duplicate": logger.error(f"Key Pair {key_pair_name} already exists") return True logger.error(f'Creating new key pair failed. error code:\n {e.response['Error']['Code']}') return False return key_pair_response["KeyMaterial"] def create_key_pair_in_vault(pvwa_integration_class, session, aws_key_name, private_key_value, pvwa_ip, safe_name, aws_account_id, aws_region_name): logger.trace(pvwa_integration_class, session, aws_key_name, pvwa_ip, safe_name, aws_account_id, aws_region_name, caller_name='create_key_pair_in_vault') header = DEFAULT_HEADER header.update({"Authorization": session}) trimmed_pem_key = str(private_key_value).replace("\n", "\\n") trimmed_pem_key = trimmed_pem_key.replace("\r", "\\r") # AWS.<AWS Account>.<Region name>.<key pair name> unique_user_name = f"AWS.{aws_account_id}.{aws_region_name}.{aws_key_name}" logger.info(f"Creating account with username:{unique_user_name}") url = f"https://{pvwa_ip}/PasswordVault/WebServices/PIMServices.svc/Account" data = f""" {{ "account" : {{ "safe":"{safe_name}", "platformID":"UnixSSHKeys", "address":1.1.1.1, "password":"{trimmed_pem_key}", "username":"{unique_user_name}", "disableAutoMgmt":"true", "disableAutoMgmtReason":"Unmanaged account" }} }} """ rest_response = pvwa_integration_class.call_rest_api_post(url, data, header) if rest_response.status_code == requests.codes.created: logger.info(f"Key Pair created successfully in safe '{safe_name}'") return True elif rest_response.status_code == requests.codes.conflict: logger.info(f"Key Pair created already exists in safe {safe_name}") return True logger.error(f"Failed to create Key Pair in safe {safe_name}, status code:{rest_response.status_code}") return False def create_session_table(): logger.trace(caller_name='create_session_table') try: logger.info('Locking Dynamo Table') sessions_table_lock = LockerClient('Sessions') sessions_table_lock.create_lock_table() except Exception as e: logger.error(f"Failed to create 'Sessions' table in DynamoDB. Exception: {str(e)}") return None logger.info("Table 'Sessions' created successfully") return True def save_verification_key_to_param_store(s3_bucket_name, verification_key_name): logger.trace(s3_bucket_name, verification_key_name, caller_name='save_verification_key_to_param_store') try: logger.info('Downloading verification key from s3') s3_resource = boto3.resource('s3') s3_resource.Bucket(s3_bucket_name).download_file(verification_key_name, '/tmp/server.crt') add_param_to_parameter_store(open('/tmp/server.crt').read(), "AOB_PVWA_Verification_Key", "PVWA Verification Key") except Exception as e: logger.error(f"An error occurred while downloading Verification Key from S3 Bucket - {s3_bucket_name}. Exception: {e}") return False return True def add_param_to_parameter_store(value, parameter_name, parameter_description): logger.trace(parameter_name, parameter_description, caller_name='add_param_to_parameter_store') try: logger.info(f'Adding parameter {parameter_name} to parameter store') ssm_client = boto3.client('ssm') ssm_client.put_parameter( Name=parameter_name, Description=parameter_description, Value=value, Type="SecureString" ) except Exception as e: logger.error(f"Unable to create parameter {parameter_name} in Parameter Store. Exception: {e}") return False return True def delete_password_from_param_store(aob_mode): logger.trace(aob_mode, caller_name='delete_password_from_param_store') try: logger.info('Deleting parameters from parameter store') ssm_client = boto3.client('ssm') ssm_client.delete_parameter( Name='AOB_Vault_Pass' ) logger.info("Parameter 'AOB_Vault_Pass' deleted successfully from Parameter Store") ssm_client.delete_parameter( Name='AOB_mode' ) logger.info("Parameter 'AOB_mode' deleted successfully from Parameter Store") if aob_mode == 'Production': ssm_client.delete_parameter( Name='AOB_PVWA_Verification_Key' ) logger.info("Parameter 'AOB_PVWA_Verification_Key' deleted successfully from Parameter Store") return True except Exception as e: if e.response["Error"]["Code"] == "ParameterNotFound": return True logger.error(f'Failed to delete parameter "Vault_Pass" from Parameter Store. Error code: {e.response['Error']['Code']}') return False def delete_sessions_table(): logger.trace(caller_name='delete_sessions_table') try: logger.info('Deleting Dynamo session table') dynamodb = boto3.resource('dynamodb') sessions_table = dynamodb.Table('Sessions') sessions_table.delete() return except Exception: logger.error("Failed to delete 'Sessions' table from DynamoDB") return def get_aob_mode(): ssm = boto3.client('ssm') ssm_parameter = ssm.get_parameter( Name='AOB_mode' ) aob_mode = ssm_parameter['Parameter']['Value'] return aob_mode
import uuid import time import requests import urllib3 import boto3 import cfnresponse from log_mechanism import LogMechanism from pvwa_integration import PvwaIntegration from dynamo_lock import LockerClient urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) DEBUG_LEVEL_DEBUG = 'debug' # Outputs all information DEFAULT_HEADER = {"content-type": "application/json"} IS_SAFE_HANDLER = True logger = LogMechanism() def lambda_handler(event, context): logger.trace(event, context, caller_name='lambda_handler') try: physical_resource_id = str(uuid.uuid4()) if 'PhysicalResourceId' in event: physical_resource_id = event['PhysicalResourceId'] # only deleting the vault_pass from parameter store if event['RequestType'] == 'Delete': aob_mode = get_aob_mode() logger.info('Delete request received') delete_params = delete_password_from_param_store(aob_mode) if not delete_params: return cfnresponse.send(event, context, cfnresponse.FAILED, "Failed to delete 'AOB_Vault_Pass' from parameter store, see detailed error in logs", {}, physical_resource_id) delete_sessions_table() return cfnresponse.send(event, context, cfnresponse.SUCCESS, None, {}, physical_resource_id) if event['RequestType'] == 'Create': logger.info('Create request received') request_unix_cpm_name = event['ResourceProperties']['CPMUnix'] request_windows_cpm_name = event['ResourceProperties']['CPMWindows'] request_username = event['ResourceProperties']['Username'] request_unix_safe_name = event['ResourceProperties']['UnixSafeName'] request_windows_safe_name = event['ResourceProperties']['WindowsSafeName'] request_pvwa_ip = event['ResourceProperties']['PVWAIP'] request_password = event['ResourceProperties']['Password'] request_key_pair_safe = event['ResourceProperties']['KeyPairSafe'] request_key_pair_name = event['ResourceProperties']['KeyPairName'] request_aws_region_name = event['ResourceProperties']['AWSRegionName'] request_aws_account_id = event['ResourceProperties']['AWSAccountId'] request_s3_bucket_name = event['ResourceProperties']['S3BucketName'] request_verification_key_name = event['ResourceProperties']['PVWAVerificationKeyFileName'] aob_mode = event['ResourceProperties']['Environment'] logger.info('Adding AOB_Vault_Pass to parameter store', DEBUG_LEVEL_DEBUG) is_password_saved = add_param_to_parameter_store(request_password, "AOB_Vault_Pass", "Vault Password") if not is_password_saved: # if password failed to be saved return cfnresponse.send(event, context, cfnresponse.FAILED, "Failed to create Vault user's password in Parameter Store", {}, physical_resource_id) if request_s3_bucket_name == '' and request_verification_key_name != '': raise Exception('Verification Key cannot be empty if S3 Bucket is provided') elif request_s3_bucket_name != '' and request_verification_key_name == '': raise Exception('S3 Bucket cannot be empty if Verification Key is provided') else: logger.info('Adding AOB_mode to parameter store', DEBUG_LEVEL_DEBUG) is_aob_mode_saved = add_param_to_parameter_store(aob_mode, 'AOB_mode', 'Dictates if the solution will work in POC(no SSL) or ' \ 'Production(with SSL) mode') if not is_aob_mode_saved: # if password failed to be saved return cfnresponse.send(event, context, cfnresponse.FAILED, "Failed to create AOB_mode parameter in Parameter Store", {}, physical_resource_id) if aob_mode == 'Production': logger.info('Adding verification key to Parameter Store', DEBUG_LEVEL_DEBUG) is_verification_key_saved = save_verification_key_to_param_store(request_s3_bucket_name, request_verification_key_name) if not is_verification_key_saved: # if password failed to be saved return cfnresponse.send(event, context, cfnresponse.FAILED, "Failed to create PVWA Verification Key in Parameter Store", {}, physical_resource_id) pvwa_integration_class = PvwaIntegration(IS_SAFE_HANDLER, aob_mode) pvwa_url = f"https://{request_pvwa_ip}/PasswordVault" pvwa_session_id = pvwa_integration_class.logon_pvwa(request_username, request_password, pvwa_url, "1") if not pvwa_session_id: return cfnresponse.send(event, context, cfnresponse.FAILED, "Failed to connect to PVWA, see detailed error in logs", {}, physical_resource_id) is_safe_created = create_safe(pvwa_integration_class, request_unix_safe_name, request_unix_cpm_name, request_pvwa_ip, pvwa_session_id, 1) if not is_safe_created: return cfnresponse.send(event, context, cfnresponse.FAILED, f"Failed to create the Safe {request_unix_safe_name}, see detailed error in logs", {}, physical_resource_id) is_safe_created = create_safe(pvwa_integration_class, request_windows_safe_name, request_windows_cpm_name, request_pvwa_ip, pvwa_session_id, 1) if not is_safe_created: return cfnresponse.send(event, context, cfnresponse.FAILED, f"Failed to create the Safe {request_windows_safe_name}, see detailed error in logs", {}, physical_resource_id) if not create_session_table(): return cfnresponse.send(event, context, cfnresponse.FAILED, "Failed to create 'Sessions' table in DynamoDB, see detailed error in logs", {}, physical_resource_id) # Creating KeyPair Safe is_safe_created = create_safe(pvwa_integration_class, request_key_pair_safe, "", request_pvwa_ip, pvwa_session_id) if not is_safe_created: return cfnresponse.send(event, context, cfnresponse.FAILED, f"Failed to create the Key Pairs safe: {request_key_pair_safe}, " \ "see detailed error in logs", {}, physical_resource_id) # key pair is optional parameter if not request_key_pair_name: logger.info("Key Pair name parameter is empty, the solution will not create a new Key Pair") return cfnresponse.send(event, context, cfnresponse.SUCCESS, None, {}, physical_resource_id) aws_key_pair = create_new_key_pair_on_aws(request_key_pair_name) if aws_key_pair is False: # Account already exist, no need to create it, can't insert it to the vault return cfnresponse.send(event, context, cfnresponse.FAILED, f"Failed to create Key Pair {request_key_pair_name} in AWS", {}, physical_resource_id) if aws_key_pair is True: return cfnresponse.send(event, context, cfnresponse.FAILED, f"Key Pair {request_key_pair_name} already exists in AWS", {}, physical_resource_id) # Create the key pair account on KeyPairs vault is_aws_account_created = create_key_pair_in_vault(pvwa_integration_class, pvwa_session_id, request_key_pair_name, aws_key_pair, request_pvwa_ip, request_key_pair_safe, request_aws_account_id, request_aws_region_name) if not is_aws_account_created: return cfnresponse.send(event, context, cfnresponse.FAILED, f"Failed to create Key Pair {request_key_pair_name} in safe " \ f"{request_key_pair_safe}. see detailed error in logs", {}, physical_resource_id) return cfnresponse.send(event, context, cfnresponse.SUCCESS, None, {}, physical_resource_id) except Exception as e: logger.error(f"Exception occurred:{str(e)}:") return cfnresponse.send(event, context, cfnresponse.FAILED, f"Exception occurred: {str(e)}", {}) finally: if 'pvwa_session_id' in locals(): # pvwa_session_id has been declared if pvwa_session_id: # Logging off the session in case of successful logon pvwa_integration_class.logoff_pvwa(pvwa_url, pvwa_session_id) # Creating a safe, if a failure occur, retry 3 time, wait 10 sec. between retries def create_safe(pvwa_integration_class, safe_name, cpm_name, pvwa_ip, session_id, number_of_days_retention=7): logger.trace(pvwa_integration_class, safe_name, cpm_name, pvwa_ip, session_id, number_of_days_retention, caller_name='create_safe') header = DEFAULT_HEADER header.update({"Authorization": session_id}) create_safe_url = f"https://{pvwa_ip}/PasswordVault/WebServices/PIMServices.svc/Safes" # Create new safe, default number of days retention is 7, unless specified otherwise data = f""" {{ "safe":{{ "SafeName":"{safe_name}", "Description":"", "OLACEnabled":false, "ManagingCPM":"{cpm_name}", "NumberOfDaysRetention":"{number_of_days_retention}" }} }} """ for i in range(0, 3): create_safe_rest_response = pvwa_integration_class.call_rest_api_post(create_safe_url, data, header) if create_safe_rest_response.status_code == requests.codes.conflict: logger.info(f"The Safe {safe_name} already exists") return True elif create_safe_rest_response.status_code == requests.codes.bad_request: logger.error(f"Failed to create Safe {safe_name}, error 400: bad request") return False elif create_safe_rest_response.status_code == requests.codes.created: # safe created logger.info(f"Safe {safe_name} was successfully created") return True else: # Error creating safe, retry for 3 times, with 10 seconds between retries logger.error(f"Error creating Safe, status code:{create_safe_rest_response.status_code}, will retry in 10 seconds") if i == 3: logger.error(f"Failed to create safe after several retries, status code:{create_safe_rest_response.status_code}") return False time.sleep(10) # Search if Key pair exist, if not - create it, return the pem key, False for error def create_new_key_pair_on_aws(key_pair_name): logger.trace(key_pair_name, caller_name='create_new_key_pair_on_aws') ec2_client = boto3.client('ec2') # throws exception if key not found, if exception is InvalidKeyPair.Duplicate return True try: logger.info('Creating key pair') key_pair_response = ec2_client.create_key_pair( KeyName=key_pair_name, DryRun=False ) except Exception as e: if e.response["Error"]["Code"] == "InvalidKeyPair.Duplicate": logger.error(f"Key Pair {key_pair_name} already exists") return True logger.error(f'Creating new key pair failed. error code:\n {e.response["Error"]["Code"]}') return False return key_pair_response["KeyMaterial"] def create_key_pair_in_vault(pvwa_integration_class, session, aws_key_name, private_key_value, pvwa_ip, safe_name, aws_account_id, aws_region_name): logger.trace(pvwa_integration_class, session, aws_key_name, pvwa_ip, safe_name, aws_account_id, aws_region_name, caller_name='create_key_pair_in_vault') header = DEFAULT_HEADER header.update({"Authorization": session}) trimmed_pem_key = str(private_key_value).replace("\n", "\\n") trimmed_pem_key = trimmed_pem_key.replace("\r", "\\r") # AWS.<AWS Account>.<Region name>.<key pair name> unique_user_name = f"AWS.{aws_account_id}.{aws_region_name}.{aws_key_name}" logger.info(f"Creating account with username:{unique_user_name}") url = f"https://{pvwa_ip}/PasswordVault/WebServices/PIMServices.svc/Account" data = f""" {{ "account" : {{ "safe":"{safe_name}", "platformID":"UnixSSHKeys", "address":1.1.1.1, "password":"{trimmed_pem_key}", "username":"{unique_user_name}", "disableAutoMgmt":"true", "disableAutoMgmtReason":"Unmanaged account" }} }} """ rest_response = pvwa_integration_class.call_rest_api_post(url, data, header) if rest_response.status_code == requests.codes.created: logger.info(f"Key Pair created successfully in safe '{safe_name}'") return True elif rest_response.status_code == requests.codes.conflict: logger.info(f"Key Pair created already exists in safe {safe_name}") return True logger.error(f"Failed to create Key Pair in safe {safe_name}, status code:{rest_response.status_code}") return False def create_session_table(): logger.trace(caller_name='create_session_table') try: logger.info('Locking Dynamo Table') sessions_table_lock = LockerClient('Sessions') sessions_table_lock.create_lock_table() except Exception as e: logger.error(f"Failed to create 'Sessions' table in DynamoDB. Exception: {str(e)}") return None logger.info("Table 'Sessions' created successfully") return True def save_verification_key_to_param_store(s3_bucket_name, verification_key_name): logger.trace(s3_bucket_name, verification_key_name, caller_name='save_verification_key_to_param_store') try: logger.info('Downloading verification key from s3') s3_resource = boto3.resource('s3') s3_resource.Bucket(s3_bucket_name).download_file(verification_key_name, '/tmp/server.crt') add_param_to_parameter_store(open('/tmp/server.crt').read(), "AOB_PVWA_Verification_Key", "PVWA Verification Key") except Exception as e: logger.error(f"An error occurred while downloading Verification Key from S3 Bucket - {s3_bucket_name}. Exception: {e}") return False return True def add_param_to_parameter_store(value, parameter_name, parameter_description): logger.trace(parameter_name, parameter_description, caller_name='add_param_to_parameter_store') try: logger.info(f'Adding parameter {parameter_name} to parameter store') ssm_client = boto3.client('ssm') ssm_client.put_parameter( Name=parameter_name, Description=parameter_description, Value=value, Type="SecureString" ) except Exception as e: logger.error(f"Unable to create parameter {parameter_name} in Parameter Store. Exception: {e}") return False return True def delete_password_from_param_store(aob_mode): logger.trace(aob_mode, caller_name='delete_password_from_param_store') try: logger.info('Deleting parameters from parameter store') ssm_client = boto3.client('ssm') ssm_client.delete_parameter( Name='AOB_Vault_Pass' ) logger.info("Parameter 'AOB_Vault_Pass' deleted successfully from Parameter Store") ssm_client.delete_parameter( Name='AOB_mode' ) logger.info("Parameter 'AOB_mode' deleted successfully from Parameter Store") if aob_mode == 'Production': ssm_client.delete_parameter( Name='AOB_PVWA_Verification_Key' ) logger.info("Parameter 'AOB_PVWA_Verification_Key' deleted successfully from Parameter Store") return True except Exception as e: if e.response["Error"]["Code"] == "ParameterNotFound": return True logger.error(f'Failed to delete parameter "Vault_Pass" from Parameter Store. Error code: {e.response["Error"]["Code"]}') return False def delete_sessions_table(): logger.trace(caller_name='delete_sessions_table') try: logger.info('Deleting Dynamo session table') dynamodb = boto3.resource('dynamodb') sessions_table = dynamodb.Table('Sessions') sessions_table.delete() return except Exception: logger.error("Failed to delete 'Sessions' table from DynamoDB") return def get_aob_mode(): ssm = boto3.client('ssm') ssm_parameter = ssm.get_parameter( Name='AOB_mode' ) aob_mode = ssm_parameter['Parameter']['Value'] return aob_mode
import math from collections.abc import Iterable from operator import itemgetter import random import os from glob import glob from .geom import hflip_pattern, vflip_pattern, rot_pattern from .error import GollyPatternsError def get_patterns(): patternfiles = glob( os.path.join(os.path.dirname(os.path.abspath(__file__)), "patterns", "*.txt") ) # trim extension patternfiles = [os.path.basename(os.path.splitext(p)[0]) for p in patternfiles] return patternfiles def get_pattern(pattern_name, hflip=False, vflip=False, rotdeg=0): """ For a given pattern, return the .o diagram as a list of strings, one string = one row """ fname = os.path.join( os.path.dirname(os.path.abspath(__file__)), "patterns", pattern_name + ".txt" ) if os.path.exists(fname): with open(fname, "r") as f: pattern = f.readlines() pattern = [r.strip() for r in pattern] if hflip: pattern = hflip_pattern(pattern) if vflip: pattern = vflip_pattern(pattern) if rotdeg: pattern = rot_pattern(pattern, rotdeg) return pattern else: raise GollyPatternsError(f"Error: pattern {fname} does not exist!") def get_pattern_size(pattern_name, **kwargs): """ Returns: (nrows, ncols) """ pattern = get_pattern(pattern_name, **kwargs) return (len(pattern), len(pattern[0])) def get_pattern_livecount(pattern_name, **kwargs): """ Returns: count of live cells in the given pattern """ pattern = get_pattern(pattern_name, **kwargs) count = 0 for row in pattern: for j in row: if j == "o": count += 1 return count def get_grid_empty(rows, columns, flat=True): if columns < 1 or rows < 1: err = f"Error: invalid number of rows {rows} or columns {columns}, must be positive integers > 0" raise GollyPatternsError(err) blank_row = ["."] * columns blank_grid = [blank_row[:] for r in range(rows)] if flat: blank_grid = ["".join(gridrow) for gridrow in blank_grid] return blank_grid def get_grid_pattern( pattern_name, rows, columns, xoffset=0, yoffset=0, hflip=False, vflip=False, rotdeg=0, check_overflow=True, ): """ Get the pattern corresponding to pattern_name, and place it on a grid of size (rows x columns) at the given offset. If check_overflow is False, the pattern added may be partially or fully outside of the specified grid. """ # TODO: add check of rows/columns, and whether this pattern # will actually fit on the specified grid size. if columns < 1 or rows < 1: err = f"Error: invalid number of rows {rows} or columns {columns}, must be positive integers > 0" raise GollyPatternsError(err) # convert list of strings to list of lists (for convenience) ogpattern = get_pattern(pattern_name, hflip=hflip, vflip=vflip, rotdeg=rotdeg) ogpattern = [list(j) for j in ogpattern] blank_row = ["."] * columns newpattern = [blank_row[:] for r in range(rows)] (pattern_h, pattern_w) = (len(ogpattern), len(ogpattern[0])) # given offset is offset for the center of the pattern, # so do some algebra to determine where we should start xstart = xoffset - pattern_w // 2 xend = xstart + pattern_w ystart = yoffset - pattern_h // 2 yend = ystart + pattern_h # Check size of pattern if check_overflow: if xstart < 0: raise GollyPatternsError( f"Error: specified offset {xoffset} is too small, need at least {pattern_w//2}" ) if xend >= columns: raise GollyPatternsError( f"Error: specified number of columns {columns} was too small, need at least {xend+1}" ) if ystart < 0: raise GollyPatternsError( f"Error: specified offset {yoffset} is too small, need at least {pattern_h//2}" ) if yend >= rows: raise GollyPatternsError( f"Error: specified number of rows {rows} was too small, need at least {yend+1}" ) # iterate through the pattern and copy over the cells that are in the final grid for iy, y in enumerate(range(ystart, yend)): if y > 0 and y < len(newpattern): for ix, x in enumerate(range(xstart, xend)): if x > 0 and x < len(newpattern[iy]): newpattern[y][x] = ogpattern[iy][ix] newpattern = ["".join(j) for j in newpattern] return newpattern def pattern_union(patterns): for i in range(1, len(patterns)): axis0different = len(patterns[i - 1]) != len(patterns[i]) axis1different = len(patterns[i - 1][0]) != len(patterns[i][0]) if axis0different or axis1different: err = "Error: pattern_union() received patterns of dissimilar size" err += "\n" for i in range(1, len(patterns)): err += f"Pattern {i+1}: rows = {len(patterns[i])}, cols = {len(patterns[i][0])}" err += "\n" raise GollyPatternsError(err) # Turn all patterns into lists of lists (for convenience) rows = len(patterns[0]) cols = len(patterns[0][0]) newpatterns = [] for pattern in patterns: newpatterns.append([list(j) for j in pattern]) patterns = newpatterns blank_row = ["."] * cols newpattern = [blank_row[:] for r in range(rows)] for iy in range(rows): for ix in range(cols): alive = False for ip, pattern in enumerate(patterns): if pattern[iy][ix] == "o": alive = True break if alive: newpattern[iy][ix] = "o" newpattern = ["".join(j) for j in newpattern] return newpattern def segment_pattern( rows, cols, seed=None, colormode=None, jitterx=0, jittery=0, nhseg=0, nvseg=0, gap_probability=None, ): """ Return a two-color pattern consisting of nhseg horizontal segments and nvseg vertical segments. In classic color mode, each segment piece is assigned to a single team. In classic broken mode, each segment piece is assigned to a single team, with some dead cells. In random color mode, each segment cell is assigned random teams. In random broken mode, each segment cell is assigned random teams, with some dead cells. gap probability dictates how often gaps occur. If there are too many gaps, maps get boring! """ valid_colormodes = ["classic", "classicbroken", "random", "randombroken"] if colormode not in valid_colormodes: raise GollyPatternsError( f"Error: invalid color mode {colormode} passed to _segment(), must be in {", ".join(valid_colormodes)}" ) if nhseg == 0 and nvseg == 0: raise GollyPatternsError( "Error: invalid number of segments (0 horizontal and 0 vertical) passed to _segment()" ) if gap_probability is None: # Defaults for gap probability if colormode in ["classicbroken", "randombroken"]: gap_probability = 0.05 else: gap_probability = 0.0 elif gap_probability < 0 or gap_probability > 1: raise GollyPatternsError( f"Error: specified gap probability for segment is invalid: {gap_probability}" ) # Get the snap-to-grid centers hsegcenters = [(iy + 1) * rows // (nhseg + 1) - 1 for iy in range(nhseg)] vsegcenters = [(ix + 1) * cols // (nvseg + 1) - 1 for ix in range(nvseg)] # Add jitter, and bookend with 0 and nrows/ncols hseglocs = ( [-1] + [k + random.randint(-jittery, jittery) for k in hsegcenters] + [rows] ) vseglocs = ( [-1] + [k + random.randint(-jitterx, jitterx) for k in vsegcenters] + [cols] ) loclenlist = [] # Construct vertical segments first: # ---------------- # Horizontal segment locations give us the start/end coordinates for vertical segments # Skip the first loc - it's 1 past the edge so the segments start at 0 for ih in range(1, len(hseglocs)): yend = hseglocs[ih] - 1 ystart = hseglocs[ih - 1] + 1 mag = yend - ystart + 1 # Skip the first vseg loc - it's 1 past the edge # Skip the last vseg loc - it's also 1 past the edge for iv in range(1, len(vseglocs) - 1): x = vseglocs[iv] loclenlist.append((ystart, yend, x, x, mag)) # Construct horizontal segments: # ---------------- for iv in range(1, len(vseglocs)): xend = vseglocs[iv] - 1 xstart = vseglocs[iv - 1] + 1 mag = xend - xstart + 1 for ih in range(1, len(hseglocs) - 1): y = hseglocs[ih] loclenlist.append((y, y, xstart, xend, mag)) # These store the the .o diagrams (flat=False means these are lists of lists of one char) team1_pattern = get_grid_empty(rows, cols, flat=False) team2_pattern = get_grid_empty(rows, cols, flat=False) # Color mode: # ------------------------ # We have a list of segments, coordinates and lengths, # now the way we populate the map depends on the color mode. if colormode in ["classic", "classicbroken"]: # Classic/classic broken color mode: # Each segment is a single solid color, # use serpentine pattern to assign colors. # If broken, use 0s to represent dead cells. serpentine_pattern = [1, 2, 2, 1] from operator import itemgetter random.shuffle(loclenlist) loclenlist.sort(key=itemgetter(4), reverse=True) for i, (starty, endy, startx, endx, mag) in enumerate(loclenlist): serpix = i % len(serpentine_pattern) serpteam = serpentine_pattern[serpix] magon = math.floor((1 - gap_probability) * mag) rem = mag - magon team_assignments = [serpteam,] * magon + [ 0, ] * rem # noqa random.shuffle(team_assignments) ta_ix = 0 for y in range(starty, endy + 1): for x in range(startx, endx + 1): if team_assignments[ta_ix] == 1: team1_pattern[y][x] = "o" elif team_assignments[ta_ix] == 2: team2_pattern[y][x] = "o" ta_ix += 1 elif colormode in ["random", "randombroken"]: # Random/random broken color mode: # For each segment of length N, # create an array of N/2 zeros and N/2 ones, # shuffle it, use it to assign colors. # If broken, include 0s to represent dead cells for i, (starty, endy, startx, endx, mag) in enumerate(loclenlist): magh = math.floor(0.5 * (1 - gap_probability) * mag) rem = mag - (2*magh) team_assignments = ( [ 1, ] * magh + [ 2, ] * magh + [ 0, ] * rem ) # noqa random.shuffle(team_assignments) ta_ix = 0 for y in range(starty, endy + 1): if y >= rows: continue for x in range(startx, endx + 1): if x >= cols: continue if team_assignments[ta_ix] == 1: team1_pattern[y][x] = "o" elif team_assignments[ta_ix] == 2: team2_pattern[y][x] = "o" ta_ix += 1 team1_pattern = ["".join(pattrow) for pattrow in team1_pattern] team2_pattern = ["".join(pattrow) for pattrow in team2_pattern] return team1_pattern, team2_pattern def metheusela_quadrants_pattern( rows, cols, seed=None, metheusela_counts=None, fixed_metheusela=None ): """ Returns a map with a cluster of metheuselas in each quadrant. The methesela_counts parameter determines how many metheuselas may be put in each corner. Valid configurations: 1 (placed in center of quadrant) 2 (placed on opposite corners of a four-point square formed by cutting quadrant into thirds 4 (placed on all corners of four-point square) 3 (placed on diagonal of square with 3 points per edge, or 8 points) 9 (placed on all corners and center of 8-point square) 16 (placed on a 4x4 grid) Procedure: First randomly pair quadrants so their metheusela counts will match. Next, place random metheusela patterns in each of the corners. """ if seed is not None: random.seed(seed) # Basic checks BIGDIMLIMIT = 150 mindim = min(rows, cols) if metheusela_counts is None: if mindim < BIGDIMLIMIT: metheusela_counts = [1, 2, 3, 4, 9] else: metheusela_counts = [1, 2, 3, 4, 9, 16] valid_mc = [1, 2, 3, 4, 9, 16] for mc in metheusela_counts: if mc not in valid_mc: msg = "Invalid metheusela counts passed: must be in {', '.join(valid_mc)}\n" msg += "you specified {', '.join(metheusela_counts)}" raise GollyPatternsError(msg) if 16 in metheusela_counts and min(rows, cols) < BIGDIMLIMIT: msg = "Invalid metheusela count specified: grid size too small for 4x4!" raise GollyPatternsError(msg) metheusela_names = [ "acorn", "bheptomino", "cheptomino", "eheptomino", "multuminparvo", "piheptomino", "rabbit", "rpentomino", "timebomb", "switchengine", ] small_metheusela_names = [ "bheptomino", "cheptomino", "eheptomino", "piheptomino", "rpentomino", ] # Store each quadrant and its upper left corner in (rows from top, cols from left) format quadrants = [ (1, (0, cols // 2)), (2, (0, 0)), (3, (rows // 2, 0)), (4, (rows // 2, cols // 2)), ] # Shuffle quadrants, first two and second two are now paired up as buddies random.shuffle(quadrants) rotdegs = [0, 90, 180, 270] all_metheuselas = [] for buddy_index in [[0, 1], [2, 3]]: # Decide how many metheuselas in this quad pair count = random.choice(metheusela_counts) if count == 1: # Only one metheusela in this quadrant, so use the center jitterx = 15 jittery = 15 for bi in buddy_index: corner = quadrants[bi][1] y = corner[0] + rows // 4 +random.randint(-jittery, jittery) x = corner[1] + cols // 4 + random.randint(-jitterx, jitterx) if fixed_metheusela: meth = fixed_metheusela else: meth = random.choice(metheusela_names) pattern = get_grid_pattern( meth, rows, cols, xoffset=x, yoffset=y, hflip=bool(random.getrandbits(1)), vflip=bool(random.getrandbits(1)), rotdeg=random.choice(rotdegs), ) livecount = get_pattern_livecount(meth) all_metheuselas.append((livecount, pattern)) elif count == 2 or count == 4: # Two or four metheuselas in this quadrant, so place at corners of a square # Form the square by cutting the quadrant into thirds if count == 4: jitterx = 2 jittery = 2 else: jitterx = 5 jittery = 5 for bi in buddy_index: corner = quadrants[bi][1] # Slices and partitions form the inside square nslices = 2 nparts = nslices + 1 posdiag = bool(random.getrandbits(1)) for a in range(1, nparts): for b in range(1, nparts): proceed = False if count == 2: if (posdiag and a == b) or ( not posdiag and a == (nslices - b + 1) ): proceed = True elif count == 4: proceed = True if proceed: y = corner[0] + a * ((rows // 2) // nparts) + random.randint(-jittery, jittery) x = corner[1] + b * ((cols // 2) // nparts) + random.randint(-jitterx, jitterx) if fixed_metheusela: meth = fixed_metheusela else: meth = random.choice(metheusela_names) try: pattern = get_grid_pattern( meth, rows, cols, xoffset=x, yoffset=y, hflip=bool(random.getrandbits(1)), vflip=bool(random.getrandbits(1)), rotdeg=random.choice(rotdegs), ) except GollyPatternsError: raise GollyPatternsError( f"Error with metheusela {meth}: cannot fit" ) livecount = get_pattern_livecount(meth) all_metheuselas.append((livecount, pattern)) elif count == 3 or count == 9: # Three or nine metheuselas, place these on a square with three points per side # or eight points total if count == 9: jitterx = 2 jittery = 2 else: jitterx = 4 jittery = 4 for bi in buddy_index: corner = quadrants[bi][1] nslices = 4 for a in range(1, nslices): for b in range(1, nslices): proceed = False if count == 3: if a == b: proceed = True elif count == 9: proceed = True if proceed: y = corner[0] + a * ((rows // 2) // nslices) + random.randint(-jittery, jittery) x = corner[1] + b * ((cols // 2) // nslices) + random.randint(-jitterx, jitterx) if fixed_metheusela: meth = fixed_metheusela elif min(rows, cols) < BIGDIMLIMIT: meth = random.choice(small_metheusela_names) else: meth = random.choice(metheusela_names) try: pattern = get_grid_pattern( meth, rows, cols, xoffset=x, yoffset=y, hflip=bool(random.getrandbits(1)), vflip=bool(random.getrandbits(1)), rotdeg=random.choice(rotdegs), ) except GollyPatternsError: raise GollyPatternsError( f"Error with metheusela {meth}: cannot fit" ) livecount = get_pattern_livecount(meth) all_metheuselas.append((livecount, pattern)) elif count == 16: # Sixteen metheuselas, place these on a 4x4 square jitterx = 1 jittery = 1 for bi in buddy_index: corner = quadrants[bi][1] nslices = 5 for a in range(1, nslices): for b in range(1, nslices): y = corner[0] + a * ((rows // 2) // nslices) + random.randint(-jittery, jittery) x = corner[1] + b * ((cols // 2) // nslices) + random.randint(-jitterx, jitterx) if fixed_metheusela: meth = fixed_metheusela else: meth = random.choice(small_metheusela_names) try: pattern = get_grid_pattern( meth, rows, cols, xoffset=x, yoffset=y, hflip=bool(random.getrandbits(1)), vflip=bool(random.getrandbits(1)), rotdeg=random.choice(rotdegs), ) except GollyPatternsError: raise GollyPatternsError( f"Error with metheusela {meth}: cannot fit" ) livecount = get_pattern_livecount(meth) all_metheuselas.append((livecount, pattern)) random.shuffle(all_metheuselas) all_metheuselas.sort(key=itemgetter(0), reverse=True) team1_patterns = [] team2_patterns = [] serpentine_pattern = [1, 2, 2, 1] for i, (_, metheusela_pattern) in enumerate(all_metheuselas): serpix = i % len(serpentine_pattern) serpteam = serpentine_pattern[serpix] if serpteam == 1: team1_patterns.append(metheusela_pattern) elif serpteam == 2: team2_patterns.append(metheusela_pattern) team1_pattern = pattern_union(team1_patterns) team2_pattern = pattern_union(team2_patterns) return team1_pattern, team2_pattern def cloud_region( which_pattern, dims, xlim, ylim, margins, jitter, flip, distancing=True ): """ Given a square region defined by the x and y limits, tile the region with copies of the specified pattern, plus jitter. Parameters: dims (rows, cols) list/tuple xlim (xstart, xend) list/tuple ylim (ystart, yend) list/tuple margins integer or (N, E, S, W) list/tuple jitter (xjitter, yjitter) list/tuple flip (do_hflip, do_vflip) list/tuple distancing boolean: if true, add an extra margin of cells (eliminates overlap in starting positions) (off is more chaotic, on is more ordered) """ if len(dims) != 2: err = "Error: could not understand dimensions input, provide (rows, cols)" raise Exception(err) rows, cols = dims[0], dims[1] if len(xlim) != 2 or len(ylim) != 2: err = "Error: could not understand xlim/ylim input, provide (xstart, xend) and (ystart, yend)" raise Exception(err) # Unpack margins if isinstance(margins, Iterable): if len(margins) != 4: err = "Error: could not understand margins input, provide single value or list of 4 values" raise Exception(err) # list of 4 values in order N E S W north = margins[0] east = margins[1] south = margins[2] west = margins[3] else: # single value, uniform margin margins = int(margins) north = east = south = west = margins # Unpack jitter if isinstance(jitter, Iterable): if len(jitter) != 2: err = "Error: could not understand jitter input, provide two values (xjitter, yjitter)" raise Exception(err) x_jitter = jitter[0] y_jitter = jitter[1] else: jitter = int(jitter) x_jitter = y_jitter = jitter # Get whether to hflip or vflip if len(flip) != 2: err = "Error: could not understand flip input, provide two values (do_hflip, do_vflip)" raise Exception(err) do_hflip = flip[0] do_vflip = flip[1] # Determine the core xlim and ylim core_xlim = [xlim[0] + west, xlim[1] - east] core_w = core_xlim[1] - core_xlim[0] if core_w < 0: t = core_xlim[1] core_xlim[1] = core_xlim[0] core_xlim[0] = t core_w = abs(core_w) core_ylim = [ylim[0] + north, ylim[1] - south] core_h = core_ylim[1] - core_ylim[0] if core_h < 0: t = core_ylim[1] core_ylim[1] = core_ylim[0] core_ylim[0] = t core_h = abs(core_h) # Tile the pattern (pattern_h, pattern_w) = get_pattern_size(which_pattern) (tile_h, tile_w) = (pattern_h + 2 * y_jitter, pattern_w + 2 * x_jitter) if distancing: tile_h += 2 tile_w += 2 tiling_nx = core_w // tile_w - 1 tiling_ny = core_h // tile_h - 1 tileset = [] for i in range(tiling_nx): for j in range(tiling_ny): if distancing: xoffset = core_xlim[0] + (tile_w // 2) + i * (tile_w + 2) + 1 yoffset = core_ylim[0] + (tile_h // 2) + j * (tile_h + 2) + 1 else: xoffset = core_xlim[0] + (tile_w // 2) + i * tile_w yoffset = core_ylim[0] + (tile_h // 2) + j * tile_h tileset.append( get_grid_pattern( which_pattern, rows, cols, xoffset=xoffset + random.randint(-x_jitter, x_jitter), yoffset=yoffset + random.randint(-y_jitter, y_jitter), hflip=do_hflip, vflip=do_vflip, check_overflow=False, ) ) tileset_pattern = pattern_union(tileset) return tileset_pattern
import math from collections.abc import Iterable from operator import itemgetter import random import os from glob import glob from .geom import hflip_pattern, vflip_pattern, rot_pattern from .error import GollyPatternsError def get_patterns(): patternfiles = glob( os.path.join(os.path.dirname(os.path.abspath(__file__)), "patterns", "*.txt") ) # trim extension patternfiles = [os.path.basename(os.path.splitext(p)[0]) for p in patternfiles] return patternfiles def get_pattern(pattern_name, hflip=False, vflip=False, rotdeg=0): """ For a given pattern, return the .o diagram as a list of strings, one string = one row """ fname = os.path.join( os.path.dirname(os.path.abspath(__file__)), "patterns", pattern_name + ".txt" ) if os.path.exists(fname): with open(fname, "r") as f: pattern = f.readlines() pattern = [r.strip() for r in pattern] if hflip: pattern = hflip_pattern(pattern) if vflip: pattern = vflip_pattern(pattern) if rotdeg: pattern = rot_pattern(pattern, rotdeg) return pattern else: raise GollyPatternsError(f"Error: pattern {fname} does not exist!") def get_pattern_size(pattern_name, **kwargs): """ Returns: (nrows, ncols) """ pattern = get_pattern(pattern_name, **kwargs) return (len(pattern), len(pattern[0])) def get_pattern_livecount(pattern_name, **kwargs): """ Returns: count of live cells in the given pattern """ pattern = get_pattern(pattern_name, **kwargs) count = 0 for row in pattern: for j in row: if j == "o": count += 1 return count def get_grid_empty(rows, columns, flat=True): if columns < 1 or rows < 1: err = f"Error: invalid number of rows {rows} or columns {columns}, must be positive integers > 0" raise GollyPatternsError(err) blank_row = ["."] * columns blank_grid = [blank_row[:] for r in range(rows)] if flat: blank_grid = ["".join(gridrow) for gridrow in blank_grid] return blank_grid def get_grid_pattern( pattern_name, rows, columns, xoffset=0, yoffset=0, hflip=False, vflip=False, rotdeg=0, check_overflow=True, ): """ Get the pattern corresponding to pattern_name, and place it on a grid of size (rows x columns) at the given offset. If check_overflow is False, the pattern added may be partially or fully outside of the specified grid. """ # TODO: add check of rows/columns, and whether this pattern # will actually fit on the specified grid size. if columns < 1 or rows < 1: err = f"Error: invalid number of rows {rows} or columns {columns}, must be positive integers > 0" raise GollyPatternsError(err) # convert list of strings to list of lists (for convenience) ogpattern = get_pattern(pattern_name, hflip=hflip, vflip=vflip, rotdeg=rotdeg) ogpattern = [list(j) for j in ogpattern] blank_row = ["."] * columns newpattern = [blank_row[:] for r in range(rows)] (pattern_h, pattern_w) = (len(ogpattern), len(ogpattern[0])) # given offset is offset for the center of the pattern, # so do some algebra to determine where we should start xstart = xoffset - pattern_w // 2 xend = xstart + pattern_w ystart = yoffset - pattern_h // 2 yend = ystart + pattern_h # Check size of pattern if check_overflow: if xstart < 0: raise GollyPatternsError( f"Error: specified offset {xoffset} is too small, need at least {pattern_w//2}" ) if xend >= columns: raise GollyPatternsError( f"Error: specified number of columns {columns} was too small, need at least {xend+1}" ) if ystart < 0: raise GollyPatternsError( f"Error: specified offset {yoffset} is too small, need at least {pattern_h//2}" ) if yend >= rows: raise GollyPatternsError( f"Error: specified number of rows {rows} was too small, need at least {yend+1}" ) # iterate through the pattern and copy over the cells that are in the final grid for iy, y in enumerate(range(ystart, yend)): if y > 0 and y < len(newpattern): for ix, x in enumerate(range(xstart, xend)): if x > 0 and x < len(newpattern[iy]): newpattern[y][x] = ogpattern[iy][ix] newpattern = ["".join(j) for j in newpattern] return newpattern def pattern_union(patterns): for i in range(1, len(patterns)): axis0different = len(patterns[i - 1]) != len(patterns[i]) axis1different = len(patterns[i - 1][0]) != len(patterns[i][0]) if axis0different or axis1different: err = "Error: pattern_union() received patterns of dissimilar size" err += "\n" for i in range(1, len(patterns)): err += f"Pattern {i+1}: rows = {len(patterns[i])}, cols = {len(patterns[i][0])}" err += "\n" raise GollyPatternsError(err) # Turn all patterns into lists of lists (for convenience) rows = len(patterns[0]) cols = len(patterns[0][0]) newpatterns = [] for pattern in patterns: newpatterns.append([list(j) for j in pattern]) patterns = newpatterns blank_row = ["."] * cols newpattern = [blank_row[:] for r in range(rows)] for iy in range(rows): for ix in range(cols): alive = False for ip, pattern in enumerate(patterns): if pattern[iy][ix] == "o": alive = True break if alive: newpattern[iy][ix] = "o" newpattern = ["".join(j) for j in newpattern] return newpattern def segment_pattern( rows, cols, seed=None, colormode=None, jitterx=0, jittery=0, nhseg=0, nvseg=0, gap_probability=None, ): """ Return a two-color pattern consisting of nhseg horizontal segments and nvseg vertical segments. In classic color mode, each segment piece is assigned to a single team. In classic broken mode, each segment piece is assigned to a single team, with some dead cells. In random color mode, each segment cell is assigned random teams. In random broken mode, each segment cell is assigned random teams, with some dead cells. gap probability dictates how often gaps occur. If there are too many gaps, maps get boring! """ valid_colormodes = ["classic", "classicbroken", "random", "randombroken"] if colormode not in valid_colormodes: raise GollyPatternsError( f"Error: invalid color mode {colormode} passed to _segment(), must be in {', '.join(valid_colormodes)}" ) if nhseg == 0 and nvseg == 0: raise GollyPatternsError( "Error: invalid number of segments (0 horizontal and 0 vertical) passed to _segment()" ) if gap_probability is None: # Defaults for gap probability if colormode in ["classicbroken", "randombroken"]: gap_probability = 0.05 else: gap_probability = 0.0 elif gap_probability < 0 or gap_probability > 1: raise GollyPatternsError( f"Error: specified gap probability for segment is invalid: {gap_probability}" ) # Get the snap-to-grid centers hsegcenters = [(iy + 1) * rows // (nhseg + 1) - 1 for iy in range(nhseg)] vsegcenters = [(ix + 1) * cols // (nvseg + 1) - 1 for ix in range(nvseg)] # Add jitter, and bookend with 0 and nrows/ncols hseglocs = ( [-1] + [k + random.randint(-jittery, jittery) for k in hsegcenters] + [rows] ) vseglocs = ( [-1] + [k + random.randint(-jitterx, jitterx) for k in vsegcenters] + [cols] ) loclenlist = [] # Construct vertical segments first: # ---------------- # Horizontal segment locations give us the start/end coordinates for vertical segments # Skip the first loc - it's 1 past the edge so the segments start at 0 for ih in range(1, len(hseglocs)): yend = hseglocs[ih] - 1 ystart = hseglocs[ih - 1] + 1 mag = yend - ystart + 1 # Skip the first vseg loc - it's 1 past the edge # Skip the last vseg loc - it's also 1 past the edge for iv in range(1, len(vseglocs) - 1): x = vseglocs[iv] loclenlist.append((ystart, yend, x, x, mag)) # Construct horizontal segments: # ---------------- for iv in range(1, len(vseglocs)): xend = vseglocs[iv] - 1 xstart = vseglocs[iv - 1] + 1 mag = xend - xstart + 1 for ih in range(1, len(hseglocs) - 1): y = hseglocs[ih] loclenlist.append((y, y, xstart, xend, mag)) # These store the the .o diagrams (flat=False means these are lists of lists of one char) team1_pattern = get_grid_empty(rows, cols, flat=False) team2_pattern = get_grid_empty(rows, cols, flat=False) # Color mode: # ------------------------ # We have a list of segments, coordinates and lengths, # now the way we populate the map depends on the color mode. if colormode in ["classic", "classicbroken"]: # Classic/classic broken color mode: # Each segment is a single solid color, # use serpentine pattern to assign colors. # If broken, use 0s to represent dead cells. serpentine_pattern = [1, 2, 2, 1] from operator import itemgetter random.shuffle(loclenlist) loclenlist.sort(key=itemgetter(4), reverse=True) for i, (starty, endy, startx, endx, mag) in enumerate(loclenlist): serpix = i % len(serpentine_pattern) serpteam = serpentine_pattern[serpix] magon = math.floor((1 - gap_probability) * mag) rem = mag - magon team_assignments = [serpteam,] * magon + [ 0, ] * rem # noqa random.shuffle(team_assignments) ta_ix = 0 for y in range(starty, endy + 1): for x in range(startx, endx + 1): if team_assignments[ta_ix] == 1: team1_pattern[y][x] = "o" elif team_assignments[ta_ix] == 2: team2_pattern[y][x] = "o" ta_ix += 1 elif colormode in ["random", "randombroken"]: # Random/random broken color mode: # For each segment of length N, # create an array of N/2 zeros and N/2 ones, # shuffle it, use it to assign colors. # If broken, include 0s to represent dead cells for i, (starty, endy, startx, endx, mag) in enumerate(loclenlist): magh = math.floor(0.5 * (1 - gap_probability) * mag) rem = mag - (2*magh) team_assignments = ( [ 1, ] * magh + [ 2, ] * magh + [ 0, ] * rem ) # noqa random.shuffle(team_assignments) ta_ix = 0 for y in range(starty, endy + 1): if y >= rows: continue for x in range(startx, endx + 1): if x >= cols: continue if team_assignments[ta_ix] == 1: team1_pattern[y][x] = "o" elif team_assignments[ta_ix] == 2: team2_pattern[y][x] = "o" ta_ix += 1 team1_pattern = ["".join(pattrow) for pattrow in team1_pattern] team2_pattern = ["".join(pattrow) for pattrow in team2_pattern] return team1_pattern, team2_pattern def metheusela_quadrants_pattern( rows, cols, seed=None, metheusela_counts=None, fixed_metheusela=None ): """ Returns a map with a cluster of metheuselas in each quadrant. The methesela_counts parameter determines how many metheuselas may be put in each corner. Valid configurations: 1 (placed in center of quadrant) 2 (placed on opposite corners of a four-point square formed by cutting quadrant into thirds 4 (placed on all corners of four-point square) 3 (placed on diagonal of square with 3 points per edge, or 8 points) 9 (placed on all corners and center of 8-point square) 16 (placed on a 4x4 grid) Procedure: First randomly pair quadrants so their metheusela counts will match. Next, place random metheusela patterns in each of the corners. """ if seed is not None: random.seed(seed) # Basic checks BIGDIMLIMIT = 150 mindim = min(rows, cols) if metheusela_counts is None: if mindim < BIGDIMLIMIT: metheusela_counts = [1, 2, 3, 4, 9] else: metheusela_counts = [1, 2, 3, 4, 9, 16] valid_mc = [1, 2, 3, 4, 9, 16] for mc in metheusela_counts: if mc not in valid_mc: msg = "Invalid metheusela counts passed: must be in {', '.join(valid_mc)}\n" msg += "you specified {', '.join(metheusela_counts)}" raise GollyPatternsError(msg) if 16 in metheusela_counts and min(rows, cols) < BIGDIMLIMIT: msg = "Invalid metheusela count specified: grid size too small for 4x4!" raise GollyPatternsError(msg) metheusela_names = [ "acorn", "bheptomino", "cheptomino", "eheptomino", "multuminparvo", "piheptomino", "rabbit", "rpentomino", "timebomb", "switchengine", ] small_metheusela_names = [ "bheptomino", "cheptomino", "eheptomino", "piheptomino", "rpentomino", ] # Store each quadrant and its upper left corner in (rows from top, cols from left) format quadrants = [ (1, (0, cols // 2)), (2, (0, 0)), (3, (rows // 2, 0)), (4, (rows // 2, cols // 2)), ] # Shuffle quadrants, first two and second two are now paired up as buddies random.shuffle(quadrants) rotdegs = [0, 90, 180, 270] all_metheuselas = [] for buddy_index in [[0, 1], [2, 3]]: # Decide how many metheuselas in this quad pair count = random.choice(metheusela_counts) if count == 1: # Only one metheusela in this quadrant, so use the center jitterx = 15 jittery = 15 for bi in buddy_index: corner = quadrants[bi][1] y = corner[0] + rows // 4 +random.randint(-jittery, jittery) x = corner[1] + cols // 4 + random.randint(-jitterx, jitterx) if fixed_metheusela: meth = fixed_metheusela else: meth = random.choice(metheusela_names) pattern = get_grid_pattern( meth, rows, cols, xoffset=x, yoffset=y, hflip=bool(random.getrandbits(1)), vflip=bool(random.getrandbits(1)), rotdeg=random.choice(rotdegs), ) livecount = get_pattern_livecount(meth) all_metheuselas.append((livecount, pattern)) elif count == 2 or count == 4: # Two or four metheuselas in this quadrant, so place at corners of a square # Form the square by cutting the quadrant into thirds if count == 4: jitterx = 2 jittery = 2 else: jitterx = 5 jittery = 5 for bi in buddy_index: corner = quadrants[bi][1] # Slices and partitions form the inside square nslices = 2 nparts = nslices + 1 posdiag = bool(random.getrandbits(1)) for a in range(1, nparts): for b in range(1, nparts): proceed = False if count == 2: if (posdiag and a == b) or ( not posdiag and a == (nslices - b + 1) ): proceed = True elif count == 4: proceed = True if proceed: y = corner[0] + a * ((rows // 2) // nparts) + random.randint(-jittery, jittery) x = corner[1] + b * ((cols // 2) // nparts) + random.randint(-jitterx, jitterx) if fixed_metheusela: meth = fixed_metheusela else: meth = random.choice(metheusela_names) try: pattern = get_grid_pattern( meth, rows, cols, xoffset=x, yoffset=y, hflip=bool(random.getrandbits(1)), vflip=bool(random.getrandbits(1)), rotdeg=random.choice(rotdegs), ) except GollyPatternsError: raise GollyPatternsError( f"Error with metheusela {meth}: cannot fit" ) livecount = get_pattern_livecount(meth) all_metheuselas.append((livecount, pattern)) elif count == 3 or count == 9: # Three or nine metheuselas, place these on a square with three points per side # or eight points total if count == 9: jitterx = 2 jittery = 2 else: jitterx = 4 jittery = 4 for bi in buddy_index: corner = quadrants[bi][1] nslices = 4 for a in range(1, nslices): for b in range(1, nslices): proceed = False if count == 3: if a == b: proceed = True elif count == 9: proceed = True if proceed: y = corner[0] + a * ((rows // 2) // nslices) + random.randint(-jittery, jittery) x = corner[1] + b * ((cols // 2) // nslices) + random.randint(-jitterx, jitterx) if fixed_metheusela: meth = fixed_metheusela elif min(rows, cols) < BIGDIMLIMIT: meth = random.choice(small_metheusela_names) else: meth = random.choice(metheusela_names) try: pattern = get_grid_pattern( meth, rows, cols, xoffset=x, yoffset=y, hflip=bool(random.getrandbits(1)), vflip=bool(random.getrandbits(1)), rotdeg=random.choice(rotdegs), ) except GollyPatternsError: raise GollyPatternsError( f"Error with metheusela {meth}: cannot fit" ) livecount = get_pattern_livecount(meth) all_metheuselas.append((livecount, pattern)) elif count == 16: # Sixteen metheuselas, place these on a 4x4 square jitterx = 1 jittery = 1 for bi in buddy_index: corner = quadrants[bi][1] nslices = 5 for a in range(1, nslices): for b in range(1, nslices): y = corner[0] + a * ((rows // 2) // nslices) + random.randint(-jittery, jittery) x = corner[1] + b * ((cols // 2) // nslices) + random.randint(-jitterx, jitterx) if fixed_metheusela: meth = fixed_metheusela else: meth = random.choice(small_metheusela_names) try: pattern = get_grid_pattern( meth, rows, cols, xoffset=x, yoffset=y, hflip=bool(random.getrandbits(1)), vflip=bool(random.getrandbits(1)), rotdeg=random.choice(rotdegs), ) except GollyPatternsError: raise GollyPatternsError( f"Error with metheusela {meth}: cannot fit" ) livecount = get_pattern_livecount(meth) all_metheuselas.append((livecount, pattern)) random.shuffle(all_metheuselas) all_metheuselas.sort(key=itemgetter(0), reverse=True) team1_patterns = [] team2_patterns = [] serpentine_pattern = [1, 2, 2, 1] for i, (_, metheusela_pattern) in enumerate(all_metheuselas): serpix = i % len(serpentine_pattern) serpteam = serpentine_pattern[serpix] if serpteam == 1: team1_patterns.append(metheusela_pattern) elif serpteam == 2: team2_patterns.append(metheusela_pattern) team1_pattern = pattern_union(team1_patterns) team2_pattern = pattern_union(team2_patterns) return team1_pattern, team2_pattern def cloud_region( which_pattern, dims, xlim, ylim, margins, jitter, flip, distancing=True ): """ Given a square region defined by the x and y limits, tile the region with copies of the specified pattern, plus jitter. Parameters: dims (rows, cols) list/tuple xlim (xstart, xend) list/tuple ylim (ystart, yend) list/tuple margins integer or (N, E, S, W) list/tuple jitter (xjitter, yjitter) list/tuple flip (do_hflip, do_vflip) list/tuple distancing boolean: if true, add an extra margin of cells (eliminates overlap in starting positions) (off is more chaotic, on is more ordered) """ if len(dims) != 2: err = "Error: could not understand dimensions input, provide (rows, cols)" raise Exception(err) rows, cols = dims[0], dims[1] if len(xlim) != 2 or len(ylim) != 2: err = "Error: could not understand xlim/ylim input, provide (xstart, xend) and (ystart, yend)" raise Exception(err) # Unpack margins if isinstance(margins, Iterable): if len(margins) != 4: err = "Error: could not understand margins input, provide single value or list of 4 values" raise Exception(err) # list of 4 values in order N E S W north = margins[0] east = margins[1] south = margins[2] west = margins[3] else: # single value, uniform margin margins = int(margins) north = east = south = west = margins # Unpack jitter if isinstance(jitter, Iterable): if len(jitter) != 2: err = "Error: could not understand jitter input, provide two values (xjitter, yjitter)" raise Exception(err) x_jitter = jitter[0] y_jitter = jitter[1] else: jitter = int(jitter) x_jitter = y_jitter = jitter # Get whether to hflip or vflip if len(flip) != 2: err = "Error: could not understand flip input, provide two values (do_hflip, do_vflip)" raise Exception(err) do_hflip = flip[0] do_vflip = flip[1] # Determine the core xlim and ylim core_xlim = [xlim[0] + west, xlim[1] - east] core_w = core_xlim[1] - core_xlim[0] if core_w < 0: t = core_xlim[1] core_xlim[1] = core_xlim[0] core_xlim[0] = t core_w = abs(core_w) core_ylim = [ylim[0] + north, ylim[1] - south] core_h = core_ylim[1] - core_ylim[0] if core_h < 0: t = core_ylim[1] core_ylim[1] = core_ylim[0] core_ylim[0] = t core_h = abs(core_h) # Tile the pattern (pattern_h, pattern_w) = get_pattern_size(which_pattern) (tile_h, tile_w) = (pattern_h + 2 * y_jitter, pattern_w + 2 * x_jitter) if distancing: tile_h += 2 tile_w += 2 tiling_nx = core_w // tile_w - 1 tiling_ny = core_h // tile_h - 1 tileset = [] for i in range(tiling_nx): for j in range(tiling_ny): if distancing: xoffset = core_xlim[0] + (tile_w // 2) + i * (tile_w + 2) + 1 yoffset = core_ylim[0] + (tile_h // 2) + j * (tile_h + 2) + 1 else: xoffset = core_xlim[0] + (tile_w // 2) + i * tile_w yoffset = core_ylim[0] + (tile_h // 2) + j * tile_h tileset.append( get_grid_pattern( which_pattern, rows, cols, xoffset=xoffset + random.randint(-x_jitter, x_jitter), yoffset=yoffset + random.randint(-y_jitter, y_jitter), hflip=do_hflip, vflip=do_vflip, check_overflow=False, ) ) tileset_pattern = pattern_union(tileset) return tileset_pattern