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 bal... | 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 ... | 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
... | 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... | 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):
... | 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_mo... | 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_... | 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 cu... | 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 al... | 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 link... | 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')... | 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 ... | 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,... | 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"... | 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 al... | 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_curr... | 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)... | 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}")
# f... | 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... | 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_... | 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 ... | 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
... | 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:
#... | 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(... | 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:
... | 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
... | 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 sessi... | 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
... | 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 c... | 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", "le... | 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"{ch... | 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
... | 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 />', sta... | 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 tok... | 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 = Fa... | 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
... | 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)
... | 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 ... | 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... | 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_*, otherwi... | 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
... | 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... | 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://' + hre... | 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:
... | 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... | 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 ... | 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
n... | 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_per... | 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 obse... | 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 ... | 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 the... | 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 return... | 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... | 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,... | 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 obse... | 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_),
... | 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 ... | 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.regulariz... | 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),
... | 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
... | 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.... | 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 o... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.