id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
3,800
MisterY/asset-allocation
asset_allocation/formatters.py
AsciiFormatter.format
def format(self, model: AssetAllocationModel, full: bool = False): """ Returns the view-friendly output of the aa model """ 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
python
def format(self, model: AssetAllocationModel, full: bool = False): 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", ")", ":", "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" ]
Returns the view-friendly output of the aa model
[ "Returns", "the", "view", "-", "friendly", "output", "of", "the", "aa", "model" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/formatters.py#L26-L50
3,801
MisterY/asset-allocation
asset_allocation/formatters.py
AsciiFormatter.__format_row
def __format_row(self, row: AssetAllocationViewModel): """ display-format one row Formats one Asset Class record """ 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
python
def __format_row(self, row: AssetAllocationViewModel): 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", ")", ":", "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" ]
display-format one row Formats one Asset Class record
[ "display", "-", "format", "one", "row", "Formats", "one", "Asset", "Class", "record" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/formatters.py#L52-L122
3,802
MisterY/asset-allocation
asset_allocation/maps.py
AssetClassMapper.map_entity
def map_entity(self, entity: dal.AssetClass): """ maps data from entity -> object """ 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
python
def map_entity(self, entity: dal.AssetClass): 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", ")", ":", "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" ]
maps data from entity -> object
[ "maps", "data", "from", "entity", "-", ">", "object" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/maps.py#L14-L28
3,803
MisterY/asset-allocation
asset_allocation/maps.py
ModelMapper.map_to_linear
def map_to_linear(self, with_stocks: bool=False): """ Maps the tree to a linear representation suitable for display """ result = [] for ac in self.model.classes: rows = self.__get_ac_tree(ac, with_stocks) result += rows return result
python
def map_to_linear(self, with_stocks: bool=False): 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", ")", ":", "result", "=", "[", "]", "for", "ac", "in", "self", ".", "model", ".", "classes", ":", "rows", "=", "self", ".", "__get_ac_tree", "(", "ac", ",", "with_stocks", ")", "result", "+=", "rows", "return", "result" ]
Maps the tree to a linear representation suitable for display
[ "Maps", "the", "tree", "to", "a", "linear", "representation", "suitable", "for", "display" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/maps.py#L36-L43
3,804
MisterY/asset-allocation
asset_allocation/maps.py
ModelMapper.__get_ac_tree
def __get_ac_tree(self, ac: model.AssetClass, with_stocks: bool): """ formats the ac tree - entity with child elements """ 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
python
def __get_ac_tree(self, ac: model.AssetClass, with_stocks: bool): 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", ")", ":", "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" ]
formats the ac tree - entity with child elements
[ "formats", "the", "ac", "tree", "-", "entity", "with", "child", "elements" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/maps.py#L45-L62
3,805
MisterY/asset-allocation
asset_allocation/maps.py
ModelMapper.__get_ac_row
def __get_ac_row(self, ac: model.AssetClass) -> AssetAllocationViewModel: """ Formats one Asset Class record """ 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
python
def __get_ac_row(self, ac: model.AssetClass) -> AssetAllocationViewModel: 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", ":", "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" ]
Formats one Asset Class record
[ "Formats", "one", "Asset", "Class", "record" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/maps.py#L64-L85
3,806
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.create_asset_class
def create_asset_class(self, item: AssetClass): """ Inserts the record """ session = self.open_session() session.add(item) session.commit()
python
def create_asset_class(self, item: AssetClass): session = self.open_session() session.add(item) session.commit()
[ "def", "create_asset_class", "(", "self", ",", "item", ":", "AssetClass", ")", ":", "session", "=", "self", ".", "open_session", "(", ")", "session", ".", "add", "(", "item", ")", "session", ".", "commit", "(", ")" ]
Inserts the record
[ "Inserts", "the", "record" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L20-L24
3,807
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.add_stock_to_class
def add_stock_to_class(self, assetclass_id: int, symbol: str): """ Add a stock link to an asset class """ 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
python
def add_stock_to_class(self, assetclass_id: int, symbol: str): 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", ")", ":", "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" ]
Add a stock link to an asset class
[ "Add", "a", "stock", "link", "to", "an", "asset", "class" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L26-L39
3,808
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.delete
def delete(self, id: int): """ Delete asset class """ assert isinstance(id, int) self.open_session() to_delete = self.get(id) self.session.delete(to_delete) self.save()
python
def delete(self, id: int): assert isinstance(id, int) self.open_session() to_delete = self.get(id) self.session.delete(to_delete) self.save()
[ "def", "delete", "(", "self", ",", "id", ":", "int", ")", ":", "assert", "isinstance", "(", "id", ",", "int", ")", "self", ".", "open_session", "(", ")", "to_delete", "=", "self", ".", "get", "(", "id", ")", "self", ".", "session", ".", "delete", "(", "to_delete", ")", "self", ".", "save", "(", ")" ]
Delete asset class
[ "Delete", "asset", "class" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L41-L48
3,809
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.find_unallocated_holdings
def find_unallocated_holdings(self): """ Identifies any holdings that are not included in asset allocation """ # 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
python
def find_unallocated_holdings(self): # 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", ")", ":", "# 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" ]
Identifies any holdings that are not included in asset allocation
[ "Identifies", "any", "holdings", "that", "are", "not", "included", "in", "asset", "allocation" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L50-L77
3,810
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.get
def get(self, id: int) -> AssetClass: """ Loads Asset Class """ self.open_session() item = self.session.query(AssetClass).filter( AssetClass.id == id).first() return item
python
def get(self, id: int) -> AssetClass: self.open_session() item = self.session.query(AssetClass).filter( AssetClass.id == id).first() return item
[ "def", "get", "(", "self", ",", "id", ":", "int", ")", "->", "AssetClass", ":", "self", ".", "open_session", "(", ")", "item", "=", "self", ".", "session", ".", "query", "(", "AssetClass", ")", ".", "filter", "(", "AssetClass", ".", "id", "==", "id", ")", ".", "first", "(", ")", "return", "item" ]
Loads Asset Class
[ "Loads", "Asset", "Class" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L79-L84
3,811
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.open_session
def open_session(self): """ Opens a db session and returns it """ 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
python
def open_session(self): 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", ")", ":", "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" ]
Opens a db session and returns it
[ "Opens", "a", "db", "session", "and", "returns", "it" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L86-L95
3,812
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.get_asset_allocation
def get_asset_allocation(self): """ Creates and populates the Asset Allocation model. The main function of the app. """ # 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
python
def get_asset_allocation(self): # 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", ")", ":", "# 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" ]
Creates and populates the Asset Allocation model. The main function of the app.
[ "Creates", "and", "populates", "the", "Asset", "Allocation", "model", ".", "The", "main", "function", "of", "the", "app", "." ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L101-L131
3,813
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.validate_model
def validate_model(self): """ Validate the model """ 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.")
python
def validate_model(self): 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", ")", ":", "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.\"", ")" ]
Validate the model
[ "Validate", "the", "model" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L146-L155
3,814
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.export_symbols
def export_symbols(self): """ Exports all used symbols """ 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")
python
def export_symbols(self): 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", ")", ":", "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\"", ")" ]
Exports all used symbols
[ "Exports", "all", "used", "symbols" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L157-L170
3,815
MisterY/asset-allocation
asset_allocation/config.py
Config.__read_config
def __read_config(self, file_path: str): """ Read the config file """ 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)
python
def __read_config(self, file_path: str): 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", ")", ":", "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", ")" ]
Read the config file
[ "Read", "the", "config", "file" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/config.py#L54-L63
3,816
MisterY/asset-allocation
asset_allocation/config.py
Config.__create_user_config
def __create_user_config(self): """ Copy the config template into user's directory """ 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!")
python
def __create_user_config(self): 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", ")", ":", "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!\"", ")" ]
Copy the config template into user's directory
[ "Copy", "the", "config", "template", "into", "user", "s", "directory" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/config.py#L75-L88
3,817
MisterY/asset-allocation
asset_allocation/config_cli.py
set
def set(aadb, cur): """ Sets the values in the config file """ 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.")
python
def set(aadb, cur): 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", ")", ":", "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.\"", ")" ]
Sets the values in the config file
[ "Sets", "the", "values", "in", "the", "config", "file" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/config_cli.py#L31-L49
3,818
MisterY/asset-allocation
asset_allocation/config_cli.py
get
def get(aadb: str): """ Retrieves a value from config """ 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.")
python
def get(aadb: str): 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", ")", ":", "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.\"", ")" ]
Retrieves a value from config
[ "Retrieves", "a", "value", "from", "config" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/config_cli.py#L53-L61
3,819
MisterY/asset-allocation
asset_allocation/model.py
_AssetBase.fullname
def fullname(self): """ includes the full path with parent names """ 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
python
def fullname(self): 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", ")", ":", "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" ]
includes the full path with parent names
[ "includes", "the", "full", "path", "with", "parent", "names" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L67-L77
3,820
MisterY/asset-allocation
asset_allocation/model.py
Stock.asset_class
def asset_class(self) -> str: """ Returns the full asset class path for this stock """ 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
python
def asset_class(self) -> str: 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", ":", "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" ]
Returns the full asset class path for this stock
[ "Returns", "the", "full", "asset", "class", "path", "for", "this", "stock" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L126-L134
3,821
MisterY/asset-allocation
asset_allocation/model.py
AssetClass.child_allocation
def child_allocation(self): """ The sum of all child asset classes' allocations """ 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
python
def child_allocation(self): 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", ")", ":", "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" ]
The sum of all child asset classes' allocations
[ "The", "sum", "of", "all", "child", "asset", "classes", "allocations" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L152-L162
3,822
MisterY/asset-allocation
asset_allocation/model.py
AssetAllocationModel.get_class_by_id
def get_class_by_id(self, ac_id: int) -> AssetClass: """ Finds the asset class by id """ 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
python
def get_class_by_id(self, ac_id: int) -> AssetClass: 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", ":", "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" ]
Finds the asset class by id
[ "Finds", "the", "asset", "class", "by", "id" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L182-L191
3,823
MisterY/asset-allocation
asset_allocation/model.py
AssetAllocationModel.get_cash_asset_class
def get_cash_asset_class(self) -> AssetClass: """ Find the cash asset class by name. """ for ac in self.asset_classes: if ac.name.lower() == "cash": return ac return None
python
def get_cash_asset_class(self) -> AssetClass: for ac in self.asset_classes: if ac.name.lower() == "cash": return ac return None
[ "def", "get_cash_asset_class", "(", "self", ")", "->", "AssetClass", ":", "for", "ac", "in", "self", ".", "asset_classes", ":", "if", "ac", ".", "name", ".", "lower", "(", ")", "==", "\"cash\"", ":", "return", "ac", "return", "None" ]
Find the cash asset class by name.
[ "Find", "the", "cash", "asset", "class", "by", "name", "." ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L193-L198
3,824
MisterY/asset-allocation
asset_allocation/model.py
AssetAllocationModel.validate
def validate(self) -> bool: """ Validate that the values match. Incomplete! """ # 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
python
def validate(self) -> bool: # 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", ":", "# 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" ]
Validate that the values match. Incomplete!
[ "Validate", "that", "the", "values", "match", ".", "Incomplete!" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L200-L227
3,825
MisterY/asset-allocation
asset_allocation/model.py
AssetAllocationModel.calculate_set_values
def calculate_set_values(self): """ Calculate the expected totals based on set allocations """ for ac in self.asset_classes: ac.alloc_value = self.total_amount * ac.allocation / Decimal(100)
python
def calculate_set_values(self): for ac in self.asset_classes: ac.alloc_value = self.total_amount * ac.allocation / Decimal(100)
[ "def", "calculate_set_values", "(", "self", ")", ":", "for", "ac", "in", "self", ".", "asset_classes", ":", "ac", ".", "alloc_value", "=", "self", ".", "total_amount", "*", "ac", ".", "allocation", "/", "Decimal", "(", "100", ")" ]
Calculate the expected totals based on set allocations
[ "Calculate", "the", "expected", "totals", "based", "on", "set", "allocations" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L229-L232
3,826
MisterY/asset-allocation
asset_allocation/model.py
AssetAllocationModel.calculate_current_allocation
def calculate_current_allocation(self): """ Calculates the current allocation % based on the value """ for ac in self.asset_classes: ac.curr_alloc = ac.curr_value * 100 / self.total_amount
python
def calculate_current_allocation(self): for ac in self.asset_classes: ac.curr_alloc = ac.curr_value * 100 / self.total_amount
[ "def", "calculate_current_allocation", "(", "self", ")", ":", "for", "ac", "in", "self", ".", "asset_classes", ":", "ac", ".", "curr_alloc", "=", "ac", ".", "curr_value", "*", "100", "/", "self", ".", "total_amount" ]
Calculates the current allocation % based on the value
[ "Calculates", "the", "current", "allocation", "%", "based", "on", "the", "value" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L234-L237
3,827
MisterY/asset-allocation
asset_allocation/model.py
AssetAllocationModel.calculate_current_value
def calculate_current_value(self): """ Add all the stock values and assign to the asset classes """ # must be recursive total = Decimal(0) for ac in self.classes: self.__calculate_current_value(ac) total += ac.curr_value self.total_amount = total
python
def calculate_current_value(self): # 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", ")", ":", "# must be recursive", "total", "=", "Decimal", "(", "0", ")", "for", "ac", "in", "self", ".", "classes", ":", "self", ".", "__calculate_current_value", "(", "ac", ")", "total", "+=", "ac", ".", "curr_value", "self", ".", "total_amount", "=", "total" ]
Add all the stock values and assign to the asset classes
[ "Add", "all", "the", "stock", "values", "and", "assign", "to", "the", "asset", "classes" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L239-L246
3,828
MisterY/asset-allocation
asset_allocation/model.py
AssetAllocationModel.__calculate_current_value
def __calculate_current_value(self, asset_class: AssetClass): """ Calculate totals for asset class by adding all the children values """ # 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
python
def __calculate_current_value(self, asset_class: AssetClass): # 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", ")", ":", "# 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" ]
Calculate totals for asset class by adding all the children values
[ "Calculate", "totals", "for", "asset", "class", "by", "adding", "all", "the", "children", "values" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L248-L264
3,829
MisterY/asset-allocation
asset_allocation/currency.py
CurrencyConverter.load_currency
def load_currency(self, mnemonic: str): """ load the latest rate for the given mnemonic; expressed in the base currency """ # , 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}!")
python
def load_currency(self, mnemonic: str): # , 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", ")", ":", "# , 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}!\"", ")" ]
load the latest rate for the given mnemonic; expressed in the base currency
[ "load", "the", "latest", "rate", "for", "the", "given", "mnemonic", ";", "expressed", "in", "the", "base", "currency" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/currency.py#L12-L24
3,830
MisterY/asset-allocation
asset_allocation/cli.py
show
def show(format, full): """ Print current allocation to the console. """ # 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)
python
def show(format, full): # 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", ")", ":", "# 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", ")" ]
Print current allocation to the console.
[ "Print", "current", "allocation", "to", "the", "console", "." ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/cli.py#L30-L46
3,831
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.load_cash_balances
def load_cash_balances(self): """ Loads cash balances from GnuCash book and recalculates into the default currency """ 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)
python
def load_cash_balances(self): 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", ")", ":", "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", ")" ]
Loads cash balances from GnuCash book and recalculates into the default currency
[ "Loads", "cash", "balances", "from", "GnuCash", "book", "and", "recalculates", "into", "the", "default", "currency" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L29-L44
3,832
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.__store_cash_balances_per_currency
def __store_cash_balances_per_currency(self, cash_balances): """ Store balance per currency as Stock records under Cash class """ 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)
python
def __store_cash_balances_per_currency(self, cash_balances): 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", ")", ":", "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", ")" ]
Store balance per currency as Stock records under Cash class
[ "Store", "balance", "per", "currency", "as", "Stock", "records", "under", "Cash", "class" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L53-L67
3,833
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.load_tree_from_db
def load_tree_from_db(self) -> AssetAllocationModel: """ Reads the asset allocation data only, and constructs the AA tree """ 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
python
def load_tree_from_db(self) -> AssetAllocationModel: 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", ":", "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" ]
Reads the asset allocation data only, and constructs the AA tree
[ "Reads", "the", "asset", "allocation", "data", "only", "and", "constructs", "the", "AA", "tree" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L69-L95
3,834
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.load_stock_links
def load_stock_links(self): """ Read stock links into the model """ 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)
python
def load_stock_links(self): 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", ")", ":", "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", ")" ]
Read stock links into the model
[ "Read", "stock", "links", "into", "the", "model" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L97-L110
3,835
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.load_stock_quantity
def load_stock_quantity(self): """ Loads quantities for all stocks """ info = StocksInfo(self.config) for stock in self.model.stocks: stock.quantity = info.load_stock_quantity(stock.symbol) info.gc_book.close()
python
def load_stock_quantity(self): 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", ")", ":", "info", "=", "StocksInfo", "(", "self", ".", "config", ")", "for", "stock", "in", "self", ".", "model", ".", "stocks", ":", "stock", ".", "quantity", "=", "info", ".", "load_stock_quantity", "(", "stock", ".", "symbol", ")", "info", ".", "gc_book", ".", "close", "(", ")" ]
Loads quantities for all stocks
[ "Loads", "quantities", "for", "all", "stocks" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L112-L117
3,836
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.load_stock_prices
def load_stock_prices(self): """ Load latest prices for securities """ 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()
python
def load_stock_prices(self): 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", ")", ":", "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", "(", ")" ]
Load latest prices for securities
[ "Load", "latest", "prices", "for", "securities" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L119-L138
3,837
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.recalculate_stock_values_into_base
def recalculate_stock_values_into_base(self): """ Loads the exchange rates and recalculates stock holding values into base currency """ 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
python
def recalculate_stock_values_into_base(self): 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", ")", ":", "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" ]
Loads the exchange rates and recalculates stock holding values into base currency
[ "Loads", "the", "exchange", "rates", "and", "recalculates", "stock", "holding", "values", "into", "base", "currency" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L140-L158
3,838
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.__map_entity
def __map_entity(self, entity: dal.AssetClass) -> AssetClass: """ maps the entity onto the model object """ mapper = self.__get_mapper() ac = mapper.map_entity(entity) return ac
python
def __map_entity(self, entity: dal.AssetClass) -> AssetClass: mapper = self.__get_mapper() ac = mapper.map_entity(entity) return ac
[ "def", "__map_entity", "(", "self", ",", "entity", ":", "dal", ".", "AssetClass", ")", "->", "AssetClass", ":", "mapper", "=", "self", ".", "__get_mapper", "(", ")", "ac", "=", "mapper", ".", "map_entity", "(", "entity", ")", "return", "ac" ]
maps the entity onto the model object
[ "maps", "the", "entity", "onto", "the", "model", "object" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L182-L186
3,839
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.__get_session
def __get_session(self): """ Opens a db session """ db_path = self.__get_config().get(ConfigKeys.asset_allocation_database_path) self.session = dal.get_session(db_path) return self.session
python
def __get_session(self): 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", ")", ":", "db_path", "=", "self", ".", "__get_config", "(", ")", ".", "get", "(", "ConfigKeys", ".", "asset_allocation_database_path", ")", "self", ".", "session", "=", "dal", ".", "get_session", "(", "db_path", ")", "return", "self", ".", "session" ]
Opens a db session
[ "Opens", "a", "db", "session" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L194-L198
3,840
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.__load_asset_class
def __load_asset_class(self, ac_id: int): """ Loads Asset Class entity """ # open database db = self.__get_session() entity = db.query(dal.AssetClass).filter(dal.AssetClass.id == ac_id).first() return entity
python
def __load_asset_class(self, ac_id: int): # 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", ")", ":", "# open database", "db", "=", "self", ".", "__get_session", "(", ")", "entity", "=", "db", ".", "query", "(", "dal", ".", "AssetClass", ")", ".", "filter", "(", "dal", ".", "AssetClass", ".", "id", "==", "ac_id", ")", ".", "first", "(", ")", "return", "entity" ]
Loads Asset Class entity
[ "Loads", "Asset", "Class", "entity" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L206-L211
3,841
MisterY/asset-allocation
asset_allocation/dal.py
get_session
def get_session(db_path: str): """ Creates and opens a database session """ # 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
python
def get_session(db_path: str): # 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", ")", ":", "# 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" ]
Creates and opens a database session
[ "Creates", "and", "opens", "a", "database", "session" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/dal.py#L53-L70
3,842
MisterY/asset-allocation
asset_allocation/assetclass_cli.py
add
def add(name): """ Add new Asset Class """ item = AssetClass() item.name = name app = AppAggregate() app.create_asset_class(item) print(f"Asset class {name} created.")
python
def add(name): item = AssetClass() item.name = name app = AppAggregate() app.create_asset_class(item) print(f"Asset class {name} created.")
[ "def", "add", "(", "name", ")", ":", "item", "=", "AssetClass", "(", ")", "item", ".", "name", "=", "name", "app", "=", "AppAggregate", "(", ")", "app", ".", "create_asset_class", "(", "item", ")", "print", "(", "f\"Asset class {name} created.\"", ")" ]
Add new Asset Class
[ "Add", "new", "Asset", "Class" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L28-L35
3,843
MisterY/asset-allocation
asset_allocation/assetclass_cli.py
edit
def edit(id: int, parent: int, alloc: Decimal): """ Edit asset class """ 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.")
python
def edit(id: int, parent: int, alloc: Decimal): 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", ")", ":", "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.\"", ")" ]
Edit asset class
[ "Edit", "asset", "class" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L50-L79
3,844
MisterY/asset-allocation
asset_allocation/assetclass_cli.py
my_list
def my_list(): """ Lists all asset classes """ session = AppAggregate().open_session() classes = session.query(AssetClass).all() for item in classes: print(item)
python
def my_list(): session = AppAggregate().open_session() classes = session.query(AssetClass).all() for item in classes: print(item)
[ "def", "my_list", "(", ")", ":", "session", "=", "AppAggregate", "(", ")", ".", "open_session", "(", ")", "classes", "=", "session", ".", "query", "(", "AssetClass", ")", ".", "all", "(", ")", "for", "item", "in", "classes", ":", "print", "(", "item", ")" ]
Lists all asset classes
[ "Lists", "all", "asset", "classes" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L83-L88
3,845
MisterY/asset-allocation
asset_allocation/assetclass_cli.py
tree
def tree(): """ Display a tree of asset classes """ 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)
python
def tree(): 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", "(", ")", ":", "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", ")" ]
Display a tree of asset classes
[ "Display", "a", "tree", "of", "asset", "classes" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L126-L141
3,846
MisterY/asset-allocation
asset_allocation/assetclass_cli.py
print_item_with_children
def print_item_with_children(ac, classes, level): """ Print the given item and all children items """ print_row(ac.id, ac.name, f"{ac.allocation:,.2f}", level) print_children_recursively(classes, ac, level + 1)
python
def print_item_with_children(ac, classes, level): 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_row", "(", "ac", ".", "id", ",", "ac", ".", "name", ",", "f\"{ac.allocation:,.2f}\"", ",", "level", ")", "print_children_recursively", "(", "classes", ",", "ac", ",", "level", "+", "1", ")" ]
Print the given item and all children items
[ "Print", "the", "given", "item", "and", "all", "children", "items" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L143-L146
3,847
MisterY/asset-allocation
asset_allocation/assetclass_cli.py
print_children_recursively
def print_children_recursively(all_items, for_item, level): """ Print asset classes recursively """ 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)
python
def print_children_recursively(all_items, for_item, level): 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", ")", ":", "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", ")" ]
Print asset classes recursively
[ "Print", "asset", "classes", "recursively" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L148-L158
3,848
MisterY/asset-allocation
asset_allocation/assetclass_cli.py
print_row
def print_row(*argv): """ Print one row of data """ #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)
python
def print_row(*argv): #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", ")", ":", "#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", ")" ]
Print one row of data
[ "Print", "one", "row", "of", "data" ]
72239aa20762cda67c091f27b86e65d61bf3b613
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L160-L175
3,849
dcwatson/bbcode
bbcode.py
render_html
def render_html(input_text, **context): """ A module-level convenience method that creates a default bbcode parser, and renders the input string as HTML. """ global g_parser if g_parser is None: g_parser = Parser() return g_parser.format(input_text, **context)
python
def render_html(input_text, **context): global g_parser if g_parser is None: g_parser = Parser() return g_parser.format(input_text, **context)
[ "def", "render_html", "(", "input_text", ",", "*", "*", "context", ")", ":", "global", "g_parser", "if", "g_parser", "is", "None", ":", "g_parser", "=", "Parser", "(", ")", "return", "g_parser", ".", "format", "(", "input_text", ",", "*", "*", "context", ")" ]
A module-level convenience method that creates a default bbcode parser, and renders the input string as HTML.
[ "A", "module", "-", "level", "convenience", "method", "that", "creates", "a", "default", "bbcode", "parser", "and", "renders", "the", "input", "string", "as", "HTML", "." ]
eb6f7ff140a78ddb1641102d7382479c4d7c1c78
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L604-L612
3,850
dcwatson/bbcode
bbcode.py
Parser.add_simple_formatter
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. """ 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)
python
def add_simple_formatter(self, tag_name, format_string, **kwargs): 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", ")", ":", "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", ")" ]
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.
[ "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", "." ]
eb6f7ff140a78ddb1641102d7382479c4d7c1c78
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L138-L149
3,851
dcwatson/bbcode
bbcode.py
Parser._newline_tokenize
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. """ 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
python
def _newline_tokenize(self, data): 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", ")", ":", "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" ]
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.
[ "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", "." ]
eb6f7ff140a78ddb1641102d7382479c4d7c1c78
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L231-L244
3,852
dcwatson/bbcode
bbcode.py
Parser._link_replace
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. """ 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)
python
def _link_replace(self, match, **context): 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", ")", ":", "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", ")" ]
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.
[ "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", "." ]
eb6f7ff140a78ddb1641102d7382479c4d7c1c78
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L473-L490
3,853
dcwatson/bbcode
bbcode.py
Parser._transform
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. """ 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
python
def _transform(self, data, escape_html, replace_links, replace_cosmetic, transform_newlines, **context): 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", ")", ":", "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" ]
Transforms the input string based on the options specified, taking into account whether the option is enabled globally for this parser.
[ "Transforms", "the", "input", "string", "based", "on", "the", "options", "specified", "taking", "into", "account", "whether", "the", "option", "is", "enabled", "globally", "for", "this", "parser", "." ]
eb6f7ff140a78ddb1641102d7382479c4d7c1c78
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L492-L523
3,854
dcwatson/bbcode
bbcode.py
Parser.format
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. """ 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)
python
def format(self, data, **context): 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", ")", ":", "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", ")" ]
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.
[ "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", "." ]
eb6f7ff140a78ddb1641102d7382479c4d7c1c78
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L578-L586
3,855
dcwatson/bbcode
bbcode.py
Parser.strip
def strip(self, data, strip_newlines=False): """ Strips out any tags from the input text, using the same tokenization as the formatter. """ 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)
python
def strip(self, data, strip_newlines=False): 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", ")", ":", "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", ")" ]
Strips out any tags from the input text, using the same tokenization as the formatter.
[ "Strips", "out", "any", "tags", "from", "the", "input", "text", "using", "the", "same", "tokenization", "as", "the", "formatter", "." ]
eb6f7ff140a78ddb1641102d7382479c4d7c1c78
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L588-L598
3,856
astroML/gatspy
gatspy/periodic/naive_multiband.py
mode_in_range
def mode_in_range(a, axis=0, tol=1E-3): """Find the mode of values to within a certain range""" 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)
python
def mode_in_range(a, axis=0, tol=1E-3): 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", ")", ":", "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", ")" ]
Find the mode of values to within a certain range
[ "Find", "the", "mode", "of", "values", "to", "within", "a", "certain", "range" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/naive_multiband.py#L18-L24
3,857
astroML/gatspy
gatspy/periodic/modeler.py
PeriodicModeler.score_frequency_grid
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 """ return self._score_frequency_grid(f0, df, N)
python
def score_frequency_grid(self, f0, df, N): return self._score_frequency_grid(f0, df, N)
[ "def", "score_frequency_grid", "(", "self", ",", "f0", ",", "df", ",", "N", ")", ":", "return", "self", ".", "_score_frequency_grid", "(", "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
[ "Compute", "the", "score", "on", "a", "frequency", "grid", "." ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L75-L92
3,858
astroML/gatspy
gatspy/periodic/modeler.py
PeriodicModeler.periodogram_auto
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 """ 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)
python
def periodogram_auto(self, oversampling=5, nyquist_factor=3, return_periods=True): 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", ")", ":", "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", ")" ]
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
[ "Compute", "the", "periodogram", "on", "an", "automatically", "-", "determined", "grid" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L94-L127
3,859
astroML/gatspy
gatspy/periodic/modeler.py
PeriodicModeler.score
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. """ periods = np.asarray(periods) return self._score(periods.ravel()).reshape(periods.shape)
python
def score(self, periods=None): periods = np.asarray(periods) return self._score(periods.ravel()).reshape(periods.shape)
[ "def", "score", "(", "self", ",", "periods", "=", "None", ")", ":", "periods", "=", "np", ".", "asarray", "(", "periods", ")", "return", "self", ".", "_score", "(", "periods", ".", "ravel", "(", ")", ")", ".", "reshape", "(", "periods", ".", "shape", ")" ]
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.
[ "Compute", "the", "periodogram", "for", "the", "given", "period", "or", "periods" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L129-L144
3,860
astroML/gatspy
gatspy/periodic/modeler.py
PeriodicModeler.best_period
def best_period(self): """Lazy evaluation of the best period given the model""" if self._best_period is None: self._best_period = self._calc_best_period() return self._best_period
python
def best_period(self): if self._best_period is None: self._best_period = self._calc_best_period() return self._best_period
[ "def", "best_period", "(", "self", ")", ":", "if", "self", ".", "_best_period", "is", "None", ":", "self", ".", "_best_period", "=", "self", ".", "_calc_best_period", "(", ")", "return", "self", ".", "_best_period" ]
Lazy evaluation of the best period given the model
[ "Lazy", "evaluation", "of", "the", "best", "period", "given", "the", "model" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L149-L153
3,861
astroML/gatspy
gatspy/periodic/modeler.py
PeriodicModeler.find_best_periods
def find_best_periods(self, n_periods=5, return_scores=False): """Find the top several best periods for the model""" return self.optimizer.find_best_periods(self, n_periods, return_scores=return_scores)
python
def find_best_periods(self, n_periods=5, return_scores=False): return self.optimizer.find_best_periods(self, n_periods, return_scores=return_scores)
[ "def", "find_best_periods", "(", "self", ",", "n_periods", "=", "5", ",", "return_scores", "=", "False", ")", ":", "return", "self", ".", "optimizer", ".", "find_best_periods", "(", "self", ",", "n_periods", ",", "return_scores", "=", "return_scores", ")" ]
Find the top several best periods for the model
[ "Find", "the", "top", "several", "best", "periods", "for", "the", "model" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L155-L158
3,862
astroML/gatspy
gatspy/periodic/_least_squares_mixin.py
LeastSquaresMixin._construct_X_M
def _construct_X_M(self, omega, **kwargs): """Construct the weighted normal matrix of the problem""" 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
python
def _construct_X_M(self, omega, **kwargs): 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", ")", ":", "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" ]
Construct the weighted normal matrix of the problem
[ "Construct", "the", "weighted", "normal", "matrix", "of", "the", "problem" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/_least_squares_mixin.py#L11-L23
3,863
astroML/gatspy
gatspy/periodic/lomb_scargle.py
LombScargle._construct_X
def _construct_X(self, omega, weighted=True, **kwargs): """Construct the design matrix for the problem""" 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))
python
def _construct_X(self, omega, weighted=True, **kwargs): 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", ")", ":", "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", ")", ")" ]
Construct the design matrix for the problem
[ "Construct", "the", "design", "matrix", "for", "the", "problem" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/lomb_scargle.py#L92-L110
3,864
astroML/gatspy
gatspy/periodic/template_modeler.py
BaseTemplateModeler._interpolated_template
def _interpolated_template(self, templateid): """Return an interpolator for the given template""" 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)
python
def _interpolated_template(self, templateid): 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", ")", ":", "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", ")" ]
Return an interpolator for the given template
[ "Return", "an", "interpolator", "for", "the", "given", "template" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/template_modeler.py#L39-L53
3,865
astroML/gatspy
gatspy/periodic/template_modeler.py
BaseTemplateModeler._eval_templates
def _eval_templates(self, period): """Evaluate the best template for the given period""" 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
python
def _eval_templates(self, period): 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", ")", ":", "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" ]
Evaluate the best template for the given period
[ "Evaluate", "the", "best", "template", "for", "the", "given", "period" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/template_modeler.py#L77-L84
3,866
astroML/gatspy
gatspy/periodic/template_modeler.py
BaseTemplateModeler._model
def _model(self, t, theta, period, tmpid): """Compute model at t for the given parameters, period, & template""" template = self.templates[tmpid] phase = (t / period - theta[2]) % 1 return theta[0] + theta[1] * template(phase)
python
def _model(self, t, theta, period, tmpid): template = self.templates[tmpid] phase = (t / period - theta[2]) % 1 return theta[0] + theta[1] * template(phase)
[ "def", "_model", "(", "self", ",", "t", ",", "theta", ",", "period", ",", "tmpid", ")", ":", "template", "=", "self", ".", "templates", "[", "tmpid", "]", "phase", "=", "(", "t", "/", "period", "-", "theta", "[", "2", "]", ")", "%", "1", "return", "theta", "[", "0", "]", "+", "theta", "[", "1", "]", "*", "template", "(", "phase", ")" ]
Compute model at t for the given parameters, period, & template
[ "Compute", "model", "at", "t", "for", "the", "given", "parameters", "period", "&", "template" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/template_modeler.py#L86-L90
3,867
astroML/gatspy
gatspy/periodic/template_modeler.py
BaseTemplateModeler._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 """ 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
python
def _chi2(self, theta, period, tmpid, return_gradient=False): 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", ")", ":", "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" ]
Compute the chi2 for the given parameters, period, & template Optionally return the gradient for faster optimization
[ "Compute", "the", "chi2", "for", "the", "given", "parameters", "period", "&", "template" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/template_modeler.py#L92-L111
3,868
astroML/gatspy
gatspy/periodic/template_modeler.py
BaseTemplateModeler._optimize
def _optimize(self, period, tmpid, use_gradient=True): """Optimize the model for the given period & template""" 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
python
def _optimize(self, period, tmpid, use_gradient=True): 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", ")", ":", "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" ]
Optimize the model for the given period & template
[ "Optimize", "the", "model", "for", "the", "given", "period", "&", "template" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/template_modeler.py#L113-L119
3,869
astroML/gatspy
gatspy/periodic/lomb_scargle_fast.py
factorial
def factorial(N): """Compute the factorial of N. If N <= 10, use a fast lookup table; otherwise use scipy.special.factorial """ if N < len(FACTORIALS): return FACTORIALS[N] else: from scipy import special return int(special.factorial(N))
python
def factorial(N): if N < len(FACTORIALS): return FACTORIALS[N] else: from scipy import special return int(special.factorial(N))
[ "def", "factorial", "(", "N", ")", ":", "if", "N", "<", "len", "(", "FACTORIALS", ")", ":", "return", "FACTORIALS", "[", "N", "]", "else", ":", "from", "scipy", "import", "special", "return", "int", "(", "special", ".", "factorial", "(", "N", ")", ")" ]
Compute the factorial of N. If N <= 10, use a fast lookup table; otherwise use scipy.special.factorial
[ "Compute", "the", "factorial", "of", "N", ".", "If", "N", "<", "=", "10", "use", "a", "fast", "lookup", "table", ";", "otherwise", "use", "scipy", ".", "special", ".", "factorial" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/lomb_scargle_fast.py#L17-L25
3,870
astroML/gatspy
gatspy/datasets/rrlyrae_generated.py
RRLyraeGenerated.observed
def observed(self, band, corrected=True): """Return observed values in the given band Parameters ---------- band : str desired bandpass: should be one of ['u', 'g', 'r', 'i', 'z'] corrected : bool (optional) If true, correct for extinction Returns ------- t, mag, dmag : ndarrays The times, magnitudes, and magnitude errors for the specified band. """ if band not in 'ugriz': raise ValueError("band='{0}' not recognized".format(band)) i = 'ugriz'.find(band) t, y, dy = self.lcdata.get_lightcurve(self.lcid, return_1d=False) if corrected: ext = self.obsmeta['rExt'] * self.ext_correction[band] else: ext = 0 return t[:, i], y[:, i] - ext, dy[:, i]
python
def observed(self, band, corrected=True): if band not in 'ugriz': raise ValueError("band='{0}' not recognized".format(band)) i = 'ugriz'.find(band) t, y, dy = self.lcdata.get_lightcurve(self.lcid, return_1d=False) if corrected: ext = self.obsmeta['rExt'] * self.ext_correction[band] else: ext = 0 return t[:, i], y[:, i] - ext, dy[:, i]
[ "def", "observed", "(", "self", ",", "band", ",", "corrected", "=", "True", ")", ":", "if", "band", "not", "in", "'ugriz'", ":", "raise", "ValueError", "(", "\"band='{0}' not recognized\"", ".", "format", "(", "band", ")", ")", "i", "=", "'ugriz'", ".", "find", "(", "band", ")", "t", ",", "y", ",", "dy", "=", "self", ".", "lcdata", ".", "get_lightcurve", "(", "self", ".", "lcid", ",", "return_1d", "=", "False", ")", "if", "corrected", ":", "ext", "=", "self", ".", "obsmeta", "[", "'rExt'", "]", "*", "self", ".", "ext_correction", "[", "band", "]", "else", ":", "ext", "=", "0", "return", "t", "[", ":", ",", "i", "]", ",", "y", "[", ":", ",", "i", "]", "-", "ext", ",", "dy", "[", ":", ",", "i", "]" ]
Return observed values in the given band Parameters ---------- band : str desired bandpass: should be one of ['u', 'g', 'r', 'i', 'z'] corrected : bool (optional) If true, correct for extinction Returns ------- t, mag, dmag : ndarrays The times, magnitudes, and magnitude errors for the specified band.
[ "Return", "observed", "values", "in", "the", "given", "band" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae_generated.py#L77-L102
3,871
astroML/gatspy
gatspy/datasets/rrlyrae_generated.py
RRLyraeGenerated.generated
def generated(self, band, t, err=None, corrected=True): """Return generated magnitudes in the specified band Parameters ---------- band : str desired bandpass: should be one of ['u', 'g', 'r', 'i', 'z'] t : array_like array of times (in days) err : float or array_like gaussian error in observations corrected : bool (optional) If true, correct for extinction Returns ------- mag : ndarray magnitudes at the specified times under the generated model. """ t = np.asarray(t) num = self.meta[band + 'T'] mu = self.meta[band + '0'] amp = self.meta[band + 'A'] t0 = self.meta[band + 'E'] # if there are nans or infinities, mask them bad_vals = np.isnan(t) | np.isinf(t) t[bad_vals] = t0 if corrected: ext = 0 else: ext = self.obsmeta['rExt'] * self.ext_correction[band] func = self._template_func(num, band, mu + ext, amp) mag = func(((t - t0) / self.period) % 1) mag[bad_vals] = np.nan if err is not None: mag += self.rng.normal(0, err, t.shape) return mag
python
def generated(self, band, t, err=None, corrected=True): t = np.asarray(t) num = self.meta[band + 'T'] mu = self.meta[band + '0'] amp = self.meta[band + 'A'] t0 = self.meta[band + 'E'] # if there are nans or infinities, mask them bad_vals = np.isnan(t) | np.isinf(t) t[bad_vals] = t0 if corrected: ext = 0 else: ext = self.obsmeta['rExt'] * self.ext_correction[band] func = self._template_func(num, band, mu + ext, amp) mag = func(((t - t0) / self.period) % 1) mag[bad_vals] = np.nan if err is not None: mag += self.rng.normal(0, err, t.shape) return mag
[ "def", "generated", "(", "self", ",", "band", ",", "t", ",", "err", "=", "None", ",", "corrected", "=", "True", ")", ":", "t", "=", "np", ".", "asarray", "(", "t", ")", "num", "=", "self", ".", "meta", "[", "band", "+", "'T'", "]", "mu", "=", "self", ".", "meta", "[", "band", "+", "'0'", "]", "amp", "=", "self", ".", "meta", "[", "band", "+", "'A'", "]", "t0", "=", "self", ".", "meta", "[", "band", "+", "'E'", "]", "# if there are nans or infinities, mask them", "bad_vals", "=", "np", ".", "isnan", "(", "t", ")", "|", "np", ".", "isinf", "(", "t", ")", "t", "[", "bad_vals", "]", "=", "t0", "if", "corrected", ":", "ext", "=", "0", "else", ":", "ext", "=", "self", ".", "obsmeta", "[", "'rExt'", "]", "*", "self", ".", "ext_correction", "[", "band", "]", "func", "=", "self", ".", "_template_func", "(", "num", ",", "band", ",", "mu", "+", "ext", ",", "amp", ")", "mag", "=", "func", "(", "(", "(", "t", "-", "t0", ")", "/", "self", ".", "period", ")", "%", "1", ")", "mag", "[", "bad_vals", "]", "=", "np", ".", "nan", "if", "err", "is", "not", "None", ":", "mag", "+=", "self", ".", "rng", ".", "normal", "(", "0", ",", "err", ",", "t", ".", "shape", ")", "return", "mag" ]
Return generated magnitudes in the specified band Parameters ---------- band : str desired bandpass: should be one of ['u', 'g', 'r', 'i', 'z'] t : array_like array of times (in days) err : float or array_like gaussian error in observations corrected : bool (optional) If true, correct for extinction Returns ------- mag : ndarray magnitudes at the specified times under the generated model.
[ "Return", "generated", "magnitudes", "in", "the", "specified", "band" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae_generated.py#L104-L146
3,872
astroML/gatspy
gatspy/datasets/rrlyrae.py
fetch_rrlyrae
def fetch_rrlyrae(partial=False, **kwargs): """Fetch RR Lyrae light curves from Sesar 2010 Parameters ---------- partial : bool (optional) If true, return the partial dataset (reduced to 1 band per night) Returns ------- rrlyrae : :class:`RRLyraeLC` object This object contains pointers to the RR Lyrae data. Other Parameters ---------------- data_home : str (optional) Specify the local cache directory for the dataset. If not used, it will default to the ``astroML`` default location. url : str (optional) Specify the URL of the datasets. Defaults to webpage associated with Sesar 2010. force_download : bool (optional) If true, then force re-downloading data even if it is already cached locally. Default is False. Examples -------- >>> rrlyrae = fetch_rrlyrae() >>> rrlyrae.ids[:5] [1013184, 1019544, 1027882, 1052471, 1056152] >>> lcid = rrlyrae.ids[0] >>> t, mag, dmag, bands = rrlyrae.get_lightcurve(lcid) >>> t[:4] array([ 51081.347856, 51081.349522, 51081.346189, 51081.347022]) >>> mag[:4] array([ 18.702, 17.553, 17.236, 17.124]) >>> dmag[:4] array([ 0.021, 0.005, 0.005, 0.006]) >>> list(bands[:4]) ['u', 'g', 'r', 'i'] """ if partial: return PartialRRLyraeLC('table1.tar.gz', cache_kwargs=kwargs) else: return RRLyraeLC('table1.tar.gz', cache_kwargs=kwargs)
python
def fetch_rrlyrae(partial=False, **kwargs): if partial: return PartialRRLyraeLC('table1.tar.gz', cache_kwargs=kwargs) else: return RRLyraeLC('table1.tar.gz', cache_kwargs=kwargs)
[ "def", "fetch_rrlyrae", "(", "partial", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "partial", ":", "return", "PartialRRLyraeLC", "(", "'table1.tar.gz'", ",", "cache_kwargs", "=", "kwargs", ")", "else", ":", "return", "RRLyraeLC", "(", "'table1.tar.gz'", ",", "cache_kwargs", "=", "kwargs", ")" ]
Fetch RR Lyrae light curves from Sesar 2010 Parameters ---------- partial : bool (optional) If true, return the partial dataset (reduced to 1 band per night) Returns ------- rrlyrae : :class:`RRLyraeLC` object This object contains pointers to the RR Lyrae data. Other Parameters ---------------- data_home : str (optional) Specify the local cache directory for the dataset. If not used, it will default to the ``astroML`` default location. url : str (optional) Specify the URL of the datasets. Defaults to webpage associated with Sesar 2010. force_download : bool (optional) If true, then force re-downloading data even if it is already cached locally. Default is False. Examples -------- >>> rrlyrae = fetch_rrlyrae() >>> rrlyrae.ids[:5] [1013184, 1019544, 1027882, 1052471, 1056152] >>> lcid = rrlyrae.ids[0] >>> t, mag, dmag, bands = rrlyrae.get_lightcurve(lcid) >>> t[:4] array([ 51081.347856, 51081.349522, 51081.346189, 51081.347022]) >>> mag[:4] array([ 18.702, 17.553, 17.236, 17.124]) >>> dmag[:4] array([ 0.021, 0.005, 0.005, 0.006]) >>> list(bands[:4]) ['u', 'g', 'r', 'i']
[ "Fetch", "RR", "Lyrae", "light", "curves", "from", "Sesar", "2010" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L343-L389
3,873
astroML/gatspy
gatspy/datasets/rrlyrae.py
fetch_rrlyrae_lc_params
def fetch_rrlyrae_lc_params(**kwargs): """Fetch data from table 2 of Sesar 2010 This table includes observationally-derived parameters for all the Sesar 2010 lightcurves. """ save_loc = _get_download_or_cache('table2.dat.gz', **kwargs) dtype = [('id', 'i'), ('type', 'S2'), ('P', 'f'), ('uA', 'f'), ('u0', 'f'), ('uE', 'f'), ('uT', 'f'), ('gA', 'f'), ('g0', 'f'), ('gE', 'f'), ('gT', 'f'), ('rA', 'f'), ('r0', 'f'), ('rE', 'f'), ('rT', 'f'), ('iA', 'f'), ('i0', 'f'), ('iE', 'f'), ('iT', 'f'), ('zA', 'f'), ('z0', 'f'), ('zE', 'f'), ('zT', 'f')] return np.loadtxt(save_loc, dtype=dtype)
python
def fetch_rrlyrae_lc_params(**kwargs): save_loc = _get_download_or_cache('table2.dat.gz', **kwargs) dtype = [('id', 'i'), ('type', 'S2'), ('P', 'f'), ('uA', 'f'), ('u0', 'f'), ('uE', 'f'), ('uT', 'f'), ('gA', 'f'), ('g0', 'f'), ('gE', 'f'), ('gT', 'f'), ('rA', 'f'), ('r0', 'f'), ('rE', 'f'), ('rT', 'f'), ('iA', 'f'), ('i0', 'f'), ('iE', 'f'), ('iT', 'f'), ('zA', 'f'), ('z0', 'f'), ('zE', 'f'), ('zT', 'f')] return np.loadtxt(save_loc, dtype=dtype)
[ "def", "fetch_rrlyrae_lc_params", "(", "*", "*", "kwargs", ")", ":", "save_loc", "=", "_get_download_or_cache", "(", "'table2.dat.gz'", ",", "*", "*", "kwargs", ")", "dtype", "=", "[", "(", "'id'", ",", "'i'", ")", ",", "(", "'type'", ",", "'S2'", ")", ",", "(", "'P'", ",", "'f'", ")", ",", "(", "'uA'", ",", "'f'", ")", ",", "(", "'u0'", ",", "'f'", ")", ",", "(", "'uE'", ",", "'f'", ")", ",", "(", "'uT'", ",", "'f'", ")", ",", "(", "'gA'", ",", "'f'", ")", ",", "(", "'g0'", ",", "'f'", ")", ",", "(", "'gE'", ",", "'f'", ")", ",", "(", "'gT'", ",", "'f'", ")", ",", "(", "'rA'", ",", "'f'", ")", ",", "(", "'r0'", ",", "'f'", ")", ",", "(", "'rE'", ",", "'f'", ")", ",", "(", "'rT'", ",", "'f'", ")", ",", "(", "'iA'", ",", "'f'", ")", ",", "(", "'i0'", ",", "'f'", ")", ",", "(", "'iE'", ",", "'f'", ")", ",", "(", "'iT'", ",", "'f'", ")", ",", "(", "'zA'", ",", "'f'", ")", ",", "(", "'z0'", ",", "'f'", ")", ",", "(", "'zE'", ",", "'f'", ")", ",", "(", "'zT'", ",", "'f'", ")", "]", "return", "np", ".", "loadtxt", "(", "save_loc", ",", "dtype", "=", "dtype", ")" ]
Fetch data from table 2 of Sesar 2010 This table includes observationally-derived parameters for all the Sesar 2010 lightcurves.
[ "Fetch", "data", "from", "table", "2", "of", "Sesar", "2010" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L392-L407
3,874
astroML/gatspy
gatspy/datasets/rrlyrae.py
fetch_rrlyrae_fitdata
def fetch_rrlyrae_fitdata(**kwargs): """Fetch data from table 3 of Sesar 2010 This table includes parameters derived from template fits to all the Sesar 2010 lightcurves. """ save_loc = _get_download_or_cache('table3.dat.gz', **kwargs) dtype = [('id', 'i'), ('RA', 'f'), ('DEC', 'f'), ('rExt', 'f'), ('d', 'f'), ('RGC', 'f'), ('u', 'f'), ('g', 'f'), ('r', 'f'), ('i', 'f'), ('z', 'f'), ('V', 'f'), ('ugmin', 'f'), ('ugmin_err', 'f'), ('grmin', 'f'), ('grmin_err', 'f')] return np.loadtxt(save_loc, dtype=dtype)
python
def fetch_rrlyrae_fitdata(**kwargs): save_loc = _get_download_or_cache('table3.dat.gz', **kwargs) dtype = [('id', 'i'), ('RA', 'f'), ('DEC', 'f'), ('rExt', 'f'), ('d', 'f'), ('RGC', 'f'), ('u', 'f'), ('g', 'f'), ('r', 'f'), ('i', 'f'), ('z', 'f'), ('V', 'f'), ('ugmin', 'f'), ('ugmin_err', 'f'), ('grmin', 'f'), ('grmin_err', 'f')] return np.loadtxt(save_loc, dtype=dtype)
[ "def", "fetch_rrlyrae_fitdata", "(", "*", "*", "kwargs", ")", ":", "save_loc", "=", "_get_download_or_cache", "(", "'table3.dat.gz'", ",", "*", "*", "kwargs", ")", "dtype", "=", "[", "(", "'id'", ",", "'i'", ")", ",", "(", "'RA'", ",", "'f'", ")", ",", "(", "'DEC'", ",", "'f'", ")", ",", "(", "'rExt'", ",", "'f'", ")", ",", "(", "'d'", ",", "'f'", ")", ",", "(", "'RGC'", ",", "'f'", ")", ",", "(", "'u'", ",", "'f'", ")", ",", "(", "'g'", ",", "'f'", ")", ",", "(", "'r'", ",", "'f'", ")", ",", "(", "'i'", ",", "'f'", ")", ",", "(", "'z'", ",", "'f'", ")", ",", "(", "'V'", ",", "'f'", ")", ",", "(", "'ugmin'", ",", "'f'", ")", ",", "(", "'ugmin_err'", ",", "'f'", ")", ",", "(", "'grmin'", ",", "'f'", ")", ",", "(", "'grmin_err'", ",", "'f'", ")", "]", "return", "np", ".", "loadtxt", "(", "save_loc", ",", "dtype", "=", "dtype", ")" ]
Fetch data from table 3 of Sesar 2010 This table includes parameters derived from template fits to all the Sesar 2010 lightcurves.
[ "Fetch", "data", "from", "table", "3", "of", "Sesar", "2010" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L410-L425
3,875
astroML/gatspy
gatspy/datasets/rrlyrae.py
RRLyraeLC.get_lightcurve
def get_lightcurve(self, star_id, return_1d=True): """Get the light curves for the given ID Parameters ---------- star_id : int A valid integer star id representing an object in the dataset return_1d : boolean (default=True) Specify whether to return 1D arrays of (t, y, dy, filts) or 2D arrays of (t, y, dy) where each column is a filter. Returns ------- t, y, dy : np.ndarrays (if return_1d == False) Times, magnitudes, and magnitude errors. The shape of each array is [Nobs, 5], where the columns refer to [u,g,r,i,z] bands. Non-observations are indicated by NaN. t, y, dy, filts : np.ndarrays (if return_1d == True) Times, magnitudes, magnitude errors, and filters The shape of each array is [Nobs], and non-observations are filtered out. """ filename = '{0}/{1}.dat'.format(self.dirname, star_id) try: data = np.loadtxt(self.data.extractfile(filename)) except KeyError: raise ValueError("invalid star id: {0}".format(star_id)) RA = data[:, 0] DEC = data[:, 1] t = data[:, 2::3] y = data[:, 3::3] dy = data[:, 4::3] nans = (y == -99.99) t[nans] = np.nan y[nans] = np.nan dy[nans] = np.nan if return_1d: t, y, dy, filts = np.broadcast_arrays(t, y, dy, ['u', 'g', 'r', 'i', 'z']) good = ~np.isnan(t) return t[good], y[good], dy[good], filts[good] else: return t, y, dy
python
def get_lightcurve(self, star_id, return_1d=True): filename = '{0}/{1}.dat'.format(self.dirname, star_id) try: data = np.loadtxt(self.data.extractfile(filename)) except KeyError: raise ValueError("invalid star id: {0}".format(star_id)) RA = data[:, 0] DEC = data[:, 1] t = data[:, 2::3] y = data[:, 3::3] dy = data[:, 4::3] nans = (y == -99.99) t[nans] = np.nan y[nans] = np.nan dy[nans] = np.nan if return_1d: t, y, dy, filts = np.broadcast_arrays(t, y, dy, ['u', 'g', 'r', 'i', 'z']) good = ~np.isnan(t) return t[good], y[good], dy[good], filts[good] else: return t, y, dy
[ "def", "get_lightcurve", "(", "self", ",", "star_id", ",", "return_1d", "=", "True", ")", ":", "filename", "=", "'{0}/{1}.dat'", ".", "format", "(", "self", ".", "dirname", ",", "star_id", ")", "try", ":", "data", "=", "np", ".", "loadtxt", "(", "self", ".", "data", ".", "extractfile", "(", "filename", ")", ")", "except", "KeyError", ":", "raise", "ValueError", "(", "\"invalid star id: {0}\"", ".", "format", "(", "star_id", ")", ")", "RA", "=", "data", "[", ":", ",", "0", "]", "DEC", "=", "data", "[", ":", ",", "1", "]", "t", "=", "data", "[", ":", ",", "2", ":", ":", "3", "]", "y", "=", "data", "[", ":", ",", "3", ":", ":", "3", "]", "dy", "=", "data", "[", ":", ",", "4", ":", ":", "3", "]", "nans", "=", "(", "y", "==", "-", "99.99", ")", "t", "[", "nans", "]", "=", "np", ".", "nan", "y", "[", "nans", "]", "=", "np", ".", "nan", "dy", "[", "nans", "]", "=", "np", ".", "nan", "if", "return_1d", ":", "t", ",", "y", ",", "dy", ",", "filts", "=", "np", ".", "broadcast_arrays", "(", "t", ",", "y", ",", "dy", ",", "[", "'u'", ",", "'g'", ",", "'r'", ",", "'i'", ",", "'z'", "]", ")", "good", "=", "~", "np", ".", "isnan", "(", "t", ")", "return", "t", "[", "good", "]", ",", "y", "[", "good", "]", ",", "dy", "[", "good", "]", ",", "filts", "[", "good", "]", "else", ":", "return", "t", ",", "y", ",", "dy" ]
Get the light curves for the given ID Parameters ---------- star_id : int A valid integer star id representing an object in the dataset return_1d : boolean (default=True) Specify whether to return 1D arrays of (t, y, dy, filts) or 2D arrays of (t, y, dy) where each column is a filter. Returns ------- t, y, dy : np.ndarrays (if return_1d == False) Times, magnitudes, and magnitude errors. The shape of each array is [Nobs, 5], where the columns refer to [u,g,r,i,z] bands. Non-observations are indicated by NaN. t, y, dy, filts : np.ndarrays (if return_1d == True) Times, magnitudes, magnitude errors, and filters The shape of each array is [Nobs], and non-observations are filtered out.
[ "Get", "the", "light", "curves", "for", "the", "given", "ID" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L125-L173
3,876
astroML/gatspy
gatspy/datasets/rrlyrae.py
RRLyraeLC.get_metadata
def get_metadata(self, lcid): """Get the parameters derived from the fit for the given id. This is table 2 of Sesar 2010 """ if self._metadata is None: self._metadata = fetch_rrlyrae_lc_params() i = np.where(self._metadata['id'] == lcid)[0] if len(i) == 0: raise ValueError("invalid lcid: {0}".format(lcid)) return self._metadata[i[0]]
python
def get_metadata(self, lcid): if self._metadata is None: self._metadata = fetch_rrlyrae_lc_params() i = np.where(self._metadata['id'] == lcid)[0] if len(i) == 0: raise ValueError("invalid lcid: {0}".format(lcid)) return self._metadata[i[0]]
[ "def", "get_metadata", "(", "self", ",", "lcid", ")", ":", "if", "self", ".", "_metadata", "is", "None", ":", "self", ".", "_metadata", "=", "fetch_rrlyrae_lc_params", "(", ")", "i", "=", "np", ".", "where", "(", "self", ".", "_metadata", "[", "'id'", "]", "==", "lcid", ")", "[", "0", "]", "if", "len", "(", "i", ")", "==", "0", ":", "raise", "ValueError", "(", "\"invalid lcid: {0}\"", ".", "format", "(", "lcid", ")", ")", "return", "self", ".", "_metadata", "[", "i", "[", "0", "]", "]" ]
Get the parameters derived from the fit for the given id. This is table 2 of Sesar 2010
[ "Get", "the", "parameters", "derived", "from", "the", "fit", "for", "the", "given", "id", ".", "This", "is", "table", "2", "of", "Sesar", "2010" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L175-L184
3,877
astroML/gatspy
gatspy/datasets/rrlyrae.py
RRLyraeLC.get_obsmeta
def get_obsmeta(self, lcid): """Get the observation metadata for the given id. This is table 3 of Sesar 2010 """ if self._obsdata is None: self._obsdata = fetch_rrlyrae_fitdata() i = np.where(self._obsdata['id'] == lcid)[0] if len(i) == 0: raise ValueError("invalid lcid: {0}".format(lcid)) return self._obsdata[i[0]]
python
def get_obsmeta(self, lcid): if self._obsdata is None: self._obsdata = fetch_rrlyrae_fitdata() i = np.where(self._obsdata['id'] == lcid)[0] if len(i) == 0: raise ValueError("invalid lcid: {0}".format(lcid)) return self._obsdata[i[0]]
[ "def", "get_obsmeta", "(", "self", ",", "lcid", ")", ":", "if", "self", ".", "_obsdata", "is", "None", ":", "self", ".", "_obsdata", "=", "fetch_rrlyrae_fitdata", "(", ")", "i", "=", "np", ".", "where", "(", "self", ".", "_obsdata", "[", "'id'", "]", "==", "lcid", ")", "[", "0", "]", "if", "len", "(", "i", ")", "==", "0", ":", "raise", "ValueError", "(", "\"invalid lcid: {0}\"", ".", "format", "(", "lcid", ")", ")", "return", "self", ".", "_obsdata", "[", "i", "[", "0", "]", "]" ]
Get the observation metadata for the given id. This is table 3 of Sesar 2010
[ "Get", "the", "observation", "metadata", "for", "the", "given", "id", ".", "This", "is", "table", "3", "of", "Sesar", "2010" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L186-L195
3,878
astroML/gatspy
gatspy/datasets/rrlyrae.py
RRLyraeTemplates.get_template
def get_template(self, template_id): """Get a particular lightcurve template Parameters ---------- template_id : str id of desired template Returns ------- phase : ndarray array of phases mag : ndarray array of normalized magnitudes """ try: data = np.loadtxt(self.data.extractfile(template_id + '.dat')) except KeyError: raise ValueError("invalid star id: {0}".format(template_id)) return data[:, 0], data[:, 1]
python
def get_template(self, template_id): try: data = np.loadtxt(self.data.extractfile(template_id + '.dat')) except KeyError: raise ValueError("invalid star id: {0}".format(template_id)) return data[:, 0], data[:, 1]
[ "def", "get_template", "(", "self", ",", "template_id", ")", ":", "try", ":", "data", "=", "np", ".", "loadtxt", "(", "self", ".", "data", ".", "extractfile", "(", "template_id", "+", "'.dat'", ")", ")", "except", "KeyError", ":", "raise", "ValueError", "(", "\"invalid star id: {0}\"", ".", "format", "(", "template_id", ")", ")", "return", "data", "[", ":", ",", "0", "]", ",", "data", "[", ":", ",", "1", "]" ]
Get a particular lightcurve template Parameters ---------- template_id : str id of desired template Returns ------- phase : ndarray array of phases mag : ndarray array of normalized magnitudes
[ "Get", "a", "particular", "lightcurve", "template" ]
a8f94082a3f27dfe9cb58165707b883bf28d9223
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L322-L340
3,879
vkurup/python-tcxparser
tcxparser/tcxparser.py
TCXParser.hr_avg
def hr_avg(self): """Average heart rate of the workout""" hr_data = self.hr_values() return int(sum(hr_data) / len(hr_data))
python
def hr_avg(self): hr_data = self.hr_values() return int(sum(hr_data) / len(hr_data))
[ "def", "hr_avg", "(", "self", ")", ":", "hr_data", "=", "self", ".", "hr_values", "(", ")", "return", "int", "(", "sum", "(", "hr_data", ")", "/", "len", "(", "hr_data", ")", ")" ]
Average heart rate of the workout
[ "Average", "heart", "rate", "of", "the", "workout" ]
b5bdd86d1e76f842043f28717e261d25025b1a8e
https://github.com/vkurup/python-tcxparser/blob/b5bdd86d1e76f842043f28717e261d25025b1a8e/tcxparser/tcxparser.py#L73-L76
3,880
vkurup/python-tcxparser
tcxparser/tcxparser.py
TCXParser.ascent
def ascent(self): """Returns ascent of workout in meters""" total_ascent = 0.0 altitude_data = self.altitude_points() for i in range(len(altitude_data) - 1): diff = altitude_data[i+1] - altitude_data[i] if diff > 0.0: total_ascent += diff return total_ascent
python
def ascent(self): total_ascent = 0.0 altitude_data = self.altitude_points() for i in range(len(altitude_data) - 1): diff = altitude_data[i+1] - altitude_data[i] if diff > 0.0: total_ascent += diff return total_ascent
[ "def", "ascent", "(", "self", ")", ":", "total_ascent", "=", "0.0", "altitude_data", "=", "self", ".", "altitude_points", "(", ")", "for", "i", "in", "range", "(", "len", "(", "altitude_data", ")", "-", "1", ")", ":", "diff", "=", "altitude_data", "[", "i", "+", "1", "]", "-", "altitude_data", "[", "i", "]", "if", "diff", ">", "0.0", ":", "total_ascent", "+=", "diff", "return", "total_ascent" ]
Returns ascent of workout in meters
[ "Returns", "ascent", "of", "workout", "in", "meters" ]
b5bdd86d1e76f842043f28717e261d25025b1a8e
https://github.com/vkurup/python-tcxparser/blob/b5bdd86d1e76f842043f28717e261d25025b1a8e/tcxparser/tcxparser.py#L113-L121
3,881
vkurup/python-tcxparser
tcxparser/tcxparser.py
TCXParser.descent
def descent(self): """Returns descent of workout in meters""" total_descent = 0.0 altitude_data = self.altitude_points() for i in range(len(altitude_data) - 1): diff = altitude_data[i+1] - altitude_data[i] if diff < 0.0: total_descent += abs(diff) return total_descent
python
def descent(self): total_descent = 0.0 altitude_data = self.altitude_points() for i in range(len(altitude_data) - 1): diff = altitude_data[i+1] - altitude_data[i] if diff < 0.0: total_descent += abs(diff) return total_descent
[ "def", "descent", "(", "self", ")", ":", "total_descent", "=", "0.0", "altitude_data", "=", "self", ".", "altitude_points", "(", ")", "for", "i", "in", "range", "(", "len", "(", "altitude_data", ")", "-", "1", ")", ":", "diff", "=", "altitude_data", "[", "i", "+", "1", "]", "-", "altitude_data", "[", "i", "]", "if", "diff", "<", "0.0", ":", "total_descent", "+=", "abs", "(", "diff", ")", "return", "total_descent" ]
Returns descent of workout in meters
[ "Returns", "descent", "of", "workout", "in", "meters" ]
b5bdd86d1e76f842043f28717e261d25025b1a8e
https://github.com/vkurup/python-tcxparser/blob/b5bdd86d1e76f842043f28717e261d25025b1a8e/tcxparser/tcxparser.py#L124-L132
3,882
uktrade/directory-validators
directory_validators/company.py
keywords_special_characters
def keywords_special_characters(keywords): """ Confirms that the keywords don't contain special characters Args: keywords (str) Raises: django.forms.ValidationError """ invalid_chars = '!\"#$%&\'()*+-./:;<=>?@[\\]^_{|}~\t\n' if any(char in invalid_chars for char in keywords): raise ValidationError(MESSAGE_KEYWORD_SPECIAL_CHARS)
python
def keywords_special_characters(keywords): invalid_chars = '!\"#$%&\'()*+-./:;<=>?@[\\]^_{|}~\t\n' if any(char in invalid_chars for char in keywords): raise ValidationError(MESSAGE_KEYWORD_SPECIAL_CHARS)
[ "def", "keywords_special_characters", "(", "keywords", ")", ":", "invalid_chars", "=", "'!\\\"#$%&\\'()*+-./:;<=>?@[\\\\]^_{|}~\\t\\n'", "if", "any", "(", "char", "in", "invalid_chars", "for", "char", "in", "keywords", ")", ":", "raise", "ValidationError", "(", "MESSAGE_KEYWORD_SPECIAL_CHARS", ")" ]
Confirms that the keywords don't contain special characters Args: keywords (str) Raises: django.forms.ValidationError
[ "Confirms", "that", "the", "keywords", "don", "t", "contain", "special", "characters" ]
e01f9d2aec683e34d978e4f67ed383ea2f9b85a0
https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/company.py#L45-L57
3,883
uktrade/directory-validators
directory_validators/company.py
image_format
def image_format(value): """ Confirms that the uploaded image is of supported format. Args: value (File): The file with an `image` property containing the image Raises: django.forms.ValidationError """ if value.image.format.upper() not in constants.ALLOWED_IMAGE_FORMATS: raise ValidationError(MESSAGE_INVALID_IMAGE_FORMAT)
python
def image_format(value): if value.image.format.upper() not in constants.ALLOWED_IMAGE_FORMATS: raise ValidationError(MESSAGE_INVALID_IMAGE_FORMAT)
[ "def", "image_format", "(", "value", ")", ":", "if", "value", ".", "image", ".", "format", ".", "upper", "(", ")", "not", "in", "constants", ".", "ALLOWED_IMAGE_FORMATS", ":", "raise", "ValidationError", "(", "MESSAGE_INVALID_IMAGE_FORMAT", ")" ]
Confirms that the uploaded image is of supported format. Args: value (File): The file with an `image` property containing the image Raises: django.forms.ValidationError
[ "Confirms", "that", "the", "uploaded", "image", "is", "of", "supported", "format", "." ]
e01f9d2aec683e34d978e4f67ed383ea2f9b85a0
https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/company.py#L60-L73
3,884
uktrade/directory-validators
directory_validators/company.py
no_company_with_insufficient_companies_house_data
def no_company_with_insufficient_companies_house_data(value): """ Confirms that the company number is not for for a company that Companies House does not hold information on. Args: value (string): The company number to check. Raises: django.forms.ValidationError """ for prefix, name in company_types_with_insufficient_companies_house_data: if value.upper().startswith(prefix): raise ValidationError( MESSAGE_INSUFFICIENT_DATA, params={'name': name} )
python
def no_company_with_insufficient_companies_house_data(value): for prefix, name in company_types_with_insufficient_companies_house_data: if value.upper().startswith(prefix): raise ValidationError( MESSAGE_INSUFFICIENT_DATA, params={'name': name} )
[ "def", "no_company_with_insufficient_companies_house_data", "(", "value", ")", ":", "for", "prefix", ",", "name", "in", "company_types_with_insufficient_companies_house_data", ":", "if", "value", ".", "upper", "(", ")", ".", "startswith", "(", "prefix", ")", ":", "raise", "ValidationError", "(", "MESSAGE_INSUFFICIENT_DATA", ",", "params", "=", "{", "'name'", ":", "name", "}", ")" ]
Confirms that the company number is not for for a company that Companies House does not hold information on. Args: value (string): The company number to check. Raises: django.forms.ValidationError
[ "Confirms", "that", "the", "company", "number", "is", "not", "for", "for", "a", "company", "that", "Companies", "House", "does", "not", "hold", "information", "on", "." ]
e01f9d2aec683e34d978e4f67ed383ea2f9b85a0
https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/company.py#L179-L196
3,885
ruipgil/TrackToTrip
tracktotrip/segment.py
remove_liers
def remove_liers(points): """ Removes obvious noise points Checks time consistency, removing points that appear out of order Args: points (:obj:`list` of :obj:`Point`) Returns: :obj:`list` of :obj:`Point` """ result = [points[0]] for i in range(1, len(points) - 2): prv = points[i-1] crr = points[i] nxt = points[i+1] if prv.time <= crr.time and crr.time <= nxt.time: result.append(crr) result.append(points[-1]) return result
python
def remove_liers(points): result = [points[0]] for i in range(1, len(points) - 2): prv = points[i-1] crr = points[i] nxt = points[i+1] if prv.time <= crr.time and crr.time <= nxt.time: result.append(crr) result.append(points[-1]) return result
[ "def", "remove_liers", "(", "points", ")", ":", "result", "=", "[", "points", "[", "0", "]", "]", "for", "i", "in", "range", "(", "1", ",", "len", "(", "points", ")", "-", "2", ")", ":", "prv", "=", "points", "[", "i", "-", "1", "]", "crr", "=", "points", "[", "i", "]", "nxt", "=", "points", "[", "i", "+", "1", "]", "if", "prv", ".", "time", "<=", "crr", ".", "time", "and", "crr", ".", "time", "<=", "nxt", ".", "time", ":", "result", ".", "append", "(", "crr", ")", "result", ".", "append", "(", "points", "[", "-", "1", "]", ")", "return", "result" ]
Removes obvious noise points Checks time consistency, removing points that appear out of order Args: points (:obj:`list` of :obj:`Point`) Returns: :obj:`list` of :obj:`Point`
[ "Removes", "obvious", "noise", "points" ]
5537c14ee9748091b5255b658ab528e1d6227f99
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L20-L39
3,886
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.bounds
def bounds(self, thr=0, lower_index=0, upper_index=-1): """ Computes the bounds of the segment, or part of it Args: lower_index (int, optional): Start index. Defaults to 0 upper_index (int, optional): End index. Defaults to 0 Returns: :obj:`tuple` of :obj:`float`: Bounds of the (sub)segment, such that (min_lat, min_lon, max_lat, max_lon) """ points = self.points[lower_index:upper_index] min_lat = float("inf") min_lon = float("inf") max_lat = -float("inf") max_lon = -float("inf") for point in points: min_lat = min(min_lat, point.lat) min_lon = min(min_lon, point.lon) max_lat = max(max_lat, point.lat) max_lon = max(max_lon, point.lon) return (min_lat - thr, min_lon - thr, max_lat + thr, max_lon + thr)
python
def bounds(self, thr=0, lower_index=0, upper_index=-1): points = self.points[lower_index:upper_index] min_lat = float("inf") min_lon = float("inf") max_lat = -float("inf") max_lon = -float("inf") for point in points: min_lat = min(min_lat, point.lat) min_lon = min(min_lon, point.lon) max_lat = max(max_lat, point.lat) max_lon = max(max_lon, point.lon) return (min_lat - thr, min_lon - thr, max_lat + thr, max_lon + thr)
[ "def", "bounds", "(", "self", ",", "thr", "=", "0", ",", "lower_index", "=", "0", ",", "upper_index", "=", "-", "1", ")", ":", "points", "=", "self", ".", "points", "[", "lower_index", ":", "upper_index", "]", "min_lat", "=", "float", "(", "\"inf\"", ")", "min_lon", "=", "float", "(", "\"inf\"", ")", "max_lat", "=", "-", "float", "(", "\"inf\"", ")", "max_lon", "=", "-", "float", "(", "\"inf\"", ")", "for", "point", "in", "points", ":", "min_lat", "=", "min", "(", "min_lat", ",", "point", ".", "lat", ")", "min_lon", "=", "min", "(", "min_lon", ",", "point", ".", "lon", ")", "max_lat", "=", "max", "(", "max_lat", ",", "point", ".", "lat", ")", "max_lon", "=", "max", "(", "max_lon", ",", "point", ".", "lon", ")", "return", "(", "min_lat", "-", "thr", ",", "min_lon", "-", "thr", ",", "max_lat", "+", "thr", ",", "max_lon", "+", "thr", ")" ]
Computes the bounds of the segment, or part of it Args: lower_index (int, optional): Start index. Defaults to 0 upper_index (int, optional): End index. Defaults to 0 Returns: :obj:`tuple` of :obj:`float`: Bounds of the (sub)segment, such that (min_lat, min_lon, max_lat, max_lon)
[ "Computes", "the", "bounds", "of", "the", "segment", "or", "part", "of", "it" ]
5537c14ee9748091b5255b658ab528e1d6227f99
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L65-L88
3,887
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.smooth
def smooth(self, noise, strategy=INVERSE_STRATEGY): """ In-place smoothing See smooth_segment function Args: noise (float): Noise expected strategy (int): Strategy to use. Either smooth.INVERSE_STRATEGY or smooth.EXTRAPOLATE_STRATEGY Returns: :obj:`Segment` """ if strategy is INVERSE_STRATEGY: self.points = with_inverse(self.points, noise) elif strategy is EXTRAPOLATE_STRATEGY: self.points = with_extrapolation(self.points, noise, 30) elif strategy is NO_STRATEGY: self.points = with_no_strategy(self.points, noise) return self
python
def smooth(self, noise, strategy=INVERSE_STRATEGY): if strategy is INVERSE_STRATEGY: self.points = with_inverse(self.points, noise) elif strategy is EXTRAPOLATE_STRATEGY: self.points = with_extrapolation(self.points, noise, 30) elif strategy is NO_STRATEGY: self.points = with_no_strategy(self.points, noise) return self
[ "def", "smooth", "(", "self", ",", "noise", ",", "strategy", "=", "INVERSE_STRATEGY", ")", ":", "if", "strategy", "is", "INVERSE_STRATEGY", ":", "self", ".", "points", "=", "with_inverse", "(", "self", ".", "points", ",", "noise", ")", "elif", "strategy", "is", "EXTRAPOLATE_STRATEGY", ":", "self", ".", "points", "=", "with_extrapolation", "(", "self", ".", "points", ",", "noise", ",", "30", ")", "elif", "strategy", "is", "NO_STRATEGY", ":", "self", ".", "points", "=", "with_no_strategy", "(", "self", ".", "points", ",", "noise", ")", "return", "self" ]
In-place smoothing See smooth_segment function Args: noise (float): Noise expected strategy (int): Strategy to use. Either smooth.INVERSE_STRATEGY or smooth.EXTRAPOLATE_STRATEGY Returns: :obj:`Segment`
[ "In", "-", "place", "smoothing" ]
5537c14ee9748091b5255b658ab528e1d6227f99
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L101-L119
3,888
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.simplify
def simplify(self, eps, max_dist_error, max_speed_error, topology_only=False): """ In-place segment simplification See `drp` and `compression` modules Args: eps (float): Distance threshold for the `drp` function max_dist_error (float): Max distance error, in meters max_speed_error (float): Max speed error, in km/h topology_only (bool, optional): True to only keep topology, not considering times when simplifying. Defaults to False. Returns: :obj:`Segment` """ if topology_only: self.points = drp(self.points, eps) else: self.points = spt(self.points, max_dist_error, max_speed_error) return self
python
def simplify(self, eps, max_dist_error, max_speed_error, topology_only=False): if topology_only: self.points = drp(self.points, eps) else: self.points = spt(self.points, max_dist_error, max_speed_error) return self
[ "def", "simplify", "(", "self", ",", "eps", ",", "max_dist_error", ",", "max_speed_error", ",", "topology_only", "=", "False", ")", ":", "if", "topology_only", ":", "self", ".", "points", "=", "drp", "(", "self", ".", "points", ",", "eps", ")", "else", ":", "self", ".", "points", "=", "spt", "(", "self", ".", "points", ",", "max_dist_error", ",", "max_speed_error", ")", "return", "self" ]
In-place segment simplification See `drp` and `compression` modules Args: eps (float): Distance threshold for the `drp` function max_dist_error (float): Max distance error, in meters max_speed_error (float): Max speed error, in km/h topology_only (bool, optional): True to only keep topology, not considering times when simplifying. Defaults to False. Returns: :obj:`Segment`
[ "In", "-", "place", "segment", "simplification" ]
5537c14ee9748091b5255b658ab528e1d6227f99
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L134-L152
3,889
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.compute_metrics
def compute_metrics(self): """ Computes metrics for each point Returns: :obj:`Segment`: self """ for prev, point in pairwise(self.points): point.compute_metrics(prev) return self
python
def compute_metrics(self): for prev, point in pairwise(self.points): point.compute_metrics(prev) return self
[ "def", "compute_metrics", "(", "self", ")", ":", "for", "prev", ",", "point", "in", "pairwise", "(", "self", ".", "points", ")", ":", "point", ".", "compute_metrics", "(", "prev", ")", "return", "self" ]
Computes metrics for each point Returns: :obj:`Segment`: self
[ "Computes", "metrics", "for", "each", "point" ]
5537c14ee9748091b5255b658ab528e1d6227f99
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L154-L162
3,890
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.infer_location
def infer_location( self, location_query, max_distance, google_key, foursquare_client_id, foursquare_client_secret, limit ): """In-place location inferring See infer_location function Args: Returns: :obj:`Segment`: self """ self.location_from = infer_location( self.points[0], location_query, max_distance, google_key, foursquare_client_id, foursquare_client_secret, limit ) self.location_to = infer_location( self.points[-1], location_query, max_distance, google_key, foursquare_client_id, foursquare_client_secret, limit ) return self
python
def infer_location( self, location_query, max_distance, google_key, foursquare_client_id, foursquare_client_secret, limit ): self.location_from = infer_location( self.points[0], location_query, max_distance, google_key, foursquare_client_id, foursquare_client_secret, limit ) self.location_to = infer_location( self.points[-1], location_query, max_distance, google_key, foursquare_client_id, foursquare_client_secret, limit ) return self
[ "def", "infer_location", "(", "self", ",", "location_query", ",", "max_distance", ",", "google_key", ",", "foursquare_client_id", ",", "foursquare_client_secret", ",", "limit", ")", ":", "self", ".", "location_from", "=", "infer_location", "(", "self", ".", "points", "[", "0", "]", ",", "location_query", ",", "max_distance", ",", "google_key", ",", "foursquare_client_id", ",", "foursquare_client_secret", ",", "limit", ")", "self", ".", "location_to", "=", "infer_location", "(", "self", ".", "points", "[", "-", "1", "]", ",", "location_query", ",", "max_distance", ",", "google_key", ",", "foursquare_client_id", ",", "foursquare_client_secret", ",", "limit", ")", "return", "self" ]
In-place location inferring See infer_location function Args: Returns: :obj:`Segment`: self
[ "In", "-", "place", "location", "inferring" ]
5537c14ee9748091b5255b658ab528e1d6227f99
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L164-L201
3,891
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.infer_transportation_mode
def infer_transportation_mode(self, clf, min_time): """In-place transportation mode inferring See infer_transportation_mode function Args: Returns: :obj:`Segment`: self """ self.transportation_modes = speed_clustering(clf, self.points, min_time) return self
python
def infer_transportation_mode(self, clf, min_time): self.transportation_modes = speed_clustering(clf, self.points, min_time) return self
[ "def", "infer_transportation_mode", "(", "self", ",", "clf", ",", "min_time", ")", ":", "self", ".", "transportation_modes", "=", "speed_clustering", "(", "clf", ",", "self", ".", "points", ",", "min_time", ")", "return", "self" ]
In-place transportation mode inferring See infer_transportation_mode function Args: Returns: :obj:`Segment`: self
[ "In", "-", "place", "transportation", "mode", "inferring" ]
5537c14ee9748091b5255b658ab528e1d6227f99
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L203-L213
3,892
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.merge_and_fit
def merge_and_fit(self, segment): """ Merges another segment with this one, ordering the points based on a distance heuristic Args: segment (:obj:`Segment`): Segment to merge with Returns: :obj:`Segment`: self """ self.points = sort_segment_points(self.points, segment.points) return self
python
def merge_and_fit(self, segment): self.points = sort_segment_points(self.points, segment.points) return self
[ "def", "merge_and_fit", "(", "self", ",", "segment", ")", ":", "self", ".", "points", "=", "sort_segment_points", "(", "self", ".", "points", ",", "segment", ".", "points", ")", "return", "self" ]
Merges another segment with this one, ordering the points based on a distance heuristic Args: segment (:obj:`Segment`): Segment to merge with Returns: :obj:`Segment`: self
[ "Merges", "another", "segment", "with", "this", "one", "ordering", "the", "points", "based", "on", "a", "distance", "heuristic" ]
5537c14ee9748091b5255b658ab528e1d6227f99
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L215-L225
3,893
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.closest_point_to
def closest_point_to(self, point, thr=20.0): """ Finds the closest point in the segment to a given point Args: point (:obj:`Point`) thr (float, optional): Distance threshold, in meters, to be considered the same point. Defaults to 20.0 Returns: (int, Point): Index of the point. -1 if doesn't exist. A point is given if it's along the segment """ i = 0 point_arr = point.gen2arr() def closest_in_line(pointA, pointB): temp = closest_point(pointA.gen2arr(), pointB.gen2arr(), point_arr) return Point(temp[1], temp[0], None) for (p_a, p_b) in pairwise(self.points): candidate = closest_in_line(p_a, p_b) if candidate.distance(point) <= thr: if p_a.distance(point) <= thr: return i, p_a elif p_b.distance(point) <= thr: return i + 1, p_b else: return i, candidate i = i + 1 return -1, None
python
def closest_point_to(self, point, thr=20.0): i = 0 point_arr = point.gen2arr() def closest_in_line(pointA, pointB): temp = closest_point(pointA.gen2arr(), pointB.gen2arr(), point_arr) return Point(temp[1], temp[0], None) for (p_a, p_b) in pairwise(self.points): candidate = closest_in_line(p_a, p_b) if candidate.distance(point) <= thr: if p_a.distance(point) <= thr: return i, p_a elif p_b.distance(point) <= thr: return i + 1, p_b else: return i, candidate i = i + 1 return -1, None
[ "def", "closest_point_to", "(", "self", ",", "point", ",", "thr", "=", "20.0", ")", ":", "i", "=", "0", "point_arr", "=", "point", ".", "gen2arr", "(", ")", "def", "closest_in_line", "(", "pointA", ",", "pointB", ")", ":", "temp", "=", "closest_point", "(", "pointA", ".", "gen2arr", "(", ")", ",", "pointB", ".", "gen2arr", "(", ")", ",", "point_arr", ")", "return", "Point", "(", "temp", "[", "1", "]", ",", "temp", "[", "0", "]", ",", "None", ")", "for", "(", "p_a", ",", "p_b", ")", "in", "pairwise", "(", "self", ".", "points", ")", ":", "candidate", "=", "closest_in_line", "(", "p_a", ",", "p_b", ")", "if", "candidate", ".", "distance", "(", "point", ")", "<=", "thr", ":", "if", "p_a", ".", "distance", "(", "point", ")", "<=", "thr", ":", "return", "i", ",", "p_a", "elif", "p_b", ".", "distance", "(", "point", ")", "<=", "thr", ":", "return", "i", "+", "1", ",", "p_b", "else", ":", "return", "i", ",", "candidate", "i", "=", "i", "+", "1", "return", "-", "1", ",", "None" ]
Finds the closest point in the segment to a given point Args: point (:obj:`Point`) thr (float, optional): Distance threshold, in meters, to be considered the same point. Defaults to 20.0 Returns: (int, Point): Index of the point. -1 if doesn't exist. A point is given if it's along the segment
[ "Finds", "the", "closest", "point", "in", "the", "segment", "to", "a", "given", "point" ]
5537c14ee9748091b5255b658ab528e1d6227f99
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L227-L255
3,894
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.slice
def slice(self, start, end): """ Creates a copy of the current segment between indexes. If end > start, points are reverted Args: start (int): Start index end (int): End index Returns: :obj:`Segment` """ reverse = False if start > end: temp = start start = end end = temp reverse = True seg = self.copy() seg.points = seg.points[start:end+1] if reverse: seg.points = list(reversed(seg.points)) return seg
python
def slice(self, start, end): reverse = False if start > end: temp = start start = end end = temp reverse = True seg = self.copy() seg.points = seg.points[start:end+1] if reverse: seg.points = list(reversed(seg.points)) return seg
[ "def", "slice", "(", "self", ",", "start", ",", "end", ")", ":", "reverse", "=", "False", "if", "start", ">", "end", ":", "temp", "=", "start", "start", "=", "end", "end", "=", "temp", "reverse", "=", "True", "seg", "=", "self", ".", "copy", "(", ")", "seg", ".", "points", "=", "seg", ".", "points", "[", "start", ":", "end", "+", "1", "]", "if", "reverse", ":", "seg", ".", "points", "=", "list", "(", "reversed", "(", "seg", ".", "points", ")", ")", "return", "seg" ]
Creates a copy of the current segment between indexes. If end > start, points are reverted Args: start (int): Start index end (int): End index Returns: :obj:`Segment`
[ "Creates", "a", "copy", "of", "the", "current", "segment", "between", "indexes", ".", "If", "end", ">", "start", "points", "are", "reverted" ]
5537c14ee9748091b5255b658ab528e1d6227f99
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L257-L280
3,895
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.to_json
def to_json(self): """ Converts segment to a JSON serializable format Returns: :obj:`dict` """ points = [point.to_json() for point in self.points] return { 'points': points, 'transportationModes': self.transportation_modes, 'locationFrom': self.location_from.to_json() if self.location_from != None else None, 'locationTo': self.location_to.to_json() if self.location_to != None else None }
python
def to_json(self): points = [point.to_json() for point in self.points] return { 'points': points, 'transportationModes': self.transportation_modes, 'locationFrom': self.location_from.to_json() if self.location_from != None else None, 'locationTo': self.location_to.to_json() if self.location_to != None else None }
[ "def", "to_json", "(", "self", ")", ":", "points", "=", "[", "point", ".", "to_json", "(", ")", "for", "point", "in", "self", ".", "points", "]", "return", "{", "'points'", ":", "points", ",", "'transportationModes'", ":", "self", ".", "transportation_modes", ",", "'locationFrom'", ":", "self", ".", "location_from", ".", "to_json", "(", ")", "if", "self", ".", "location_from", "!=", "None", "else", "None", ",", "'locationTo'", ":", "self", ".", "location_to", ".", "to_json", "(", ")", "if", "self", ".", "location_to", "!=", "None", "else", "None", "}" ]
Converts segment to a JSON serializable format Returns: :obj:`dict`
[ "Converts", "segment", "to", "a", "JSON", "serializable", "format" ]
5537c14ee9748091b5255b658ab528e1d6227f99
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L290-L302
3,896
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.from_gpx
def from_gpx(gpx_segment): """ Creates a segment from a GPX format. No preprocessing is done. Arguments: gpx_segment (:obj:`gpxpy.GPXTrackSegment`) Return: :obj:`Segment` """ points = [] for point in gpx_segment.points: points.append(Point.from_gpx(point)) return Segment(points)
python
def from_gpx(gpx_segment): points = [] for point in gpx_segment.points: points.append(Point.from_gpx(point)) return Segment(points)
[ "def", "from_gpx", "(", "gpx_segment", ")", ":", "points", "=", "[", "]", "for", "point", "in", "gpx_segment", ".", "points", ":", "points", ".", "append", "(", "Point", ".", "from_gpx", "(", "point", ")", ")", "return", "Segment", "(", "points", ")" ]
Creates a segment from a GPX format. No preprocessing is done. Arguments: gpx_segment (:obj:`gpxpy.GPXTrackSegment`) Return: :obj:`Segment`
[ "Creates", "a", "segment", "from", "a", "GPX", "format", "." ]
5537c14ee9748091b5255b658ab528e1d6227f99
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L305-L318
3,897
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.from_json
def from_json(json): """ Creates a segment from a JSON file. No preprocessing is done. Arguments: json (:obj:`dict`): JSON representation. See to_json. Return: :obj:`Segment` """ points = [] for point in json['points']: points.append(Point.from_json(point)) return Segment(points)
python
def from_json(json): points = [] for point in json['points']: points.append(Point.from_json(point)) return Segment(points)
[ "def", "from_json", "(", "json", ")", ":", "points", "=", "[", "]", "for", "point", "in", "json", "[", "'points'", "]", ":", "points", ".", "append", "(", "Point", ".", "from_json", "(", "point", ")", ")", "return", "Segment", "(", "points", ")" ]
Creates a segment from a JSON file. No preprocessing is done. Arguments: json (:obj:`dict`): JSON representation. See to_json. Return: :obj:`Segment`
[ "Creates", "a", "segment", "from", "a", "JSON", "file", "." ]
5537c14ee9748091b5255b658ab528e1d6227f99
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L321-L334
3,898
ruipgil/TrackToTrip
tracktotrip/smooth.py
extrapolate_points
def extrapolate_points(points, n_points): """ Extrapolate a number of points, based on the first ones Args: points (:obj:`list` of :obj:`Point`) n_points (int): number of points to extrapolate Returns: :obj:`list` of :obj:`Point` """ points = points[:n_points] lat = [] lon = [] last = None for point in points: if last is not None: lat.append(last.lat-point.lat) lon.append(last.lon-point.lon) last = point dts = np.mean([p.dt for p in points]) lons = np.mean(lon) lats = np.mean(lat) gen_sample = [] last = points[0] for _ in range(n_points): point = Point(last.lat+lats, last.lon+lons, None) point.dt = dts # point.compute_metrics(last) gen_sample.append(point) last = point return gen_sample
python
def extrapolate_points(points, n_points): points = points[:n_points] lat = [] lon = [] last = None for point in points: if last is not None: lat.append(last.lat-point.lat) lon.append(last.lon-point.lon) last = point dts = np.mean([p.dt for p in points]) lons = np.mean(lon) lats = np.mean(lat) gen_sample = [] last = points[0] for _ in range(n_points): point = Point(last.lat+lats, last.lon+lons, None) point.dt = dts # point.compute_metrics(last) gen_sample.append(point) last = point return gen_sample
[ "def", "extrapolate_points", "(", "points", ",", "n_points", ")", ":", "points", "=", "points", "[", ":", "n_points", "]", "lat", "=", "[", "]", "lon", "=", "[", "]", "last", "=", "None", "for", "point", "in", "points", ":", "if", "last", "is", "not", "None", ":", "lat", ".", "append", "(", "last", ".", "lat", "-", "point", ".", "lat", ")", "lon", ".", "append", "(", "last", ".", "lon", "-", "point", ".", "lon", ")", "last", "=", "point", "dts", "=", "np", ".", "mean", "(", "[", "p", ".", "dt", "for", "p", "in", "points", "]", ")", "lons", "=", "np", ".", "mean", "(", "lon", ")", "lats", "=", "np", ".", "mean", "(", "lat", ")", "gen_sample", "=", "[", "]", "last", "=", "points", "[", "0", "]", "for", "_", "in", "range", "(", "n_points", ")", ":", "point", "=", "Point", "(", "last", ".", "lat", "+", "lats", ",", "last", ".", "lon", "+", "lons", ",", "None", ")", "point", ".", "dt", "=", "dts", "# point.compute_metrics(last)", "gen_sample", ".", "append", "(", "point", ")", "last", "=", "point", "return", "gen_sample" ]
Extrapolate a number of points, based on the first ones Args: points (:obj:`list` of :obj:`Point`) n_points (int): number of points to extrapolate Returns: :obj:`list` of :obj:`Point`
[ "Extrapolate", "a", "number", "of", "points", "based", "on", "the", "first", "ones" ]
5537c14ee9748091b5255b658ab528e1d6227f99
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/smooth.py#L13-L45
3,899
ruipgil/TrackToTrip
tracktotrip/smooth.py
with_extrapolation
def with_extrapolation(points, noise, n_points): """ Smooths a set of points, but it extrapolates some points at the beginning Args: points (:obj:`list` of :obj:`Point`) noise (float): Expected noise, the higher it is the more the path will be smoothed. Returns: :obj:`list` of :obj:`Point` """ n_points = 10 return kalman_filter(extrapolate_points(points, n_points) + points, noise)[n_points:]
python
def with_extrapolation(points, noise, n_points): n_points = 10 return kalman_filter(extrapolate_points(points, n_points) + points, noise)[n_points:]
[ "def", "with_extrapolation", "(", "points", ",", "noise", ",", "n_points", ")", ":", "n_points", "=", "10", "return", "kalman_filter", "(", "extrapolate_points", "(", "points", ",", "n_points", ")", "+", "points", ",", "noise", ")", "[", "n_points", ":", "]" ]
Smooths a set of points, but it extrapolates some points at the beginning Args: points (:obj:`list` of :obj:`Point`) noise (float): Expected noise, the higher it is the more the path will be smoothed. Returns: :obj:`list` of :obj:`Point`
[ "Smooths", "a", "set", "of", "points", "but", "it", "extrapolates", "some", "points", "at", "the", "beginning" ]
5537c14ee9748091b5255b658ab528e1d6227f99
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/smooth.py#L47-L58