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 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
intuition-io/intuition | intuition/api/portfolio.py | PortfolioFactory.update | def update(self, portfolio, date, perfs=None):
'''
Actualizes the portfolio universe with the alog state
'''
# Make the manager aware of current simulation
self.portfolio = portfolio
self.perfs = perfs
self.date = date | python | def update(self, portfolio, date, perfs=None):
'''
Actualizes the portfolio universe with the alog state
'''
# Make the manager aware of current simulation
self.portfolio = portfolio
self.perfs = perfs
self.date = date | [
"def",
"update",
"(",
"self",
",",
"portfolio",
",",
"date",
",",
"perfs",
"=",
"None",
")",
":",
"self",
".",
"portfolio",
"=",
"portfolio",
"self",
".",
"perfs",
"=",
"perfs",
"self",
".",
"date",
"=",
"date"
] | Actualizes the portfolio universe with the alog state | [
"Actualizes",
"the",
"portfolio",
"universe",
"with",
"the",
"alog",
"state"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/portfolio.py#L77-L84 | train |
intuition-io/intuition | intuition/api/portfolio.py | PortfolioFactory.trade_signals_handler | def trade_signals_handler(self, signals):
'''
Process buy and sell signals from the simulation
'''
alloc = {}
if signals['buy'] or signals['sell']:
# Compute the optimal portfolio allocation,
# Using user defined function
try:
... | python | def trade_signals_handler(self, signals):
'''
Process buy and sell signals from the simulation
'''
alloc = {}
if signals['buy'] or signals['sell']:
# Compute the optimal portfolio allocation,
# Using user defined function
try:
... | [
"def",
"trade_signals_handler",
"(",
"self",
",",
"signals",
")",
":",
"alloc",
"=",
"{",
"}",
"if",
"signals",
"[",
"'buy'",
"]",
"or",
"signals",
"[",
"'sell'",
"]",
":",
"try",
":",
"alloc",
",",
"e_ret",
",",
"e_risk",
"=",
"self",
".",
"optimize... | Process buy and sell signals from the simulation | [
"Process",
"buy",
"and",
"sell",
"signals",
"from",
"the",
"simulation"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/portfolio.py#L86-L102 | train |
intuition-io/intuition | intuition/data/remote.py | historical_pandas_yahoo | def historical_pandas_yahoo(symbol, source='yahoo', start=None, end=None):
'''
Fetch from yahoo! finance historical quotes
'''
#NOTE Panel for multiple symbols ?
#NOTE Adj Close column name not cool (a space)
return DataReader(symbol, source, start=start, end=end) | python | def historical_pandas_yahoo(symbol, source='yahoo', start=None, end=None):
'''
Fetch from yahoo! finance historical quotes
'''
#NOTE Panel for multiple symbols ?
#NOTE Adj Close column name not cool (a space)
return DataReader(symbol, source, start=start, end=end) | [
"def",
"historical_pandas_yahoo",
"(",
"symbol",
",",
"source",
"=",
"'yahoo'",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"return",
"DataReader",
"(",
"symbol",
",",
"source",
",",
"start",
"=",
"start",
",",
"end",
"=",
"end",
")"
... | Fetch from yahoo! finance historical quotes | [
"Fetch",
"from",
"yahoo!",
"finance",
"historical",
"quotes"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/remote.py#L26-L32 | train |
intuition-io/intuition | intuition/finance.py | average_returns | def average_returns(ts, **kwargs):
''' Compute geometric average returns from a returns time serie'''
average_type = kwargs.get('type', 'net')
if average_type == 'net':
relative = 0
else:
relative = -1 # gross
#start = kwargs.get('start', ts.index[0])
#end = kwargs.get('end', ts... | python | def average_returns(ts, **kwargs):
''' Compute geometric average returns from a returns time serie'''
average_type = kwargs.get('type', 'net')
if average_type == 'net':
relative = 0
else:
relative = -1 # gross
#start = kwargs.get('start', ts.index[0])
#end = kwargs.get('end', ts... | [
"def",
"average_returns",
"(",
"ts",
",",
"**",
"kwargs",
")",
":",
"average_type",
"=",
"kwargs",
".",
"get",
"(",
"'type'",
",",
"'net'",
")",
"if",
"average_type",
"==",
"'net'",
":",
"relative",
"=",
"0",
"else",
":",
"relative",
"=",
"-",
"1",
"... | Compute geometric average returns from a returns time serie | [
"Compute",
"geometric",
"average",
"returns",
"from",
"a",
"returns",
"time",
"serie"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/finance.py#L116-L136 | train |
intuition-io/intuition | intuition/finance.py | returns | def returns(ts, **kwargs):
'''
Compute returns on the given period
@param ts : time serie to process
@param kwargs.type: gross or simple returns
@param delta : period betweend two computed returns
@param start : with end, will return the return betweend this elapsed time
@param period : del... | python | def returns(ts, **kwargs):
'''
Compute returns on the given period
@param ts : time serie to process
@param kwargs.type: gross or simple returns
@param delta : period betweend two computed returns
@param start : with end, will return the return betweend this elapsed time
@param period : del... | [
"def",
"returns",
"(",
"ts",
",",
"**",
"kwargs",
")",
":",
"returns_type",
"=",
"kwargs",
".",
"get",
"(",
"'type'",
",",
"'net'",
")",
"cumulative",
"=",
"kwargs",
".",
"get",
"(",
"'cumulative'",
",",
"False",
")",
"if",
"returns_type",
"==",
"'net'... | Compute returns on the given period
@param ts : time serie to process
@param kwargs.type: gross or simple returns
@param delta : period betweend two computed returns
@param start : with end, will return the return betweend this elapsed time
@param period : delta is the number of lines/periods provi... | [
"Compute",
"returns",
"on",
"the",
"given",
"period"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/finance.py#L151-L184 | train |
intuition-io/intuition | intuition/finance.py | daily_returns | def daily_returns(ts, **kwargs):
''' re-compute ts on a daily basis '''
relative = kwargs.get('relative', 0)
return returns(ts, delta=BDay(), relative=relative) | python | def daily_returns(ts, **kwargs):
''' re-compute ts on a daily basis '''
relative = kwargs.get('relative', 0)
return returns(ts, delta=BDay(), relative=relative) | [
"def",
"daily_returns",
"(",
"ts",
",",
"**",
"kwargs",
")",
":",
"relative",
"=",
"kwargs",
".",
"get",
"(",
"'relative'",
",",
"0",
")",
"return",
"returns",
"(",
"ts",
",",
"delta",
"=",
"BDay",
"(",
")",
",",
"relative",
"=",
"relative",
")"
] | re-compute ts on a daily basis | [
"re",
"-",
"compute",
"ts",
"on",
"a",
"daily",
"basis"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/finance.py#L187-L190 | train |
Callidon/pyHDT | setup.py | list_files | def list_files(path, extension=".cpp", exclude="S.cpp"):
"""List paths to all files that ends with a given extension"""
return ["%s/%s" % (path, f) for f in listdir(path) if f.endswith(extension) and (not f.endswith(exclude))] | python | def list_files(path, extension=".cpp", exclude="S.cpp"):
"""List paths to all files that ends with a given extension"""
return ["%s/%s" % (path, f) for f in listdir(path) if f.endswith(extension) and (not f.endswith(exclude))] | [
"def",
"list_files",
"(",
"path",
",",
"extension",
"=",
"\".cpp\"",
",",
"exclude",
"=",
"\"S.cpp\"",
")",
":",
"return",
"[",
"\"%s/%s\"",
"%",
"(",
"path",
",",
"f",
")",
"for",
"f",
"in",
"listdir",
"(",
"path",
")",
"if",
"f",
".",
"endswith",
... | List paths to all files that ends with a given extension | [
"List",
"paths",
"to",
"all",
"files",
"that",
"ends",
"with",
"a",
"given",
"extension"
] | 8b18c950ee98ab554d34d9fddacab962d3989b55 | https://github.com/Callidon/pyHDT/blob/8b18c950ee98ab554d34d9fddacab962d3989b55/setup.py#L15-L17 | train |
intuition-io/intuition | intuition/cli.py | intuition | def intuition(args):
'''
Main simulation wrapper
Load the configuration, run the engine and return the analyze.
'''
# Use the provided context builder to fill:
# - config: General behavior
# - strategy: Modules properties
# - market: The universe we will trade on
with setup.Co... | python | def intuition(args):
'''
Main simulation wrapper
Load the configuration, run the engine and return the analyze.
'''
# Use the provided context builder to fill:
# - config: General behavior
# - strategy: Modules properties
# - market: The universe we will trade on
with setup.Co... | [
"def",
"intuition",
"(",
"args",
")",
":",
"with",
"setup",
".",
"Context",
"(",
"args",
"[",
"'context'",
"]",
")",
"as",
"context",
":",
"simulation",
"=",
"Simulation",
"(",
")",
"modules",
"=",
"context",
"[",
"'config'",
"]",
"[",
"'modules'",
"]"... | Main simulation wrapper
Load the configuration, run the engine and return the analyze. | [
"Main",
"simulation",
"wrapper",
"Load",
"the",
"configuration",
"run",
"the",
"engine",
"and",
"return",
"the",
"analyze",
"."
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/cli.py#L25-L68 | train |
intuition-io/intuition | intuition/api/algorithm.py | TradingFactory._is_interactive | def _is_interactive(self):
''' Prevent middlewares and orders to work outside live mode '''
return not (
self.realworld and (dt.date.today() > self.datetime.date())) | python | def _is_interactive(self):
''' Prevent middlewares and orders to work outside live mode '''
return not (
self.realworld and (dt.date.today() > self.datetime.date())) | [
"def",
"_is_interactive",
"(",
"self",
")",
":",
"return",
"not",
"(",
"self",
".",
"realworld",
"and",
"(",
"dt",
".",
"date",
".",
"today",
"(",
")",
">",
"self",
".",
"datetime",
".",
"date",
"(",
")",
")",
")"
] | Prevent middlewares and orders to work outside live mode | [
"Prevent",
"middlewares",
"and",
"orders",
"to",
"work",
"outside",
"live",
"mode"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/algorithm.py#L46-L49 | train |
intuition-io/intuition | intuition/api/algorithm.py | TradingFactory.use | def use(self, func, when='whenever'):
''' Append a middleware to the algorithm '''
#NOTE A middleware Object ?
# self.use() is usually called from initialize(), so no logger yet
print('registering middleware {}'.format(func.__name__))
self.middlewares.append({
'call':... | python | def use(self, func, when='whenever'):
''' Append a middleware to the algorithm '''
#NOTE A middleware Object ?
# self.use() is usually called from initialize(), so no logger yet
print('registering middleware {}'.format(func.__name__))
self.middlewares.append({
'call':... | [
"def",
"use",
"(",
"self",
",",
"func",
",",
"when",
"=",
"'whenever'",
")",
":",
"print",
"(",
"'registering middleware {}'",
".",
"format",
"(",
"func",
".",
"__name__",
")",
")",
"self",
".",
"middlewares",
".",
"append",
"(",
"{",
"'call'",
":",
"f... | Append a middleware to the algorithm | [
"Append",
"a",
"middleware",
"to",
"the",
"algorithm"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/algorithm.py#L51-L61 | train |
intuition-io/intuition | intuition/api/algorithm.py | TradingFactory.process_orders | def process_orders(self, orderbook):
''' Default and costant orders processor. Overwrite it for more
sophisticated strategies '''
for stock, alloc in orderbook.iteritems():
self.logger.info('{}: Ordered {} {} stocks'.format(
self.datetime, stock, alloc))
i... | python | def process_orders(self, orderbook):
''' Default and costant orders processor. Overwrite it for more
sophisticated strategies '''
for stock, alloc in orderbook.iteritems():
self.logger.info('{}: Ordered {} {} stocks'.format(
self.datetime, stock, alloc))
i... | [
"def",
"process_orders",
"(",
"self",
",",
"orderbook",
")",
":",
"for",
"stock",
",",
"alloc",
"in",
"orderbook",
".",
"iteritems",
"(",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'{}: Ordered {} {} stocks'",
".",
"format",
"(",
"self",
".",
"d... | Default and costant orders processor. Overwrite it for more
sophisticated strategies | [
"Default",
"and",
"costant",
"orders",
"processor",
".",
"Overwrite",
"it",
"for",
"more",
"sophisticated",
"strategies"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/algorithm.py#L114-L128 | train |
intuition-io/intuition | intuition/api/algorithm.py | TradingFactory._call_one_middleware | def _call_one_middleware(self, middleware):
''' Evaluate arguments and execute the middleware function '''
args = {}
for arg in middleware['args']:
if hasattr(self, arg):
# same as eval() but safer for arbitrary code execution
args[arg] = reduce(getatt... | python | def _call_one_middleware(self, middleware):
''' Evaluate arguments and execute the middleware function '''
args = {}
for arg in middleware['args']:
if hasattr(self, arg):
# same as eval() but safer for arbitrary code execution
args[arg] = reduce(getatt... | [
"def",
"_call_one_middleware",
"(",
"self",
",",
"middleware",
")",
":",
"args",
"=",
"{",
"}",
"for",
"arg",
"in",
"middleware",
"[",
"'args'",
"]",
":",
"if",
"hasattr",
"(",
"self",
",",
"arg",
")",
":",
"args",
"[",
"arg",
"]",
"=",
"reduce",
"... | Evaluate arguments and execute the middleware function | [
"Evaluate",
"arguments",
"and",
"execute",
"the",
"middleware",
"function"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/algorithm.py#L130-L139 | train |
intuition-io/intuition | intuition/api/algorithm.py | TradingFactory._call_middlewares | def _call_middlewares(self):
''' Execute the middleware stack '''
for middleware in self.middlewares:
if self._check_condition(middleware['when']):
self._call_one_middleware(middleware) | python | def _call_middlewares(self):
''' Execute the middleware stack '''
for middleware in self.middlewares:
if self._check_condition(middleware['when']):
self._call_one_middleware(middleware) | [
"def",
"_call_middlewares",
"(",
"self",
")",
":",
"for",
"middleware",
"in",
"self",
".",
"middlewares",
":",
"if",
"self",
".",
"_check_condition",
"(",
"middleware",
"[",
"'when'",
"]",
")",
":",
"self",
".",
"_call_one_middleware",
"(",
"middleware",
")"... | Execute the middleware stack | [
"Execute",
"the",
"middleware",
"stack"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/algorithm.py#L146-L150 | train |
intuition-io/intuition | intuition/data/loader.py | LiveBenchmark.normalize_date | def normalize_date(self, test_date):
''' Same function as zipline.finance.trading.py'''
test_date = pd.Timestamp(test_date, tz='UTC')
return pd.tseries.tools.normalize_date(test_date) | python | def normalize_date(self, test_date):
''' Same function as zipline.finance.trading.py'''
test_date = pd.Timestamp(test_date, tz='UTC')
return pd.tseries.tools.normalize_date(test_date) | [
"def",
"normalize_date",
"(",
"self",
",",
"test_date",
")",
":",
"test_date",
"=",
"pd",
".",
"Timestamp",
"(",
"test_date",
",",
"tz",
"=",
"'UTC'",
")",
"return",
"pd",
".",
"tseries",
".",
"tools",
".",
"normalize_date",
"(",
"test_date",
")"
] | Same function as zipline.finance.trading.py | [
"Same",
"function",
"as",
"zipline",
".",
"finance",
".",
"trading",
".",
"py"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/loader.py#L32-L35 | train |
intuition-io/intuition | intuition/data/universe.py | Market._load_market_scheme | def _load_market_scheme(self):
''' Load market yaml description '''
try:
self.scheme = yaml.load(open(self.scheme_path, 'r'))
except Exception, error:
raise LoadMarketSchemeFailed(reason=error) | python | def _load_market_scheme(self):
''' Load market yaml description '''
try:
self.scheme = yaml.load(open(self.scheme_path, 'r'))
except Exception, error:
raise LoadMarketSchemeFailed(reason=error) | [
"def",
"_load_market_scheme",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"scheme",
"=",
"yaml",
".",
"load",
"(",
"open",
"(",
"self",
".",
"scheme_path",
",",
"'r'",
")",
")",
"except",
"Exception",
",",
"error",
":",
"raise",
"LoadMarketSchemeFail... | Load market yaml description | [
"Load",
"market",
"yaml",
"description"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/universe.py#L44-L49 | train |
intuition-io/intuition | intuition/data/quandl.py | DataQuandl.fetch | def fetch(self, code, **kwargs):
'''
Quandl entry point in datafeed object
'''
log.debug('fetching QuanDL data (%s)' % code)
# This way you can use your credentials even if
# you didn't provide them to the constructor
if 'authtoken' in kwargs:
self.qua... | python | def fetch(self, code, **kwargs):
'''
Quandl entry point in datafeed object
'''
log.debug('fetching QuanDL data (%s)' % code)
# This way you can use your credentials even if
# you didn't provide them to the constructor
if 'authtoken' in kwargs:
self.qua... | [
"def",
"fetch",
"(",
"self",
",",
"code",
",",
"**",
"kwargs",
")",
":",
"log",
".",
"debug",
"(",
"'fetching QuanDL data (%s)'",
"%",
"code",
")",
"if",
"'authtoken'",
"in",
"kwargs",
":",
"self",
".",
"quandl_key",
"=",
"kwargs",
".",
"pop",
"(",
"'a... | Quandl entry point in datafeed object | [
"Quandl",
"entry",
"point",
"in",
"datafeed",
"object"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/quandl.py#L90-L113 | train |
intuition-io/intuition | intuition/core/analyzes.py | Analyze.rolling_performances | def rolling_performances(self, timestamp='one_month'):
''' Filters self.perfs '''
# TODO Study the impact of month choice
# TODO Check timestamp in an enumeration
# TODO Implement other benchmarks for perf computation
# (zipline issue, maybe expected)
if self.metrics:
... | python | def rolling_performances(self, timestamp='one_month'):
''' Filters self.perfs '''
# TODO Study the impact of month choice
# TODO Check timestamp in an enumeration
# TODO Implement other benchmarks for perf computation
# (zipline issue, maybe expected)
if self.metrics:
... | [
"def",
"rolling_performances",
"(",
"self",
",",
"timestamp",
"=",
"'one_month'",
")",
":",
"if",
"self",
".",
"metrics",
":",
"perfs",
"=",
"{",
"}",
"length",
"=",
"range",
"(",
"len",
"(",
"self",
".",
"metrics",
"[",
"timestamp",
"]",
")",
")",
"... | Filters self.perfs | [
"Filters",
"self",
".",
"perfs"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/core/analyzes.py#L87-L109 | train |
intuition-io/intuition | intuition/core/analyzes.py | Analyze.overall_metrics | def overall_metrics(self, timestamp='one_month', metrics=None):
'''
Use zipline results to compute some performance indicators
'''
perfs = dict()
# If no rolling perfs provided, computes it
if metrics is None:
metrics = self.rolling_performances(timestamp=tim... | python | def overall_metrics(self, timestamp='one_month', metrics=None):
'''
Use zipline results to compute some performance indicators
'''
perfs = dict()
# If no rolling perfs provided, computes it
if metrics is None:
metrics = self.rolling_performances(timestamp=tim... | [
"def",
"overall_metrics",
"(",
"self",
",",
"timestamp",
"=",
"'one_month'",
",",
"metrics",
"=",
"None",
")",
":",
"perfs",
"=",
"dict",
"(",
")",
"if",
"metrics",
"is",
"None",
":",
"metrics",
"=",
"self",
".",
"rolling_performances",
"(",
"timestamp",
... | Use zipline results to compute some performance indicators | [
"Use",
"zipline",
"results",
"to",
"compute",
"some",
"performance",
"indicators"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/core/analyzes.py#L111-L133 | train |
intuition-io/intuition | intuition/api/context.py | ContextFactory._normalize_data_types | def _normalize_data_types(self, strategy):
''' some contexts only retrieves strings, giving back right type '''
for k, v in strategy.iteritems():
if not isinstance(v, str):
# There is probably nothing to do
continue
if v == 'true':
... | python | def _normalize_data_types(self, strategy):
''' some contexts only retrieves strings, giving back right type '''
for k, v in strategy.iteritems():
if not isinstance(v, str):
# There is probably nothing to do
continue
if v == 'true':
... | [
"def",
"_normalize_data_types",
"(",
"self",
",",
"strategy",
")",
":",
"for",
"k",
",",
"v",
"in",
"strategy",
".",
"iteritems",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"v",
",",
"str",
")",
":",
"continue",
"if",
"v",
"==",
"'true'",
":",
... | some contexts only retrieves strings, giving back right type | [
"some",
"contexts",
"only",
"retrieves",
"strings",
"giving",
"back",
"right",
"type"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/context.py#L86-L103 | train |
intuition-io/intuition | intuition/core/engine.py | Simulation._get_benchmark_handler | def _get_benchmark_handler(self, last_trade, freq='minutely'):
'''
Setup a custom benchmark handler or let zipline manage it
'''
return LiveBenchmark(
last_trade, frequency=freq).surcharge_market_data \
if utils.is_live(last_trade) else None | python | def _get_benchmark_handler(self, last_trade, freq='minutely'):
'''
Setup a custom benchmark handler or let zipline manage it
'''
return LiveBenchmark(
last_trade, frequency=freq).surcharge_market_data \
if utils.is_live(last_trade) else None | [
"def",
"_get_benchmark_handler",
"(",
"self",
",",
"last_trade",
",",
"freq",
"=",
"'minutely'",
")",
":",
"return",
"LiveBenchmark",
"(",
"last_trade",
",",
"frequency",
"=",
"freq",
")",
".",
"surcharge_market_data",
"if",
"utils",
".",
"is_live",
"(",
"last... | Setup a custom benchmark handler or let zipline manage it | [
"Setup",
"a",
"custom",
"benchmark",
"handler",
"or",
"let",
"zipline",
"manage",
"it"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/core/engine.py#L64-L70 | train |
intuition-io/intuition | intuition/core/engine.py | Simulation.configure_environment | def configure_environment(self, last_trade, benchmark, timezone):
''' Prepare benchmark loader and trading context '''
if last_trade.tzinfo is None:
last_trade = pytz.utc.localize(last_trade)
# Setup the trading calendar from market informations
self.benchmark = benchmark
... | python | def configure_environment(self, last_trade, benchmark, timezone):
''' Prepare benchmark loader and trading context '''
if last_trade.tzinfo is None:
last_trade = pytz.utc.localize(last_trade)
# Setup the trading calendar from market informations
self.benchmark = benchmark
... | [
"def",
"configure_environment",
"(",
"self",
",",
"last_trade",
",",
"benchmark",
",",
"timezone",
")",
":",
"if",
"last_trade",
".",
"tzinfo",
"is",
"None",
":",
"last_trade",
"=",
"pytz",
".",
"utc",
".",
"localize",
"(",
"last_trade",
")",
"self",
".",
... | Prepare benchmark loader and trading context | [
"Prepare",
"benchmark",
"loader",
"and",
"trading",
"context"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/core/engine.py#L72-L83 | train |
intuition-io/intuition | intuition/data/utils.py | apply_mapping | def apply_mapping(raw_row, mapping):
'''
Override this to hand craft conversion of row.
'''
row = {target: mapping_func(raw_row[source_key])
for target, (mapping_func, source_key)
in mapping.fget().items()}
return row | python | def apply_mapping(raw_row, mapping):
'''
Override this to hand craft conversion of row.
'''
row = {target: mapping_func(raw_row[source_key])
for target, (mapping_func, source_key)
in mapping.fget().items()}
return row | [
"def",
"apply_mapping",
"(",
"raw_row",
",",
"mapping",
")",
":",
"row",
"=",
"{",
"target",
":",
"mapping_func",
"(",
"raw_row",
"[",
"source_key",
"]",
")",
"for",
"target",
",",
"(",
"mapping_func",
",",
"source_key",
")",
"in",
"mapping",
".",
"fget"... | Override this to hand craft conversion of row. | [
"Override",
"this",
"to",
"hand",
"craft",
"conversion",
"of",
"row",
"."
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/utils.py#L25-L32 | train |
intuition-io/intuition | intuition/data/utils.py | invert_dataframe_axis | def invert_dataframe_axis(fct):
'''
Make dataframe index column names,
and vice et versa
'''
def inner(*args, **kwargs):
df_to_invert = fct(*args, **kwargs)
return pd.DataFrame(df_to_invert.to_dict().values(),
index=df_to_invert.to_dict().keys())
retur... | python | def invert_dataframe_axis(fct):
'''
Make dataframe index column names,
and vice et versa
'''
def inner(*args, **kwargs):
df_to_invert = fct(*args, **kwargs)
return pd.DataFrame(df_to_invert.to_dict().values(),
index=df_to_invert.to_dict().keys())
retur... | [
"def",
"invert_dataframe_axis",
"(",
"fct",
")",
":",
"def",
"inner",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"df_to_invert",
"=",
"fct",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"return",
"pd",
".",
"DataFrame",
"(",
"df_to_invert",
".",
... | Make dataframe index column names,
and vice et versa | [
"Make",
"dataframe",
"index",
"column",
"names",
"and",
"vice",
"et",
"versa"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/utils.py#L35-L44 | train |
intuition-io/intuition | intuition/data/utils.py | use_google_symbol | def use_google_symbol(fct):
'''
Removes ".PA" or other market indicator from yahoo symbol
convention to suit google convention
'''
def decorator(symbols):
google_symbols = []
# If one symbol string
if isinstance(symbols, str):
symbols = [symbols]
symbols... | python | def use_google_symbol(fct):
'''
Removes ".PA" or other market indicator from yahoo symbol
convention to suit google convention
'''
def decorator(symbols):
google_symbols = []
# If one symbol string
if isinstance(symbols, str):
symbols = [symbols]
symbols... | [
"def",
"use_google_symbol",
"(",
"fct",
")",
":",
"def",
"decorator",
"(",
"symbols",
")",
":",
"google_symbols",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"symbols",
",",
"str",
")",
":",
"symbols",
"=",
"[",
"symbols",
"]",
"symbols",
"=",
"sorted",
"(... | Removes ".PA" or other market indicator from yahoo symbol
convention to suit google convention | [
"Removes",
".",
"PA",
"or",
"other",
"market",
"indicator",
"from",
"yahoo",
"symbol",
"convention",
"to",
"suit",
"google",
"convention"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/utils.py#L48-L70 | train |
intuition-io/intuition | intuition/data/ystockquote.py | get_sector | def get_sector(symbol):
'''
Uses BeautifulSoup to scrape stock sector from Yahoo! Finance website
'''
url = 'http://finance.yahoo.com/q/pr?s=%s+Profile' % symbol
soup = BeautifulSoup(urlopen(url).read())
try:
sector = soup.find('td', text='Sector:').\
find_next_sibling().stri... | python | def get_sector(symbol):
'''
Uses BeautifulSoup to scrape stock sector from Yahoo! Finance website
'''
url = 'http://finance.yahoo.com/q/pr?s=%s+Profile' % symbol
soup = BeautifulSoup(urlopen(url).read())
try:
sector = soup.find('td', text='Sector:').\
find_next_sibling().stri... | [
"def",
"get_sector",
"(",
"symbol",
")",
":",
"url",
"=",
"'http://finance.yahoo.com/q/pr?s=%s+Profile'",
"%",
"symbol",
"soup",
"=",
"BeautifulSoup",
"(",
"urlopen",
"(",
"url",
")",
".",
"read",
"(",
")",
")",
"try",
":",
"sector",
"=",
"soup",
".",
"fin... | Uses BeautifulSoup to scrape stock sector from Yahoo! Finance website | [
"Uses",
"BeautifulSoup",
"to",
"scrape",
"stock",
"sector",
"from",
"Yahoo!",
"Finance",
"website"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/ystockquote.py#L465-L476 | train |
intuition-io/intuition | intuition/data/ystockquote.py | get_industry | def get_industry(symbol):
'''
Uses BeautifulSoup to scrape stock industry from Yahoo! Finance website
'''
url = 'http://finance.yahoo.com/q/pr?s=%s+Profile' % symbol
soup = BeautifulSoup(urlopen(url).read())
try:
industry = soup.find('td', text='Industry:').\
find_next_siblin... | python | def get_industry(symbol):
'''
Uses BeautifulSoup to scrape stock industry from Yahoo! Finance website
'''
url = 'http://finance.yahoo.com/q/pr?s=%s+Profile' % symbol
soup = BeautifulSoup(urlopen(url).read())
try:
industry = soup.find('td', text='Industry:').\
find_next_siblin... | [
"def",
"get_industry",
"(",
"symbol",
")",
":",
"url",
"=",
"'http://finance.yahoo.com/q/pr?s=%s+Profile'",
"%",
"symbol",
"soup",
"=",
"BeautifulSoup",
"(",
"urlopen",
"(",
"url",
")",
".",
"read",
"(",
")",
")",
"try",
":",
"industry",
"=",
"soup",
".",
... | Uses BeautifulSoup to scrape stock industry from Yahoo! Finance website | [
"Uses",
"BeautifulSoup",
"to",
"scrape",
"stock",
"industry",
"from",
"Yahoo!",
"Finance",
"website"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/ystockquote.py#L479-L490 | train |
intuition-io/intuition | intuition/data/ystockquote.py | get_type | def get_type(symbol):
'''
Uses BeautifulSoup to scrape symbol category from Yahoo! Finance website
'''
url = 'http://finance.yahoo.com/q/pr?s=%s+Profile' % symbol
soup = BeautifulSoup(urlopen(url).read())
if soup.find('span', text='Business Summary'):
return 'Stock'
elif soup.find('s... | python | def get_type(symbol):
'''
Uses BeautifulSoup to scrape symbol category from Yahoo! Finance website
'''
url = 'http://finance.yahoo.com/q/pr?s=%s+Profile' % symbol
soup = BeautifulSoup(urlopen(url).read())
if soup.find('span', text='Business Summary'):
return 'Stock'
elif soup.find('s... | [
"def",
"get_type",
"(",
"symbol",
")",
":",
"url",
"=",
"'http://finance.yahoo.com/q/pr?s=%s+Profile'",
"%",
"symbol",
"soup",
"=",
"BeautifulSoup",
"(",
"urlopen",
"(",
"url",
")",
".",
"read",
"(",
")",
")",
"if",
"soup",
".",
"find",
"(",
"'span'",
",",... | Uses BeautifulSoup to scrape symbol category from Yahoo! Finance website | [
"Uses",
"BeautifulSoup",
"to",
"scrape",
"symbol",
"category",
"from",
"Yahoo!",
"Finance",
"website"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/ystockquote.py#L493-L507 | train |
intuition-io/intuition | intuition/data/ystockquote.py | get_historical_prices | def get_historical_prices(symbol, start_date, end_date):
"""
Get historical prices for the given ticker symbol.
Date format is 'YYYY-MM-DD'
Returns a nested dictionary (dict of dicts).
outer dict keys are dates ('YYYY-MM-DD')
"""
params = urlencode({
's': symbol,
'a': int(st... | python | def get_historical_prices(symbol, start_date, end_date):
"""
Get historical prices for the given ticker symbol.
Date format is 'YYYY-MM-DD'
Returns a nested dictionary (dict of dicts).
outer dict keys are dates ('YYYY-MM-DD')
"""
params = urlencode({
's': symbol,
'a': int(st... | [
"def",
"get_historical_prices",
"(",
"symbol",
",",
"start_date",
",",
"end_date",
")",
":",
"params",
"=",
"urlencode",
"(",
"{",
"'s'",
":",
"symbol",
",",
"'a'",
":",
"int",
"(",
"start_date",
"[",
"5",
":",
"7",
"]",
")",
"-",
"1",
",",
"'b'",
... | Get historical prices for the given ticker symbol.
Date format is 'YYYY-MM-DD'
Returns a nested dictionary (dict of dicts).
outer dict keys are dates ('YYYY-MM-DD') | [
"Get",
"historical",
"prices",
"for",
"the",
"given",
"ticker",
"symbol",
".",
"Date",
"format",
"is",
"YYYY",
"-",
"MM",
"-",
"DD"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/ystockquote.py#L524-L560 | train |
intuition-io/intuition | intuition/data/forex.py | _fx_mapping | def _fx_mapping(raw_rates):
''' Map raw output to clearer labels '''
return {pair[0].lower(): {
'timeStamp': pair[1],
'bid': float(pair[2] + pair[3]),
'ask': float(pair[4] + pair[5]),
'high': float(pair[6]),
'low': float(pair[7])
} for pair in map(lambda x: x.split(',... | python | def _fx_mapping(raw_rates):
''' Map raw output to clearer labels '''
return {pair[0].lower(): {
'timeStamp': pair[1],
'bid': float(pair[2] + pair[3]),
'ask': float(pair[4] + pair[5]),
'high': float(pair[6]),
'low': float(pair[7])
} for pair in map(lambda x: x.split(',... | [
"def",
"_fx_mapping",
"(",
"raw_rates",
")",
":",
"return",
"{",
"pair",
"[",
"0",
"]",
".",
"lower",
"(",
")",
":",
"{",
"'timeStamp'",
":",
"pair",
"[",
"1",
"]",
",",
"'bid'",
":",
"float",
"(",
"pair",
"[",
"2",
"]",
"+",
"pair",
"[",
"3",
... | Map raw output to clearer labels | [
"Map",
"raw",
"output",
"to",
"clearer",
"labels"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/forex.py#L29-L37 | train |
intuition-io/intuition | intuition/data/forex.py | TrueFX.query_rates | def query_rates(self, pairs=[]):
''' Perform a request against truefx data '''
# If no pairs, TrueFx will use the ones given the last time
payload = {'id': self._session}
if pairs:
payload['c'] = _clean_pairs(pairs)
response = requests.get(self._api_url, params=payloa... | python | def query_rates(self, pairs=[]):
''' Perform a request against truefx data '''
# If no pairs, TrueFx will use the ones given the last time
payload = {'id': self._session}
if pairs:
payload['c'] = _clean_pairs(pairs)
response = requests.get(self._api_url, params=payloa... | [
"def",
"query_rates",
"(",
"self",
",",
"pairs",
"=",
"[",
"]",
")",
":",
"payload",
"=",
"{",
"'id'",
":",
"self",
".",
"_session",
"}",
"if",
"pairs",
":",
"payload",
"[",
"'c'",
"]",
"=",
"_clean_pairs",
"(",
"pairs",
")",
"response",
"=",
"requ... | Perform a request against truefx data | [
"Perform",
"a",
"request",
"against",
"truefx",
"data"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/data/forex.py#L75-L85 | train |
intuition-io/intuition | intuition/utils.py | next_tick | def next_tick(date, interval=15):
'''
Only return when we reach given datetime
'''
# Intuition works with utc dates, conversion are made for I/O
now = dt.datetime.now(pytz.utc)
live = False
# Sleep until we reach the given date
while now < date:
time.sleep(interval)
# Upd... | python | def next_tick(date, interval=15):
'''
Only return when we reach given datetime
'''
# Intuition works with utc dates, conversion are made for I/O
now = dt.datetime.now(pytz.utc)
live = False
# Sleep until we reach the given date
while now < date:
time.sleep(interval)
# Upd... | [
"def",
"next_tick",
"(",
"date",
",",
"interval",
"=",
"15",
")",
":",
"now",
"=",
"dt",
".",
"datetime",
".",
"now",
"(",
"pytz",
".",
"utc",
")",
"live",
"=",
"False",
"while",
"now",
"<",
"date",
":",
"time",
".",
"sleep",
"(",
"interval",
")"... | Only return when we reach given datetime | [
"Only",
"return",
"when",
"we",
"reach",
"given",
"datetime"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/utils.py#L26-L40 | train |
intuition-io/intuition | intuition/utils.py | intuition_module | def intuition_module(location):
''' Build the module path and import it '''
path = location.split('.')
# Get the last field, i.e. the object name in the file
obj = path.pop(-1)
return dna.utils.dynamic_import('.'.join(path), obj) | python | def intuition_module(location):
''' Build the module path and import it '''
path = location.split('.')
# Get the last field, i.e. the object name in the file
obj = path.pop(-1)
return dna.utils.dynamic_import('.'.join(path), obj) | [
"def",
"intuition_module",
"(",
"location",
")",
":",
"path",
"=",
"location",
".",
"split",
"(",
"'.'",
")",
"obj",
"=",
"path",
".",
"pop",
"(",
"-",
"1",
")",
"return",
"dna",
".",
"utils",
".",
"dynamic_import",
"(",
"'.'",
".",
"join",
"(",
"p... | Build the module path and import it | [
"Build",
"the",
"module",
"path",
"and",
"import",
"it"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/utils.py#L43-L48 | train |
intuition-io/intuition | intuition/utils.py | build_trading_timeline | def build_trading_timeline(start, end):
''' Build the daily-based index we will trade on '''
EMPTY_DATES = pd.date_range('2000/01/01', periods=0, tz=pytz.utc)
now = dt.datetime.now(tz=pytz.utc)
if not start:
if not end:
# Live trading until the end of the day
bt_dates = ... | python | def build_trading_timeline(start, end):
''' Build the daily-based index we will trade on '''
EMPTY_DATES = pd.date_range('2000/01/01', periods=0, tz=pytz.utc)
now = dt.datetime.now(tz=pytz.utc)
if not start:
if not end:
# Live trading until the end of the day
bt_dates = ... | [
"def",
"build_trading_timeline",
"(",
"start",
",",
"end",
")",
":",
"EMPTY_DATES",
"=",
"pd",
".",
"date_range",
"(",
"'2000/01/01'",
",",
"periods",
"=",
"0",
",",
"tz",
"=",
"pytz",
".",
"utc",
")",
"now",
"=",
"dt",
".",
"datetime",
".",
"now",
"... | Build the daily-based index we will trade on | [
"Build",
"the",
"daily",
"-",
"based",
"index",
"we",
"will",
"trade",
"on"
] | cd517e6b3b315a743eb4d0d0dc294e264ab913ce | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/utils.py#L52-L113 | train |
phn/jdcal | jdcal.py | is_leap | def is_leap(year):
"""Leap year or not in the Gregorian calendar."""
x = math.fmod(year, 4)
y = math.fmod(year, 100)
z = math.fmod(year, 400)
# Divisible by 4 and,
# either not divisible by 100 or divisible by 400.
return not x and (y or not z) | python | def is_leap(year):
"""Leap year or not in the Gregorian calendar."""
x = math.fmod(year, 4)
y = math.fmod(year, 100)
z = math.fmod(year, 400)
# Divisible by 4 and,
# either not divisible by 100 or divisible by 400.
return not x and (y or not z) | [
"def",
"is_leap",
"(",
"year",
")",
":",
"x",
"=",
"math",
".",
"fmod",
"(",
"year",
",",
"4",
")",
"y",
"=",
"math",
".",
"fmod",
"(",
"year",
",",
"100",
")",
"z",
"=",
"math",
".",
"fmod",
"(",
"year",
",",
"400",
")",
"return",
"not",
"... | Leap year or not in the Gregorian calendar. | [
"Leap",
"year",
"or",
"not",
"in",
"the",
"Gregorian",
"calendar",
"."
] | 1e65e9be80a9d38b5f9001161b49c52a0a6f05e6 | https://github.com/phn/jdcal/blob/1e65e9be80a9d38b5f9001161b49c52a0a6f05e6/jdcal.py#L56-L64 | train |
phn/jdcal | jdcal.py | gcal2jd | def gcal2jd(year, month, day):
"""Gregorian calendar date to Julian date.
The input and output are for the proleptic Gregorian calendar,
i.e., no consideration of historical usage of the calendar is
made.
Parameters
----------
year : int
Year as an integer.
month : int
... | python | def gcal2jd(year, month, day):
"""Gregorian calendar date to Julian date.
The input and output are for the proleptic Gregorian calendar,
i.e., no consideration of historical usage of the calendar is
made.
Parameters
----------
year : int
Year as an integer.
month : int
... | [
"def",
"gcal2jd",
"(",
"year",
",",
"month",
",",
"day",
")",
":",
"year",
"=",
"int",
"(",
"year",
")",
"month",
"=",
"int",
"(",
"month",
")",
"day",
"=",
"int",
"(",
"day",
")",
"a",
"=",
"ipart",
"(",
"(",
"month",
"-",
"14",
")",
"/",
... | Gregorian calendar date to Julian date.
The input and output are for the proleptic Gregorian calendar,
i.e., no consideration of historical usage of the calendar is
made.
Parameters
----------
year : int
Year as an integer.
month : int
Month as an integer.
day : int
... | [
"Gregorian",
"calendar",
"date",
"to",
"Julian",
"date",
"."
] | 1e65e9be80a9d38b5f9001161b49c52a0a6f05e6 | https://github.com/phn/jdcal/blob/1e65e9be80a9d38b5f9001161b49c52a0a6f05e6/jdcal.py#L67-L195 | train |
phn/jdcal | jdcal.py | jd2gcal | def jd2gcal(jd1, jd2):
"""Julian date to Gregorian calendar date and time of day.
The input and output are for the proleptic Gregorian calendar,
i.e., no consideration of historical usage of the calendar is
made.
Parameters
----------
jd1, jd2: int
Sum of the two numbers is taken a... | python | def jd2gcal(jd1, jd2):
"""Julian date to Gregorian calendar date and time of day.
The input and output are for the proleptic Gregorian calendar,
i.e., no consideration of historical usage of the calendar is
made.
Parameters
----------
jd1, jd2: int
Sum of the two numbers is taken a... | [
"def",
"jd2gcal",
"(",
"jd1",
",",
"jd2",
")",
":",
"from",
"math",
"import",
"modf",
"jd1_f",
",",
"jd1_i",
"=",
"modf",
"(",
"jd1",
")",
"jd2_f",
",",
"jd2_i",
"=",
"modf",
"(",
"jd2",
")",
"jd_i",
"=",
"jd1_i",
"+",
"jd2_i",
"f",
"=",
"jd1_f",... | Julian date to Gregorian calendar date and time of day.
The input and output are for the proleptic Gregorian calendar,
i.e., no consideration of historical usage of the calendar is
made.
Parameters
----------
jd1, jd2: int
Sum of the two numbers is taken as the given Julian date. For
... | [
"Julian",
"date",
"to",
"Gregorian",
"calendar",
"date",
"and",
"time",
"of",
"day",
"."
] | 1e65e9be80a9d38b5f9001161b49c52a0a6f05e6 | https://github.com/phn/jdcal/blob/1e65e9be80a9d38b5f9001161b49c52a0a6f05e6/jdcal.py#L198-L296 | train |
phn/jdcal | jdcal.py | jcal2jd | def jcal2jd(year, month, day):
"""Julian calendar date to Julian date.
The input and output are for the proleptic Julian calendar,
i.e., no consideration of historical usage of the calendar is
made.
Parameters
----------
year : int
Year as an integer.
month : int
Month ... | python | def jcal2jd(year, month, day):
"""Julian calendar date to Julian date.
The input and output are for the proleptic Julian calendar,
i.e., no consideration of historical usage of the calendar is
made.
Parameters
----------
year : int
Year as an integer.
month : int
Month ... | [
"def",
"jcal2jd",
"(",
"year",
",",
"month",
",",
"day",
")",
":",
"year",
"=",
"int",
"(",
"year",
")",
"month",
"=",
"int",
"(",
"month",
")",
"day",
"=",
"int",
"(",
"day",
")",
"jd",
"=",
"367",
"*",
"year",
"x",
"=",
"ipart",
"(",
"(",
... | Julian calendar date to Julian date.
The input and output are for the proleptic Julian calendar,
i.e., no consideration of historical usage of the calendar is
made.
Parameters
----------
year : int
Year as an integer.
month : int
Month as an integer.
day : int
D... | [
"Julian",
"calendar",
"date",
"to",
"Julian",
"date",
"."
] | 1e65e9be80a9d38b5f9001161b49c52a0a6f05e6 | https://github.com/phn/jdcal/blob/1e65e9be80a9d38b5f9001161b49c52a0a6f05e6/jdcal.py#L299-L363 | train |
CEA-COSMIC/ModOpt | modopt/base/wrappers.py | add_args_kwargs | def add_args_kwargs(func):
"""Add Args and Kwargs
This wrapper adds support for additional arguments and keyword arguments to
any callable function
Parameters
----------
func : function
Callable function
Returns
-------
function wrapper
"""
@wraps(func)
def w... | python | def add_args_kwargs(func):
"""Add Args and Kwargs
This wrapper adds support for additional arguments and keyword arguments to
any callable function
Parameters
----------
func : function
Callable function
Returns
-------
function wrapper
"""
@wraps(func)
def w... | [
"def",
"add_args_kwargs",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"props",
"=",
"argspec",
"(",
"func",
")",
"if",
"isinstance",
"(",
"props",
"[",
"1",
"]",
",",
"... | Add Args and Kwargs
This wrapper adds support for additional arguments and keyword arguments to
any callable function
Parameters
----------
func : function
Callable function
Returns
-------
function wrapper | [
"Add",
"Args",
"and",
"Kwargs"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/wrappers.py#L19-L55 | train |
CEA-COSMIC/ModOpt | modopt/interface/log.py | set_up_log | def set_up_log(filename, verbose=True):
"""Set up log
This method sets up a basic log.
Parameters
----------
filename : str
Log file name
Returns
-------
logging.Logger instance
"""
# Add file extension.
filename += '.log'
if verbose:
print('Preparin... | python | def set_up_log(filename, verbose=True):
"""Set up log
This method sets up a basic log.
Parameters
----------
filename : str
Log file name
Returns
-------
logging.Logger instance
"""
# Add file extension.
filename += '.log'
if verbose:
print('Preparin... | [
"def",
"set_up_log",
"(",
"filename",
",",
"verbose",
"=",
"True",
")",
":",
"filename",
"+=",
"'.log'",
"if",
"verbose",
":",
"print",
"(",
"'Preparing log file:'",
",",
"filename",
")",
"logging",
".",
"captureWarnings",
"(",
"True",
")",
"formatter",
"=",... | Set up log
This method sets up a basic log.
Parameters
----------
filename : str
Log file name
Returns
-------
logging.Logger instance | [
"Set",
"up",
"log"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/interface/log.py#L16-L58 | train |
CEA-COSMIC/ModOpt | modopt/base/observable.py | Observable.add_observer | def add_observer(self, signal, observer):
"""Add an observer to the object.
Raise an exception if the signal is not allowed.
Parameters
----------
signal : str
a valid signal.
observer : @func
a function that will be called when the signal is emi... | python | def add_observer(self, signal, observer):
"""Add an observer to the object.
Raise an exception if the signal is not allowed.
Parameters
----------
signal : str
a valid signal.
observer : @func
a function that will be called when the signal is emi... | [
"def",
"add_observer",
"(",
"self",
",",
"signal",
",",
"observer",
")",
":",
"self",
".",
"_is_allowed_signal",
"(",
"signal",
")",
"self",
".",
"_add_observer",
"(",
"signal",
",",
"observer",
")"
] | Add an observer to the object.
Raise an exception if the signal is not allowed.
Parameters
----------
signal : str
a valid signal.
observer : @func
a function that will be called when the signal is emitted. | [
"Add",
"an",
"observer",
"to",
"the",
"object",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/observable.py#L51-L66 | train |
CEA-COSMIC/ModOpt | modopt/base/observable.py | Observable.remove_observer | def remove_observer(self, signal, observer):
"""Remove an observer from the object.
Raise an eception if the signal is not allowed.
Parameters
----------
signal : str
a valid signal.
observer : @func
an obervation function to be removed.
... | python | def remove_observer(self, signal, observer):
"""Remove an observer from the object.
Raise an eception if the signal is not allowed.
Parameters
----------
signal : str
a valid signal.
observer : @func
an obervation function to be removed.
... | [
"def",
"remove_observer",
"(",
"self",
",",
"signal",
",",
"observer",
")",
":",
"self",
".",
"_is_allowed_event",
"(",
"signal",
")",
"self",
".",
"_remove_observer",
"(",
"signal",
",",
"observer",
")"
] | Remove an observer from the object.
Raise an eception if the signal is not allowed.
Parameters
----------
signal : str
a valid signal.
observer : @func
an obervation function to be removed. | [
"Remove",
"an",
"observer",
"from",
"the",
"object",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/observable.py#L68-L83 | train |
CEA-COSMIC/ModOpt | modopt/base/observable.py | Observable.notify_observers | def notify_observers(self, signal, **kwargs):
""" Notify observers of a given signal.
Parameters
----------
signal : str
a valid signal.
kwargs : dict
the parameters that will be sent to the observers.
Returns
-------
out: bool
... | python | def notify_observers(self, signal, **kwargs):
""" Notify observers of a given signal.
Parameters
----------
signal : str
a valid signal.
kwargs : dict
the parameters that will be sent to the observers.
Returns
-------
out: bool
... | [
"def",
"notify_observers",
"(",
"self",
",",
"signal",
",",
"**",
"kwargs",
")",
":",
"if",
"self",
".",
"_locked",
":",
"return",
"False",
"self",
".",
"_locked",
"=",
"True",
"signal_to_be_notified",
"=",
"SignalObject",
"(",
")",
"setattr",
"(",
"signal... | Notify observers of a given signal.
Parameters
----------
signal : str
a valid signal.
kwargs : dict
the parameters that will be sent to the observers.
Returns
-------
out: bool
False if a notification is in progress, otherwis... | [
"Notify",
"observers",
"of",
"a",
"given",
"signal",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/observable.py#L85-L118 | train |
CEA-COSMIC/ModOpt | modopt/base/observable.py | Observable._is_allowed_signal | def _is_allowed_signal(self, signal):
"""Check if a signal is valid.
Raise an exception if the signal is not allowed.
Parameters
----------
signal: str
a signal.
"""
if signal not in self._allowed_signals:
raise Exception("Signal '{0}' ... | python | def _is_allowed_signal(self, signal):
"""Check if a signal is valid.
Raise an exception if the signal is not allowed.
Parameters
----------
signal: str
a signal.
"""
if signal not in self._allowed_signals:
raise Exception("Signal '{0}' ... | [
"def",
"_is_allowed_signal",
"(",
"self",
",",
"signal",
")",
":",
"if",
"signal",
"not",
"in",
"self",
".",
"_allowed_signals",
":",
"raise",
"Exception",
"(",
"\"Signal '{0}' is not allowed for '{1}'.\"",
".",
"format",
"(",
"signal",
",",
"type",
"(",
"self",... | Check if a signal is valid.
Raise an exception if the signal is not allowed.
Parameters
----------
signal: str
a signal. | [
"Check",
"if",
"a",
"signal",
"is",
"valid",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/observable.py#L137-L151 | train |
CEA-COSMIC/ModOpt | modopt/base/observable.py | Observable._add_observer | def _add_observer(self, signal, observer):
"""Associate an observer to a valid signal.
Parameters
----------
signal : str
a valid signal.
observer : @func
an obervation function.
"""
if observer not in self._observers[signal]:
... | python | def _add_observer(self, signal, observer):
"""Associate an observer to a valid signal.
Parameters
----------
signal : str
a valid signal.
observer : @func
an obervation function.
"""
if observer not in self._observers[signal]:
... | [
"def",
"_add_observer",
"(",
"self",
",",
"signal",
",",
"observer",
")",
":",
"if",
"observer",
"not",
"in",
"self",
".",
"_observers",
"[",
"signal",
"]",
":",
"self",
".",
"_observers",
"[",
"signal",
"]",
".",
"append",
"(",
"observer",
")"
] | Associate an observer to a valid signal.
Parameters
----------
signal : str
a valid signal.
observer : @func
an obervation function. | [
"Associate",
"an",
"observer",
"to",
"a",
"valid",
"signal",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/observable.py#L153-L166 | train |
CEA-COSMIC/ModOpt | modopt/base/observable.py | Observable._remove_observer | def _remove_observer(self, signal, observer):
"""Remove an observer to a valid signal.
Parameters
----------
signal : str
a valid signal.
observer : @func
an obervation function to be removed.
"""
if observer in self._observers[signal]:
... | python | def _remove_observer(self, signal, observer):
"""Remove an observer to a valid signal.
Parameters
----------
signal : str
a valid signal.
observer : @func
an obervation function to be removed.
"""
if observer in self._observers[signal]:
... | [
"def",
"_remove_observer",
"(",
"self",
",",
"signal",
",",
"observer",
")",
":",
"if",
"observer",
"in",
"self",
".",
"_observers",
"[",
"signal",
"]",
":",
"self",
".",
"_observers",
"[",
"signal",
"]",
".",
"remove",
"(",
"observer",
")"
] | Remove an observer to a valid signal.
Parameters
----------
signal : str
a valid signal.
observer : @func
an obervation function to be removed. | [
"Remove",
"an",
"observer",
"to",
"a",
"valid",
"signal",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/observable.py#L168-L181 | train |
CEA-COSMIC/ModOpt | modopt/base/observable.py | MetricObserver.is_converge | def is_converge(self):
"""Return True if the convergence criteria is matched.
"""
if len(self.list_cv_values) < self.wind:
return
start_idx = -self.wind
mid_idx = -(self.wind // 2)
old_mean = np.array(self.list_cv_values[start_idx:mid_idx]).mean()
cu... | python | def is_converge(self):
"""Return True if the convergence criteria is matched.
"""
if len(self.list_cv_values) < self.wind:
return
start_idx = -self.wind
mid_idx = -(self.wind // 2)
old_mean = np.array(self.list_cv_values[start_idx:mid_idx]).mean()
cu... | [
"def",
"is_converge",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"list_cv_values",
")",
"<",
"self",
".",
"wind",
":",
"return",
"start_idx",
"=",
"-",
"self",
".",
"wind",
"mid_idx",
"=",
"-",
"(",
"self",
".",
"wind",
"//",
"2",
")",
... | Return True if the convergence criteria is matched. | [
"Return",
"True",
"if",
"the",
"convergence",
"criteria",
"is",
"matched",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/observable.py#L256-L269 | train |
CEA-COSMIC/ModOpt | modopt/base/observable.py | MetricObserver.retrieve_metrics | def retrieve_metrics(self):
"""Return the convergence metrics saved with the corresponding
iterations.
"""
time = np.array(self.list_dates)
if len(time) >= 1:
time -= time[0]
return {'time': time, 'index': self.list_iters,
'values': self.list... | python | def retrieve_metrics(self):
"""Return the convergence metrics saved with the corresponding
iterations.
"""
time = np.array(self.list_dates)
if len(time) >= 1:
time -= time[0]
return {'time': time, 'index': self.list_iters,
'values': self.list... | [
"def",
"retrieve_metrics",
"(",
"self",
")",
":",
"time",
"=",
"np",
".",
"array",
"(",
"self",
".",
"list_dates",
")",
"if",
"len",
"(",
"time",
")",
">=",
"1",
":",
"time",
"-=",
"time",
"[",
"0",
"]",
"return",
"{",
"'time'",
":",
"time",
",",... | Return the convergence metrics saved with the corresponding
iterations. | [
"Return",
"the",
"convergence",
"metrics",
"saved",
"with",
"the",
"corresponding",
"iterations",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/observable.py#L271-L281 | train |
CEA-COSMIC/ModOpt | modopt/opt/cost.py | costObj._check_cost | def _check_cost(self):
"""Check cost function
This method tests the cost function for convergence in the specified
interval of iterations using the last n (test_range) cost values
Returns
-------
bool result of the convergence test
"""
# Add current co... | python | def _check_cost(self):
"""Check cost function
This method tests the cost function for convergence in the specified
interval of iterations using the last n (test_range) cost values
Returns
-------
bool result of the convergence test
"""
# Add current co... | [
"def",
"_check_cost",
"(",
"self",
")",
":",
"self",
".",
"_test_list",
".",
"append",
"(",
"self",
".",
"cost",
")",
"if",
"len",
"(",
"self",
".",
"_test_list",
")",
"==",
"self",
".",
"_test_range",
":",
"t1",
"=",
"np",
".",
"mean",
"(",
"self"... | Check cost function
This method tests the cost function for convergence in the specified
interval of iterations using the last n (test_range) cost values
Returns
-------
bool result of the convergence test | [
"Check",
"cost",
"function"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/cost.py#L120-L160 | train |
CEA-COSMIC/ModOpt | modopt/opt/cost.py | costObj._calc_cost | def _calc_cost(self, *args, **kwargs):
"""Calculate the cost
This method calculates the cost from each of the input operators
Returns
-------
float cost
"""
return np.sum([op.cost(*args, **kwargs) for op in self._operators]) | python | def _calc_cost(self, *args, **kwargs):
"""Calculate the cost
This method calculates the cost from each of the input operators
Returns
-------
float cost
"""
return np.sum([op.cost(*args, **kwargs) for op in self._operators]) | [
"def",
"_calc_cost",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"np",
".",
"sum",
"(",
"[",
"op",
".",
"cost",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"for",
"op",
"in",
"self",
".",
"_operators",
"]",
")"
] | Calculate the cost
This method calculates the cost from each of the input operators
Returns
-------
float cost | [
"Calculate",
"the",
"cost"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/cost.py#L162-L173 | train |
CEA-COSMIC/ModOpt | modopt/opt/cost.py | costObj.get_cost | def get_cost(self, *args, **kwargs):
"""Get cost function
This method calculates the current cost and tests for convergence
Returns
-------
bool result of the convergence test
"""
# Check if the cost should be calculated
if self._iteration % self._cost... | python | def get_cost(self, *args, **kwargs):
"""Get cost function
This method calculates the current cost and tests for convergence
Returns
-------
bool result of the convergence test
"""
# Check if the cost should be calculated
if self._iteration % self._cost... | [
"def",
"get_cost",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"self",
".",
"_iteration",
"%",
"self",
".",
"_cost_interval",
":",
"test_result",
"=",
"False",
"else",
":",
"if",
"self",
".",
"_verbose",
":",
"print",
"(",
"' ... | Get cost function
This method calculates the current cost and tests for convergence
Returns
-------
bool result of the convergence test | [
"Get",
"cost",
"function"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/cost.py#L175-L210 | train |
CEA-COSMIC/ModOpt | modopt/signal/noise.py | add_noise | def add_noise(data, sigma=1.0, noise_type='gauss'):
r"""Add noise to data
This method adds Gaussian or Poisson noise to the input data
Parameters
----------
data : np.ndarray, list or tuple
Input data array
sigma : float or list, optional
Standard deviation of the noise to be a... | python | def add_noise(data, sigma=1.0, noise_type='gauss'):
r"""Add noise to data
This method adds Gaussian or Poisson noise to the input data
Parameters
----------
data : np.ndarray, list or tuple
Input data array
sigma : float or list, optional
Standard deviation of the noise to be a... | [
"def",
"add_noise",
"(",
"data",
",",
"sigma",
"=",
"1.0",
",",
"noise_type",
"=",
"'gauss'",
")",
":",
"r",
"data",
"=",
"np",
".",
"array",
"(",
"data",
")",
"if",
"noise_type",
"not",
"in",
"(",
"'gauss'",
",",
"'poisson'",
")",
":",
"raise",
"V... | r"""Add noise to data
This method adds Gaussian or Poisson noise to the input data
Parameters
----------
data : np.ndarray, list or tuple
Input data array
sigma : float or list, optional
Standard deviation of the noise to be added ('gauss' only)
noise_type : str {'gauss', 'pois... | [
"r",
"Add",
"noise",
"to",
"data"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/noise.py#L15-L88 | train |
CEA-COSMIC/ModOpt | modopt/signal/noise.py | thresh | def thresh(data, threshold, threshold_type='hard'):
r"""Threshold data
This method perfoms hard or soft thresholding on the input data
Parameters
----------
data : np.ndarray, list or tuple
Input data array
threshold : float or np.ndarray
Threshold level(s)
threshold_type :... | python | def thresh(data, threshold, threshold_type='hard'):
r"""Threshold data
This method perfoms hard or soft thresholding on the input data
Parameters
----------
data : np.ndarray, list or tuple
Input data array
threshold : float or np.ndarray
Threshold level(s)
threshold_type :... | [
"def",
"thresh",
"(",
"data",
",",
"threshold",
",",
"threshold_type",
"=",
"'hard'",
")",
":",
"r",
"data",
"=",
"np",
".",
"array",
"(",
"data",
")",
"if",
"threshold_type",
"not",
"in",
"(",
"'hard'",
",",
"'soft'",
")",
":",
"raise",
"ValueError",
... | r"""Threshold data
This method perfoms hard or soft thresholding on the input data
Parameters
----------
data : np.ndarray, list or tuple
Input data array
threshold : float or np.ndarray
Threshold level(s)
threshold_type : str {'hard', 'soft'}
Type of noise to be added ... | [
"r",
"Threshold",
"data"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/noise.py#L91-L173 | train |
CEA-COSMIC/ModOpt | modopt/opt/gradient.py | GradBasic._get_grad_method | def _get_grad_method(self, data):
r"""Get the gradient
This method calculates the gradient step from the input data
Parameters
----------
data : np.ndarray
Input data array
Notes
-----
Implements the following equation:
.. math::
... | python | def _get_grad_method(self, data):
r"""Get the gradient
This method calculates the gradient step from the input data
Parameters
----------
data : np.ndarray
Input data array
Notes
-----
Implements the following equation:
.. math::
... | [
"def",
"_get_grad_method",
"(",
"self",
",",
"data",
")",
":",
"r",
"self",
".",
"grad",
"=",
"self",
".",
"trans_op",
"(",
"self",
".",
"op",
"(",
"data",
")",
"-",
"self",
".",
"obs_data",
")"
] | r"""Get the gradient
This method calculates the gradient step from the input data
Parameters
----------
data : np.ndarray
Input data array
Notes
-----
Implements the following equation:
.. math::
\nabla F(x) = \mathbf{H}^T(\math... | [
"r",
"Get",
"the",
"gradient"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/gradient.py#L222-L241 | train |
CEA-COSMIC/ModOpt | modopt/opt/gradient.py | GradBasic._cost_method | def _cost_method(self, *args, **kwargs):
"""Calculate gradient component of the cost
This method returns the l2 norm error of the difference between the
original data and the data obtained after optimisation
Returns
-------
float gradient cost component
"""
... | python | def _cost_method(self, *args, **kwargs):
"""Calculate gradient component of the cost
This method returns the l2 norm error of the difference between the
original data and the data obtained after optimisation
Returns
-------
float gradient cost component
"""
... | [
"def",
"_cost_method",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"cost_val",
"=",
"0.5",
"*",
"np",
".",
"linalg",
".",
"norm",
"(",
"self",
".",
"obs_data",
"-",
"self",
".",
"op",
"(",
"args",
"[",
"0",
"]",
")",
")",
"**"... | Calculate gradient component of the cost
This method returns the l2 norm error of the difference between the
original data and the data obtained after optimisation
Returns
-------
float gradient cost component | [
"Calculate",
"gradient",
"component",
"of",
"the",
"cost"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/gradient.py#L243-L260 | train |
CEA-COSMIC/ModOpt | modopt/opt/proximity.py | Positivity._cost_method | def _cost_method(self, *args, **kwargs):
"""Calculate positivity component of the cost
This method returns 0 as the posivituty does not contribute to the
cost.
Returns
-------
float zero
"""
if 'verbose' in kwargs and kwargs['verbose']:
pri... | python | def _cost_method(self, *args, **kwargs):
"""Calculate positivity component of the cost
This method returns 0 as the posivituty does not contribute to the
cost.
Returns
-------
float zero
"""
if 'verbose' in kwargs and kwargs['verbose']:
pri... | [
"def",
"_cost_method",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"'verbose'",
"in",
"kwargs",
"and",
"kwargs",
"[",
"'verbose'",
"]",
":",
"print",
"(",
"' - Min (X):'",
",",
"np",
".",
"min",
"(",
"args",
"[",
"0",
"]",
"... | Calculate positivity component of the cost
This method returns 0 as the posivituty does not contribute to the
cost.
Returns
-------
float zero | [
"Calculate",
"positivity",
"component",
"of",
"the",
"cost"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/proximity.py#L90-L105 | train |
CEA-COSMIC/ModOpt | modopt/opt/proximity.py | SparseThreshold._cost_method | def _cost_method(self, *args, **kwargs):
"""Calculate sparsity component of the cost
This method returns the l1 norm error of the weighted wavelet
coefficients
Returns
-------
float sparsity cost component
"""
cost_val = np.sum(np.abs(self.weights * se... | python | def _cost_method(self, *args, **kwargs):
"""Calculate sparsity component of the cost
This method returns the l1 norm error of the weighted wavelet
coefficients
Returns
-------
float sparsity cost component
"""
cost_val = np.sum(np.abs(self.weights * se... | [
"def",
"_cost_method",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"cost_val",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"abs",
"(",
"self",
".",
"weights",
"*",
"self",
".",
"_linear",
".",
"op",
"(",
"args",
"[",
"0",
"]",
")",... | Calculate sparsity component of the cost
This method returns the l1 norm error of the weighted wavelet
coefficients
Returns
-------
float sparsity cost component | [
"Calculate",
"sparsity",
"component",
"of",
"the",
"cost"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/proximity.py#L154-L171 | train |
CEA-COSMIC/ModOpt | modopt/opt/proximity.py | LowRankMatrix._cost_method | def _cost_method(self, *args, **kwargs):
"""Calculate low-rank component of the cost
This method returns the nuclear norm error of the deconvolved data in
matrix form
Returns
-------
float low-rank cost component
"""
cost_val = self.thresh * nuclear_no... | python | def _cost_method(self, *args, **kwargs):
"""Calculate low-rank component of the cost
This method returns the nuclear norm error of the deconvolved data in
matrix form
Returns
-------
float low-rank cost component
"""
cost_val = self.thresh * nuclear_no... | [
"def",
"_cost_method",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"cost_val",
"=",
"self",
".",
"thresh",
"*",
"nuclear_norm",
"(",
"cube2matrix",
"(",
"args",
"[",
"0",
"]",
")",
")",
"if",
"'verbose'",
"in",
"kwargs",
"and",
"kwa... | Calculate low-rank component of the cost
This method returns the nuclear norm error of the deconvolved data in
matrix form
Returns
-------
float low-rank cost component | [
"Calculate",
"low",
"-",
"rank",
"component",
"of",
"the",
"cost"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/proximity.py#L255-L272 | train |
CEA-COSMIC/ModOpt | modopt/opt/proximity.py | LinearCompositionProx._op_method | def _op_method(self, data, extra_factor=1.0):
r"""Operator method
This method returns the scaled version of the proximity operator as
given by Lemma 2.8 of [CW2005].
Parameters
----------
data : np.ndarray
Input data array
extra_factor : float
... | python | def _op_method(self, data, extra_factor=1.0):
r"""Operator method
This method returns the scaled version of the proximity operator as
given by Lemma 2.8 of [CW2005].
Parameters
----------
data : np.ndarray
Input data array
extra_factor : float
... | [
"def",
"_op_method",
"(",
"self",
",",
"data",
",",
"extra_factor",
"=",
"1.0",
")",
":",
"r",
"return",
"self",
".",
"linear_op",
".",
"adj_op",
"(",
"self",
".",
"prox_op",
".",
"op",
"(",
"self",
".",
"linear_op",
".",
"op",
"(",
"data",
")",
",... | r"""Operator method
This method returns the scaled version of the proximity operator as
given by Lemma 2.8 of [CW2005].
Parameters
----------
data : np.ndarray
Input data array
extra_factor : float
Additional multiplication factor
Return... | [
"r",
"Operator",
"method"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/proximity.py#L295-L314 | train |
CEA-COSMIC/ModOpt | modopt/opt/proximity.py | LinearCompositionProx._cost_method | def _cost_method(self, *args, **kwargs):
"""Calculate the cost function associated to the composed function
Returns
-------
float the cost of the associated composed function
"""
return self.prox_op.cost(self.linear_op.op(args[0]), **kwargs) | python | def _cost_method(self, *args, **kwargs):
"""Calculate the cost function associated to the composed function
Returns
-------
float the cost of the associated composed function
"""
return self.prox_op.cost(self.linear_op.op(args[0]), **kwargs) | [
"def",
"_cost_method",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"self",
".",
"prox_op",
".",
"cost",
"(",
"self",
".",
"linear_op",
".",
"op",
"(",
"args",
"[",
"0",
"]",
")",
",",
"**",
"kwargs",
")"
] | Calculate the cost function associated to the composed function
Returns
-------
float the cost of the associated composed function | [
"Calculate",
"the",
"cost",
"function",
"associated",
"to",
"the",
"composed",
"function"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/proximity.py#L316-L323 | train |
CEA-COSMIC/ModOpt | modopt/opt/proximity.py | ProximityCombo._cost_method | def _cost_method(self, *args, **kwargs):
"""Calculate combined proximity operator components of the cost
This method returns the sum of the cost components from each of the
proximity operators
Returns
-------
float combinded cost components
"""
return ... | python | def _cost_method(self, *args, **kwargs):
"""Calculate combined proximity operator components of the cost
This method returns the sum of the cost components from each of the
proximity operators
Returns
-------
float combinded cost components
"""
return ... | [
"def",
"_cost_method",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"np",
".",
"sum",
"(",
"[",
"operator",
".",
"cost",
"(",
"data",
")",
"for",
"operator",
",",
"data",
"in",
"zip",
"(",
"self",
".",
"operators",
",",
... | Calculate combined proximity operator components of the cost
This method returns the sum of the cost components from each of the
proximity operators
Returns
-------
float combinded cost components | [
"Calculate",
"combined",
"proximity",
"operator",
"components",
"of",
"the",
"cost"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/proximity.py#L423-L436 | train |
CEA-COSMIC/ModOpt | modopt/math/metrics.py | min_max_normalize | def min_max_normalize(img):
"""Centre and normalize a given array.
Parameters:
----------
img: np.ndarray
"""
min_img = img.min()
max_img = img.max()
return (img - min_img) / (max_img - min_img) | python | def min_max_normalize(img):
"""Centre and normalize a given array.
Parameters:
----------
img: np.ndarray
"""
min_img = img.min()
max_img = img.max()
return (img - min_img) / (max_img - min_img) | [
"def",
"min_max_normalize",
"(",
"img",
")",
":",
"min_img",
"=",
"img",
".",
"min",
"(",
")",
"max_img",
"=",
"img",
".",
"max",
"(",
")",
"return",
"(",
"img",
"-",
"min_img",
")",
"/",
"(",
"max_img",
"-",
"min_img",
")"
] | Centre and normalize a given array.
Parameters:
----------
img: np.ndarray | [
"Centre",
"and",
"normalize",
"a",
"given",
"array",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/metrics.py#L21-L33 | train |
CEA-COSMIC/ModOpt | modopt/math/metrics.py | _preprocess_input | def _preprocess_input(test, ref, mask=None):
"""Wrapper to the metric
Parameters
----------
ref : np.ndarray
the reference image
test : np.ndarray
the tested image
mask : np.ndarray, optional
the mask for the ROI
Notes
-----
Compute the metric only on magnet... | python | def _preprocess_input(test, ref, mask=None):
"""Wrapper to the metric
Parameters
----------
ref : np.ndarray
the reference image
test : np.ndarray
the tested image
mask : np.ndarray, optional
the mask for the ROI
Notes
-----
Compute the metric only on magnet... | [
"def",
"_preprocess_input",
"(",
"test",
",",
"ref",
",",
"mask",
"=",
"None",
")",
":",
"test",
"=",
"np",
".",
"abs",
"(",
"np",
".",
"copy",
"(",
"test",
")",
")",
".",
"astype",
"(",
"'float64'",
")",
"ref",
"=",
"np",
".",
"abs",
"(",
"np"... | Wrapper to the metric
Parameters
----------
ref : np.ndarray
the reference image
test : np.ndarray
the tested image
mask : np.ndarray, optional
the mask for the ROI
Notes
-----
Compute the metric only on magnetude.
Returns
-------
ssim: float, the s... | [
"Wrapper",
"to",
"the",
"metric"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/metrics.py#L36-L70 | train |
CEA-COSMIC/ModOpt | modopt/interface/errors.py | file_name_error | def file_name_error(file_name):
"""File name error
This method checks if the input file name is valid.
Parameters
----------
file_name : str
File name string
Raises
------
IOError
If file name not specified or file not found
"""
if file_name == '' or file_nam... | python | def file_name_error(file_name):
"""File name error
This method checks if the input file name is valid.
Parameters
----------
file_name : str
File name string
Raises
------
IOError
If file name not specified or file not found
"""
if file_name == '' or file_nam... | [
"def",
"file_name_error",
"(",
"file_name",
")",
":",
"if",
"file_name",
"==",
"''",
"or",
"file_name",
"[",
"0",
"]",
"[",
"0",
"]",
"==",
"'-'",
":",
"raise",
"IOError",
"(",
"'Input file name not specified.'",
")",
"elif",
"not",
"os",
".",
"path",
".... | File name error
This method checks if the input file name is valid.
Parameters
----------
file_name : str
File name string
Raises
------
IOError
If file name not specified or file not found | [
"File",
"name",
"error"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/interface/errors.py#L79-L100 | train |
CEA-COSMIC/ModOpt | modopt/interface/errors.py | is_executable | def is_executable(exe_name):
"""Check if Input is Executable
This methid checks if the input executable exists.
Parameters
----------
exe_name : str
Executable name
Returns
-------
Bool result of test
Raises
------
TypeError
For invalid input type
"""... | python | def is_executable(exe_name):
"""Check if Input is Executable
This methid checks if the input executable exists.
Parameters
----------
exe_name : str
Executable name
Returns
-------
Bool result of test
Raises
------
TypeError
For invalid input type
"""... | [
"def",
"is_executable",
"(",
"exe_name",
")",
":",
"if",
"not",
"isinstance",
"(",
"exe_name",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'Executable name must be a string.'",
")",
"def",
"is_exe",
"(",
"fpath",
")",
":",
"return",
"os",
".",
"path",
... | Check if Input is Executable
This methid checks if the input executable exists.
Parameters
----------
exe_name : str
Executable name
Returns
-------
Bool result of test
Raises
------
TypeError
For invalid input type | [
"Check",
"if",
"Input",
"is",
"Executable"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/interface/errors.py#L103-L145 | train |
CEA-COSMIC/ModOpt | modopt/opt/algorithms.py | SetUp._check_operator | def _check_operator(self, operator):
""" Check Set-Up
This method checks algorithm operator against the expected parent
classes
Parameters
----------
operator : str
Algorithm operator to check
"""
if not isinstance(operator, type(None)):
... | python | def _check_operator(self, operator):
""" Check Set-Up
This method checks algorithm operator against the expected parent
classes
Parameters
----------
operator : str
Algorithm operator to check
"""
if not isinstance(operator, type(None)):
... | [
"def",
"_check_operator",
"(",
"self",
",",
"operator",
")",
":",
"if",
"not",
"isinstance",
"(",
"operator",
",",
"type",
"(",
"None",
")",
")",
":",
"tree",
"=",
"[",
"obj",
".",
"__name__",
"for",
"obj",
"in",
"getmro",
"(",
"operator",
".",
"__cl... | Check Set-Up
This method checks algorithm operator against the expected parent
classes
Parameters
----------
operator : str
Algorithm operator to check | [
"Check",
"Set",
"-",
"Up"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/algorithms.py#L157-L175 | train |
CEA-COSMIC/ModOpt | modopt/opt/algorithms.py | FISTA._check_restart_params | def _check_restart_params(self, restart_strategy, min_beta, s_greedy,
xi_restart):
r""" Check restarting parameters
This method checks that the restarting parameters are set and satisfy
the correct assumptions. It also checks that the current mode is
regula... | python | def _check_restart_params(self, restart_strategy, min_beta, s_greedy,
xi_restart):
r""" Check restarting parameters
This method checks that the restarting parameters are set and satisfy
the correct assumptions. It also checks that the current mode is
regula... | [
"def",
"_check_restart_params",
"(",
"self",
",",
"restart_strategy",
",",
"min_beta",
",",
"s_greedy",
",",
"xi_restart",
")",
":",
"r",
"if",
"restart_strategy",
"is",
"None",
":",
"return",
"True",
"if",
"self",
".",
"mode",
"!=",
"'regular'",
":",
"raise... | r""" Check restarting parameters
This method checks that the restarting parameters are set and satisfy
the correct assumptions. It also checks that the current mode is
regular (as opposed to CD for now).
Parameters
----------
restart_strategy: str or None
na... | [
"r",
"Check",
"restarting",
"parameters"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/algorithms.py#L307-L361 | train |
CEA-COSMIC/ModOpt | modopt/opt/algorithms.py | FISTA.is_restart | def is_restart(self, z_old, x_new, x_old):
r""" Check whether the algorithm needs to restart
This method implements the checks necessary to tell whether the
algorithm needs to restart depending on the restarting strategy.
It also updates the FISTA parameters according to the restarting
... | python | def is_restart(self, z_old, x_new, x_old):
r""" Check whether the algorithm needs to restart
This method implements the checks necessary to tell whether the
algorithm needs to restart depending on the restarting strategy.
It also updates the FISTA parameters according to the restarting
... | [
"def",
"is_restart",
"(",
"self",
",",
"z_old",
",",
"x_new",
",",
"x_old",
")",
":",
"r",
"if",
"self",
".",
"restart_strategy",
"is",
"None",
":",
"return",
"False",
"criterion",
"=",
"np",
".",
"vdot",
"(",
"z_old",
"-",
"x_new",
",",
"x_new",
"-"... | r""" Check whether the algorithm needs to restart
This method implements the checks necessary to tell whether the
algorithm needs to restart depending on the restarting strategy.
It also updates the FISTA parameters according to the restarting
strategy (namely beta and r).
Para... | [
"r",
"Check",
"whether",
"the",
"algorithm",
"needs",
"to",
"restart"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/algorithms.py#L363-L407 | train |
CEA-COSMIC/ModOpt | modopt/opt/algorithms.py | FISTA.update_beta | def update_beta(self, beta):
r"""Update beta
This method updates beta only in the case of safeguarding (should only
be done in the greedy restarting strategy).
Parameters
----------
beta: float
The beta parameter
Returns
-------
floa... | python | def update_beta(self, beta):
r"""Update beta
This method updates beta only in the case of safeguarding (should only
be done in the greedy restarting strategy).
Parameters
----------
beta: float
The beta parameter
Returns
-------
floa... | [
"def",
"update_beta",
"(",
"self",
",",
"beta",
")",
":",
"r",
"if",
"self",
".",
"_safeguard",
":",
"beta",
"*=",
"self",
".",
"xi_restart",
"beta",
"=",
"max",
"(",
"beta",
",",
"self",
".",
"min_beta",
")",
"return",
"beta"
] | r"""Update beta
This method updates beta only in the case of safeguarding (should only
be done in the greedy restarting strategy).
Parameters
----------
beta: float
The beta parameter
Returns
-------
float: the new value for the beta paramet... | [
"r",
"Update",
"beta"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/algorithms.py#L409-L429 | train |
CEA-COSMIC/ModOpt | modopt/opt/algorithms.py | FISTA.update_lambda | def update_lambda(self, *args, **kwargs):
r"""Update lambda
This method updates the value of lambda
Returns
-------
float current lambda value
Notes
-----
Implements steps 3 and 4 from algoritm 10.7 in [B2011]_
"""
if self.restart_stra... | python | def update_lambda(self, *args, **kwargs):
r"""Update lambda
This method updates the value of lambda
Returns
-------
float current lambda value
Notes
-----
Implements steps 3 and 4 from algoritm 10.7 in [B2011]_
"""
if self.restart_stra... | [
"def",
"update_lambda",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"r",
"if",
"self",
".",
"restart_strategy",
"==",
"'greedy'",
":",
"return",
"2",
"self",
".",
"_t_prev",
"=",
"self",
".",
"_t_now",
"if",
"self",
".",
"mode",
"==... | r"""Update lambda
This method updates the value of lambda
Returns
-------
float current lambda value
Notes
-----
Implements steps 3 and 4 from algoritm 10.7 in [B2011]_ | [
"r",
"Update",
"lambda"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/algorithms.py#L431-L460 | train |
CEA-COSMIC/ModOpt | modopt/signal/wavelet.py | call_mr_transform | def call_mr_transform(data, opt='', path='./',
remove_files=True): # pragma: no cover
r"""Call mr_transform
This method calls the iSAP module mr_transform
Parameters
----------
data : np.ndarray
Input data, 2D array
opt : list or str, optional
Options to ... | python | def call_mr_transform(data, opt='', path='./',
remove_files=True): # pragma: no cover
r"""Call mr_transform
This method calls the iSAP module mr_transform
Parameters
----------
data : np.ndarray
Input data, 2D array
opt : list or str, optional
Options to ... | [
"def",
"call_mr_transform",
"(",
"data",
",",
"opt",
"=",
"''",
",",
"path",
"=",
"'./'",
",",
"remove_files",
"=",
"True",
")",
":",
"r",
"if",
"not",
"import_astropy",
":",
"raise",
"ImportError",
"(",
"'Astropy package not found.'",
")",
"if",
"(",
"not... | r"""Call mr_transform
This method calls the iSAP module mr_transform
Parameters
----------
data : np.ndarray
Input data, 2D array
opt : list or str, optional
Options to be passed to mr_transform
path : str, optional
Path for output files (default is './')
remove_fil... | [
"r",
"Call",
"mr_transform"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/wavelet.py#L36-L131 | train |
CEA-COSMIC/ModOpt | modopt/signal/wavelet.py | get_mr_filters | def get_mr_filters(data_shape, opt='', coarse=False): # pragma: no cover
"""Get mr_transform filters
This method obtains wavelet filters by calling mr_transform
Parameters
----------
data_shape : tuple
2D data shape
opt : list, optional
List of additonal mr_transform options
... | python | def get_mr_filters(data_shape, opt='', coarse=False): # pragma: no cover
"""Get mr_transform filters
This method obtains wavelet filters by calling mr_transform
Parameters
----------
data_shape : tuple
2D data shape
opt : list, optional
List of additonal mr_transform options
... | [
"def",
"get_mr_filters",
"(",
"data_shape",
",",
"opt",
"=",
"''",
",",
"coarse",
"=",
"False",
")",
":",
"data_shape",
"=",
"np",
".",
"array",
"(",
"data_shape",
")",
"data_shape",
"+=",
"data_shape",
"%",
"2",
"-",
"1",
"fake_data",
"=",
"np",
".",
... | Get mr_transform filters
This method obtains wavelet filters by calling mr_transform
Parameters
----------
data_shape : tuple
2D data shape
opt : list, optional
List of additonal mr_transform options
coarse : bool, optional
Option to keep coarse scale (default is 'False... | [
"Get",
"mr_transform",
"filters"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/wavelet.py#L134-L169 | train |
CEA-COSMIC/ModOpt | modopt/math/matrix.py | gram_schmidt | def gram_schmidt(matrix, return_opt='orthonormal'):
r"""Gram-Schmit
This method orthonormalizes the row vectors of the input matrix.
Parameters
----------
matrix : np.ndarray
Input matrix array
return_opt : str {orthonormal, orthogonal, both}
Option to return u, e or both.
... | python | def gram_schmidt(matrix, return_opt='orthonormal'):
r"""Gram-Schmit
This method orthonormalizes the row vectors of the input matrix.
Parameters
----------
matrix : np.ndarray
Input matrix array
return_opt : str {orthonormal, orthogonal, both}
Option to return u, e or both.
... | [
"def",
"gram_schmidt",
"(",
"matrix",
",",
"return_opt",
"=",
"'orthonormal'",
")",
":",
"r",
"if",
"return_opt",
"not",
"in",
"(",
"'orthonormal'",
",",
"'orthogonal'",
",",
"'both'",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid return_opt, options are: \"orth... | r"""Gram-Schmit
This method orthonormalizes the row vectors of the input matrix.
Parameters
----------
matrix : np.ndarray
Input matrix array
return_opt : str {orthonormal, orthogonal, both}
Option to return u, e or both.
Returns
-------
Lists of orthogonal vectors, u,... | [
"r",
"Gram",
"-",
"Schmit"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/matrix.py#L17-L74 | train |
CEA-COSMIC/ModOpt | modopt/math/matrix.py | nuclear_norm | def nuclear_norm(data):
r"""Nuclear norm
This method computes the nuclear (or trace) norm of the input data.
Parameters
----------
data : np.ndarray
Input data array
Returns
-------
float nuclear norm value
Examples
--------
>>> from modopt.math.matrix import nucl... | python | def nuclear_norm(data):
r"""Nuclear norm
This method computes the nuclear (or trace) norm of the input data.
Parameters
----------
data : np.ndarray
Input data array
Returns
-------
float nuclear norm value
Examples
--------
>>> from modopt.math.matrix import nucl... | [
"def",
"nuclear_norm",
"(",
"data",
")",
":",
"r",
"u",
",",
"s",
",",
"v",
"=",
"np",
".",
"linalg",
".",
"svd",
"(",
"data",
")",
"return",
"np",
".",
"sum",
"(",
"s",
")"
] | r"""Nuclear norm
This method computes the nuclear (or trace) norm of the input data.
Parameters
----------
data : np.ndarray
Input data array
Returns
-------
float nuclear norm value
Examples
--------
>>> from modopt.math.matrix import nuclear_norm
>>> a = np.aran... | [
"r",
"Nuclear",
"norm"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/matrix.py#L77-L111 | train |
CEA-COSMIC/ModOpt | modopt/math/matrix.py | project | def project(u, v):
r"""Project vector
This method projects vector v onto vector u.
Parameters
----------
u : np.ndarray
Input vector
v : np.ndarray
Input vector
Returns
-------
np.ndarray projection
Examples
--------
>>> from modopt.math.matrix import ... | python | def project(u, v):
r"""Project vector
This method projects vector v onto vector u.
Parameters
----------
u : np.ndarray
Input vector
v : np.ndarray
Input vector
Returns
-------
np.ndarray projection
Examples
--------
>>> from modopt.math.matrix import ... | [
"def",
"project",
"(",
"u",
",",
"v",
")",
":",
"r",
"return",
"np",
".",
"inner",
"(",
"v",
",",
"u",
")",
"/",
"np",
".",
"inner",
"(",
"u",
",",
"u",
")",
"*",
"u"
] | r"""Project vector
This method projects vector v onto vector u.
Parameters
----------
u : np.ndarray
Input vector
v : np.ndarray
Input vector
Returns
-------
np.ndarray projection
Examples
--------
>>> from modopt.math.matrix import project
>>> a = np.... | [
"r",
"Project",
"vector"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/matrix.py#L114-L150 | train |
CEA-COSMIC/ModOpt | modopt/math/matrix.py | rot_matrix | def rot_matrix(angle):
r"""Rotation matrix
This method produces a 2x2 rotation matrix for the given input angle.
Parameters
----------
angle : float
Rotation angle in radians
Returns
-------
np.ndarray 2x2 rotation matrix
Examples
--------
>>> from modopt.math.mat... | python | def rot_matrix(angle):
r"""Rotation matrix
This method produces a 2x2 rotation matrix for the given input angle.
Parameters
----------
angle : float
Rotation angle in radians
Returns
-------
np.ndarray 2x2 rotation matrix
Examples
--------
>>> from modopt.math.mat... | [
"def",
"rot_matrix",
"(",
"angle",
")",
":",
"r",
"return",
"np",
".",
"around",
"(",
"np",
".",
"array",
"(",
"[",
"[",
"np",
".",
"cos",
"(",
"angle",
")",
",",
"-",
"np",
".",
"sin",
"(",
"angle",
")",
"]",
",",
"[",
"np",
".",
"sin",
"(... | r"""Rotation matrix
This method produces a 2x2 rotation matrix for the given input angle.
Parameters
----------
angle : float
Rotation angle in radians
Returns
-------
np.ndarray 2x2 rotation matrix
Examples
--------
>>> from modopt.math.matrix import rot_matrix
>... | [
"r",
"Rotation",
"matrix"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/matrix.py#L153-L187 | train |
CEA-COSMIC/ModOpt | modopt/math/matrix.py | PowerMethod._set_initial_x | def _set_initial_x(self):
"""Set initial value of x
This method sets the initial value of x to an arrray of random values
Returns
-------
np.ndarray of random values of the same shape as the input data
"""
return np.random.random(self._data_shape).astype(self.... | python | def _set_initial_x(self):
"""Set initial value of x
This method sets the initial value of x to an arrray of random values
Returns
-------
np.ndarray of random values of the same shape as the input data
"""
return np.random.random(self._data_shape).astype(self.... | [
"def",
"_set_initial_x",
"(",
"self",
")",
":",
"return",
"np",
".",
"random",
".",
"random",
"(",
"self",
".",
"_data_shape",
")",
".",
"astype",
"(",
"self",
".",
"_data_type",
")"
] | Set initial value of x
This method sets the initial value of x to an arrray of random values
Returns
-------
np.ndarray of random values of the same shape as the input data | [
"Set",
"initial",
"value",
"of",
"x"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/matrix.py#L285-L296 | train |
CEA-COSMIC/ModOpt | modopt/math/matrix.py | PowerMethod.get_spec_rad | def get_spec_rad(self, tolerance=1e-6, max_iter=20, extra_factor=1.0):
"""Get spectral radius
This method calculates the spectral radius
Parameters
----------
tolerance : float, optional
Tolerance threshold for convergence (default is "1e-6")
max_iter : int,... | python | def get_spec_rad(self, tolerance=1e-6, max_iter=20, extra_factor=1.0):
"""Get spectral radius
This method calculates the spectral radius
Parameters
----------
tolerance : float, optional
Tolerance threshold for convergence (default is "1e-6")
max_iter : int,... | [
"def",
"get_spec_rad",
"(",
"self",
",",
"tolerance",
"=",
"1e-6",
",",
"max_iter",
"=",
"20",
",",
"extra_factor",
"=",
"1.0",
")",
":",
"x_old",
"=",
"self",
".",
"_set_initial_x",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"max_iter",
")",
":",
"x_... | Get spectral radius
This method calculates the spectral radius
Parameters
----------
tolerance : float, optional
Tolerance threshold for convergence (default is "1e-6")
max_iter : int, optional
Maximum number of iterations (default is 20)
extra_f... | [
"Get",
"spectral",
"radius"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/matrix.py#L298-L340 | train |
CEA-COSMIC/ModOpt | modopt/opt/linear.py | LinearCombo._check_type | def _check_type(self, input_val):
""" Check Input Type
This method checks if the input is a list, tuple or a numpy array and
converts the input to a numpy array
Parameters
----------
input_val : list, tuple or np.ndarray
Returns
-------
np.ndarr... | python | def _check_type(self, input_val):
""" Check Input Type
This method checks if the input is a list, tuple or a numpy array and
converts the input to a numpy array
Parameters
----------
input_val : list, tuple or np.ndarray
Returns
-------
np.ndarr... | [
"def",
"_check_type",
"(",
"self",
",",
"input_val",
")",
":",
"if",
"not",
"isinstance",
"(",
"input_val",
",",
"(",
"list",
",",
"tuple",
",",
"np",
".",
"ndarray",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Invalid input type, input must be a list, tuple '... | Check Input Type
This method checks if the input is a list, tuple or a numpy array and
converts the input to a numpy array
Parameters
----------
input_val : list, tuple or np.ndarray
Returns
-------
np.ndarray of input
Raises
------
... | [
"Check",
"Input",
"Type"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/linear.py#L154-L184 | train |
CEA-COSMIC/ModOpt | modopt/signal/svd.py | find_n_pc | def find_n_pc(u, factor=0.5):
"""Find number of principal components
This method finds the minimum number of principal components required
Parameters
----------
u : np.ndarray
Left singular vector of the original data
factor : float, optional
Factor for testing the auto correla... | python | def find_n_pc(u, factor=0.5):
"""Find number of principal components
This method finds the minimum number of principal components required
Parameters
----------
u : np.ndarray
Left singular vector of the original data
factor : float, optional
Factor for testing the auto correla... | [
"def",
"find_n_pc",
"(",
"u",
",",
"factor",
"=",
"0.5",
")",
":",
"if",
"np",
".",
"sqrt",
"(",
"u",
".",
"shape",
"[",
"0",
"]",
")",
"%",
"1",
":",
"raise",
"ValueError",
"(",
"'Invalid left singular value. The size of the first '",
"'dimenion of u must b... | Find number of principal components
This method finds the minimum number of principal components required
Parameters
----------
u : np.ndarray
Left singular vector of the original data
factor : float, optional
Factor for testing the auto correlation (default is '0.5')
Returns
... | [
"Find",
"number",
"of",
"principal",
"components"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/svd.py#L21-L60 | train |
CEA-COSMIC/ModOpt | modopt/signal/svd.py | calculate_svd | def calculate_svd(data):
"""Calculate Singular Value Decomposition
This method calculates the Singular Value Decomposition (SVD) of the input
data using SciPy.
Parameters
----------
data : np.ndarray
Input data array, 2D matrix
Returns
-------
tuple of left singular vector... | python | def calculate_svd(data):
"""Calculate Singular Value Decomposition
This method calculates the Singular Value Decomposition (SVD) of the input
data using SciPy.
Parameters
----------
data : np.ndarray
Input data array, 2D matrix
Returns
-------
tuple of left singular vector... | [
"def",
"calculate_svd",
"(",
"data",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"data",
",",
"np",
".",
"ndarray",
")",
")",
"or",
"(",
"data",
".",
"ndim",
"!=",
"2",
")",
":",
"raise",
"TypeError",
"(",
"'Input data must be a 2D np.ndarray.'",
")",... | Calculate Singular Value Decomposition
This method calculates the Singular Value Decomposition (SVD) of the input
data using SciPy.
Parameters
----------
data : np.ndarray
Input data array, 2D matrix
Returns
-------
tuple of left singular vector, singular values and right sing... | [
"Calculate",
"Singular",
"Value",
"Decomposition"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/svd.py#L63-L89 | train |
CEA-COSMIC/ModOpt | modopt/signal/svd.py | svd_thresh | def svd_thresh(data, threshold=None, n_pc=None, thresh_type='hard'):
r"""Threshold the singular values
This method thresholds the input data using singular value decomposition
Parameters
----------
data : np.ndarray
Input data array, 2D matrix
threshold : float or np.ndarray, optional
... | python | def svd_thresh(data, threshold=None, n_pc=None, thresh_type='hard'):
r"""Threshold the singular values
This method thresholds the input data using singular value decomposition
Parameters
----------
data : np.ndarray
Input data array, 2D matrix
threshold : float or np.ndarray, optional
... | [
"def",
"svd_thresh",
"(",
"data",
",",
"threshold",
"=",
"None",
",",
"n_pc",
"=",
"None",
",",
"thresh_type",
"=",
"'hard'",
")",
":",
"r",
"if",
"(",
"(",
"not",
"isinstance",
"(",
"n_pc",
",",
"(",
"int",
",",
"str",
",",
"type",
"(",
"None",
... | r"""Threshold the singular values
This method thresholds the input data using singular value decomposition
Parameters
----------
data : np.ndarray
Input data array, 2D matrix
threshold : float or np.ndarray, optional
Threshold value(s)
n_pc : int or str, optional
Number... | [
"r",
"Threshold",
"the",
"singular",
"values"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/svd.py#L92-L168 | train |
CEA-COSMIC/ModOpt | modopt/signal/svd.py | svd_thresh_coef | def svd_thresh_coef(data, operator, threshold, thresh_type='hard'):
"""Threshold the singular values coefficients
This method thresholds the input data using singular value decomposition
Parameters
----------
data : np.ndarray
Input data array, 2D matrix
operator : class
Operat... | python | def svd_thresh_coef(data, operator, threshold, thresh_type='hard'):
"""Threshold the singular values coefficients
This method thresholds the input data using singular value decomposition
Parameters
----------
data : np.ndarray
Input data array, 2D matrix
operator : class
Operat... | [
"def",
"svd_thresh_coef",
"(",
"data",
",",
"operator",
",",
"threshold",
",",
"thresh_type",
"=",
"'hard'",
")",
":",
"if",
"not",
"callable",
"(",
"operator",
")",
":",
"raise",
"TypeError",
"(",
"'Operator must be a callable function.'",
")",
"u",
",",
"s",... | Threshold the singular values coefficients
This method thresholds the input data using singular value decomposition
Parameters
----------
data : np.ndarray
Input data array, 2D matrix
operator : class
Operator class instance
threshold : float or np.ndarray
Threshold val... | [
"Threshold",
"the",
"singular",
"values",
"coefficients"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/svd.py#L171-L222 | train |
CEA-COSMIC/ModOpt | modopt/math/stats.py | gaussian_kernel | def gaussian_kernel(data_shape, sigma, norm='max'):
r"""Gaussian kernel
This method produces a Gaussian kerenal of a specified size and dispersion
Parameters
----------
data_shape : tuple
Desiered shape of the kernel
sigma : float
Standard deviation of the kernel
norm : str... | python | def gaussian_kernel(data_shape, sigma, norm='max'):
r"""Gaussian kernel
This method produces a Gaussian kerenal of a specified size and dispersion
Parameters
----------
data_shape : tuple
Desiered shape of the kernel
sigma : float
Standard deviation of the kernel
norm : str... | [
"def",
"gaussian_kernel",
"(",
"data_shape",
",",
"sigma",
",",
"norm",
"=",
"'max'",
")",
":",
"r",
"if",
"not",
"import_astropy",
":",
"raise",
"ImportError",
"(",
"'Astropy package not found.'",
")",
"if",
"norm",
"not",
"in",
"(",
"'max'",
",",
"'sum'",
... | r"""Gaussian kernel
This method produces a Gaussian kerenal of a specified size and dispersion
Parameters
----------
data_shape : tuple
Desiered shape of the kernel
sigma : float
Standard deviation of the kernel
norm : str {'max', 'sum', 'none'}, optional
Normalisation ... | [
"r",
"Gaussian",
"kernel"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/stats.py#L23-L72 | train |
CEA-COSMIC/ModOpt | modopt/math/stats.py | mad | def mad(data):
r"""Median absolute deviation
This method calculates the median absolute deviation of the input data.
Parameters
----------
data : np.ndarray
Input data array
Returns
-------
float MAD value
Examples
--------
>>> from modopt.math.stats import mad
... | python | def mad(data):
r"""Median absolute deviation
This method calculates the median absolute deviation of the input data.
Parameters
----------
data : np.ndarray
Input data array
Returns
-------
float MAD value
Examples
--------
>>> from modopt.math.stats import mad
... | [
"def",
"mad",
"(",
"data",
")",
":",
"r",
"return",
"np",
".",
"median",
"(",
"np",
".",
"abs",
"(",
"data",
"-",
"np",
".",
"median",
"(",
"data",
")",
")",
")"
] | r"""Median absolute deviation
This method calculates the median absolute deviation of the input data.
Parameters
----------
data : np.ndarray
Input data array
Returns
-------
float MAD value
Examples
--------
>>> from modopt.math.stats import mad
>>> a = np.arange... | [
"r",
"Median",
"absolute",
"deviation"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/stats.py#L75-L106 | train |
CEA-COSMIC/ModOpt | modopt/math/stats.py | psnr | def psnr(data1, data2, method='starck', max_pix=255):
r"""Peak Signal-to-Noise Ratio
This method calculates the Peak Signal-to-Noise Ratio between an two data
sets
Parameters
----------
data1 : np.ndarray
First data set
data2 : np.ndarray
Second data set
method : str {'... | python | def psnr(data1, data2, method='starck', max_pix=255):
r"""Peak Signal-to-Noise Ratio
This method calculates the Peak Signal-to-Noise Ratio between an two data
sets
Parameters
----------
data1 : np.ndarray
First data set
data2 : np.ndarray
Second data set
method : str {'... | [
"def",
"psnr",
"(",
"data1",
",",
"data2",
",",
"method",
"=",
"'starck'",
",",
"max_pix",
"=",
"255",
")",
":",
"r",
"if",
"method",
"==",
"'starck'",
":",
"return",
"(",
"20",
"*",
"np",
".",
"log10",
"(",
"(",
"data1",
".",
"shape",
"[",
"0",
... | r"""Peak Signal-to-Noise Ratio
This method calculates the Peak Signal-to-Noise Ratio between an two data
sets
Parameters
----------
data1 : np.ndarray
First data set
data2 : np.ndarray
Second data set
method : str {'starck', 'wiki'}, optional
PSNR implementation, de... | [
"r",
"Peak",
"Signal",
"-",
"to",
"-",
"Noise",
"Ratio"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/stats.py#L133-L195 | train |
CEA-COSMIC/ModOpt | modopt/math/stats.py | psnr_stack | def psnr_stack(data1, data2, metric=np.mean, method='starck'):
r"""Peak Signa-to-Noise for stack of images
This method calculates the PSNRs for two stacks of 2D arrays.
By default the metod returns the mean value of the PSNRs, but any other
metric can be used.
Parameters
----------
data1 :... | python | def psnr_stack(data1, data2, metric=np.mean, method='starck'):
r"""Peak Signa-to-Noise for stack of images
This method calculates the PSNRs for two stacks of 2D arrays.
By default the metod returns the mean value of the PSNRs, but any other
metric can be used.
Parameters
----------
data1 :... | [
"def",
"psnr_stack",
"(",
"data1",
",",
"data2",
",",
"metric",
"=",
"np",
".",
"mean",
",",
"method",
"=",
"'starck'",
")",
":",
"r",
"if",
"data1",
".",
"ndim",
"!=",
"3",
"or",
"data2",
".",
"ndim",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
... | r"""Peak Signa-to-Noise for stack of images
This method calculates the PSNRs for two stacks of 2D arrays.
By default the metod returns the mean value of the PSNRs, but any other
metric can be used.
Parameters
----------
data1 : np.ndarray
Stack of images, 3D array
data2 : np.ndarra... | [
"r",
"Peak",
"Signa",
"-",
"to",
"-",
"Noise",
"for",
"stack",
"of",
"images"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/stats.py#L198-L239 | train |
CEA-COSMIC/ModOpt | modopt/base/transform.py | cube2map | def cube2map(data_cube, layout):
r"""Cube to Map
This method transforms the input data from a 3D cube to a 2D map with a
specified layout
Parameters
----------
data_cube : np.ndarray
Input data cube, 3D array of 2D images
Layout : tuple
2D layout of 2D images
Returns
... | python | def cube2map(data_cube, layout):
r"""Cube to Map
This method transforms the input data from a 3D cube to a 2D map with a
specified layout
Parameters
----------
data_cube : np.ndarray
Input data cube, 3D array of 2D images
Layout : tuple
2D layout of 2D images
Returns
... | [
"def",
"cube2map",
"(",
"data_cube",
",",
"layout",
")",
":",
"r",
"if",
"data_cube",
".",
"ndim",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"'The input data must have 3 dimensions.'",
")",
"if",
"data_cube",
".",
"shape",
"[",
"0",
"]",
"!=",
"np",
".",... | r"""Cube to Map
This method transforms the input data from a 3D cube to a 2D map with a
specified layout
Parameters
----------
data_cube : np.ndarray
Input data cube, 3D array of 2D images
Layout : tuple
2D layout of 2D images
Returns
-------
np.ndarray 2D map
... | [
"r",
"Cube",
"to",
"Map"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L16-L60 | train |
CEA-COSMIC/ModOpt | modopt/base/transform.py | map2cube | def map2cube(data_map, layout):
r"""Map to cube
This method transforms the input data from a 2D map with given layout to
a 3D cube
Parameters
----------
data_map : np.ndarray
Input data map, 2D array
layout : tuple
2D layout of 2D images
Returns
-------
np.ndar... | python | def map2cube(data_map, layout):
r"""Map to cube
This method transforms the input data from a 2D map with given layout to
a 3D cube
Parameters
----------
data_map : np.ndarray
Input data map, 2D array
layout : tuple
2D layout of 2D images
Returns
-------
np.ndar... | [
"def",
"map2cube",
"(",
"data_map",
",",
"layout",
")",
":",
"r",
"if",
"np",
".",
"all",
"(",
"np",
".",
"array",
"(",
"data_map",
".",
"shape",
")",
"%",
"np",
".",
"array",
"(",
"layout",
")",
")",
":",
"raise",
"ValueError",
"(",
"'The desired ... | r"""Map to cube
This method transforms the input data from a 2D map with given layout to
a 3D cube
Parameters
----------
data_map : np.ndarray
Input data map, 2D array
layout : tuple
2D layout of 2D images
Returns
-------
np.ndarray 3D cube
Raises
------
... | [
"r",
"Map",
"to",
"cube"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L63-L113 | train |
CEA-COSMIC/ModOpt | modopt/base/transform.py | map2matrix | def map2matrix(data_map, layout):
r"""Map to Matrix
This method transforms a 2D map to a 2D matrix
Parameters
----------
data_map : np.ndarray
Input data map, 2D array
layout : tuple
2D layout of 2D images
Returns
-------
np.ndarray 2D matrix
Raises
------... | python | def map2matrix(data_map, layout):
r"""Map to Matrix
This method transforms a 2D map to a 2D matrix
Parameters
----------
data_map : np.ndarray
Input data map, 2D array
layout : tuple
2D layout of 2D images
Returns
-------
np.ndarray 2D matrix
Raises
------... | [
"def",
"map2matrix",
"(",
"data_map",
",",
"layout",
")",
":",
"r",
"layout",
"=",
"np",
".",
"array",
"(",
"layout",
")",
"n_obj",
"=",
"np",
".",
"prod",
"(",
"layout",
")",
"image_shape",
"=",
"(",
"np",
".",
"array",
"(",
"data_map",
".",
"shap... | r"""Map to Matrix
This method transforms a 2D map to a 2D matrix
Parameters
----------
data_map : np.ndarray
Input data map, 2D array
layout : tuple
2D layout of 2D images
Returns
-------
np.ndarray 2D matrix
Raises
------
ValueError
For invalid la... | [
"r",
"Map",
"to",
"Matrix"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L116-L169 | train |
CEA-COSMIC/ModOpt | modopt/base/transform.py | matrix2map | def matrix2map(data_matrix, map_shape):
r"""Matrix to Map
This method transforms a 2D matrix to a 2D map
Parameters
----------
data_matrix : np.ndarray
Input data matrix, 2D array
map_shape : tuple
2D shape of the output map
Returns
-------
np.ndarray 2D map
R... | python | def matrix2map(data_matrix, map_shape):
r"""Matrix to Map
This method transforms a 2D matrix to a 2D map
Parameters
----------
data_matrix : np.ndarray
Input data matrix, 2D array
map_shape : tuple
2D shape of the output map
Returns
-------
np.ndarray 2D map
R... | [
"def",
"matrix2map",
"(",
"data_matrix",
",",
"map_shape",
")",
":",
"r",
"map_shape",
"=",
"np",
".",
"array",
"(",
"map_shape",
")",
"image_shape",
"=",
"np",
".",
"sqrt",
"(",
"data_matrix",
".",
"shape",
"[",
"0",
"]",
")",
".",
"astype",
"(",
"i... | r"""Matrix to Map
This method transforms a 2D matrix to a 2D map
Parameters
----------
data_matrix : np.ndarray
Input data matrix, 2D array
map_shape : tuple
2D shape of the output map
Returns
-------
np.ndarray 2D map
Raises
------
ValueError
For ... | [
"r",
"Matrix",
"to",
"Map"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L172-L224 | train |
CEA-COSMIC/ModOpt | modopt/base/transform.py | cube2matrix | def cube2matrix(data_cube):
r"""Cube to Matrix
This method transforms a 3D cube to a 2D matrix
Parameters
----------
data_cube : np.ndarray
Input data cube, 3D array
Returns
-------
np.ndarray 2D matrix
Examples
--------
>>> from modopt.base.transform import cube2... | python | def cube2matrix(data_cube):
r"""Cube to Matrix
This method transforms a 3D cube to a 2D matrix
Parameters
----------
data_cube : np.ndarray
Input data cube, 3D array
Returns
-------
np.ndarray 2D matrix
Examples
--------
>>> from modopt.base.transform import cube2... | [
"def",
"cube2matrix",
"(",
"data_cube",
")",
":",
"r",
"return",
"data_cube",
".",
"reshape",
"(",
"[",
"data_cube",
".",
"shape",
"[",
"0",
"]",
"]",
"+",
"[",
"np",
".",
"prod",
"(",
"data_cube",
".",
"shape",
"[",
"1",
":",
"]",
")",
"]",
")",... | r"""Cube to Matrix
This method transforms a 3D cube to a 2D matrix
Parameters
----------
data_cube : np.ndarray
Input data cube, 3D array
Returns
-------
np.ndarray 2D matrix
Examples
--------
>>> from modopt.base.transform import cube2matrix
>>> a = np.arange(16)... | [
"r",
"Cube",
"to",
"Matrix"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L227-L254 | train |
CEA-COSMIC/ModOpt | modopt/base/transform.py | matrix2cube | def matrix2cube(data_matrix, im_shape):
r"""Matrix to Cube
This method transforms a 2D matrix to a 3D cube
Parameters
----------
data_matrix : np.ndarray
Input data cube, 2D array
im_shape : tuple
2D shape of the individual images
Returns
-------
np.ndarray 3D cube... | python | def matrix2cube(data_matrix, im_shape):
r"""Matrix to Cube
This method transforms a 2D matrix to a 3D cube
Parameters
----------
data_matrix : np.ndarray
Input data cube, 2D array
im_shape : tuple
2D shape of the individual images
Returns
-------
np.ndarray 3D cube... | [
"def",
"matrix2cube",
"(",
"data_matrix",
",",
"im_shape",
")",
":",
"r",
"return",
"data_matrix",
".",
"T",
".",
"reshape",
"(",
"[",
"data_matrix",
".",
"shape",
"[",
"1",
"]",
"]",
"+",
"list",
"(",
"im_shape",
")",
")"
] | r"""Matrix to Cube
This method transforms a 2D matrix to a 3D cube
Parameters
----------
data_matrix : np.ndarray
Input data cube, 2D array
im_shape : tuple
2D shape of the individual images
Returns
-------
np.ndarray 3D cube
Examples
--------
>>> from mod... | [
"r",
"Matrix",
"to",
"Cube"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L257-L293 | train |
CEA-COSMIC/ModOpt | modopt/plot/cost_plot.py | plotCost | def plotCost(cost_list, output=None):
"""Plot cost function
Plot the final cost function
Parameters
----------
cost_list : list
List of cost function values
output : str, optional
Output file name
"""
if not import_fail:
if isinstance(output, type(None)):
... | python | def plotCost(cost_list, output=None):
"""Plot cost function
Plot the final cost function
Parameters
----------
cost_list : list
List of cost function values
output : str, optional
Output file name
"""
if not import_fail:
if isinstance(output, type(None)):
... | [
"def",
"plotCost",
"(",
"cost_list",
",",
"output",
"=",
"None",
")",
":",
"if",
"not",
"import_fail",
":",
"if",
"isinstance",
"(",
"output",
",",
"type",
"(",
"None",
")",
")",
":",
"file_name",
"=",
"'cost_function.png'",
"else",
":",
"file_name",
"="... | Plot cost function
Plot the final cost function
Parameters
----------
cost_list : list
List of cost function values
output : str, optional
Output file name | [
"Plot",
"cost",
"function"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/plot/cost_plot.py#L22-L55 | train |
CEA-COSMIC/ModOpt | modopt/signal/filter.py | Gaussian_filter | def Gaussian_filter(x, sigma, norm=True):
r"""Gaussian filter
This method implements a Gaussian filter.
Parameters
----------
x : float
Input data point
sigma : float
Standard deviation (filter scale)
norm : bool
Option to return normalised data. Default (norm=True)... | python | def Gaussian_filter(x, sigma, norm=True):
r"""Gaussian filter
This method implements a Gaussian filter.
Parameters
----------
x : float
Input data point
sigma : float
Standard deviation (filter scale)
norm : bool
Option to return normalised data. Default (norm=True)... | [
"def",
"Gaussian_filter",
"(",
"x",
",",
"sigma",
",",
"norm",
"=",
"True",
")",
":",
"r",
"x",
"=",
"check_float",
"(",
"x",
")",
"sigma",
"=",
"check_float",
"(",
"sigma",
")",
"val",
"=",
"np",
".",
"exp",
"(",
"-",
"0.5",
"*",
"(",
"x",
"/"... | r"""Gaussian filter
This method implements a Gaussian filter.
Parameters
----------
x : float
Input data point
sigma : float
Standard deviation (filter scale)
norm : bool
Option to return normalised data. Default (norm=True)
Returns
-------
float Gaussian f... | [
"r",
"Gaussian",
"filter"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/filter.py#L16-L54 | train |
CEA-COSMIC/ModOpt | modopt/signal/filter.py | mex_hat | def mex_hat(x, sigma):
r"""Mexican hat
This method implements a Mexican hat (or Ricker) wavelet.
Parameters
----------
x : float
Input data point
sigma : float
Standard deviation (filter scale)
Returns
-------
float Mexican hat filtered data point
Examples
... | python | def mex_hat(x, sigma):
r"""Mexican hat
This method implements a Mexican hat (or Ricker) wavelet.
Parameters
----------
x : float
Input data point
sigma : float
Standard deviation (filter scale)
Returns
-------
float Mexican hat filtered data point
Examples
... | [
"def",
"mex_hat",
"(",
"x",
",",
"sigma",
")",
":",
"r",
"x",
"=",
"check_float",
"(",
"x",
")",
"sigma",
"=",
"check_float",
"(",
"sigma",
")",
"xs",
"=",
"(",
"x",
"/",
"sigma",
")",
"**",
"2",
"val",
"=",
"2",
"*",
"(",
"3",
"*",
"sigma",
... | r"""Mexican hat
This method implements a Mexican hat (or Ricker) wavelet.
Parameters
----------
x : float
Input data point
sigma : float
Standard deviation (filter scale)
Returns
-------
float Mexican hat filtered data point
Examples
--------
>>> from modo... | [
"r",
"Mexican",
"hat"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/filter.py#L57-L87 | train |
CEA-COSMIC/ModOpt | modopt/signal/filter.py | mex_hat_dir | def mex_hat_dir(x, y, sigma):
r"""Directional Mexican hat
This method implements a directional Mexican hat (or Ricker) wavelet.
Parameters
----------
x : float
Input data point for Gaussian
y : float
Input data point for Mexican hat
sigma : float
Standard deviation ... | python | def mex_hat_dir(x, y, sigma):
r"""Directional Mexican hat
This method implements a directional Mexican hat (or Ricker) wavelet.
Parameters
----------
x : float
Input data point for Gaussian
y : float
Input data point for Mexican hat
sigma : float
Standard deviation ... | [
"def",
"mex_hat_dir",
"(",
"x",
",",
"y",
",",
"sigma",
")",
":",
"r",
"x",
"=",
"check_float",
"(",
"x",
")",
"sigma",
"=",
"check_float",
"(",
"sigma",
")",
"return",
"-",
"0.5",
"*",
"(",
"x",
"/",
"sigma",
")",
"**",
"2",
"*",
"mex_hat",
"(... | r"""Directional Mexican hat
This method implements a directional Mexican hat (or Ricker) wavelet.
Parameters
----------
x : float
Input data point for Gaussian
y : float
Input data point for Mexican hat
sigma : float
Standard deviation (filter scale)
Returns
--... | [
"r",
"Directional",
"Mexican",
"hat"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/filter.py#L90-L119 | train |
CEA-COSMIC/ModOpt | modopt/math/convolve.py | convolve | def convolve(data, kernel, method='scipy'):
r"""Convolve data with kernel
This method convolves the input data with a given kernel using FFT and
is the default convolution used for all routines
Parameters
----------
data : np.ndarray
Input data array, normally a 2D image
kernel : n... | python | def convolve(data, kernel, method='scipy'):
r"""Convolve data with kernel
This method convolves the input data with a given kernel using FFT and
is the default convolution used for all routines
Parameters
----------
data : np.ndarray
Input data array, normally a 2D image
kernel : n... | [
"def",
"convolve",
"(",
"data",
",",
"kernel",
",",
"method",
"=",
"'scipy'",
")",
":",
"r",
"if",
"data",
".",
"ndim",
"!=",
"kernel",
".",
"ndim",
":",
"raise",
"ValueError",
"(",
"'Data and kernel must have the same dimensions.'",
")",
"if",
"method",
"no... | r"""Convolve data with kernel
This method convolves the input data with a given kernel using FFT and
is the default convolution used for all routines
Parameters
----------
data : np.ndarray
Input data array, normally a 2D image
kernel : np.ndarray
Input kernel array, normally a... | [
"r",
"Convolve",
"data",
"with",
"kernel"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/convolve.py#L33-L103 | train |
CEA-COSMIC/ModOpt | modopt/math/convolve.py | convolve_stack | def convolve_stack(data, kernel, rot_kernel=False, method='scipy'):
r"""Convolve stack of data with stack of kernels
This method convolves the input data with a given kernel using FFT and
is the default convolution used for all routines
Parameters
----------
data : np.ndarray
Input dat... | python | def convolve_stack(data, kernel, rot_kernel=False, method='scipy'):
r"""Convolve stack of data with stack of kernels
This method convolves the input data with a given kernel using FFT and
is the default convolution used for all routines
Parameters
----------
data : np.ndarray
Input dat... | [
"def",
"convolve_stack",
"(",
"data",
",",
"kernel",
",",
"rot_kernel",
"=",
"False",
",",
"method",
"=",
"'scipy'",
")",
":",
"r",
"if",
"rot_kernel",
":",
"kernel",
"=",
"rotate_stack",
"(",
"kernel",
")",
"return",
"np",
".",
"array",
"(",
"[",
"con... | r"""Convolve stack of data with stack of kernels
This method convolves the input data with a given kernel using FFT and
is the default convolution used for all routines
Parameters
----------
data : np.ndarray
Input data array, normally a 2D image
kernel : np.ndarray
Input kerne... | [
"r",
"Convolve",
"stack",
"of",
"data",
"with",
"stack",
"of",
"kernels"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/convolve.py#L106-L161 | train |
CEA-COSMIC/ModOpt | modopt/base/types.py | check_callable | def check_callable(val, add_agrs=True):
r""" Check input object is callable
This method checks if the input operator is a callable funciton and
optionally adds support for arguments and keyword arguments if not already
provided
Parameters
----------
val : function
Callable function... | python | def check_callable(val, add_agrs=True):
r""" Check input object is callable
This method checks if the input operator is a callable funciton and
optionally adds support for arguments and keyword arguments if not already
provided
Parameters
----------
val : function
Callable function... | [
"def",
"check_callable",
"(",
"val",
",",
"add_agrs",
"=",
"True",
")",
":",
"r",
"if",
"not",
"callable",
"(",
"val",
")",
":",
"raise",
"TypeError",
"(",
"'The input object must be a callable function.'",
")",
"if",
"add_agrs",
":",
"val",
"=",
"add_args_kwa... | r""" Check input object is callable
This method checks if the input operator is a callable funciton and
optionally adds support for arguments and keyword arguments if not already
provided
Parameters
----------
val : function
Callable function
add_agrs : bool, optional
Optio... | [
"r",
"Check",
"input",
"object",
"is",
"callable"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/types.py#L16-L47 | train |
CEA-COSMIC/ModOpt | modopt/base/types.py | check_float | def check_float(val):
r"""Check if input value is a float or a np.ndarray of floats, if not
convert.
Parameters
----------
val : any
Input value
Returns
-------
float or np.ndarray of floats
Examples
--------
>>> from modopt.base.types import check_float
>>> a ... | python | def check_float(val):
r"""Check if input value is a float or a np.ndarray of floats, if not
convert.
Parameters
----------
val : any
Input value
Returns
-------
float or np.ndarray of floats
Examples
--------
>>> from modopt.base.types import check_float
>>> a ... | [
"def",
"check_float",
"(",
"val",
")",
":",
"r",
"if",
"not",
"isinstance",
"(",
"val",
",",
"(",
"int",
",",
"float",
",",
"list",
",",
"tuple",
",",
"np",
".",
"ndarray",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Invalid input type.'",
")",
"if",... | r"""Check if input value is a float or a np.ndarray of floats, if not
convert.
Parameters
----------
val : any
Input value
Returns
-------
float or np.ndarray of floats
Examples
--------
>>> from modopt.base.types import check_float
>>> a = np.arange(5)
>>> a
... | [
"r",
"Check",
"if",
"input",
"value",
"is",
"a",
"float",
"or",
"a",
"np",
".",
"ndarray",
"of",
"floats",
"if",
"not",
"convert",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/types.py#L50-L84 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.