code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
from gnucash_portfolio import BookAggregate holdings = [] with BookAggregate() as book: # query = book.securities.query.filter(Commodity.) holding_entities = book.securities.get_all() for item in holding_entities: # Check holding balance agg = book.securities.get_aggregate(item) balance = agg.get_num_shares() if balance > Decimal(0): holdings.append(f"{item.namespace}:{item.mnemonic}") else: self.logger.debug(f"0 balance for {item}") # holdings = map(lambda x: , holding_entities) return holdings
def get_symbols_with_positive_balances(self) -> List[str]
Identifies all the securities with positive balances
7.224802
6.872876
1.051205
from pricedb import dal if not self.pricedb_session: self.pricedb_session = dal.get_default_session() return self.pricedb_session
def __get_pricedb_session(self)
Provides initialization and access to module-level session
3.678598
3.171856
1.159762
assert isinstance(symbol, str) assert isinstance(assetclass, int) symbol = symbol.upper() app = AppAggregate() new_item = app.add_stock_to_class(assetclass, symbol) print(f"Record added: {new_item}.")
def add(assetclass: int, symbol: str)
Add a stock to an asset class
5.733372
4.55197
1.259536
app = AppAggregate() app.logger = logger unalloc = app.find_unallocated_holdings() if not unalloc: print(f"No unallocated holdings.") for item in unalloc: print(item)
def unallocated()
Identify unallocated holdings
6.558844
5.620137
1.167026
self.full = full # Header output = f"Asset Allocation model, total: {model.currency} {model.total_amount:,.2f}\n" # Column Headers for column in self.columns: name = column['name'] if not self.full and name == "loc.cur.": # Skip local currency if not displaying stocks. continue width = column["width"] output += f"{name:^{width}}" output += "\n" output += f"-------------------------------------------------------------------------------\n" # Asset classes view_model = ModelMapper(model).map_to_linear(self.full) for row in view_model: output += self.__format_row(row) + "\n" return output
def format(self, model: AssetAllocationModel, full: bool = False)
Returns the view-friendly output of the aa model
6.644768
6.086122
1.09179
output = "" index = 0 # Name value = row.name # Indent according to depth. for _ in range(0, row.depth): value = f" {value}" output += self.append_text_column(value, index) # Set Allocation value = "" index += 1 if row.set_allocation > 0: value = f"{row.set_allocation:.2f}" output += self.append_num_column(value, index) # Current Allocation value = "" index += 1 if row.curr_allocation > Decimal(0): value = f"{row.curr_allocation:.2f}" output += self.append_num_column(value, index) # Allocation difference, percentage value = "" index += 1 if row.alloc_diff_perc.copy_abs() > Decimal(0): value = f"{row.alloc_diff_perc:.0f} %" output += self.append_num_column(value, index) # Allocated value index += 1 value = "" if row.set_value: value = f"{row.set_value:,.0f}" output += self.append_num_column(value, index) # Current Value index += 1 value = f"{row.curr_value:,.0f}" output += self.append_num_column(value, index) # Value in security's currency. Show only if displaying full model, with stocks. index += 1 if self.full: value = "" if row.curr_value_own_currency: value = f"({row.curr_value_own_currency:,.0f}" value += f" {row.own_currency}" value += ")" output += self.append_num_column(value, index) # https://en.wikipedia.org/wiki/ANSI_escape_code # CSI="\x1B[" # red = 31, green = 32 # output += CSI+"31;40m" + "Colored Text" + CSI + "0m" # Value diff index += 1 value = "" if row.diff_value: value = f"{row.diff_value:,.0f}" # Color the output # value = f"{CSI};40m{value}{CSI};40m" output += self.append_num_column(value, index) return output
def __format_row(self, row: AssetAllocationViewModel)
display-format one row Formats one Asset Class record
2.864103
2.845118
1.006673
width = self.columns[index]["width"] return f"{text:>{width}}"
def append_num_column(self, text: str, index: int)
Add value to the output row, width based on index
11.712528
6.120308
1.913715
width = self.columns[index]["width"] return f"{text:<{width}}"
def append_text_column(self, text: str, index: int)
Add value to the output row, width based on index
11.795335
6.411293
1.839775
obj = model.AssetClass() obj.id = entity.id obj.parent_id = entity.parentid obj.name = entity.name obj.allocation = entity.allocation obj.sort_order = entity.sortorder #entity.stock_links #entity.diff_adjustment if entity.parentid == None: obj.depth = 0 return obj
def map_entity(self, entity: dal.AssetClass)
maps data from entity -> object
5.590339
4.855389
1.151368
result = [] for ac in self.model.classes: rows = self.__get_ac_tree(ac, with_stocks) result += rows return result
def map_to_linear(self, with_stocks: bool=False)
Maps the tree to a linear representation suitable for display
11.70858
9.399848
1.245614
output = [] output.append(self.__get_ac_row(ac)) for child in ac.classes: output += self.__get_ac_tree(child, with_stocks) if with_stocks: for stock in ac.stocks: row = None if isinstance(stock, Stock): row = self.__get_stock_row(stock, ac.depth + 1) elif isinstance(stock, CashBalance): row = self.__get_cash_row(stock, ac.depth + 1) output.append(row) return output
def __get_ac_tree(self, ac: model.AssetClass, with_stocks: bool)
formats the ac tree - entity with child elements
2.427999
2.316898
1.047952
view_model = AssetAllocationViewModel() view_model.depth = ac.depth # Name view_model.name = ac.name view_model.set_allocation = ac.allocation view_model.curr_allocation = ac.curr_alloc view_model.diff_allocation = ac.alloc_diff view_model.alloc_diff_perc = ac.alloc_diff_perc # value view_model.curr_value = ac.curr_value # expected value view_model.set_value = ac.alloc_value # diff view_model.diff_value = ac.value_diff return view_model
def __get_ac_row(self, ac: model.AssetClass) -> AssetAllocationViewModel
Formats one Asset Class record
3.233455
3.21032
1.007206
assert isinstance(stock, Stock) view_model = AssetAllocationViewModel() view_model.depth = depth # Symbol view_model.name = stock.symbol # Current allocation view_model.curr_allocation = stock.curr_alloc # Value in base currency view_model.curr_value = stock.value_in_base_currency # Value in security's currency. view_model.curr_value_own_currency = stock.value view_model.own_currency = stock.currency return view_model
def __get_stock_row(self, stock: Stock, depth: int) -> str
formats stock row
4.582006
4.371866
1.048066
assert isinstance(item, CashBalance) view_model = AssetAllocationViewModel() view_model.depth = depth # Symbol view_model.name = item.symbol # Value in base currency view_model.curr_value = item.value_in_base_currency # Value in security's currency. view_model.curr_value_own_currency = item.value view_model.own_currency = item.currency return view_model
def __get_cash_row(self, item: CashBalance, depth: int) -> str
formats stock row
4.959275
4.675919
1.060599
session = self.open_session() session.add(item) session.commit()
def create_asset_class(self, item: AssetClass)
Inserts the record
5.530194
4.369066
1.265761
assert isinstance(symbol, str) assert isinstance(assetclass_id, int) item = AssetClassStock() item.assetclassid = assetclass_id item.symbol = symbol session = self.open_session() session.add(item) self.save() return item
def add_stock_to_class(self, assetclass_id: int, symbol: str)
Add a stock link to an asset class
3.475927
3.207223
1.083781
assert isinstance(id, int) self.open_session() to_delete = self.get(id) self.session.delete(to_delete) self.save()
def delete(self, id: int)
Delete asset class
4.596239
4.317053
1.06467
# Get linked securities session = self.open_session() linked_entities = session.query(AssetClassStock).all() linked = [] # linked = map(lambda x: f"{x.symbol}", linked_entities) for item in linked_entities: linked.append(item.symbol) # Get all securities with balance > 0. from .stocks import StocksInfo stocks = StocksInfo() stocks.logger = self.logger holdings = stocks.get_symbols_with_positive_balances() # Find those which are not included in the stock links. non_alloc = [] index = -1 for item in holdings: try: index = linked.index(item) self.logger.debug(index) except ValueError: non_alloc.append(item) return non_alloc
def find_unallocated_holdings(self)
Identifies any holdings that are not included in asset allocation
4.613207
4.483819
1.028857
self.open_session() item = self.session.query(AssetClass).filter( AssetClass.id == id).first() return item
def get(self, id: int) -> AssetClass
Loads Asset Class
4.131219
4.910508
0.841302
from .dal import get_session cfg = Config() cfg.logger = self.logger db_path = cfg.get(ConfigKeys.asset_allocation_database_path) self.session = get_session(db_path) return self.session
def open_session(self)
Opens a db session and returns it
7.440061
6.755641
1.101311
# load from db # TODO set the base currency base_currency = "EUR" loader = AssetAllocationLoader(base_currency=base_currency) loader.logger = self.logger model = loader.load_tree_from_db() model.validate() # securities # read stock links loader.load_stock_links() # read stock quantities from GnuCash loader.load_stock_quantity() # Load cash balances loader.load_cash_balances() # loader.session # read prices from Prices database loader.load_stock_prices() # recalculate stock values into base currency loader.recalculate_stock_values_into_base() # calculate model.calculate_current_value() model.calculate_set_values() model.calculate_current_allocation() # return the model for display return model
def get_asset_allocation(self)
Creates and populates the Asset Allocation model. The main function of the app.
7.111367
6.83295
1.040746
full_symbol = symbol if namespace: full_symbol = f"{namespace}:{symbol}" result = ( self.session.query(AssetClassStock) .filter(AssetClassStock.symbol == full_symbol) .all() ) return result
def get_asset_classes_for_security(self, namespace: str, symbol: str) -> List[AssetClass]
Find all asset classes (should be only one at the moment, though!) to which the symbol belongs
3.361421
3.109123
1.081148
model: AssetAllocationModel = self.get_asset_allocation_model() model.logger = self.logger valid = model.validate() if valid: print(f"The model is valid. Congratulations") else: print(f"The model is invalid.")
def validate_model(self)
Validate the model
5.078965
4.70466
1.07956
session = self.open_session() links = session.query(AssetClassStock).order_by( AssetClassStock.symbol).all() output = [] for link in links: output.append(link.symbol + '\n') # Save output to a text file. with open("symbols.txt", mode='w') as file: file.writelines(output) print("Symbols exported to symbols.txt")
def export_symbols(self)
Exports all used symbols
4.1918
4.243122
0.987905
if not os.path.exists(file_path): raise FileNotFoundError("File path not found: %s", file_path) # check if file exists if not os.path.isfile(file_path): log(ERROR, "file not found: %s", file_path) raise FileNotFoundError("configuration file not found %s", file_path) self.config.read(file_path)
def __read_config(self, file_path: str)
Read the config file
3.146457
2.79868
1.124265
src_path = self.__get_config_template_path() src = os.path.abspath(src_path) if not os.path.exists(src): log(ERROR, "Config template not found %s", src) raise FileNotFoundError() dst = os.path.abspath(self.get_config_path()) shutil.copyfile(src, dst) if not os.path.exists(dst): raise FileNotFoundError("Config file could not be copied to user dir!")
def __create_user_config(self)
Copy the config template into user's directory
3.438697
2.964546
1.15994
cfg = Config() edited = False if aadb: cfg.set(ConfigKeys.asset_allocation_database_path, aadb) print(f"The database has been set to {aadb}.") edited = True if cur: cfg.set(ConfigKeys.default_currency, cur) edited = True if edited: print(f"Changes saved.") else: print(f"No changes were made.") print(f"Use --help parameter for more information.")
def set(aadb, cur)
Sets the values in the config file
4.544334
4.605247
0.986773
if (aadb): cfg = Config() value = cfg.get(ConfigKeys.asset_allocation_database_path) click.echo(value) if not aadb: click.echo("Use --help for more information.")
def get(aadb: str)
Retrieves a value from config
10.209177
8.751238
1.166598
prefix = "" if self.parent: if self.parent.fullname: prefix = self.parent.fullname + ":" else: # Only the root does not have a parent. In that case we also don't need a name. return "" return prefix + self.name
def fullname(self)
includes the full path with parent names
5.259528
4.88118
1.077512
assert isinstance(self.price, Decimal) return self.quantity * self.price
def value(self) -> Decimal
Value of the holdings in exchange currency. Value = Quantity * Price
8.778597
6.000494
1.462979
result = self.parent.name if self.parent else "" # Iterate to the top asset class and add names. cursor = self.parent while cursor: result = cursor.name + ":" + result cursor = cursor.parent return result
def asset_class(self) -> str
Returns the full asset class path for this stock
6.532914
6.07388
1.075575
sum = Decimal(0) if self.classes: for child in self.classes: sum += child.child_allocation else: # This is not a branch but a leaf. Return own allocation. sum = self.allocation return sum
def child_allocation(self)
The sum of all child asset classes' allocations
6.685163
5.670781
1.178879
assert isinstance(ac_id, int) # iterate recursively for ac in self.asset_classes: if ac.id == ac_id: return ac # if nothing returned so far. return None
def get_class_by_id(self, ac_id: int) -> AssetClass
Finds the asset class by id
5.993878
5.595055
1.071281
for ac in self.asset_classes: if ac.name.lower() == "cash": return ac return None
def get_cash_asset_class(self) -> AssetClass
Find the cash asset class by name.
3.886109
2.828339
1.37399
# Asset class allocation should match the sum of children's allocations. # Each group should be compared. sum = Decimal(0) # Go through each asset class, not just the top level. for ac in self.asset_classes: if ac.classes: # get the sum of all the children's allocations child_alloc_sum = ac.child_allocation # compare to set allocation if ac.allocation != child_alloc_sum: message = f"The sum of child allocations {child_alloc_sum:.2f} invalid for {ac}!" self.logger.warning(message) print(message) return False # also make sure that the sum of 1st level children matches 100 for ac in self.classes: sum += ac.allocation if sum != Decimal(100): message = f"The sum of all allocations ({sum:.2f}) does not equal 100!" self.logger.warning(message) print(message) return False return True
def validate(self) -> bool
Validate that the values match. Incomplete!
4.78323
4.657994
1.026886
for ac in self.asset_classes: ac.alloc_value = self.total_amount * ac.allocation / Decimal(100)
def calculate_set_values(self)
Calculate the expected totals based on set allocations
9.82516
7.306177
1.344774
for ac in self.asset_classes: ac.curr_alloc = ac.curr_value * 100 / self.total_amount
def calculate_current_allocation(self)
Calculates the current allocation % based on the value
7.66886
6.615613
1.159206
# must be recursive total = Decimal(0) for ac in self.classes: self.__calculate_current_value(ac) total += ac.curr_value self.total_amount = total
def calculate_current_value(self)
Add all the stock values and assign to the asset classes
8.768884
6.765219
1.296171
# Is this the final asset class, the one with stocks? if asset_class.stocks: # add all the stocks stocks_sum = Decimal(0) for stock in asset_class.stocks: # recalculate into base currency! stocks_sum += stock.value_in_base_currency asset_class.curr_value = stocks_sum if asset_class.classes: # load totals for child classes for child in asset_class.classes: self.__calculate_current_value(child) asset_class.curr_value += child.curr_value
def __calculate_current_value(self, asset_class: AssetClass)
Calculate totals for asset class by adding all the children values
4.913456
4.319405
1.137531
# , base_currency: str <= ignored for now. if self.rate and self.rate.currency == mnemonic: # Already loaded. return app = PriceDbApplication() # TODO use the base_currency parameter for the query #33 symbol = SecuritySymbol("CURRENCY", mnemonic) self.rate = app.get_latest_price(symbol) if not self.rate: raise ValueError(f"No rate found for {mnemonic}!")
def load_currency(self, mnemonic: str)
load the latest rate for the given mnemonic; expressed in the base currency
10.05104
8.796093
1.142671
# load asset allocation app = AppAggregate() app.logger = logger model = app.get_asset_allocation() if format == "ascii": formatter = AsciiFormatter() elif format == "html": formatter = HtmlFormatter else: raise ValueError(f"Unknown formatter {format}") # formatters can display stock information with --full output = formatter.format(model, full=full) print(output)
def show(format, full)
Print current allocation to the console.
7.800548
7.565035
1.031132
from gnucash_portfolio.accounts import AccountsAggregate, AccountAggregate cfg = self.__get_config() cash_root_name = cfg.get(ConfigKeys.cash_root) # Load cash from all accounts under the root. gc_db = self.config.get(ConfigKeys.gnucash_book_path) with open_book(gc_db, open_if_lock=True) as book: svc = AccountsAggregate(book) root_account = svc.get_by_fullname(cash_root_name) acct_svc = AccountAggregate(book, root_account) cash_balances = acct_svc.load_cash_balances_with_children(cash_root_name) # Treat each sum per currency as a Stock, for display in full mode. self.__store_cash_balances_per_currency(cash_balances)
def load_cash_balances(self)
Loads cash balances from GnuCash book and recalculates into the default currency
6.83504
6.278216
1.088691
cash = self.model.get_cash_asset_class() for cur_symbol in cash_balances: item = CashBalance(cur_symbol) item.parent = cash quantity = cash_balances[cur_symbol]["total"] item.value = Decimal(quantity) item.currency = cur_symbol # self.logger.debug(f"adding {item}") cash.stocks.append(item) self.model.stocks.append(item)
def __store_cash_balances_per_currency(self, cash_balances)
Store balance per currency as Stock records under Cash class
4.820618
4.209949
1.145054
self.model = AssetAllocationModel() # currency self.model.currency = self.__get_config().get(ConfigKeys.default_currency) # Asset Classes db = self.__get_session() first_level = ( db.query(dal.AssetClass) .filter(dal.AssetClass.parentid == None) .order_by(dal.AssetClass.sortorder) .all() ) # create tree for entity in first_level: ac = self.__map_entity(entity) self.model.classes.append(ac) # Add to index self.model.asset_classes.append(ac) # append child classes recursively self.__load_child_classes(ac) return self.model
def load_tree_from_db(self) -> AssetAllocationModel
Reads the asset allocation data only, and constructs the AA tree
4.208115
4.306583
0.977135
links = self.__get_session().query(dal.AssetClassStock).all() for entity in links: # log(DEBUG, f"adding {entity.symbol} to {entity.assetclassid}") # mapping stock: Stock = Stock(entity.symbol) # find parent classes by id and assign children parent: AssetClass = self.model.get_class_by_id(entity.assetclassid) if parent: # Assign to parent. parent.stocks.append(stock) # Add to index for easy reference self.model.stocks.append(stock)
def load_stock_links(self)
Read stock links into the model
7.763644
7.437394
1.043866
info = StocksInfo(self.config) for stock in self.model.stocks: stock.quantity = info.load_stock_quantity(stock.symbol) info.gc_book.close()
def load_stock_quantity(self)
Loads quantities for all stocks
8.155509
6.784525
1.202075
from pricedb import SecuritySymbol info = StocksInfo(self.config) for item in self.model.stocks: symbol = SecuritySymbol("", "") symbol.parse(item.symbol) price: PriceModel = info.load_latest_price(symbol) if not price: # Use a dummy price of 1, effectively keeping the original amount. price = PriceModel() price.currency = self.config.get(ConfigKeys.default_currency) price.value = Decimal(1) item.price = price.value if isinstance(item, Stock): item.currency = price.currency # Do not set currency for Cash balance records. info.close_databases()
def load_stock_prices(self)
Load latest prices for securities
8.478107
7.926024
1.069654
from .currency import CurrencyConverter conv = CurrencyConverter() cash = self.model.get_cash_asset_class() for stock in self.model.stocks: if stock.currency != self.base_currency: # Recalculate into base currency conv.load_currency(stock.currency) assert isinstance(stock.value, Decimal) val_base = stock.value * conv.rate.value else: # Already in base currency. val_base = stock.value stock.value_in_base_currency = val_base
def recalculate_stock_values_into_base(self)
Loads the exchange rates and recalculates stock holding values into base currency
4.861919
4.435936
1.09603
# load child classes for ac db = self.__get_session() entities = ( db.query(dal.AssetClass) .filter(dal.AssetClass.parentid == ac.id) .order_by(dal.AssetClass.sortorder) .all() ) # map for entity in entities: child_ac = self.__map_entity(entity) # depth child_ac.depth = ac.depth + 1 ac.classes.append(child_ac) # Add to index self.model.asset_classes.append(child_ac) self.__load_child_classes(child_ac)
def __load_child_classes(self, ac: AssetClass)
Loads child classes/stocks
3.455281
3.302392
1.046296
mapper = self.__get_mapper() ac = mapper.map_entity(entity) return ac
def __map_entity(self, entity: dal.AssetClass) -> AssetClass
maps the entity onto the model object
6.371558
5.649158
1.127877
db_path = self.__get_config().get(ConfigKeys.asset_allocation_database_path) self.session = dal.get_session(db_path) return self.session
def __get_session(self)
Opens a db session
7.913364
6.965743
1.13604
# open database db = self.__get_session() entity = db.query(dal.AssetClass).filter(dal.AssetClass.id == ac_id).first() return entity
def __load_asset_class(self, ac_id: int)
Loads Asset Class entity
5.747401
4.400071
1.306206
if asset_class.fullname == fullname: return asset_class if not hasattr(asset_class, "classes"): return None for child in asset_class.classes: found = self.__get_by_fullname(child, fullname) if found: return found return None
def __get_by_fullname(self, asset_class, fullname: str)
Recursive function
2.510276
2.052164
1.223234
# cfg = Config() # db_path = cfg.get(ConfigKeys.asset_allocation_database_path) # connection con_str = "sqlite:///" + db_path # Display all SQLite info with echo. engine = create_engine(con_str, echo=False) # create metadata (?) Base.metadata.create_all(engine) # create session Session = sessionmaker(bind=engine) session = Session() return session
def get_session(db_path: str)
Creates and opens a database session
5.666042
5.289841
1.071118
item = AssetClass() item.name = name app = AppAggregate() app.create_asset_class(item) print(f"Asset class {name} created.")
def add(name)
Add new Asset Class
8.262021
6.320488
1.307181
saved = False # load app = AppAggregate() item = app.get(id) if not item: raise KeyError("Asset Class with id %s not found.", id) if parent: assert parent != id, "Parent can not be set to self." # TODO check if parent exists? item.parentid = parent saved = True # click.echo(f"parent set to {parent}") if alloc: assert alloc != Decimal(0) item.allocation = alloc saved = True app.save() if saved: click.echo("Data saved.") else: click.echo("No data modified. Use --help to see possible parameters.")
def edit(id: int, parent: int, alloc: Decimal)
Edit asset class
5.425779
5.04588
1.075289
session = AppAggregate().open_session() classes = session.query(AssetClass).all() for item in classes: print(item)
def my_list()
Lists all asset classes
11.55798
7.489133
1.5433
# , help="The path to the CSV file to import. The first row must contain column names." lines = None with open(file) as csv_file: lines = csv_file.readlines() # Header, the first line. header = lines[0] lines.remove(header) header = header.rstrip() # Parse records from a csv row. counter = 0 app = AppAggregate() app.open_session() for line in lines: # Create insert statements line = line.rstrip() command = f"insert into AssetClass ({header}) values ({line});" # insert records app.session.execute(command) try: app.save() except: print(f"error: ", sys.exc_info()[0]) app.session.close() counter += 1 print(f"Data imported. {counter} rows created.")
def my_import(file)
Import Asset Class(es) from a .csv file
5.803177
5.543992
1.046751
session = AppAggregate().open_session() classes = session.query(AssetClass).all() # Get the root classes root = [] for ac in classes: if ac.parentid is None: root.append(ac) # logger.debug(ac.parentid) # header print_row("id", "asset class", "allocation", "level") print(f"-------------------------------") for ac in root: print_item_with_children(ac, classes, 0)
def tree()
Display a tree of asset classes
7.163776
6.357188
1.126878
print_row(ac.id, ac.name, f"{ac.allocation:,.2f}", level) print_children_recursively(classes, ac, level + 1)
def print_item_with_children(ac, classes, level)
Print the given item and all children items
6.229067
6.728953
0.925711
children = [child for child in all_items if child.parentid == for_item.id] for child in children: #message = f"{for_item.name}({for_item.id}) is a parent to {child.name}({child.id})" indent = " " * level * 2 id_col = f"{indent} {child.id}" print_row(id_col, child.name, f"{child.allocation:,.2f}", level) # Process children. print_children_recursively(all_items, child, level+1)
def print_children_recursively(all_items, for_item, level)
Print asset classes recursively
3.578801
3.635409
0.984429
#for i in range(0, len(argv)): # row += f"{argv[i]}" # columns row = "" # id row += f"{argv[0]:<3}" # name row += f" {argv[1]:<13}" # allocation row += f" {argv[2]:>5}" # level #row += f"{argv[3]}" print(row)
def print_row(*argv)
Print one row of data
4.418923
4.481239
0.986094
global g_parser if g_parser is None: g_parser = Parser() return g_parser.format(input_text, **context)
def render_html(input_text, **context)
A module-level convenience method that creates a default bbcode parser, and renders the input string as HTML.
3.699702
3.130571
1.181798
options = TagOptions(tag_name.strip().lower(), **kwargs) self.recognized_tags[options.tag_name] = (render_func, options)
def add_formatter(self, tag_name, render_func, **kwargs)
Installs a render function for the specified tag name. The render function should have the following signature: def render(tag_name, value, options, parent, context) The arguments are as follows: tag_name The name of the tag being rendered. value The context between start and end tags, or None for standalone tags. Whether this has been rendered depends on render_embedded tag option. options A dictionary of options specified on the opening tag. parent The parent TagOptions, if the tag is being rendered inside another tag, otherwise None. context The keyword argument dictionary passed into the format call.
5.891166
7.404213
0.795651
def _render(name, value, options, parent, context): fmt = {} if options: fmt.update(options) fmt.update({'value': value}) return format_string % fmt self.add_formatter(tag_name, _render, **kwargs)
def add_simple_formatter(self, tag_name, format_string, **kwargs)
Installs a formatter that takes the tag options dictionary, puts a value key in it, and uses it as a format dictionary to the given format string.
3.803655
3.389571
1.122164
self.add_simple_formatter('b', '<strong>%(value)s</strong>') self.add_simple_formatter('i', '<em>%(value)s</em>') self.add_simple_formatter('u', '<u>%(value)s</u>') self.add_simple_formatter('s', '<strike>%(value)s</strike>') self.add_simple_formatter('hr', '<hr />', standalone=True) self.add_simple_formatter('sub', '<sub>%(value)s</sub>') self.add_simple_formatter('sup', '<sup>%(value)s</sup>') def _render_list(name, value, options, parent, context): list_type = options['list'] if (options and 'list' in options) else '*' css_opts = { '1': 'decimal', '01': 'decimal-leading-zero', 'a': 'lower-alpha', 'A': 'upper-alpha', 'i': 'lower-roman', 'I': 'upper-roman', } tag = 'ol' if list_type in css_opts else 'ul' css = ' style="list-style-type:%s;"' % css_opts[list_type] if list_type in css_opts else '' return '<%s%s>%s</%s>' % (tag, css, value, tag) self.add_formatter('list', _render_list, transform_newlines=False, strip=True, swallow_trailing_newline=True) # Make sure transform_newlines = False for [*], so [code] tags can be embedded without transformation. def _render_list_item(name, value, options, parent, context): if not parent or parent.tag_name != 'list': return '[*]%s<br />' % value return '<li>%s</li>' % value self.add_formatter('*', _render_list_item, newline_closes=True, transform_newlines=False, same_tag_closes=True, strip=True) self.add_simple_formatter('quote', '<blockquote>%(value)s</blockquote>', strip=True, swallow_trailing_newline=True) self.add_simple_formatter('code', '<code>%(value)s</code>', render_embedded=False, transform_newlines=False, swallow_trailing_newline=True, replace_cosmetic=False) self.add_simple_formatter('center', '<div style="text-align:center;">%(value)s</div>') def _render_color(name, value, options, parent, context): if 'color' in options: color = options['color'].strip() elif options: color = list(options.keys())[0].strip() else: return value match = re.match(r'^([a-z]+)|^(#[a-f0-9]{3,6})', color, re.I) color = match.group() if match else 'inherit' return '<span style="color:%(color)s;">%(value)s</span>' % { 'color': color, 'value': value, } self.add_formatter('color', _render_color) def _render_url(name, value, options, parent, context): if options and 'url' in options: # Option values are not escaped for HTML output. href = self._replace(options['url'], self.REPLACE_ESCAPE) else: href = value # Completely ignore javascript: and data: "links". if re.sub(r'[^a-z0-9+]', '', href.lower().split(':', 1)[0]) in ('javascript', 'data', 'vbscript'): return '' # Only add the missing http:// if it looks like it starts with a domain name. if '://' not in href and _domain_re.match(href): href = 'http://' + href return self.url_template.format(href=href.replace('"', '%22'), text=value) self.add_formatter('url', _render_url, replace_links=False, replace_cosmetic=False)
def install_default_formatters(self)
Installs default formatters for the following tags: b, i, u, s, list (and \*), quote, code, center, color, url
2.67066
2.583223
1.033848
for find, repl in replacements: data = data.replace(find, repl) return data
def _replace(self, data, replacements)
Given a list of 2-tuples (find, repl) this function performs all replacements on the input and returns the result.
3.57901
2.498571
1.432423
parts = data.split('\n') tokens = [] for num, part in enumerate(parts): if part: tokens.append((self.TOKEN_DATA, None, None, part)) if num < (len(parts) - 1): tokens.append((self.TOKEN_NEWLINE, None, None, '\n')) return tokens
def _newline_tokenize(self, data)
Given a string that does not contain any tags, this function will return a list of NEWLINE and DATA tokens such that if you concatenate their data, you will have the original string.
2.737948
2.524664
1.08448
name = None try: # OrderedDict is only available for 2.7+, so leave regular unsorted dicts as a fallback. from collections import OrderedDict opts = OrderedDict() except ImportError: opts = {} in_value = False in_quote = False attr = '' value = '' attr_done = False stripped = data.strip() ls = len(stripped) pos = 0 while pos < ls: ch = stripped[pos] if in_value: if in_quote: if ch == '\\' and ls > pos + 1 and stripped[pos + 1] in ('\\', '"', "'"): value += stripped[pos + 1] pos += 1 elif ch == in_quote: in_quote = False in_value = False if attr: opts[attr.lower()] = value.strip() attr = '' value = '' else: value += ch else: if ch in ('"', "'"): in_quote = ch elif ch == ' ' and data.find('=', pos + 1) > 0: # If there is no = after this, the value may accept spaces. opts[attr.lower()] = value.strip() attr = '' value = '' in_value = False else: value += ch else: if ch == '=': in_value = True if name is None: name = attr elif ch == ' ': attr_done = True else: if attr_done: if attr: if name is None: name = attr else: opts[attr.lower()] = '' attr = '' attr_done = False attr += ch pos += 1 if attr: if name is None: name = attr opts[attr.lower()] = value.strip() return name.lower(), opts
def _parse_opts(self, data)
Given a tag string, this function will parse any options out of it and return a tuple of (tag_name, options_dict). Options may be quoted in order to preserve spaces, and free-standing options are allowed. The tag name itself may also serve as an option if it is immediately followed by an equal sign. Here are some examples: quote author="Dan Watson" tag_name=quote, options={'author': 'Dan Watson'} url="http://test.com/s.php?a=bcd efg" popup tag_name=url, options={'url': 'http://test.com/s.php?a=bcd efg', 'popup': ''}
2.702335
2.644153
1.022004
if not tag.startswith(self.tag_opener) or not tag.endswith(self.tag_closer) or ('\n' in tag) or ('\r' in tag): return (False, tag, False, None) tag_name = tag[len(self.tag_opener):-len(self.tag_closer)].strip() if not tag_name: return (False, tag, False, None) closer = False opts = {} if tag_name[0] == '/': tag_name = tag_name[1:] closer = True # Parse options inside the opening tag, if needed. if (('=' in tag_name) or (' ' in tag_name)) and not closer: tag_name, opts = self._parse_opts(tag_name) return (True, tag_name.strip().lower(), closer, opts)
def _parse_tag(self, tag)
Given a tag string (characters enclosed by []), this function will parse any options and return a tuple of the form: (valid, tag_name, closer, options)
2.711817
2.279335
1.18974
in_quote = False quotable = False lto = len(self.tag_opener) ltc = len(self.tag_closer) for i in xrange(start + 1, len(data)): ch = data[i] if ch == '=': quotable = True if ch in ('"', "'"): if quotable and not in_quote: in_quote = ch elif in_quote == ch: in_quote = False quotable = False if not in_quote and data[i:i + lto] == self.tag_opener: return i, False if not in_quote and data[i:i + ltc] == self.tag_closer: return i + ltc, True return len(data), False
def _tag_extent(self, data, start)
Finds the extent of a tag, accounting for option quoting and new tags starting before the current one closes. Returns (found_close, end_pos) where valid is False if another tag started before this one closed.
2.369605
2.26292
1.047145
data = data.replace('\r\n', '\n').replace('\r', '\n') pos = start = end = 0 ld = len(data) tokens = [] while pos < ld: start = data.find(self.tag_opener, pos) if start >= pos: # Check to see if there was data between this start and the last end. if start > pos: tl = self._newline_tokenize(data[pos:start]) tokens.extend(tl) pos = start # Find the extent of this tag, if it's ever closed. end, found_close = self._tag_extent(data, start) if found_close: tag = data[start:end] valid, tag_name, closer, opts = self._parse_tag(tag) # Make sure this is a well-formed, recognized tag, otherwise it's just data. if valid and tag_name in self.recognized_tags: if closer: tokens.append((self.TOKEN_TAG_END, tag_name, None, tag)) else: tokens.append((self.TOKEN_TAG_START, tag_name, opts, tag)) elif valid and self.drop_unrecognized and tag_name not in self.recognized_tags: # If we found a valid (but unrecognized) tag and self.drop_unrecognized is True, just drop it. pass else: tokens.extend(self._newline_tokenize(tag)) else: # We didn't find a closing tag, tack it on as text. tokens.extend(self._newline_tokenize(data[start:end])) pos = end else: # No more tags left to parse. break if pos < ld: tl = self._newline_tokenize(data[pos:]) tokens.extend(tl) return tokens
def tokenize(self, data)
Tokenizes the given string. A token is a 4-tuple of the form: (token_type, tag_name, tag_options, token_text) token_type One of: TOKEN_TAG_START, TOKEN_TAG_END, TOKEN_NEWLINE, TOKEN_DATA tag_name The name of the tag if token_type=TOKEN_TAG_*, otherwise None tag_options A dictionary of options specified for TOKEN_TAG_START, otherwise None token_text The original token text
3.312211
3.055907
1.083872
embed_count = 0 block_count = 0 lt = len(tokens) while pos < lt: token_type, tag_name, tag_opts, token_text = tokens[pos] if token_type == self.TOKEN_DATA: # Short-circuit for performance. pos += 1 continue if tag.newline_closes and token_type in (self.TOKEN_TAG_START, self.TOKEN_TAG_END): # If we're finding the closing token for a tag that is closed by newlines, but # there is an embedded tag that doesn't transform newlines (i.e. a code tag # that keeps newlines intact), we need to skip over that. inner_tag = self.recognized_tags[tag_name][1] if not inner_tag.transform_newlines: if token_type == self.TOKEN_TAG_START: block_count += 1 else: block_count -= 1 if token_type == self.TOKEN_NEWLINE and tag.newline_closes and block_count == 0: # If for some crazy reason there are embedded tags that both close on newline, # the first newline will automatically close all those nested tags. return pos, True elif token_type == self.TOKEN_TAG_START and tag_name == tag.tag_name: if tag.same_tag_closes: return pos, False if tag.render_embedded: embed_count += 1 elif token_type == self.TOKEN_TAG_END and tag_name == tag.tag_name: if embed_count > 0: embed_count -= 1 else: return pos, True pos += 1 return pos, True
def _find_closing_token(self, tag, tokens, pos)
Given the current tag options, a list of tokens, and the current position in the token list, this function will find the position of the closing token associated with the specified tag. This may be a closing tag, a newline, or simply the end of the list (to ensure tags are closed). This function should return a tuple of the form (end_pos, consume), where consume should indicate whether the ending token should be consumed or not.
3.5795
3.438761
1.040927
url = match.group(0) if self.linker: if self.linker_takes_context: return self.linker(url, context) else: return self.linker(url) else: href = url if '://' not in href: href = 'http://' + href # Escape quotes to avoid XSS, let the browser escape the rest. return self.url_template.format(href=href.replace('"', '%22'), text=url)
def _link_replace(self, match, **context)
Callback for re.sub to replace link text with markup. Turns out using a callback function is actually faster than using backrefs, plus this lets us provide a hook for user customization. linker_takes_context=True means that the linker gets passed context like a standard format function.
4.123423
3.252896
1.267616
url_matches = {} if self.replace_links and replace_links: # If we're replacing links in the text (i.e. not those in [url] tags) then we need to be # careful to pull them out before doing any escaping or cosmetic replacement. pos = 0 while True: match = _url_re.search(data, pos) if not match: break # Replace any link with a token that we can substitute back in after replacements. token = '{{ bbcode-link-%s }}' % len(url_matches) url_matches[token] = self._link_replace(match, **context) start, end = match.span() data = data[:start] + token + data[end:] # To be perfectly accurate, this should probably be len(data[:start] + token), but # start will work, because the token itself won't match as a URL. pos = start if escape_html: data = self._replace(data, self.REPLACE_ESCAPE) if replace_cosmetic: data = self._replace(data, self.REPLACE_COSMETIC) # Now put the replaced links back in the text. for token, replacement in url_matches.items(): data = data.replace(token, replacement) if transform_newlines: data = data.replace('\n', '\r') return data
def _transform(self, data, escape_html, replace_links, replace_cosmetic, transform_newlines, **context)
Transforms the input string based on the options specified, taking into account whether the option is enabled globally for this parser.
4.411331
4.476626
0.985414
tokens = self.tokenize(data) full_context = self.default_context.copy() full_context.update(context) return self._format_tokens(tokens, None, **full_context).replace('\r', self.newline)
def format(self, data, **context)
Formats the input text using any installed renderers. Any context keyword arguments given here will be passed along to the render functions as a context dictionary.
4.771622
4.307303
1.107798
text = [] for token_type, tag_name, tag_opts, token_text in self.tokenize(data): if token_type == self.TOKEN_DATA: text.append(token_text) elif token_type == self.TOKEN_NEWLINE and not strip_newlines: text.append(token_text) return ''.join(text)
def strip(self, data, strip_newlines=False)
Strips out any tags from the input text, using the same tokenization as the formatter.
2.75539
2.722872
1.011943
a_trunc = a // tol vals, counts = mode(a_trunc, axis) mask = (a_trunc == vals) # mean of each row return np.sum(a * mask, axis) / np.sum(mask, axis)
def mode_in_range(a, axis=0, tol=1E-3)
Find the mode of values to within a certain range
5.640103
5.891741
0.95729
return dict([(filt, model.score(periods)) for (filt, model) in self.models_.items()])
def scores(self, periods)
Compute the scores under the various models Parameters ---------- periods : array_like array of periods at which to compute scores Returns ------- scores : dict Dictionary of scores. Dictionary keys are the unique filter names passed to fit()
9.029473
10.959284
0.823911
for (key, model) in self.models_.items(): model.optimizer = self.optimizer return dict((filt, model.best_period) for (filt, model) in self.models_.items())
def best_periods(self)
Compute the scores under the various models Parameters ---------- periods : array_like array of periods at which to compute scores Returns ------- best_periods : dict Dictionary of best periods. Dictionary keys are the unique filter names passed to fit()
6.824163
7.146065
0.954954
# For linear models, dy=1 is equivalent to no errors if dy is None: dy = 1 self.t, self.y, self.dy = np.broadcast_arrays(t, y, dy) self._fit(self.t, self.y, self.dy) self._best_period = None # reset best period in case of refitting if self.fit_period: self._best_period = self._calc_best_period() return self
def fit(self, t, y, dy=None)
Fit the multiterm Periodogram model to the data. Parameters ---------- t : array_like, one-dimensional sequence of observation times y : array_like, one-dimensional sequence of observed values dy : float or array_like (optional) errors on observed values
3.763429
3.86806
0.97295
t = np.asarray(t) if period is None: period = self.best_period result = self._predict(t.ravel(), period=period) return result.reshape(t.shape)
def predict(self, t, period=None)
Compute the best-fit model at ``t`` for a given period Parameters ---------- t : float or array_like times at which to predict period : float (optional) The period at which to compute the model. If not specified, it will be computed via the optimizer provided at initialization. Returns ------- y : np.ndarray predicted model values at times t
3.301177
4.085125
0.808097
return self._score_frequency_grid(f0, df, N)
def score_frequency_grid(self, f0, df, N)
Compute the score on a frequency grid. Some models can compute results faster if the inputs are passed in this manner. Parameters ---------- f0, df, N : (float, float, int) parameters describing the frequency grid freq = f0 + df * arange(N) Note that these are frequencies, not angular frequencies. Returns ------- score : ndarray the length-N array giving the score at each frequency
3.626929
9.881021
0.36706
N = len(self.t) T = np.max(self.t) - np.min(self.t) df = 1. / T / oversampling f0 = df Nf = int(0.5 * oversampling * nyquist_factor * N) freq = f0 + df * np.arange(Nf) return 1. / freq, self._score_frequency_grid(f0, df, Nf)
def periodogram_auto(self, oversampling=5, nyquist_factor=3, return_periods=True)
Compute the periodogram on an automatically-determined grid This function uses heuristic arguments to choose a suitable frequency grid for the data. Note that depending on the data window function, the model may be sensitive to periodicity at higher frequencies than this function returns! The final number of frequencies will be Nf = oversampling * nyquist_factor * len(t) / 2 Parameters ---------- oversampling : float the number of samples per approximate peak width nyquist_factor : float the highest frequency, in units of the nyquist frequency for points spread uniformly through the data range. Returns ------- period : ndarray the grid of periods power : ndarray the power at each frequency
3.751449
4.126262
0.909164
periods = np.asarray(periods) return self._score(periods.ravel()).reshape(periods.shape)
def score(self, periods=None)
Compute the periodogram for the given period or periods Parameters ---------- periods : float or array_like Array of periods at which to compute the periodogram. Returns ------- scores : np.ndarray Array of normalized powers (between 0 and 1) for each period. Shape of scores matches the shape of the provided periods.
6.41082
8.253489
0.776741
if self._best_period is None: self._best_period = self._calc_best_period() return self._best_period
def best_period(self)
Lazy evaluation of the best period given the model
2.857224
2.317393
1.232947
return self.optimizer.find_best_periods(self, n_periods, return_scores=return_scores)
def find_best_periods(self, n_periods=5, return_scores=False)
Find the top several best periods for the model
4.15344
4.349001
0.955033
self.unique_filts_ = np.unique(filts) # For linear models, dy=1 is equivalent to no errors if dy is None: dy = 1 all_data = np.broadcast_arrays(t, y, dy, filts) self.t, self.y, self.dy, self.filts = map(np.ravel, all_data) self._fit(self.t, self.y, self.dy, self.filts) self._best_period = None # reset best period in case of refitting if self.fit_period: self._best_period = self._calc_best_period() return self
def fit(self, t, y, dy=None, filts=0)
Fit the multiterm Periodogram model to the data. Parameters ---------- t : array_like, one-dimensional sequence of observation times y : array_like, one-dimensional sequence of observed values dy : float or array_like (optional) errors on observed values filts : array_like (optional) The array specifying the filter/bandpass for each observation.
3.587828
3.53596
1.014669
unique_filts = set(np.unique(filts)) if not unique_filts.issubset(self.unique_filts_): raise ValueError("filts does not match training data: " "input: {0} output: {1}" "".format(set(self.unique_filts_), set(unique_filts))) t, filts = np.broadcast_arrays(t, filts) if period is None: period = self.best_period result = self._predict(t.ravel(), filts=filts.ravel(), period=period) return result.reshape(t.shape)
def predict(self, t, filts, period=None)
Compute the best-fit model at ``t`` for a given period Parameters ---------- t : float or array_like times at which to predict filts : array_like (optional) the array specifying the filter/bandpass for each observation. This is used only in multiband periodograms. period : float (optional) The period at which to compute the model. If not specified, it will be computed via the optimizer provided at initialization. Returns ------- y : np.ndarray predicted model values at times t
3.008857
3.284303
0.916132
X = self._construct_X(omega, weighted=True, **kwargs) M = np.dot(X.T, X) if getattr(self, 'regularization', None) is not None: diag = M.ravel(order='K')[::M.shape[0] + 1] if self.regularize_by_trace: diag += diag.sum() * np.asarray(self.regularization) else: diag += np.asarray(self.regularization) return X, M
def _construct_X_M(self, omega, **kwargs)
Construct the weighted normal matrix of the problem
3.461186
3.303403
1.047764
y = np.asarray(kwargs.get('y', self.y)) dy = np.asarray(kwargs.get('dy', self.dy)) if dy.size == 1: return np.mean(y) else: return np.average(y, weights=1 / dy ** 2)
def _compute_ymean(self, **kwargs)
Compute the (weighted) mean of the y data
2.472498
2.201612
1.12304
t = kwargs.get('t', self.t) dy = kwargs.get('dy', self.dy) fit_offset = kwargs.get('fit_offset', self.fit_offset) if fit_offset: offsets = [np.ones(len(t))] else: offsets = [] cols = sum(([np.sin((i + 1) * omega * t), np.cos((i + 1) * omega * t)] for i in range(self.Nterms)), offsets) if weighted: return np.transpose(np.vstack(cols) / dy) else: return np.transpose(np.vstack(cols))
def _construct_X(self, omega, weighted=True, **kwargs)
Construct the design matrix for the problem
2.872202
2.772336
1.036022
phase, y = self._get_template_by_id(templateid) # double-check that phase ranges from 0 to 1 assert phase.min() >= 0 assert phase.max() <= 1 # at the start and end points, we need to add ~5 points to make sure # the spline & derivatives wrap appropriately phase = np.concatenate([phase[-5:] - 1, phase, phase[:5] + 1]) y = np.concatenate([y[-5:], y, y[:5]]) # Univariate spline allows for derivatives; use this! return UnivariateSpline(phase, y, s=0, k=5)
def _interpolated_template(self, templateid)
Return an interpolator for the given template
5.808297
5.837974
0.994916
theta_best = [self._optimize(period, tmpid) for tmpid, _ in enumerate(self.templates)] chi2 = [self._chi2(theta, period, tmpid) for tmpid, theta in enumerate(theta_best)] return theta_best, chi2
def _eval_templates(self, period)
Evaluate the best template for the given period
4.682931
4.252057
1.101333
template = self.templates[tmpid] phase = (t / period - theta[2]) % 1 return theta[0] + theta[1] * template(phase)
def _model(self, t, theta, period, tmpid)
Compute model at t for the given parameters, period, & template
5.879387
4.587537
1.2816
template = self.templates[tmpid] phase = (self.t / period - theta[2]) % 1 model = theta[0] + theta[1] * template(phase) chi2 = (((model - self.y) / self.dy) ** 2).sum() if return_gradient: grad = 2 * (model - self.y) / self.dy ** 2 gradient = np.array([np.sum(grad), np.sum(grad * template(phase)), -np.sum(grad * theta[1] * template.derivative(1)(phase))]) return chi2, gradient else: return chi2
def _chi2(self, theta, period, tmpid, return_gradient=False)
Compute the chi2 for the given parameters, period, & template Optionally return the gradient for faster optimization
2.777893
2.7639
1.005063
theta_0 = [self.y.min(), self.y.max() - self.y.min(), 0] result = minimize(self._chi2, theta_0, jac=bool(use_gradient), bounds=[(None, None), (0, None), (None, None)], args=(period, tmpid, use_gradient)) return result.x
def _optimize(self, period, tmpid, use_gradient=True)
Optimize the model for the given period & template
3.550736
3.517948
1.00932
# compute the estimated peak width from the data range tmin, tmax = np.min(model.t), np.max(model.t) width = 2 * np.pi / (tmax - tmin) # raise a ValueError if period limits are out of range if tmax - tmin < np.max(self.period_range): raise ValueError("The optimizer is not designed to search for " "for periods larger than the data baseline. ") # our candidate steps in omega is controlled by period_range & coverage omega_step = width / self.first_pass_coverage omega_min = 2 * np.pi / np.max(self.period_range) omega_max = 2 * np.pi / np.min(self.period_range) omegas = np.arange(omega_min, omega_max + omega_step, omega_step) periods = 2 * np.pi / omegas # print some updates if desired if not self.quiet: print("Finding optimal frequency:") print(" - Estimated peak width = {0:.3g}".format(width)) print(" - Using {0} steps per peak; " "omega_step = {1:.3g}".format(self.first_pass_coverage, omega_step)) print(" - User-specified period range: " " {0:.2g} to {1:.2g}".format(periods.min(), periods.max())) print(" - Computing periods at {0:.0f} steps".format(len(periods))) sys.stdout.flush() # Compute the score on the initial grid N = int(1 + width // omega_step) score = model.score_frequency_grid(omega_min / (2 * np.pi), omega_step / (2 * np.pi), len(omegas)) # find initial candidates of unique peaks minscore = score.min() n_candidates = max(5, 2 * n_periods) candidate_freqs = np.zeros(n_candidates) candidate_scores = np.zeros(n_candidates) for i in range(n_candidates): j = np.argmax(score) candidate_freqs[i] = omegas[j] candidate_scores[i] = score[j] score[max(0, j - N):(j + N)] = minscore # If required, do a final pass on these unique at higher resolution if self.final_pass_coverage <= self.first_pass_coverage: best_periods = 2 * np.pi / candidate_freqs[:n_periods] best_scores = candidate_scores[:n_periods] else: f0 = -omega_step / (2 * np.pi) df = width / self.final_pass_coverage / (2 * np.pi) Nf = abs(2 * f0) // df steps = f0 + df * np.arange(Nf) candidate_freqs /= (2 * np.pi) freqs = steps + candidate_freqs[:, np.newaxis] periods = 1. / freqs if not self.quiet: print("Zooming-in on {0} candidate peaks:" "".format(n_candidates)) print(" - Computing periods at {0:.0f} " "steps".format(periods.size)) sys.stdout.flush() #scores = model.score(periods) scores = np.array([model.score_frequency_grid(c + f0, df, Nf) for c in candidate_freqs]) best_scores = scores.max(1) j = np.argmax(scores, 1) i = np.argsort(best_scores)[::-1] best_periods = periods[i, j[i]] best_scores = best_scores[i] if return_scores: return best_periods[:n_periods], best_scores[:n_periods] else: return best_periods[:n_periods]
def find_best_periods(self, model, n_periods=5, return_scores=False)
Find the `n_periods` best periods in the model
3.403512
3.409406
0.998271
if N < len(FACTORIALS): return FACTORIALS[N] else: from scipy import special return int(special.factorial(N))
def factorial(N)
Compute the factorial of N. If N <= 10, use a fast lookup table; otherwise use scipy.special.factorial
3.359873
2.80825
1.196429
# Note: for Python 2.7 and 3.x, this is faster: # return 1 << int(N - 1).bit_length() N = int(N) - 1 for i in [1, 2, 4, 8, 16, 32]: N |= N >> i return N + 1
def bitceil(N)
Find the bit (i.e. power of 2) immediately greater than or equal to N Note: this works for numbers up to 2 ** 64. Roughly equivalent to int(2 ** np.ceil(np.log2(N)))
3.55322
3.393852
1.046958