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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
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", ")", ":", "# Make the manager aware of current simulation", "self", ".", "portfolio", "=", "portfolio", "self", ".", "perfs", "=", "perfs", "self", ".", "date", "=", "dat...
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
25,300
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: alloc, e_ret, e_risk = self.optimize( self.date, signals['buy'], signals['sell'], self._optimizer_parameters) except Exception, error: raise PortfolioOptimizationFailed( reason=error, date=self.date, data=signals) return _remove_useless_orders(alloc)
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: alloc, e_ret, e_risk = self.optimize( self.date, signals['buy'], signals['sell'], self._optimizer_parameters) except Exception, error: raise PortfolioOptimizationFailed( reason=error, date=self.date, data=signals) return _remove_useless_orders(alloc)
[ "def", "trade_signals_handler", "(", "self", ",", "signals", ")", ":", "alloc", "=", "{", "}", "if", "signals", "[", "'buy'", "]", "or", "signals", "[", "'sell'", "]", ":", "# Compute the optimal portfolio allocation,", "# Using user defined function", "try", ":",...
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
25,301
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", ")", ":", "#NOTE Panel for multiple symbols ?", "#NOTE Adj Close column name not cool (a space)", "return", "DataReader", "(", "symbol", ...
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
25,302
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.index[len(ts.index) - 1]) #delta = kwargs.get('delta', ts.index[1] - ts.index[0]) period = kwargs.get('period', None) if isinstance(period, int): pass #else: #ts = reIndexDF(ts, start=start, end=end, delta=delta) #period = 1 avg_ret = 1 for idx in range(len(ts.index)): if idx % period == 0: avg_ret *= (1 + ts[idx] + relative) return avg_ret - 1
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.index[len(ts.index) - 1]) #delta = kwargs.get('delta', ts.index[1] - ts.index[0]) period = kwargs.get('period', None) if isinstance(period, int): pass #else: #ts = reIndexDF(ts, start=start, end=end, delta=delta) #period = 1 avg_ret = 1 for idx in range(len(ts.index)): if idx % period == 0: avg_ret *= (1 + ts[idx] + relative) return avg_ret - 1
[ "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
25,303
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 : delta is the number of lines/periods provided @param end : so said @param cumulative: compute cumulative returns ''' returns_type = kwargs.get('type', 'net') cumulative = kwargs.get('cumulative', False) if returns_type == 'net': relative = 0 else: relative = 1 # gross start = kwargs.get('start', None) end = kwargs.get('end', dt.datetime.today()) #delta = kwargs.get('delta', None) period = kwargs.get('period', 1) if isinstance(start, dt.datetime): log.debug('{} / {} -1'.format(ts[end], ts[start])) return ts[end] / ts[start] - 1 + relative #elif isinstance(delta, pd.DateOffset) or isinstance(delta, dt.timedelta): #FIXME timezone problem #FIXME reIndexDF is deprecated #ts = reIndexDF(ts, delta=delta) #period = 1 rets_df = ts / ts.shift(period) - 1 + relative if cumulative: return rets_df.cumprod() return rets_df[1:]
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 : delta is the number of lines/periods provided @param end : so said @param cumulative: compute cumulative returns ''' returns_type = kwargs.get('type', 'net') cumulative = kwargs.get('cumulative', False) if returns_type == 'net': relative = 0 else: relative = 1 # gross start = kwargs.get('start', None) end = kwargs.get('end', dt.datetime.today()) #delta = kwargs.get('delta', None) period = kwargs.get('period', 1) if isinstance(start, dt.datetime): log.debug('{} / {} -1'.format(ts[end], ts[start])) return ts[end] / ts[start] - 1 + relative #elif isinstance(delta, pd.DateOffset) or isinstance(delta, dt.timedelta): #FIXME timezone problem #FIXME reIndexDF is deprecated #ts = reIndexDF(ts, delta=delta) #period = 1 rets_df = ts / ts.shift(period) - 1 + relative if cumulative: return rets_df.cumprod() return rets_df[1:]
[ "def", "returns", "(", "ts", ",", "*", "*", "kwargs", ")", ":", "returns_type", "=", "kwargs", ".", "get", "(", "'type'", ",", "'net'", ")", "cumulative", "=", "kwargs", ".", "get", "(", "'cumulative'", ",", "False", ")", "if", "returns_type", "==", ...
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 provided @param end : so said @param cumulative: compute cumulative returns
[ "Compute", "returns", "on", "the", "given", "period" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/finance.py#L151-L184
train
25,304
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
25,305
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
25,306
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.Context(args['context']) as context: # Backtest or live engine. # Registers configuration and setups data client simulation = Simulation() # Intuition building blocks modules = context['config']['modules'] # Prepare benchmark, timezone, trading calendar simulation.configure_environment( context['config']['index'][-1], context['market'].benchmark, context['market'].timezone) # Wire togetether modules and initialize them simulation.build(args['session'], modules, context['strategy']) # Build data generator # NOTE How can I use several sources ? data = {'universe': context['market'], 'index': context['config']['index']} # Add user settings data.update(context['strategy']['data']) # Load backtest and / or live module(s) if 'backtest' in modules: data['backtest'] = utils.intuition_module(modules['backtest']) if 'live' in modules: data['live'] = utils.intuition_module(modules['live']) # Run the simulation and return an intuition.core.analyzes object return simulation(datafeed.HybridDataFactory(**data), args['bot'])
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.Context(args['context']) as context: # Backtest or live engine. # Registers configuration and setups data client simulation = Simulation() # Intuition building blocks modules = context['config']['modules'] # Prepare benchmark, timezone, trading calendar simulation.configure_environment( context['config']['index'][-1], context['market'].benchmark, context['market'].timezone) # Wire togetether modules and initialize them simulation.build(args['session'], modules, context['strategy']) # Build data generator # NOTE How can I use several sources ? data = {'universe': context['market'], 'index': context['config']['index']} # Add user settings data.update(context['strategy']['data']) # Load backtest and / or live module(s) if 'backtest' in modules: data['backtest'] = utils.intuition_module(modules['backtest']) if 'live' in modules: data['live'] = utils.intuition_module(modules['live']) # Run the simulation and return an intuition.core.analyzes object return simulation(datafeed.HybridDataFactory(**data), args['bot'])
[ "def", "intuition", "(", "args", ")", ":", "# Use the provided context builder to fill:", "# - config: General behavior", "# - strategy: Modules properties", "# - market: The universe we will trade on", "with", "setup", ".", "Context", "(", "args", "[", "'context'", "]", ...
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
25,307
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
25,308
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': func, 'name': func.__name__, 'args': func.func_code.co_varnames, 'when': when })
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': func, 'name': func.__name__, 'args': func.func_code.co_varnames, 'when': when })
[ "def", "use", "(", "self", ",", "func", ",", "when", "=", "'whenever'", ")", ":", "#NOTE A middleware Object ?", "# self.use() is usually called from initialize(), so no logger yet", "print", "(", "'registering middleware {}'", ".", "format", "(", "func", ".", "__name__",...
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
25,309
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)) if isinstance(alloc, int): self.order(stock, alloc) elif isinstance(alloc, float) and \ alloc >= -1 and alloc <= 1: self.order_percent(stock, alloc) else: self.logger.warning( '{}: invalid order for {}: {})' .format(self.datetime, stock, alloc))
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)) if isinstance(alloc, int): self.order(stock, alloc) elif isinstance(alloc, float) and \ alloc >= -1 and alloc <= 1: self.order_percent(stock, alloc) else: self.logger.warning( '{}: invalid order for {}: {})' .format(self.datetime, stock, alloc))
[ "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
25,310
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(getattr, arg.split('.'), self) self.logger.debug('calling middleware event {}' .format(middleware['name'])) middleware['call'](**args)
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(getattr, arg.split('.'), self) self.logger.debug('calling middleware event {}' .format(middleware['name'])) middleware['call'](**args)
[ "def", "_call_one_middleware", "(", "self", ",", "middleware", ")", ":", "args", "=", "{", "}", "for", "arg", "in", "middleware", "[", "'args'", "]", ":", "if", "hasattr", "(", "self", ",", "arg", ")", ":", "# same as eval() but safer for arbitrary code execut...
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
25,311
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
25,312
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
25,313
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
25,314
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.quandl_key = kwargs.pop('authtoken') # Harmonization: Quandl call start trim_start if 'start' in kwargs: kwargs['trim_start'] = kwargs.pop('start') if 'end' in kwargs: kwargs['trim_end'] = kwargs.pop('end') try: data = Quandl.get(code, authtoken=self.quandl_key, **kwargs) # FIXME With a symbol not found, insert a not_found column data.index = data.index.tz_localize(pytz.utc) except Exception, error: log.error('unable to fetch {}: {}'.format(code, error)) data = pd.DataFrame() return data
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.quandl_key = kwargs.pop('authtoken') # Harmonization: Quandl call start trim_start if 'start' in kwargs: kwargs['trim_start'] = kwargs.pop('start') if 'end' in kwargs: kwargs['trim_end'] = kwargs.pop('end') try: data = Quandl.get(code, authtoken=self.quandl_key, **kwargs) # FIXME With a symbol not found, insert a not_found column data.index = data.index.tz_localize(pytz.utc) except Exception, error: log.error('unable to fetch {}: {}'.format(code, error)) data = pd.DataFrame() return data
[ "def", "fetch", "(", "self", ",", "code", ",", "*", "*", "kwargs", ")", ":", "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'"...
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
25,315
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: perfs = {} length = range(len(self.metrics[timestamp])) index = self._get_index(self.metrics[timestamp]) perf_keys = self.metrics[timestamp][0].keys() perf_keys.pop(perf_keys.index('period_label')) perfs['period'] = np.array( [pd.datetime.date(date) for date in index]) for key in perf_keys: perfs[key] = self._to_perf_array(timestamp, key, length) else: # TODO Get it from DB if it exists raise NotImplementedError() return pd.DataFrame(perfs, index=index)
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: perfs = {} length = range(len(self.metrics[timestamp])) index = self._get_index(self.metrics[timestamp]) perf_keys = self.metrics[timestamp][0].keys() perf_keys.pop(perf_keys.index('period_label')) perfs['period'] = np.array( [pd.datetime.date(date) for date in index]) for key in perf_keys: perfs[key] = self._to_perf_array(timestamp, key, length) else: # TODO Get it from DB if it exists raise NotImplementedError() return pd.DataFrame(perfs, index=index)
[ "def", "rolling_performances", "(", "self", ",", "timestamp", "=", "'one_month'", ")", ":", "# 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"...
Filters self.perfs
[ "Filters", "self", ".", "perfs" ]
cd517e6b3b315a743eb4d0d0dc294e264ab913ce
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/core/analyzes.py#L87-L109
train
25,316
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=timestamp) riskfree = np.mean(metrics['treasury_period_return']) perfs['sharpe'] = qstk_get_sharpe_ratio( metrics['algorithm_period_return'].values, risk_free=riskfree) perfs['algorithm_period_return'] = ( ((metrics['algorithm_period_return'] + 1).cumprod()) - 1)[-1] perfs['max_drawdown'] = max(metrics['max_drawdown']) perfs['algo_volatility'] = np.mean(metrics['algo_volatility']) perfs['beta'] = np.mean(metrics['beta']) perfs['alpha'] = np.mean(metrics['alpha']) perfs['benchmark_period_return'] = ( ((metrics['benchmark_period_return'] + 1).cumprod()) - 1)[-1] return perfs
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=timestamp) riskfree = np.mean(metrics['treasury_period_return']) perfs['sharpe'] = qstk_get_sharpe_ratio( metrics['algorithm_period_return'].values, risk_free=riskfree) perfs['algorithm_period_return'] = ( ((metrics['algorithm_period_return'] + 1).cumprod()) - 1)[-1] perfs['max_drawdown'] = max(metrics['max_drawdown']) perfs['algo_volatility'] = np.mean(metrics['algo_volatility']) perfs['beta'] = np.mean(metrics['beta']) perfs['alpha'] = np.mean(metrics['alpha']) perfs['benchmark_period_return'] = ( ((metrics['benchmark_period_return'] + 1).cumprod()) - 1)[-1] return perfs
[ "def", "overall_metrics", "(", "self", ",", "timestamp", "=", "'one_month'", ",", "metrics", "=", "None", ")", ":", "perfs", "=", "dict", "(", ")", "# If no rolling perfs provided, computes it", "if", "metrics", "is", "None", ":", "metrics", "=", "self", ".", ...
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
25,317
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': strategy[k] = True elif v == 'false' or v is None: strategy[k] = False else: try: if v.find('.') > 0: strategy[k] = float(v) else: strategy[k] = int(v) except ValueError: pass
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': strategy[k] = True elif v == 'false' or v is None: strategy[k] = False else: try: if v.find('.') > 0: strategy[k] = float(v) else: strategy[k] = int(v) except ValueError: pass
[ "def", "_normalize_data_types", "(", "self", ",", "strategy", ")", ":", "for", "k", ",", "v", "in", "strategy", ".", "iteritems", "(", ")", ":", "if", "not", "isinstance", "(", "v", ",", "str", ")", ":", "# There is probably nothing to do", "continue", "if...
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
25,318
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
25,319
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 self.context = TradingEnvironment( bm_symbol=benchmark, exchange_tz=timezone, load=self._get_benchmark_handler(last_trade))
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 self.context = TradingEnvironment( bm_symbol=benchmark, exchange_tz=timezone, load=self._get_benchmark_handler(last_trade))
[ "def", "configure_environment", "(", "self", ",", "last_trade", ",", "benchmark", ",", "timezone", ")", ":", "if", "last_trade", ".", "tzinfo", "is", "None", ":", "last_trade", "=", "pytz", ".", "utc", ".", "localize", "(", "last_trade", ")", "# Setup the tr...
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
25,320
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
25,321
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()) return inner
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()) return inner
[ "def", "invert_dataframe_axis", "(", "fct", ")", ":", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "df_to_invert", "=", "fct", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "pd", ".", "DataFrame", "(", "df_to_inver...
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
25,322
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 = sorted(symbols) for symbol in symbols: dot_pos = symbol.find('.') google_symbols.append( symbol[:dot_pos] if (dot_pos > 0) else symbol) data = fct(google_symbols) #NOTE Not very elegant data.columns = [s for s in symbols if s.split('.')[0] in data.columns] return data return decorator
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 = sorted(symbols) for symbol in symbols: dot_pos = symbol.find('.') google_symbols.append( symbol[:dot_pos] if (dot_pos > 0) else symbol) data = fct(google_symbols) #NOTE Not very elegant data.columns = [s for s in symbols if s.split('.')[0] in data.columns] return data return decorator
[ "def", "use_google_symbol", "(", "fct", ")", ":", "def", "decorator", "(", "symbols", ")", ":", "google_symbols", "=", "[", "]", "# If one symbol string", "if", "isinstance", "(", "symbols", ",", "str", ")", ":", "symbols", "=", "[", "symbols", "]", "symbo...
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
25,323
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().string.encode('utf-8') except: sector = '' return sector
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().string.encode('utf-8') except: sector = '' return sector
[ "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
25,324
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_sibling().string.encode('utf-8') except: industry = '' return industry
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_sibling().string.encode('utf-8') except: industry = '' return industry
[ "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
25,325
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('span', text='Fund Summary'): asset_type = 'Fund' elif symbol.find('^') == 0: asset_type = 'Index' else: pass return asset_type
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('span', text='Fund Summary'): asset_type = 'Fund' elif symbol.find('^') == 0: asset_type = 'Index' else: pass return asset_type
[ "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
25,326
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(start_date[5:7]) - 1, 'b': int(start_date[8:10]), 'c': int(start_date[0:4]), 'd': int(end_date[5:7]) - 1, 'e': int(end_date[8:10]), 'f': int(end_date[0:4]), 'g': 'd', 'ignore': '.csv', }) url = 'http://ichart.yahoo.com/table.csv?%s' % params req = Request(url) resp = urlopen(req) content = str(resp.read().decode('utf-8').strip()) daily_data = content.splitlines() hist_dict = dict() keys = daily_data[0].split(',') for day in daily_data[1:]: day_data = day.split(',') date = day_data[0] hist_dict[date] = \ {keys[1]: day_data[1], keys[2]: day_data[2], keys[3]: day_data[3], keys[4]: day_data[4], keys[5]: day_data[5], keys[6]: day_data[6]} return hist_dict
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(start_date[5:7]) - 1, 'b': int(start_date[8:10]), 'c': int(start_date[0:4]), 'd': int(end_date[5:7]) - 1, 'e': int(end_date[8:10]), 'f': int(end_date[0:4]), 'g': 'd', 'ignore': '.csv', }) url = 'http://ichart.yahoo.com/table.csv?%s' % params req = Request(url) resp = urlopen(req) content = str(resp.read().decode('utf-8').strip()) daily_data = content.splitlines() hist_dict = dict() keys = daily_data[0].split(',') for day in daily_data[1:]: day_data = day.split(',') date = day_data[0] hist_dict[date] = \ {keys[1]: day_data[1], keys[2]: day_data[2], keys[3]: day_data[3], keys[4]: day_data[4], keys[5]: day_data[5], keys[6]: day_data[6]} return hist_dict
[ "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
25,327
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(','), raw_rates)}
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(','), raw_rates)}
[ "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
25,328
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=payload) mapped_data = _fx_mapping(response.content.split('\n')[:-2]) return Series(mapped_data) if len(mapped_data) == 1 \ else DataFrame(mapped_data)
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=payload) mapped_data = _fx_mapping(response.content.split('\n')[:-2]) return Series(mapped_data) if len(mapped_data) == 1 \ else DataFrame(mapped_data)
[ "def", "query_rates", "(", "self", ",", "pairs", "=", "[", "]", ")", ":", "# If no pairs, TrueFx will use the ones given the last time", "payload", "=", "{", "'id'", ":", "self", ".", "_session", "}", "if", "pairs", ":", "payload", "[", "'c'", "]", "=", "_cl...
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
25,329
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) # Update current time now = dt.datetime.now(pytz.utc) # Since we're here, we waited a future date, so this is live trading live = True return live
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) # Update current time now = dt.datetime.now(pytz.utc) # Since we're here, we waited a future date, so this is live trading live = True return live
[ "def", "next_tick", "(", "date", ",", "interval", "=", "15", ")", ":", "# Intuition works with utc dates, conversion are made for I/O", "now", "=", "dt", ".", "datetime", ".", "now", "(", "pytz", ".", "utc", ")", "live", "=", "False", "# Sleep until we reach the g...
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
25,330
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", "(", "'.'", ")", "# Get the last field, i.e. the object name in the file", "obj", "=", "path", ".", "pop", "(", "-", "1", ")", "return", "dna", ".", "utils", ".", "d...
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
25,331
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 = EMPTY_DATES live_dates = pd.date_range( start=now, end=normalize_date_format('23h59')) else: end = normalize_date_format(end) if end < now: # Backtesting since a year before end bt_dates = pd.date_range( start=end - 360 * pd.datetools.day, end=end) live_dates = EMPTY_DATES elif end > now: # Live trading from now to end bt_dates = EMPTY_DATES live_dates = pd.date_range(start=now, end=end) else: start = normalize_date_format(start) if start < now: if not end: # Backtest for a year or until now end = start + 360 * pd.datetools.day if end > now: end = now - pd.datetools.day live_dates = EMPTY_DATES bt_dates = pd.date_range( start=start, end=end) else: end = normalize_date_format(end) if end < now: # Nothing to do, backtest from start to end live_dates = EMPTY_DATES bt_dates = pd.date_range(start=start, end=end) elif end > now: # Hybrid timeline, backtest from start to end, live # trade from now to end bt_dates = pd.date_range( start=start, end=now - pd.datetools.day) live_dates = pd.date_range(start=now, end=end) elif start > now: if not end: # Live trading from start to the end of the day bt_dates = EMPTY_DATES live_dates = pd.date_range( start=start, end=normalize_date_format('23h59')) else: # Live trading from start to end end = normalize_date_format(end) bt_dates = EMPTY_DATES live_dates = pd.date_range(start=start, end=end) return bt_dates + live_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 = EMPTY_DATES live_dates = pd.date_range( start=now, end=normalize_date_format('23h59')) else: end = normalize_date_format(end) if end < now: # Backtesting since a year before end bt_dates = pd.date_range( start=end - 360 * pd.datetools.day, end=end) live_dates = EMPTY_DATES elif end > now: # Live trading from now to end bt_dates = EMPTY_DATES live_dates = pd.date_range(start=now, end=end) else: start = normalize_date_format(start) if start < now: if not end: # Backtest for a year or until now end = start + 360 * pd.datetools.day if end > now: end = now - pd.datetools.day live_dates = EMPTY_DATES bt_dates = pd.date_range( start=start, end=end) else: end = normalize_date_format(end) if end < now: # Nothing to do, backtest from start to end live_dates = EMPTY_DATES bt_dates = pd.date_range(start=start, end=end) elif end > now: # Hybrid timeline, backtest from start to end, live # trade from now to end bt_dates = pd.date_range( start=start, end=now - pd.datetools.day) live_dates = pd.date_range(start=now, end=end) elif start > now: if not end: # Live trading from start to the end of the day bt_dates = EMPTY_DATES live_dates = pd.date_range( start=start, end=normalize_date_format('23h59')) else: # Live trading from start to end end = normalize_date_format(end) bt_dates = EMPTY_DATES live_dates = pd.date_range(start=start, end=end) return bt_dates + live_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
25,332
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", ")", "# Divisible by 4 and,...
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
25,333
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 Month as an integer. day : int Day as an integer. Returns ------- jd1, jd2: 2-element tuple of floats When added together, the numbers give the Julian date for the given Gregorian calendar date. The first number is always MJD_0 i.e., 2451545.5. So the second is the MJD. Examples -------- >>> gcal2jd(2000,1,1) (2400000.5, 51544.0) >>> 2400000.5 + 51544.0 + 0.5 2451545.0 >>> year = [-4699, -2114, -1050, -123, -1, 0, 1, 123, 1678.0, 2000, ....: 2012, 2245] >>> month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> day = [1, 12, 23, 14, 25, 16, 27, 8, 9, 10, 11, 31] >>> x = [gcal2jd(y, m, d) for y, m, d in zip(year, month, day)] >>> for i in x: print i (2400000.5, -2395215.0) (2400000.5, -1451021.0) (2400000.5, -1062364.0) (2400000.5, -723762.0) (2400000.5, -679162.0) (2400000.5, -678774.0) (2400000.5, -678368.0) (2400000.5, -633797.0) (2400000.5, -65812.0) (2400000.5, 51827.0) (2400000.5, 56242.0) (2400000.5, 141393.0) Negative months and days are valid. For example, 2000/-2/-4 => 1999/+12-2/-4 => 1999/10/-4 => 1999/9/30-4 => 1999/9/26. >>> gcal2jd(2000, -2, -4) (2400000.5, 51447.0) >>> gcal2jd(1999, 9, 26) (2400000.5, 51447.0) >>> gcal2jd(2000, 2, -1) (2400000.5, 51573.0) >>> gcal2jd(2000, 1, 30) (2400000.5, 51573.0) >>> gcal2jd(2000, 3, -1) (2400000.5, 51602.0) >>> gcal2jd(2000, 2, 28) (2400000.5, 51602.0) Month 0 becomes previous month. >>> gcal2jd(2000, 0, 1) (2400000.5, 51513.0) >>> gcal2jd(1999, 12, 1) (2400000.5, 51513.0) Day number 0 becomes last day of previous month. >>> gcal2jd(2000, 3, 0) (2400000.5, 51603.0) >>> gcal2jd(2000, 2, 29) (2400000.5, 51603.0) If `day` is greater than the number of days in `month`, then it gets carried over to the next month. >>> gcal2jd(2000,2,30) (2400000.5, 51604.0) >>> gcal2jd(2000,3,1) (2400000.5, 51604.0) >>> gcal2jd(2001,2,30) (2400000.5, 51970.0) >>> gcal2jd(2001,3,2) (2400000.5, 51970.0) Notes ----- The returned Julian date is for mid-night of the given date. To find the Julian date for any time of the day, simply add time as a fraction of a day. For example Julian date for mid-day can be obtained by adding 0.5 to either the first part or the second part. The latter is preferable, since it will give the MJD for the date and time. BC dates should be given as -(BC - 1) where BC is the year. For example 1 BC == 0, 2 BC == -1, and so on. Negative numbers can be used for `month` and `day`. For example 2000, -1, 1 is the same as 1999, 11, 1. The Julian dates are proleptic Julian dates, i.e., values are returned without considering if Gregorian dates are valid for the given date. The input values are truncated to integers. """ year = int(year) month = int(month) day = int(day) a = ipart((month - 14) / 12.0) jd = ipart((1461 * (year + 4800 + a)) / 4.0) jd += ipart((367 * (month - 2 - 12 * a)) / 12.0) x = ipart((year + 4900 + a) / 100.0) jd -= ipart((3 * x) / 4.0) jd += day - 2432075.5 # was 32075; add 2400000.5 jd -= 0.5 # 0 hours; above JD is for midday, switch to midnight. return MJD_0, jd
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 Month as an integer. day : int Day as an integer. Returns ------- jd1, jd2: 2-element tuple of floats When added together, the numbers give the Julian date for the given Gregorian calendar date. The first number is always MJD_0 i.e., 2451545.5. So the second is the MJD. Examples -------- >>> gcal2jd(2000,1,1) (2400000.5, 51544.0) >>> 2400000.5 + 51544.0 + 0.5 2451545.0 >>> year = [-4699, -2114, -1050, -123, -1, 0, 1, 123, 1678.0, 2000, ....: 2012, 2245] >>> month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> day = [1, 12, 23, 14, 25, 16, 27, 8, 9, 10, 11, 31] >>> x = [gcal2jd(y, m, d) for y, m, d in zip(year, month, day)] >>> for i in x: print i (2400000.5, -2395215.0) (2400000.5, -1451021.0) (2400000.5, -1062364.0) (2400000.5, -723762.0) (2400000.5, -679162.0) (2400000.5, -678774.0) (2400000.5, -678368.0) (2400000.5, -633797.0) (2400000.5, -65812.0) (2400000.5, 51827.0) (2400000.5, 56242.0) (2400000.5, 141393.0) Negative months and days are valid. For example, 2000/-2/-4 => 1999/+12-2/-4 => 1999/10/-4 => 1999/9/30-4 => 1999/9/26. >>> gcal2jd(2000, -2, -4) (2400000.5, 51447.0) >>> gcal2jd(1999, 9, 26) (2400000.5, 51447.0) >>> gcal2jd(2000, 2, -1) (2400000.5, 51573.0) >>> gcal2jd(2000, 1, 30) (2400000.5, 51573.0) >>> gcal2jd(2000, 3, -1) (2400000.5, 51602.0) >>> gcal2jd(2000, 2, 28) (2400000.5, 51602.0) Month 0 becomes previous month. >>> gcal2jd(2000, 0, 1) (2400000.5, 51513.0) >>> gcal2jd(1999, 12, 1) (2400000.5, 51513.0) Day number 0 becomes last day of previous month. >>> gcal2jd(2000, 3, 0) (2400000.5, 51603.0) >>> gcal2jd(2000, 2, 29) (2400000.5, 51603.0) If `day` is greater than the number of days in `month`, then it gets carried over to the next month. >>> gcal2jd(2000,2,30) (2400000.5, 51604.0) >>> gcal2jd(2000,3,1) (2400000.5, 51604.0) >>> gcal2jd(2001,2,30) (2400000.5, 51970.0) >>> gcal2jd(2001,3,2) (2400000.5, 51970.0) Notes ----- The returned Julian date is for mid-night of the given date. To find the Julian date for any time of the day, simply add time as a fraction of a day. For example Julian date for mid-day can be obtained by adding 0.5 to either the first part or the second part. The latter is preferable, since it will give the MJD for the date and time. BC dates should be given as -(BC - 1) where BC is the year. For example 1 BC == 0, 2 BC == -1, and so on. Negative numbers can be used for `month` and `day`. For example 2000, -1, 1 is the same as 1999, 11, 1. The Julian dates are proleptic Julian dates, i.e., values are returned without considering if Gregorian dates are valid for the given date. The input values are truncated to integers. """ year = int(year) month = int(month) day = int(day) a = ipart((month - 14) / 12.0) jd = ipart((1461 * (year + 4800 + a)) / 4.0) jd += ipart((367 * (month - 2 - 12 * a)) / 12.0) x = ipart((year + 4900 + a) / 100.0) jd -= ipart((3 * x) / 4.0) jd += day - 2432075.5 # was 32075; add 2400000.5 jd -= 0.5 # 0 hours; above JD is for midday, switch to midnight. return MJD_0, jd
[ "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 Day as an integer. Returns ------- jd1, jd2: 2-element tuple of floats When added together, the numbers give the Julian date for the given Gregorian calendar date. The first number is always MJD_0 i.e., 2451545.5. So the second is the MJD. Examples -------- >>> gcal2jd(2000,1,1) (2400000.5, 51544.0) >>> 2400000.5 + 51544.0 + 0.5 2451545.0 >>> year = [-4699, -2114, -1050, -123, -1, 0, 1, 123, 1678.0, 2000, ....: 2012, 2245] >>> month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> day = [1, 12, 23, 14, 25, 16, 27, 8, 9, 10, 11, 31] >>> x = [gcal2jd(y, m, d) for y, m, d in zip(year, month, day)] >>> for i in x: print i (2400000.5, -2395215.0) (2400000.5, -1451021.0) (2400000.5, -1062364.0) (2400000.5, -723762.0) (2400000.5, -679162.0) (2400000.5, -678774.0) (2400000.5, -678368.0) (2400000.5, -633797.0) (2400000.5, -65812.0) (2400000.5, 51827.0) (2400000.5, 56242.0) (2400000.5, 141393.0) Negative months and days are valid. For example, 2000/-2/-4 => 1999/+12-2/-4 => 1999/10/-4 => 1999/9/30-4 => 1999/9/26. >>> gcal2jd(2000, -2, -4) (2400000.5, 51447.0) >>> gcal2jd(1999, 9, 26) (2400000.5, 51447.0) >>> gcal2jd(2000, 2, -1) (2400000.5, 51573.0) >>> gcal2jd(2000, 1, 30) (2400000.5, 51573.0) >>> gcal2jd(2000, 3, -1) (2400000.5, 51602.0) >>> gcal2jd(2000, 2, 28) (2400000.5, 51602.0) Month 0 becomes previous month. >>> gcal2jd(2000, 0, 1) (2400000.5, 51513.0) >>> gcal2jd(1999, 12, 1) (2400000.5, 51513.0) Day number 0 becomes last day of previous month. >>> gcal2jd(2000, 3, 0) (2400000.5, 51603.0) >>> gcal2jd(2000, 2, 29) (2400000.5, 51603.0) If `day` is greater than the number of days in `month`, then it gets carried over to the next month. >>> gcal2jd(2000,2,30) (2400000.5, 51604.0) >>> gcal2jd(2000,3,1) (2400000.5, 51604.0) >>> gcal2jd(2001,2,30) (2400000.5, 51970.0) >>> gcal2jd(2001,3,2) (2400000.5, 51970.0) Notes ----- The returned Julian date is for mid-night of the given date. To find the Julian date for any time of the day, simply add time as a fraction of a day. For example Julian date for mid-day can be obtained by adding 0.5 to either the first part or the second part. The latter is preferable, since it will give the MJD for the date and time. BC dates should be given as -(BC - 1) where BC is the year. For example 1 BC == 0, 2 BC == -1, and so on. Negative numbers can be used for `month` and `day`. For example 2000, -1, 1 is the same as 1999, 11, 1. The Julian dates are proleptic Julian dates, i.e., values are returned without considering if Gregorian dates are valid for the given date. The input values are truncated to integers.
[ "Gregorian", "calendar", "date", "to", "Julian", "date", "." ]
1e65e9be80a9d38b5f9001161b49c52a0a6f05e6
https://github.com/phn/jdcal/blob/1e65e9be80a9d38b5f9001161b49c52a0a6f05e6/jdcal.py#L67-L195
train
25,334
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 as the given Julian date. For example `jd1` can be the zero point of MJD (MJD_0) and `jd2` can be the MJD of the date and time. But any combination will work. Returns ------- y, m, d, f : int, int, int, float Four element tuple containing year, month, day and the fractional part of the day in the Gregorian calendar. The first three are integers, and the last part is a float. Examples -------- >>> jd2gcal(*gcal2jd(2000,1,1)) (2000, 1, 1, 0.0) >>> jd2gcal(*gcal2jd(1950,1,1)) (1950, 1, 1, 0.0) Out of range months and days are carried over to the next/previous year or next/previous month. See gcal2jd for more examples. >>> jd2gcal(*gcal2jd(1999,10,12)) (1999, 10, 12, 0.0) >>> jd2gcal(*gcal2jd(2000,2,30)) (2000, 3, 1, 0.0) >>> jd2gcal(*gcal2jd(-1999,10,12)) (-1999, 10, 12, 0.0) >>> jd2gcal(*gcal2jd(2000, -2, -4)) (1999, 9, 26, 0.0) >>> gcal2jd(2000,1,1) (2400000.5, 51544.0) >>> jd2gcal(2400000.5, 51544.0) (2000, 1, 1, 0.0) >>> jd2gcal(2400000.5, 51544.5) (2000, 1, 1, 0.5) >>> jd2gcal(2400000.5, 51544.245) (2000, 1, 1, 0.24500000000261934) >>> jd2gcal(2400000.5, 51544.1) (2000, 1, 1, 0.099999999998544808) >>> jd2gcal(2400000.5, 51544.75) (2000, 1, 1, 0.75) Notes ----- The last element of the tuple is the same as (hh + mm / 60.0 + ss / 3600.0) / 24.0 where hh, mm, and ss are the hour, minute and second of the day. See Also -------- gcal2jd """ 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 + jd2_f # Set JD to noon of the current date. Fractional part is the # fraction from midnight of the current date. if -0.5 < f < 0.5: f += 0.5 elif f >= 0.5: jd_i += 1 f -= 0.5 elif f <= -0.5: jd_i -= 1 f += 1.5 l = jd_i + 68569 n = ipart((4 * l) / 146097.0) l -= ipart(((146097 * n) + 3) / 4.0) i = ipart((4000 * (l + 1)) / 1461001) l -= ipart((1461 * i) / 4.0) - 31 j = ipart((80 * l) / 2447.0) day = l - ipart((2447 * j) / 80.0) l = ipart(j / 11.0) month = j + 2 - (12 * l) year = 100 * (n - 49) + i + l return int(year), int(month), int(day), f
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 as the given Julian date. For example `jd1` can be the zero point of MJD (MJD_0) and `jd2` can be the MJD of the date and time. But any combination will work. Returns ------- y, m, d, f : int, int, int, float Four element tuple containing year, month, day and the fractional part of the day in the Gregorian calendar. The first three are integers, and the last part is a float. Examples -------- >>> jd2gcal(*gcal2jd(2000,1,1)) (2000, 1, 1, 0.0) >>> jd2gcal(*gcal2jd(1950,1,1)) (1950, 1, 1, 0.0) Out of range months and days are carried over to the next/previous year or next/previous month. See gcal2jd for more examples. >>> jd2gcal(*gcal2jd(1999,10,12)) (1999, 10, 12, 0.0) >>> jd2gcal(*gcal2jd(2000,2,30)) (2000, 3, 1, 0.0) >>> jd2gcal(*gcal2jd(-1999,10,12)) (-1999, 10, 12, 0.0) >>> jd2gcal(*gcal2jd(2000, -2, -4)) (1999, 9, 26, 0.0) >>> gcal2jd(2000,1,1) (2400000.5, 51544.0) >>> jd2gcal(2400000.5, 51544.0) (2000, 1, 1, 0.0) >>> jd2gcal(2400000.5, 51544.5) (2000, 1, 1, 0.5) >>> jd2gcal(2400000.5, 51544.245) (2000, 1, 1, 0.24500000000261934) >>> jd2gcal(2400000.5, 51544.1) (2000, 1, 1, 0.099999999998544808) >>> jd2gcal(2400000.5, 51544.75) (2000, 1, 1, 0.75) Notes ----- The last element of the tuple is the same as (hh + mm / 60.0 + ss / 3600.0) / 24.0 where hh, mm, and ss are the hour, minute and second of the day. See Also -------- gcal2jd """ 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 + jd2_f # Set JD to noon of the current date. Fractional part is the # fraction from midnight of the current date. if -0.5 < f < 0.5: f += 0.5 elif f >= 0.5: jd_i += 1 f -= 0.5 elif f <= -0.5: jd_i -= 1 f += 1.5 l = jd_i + 68569 n = ipart((4 * l) / 146097.0) l -= ipart(((146097 * n) + 3) / 4.0) i = ipart((4000 * (l + 1)) / 1461001) l -= ipart((1461 * i) / 4.0) - 31 j = ipart((80 * l) / 2447.0) day = l - ipart((2447 * j) / 80.0) l = ipart(j / 11.0) month = j + 2 - (12 * l) year = 100 * (n - 49) + i + l return int(year), int(month), int(day), f
[ "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 example `jd1` can be the zero point of MJD (MJD_0) and `jd2` can be the MJD of the date and time. But any combination will work. Returns ------- y, m, d, f : int, int, int, float Four element tuple containing year, month, day and the fractional part of the day in the Gregorian calendar. The first three are integers, and the last part is a float. Examples -------- >>> jd2gcal(*gcal2jd(2000,1,1)) (2000, 1, 1, 0.0) >>> jd2gcal(*gcal2jd(1950,1,1)) (1950, 1, 1, 0.0) Out of range months and days are carried over to the next/previous year or next/previous month. See gcal2jd for more examples. >>> jd2gcal(*gcal2jd(1999,10,12)) (1999, 10, 12, 0.0) >>> jd2gcal(*gcal2jd(2000,2,30)) (2000, 3, 1, 0.0) >>> jd2gcal(*gcal2jd(-1999,10,12)) (-1999, 10, 12, 0.0) >>> jd2gcal(*gcal2jd(2000, -2, -4)) (1999, 9, 26, 0.0) >>> gcal2jd(2000,1,1) (2400000.5, 51544.0) >>> jd2gcal(2400000.5, 51544.0) (2000, 1, 1, 0.0) >>> jd2gcal(2400000.5, 51544.5) (2000, 1, 1, 0.5) >>> jd2gcal(2400000.5, 51544.245) (2000, 1, 1, 0.24500000000261934) >>> jd2gcal(2400000.5, 51544.1) (2000, 1, 1, 0.099999999998544808) >>> jd2gcal(2400000.5, 51544.75) (2000, 1, 1, 0.75) Notes ----- The last element of the tuple is the same as (hh + mm / 60.0 + ss / 3600.0) / 24.0 where hh, mm, and ss are the hour, minute and second of the day. See Also -------- gcal2jd
[ "Julian", "date", "to", "Gregorian", "calendar", "date", "and", "time", "of", "day", "." ]
1e65e9be80a9d38b5f9001161b49c52a0a6f05e6
https://github.com/phn/jdcal/blob/1e65e9be80a9d38b5f9001161b49c52a0a6f05e6/jdcal.py#L198-L296
train
25,335
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 as an integer. day : int Day as an integer. Returns ------- jd1, jd2: 2-element tuple of floats When added together, the numbers give the Julian date for the given Julian calendar date. The first number is always MJD_0 i.e., 2451545.5. So the second is the MJD. Examples -------- >>> jcal2jd(2000, 1, 1) (2400000.5, 51557.0) >>> year = [-4699, -2114, -1050, -123, -1, 0, 1, 123, 1678, 2000, ...: 2012, 2245] >>> month = [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12] >>> day = [1, 12, 23, 14, 25, 16, 27, 8, 9, 10, 11, 31] >>> x = [jcal2jd(y, m, d) for y, m, d in zip(year, month, day)] >>> for i in x: print i (2400000.5, -2395252.0) (2400000.5, -1451039.0) (2400000.5, -1062374.0) (2400000.5, -723765.0) (2400000.5, -679164.0) (2400000.5, -678776.0) (2400000.5, -678370.0) (2400000.5, -633798.0) (2400000.5, -65772.0) (2400000.5, 51871.0) (2400000.5, 56285.0) Notes ----- Unlike `gcal2jd`, negative months and days can result in incorrect Julian dates. """ year = int(year) month = int(month) day = int(day) jd = 367 * year x = ipart((month - 9) / 7.0) jd -= ipart((7 * (year + 5001 + x)) / 4.0) jd += ipart((275 * month) / 9.0) jd += day jd += 1729777 - 2400000.5 # Return 240000.5 as first part of JD. jd -= 0.5 # Convert midday to midnight. return MJD_0, jd
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 as an integer. day : int Day as an integer. Returns ------- jd1, jd2: 2-element tuple of floats When added together, the numbers give the Julian date for the given Julian calendar date. The first number is always MJD_0 i.e., 2451545.5. So the second is the MJD. Examples -------- >>> jcal2jd(2000, 1, 1) (2400000.5, 51557.0) >>> year = [-4699, -2114, -1050, -123, -1, 0, 1, 123, 1678, 2000, ...: 2012, 2245] >>> month = [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12] >>> day = [1, 12, 23, 14, 25, 16, 27, 8, 9, 10, 11, 31] >>> x = [jcal2jd(y, m, d) for y, m, d in zip(year, month, day)] >>> for i in x: print i (2400000.5, -2395252.0) (2400000.5, -1451039.0) (2400000.5, -1062374.0) (2400000.5, -723765.0) (2400000.5, -679164.0) (2400000.5, -678776.0) (2400000.5, -678370.0) (2400000.5, -633798.0) (2400000.5, -65772.0) (2400000.5, 51871.0) (2400000.5, 56285.0) Notes ----- Unlike `gcal2jd`, negative months and days can result in incorrect Julian dates. """ year = int(year) month = int(month) day = int(day) jd = 367 * year x = ipart((month - 9) / 7.0) jd -= ipart((7 * (year + 5001 + x)) / 4.0) jd += ipart((275 * month) / 9.0) jd += day jd += 1729777 - 2400000.5 # Return 240000.5 as first part of JD. jd -= 0.5 # Convert midday to midnight. return MJD_0, jd
[ "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 Day as an integer. Returns ------- jd1, jd2: 2-element tuple of floats When added together, the numbers give the Julian date for the given Julian calendar date. The first number is always MJD_0 i.e., 2451545.5. So the second is the MJD. Examples -------- >>> jcal2jd(2000, 1, 1) (2400000.5, 51557.0) >>> year = [-4699, -2114, -1050, -123, -1, 0, 1, 123, 1678, 2000, ...: 2012, 2245] >>> month = [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12] >>> day = [1, 12, 23, 14, 25, 16, 27, 8, 9, 10, 11, 31] >>> x = [jcal2jd(y, m, d) for y, m, d in zip(year, month, day)] >>> for i in x: print i (2400000.5, -2395252.0) (2400000.5, -1451039.0) (2400000.5, -1062374.0) (2400000.5, -723765.0) (2400000.5, -679164.0) (2400000.5, -678776.0) (2400000.5, -678370.0) (2400000.5, -633798.0) (2400000.5, -65772.0) (2400000.5, 51871.0) (2400000.5, 56285.0) Notes ----- Unlike `gcal2jd`, negative months and days can result in incorrect Julian dates.
[ "Julian", "calendar", "date", "to", "Julian", "date", "." ]
1e65e9be80a9d38b5f9001161b49c52a0a6f05e6
https://github.com/phn/jdcal/blob/1e65e9be80a9d38b5f9001161b49c52a0a6f05e6/jdcal.py#L299-L363
train
25,336
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 wrapper(*args, **kwargs): props = argspec(func) # if 'args' not in props: if isinstance(props[1], type(None)): args = args[:len(props[0])] if ((not isinstance(props[2], type(None))) or (not isinstance(props[3], type(None)))): return func(*args, **kwargs) else: return func(*args) return wrapper
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 wrapper(*args, **kwargs): props = argspec(func) # if 'args' not in props: if isinstance(props[1], type(None)): args = args[:len(props[0])] if ((not isinstance(props[2], type(None))) or (not isinstance(props[3], type(None)))): return func(*args, **kwargs) else: return func(*args) return wrapper
[ "def", "add_args_kwargs", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "props", "=", "argspec", "(", "func", ")", "# if 'args' not in props:", "if", "isinstance", "(", "pr...
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
25,337
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('Preparing log file:', filename) # Capture warnings. logging.captureWarnings(True) # Set output format. formatter = logging.Formatter(fmt='%(asctime)s %(message)s', datefmt='%d/%m/%Y %H:%M:%S') # Create file handler. fh = logging.FileHandler(filename=filename, mode='w') fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) # Create log. log = logging.getLogger(filename) log.setLevel(logging.DEBUG) log.addHandler(fh) # Send opening message. log.info('The log file has been set-up.') return log
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('Preparing log file:', filename) # Capture warnings. logging.captureWarnings(True) # Set output format. formatter = logging.Formatter(fmt='%(asctime)s %(message)s', datefmt='%d/%m/%Y %H:%M:%S') # Create file handler. fh = logging.FileHandler(filename=filename, mode='w') fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) # Create log. log = logging.getLogger(filename) log.setLevel(logging.DEBUG) log.addHandler(fh) # Send opening message. log.info('The log file has been set-up.') return log
[ "def", "set_up_log", "(", "filename", ",", "verbose", "=", "True", ")", ":", "# Add file extension.", "filename", "+=", "'.log'", "if", "verbose", ":", "print", "(", "'Preparing log file:'", ",", "filename", ")", "# Capture warnings.", "logging", ".", "captureWarn...
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
25,338
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 emitted. """ self._is_allowed_signal(signal) self._add_observer(signal, observer)
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 emitted. """ self._is_allowed_signal(signal) self._add_observer(signal, observer)
[ "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
25,339
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. """ self._is_allowed_event(signal) self._remove_observer(signal, observer)
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. """ self._is_allowed_event(signal) self._remove_observer(signal, observer)
[ "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
25,340
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 False if a notification is in progress, otherwise True. """ # Check if a notification if in progress if self._locked: return False # Set the lock self._locked = True # Create a signal object signal_to_be_notified = SignalObject() setattr(signal_to_be_notified, "object", self) setattr(signal_to_be_notified, "signal", signal) for name, value in kwargs.items(): setattr(signal_to_be_notified, name, value) # Notify all the observers for observer in self._observers[signal]: observer(signal_to_be_notified) # Unlock the notification process self._locked = False
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 False if a notification is in progress, otherwise True. """ # Check if a notification if in progress if self._locked: return False # Set the lock self._locked = True # Create a signal object signal_to_be_notified = SignalObject() setattr(signal_to_be_notified, "object", self) setattr(signal_to_be_notified, "signal", signal) for name, value in kwargs.items(): setattr(signal_to_be_notified, name, value) # Notify all the observers for observer in self._observers[signal]: observer(signal_to_be_notified) # Unlock the notification process self._locked = False
[ "def", "notify_observers", "(", "self", ",", "signal", ",", "*", "*", "kwargs", ")", ":", "# Check if a notification if in progress", "if", "self", ".", "_locked", ":", "return", "False", "# Set the lock", "self", ".", "_locked", "=", "True", "# Create a signal ob...
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, otherwise True.
[ "Notify", "observers", "of", "a", "given", "signal", "." ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/observable.py#L85-L118
train
25,341
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}' is not allowed for '{1}'.".format( signal, type(self)))
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}' is not allowed for '{1}'.".format( signal, type(self)))
[ "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
25,342
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]: self._observers[signal].append(observer)
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]: self._observers[signal].append(observer)
[ "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
25,343
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]: self._observers[signal].remove(observer)
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]: self._observers[signal].remove(observer)
[ "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
25,344
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() current_mean = np.array(self.list_cv_values[mid_idx:]).mean() normalize_residual_metrics = (np.abs(old_mean - current_mean) / np.abs(old_mean)) self.converge_flag = normalize_residual_metrics < self.eps
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() current_mean = np.array(self.list_cv_values[mid_idx:]).mean() normalize_residual_metrics = (np.abs(old_mean - current_mean) / np.abs(old_mean)) self.converge_flag = normalize_residual_metrics < self.eps
[ "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
25,345
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_cv_values}
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_cv_values}
[ "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
25,346
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 cost value to the test list self._test_list.append(self.cost) # Check if enough cost values have been collected if len(self._test_list) == self._test_range: # The mean of the first half of the test list t1 = np.mean(self._test_list[len(self._test_list) // 2:], axis=0) # The mean of the second half of the test list t2 = np.mean(self._test_list[:len(self._test_list) // 2], axis=0) # Calculate the change across the test list if not np.around(t1, decimals=16): cost_diff = 0.0 else: cost_diff = (np.linalg.norm(t1 - t2) / np.linalg.norm(t1)) # Reset the test list self._test_list = [] if self._verbose: print(' - CONVERGENCE TEST - ') print(' - CHANGE IN COST:', cost_diff) print('') # Check for convergence return cost_diff <= self._tolerance else: return False
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 cost value to the test list self._test_list.append(self.cost) # Check if enough cost values have been collected if len(self._test_list) == self._test_range: # The mean of the first half of the test list t1 = np.mean(self._test_list[len(self._test_list) // 2:], axis=0) # The mean of the second half of the test list t2 = np.mean(self._test_list[:len(self._test_list) // 2], axis=0) # Calculate the change across the test list if not np.around(t1, decimals=16): cost_diff = 0.0 else: cost_diff = (np.linalg.norm(t1 - t2) / np.linalg.norm(t1)) # Reset the test list self._test_list = [] if self._verbose: print(' - CONVERGENCE TEST - ') print(' - CHANGE IN COST:', cost_diff) print('') # Check for convergence return cost_diff <= self._tolerance else: return False
[ "def", "_check_cost", "(", "self", ")", ":", "# Add current cost value to the test list", "self", ".", "_test_list", ".", "append", "(", "self", ".", "cost", ")", "# Check if enough cost values have been collected", "if", "len", "(", "self", ".", "_test_list", ")", ...
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
25,347
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
25,348
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_interval: test_result = False else: if self._verbose: print(' - ITERATION:', self._iteration) # Calculate the current cost self.cost = self._calc_cost(verbose=self._verbose, *args, **kwargs) self._cost_list.append(self.cost) if self._verbose: print(' - COST:', self.cost) print('') # Test for convergence test_result = self._check_cost() # Update the current iteration number self._iteration += 1 return test_result
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_interval: test_result = False else: if self._verbose: print(' - ITERATION:', self._iteration) # Calculate the current cost self.cost = self._calc_cost(verbose=self._verbose, *args, **kwargs) self._cost_list.append(self.cost) if self._verbose: print(' - COST:', self.cost) print('') # Test for convergence test_result = self._check_cost() # Update the current iteration number self._iteration += 1 return test_result
[ "def", "get_cost", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Check if the cost should be calculated", "if", "self", ".", "_iteration", "%", "self", ".", "_cost_interval", ":", "test_result", "=", "False", "else", ":", "if", "self",...
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
25,349
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 added ('gauss' only) noise_type : str {'gauss', 'poisson'} Type of noise to be added (default is 'gauss') Returns ------- np.ndarray input data with added noise Raises ------ ValueError If `noise_type` is not 'gauss' or 'poisson' ValueError If number of `sigma` values does not match the first dimension of the input data Examples -------- >>> import numpy as np >>> from modopt.signal.noise import add_noise >>> x = np.arange(9).reshape(3, 3).astype(float) >>> x array([[ 0., 1., 2.], [ 3., 4., 5.], [ 6., 7., 8.]]) >>> np.random.seed(1) >>> add_noise(x, noise_type='poisson') array([[ 0., 2., 2.], [ 4., 5., 10.], [ 11., 15., 18.]]) >>> import numpy as np >>> from modopt.signal.noise import add_noise >>> x = np.zeros(5) >>> x array([ 0., 0., 0., 0., 0.]) >>> np.random.seed(1) >>> add_noise(x, sigma=2.0) array([ 3.24869073, -1.22351283, -1.0563435 , -2.14593724, 1.73081526]) """ data = np.array(data) if noise_type not in ('gauss', 'poisson'): raise ValueError('Invalid noise type. Options are "gauss" or' '"poisson"') if isinstance(sigma, (list, tuple, np.ndarray)): if len(sigma) != data.shape[0]: raise ValueError('Number of sigma values must match first ' 'dimension of input data') if noise_type is 'gauss': random = np.random.randn(*data.shape) elif noise_type is 'poisson': random = np.random.poisson(np.abs(data)) if isinstance(sigma, (int, float)): return data + sigma * random else: return data + np.array([s * r for s, r in zip(sigma, random)])
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 added ('gauss' only) noise_type : str {'gauss', 'poisson'} Type of noise to be added (default is 'gauss') Returns ------- np.ndarray input data with added noise Raises ------ ValueError If `noise_type` is not 'gauss' or 'poisson' ValueError If number of `sigma` values does not match the first dimension of the input data Examples -------- >>> import numpy as np >>> from modopt.signal.noise import add_noise >>> x = np.arange(9).reshape(3, 3).astype(float) >>> x array([[ 0., 1., 2.], [ 3., 4., 5.], [ 6., 7., 8.]]) >>> np.random.seed(1) >>> add_noise(x, noise_type='poisson') array([[ 0., 2., 2.], [ 4., 5., 10.], [ 11., 15., 18.]]) >>> import numpy as np >>> from modopt.signal.noise import add_noise >>> x = np.zeros(5) >>> x array([ 0., 0., 0., 0., 0.]) >>> np.random.seed(1) >>> add_noise(x, sigma=2.0) array([ 3.24869073, -1.22351283, -1.0563435 , -2.14593724, 1.73081526]) """ data = np.array(data) if noise_type not in ('gauss', 'poisson'): raise ValueError('Invalid noise type. Options are "gauss" or' '"poisson"') if isinstance(sigma, (list, tuple, np.ndarray)): if len(sigma) != data.shape[0]: raise ValueError('Number of sigma values must match first ' 'dimension of input data') if noise_type is 'gauss': random = np.random.randn(*data.shape) elif noise_type is 'poisson': random = np.random.poisson(np.abs(data)) if isinstance(sigma, (int, float)): return data + sigma * random else: return data + np.array([s * r for s, r in zip(sigma, random)])
[ "def", "add_noise", "(", "data", ",", "sigma", "=", "1.0", ",", "noise_type", "=", "'gauss'", ")", ":", "data", "=", "np", ".", "array", "(", "data", ")", "if", "noise_type", "not", "in", "(", "'gauss'", ",", "'poisson'", ")", ":", "raise", "ValueErr...
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', 'poisson'} Type of noise to be added (default is 'gauss') Returns ------- np.ndarray input data with added noise Raises ------ ValueError If `noise_type` is not 'gauss' or 'poisson' ValueError If number of `sigma` values does not match the first dimension of the input data Examples -------- >>> import numpy as np >>> from modopt.signal.noise import add_noise >>> x = np.arange(9).reshape(3, 3).astype(float) >>> x array([[ 0., 1., 2.], [ 3., 4., 5.], [ 6., 7., 8.]]) >>> np.random.seed(1) >>> add_noise(x, noise_type='poisson') array([[ 0., 2., 2.], [ 4., 5., 10.], [ 11., 15., 18.]]) >>> import numpy as np >>> from modopt.signal.noise import add_noise >>> x = np.zeros(5) >>> x array([ 0., 0., 0., 0., 0.]) >>> np.random.seed(1) >>> add_noise(x, sigma=2.0) array([ 3.24869073, -1.22351283, -1.0563435 , -2.14593724, 1.73081526])
[ "r", "Add", "noise", "to", "data" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/noise.py#L15-L88
train
25,350
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 : str {'hard', 'soft'} Type of noise to be added (default is 'hard') Returns ------- np.ndarray thresholded data Raises ------ ValueError If `threshold_type` is not 'hard' or 'soft' Notes ----- Implements one of the following two equations: * Hard Threshold .. math:: \mathrm{HT}_\lambda(x) = \begin{cases} x & \text{if } |x|\geq\lambda \\ 0 & \text{otherwise} \end{cases} * Soft Threshold .. math:: \mathrm{ST}_\lambda(x) = \begin{cases} x-\lambda\text{sign}(x) & \text{if } |x|\geq\lambda \\ 0 & \text{otherwise} \end{cases} Examples -------- >>> import numpy as np >>> from modopt.signal.noise import thresh >>> np.random.seed(1) >>> x = np.random.randint(-9, 9, 10) >>> x array([-4, 2, 3, -1, 0, 2, -4, 6, -9, 7]) >>> thresh(x, 4) array([-4, 0, 0, 0, 0, 0, -4, 6, -9, 7]) >>> import numpy as np >>> from modopt.signal.noise import thresh >>> np.random.seed(1) >>> x = np.random.ranf((3, 3)) >>> x array([[ 4.17022005e-01, 7.20324493e-01, 1.14374817e-04], [ 3.02332573e-01, 1.46755891e-01, 9.23385948e-02], [ 1.86260211e-01, 3.45560727e-01, 3.96767474e-01]]) >>> thresh(x, 0.2, threshold_type='soft') array([[ 0.217022 , 0.52032449, -0. ], [ 0.10233257, -0. , -0. ], [-0. , 0.14556073, 0.19676747]]) """ data = np.array(data) if threshold_type not in ('hard', 'soft'): raise ValueError('Invalid threshold type. Options are "hard" or' '"soft"') if threshold_type == 'soft': return np.around(np.maximum((1.0 - threshold / np.maximum(np.finfo(np.float64).eps, np.abs(data))), 0.0) * data, decimals=15) else: return data * (np.abs(data) >= threshold)
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 : str {'hard', 'soft'} Type of noise to be added (default is 'hard') Returns ------- np.ndarray thresholded data Raises ------ ValueError If `threshold_type` is not 'hard' or 'soft' Notes ----- Implements one of the following two equations: * Hard Threshold .. math:: \mathrm{HT}_\lambda(x) = \begin{cases} x & \text{if } |x|\geq\lambda \\ 0 & \text{otherwise} \end{cases} * Soft Threshold .. math:: \mathrm{ST}_\lambda(x) = \begin{cases} x-\lambda\text{sign}(x) & \text{if } |x|\geq\lambda \\ 0 & \text{otherwise} \end{cases} Examples -------- >>> import numpy as np >>> from modopt.signal.noise import thresh >>> np.random.seed(1) >>> x = np.random.randint(-9, 9, 10) >>> x array([-4, 2, 3, -1, 0, 2, -4, 6, -9, 7]) >>> thresh(x, 4) array([-4, 0, 0, 0, 0, 0, -4, 6, -9, 7]) >>> import numpy as np >>> from modopt.signal.noise import thresh >>> np.random.seed(1) >>> x = np.random.ranf((3, 3)) >>> x array([[ 4.17022005e-01, 7.20324493e-01, 1.14374817e-04], [ 3.02332573e-01, 1.46755891e-01, 9.23385948e-02], [ 1.86260211e-01, 3.45560727e-01, 3.96767474e-01]]) >>> thresh(x, 0.2, threshold_type='soft') array([[ 0.217022 , 0.52032449, -0. ], [ 0.10233257, -0. , -0. ], [-0. , 0.14556073, 0.19676747]]) """ data = np.array(data) if threshold_type not in ('hard', 'soft'): raise ValueError('Invalid threshold type. Options are "hard" or' '"soft"') if threshold_type == 'soft': return np.around(np.maximum((1.0 - threshold / np.maximum(np.finfo(np.float64).eps, np.abs(data))), 0.0) * data, decimals=15) else: return data * (np.abs(data) >= threshold)
[ "def", "thresh", "(", "data", ",", "threshold", ",", "threshold_type", "=", "'hard'", ")", ":", "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 (default is 'hard') Returns ------- np.ndarray thresholded data Raises ------ ValueError If `threshold_type` is not 'hard' or 'soft' Notes ----- Implements one of the following two equations: * Hard Threshold .. math:: \mathrm{HT}_\lambda(x) = \begin{cases} x & \text{if } |x|\geq\lambda \\ 0 & \text{otherwise} \end{cases} * Soft Threshold .. math:: \mathrm{ST}_\lambda(x) = \begin{cases} x-\lambda\text{sign}(x) & \text{if } |x|\geq\lambda \\ 0 & \text{otherwise} \end{cases} Examples -------- >>> import numpy as np >>> from modopt.signal.noise import thresh >>> np.random.seed(1) >>> x = np.random.randint(-9, 9, 10) >>> x array([-4, 2, 3, -1, 0, 2, -4, 6, -9, 7]) >>> thresh(x, 4) array([-4, 0, 0, 0, 0, 0, -4, 6, -9, 7]) >>> import numpy as np >>> from modopt.signal.noise import thresh >>> np.random.seed(1) >>> x = np.random.ranf((3, 3)) >>> x array([[ 4.17022005e-01, 7.20324493e-01, 1.14374817e-04], [ 3.02332573e-01, 1.46755891e-01, 9.23385948e-02], [ 1.86260211e-01, 3.45560727e-01, 3.96767474e-01]]) >>> thresh(x, 0.2, threshold_type='soft') array([[ 0.217022 , 0.52032449, -0. ], [ 0.10233257, -0. , -0. ], [-0. , 0.14556073, 0.19676747]])
[ "r", "Threshold", "data" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/noise.py#L91-L173
train
25,351
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:: \nabla F(x) = \mathbf{H}^T(\mathbf{H}\mathbf{x} - \mathbf{y}) """ self.grad = self.trans_op(self.op(data) - self.obs_data)
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:: \nabla F(x) = \mathbf{H}^T(\mathbf{H}\mathbf{x} - \mathbf{y}) """ self.grad = self.trans_op(self.op(data) - self.obs_data)
[ "def", "_get_grad_method", "(", "self", ",", "data", ")", ":", "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(\mathbf{H}\mathbf{x} - \mathbf{y})
[ "r", "Get", "the", "gradient" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/gradient.py#L222-L241
train
25,352
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 """ cost_val = 0.5 * np.linalg.norm(self.obs_data - self.op(args[0])) ** 2 if 'verbose' in kwargs and kwargs['verbose']: print(' - DATA FIDELITY (X):', cost_val) return cost_val
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 """ cost_val = 0.5 * np.linalg.norm(self.obs_data - self.op(args[0])) ** 2 if 'verbose' in kwargs and kwargs['verbose']: print(' - DATA FIDELITY (X):', cost_val) return cost_val
[ "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
25,353
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']: print(' - Min (X):', np.min(args[0])) return 0.0
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']: print(' - Min (X):', np.min(args[0])) return 0.0
[ "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
25,354
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 * self._linear.op(args[0]))) if 'verbose' in kwargs and kwargs['verbose']: print(' - L1 NORM (X):', cost_val) return cost_val
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 * self._linear.op(args[0]))) if 'verbose' in kwargs and kwargs['verbose']: print(' - L1 NORM (X):', cost_val) return cost_val
[ "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
25,355
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_norm(cube2matrix(args[0])) if 'verbose' in kwargs and kwargs['verbose']: print(' - NUCLEAR NORM (X):', cost_val) return cost_val
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_norm(cube2matrix(args[0])) if 'verbose' in kwargs and kwargs['verbose']: print(' - NUCLEAR NORM (X):', cost_val) return cost_val
[ "def", "_cost_method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cost_val", "=", "self", ".", "thresh", "*", "nuclear_norm", "(", "cube2matrix", "(", "args", "[", "0", "]", ")", ")", "if", "'verbose'", "in", "kwargs", "and", ...
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
25,356
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 Additional multiplication factor Returns ------- np.ndarray result of the scaled proximity operator """ return self.linear_op.adj_op( self.prox_op.op(self.linear_op.op(data), extra_factor=extra_factor) )
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 Additional multiplication factor Returns ------- np.ndarray result of the scaled proximity operator """ return self.linear_op.adj_op( self.prox_op.op(self.linear_op.op(data), extra_factor=extra_factor) )
[ "def", "_op_method", "(", "self", ",", "data", ",", "extra_factor", "=", "1.0", ")", ":", "return", "self", ".", "linear_op", ".", "adj_op", "(", "self", ".", "prox_op", ".", "op", "(", "self", ".", "linear_op", ".", "op", "(", "data", ")", ",", "e...
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 Returns ------- np.ndarray result of the scaled proximity operator
[ "r", "Operator", "method" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/proximity.py#L295-L314
train
25,357
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
25,358
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 np.sum([operator.cost(data) for operator, data in zip(self.operators, args[0])])
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 np.sum([operator.cost(data) for operator, data in zip(self.operators, args[0])])
[ "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
25,359
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
25,360
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 magnetude. Returns ------- ssim: float, the snr """ test = np.abs(np.copy(test)).astype('float64') ref = np.abs(np.copy(ref)).astype('float64') test = min_max_normalize(test) ref = min_max_normalize(ref) if (not isinstance(mask, np.ndarray)) and (mask is not None): raise ValueError("mask should be None, or a np.ndarray," " got '{0}' instead.".format(mask)) if mask is None: return test, ref, None return test, ref, mask
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 magnetude. Returns ------- ssim: float, the snr """ test = np.abs(np.copy(test)).astype('float64') ref = np.abs(np.copy(ref)).astype('float64') test = min_max_normalize(test) ref = min_max_normalize(ref) if (not isinstance(mask, np.ndarray)) and (mask is not None): raise ValueError("mask should be None, or a np.ndarray," " got '{0}' instead.".format(mask)) if mask is None: return test, ref, None return test, ref, mask
[ "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 snr
[ "Wrapper", "to", "the", "metric" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/metrics.py#L36-L70
train
25,361
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_name[0][0] == '-': raise IOError('Input file name not specified.') elif not os.path.isfile(file_name): raise IOError('Input file name [%s] not found!' % file_name)
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_name[0][0] == '-': raise IOError('Input file name not specified.') elif not os.path.isfile(file_name): raise IOError('Input file name [%s] not found!' % file_name)
[ "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
25,362
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 """ if not isinstance(exe_name, str): raise TypeError('Executable name must be a string.') def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(exe_name) if not fpath: res = any([is_exe(os.path.join(path, exe_name)) for path in os.environ["PATH"].split(os.pathsep)]) else: res = is_exe(exe_name) if not res: raise IOError('{} does not appear to be a valid executable on this ' 'system.'.format(exe_name))
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 """ if not isinstance(exe_name, str): raise TypeError('Executable name must be a string.') def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(exe_name) if not fpath: res = any([is_exe(os.path.join(path, exe_name)) for path in os.environ["PATH"].split(os.pathsep)]) else: res = is_exe(exe_name) if not res: raise IOError('{} does not appear to be a valid executable on this ' 'system.'.format(exe_name))
[ "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
25,363
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)): tree = [obj.__name__ for obj in getmro(operator.__class__)] if not any([parent in tree for parent in self._op_parents]): warn('{0} does not inherit an operator ' 'parent.'.format(str(operator.__class__)))
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)): tree = [obj.__name__ for obj in getmro(operator.__class__)] if not any([parent in tree for parent in self._op_parents]): warn('{0} does not inherit an operator ' 'parent.'.format(str(operator.__class__)))
[ "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
25,364
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 regular (as opposed to CD for now). Parameters ---------- restart_strategy: str or None name of the restarting strategy. If None, there is no restarting. Defaults to None. min_beta: float or None the minimum beta when using the greedy restarting strategy. Defaults to None. s_greedy: float or None. parameter for the safeguard comparison in the greedy restarting strategy. It has to be > 1. Defaults to None. xi_restart: float or None. mutlitplicative parameter for the update of beta in the greedy restarting strategy and for the update of r_lazy in the adaptive restarting strategies. It has to be > 1. Defaults to None. Returns ------- bool: True Raises ------ ValueError When a parameter that should be set isn't or doesn't verify the correct assumptions. """ if restart_strategy is None: return True if self.mode != 'regular': raise ValueError('Restarting strategies can only be used with ' 'regular mode.') greedy_params_check = (min_beta is None or s_greedy is None or s_greedy <= 1) if restart_strategy == 'greedy' and greedy_params_check: raise ValueError('You need a min_beta and an s_greedy > 1 for ' 'greedy restart.') if xi_restart is None or xi_restart >= 1: raise ValueError('You need a xi_restart < 1 for restart.') return True
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 regular (as opposed to CD for now). Parameters ---------- restart_strategy: str or None name of the restarting strategy. If None, there is no restarting. Defaults to None. min_beta: float or None the minimum beta when using the greedy restarting strategy. Defaults to None. s_greedy: float or None. parameter for the safeguard comparison in the greedy restarting strategy. It has to be > 1. Defaults to None. xi_restart: float or None. mutlitplicative parameter for the update of beta in the greedy restarting strategy and for the update of r_lazy in the adaptive restarting strategies. It has to be > 1. Defaults to None. Returns ------- bool: True Raises ------ ValueError When a parameter that should be set isn't or doesn't verify the correct assumptions. """ if restart_strategy is None: return True if self.mode != 'regular': raise ValueError('Restarting strategies can only be used with ' 'regular mode.') greedy_params_check = (min_beta is None or s_greedy is None or s_greedy <= 1) if restart_strategy == 'greedy' and greedy_params_check: raise ValueError('You need a min_beta and an s_greedy > 1 for ' 'greedy restart.') if xi_restart is None or xi_restart >= 1: raise ValueError('You need a xi_restart < 1 for restart.') return True
[ "def", "_check_restart_params", "(", "self", ",", "restart_strategy", ",", "min_beta", ",", "s_greedy", ",", "xi_restart", ")", ":", "if", "restart_strategy", "is", "None", ":", "return", "True", "if", "self", ".", "mode", "!=", "'regular'", ":", "raise", "V...
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 name of the restarting strategy. If None, there is no restarting. Defaults to None. min_beta: float or None the minimum beta when using the greedy restarting strategy. Defaults to None. s_greedy: float or None. parameter for the safeguard comparison in the greedy restarting strategy. It has to be > 1. Defaults to None. xi_restart: float or None. mutlitplicative parameter for the update of beta in the greedy restarting strategy and for the update of r_lazy in the adaptive restarting strategies. It has to be > 1. Defaults to None. Returns ------- bool: True Raises ------ ValueError When a parameter that should be set isn't or doesn't verify the correct assumptions.
[ "r", "Check", "restarting", "parameters" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/algorithms.py#L307-L361
train
25,365
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 strategy (namely beta and r). Parameters ---------- z_old: ndarray Corresponds to y_n in [L2018]. x_new: ndarray Corresponds to x_{n+1} in [L2018]. x_old: ndarray Corresponds to x_n in [L2018]. Returns ------- bool: whether the algorithm should restart Notes ----- Implements restarting and safeguarding steps in alg 4-5 o [L2018] """ if self.restart_strategy is None: return False criterion = np.vdot(z_old - x_new, x_new - x_old) >= 0 if criterion: if 'adaptive' in self.restart_strategy: self.r_lazy *= self.xi_restart if self.restart_strategy in ['adaptive-ii', 'adaptive-2']: self._t_now = 1 if self.restart_strategy == 'greedy': cur_delta = np.linalg.norm(x_new - x_old) if self._delta_0 is None: self._delta_0 = self.s_greedy * cur_delta else: self._safeguard = cur_delta >= self._delta_0 return criterion
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 strategy (namely beta and r). Parameters ---------- z_old: ndarray Corresponds to y_n in [L2018]. x_new: ndarray Corresponds to x_{n+1} in [L2018]. x_old: ndarray Corresponds to x_n in [L2018]. Returns ------- bool: whether the algorithm should restart Notes ----- Implements restarting and safeguarding steps in alg 4-5 o [L2018] """ if self.restart_strategy is None: return False criterion = np.vdot(z_old - x_new, x_new - x_old) >= 0 if criterion: if 'adaptive' in self.restart_strategy: self.r_lazy *= self.xi_restart if self.restart_strategy in ['adaptive-ii', 'adaptive-2']: self._t_now = 1 if self.restart_strategy == 'greedy': cur_delta = np.linalg.norm(x_new - x_old) if self._delta_0 is None: self._delta_0 = self.s_greedy * cur_delta else: self._safeguard = cur_delta >= self._delta_0 return criterion
[ "def", "is_restart", "(", "self", ",", "z_old", ",", "x_new", ",", "x_old", ")", ":", "if", "self", ".", "restart_strategy", "is", "None", ":", "return", "False", "criterion", "=", "np", ".", "vdot", "(", "z_old", "-", "x_new", ",", "x_new", "-", "x_...
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). Parameters ---------- z_old: ndarray Corresponds to y_n in [L2018]. x_new: ndarray Corresponds to x_{n+1} in [L2018]. x_old: ndarray Corresponds to x_n in [L2018]. Returns ------- bool: whether the algorithm should restart Notes ----- Implements restarting and safeguarding steps in alg 4-5 o [L2018]
[ "r", "Check", "whether", "the", "algorithm", "needs", "to", "restart" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/algorithms.py#L363-L407
train
25,366
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 ------- float: the new value for the beta parameter """ if self._safeguard: beta *= self.xi_restart beta = max(beta, self.min_beta) return beta
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 ------- float: the new value for the beta parameter """ if self._safeguard: beta *= self.xi_restart beta = max(beta, self.min_beta) return beta
[ "def", "update_beta", "(", "self", ",", "beta", ")", ":", "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 parameter
[ "r", "Update", "beta" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/algorithms.py#L409-L429
train
25,367
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_strategy == 'greedy': return 2 # Steps 3 and 4 from alg.10.7. self._t_prev = self._t_now if self.mode == 'regular': self._t_now = (self.p_lazy + np.sqrt(self.r_lazy * self._t_prev ** 2 + self.q_lazy)) * 0.5 elif self.mode == 'CD': self._t_now = (self._n + self.a_cd - 1) / self.a_cd self._n += 1 return 1 + (self._t_prev - 1) / self._t_now
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_strategy == 'greedy': return 2 # Steps 3 and 4 from alg.10.7. self._t_prev = self._t_now if self.mode == 'regular': self._t_now = (self.p_lazy + np.sqrt(self.r_lazy * self._t_prev ** 2 + self.q_lazy)) * 0.5 elif self.mode == 'CD': self._t_now = (self._n + self.a_cd - 1) / self.a_cd self._n += 1 return 1 + (self._t_prev - 1) / self._t_now
[ "def", "update_lambda", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "restart_strategy", "==", "'greedy'", ":", "return", "2", "# Steps 3 and 4 from alg.10.7.", "self", ".", "_t_prev", "=", "self", ".", "_t_now", "if...
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
25,368
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 be passed to mr_transform path : str, optional Path for output files (default is './') remove_files : bool, optional Option to remove output files (default is 'True') Returns ------- np.ndarray results of mr_transform Raises ------ ValueError If the input data is not a 2D numpy array Examples -------- >>> from modopt.signal.wavelet import * >>> a = np.arange(9).reshape(3, 3).astype(float) >>> call_mr_transform(a) array([[[-1.5 , -1.125 , -0.75 ], [-0.375 , 0. , 0.375 ], [ 0.75 , 1.125 , 1.5 ]], [[-1.5625 , -1.171875 , -0.78125 ], [-0.390625 , 0. , 0.390625 ], [ 0.78125 , 1.171875 , 1.5625 ]], [[-0.5859375 , -0.43945312, -0.29296875], [-0.14648438, 0. , 0.14648438], [ 0.29296875, 0.43945312, 0.5859375 ]], [[ 3.6484375 , 3.73632812, 3.82421875], [ 3.91210938, 4. , 4.08789062], [ 4.17578125, 4.26367188, 4.3515625 ]]], dtype=float32) """ if not import_astropy: raise ImportError('Astropy package not found.') if (not isinstance(data, np.ndarray)) or (data.ndim != 2): raise ValueError('Input data must be a 2D numpy array.') executable = 'mr_transform' # Make sure mr_transform is installed. is_executable(executable) # Create a unique string using the current date and time. unique_string = datetime.now().strftime('%Y.%m.%d_%H.%M.%S') # Set the ouput file names. file_name = path + 'mr_temp_' + unique_string file_fits = file_name + '.fits' file_mr = file_name + '.mr' # Write the input data to a fits file. fits.writeto(file_fits, data) if isinstance(opt, str): opt = opt.split() # Call mr_transform. try: check_call([executable] + opt + [file_fits, file_mr]) except Exception: warn('{} failed to run with the options provided.'.format(executable)) remove(file_fits) else: # Retrieve wavelet transformed data. result = fits.getdata(file_mr) # Remove the temporary files. if remove_files: remove(file_fits) remove(file_mr) # Return the mr_transform results. return result
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 be passed to mr_transform path : str, optional Path for output files (default is './') remove_files : bool, optional Option to remove output files (default is 'True') Returns ------- np.ndarray results of mr_transform Raises ------ ValueError If the input data is not a 2D numpy array Examples -------- >>> from modopt.signal.wavelet import * >>> a = np.arange(9).reshape(3, 3).astype(float) >>> call_mr_transform(a) array([[[-1.5 , -1.125 , -0.75 ], [-0.375 , 0. , 0.375 ], [ 0.75 , 1.125 , 1.5 ]], [[-1.5625 , -1.171875 , -0.78125 ], [-0.390625 , 0. , 0.390625 ], [ 0.78125 , 1.171875 , 1.5625 ]], [[-0.5859375 , -0.43945312, -0.29296875], [-0.14648438, 0. , 0.14648438], [ 0.29296875, 0.43945312, 0.5859375 ]], [[ 3.6484375 , 3.73632812, 3.82421875], [ 3.91210938, 4. , 4.08789062], [ 4.17578125, 4.26367188, 4.3515625 ]]], dtype=float32) """ if not import_astropy: raise ImportError('Astropy package not found.') if (not isinstance(data, np.ndarray)) or (data.ndim != 2): raise ValueError('Input data must be a 2D numpy array.') executable = 'mr_transform' # Make sure mr_transform is installed. is_executable(executable) # Create a unique string using the current date and time. unique_string = datetime.now().strftime('%Y.%m.%d_%H.%M.%S') # Set the ouput file names. file_name = path + 'mr_temp_' + unique_string file_fits = file_name + '.fits' file_mr = file_name + '.mr' # Write the input data to a fits file. fits.writeto(file_fits, data) if isinstance(opt, str): opt = opt.split() # Call mr_transform. try: check_call([executable] + opt + [file_fits, file_mr]) except Exception: warn('{} failed to run with the options provided.'.format(executable)) remove(file_fits) else: # Retrieve wavelet transformed data. result = fits.getdata(file_mr) # Remove the temporary files. if remove_files: remove(file_fits) remove(file_mr) # Return the mr_transform results. return result
[ "def", "call_mr_transform", "(", "data", ",", "opt", "=", "''", ",", "path", "=", "'./'", ",", "remove_files", "=", "True", ")", ":", "# pragma: no cover", "if", "not", "import_astropy", ":", "raise", "ImportError", "(", "'Astropy package not found.'", ")", "i...
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_files : bool, optional Option to remove output files (default is 'True') Returns ------- np.ndarray results of mr_transform Raises ------ ValueError If the input data is not a 2D numpy array Examples -------- >>> from modopt.signal.wavelet import * >>> a = np.arange(9).reshape(3, 3).astype(float) >>> call_mr_transform(a) array([[[-1.5 , -1.125 , -0.75 ], [-0.375 , 0. , 0.375 ], [ 0.75 , 1.125 , 1.5 ]], [[-1.5625 , -1.171875 , -0.78125 ], [-0.390625 , 0. , 0.390625 ], [ 0.78125 , 1.171875 , 1.5625 ]], [[-0.5859375 , -0.43945312, -0.29296875], [-0.14648438, 0. , 0.14648438], [ 0.29296875, 0.43945312, 0.5859375 ]], [[ 3.6484375 , 3.73632812, 3.82421875], [ 3.91210938, 4. , 4.08789062], [ 4.17578125, 4.26367188, 4.3515625 ]]], dtype=float32)
[ "r", "Call", "mr_transform" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/wavelet.py#L36-L131
train
25,369
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 coarse : bool, optional Option to keep coarse scale (default is 'False') Returns ------- np.ndarray 3D array of wavelet filters """ # Adjust the shape of the input data. data_shape = np.array(data_shape) data_shape += data_shape % 2 - 1 # Create fake data. fake_data = np.zeros(data_shape) fake_data[tuple(zip(data_shape // 2))] = 1 # Call mr_transform. mr_filters = call_mr_transform(fake_data, opt=opt) # Return filters if coarse: return mr_filters else: return mr_filters[:-1]
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 coarse : bool, optional Option to keep coarse scale (default is 'False') Returns ------- np.ndarray 3D array of wavelet filters """ # Adjust the shape of the input data. data_shape = np.array(data_shape) data_shape += data_shape % 2 - 1 # Create fake data. fake_data = np.zeros(data_shape) fake_data[tuple(zip(data_shape // 2))] = 1 # Call mr_transform. mr_filters = call_mr_transform(fake_data, opt=opt) # Return filters if coarse: return mr_filters else: return mr_filters[:-1]
[ "def", "get_mr_filters", "(", "data_shape", ",", "opt", "=", "''", ",", "coarse", "=", "False", ")", ":", "# pragma: no cover", "# Adjust the shape of the input data.", "data_shape", "=", "np", ".", "array", "(", "data_shape", ")", "data_shape", "+=", "data_shape"...
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') Returns ------- np.ndarray 3D array of wavelet filters
[ "Get", "mr_transform", "filters" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/wavelet.py#L134-L169
train
25,370
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. Returns ------- Lists of orthogonal vectors, u, and/or orthonormal vectors, e Examples -------- >>> from modopt.math.matrix import gram_schmidt >>> a = np.arange(9).reshape(3, 3) >>> gram_schmidt(a) array([[ 0. , 0.4472136 , 0.89442719], [ 0.91287093, 0.36514837, -0.18257419], [-1. , 0. , 0. ]]) Notes ----- Implementation from: https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process """ if return_opt not in ('orthonormal', 'orthogonal', 'both'): raise ValueError('Invalid return_opt, options are: "orthonormal", ' '"orthogonal" or "both"') u = [] e = [] for vector in matrix: if len(u) == 0: u_now = vector else: u_now = vector - sum([project(u_i, vector) for u_i in u]) u.append(u_now) e.append(u_now / np.linalg.norm(u_now, 2)) u = np.array(u) e = np.array(e) if return_opt == 'orthonormal': return e elif return_opt == 'orthogonal': return u elif return_opt == 'both': return u, e
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. Returns ------- Lists of orthogonal vectors, u, and/or orthonormal vectors, e Examples -------- >>> from modopt.math.matrix import gram_schmidt >>> a = np.arange(9).reshape(3, 3) >>> gram_schmidt(a) array([[ 0. , 0.4472136 , 0.89442719], [ 0.91287093, 0.36514837, -0.18257419], [-1. , 0. , 0. ]]) Notes ----- Implementation from: https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process """ if return_opt not in ('orthonormal', 'orthogonal', 'both'): raise ValueError('Invalid return_opt, options are: "orthonormal", ' '"orthogonal" or "both"') u = [] e = [] for vector in matrix: if len(u) == 0: u_now = vector else: u_now = vector - sum([project(u_i, vector) for u_i in u]) u.append(u_now) e.append(u_now / np.linalg.norm(u_now, 2)) u = np.array(u) e = np.array(e) if return_opt == 'orthonormal': return e elif return_opt == 'orthogonal': return u elif return_opt == 'both': return u, e
[ "def", "gram_schmidt", "(", "matrix", ",", "return_opt", "=", "'orthonormal'", ")", ":", "if", "return_opt", "not", "in", "(", "'orthonormal'", ",", "'orthogonal'", ",", "'both'", ")", ":", "raise", "ValueError", "(", "'Invalid return_opt, options are: \"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. Returns ------- Lists of orthogonal vectors, u, and/or orthonormal vectors, e Examples -------- >>> from modopt.math.matrix import gram_schmidt >>> a = np.arange(9).reshape(3, 3) >>> gram_schmidt(a) array([[ 0. , 0.4472136 , 0.89442719], [ 0.91287093, 0.36514837, -0.18257419], [-1. , 0. , 0. ]]) Notes ----- Implementation from: https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process
[ "r", "Gram", "-", "Schmit" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/matrix.py#L17-L74
train
25,371
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 nuclear_norm >>> a = np.arange(9).reshape(3, 3) >>> nuclear_norm(a) 15.49193338482967 Notes ----- Implements the following equation: .. math:: \|\mathbf{A}\|_* = \sum_{i=1}^{\min\{m,n\}} \sigma_i (\mathbf{A}) """ # Get SVD of the data. u, s, v = np.linalg.svd(data) # Return nuclear norm. return np.sum(s)
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 nuclear_norm >>> a = np.arange(9).reshape(3, 3) >>> nuclear_norm(a) 15.49193338482967 Notes ----- Implements the following equation: .. math:: \|\mathbf{A}\|_* = \sum_{i=1}^{\min\{m,n\}} \sigma_i (\mathbf{A}) """ # Get SVD of the data. u, s, v = np.linalg.svd(data) # Return nuclear norm. return np.sum(s)
[ "def", "nuclear_norm", "(", "data", ")", ":", "# Get SVD of the data.", "u", ",", "s", ",", "v", "=", "np", ".", "linalg", ".", "svd", "(", "data", ")", "# Return nuclear norm.", "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.arange(9).reshape(3, 3) >>> nuclear_norm(a) 15.49193338482967 Notes ----- Implements the following equation: .. math:: \|\mathbf{A}\|_* = \sum_{i=1}^{\min\{m,n\}} \sigma_i (\mathbf{A})
[ "r", "Nuclear", "norm" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/matrix.py#L77-L111
train
25,372
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 project >>> a = np.arange(3) >>> b = a + 3 >>> project(a, b) array([ 0. , 2.8, 5.6]) Notes ----- Implements the following equation: .. math:: \textrm{proj}_\mathbf{u}(\mathbf{v}) = \frac{\langle\mathbf{u}, \mathbf{v}\rangle}{\langle\mathbf{u}, \mathbf{u}\rangle}\mathbf{u} (see https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process) """ return np.inner(v, u) / np.inner(u, u) * u
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 project >>> a = np.arange(3) >>> b = a + 3 >>> project(a, b) array([ 0. , 2.8, 5.6]) Notes ----- Implements the following equation: .. math:: \textrm{proj}_\mathbf{u}(\mathbf{v}) = \frac{\langle\mathbf{u}, \mathbf{v}\rangle}{\langle\mathbf{u}, \mathbf{u}\rangle}\mathbf{u} (see https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process) """ return np.inner(v, u) / np.inner(u, u) * u
[ "def", "project", "(", "u", ",", "v", ")", ":", "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.arange(3) >>> b = a + 3 >>> project(a, b) array([ 0. , 2.8, 5.6]) Notes ----- Implements the following equation: .. math:: \textrm{proj}_\mathbf{u}(\mathbf{v}) = \frac{\langle\mathbf{u}, \mathbf{v}\rangle}{\langle\mathbf{u}, \mathbf{u}\rangle}\mathbf{u} (see https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process)
[ "r", "Project", "vector" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/matrix.py#L114-L150
train
25,373
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.matrix import rot_matrix >>> rot_matrix(np.pi / 6) array([[ 0.8660254, -0.5 ], [ 0.5 , 0.8660254]]) Notes ----- Implements the following equation: .. math:: R(\theta) = \begin{bmatrix} \cos(\theta) & -\sin(\theta) \\ \sin(\theta) & \cos(\theta) \end{bmatrix} """ return np.around(np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]], dtype='float'), 10)
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.matrix import rot_matrix >>> rot_matrix(np.pi / 6) array([[ 0.8660254, -0.5 ], [ 0.5 , 0.8660254]]) Notes ----- Implements the following equation: .. math:: R(\theta) = \begin{bmatrix} \cos(\theta) & -\sin(\theta) \\ \sin(\theta) & \cos(\theta) \end{bmatrix} """ return np.around(np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]], dtype='float'), 10)
[ "def", "rot_matrix", "(", "angle", ")", ":", "return", "np", ".", "around", "(", "np", ".", "array", "(", "[", "[", "np", ".", "cos", "(", "angle", ")", ",", "-", "np", ".", "sin", "(", "angle", ")", "]", ",", "[", "np", ".", "sin", "(", "a...
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 >>> rot_matrix(np.pi / 6) array([[ 0.8660254, -0.5 ], [ 0.5 , 0.8660254]]) Notes ----- Implements the following equation: .. math:: R(\theta) = \begin{bmatrix} \cos(\theta) & -\sin(\theta) \\ \sin(\theta) & \cos(\theta) \end{bmatrix}
[ "r", "Rotation", "matrix" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/matrix.py#L153-L187
train
25,374
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._data_type)
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._data_type)
[ "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
25,375
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, optional Maximum number of iterations (default is 20) extra_factor : float, optional Extra multiplicative factor for calculating the spectral radius (default is 1.0) """ # Set (or reset) values of x. x_old = self._set_initial_x() # Iterate until the L2 norm of x converges. for i in range(max_iter): x_old_norm = np.linalg.norm(x_old) x_new = self._operator(x_old) / x_old_norm x_new_norm = np.linalg.norm(x_new) if(np.abs(x_new_norm - x_old_norm) < tolerance): if self._verbose: print(' - Power Method converged after %d iterations!' % (i + 1)) break elif i == max_iter - 1 and self._verbose: print(' - Power Method did not converge after %d ' 'iterations!' % max_iter) np.copyto(x_old, x_new) self.spec_rad = x_new_norm * extra_factor self.inv_spec_rad = 1.0 / self.spec_rad
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, optional Maximum number of iterations (default is 20) extra_factor : float, optional Extra multiplicative factor for calculating the spectral radius (default is 1.0) """ # Set (or reset) values of x. x_old = self._set_initial_x() # Iterate until the L2 norm of x converges. for i in range(max_iter): x_old_norm = np.linalg.norm(x_old) x_new = self._operator(x_old) / x_old_norm x_new_norm = np.linalg.norm(x_new) if(np.abs(x_new_norm - x_old_norm) < tolerance): if self._verbose: print(' - Power Method converged after %d iterations!' % (i + 1)) break elif i == max_iter - 1 and self._verbose: print(' - Power Method did not converge after %d ' 'iterations!' % max_iter) np.copyto(x_old, x_new) self.spec_rad = x_new_norm * extra_factor self.inv_spec_rad = 1.0 / self.spec_rad
[ "def", "get_spec_rad", "(", "self", ",", "tolerance", "=", "1e-6", ",", "max_iter", "=", "20", ",", "extra_factor", "=", "1.0", ")", ":", "# Set (or reset) values of x.", "x_old", "=", "self", ".", "_set_initial_x", "(", ")", "# Iterate until the L2 norm of x conv...
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_factor : float, optional Extra multiplicative factor for calculating the spectral radius (default is 1.0)
[ "Get", "spectral", "radius" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/matrix.py#L298-L340
train
25,376
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.ndarray of input Raises ------ TypeError For invalid input type """ if not isinstance(input_val, (list, tuple, np.ndarray)): raise TypeError('Invalid input type, input must be a list, tuple ' 'or numpy array.') input_val = np.array(input_val) if not input_val.size: raise ValueError('Input list is empty.') return input_val
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.ndarray of input Raises ------ TypeError For invalid input type """ if not isinstance(input_val, (list, tuple, np.ndarray)): raise TypeError('Invalid input type, input must be a list, tuple ' 'or numpy array.') input_val = np.array(input_val) if not input_val.size: raise ValueError('Input list is empty.') return input_val
[ "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 ------ TypeError For invalid input type
[ "Check", "Input", "Type" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/linear.py#L154-L184
train
25,377
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 correlation (default is '0.5') Returns ------- int number of principal components Examples -------- >>> from scipy.linalg import svd >>> from modopt.signal.svd import find_n_pc >>> x = np.arange(18).reshape(9, 2).astype(float) >>> find_n_pc(svd(x)[0]) array([3]) """ if np.sqrt(u.shape[0]) % 1: raise ValueError('Invalid left singular value. The size of the first ' 'dimenion of u must be perfect square.') # Get the shape of the array array_shape = np.repeat(np.int(np.sqrt(u.shape[0])), 2) # Find the auto correlation of the left singular vector. u_auto = [convolve(a.reshape(array_shape), np.rot90(a.reshape(array_shape), 2)) for a in u.T] # Return the required number of principal components. return np.sum([(a[tuple(zip(array_shape // 2))] ** 2 <= factor * np.sum(a ** 2)) for a in u_auto])
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 correlation (default is '0.5') Returns ------- int number of principal components Examples -------- >>> from scipy.linalg import svd >>> from modopt.signal.svd import find_n_pc >>> x = np.arange(18).reshape(9, 2).astype(float) >>> find_n_pc(svd(x)[0]) array([3]) """ if np.sqrt(u.shape[0]) % 1: raise ValueError('Invalid left singular value. The size of the first ' 'dimenion of u must be perfect square.') # Get the shape of the array array_shape = np.repeat(np.int(np.sqrt(u.shape[0])), 2) # Find the auto correlation of the left singular vector. u_auto = [convolve(a.reshape(array_shape), np.rot90(a.reshape(array_shape), 2)) for a in u.T] # Return the required number of principal components. return np.sum([(a[tuple(zip(array_shape // 2))] ** 2 <= factor * np.sum(a ** 2)) for a in u_auto])
[ "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 ------- int number of principal components Examples -------- >>> from scipy.linalg import svd >>> from modopt.signal.svd import find_n_pc >>> x = np.arange(18).reshape(9, 2).astype(float) >>> find_n_pc(svd(x)[0]) array([3])
[ "Find", "number", "of", "principal", "components" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/svd.py#L21-L60
train
25,378
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, singular values and right singular vector Raises ------ TypeError For invalid data type """ if (not isinstance(data, np.ndarray)) or (data.ndim != 2): raise TypeError('Input data must be a 2D np.ndarray.') return svd(data, check_finite=False, lapack_driver='gesvd', full_matrices=False)
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, singular values and right singular vector Raises ------ TypeError For invalid data type """ if (not isinstance(data, np.ndarray)) or (data.ndim != 2): raise TypeError('Input data must be a 2D np.ndarray.') return svd(data, check_finite=False, lapack_driver='gesvd', full_matrices=False)
[ "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 singular vector Raises ------ TypeError For invalid data type
[ "Calculate", "Singular", "Value", "Decomposition" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/svd.py#L63-L89
train
25,379
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 Threshold value(s) n_pc : int or str, optional Number of principal components, specify an integer value or 'all' threshold_type : str {'hard', 'soft'}, optional Type of thresholding (default is 'hard') Returns ------- np.ndarray thresholded data Raises ------ ValueError For invalid n_pc value Examples -------- >>> from modopt.signal.svd import svd_thresh >>> x = np.arange(18).reshape(9, 2).astype(float) >>> svd_thresh(x, n_pc=1) array([[ 0.49815487, 0.54291537], [ 2.40863386, 2.62505584], [ 4.31911286, 4.70719631], [ 6.22959185, 6.78933678], [ 8.14007085, 8.87147725], [ 10.05054985, 10.95361772], [ 11.96102884, 13.03575819], [ 13.87150784, 15.11789866], [ 15.78198684, 17.20003913]]) """ if ((not isinstance(n_pc, (int, str, type(None)))) or (isinstance(n_pc, int) and n_pc <= 0) or (isinstance(n_pc, str) and n_pc != 'all')): raise ValueError('Invalid value for "n_pc", specify a positive ' 'integer value or "all"') # Get SVD of input data. u, s, v = calculate_svd(data) # Find the threshold if not provided. if isinstance(threshold, type(None)): # Find the required number of principal components if not specified. if isinstance(n_pc, type(None)): n_pc = find_n_pc(u, factor=0.1) # If the number of PCs is too large use all of the singular values. if ((isinstance(n_pc, int) and n_pc >= s.size) or (isinstance(n_pc, str) and n_pc == 'all')): n_pc = s.size warn('Using all singular values.') threshold = s[n_pc - 1] # Threshold the singular values. s_new = thresh(s, threshold, thresh_type) if np.all(s_new == s): warn('No change to singular values.') # Diagonalize the svd s_new = np.diag(s_new) # Return the thresholded data. return np.dot(u, np.dot(s_new, v))
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 Threshold value(s) n_pc : int or str, optional Number of principal components, specify an integer value or 'all' threshold_type : str {'hard', 'soft'}, optional Type of thresholding (default is 'hard') Returns ------- np.ndarray thresholded data Raises ------ ValueError For invalid n_pc value Examples -------- >>> from modopt.signal.svd import svd_thresh >>> x = np.arange(18).reshape(9, 2).astype(float) >>> svd_thresh(x, n_pc=1) array([[ 0.49815487, 0.54291537], [ 2.40863386, 2.62505584], [ 4.31911286, 4.70719631], [ 6.22959185, 6.78933678], [ 8.14007085, 8.87147725], [ 10.05054985, 10.95361772], [ 11.96102884, 13.03575819], [ 13.87150784, 15.11789866], [ 15.78198684, 17.20003913]]) """ if ((not isinstance(n_pc, (int, str, type(None)))) or (isinstance(n_pc, int) and n_pc <= 0) or (isinstance(n_pc, str) and n_pc != 'all')): raise ValueError('Invalid value for "n_pc", specify a positive ' 'integer value or "all"') # Get SVD of input data. u, s, v = calculate_svd(data) # Find the threshold if not provided. if isinstance(threshold, type(None)): # Find the required number of principal components if not specified. if isinstance(n_pc, type(None)): n_pc = find_n_pc(u, factor=0.1) # If the number of PCs is too large use all of the singular values. if ((isinstance(n_pc, int) and n_pc >= s.size) or (isinstance(n_pc, str) and n_pc == 'all')): n_pc = s.size warn('Using all singular values.') threshold = s[n_pc - 1] # Threshold the singular values. s_new = thresh(s, threshold, thresh_type) if np.all(s_new == s): warn('No change to singular values.') # Diagonalize the svd s_new = np.diag(s_new) # Return the thresholded data. return np.dot(u, np.dot(s_new, v))
[ "def", "svd_thresh", "(", "data", ",", "threshold", "=", "None", ",", "n_pc", "=", "None", ",", "thresh_type", "=", "'hard'", ")", ":", "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 of principal components, specify an integer value or 'all' threshold_type : str {'hard', 'soft'}, optional Type of thresholding (default is 'hard') Returns ------- np.ndarray thresholded data Raises ------ ValueError For invalid n_pc value Examples -------- >>> from modopt.signal.svd import svd_thresh >>> x = np.arange(18).reshape(9, 2).astype(float) >>> svd_thresh(x, n_pc=1) array([[ 0.49815487, 0.54291537], [ 2.40863386, 2.62505584], [ 4.31911286, 4.70719631], [ 6.22959185, 6.78933678], [ 8.14007085, 8.87147725], [ 10.05054985, 10.95361772], [ 11.96102884, 13.03575819], [ 13.87150784, 15.11789866], [ 15.78198684, 17.20003913]])
[ "r", "Threshold", "the", "singular", "values" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/svd.py#L92-L168
train
25,380
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 Operator class instance threshold : float or np.ndarray Threshold value(s) threshold_type : str {'hard', 'soft'} Type of noise to be added (default is 'hard') Returns ------- np.ndarray thresholded data Raises ------ ValueError For invalid string entry for n_pc """ if not callable(operator): raise TypeError('Operator must be a callable function.') # Get SVD of data matrix u, s, v = calculate_svd(data) # Diagnalise s s = np.diag(s) # Compute coefficients a = np.dot(s, v) # Get the shape of the array array_shape = np.repeat(np.int(np.sqrt(u.shape[0])), 2) # Compute threshold matrix. ti = np.array([np.linalg.norm(x) for x in operator(matrix2cube(u, array_shape))]) threshold *= np.repeat(ti, a.shape[1]).reshape(a.shape) # Threshold coefficients. a_new = thresh(a, threshold, thresh_type) # Return the thresholded image. return np.dot(u, a_new)
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 Operator class instance threshold : float or np.ndarray Threshold value(s) threshold_type : str {'hard', 'soft'} Type of noise to be added (default is 'hard') Returns ------- np.ndarray thresholded data Raises ------ ValueError For invalid string entry for n_pc """ if not callable(operator): raise TypeError('Operator must be a callable function.') # Get SVD of data matrix u, s, v = calculate_svd(data) # Diagnalise s s = np.diag(s) # Compute coefficients a = np.dot(s, v) # Get the shape of the array array_shape = np.repeat(np.int(np.sqrt(u.shape[0])), 2) # Compute threshold matrix. ti = np.array([np.linalg.norm(x) for x in operator(matrix2cube(u, array_shape))]) threshold *= np.repeat(ti, a.shape[1]).reshape(a.shape) # Threshold coefficients. a_new = thresh(a, threshold, thresh_type) # Return the thresholded image. return np.dot(u, a_new)
[ "def", "svd_thresh_coef", "(", "data", ",", "operator", ",", "threshold", ",", "thresh_type", "=", "'hard'", ")", ":", "if", "not", "callable", "(", "operator", ")", ":", "raise", "TypeError", "(", "'Operator must be a callable function.'", ")", "# Get SVD of data...
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 value(s) threshold_type : str {'hard', 'soft'} Type of noise to be added (default is 'hard') Returns ------- np.ndarray thresholded data Raises ------ ValueError For invalid string entry for n_pc
[ "Threshold", "the", "singular", "values", "coefficients" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/svd.py#L171-L222
train
25,381
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 {'max', 'sum', 'none'}, optional Normalisation of the kerenl (options are 'max', 'sum' or 'none') Returns ------- np.ndarray kernel Examples -------- >>> from modopt.math.stats import gaussian_kernel >>> gaussian_kernel((3, 3), 1) array([[ 0.36787944, 0.60653066, 0.36787944], [ 0.60653066, 1. , 0.60653066], [ 0.36787944, 0.60653066, 0.36787944]]) >>> gaussian_kernel((3, 3), 1, norm='sum') array([[ 0.07511361, 0.1238414 , 0.07511361], [ 0.1238414 , 0.20417996, 0.1238414 ], [ 0.07511361, 0.1238414 , 0.07511361]]) """ if not import_astropy: # pragma: no cover raise ImportError('Astropy package not found.') if norm not in ('max', 'sum', 'none'): raise ValueError('Invalid norm, options are "max", "sum" or "none".') kernel = np.array(Gaussian2DKernel(sigma, x_size=data_shape[1], y_size=data_shape[0])) if norm == 'max': return kernel / np.max(kernel) elif norm == 'sum': return kernel / np.sum(kernel) elif norm == 'none': return kernel
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 {'max', 'sum', 'none'}, optional Normalisation of the kerenl (options are 'max', 'sum' or 'none') Returns ------- np.ndarray kernel Examples -------- >>> from modopt.math.stats import gaussian_kernel >>> gaussian_kernel((3, 3), 1) array([[ 0.36787944, 0.60653066, 0.36787944], [ 0.60653066, 1. , 0.60653066], [ 0.36787944, 0.60653066, 0.36787944]]) >>> gaussian_kernel((3, 3), 1, norm='sum') array([[ 0.07511361, 0.1238414 , 0.07511361], [ 0.1238414 , 0.20417996, 0.1238414 ], [ 0.07511361, 0.1238414 , 0.07511361]]) """ if not import_astropy: # pragma: no cover raise ImportError('Astropy package not found.') if norm not in ('max', 'sum', 'none'): raise ValueError('Invalid norm, options are "max", "sum" or "none".') kernel = np.array(Gaussian2DKernel(sigma, x_size=data_shape[1], y_size=data_shape[0])) if norm == 'max': return kernel / np.max(kernel) elif norm == 'sum': return kernel / np.sum(kernel) elif norm == 'none': return kernel
[ "def", "gaussian_kernel", "(", "data_shape", ",", "sigma", ",", "norm", "=", "'max'", ")", ":", "if", "not", "import_astropy", ":", "# pragma: no cover", "raise", "ImportError", "(", "'Astropy package not found.'", ")", "if", "norm", "not", "in", "(", "'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 {'max', 'sum', 'none'}, optional Normalisation of the kerenl (options are 'max', 'sum' or 'none') Returns ------- np.ndarray kernel Examples -------- >>> from modopt.math.stats import gaussian_kernel >>> gaussian_kernel((3, 3), 1) array([[ 0.36787944, 0.60653066, 0.36787944], [ 0.60653066, 1. , 0.60653066], [ 0.36787944, 0.60653066, 0.36787944]]) >>> gaussian_kernel((3, 3), 1, norm='sum') array([[ 0.07511361, 0.1238414 , 0.07511361], [ 0.1238414 , 0.20417996, 0.1238414 ], [ 0.07511361, 0.1238414 , 0.07511361]])
[ "r", "Gaussian", "kernel" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/stats.py#L23-L72
train
25,382
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 >>> a = np.arange(9).reshape(3, 3) >>> mad(a) 2.0 Notes ----- The MAD is calculated as follows: .. math:: \mathrm{MAD} = \mathrm{median}\left(|X_i - \mathrm{median}(X)|\right) """ return np.median(np.abs(data - np.median(data)))
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 >>> a = np.arange(9).reshape(3, 3) >>> mad(a) 2.0 Notes ----- The MAD is calculated as follows: .. math:: \mathrm{MAD} = \mathrm{median}\left(|X_i - \mathrm{median}(X)|\right) """ return np.median(np.abs(data - np.median(data)))
[ "def", "mad", "(", "data", ")", ":", "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(9).reshape(3, 3) >>> mad(a) 2.0 Notes ----- The MAD is calculated as follows: .. math:: \mathrm{MAD} = \mathrm{median}\left(|X_i - \mathrm{median}(X)|\right)
[ "r", "Median", "absolute", "deviation" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/stats.py#L75-L106
train
25,383
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 {'starck', 'wiki'}, optional PSNR implementation, default ('starck') max_pix : int, optional Maximum number of pixels, default (max_pix=255) Returns ------- float PSNR value Examples -------- >>> from modopt.math.stats import psnr >>> a = np.arange(9).reshape(3, 3) >>> psnr(a, a + 2) 12.041199826559248 >>> psnr(a, a + 2, method='wiki') 42.110203695399477 Notes ----- 'starck': Implements eq.3.7 from _[S2010] 'wiki': Implements PSNR equation on https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio .. math:: \mathrm{PSNR} = 20\log_{10}(\mathrm{MAX}_I - 10\log_{10}(\mathrm{MSE})) """ if method == 'starck': return (20 * np.log10((data1.shape[0] * np.abs(np.max(data1) - np.min(data1))) / np.linalg.norm(data1 - data2))) elif method == 'wiki': return (20 * np.log10(max_pix) - 10 * np.log10(mse(data1, data2))) else: raise ValueError('Invalid PSNR method. Options are "starck" and ' '"wiki"')
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 {'starck', 'wiki'}, optional PSNR implementation, default ('starck') max_pix : int, optional Maximum number of pixels, default (max_pix=255) Returns ------- float PSNR value Examples -------- >>> from modopt.math.stats import psnr >>> a = np.arange(9).reshape(3, 3) >>> psnr(a, a + 2) 12.041199826559248 >>> psnr(a, a + 2, method='wiki') 42.110203695399477 Notes ----- 'starck': Implements eq.3.7 from _[S2010] 'wiki': Implements PSNR equation on https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio .. math:: \mathrm{PSNR} = 20\log_{10}(\mathrm{MAX}_I - 10\log_{10}(\mathrm{MSE})) """ if method == 'starck': return (20 * np.log10((data1.shape[0] * np.abs(np.max(data1) - np.min(data1))) / np.linalg.norm(data1 - data2))) elif method == 'wiki': return (20 * np.log10(max_pix) - 10 * np.log10(mse(data1, data2))) else: raise ValueError('Invalid PSNR method. Options are "starck" and ' '"wiki"')
[ "def", "psnr", "(", "data1", ",", "data2", ",", "method", "=", "'starck'", ",", "max_pix", "=", "255", ")", ":", "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, default ('starck') max_pix : int, optional Maximum number of pixels, default (max_pix=255) Returns ------- float PSNR value Examples -------- >>> from modopt.math.stats import psnr >>> a = np.arange(9).reshape(3, 3) >>> psnr(a, a + 2) 12.041199826559248 >>> psnr(a, a + 2, method='wiki') 42.110203695399477 Notes ----- 'starck': Implements eq.3.7 from _[S2010] 'wiki': Implements PSNR equation on https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio .. math:: \mathrm{PSNR} = 20\log_{10}(\mathrm{MAX}_I - 10\log_{10}(\mathrm{MSE}))
[ "r", "Peak", "Signal", "-", "to", "-", "Noise", "Ratio" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/stats.py#L133-L195
train
25,384
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 : np.ndarray Stack of images, 3D array data2 : np.ndarray Stack of recovered images, 3D array method : str {'starck', 'wiki'}, optional PSNR implementation, default ('starck') metric : function The desired metric to be applied to the PSNR values (default is 'np.mean') Returns ------- float metric result of PSNR values Raises ------ ValueError For invalid input data dimensions Examples -------- >>> from modopt.math.stats import psnr_stack >>> a = np.arange(18).reshape(2, 3, 3) >>> psnr_stack(a, a + 2) 12.041199826559248 """ if data1.ndim != 3 or data2.ndim != 3: raise ValueError('Input data must be a 3D np.ndarray') return metric([psnr(i, j, method=method) for i, j in zip(data1, data2)])
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 : np.ndarray Stack of images, 3D array data2 : np.ndarray Stack of recovered images, 3D array method : str {'starck', 'wiki'}, optional PSNR implementation, default ('starck') metric : function The desired metric to be applied to the PSNR values (default is 'np.mean') Returns ------- float metric result of PSNR values Raises ------ ValueError For invalid input data dimensions Examples -------- >>> from modopt.math.stats import psnr_stack >>> a = np.arange(18).reshape(2, 3, 3) >>> psnr_stack(a, a + 2) 12.041199826559248 """ if data1.ndim != 3 or data2.ndim != 3: raise ValueError('Input data must be a 3D np.ndarray') return metric([psnr(i, j, method=method) for i, j in zip(data1, data2)])
[ "def", "psnr_stack", "(", "data1", ",", "data2", ",", "metric", "=", "np", ".", "mean", ",", "method", "=", "'starck'", ")", ":", "if", "data1", ".", "ndim", "!=", "3", "or", "data2", ".", "ndim", "!=", "3", ":", "raise", "ValueError", "(", "'Input...
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.ndarray Stack of recovered images, 3D array method : str {'starck', 'wiki'}, optional PSNR implementation, default ('starck') metric : function The desired metric to be applied to the PSNR values (default is 'np.mean') Returns ------- float metric result of PSNR values Raises ------ ValueError For invalid input data dimensions Examples -------- >>> from modopt.math.stats import psnr_stack >>> a = np.arange(18).reshape(2, 3, 3) >>> psnr_stack(a, a + 2) 12.041199826559248
[ "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
25,385
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 ------- np.ndarray 2D map Raises ------ ValueError For invalid data dimensions ValueError For invalid layout Examples -------- >>> from modopt.base.transform import cube2map >>> a = np.arange(16).reshape((4, 2, 2)) >>> cube2map(a, (2, 2)) array([[ 0, 1, 4, 5], [ 2, 3, 6, 7], [ 8, 9, 12, 13], [10, 11, 14, 15]]) """ if data_cube.ndim != 3: raise ValueError('The input data must have 3 dimensions.') if data_cube.shape[0] != np.prod(layout): raise ValueError('The desired layout must match the number of input ' 'data layers.') return np.vstack([np.hstack(data_cube[slice(layout[1] * i, layout[1] * (i + 1))]) for i in range(layout[0])])
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 ------- np.ndarray 2D map Raises ------ ValueError For invalid data dimensions ValueError For invalid layout Examples -------- >>> from modopt.base.transform import cube2map >>> a = np.arange(16).reshape((4, 2, 2)) >>> cube2map(a, (2, 2)) array([[ 0, 1, 4, 5], [ 2, 3, 6, 7], [ 8, 9, 12, 13], [10, 11, 14, 15]]) """ if data_cube.ndim != 3: raise ValueError('The input data must have 3 dimensions.') if data_cube.shape[0] != np.prod(layout): raise ValueError('The desired layout must match the number of input ' 'data layers.') return np.vstack([np.hstack(data_cube[slice(layout[1] * i, layout[1] * (i + 1))]) for i in range(layout[0])])
[ "def", "cube2map", "(", "data_cube", ",", "layout", ")", ":", "if", "data_cube", ".", "ndim", "!=", "3", ":", "raise", "ValueError", "(", "'The input data must have 3 dimensions.'", ")", "if", "data_cube", ".", "shape", "[", "0", "]", "!=", "np", ".", "pro...
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 Raises ------ ValueError For invalid data dimensions ValueError For invalid layout Examples -------- >>> from modopt.base.transform import cube2map >>> a = np.arange(16).reshape((4, 2, 2)) >>> cube2map(a, (2, 2)) array([[ 0, 1, 4, 5], [ 2, 3, 6, 7], [ 8, 9, 12, 13], [10, 11, 14, 15]])
[ "r", "Cube", "to", "Map" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L16-L60
train
25,386
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.ndarray 3D cube Raises ------ ValueError For invalid layout Examples -------- >>> from modopt.base.transform import map2cube >>> a = np.array([[0, 1, 4, 5], [2, 3, 6, 7], [8, 9, 12, 13], [10, 11, 14, 15]]) >>> map2cube(a, (2, 2)) array([[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]], [[ 8, 9], [10, 11]], [[12, 13], [14, 15]]]) """ if np.all(np.array(data_map.shape) % np.array(layout)): raise ValueError('The desired layout must be a multiple of the number ' 'pixels in the data map.') d_shape = np.array(data_map.shape) // np.array(layout) return np.array([data_map[(slice(i * d_shape[0], (i + 1) * d_shape[0]), slice(j * d_shape[1], (j + 1) * d_shape[1]))] for i in range(layout[0]) for j in range(layout[1])])
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.ndarray 3D cube Raises ------ ValueError For invalid layout Examples -------- >>> from modopt.base.transform import map2cube >>> a = np.array([[0, 1, 4, 5], [2, 3, 6, 7], [8, 9, 12, 13], [10, 11, 14, 15]]) >>> map2cube(a, (2, 2)) array([[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]], [[ 8, 9], [10, 11]], [[12, 13], [14, 15]]]) """ if np.all(np.array(data_map.shape) % np.array(layout)): raise ValueError('The desired layout must be a multiple of the number ' 'pixels in the data map.') d_shape = np.array(data_map.shape) // np.array(layout) return np.array([data_map[(slice(i * d_shape[0], (i + 1) * d_shape[0]), slice(j * d_shape[1], (j + 1) * d_shape[1]))] for i in range(layout[0]) for j in range(layout[1])])
[ "def", "map2cube", "(", "data_map", ",", "layout", ")", ":", "if", "np", ".", "all", "(", "np", ".", "array", "(", "data_map", ".", "shape", ")", "%", "np", ".", "array", "(", "layout", ")", ")", ":", "raise", "ValueError", "(", "'The desired 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.ndarray 3D cube Raises ------ ValueError For invalid layout Examples -------- >>> from modopt.base.transform import map2cube >>> a = np.array([[0, 1, 4, 5], [2, 3, 6, 7], [8, 9, 12, 13], [10, 11, 14, 15]]) >>> map2cube(a, (2, 2)) array([[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]], [[ 8, 9], [10, 11]], [[12, 13], [14, 15]]])
[ "r", "Map", "to", "cube" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L63-L113
train
25,387
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 ------ ValueError For invalid layout Examples -------- >>> from modopt.base.transform import map2matrix >>> a = np.array([[0, 1, 4, 5], [2, 3, 6, 7], [8, 9, 12, 13], [10, 11, 14, 15]]) >>> map2matrix(a, (2, 2)) array([[ 0, 4, 8, 12], [ 1, 5, 9, 13], [ 2, 6, 10, 14], [ 3, 7, 11, 15]]) """ layout = np.array(layout) # Select n objects n_obj = np.prod(layout) # Get the shape of the images image_shape = (np.array(data_map.shape) // layout)[0] # Stack objects from map data_matrix = [] for i in range(n_obj): lower = (image_shape * (i // layout[1]), image_shape * (i % layout[1])) upper = (image_shape * (i // layout[1] + 1), image_shape * (i % layout[1] + 1)) data_matrix.append((data_map[lower[0]:upper[0], lower[1]:upper[1]]).reshape(image_shape ** 2)) return np.array(data_matrix).T
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 ------ ValueError For invalid layout Examples -------- >>> from modopt.base.transform import map2matrix >>> a = np.array([[0, 1, 4, 5], [2, 3, 6, 7], [8, 9, 12, 13], [10, 11, 14, 15]]) >>> map2matrix(a, (2, 2)) array([[ 0, 4, 8, 12], [ 1, 5, 9, 13], [ 2, 6, 10, 14], [ 3, 7, 11, 15]]) """ layout = np.array(layout) # Select n objects n_obj = np.prod(layout) # Get the shape of the images image_shape = (np.array(data_map.shape) // layout)[0] # Stack objects from map data_matrix = [] for i in range(n_obj): lower = (image_shape * (i // layout[1]), image_shape * (i % layout[1])) upper = (image_shape * (i // layout[1] + 1), image_shape * (i % layout[1] + 1)) data_matrix.append((data_map[lower[0]:upper[0], lower[1]:upper[1]]).reshape(image_shape ** 2)) return np.array(data_matrix).T
[ "def", "map2matrix", "(", "data_map", ",", "layout", ")", ":", "layout", "=", "np", ".", "array", "(", "layout", ")", "# Select n objects", "n_obj", "=", "np", ".", "prod", "(", "layout", ")", "# Get the shape of the images", "image_shape", "=", "(", "np", ...
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 layout Examples -------- >>> from modopt.base.transform import map2matrix >>> a = np.array([[0, 1, 4, 5], [2, 3, 6, 7], [8, 9, 12, 13], [10, 11, 14, 15]]) >>> map2matrix(a, (2, 2)) array([[ 0, 4, 8, 12], [ 1, 5, 9, 13], [ 2, 6, 10, 14], [ 3, 7, 11, 15]])
[ "r", "Map", "to", "Matrix" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L116-L169
train
25,388
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 Raises ------ ValueError For invalid layout Examples -------- >>> from modopt.base.transform import matrix2map >>> a = np.array([[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15]]) >>> matrix2map(a, (2, 2)) array([[ 0, 1, 4, 5], [ 2, 3, 6, 7], [ 8, 9, 12, 13], [10, 11, 14, 15]]) """ map_shape = np.array(map_shape) # Get the shape and layout of the images image_shape = np.sqrt(data_matrix.shape[0]).astype(int) layout = np.array(map_shape // np.repeat(image_shape, 2), dtype='int') # Map objects from matrix data_map = np.zeros(map_shape) temp = data_matrix.reshape(image_shape, image_shape, data_matrix.shape[1]) for i in range(data_matrix.shape[1]): lower = (image_shape * (i // layout[1]), image_shape * (i % layout[1])) upper = (image_shape * (i // layout[1] + 1), image_shape * (i % layout[1] + 1)) data_map[lower[0]:upper[0], lower[1]:upper[1]] = temp[:, :, i] return data_map.astype(int)
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 Raises ------ ValueError For invalid layout Examples -------- >>> from modopt.base.transform import matrix2map >>> a = np.array([[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15]]) >>> matrix2map(a, (2, 2)) array([[ 0, 1, 4, 5], [ 2, 3, 6, 7], [ 8, 9, 12, 13], [10, 11, 14, 15]]) """ map_shape = np.array(map_shape) # Get the shape and layout of the images image_shape = np.sqrt(data_matrix.shape[0]).astype(int) layout = np.array(map_shape // np.repeat(image_shape, 2), dtype='int') # Map objects from matrix data_map = np.zeros(map_shape) temp = data_matrix.reshape(image_shape, image_shape, data_matrix.shape[1]) for i in range(data_matrix.shape[1]): lower = (image_shape * (i // layout[1]), image_shape * (i % layout[1])) upper = (image_shape * (i // layout[1] + 1), image_shape * (i % layout[1] + 1)) data_map[lower[0]:upper[0], lower[1]:upper[1]] = temp[:, :, i] return data_map.astype(int)
[ "def", "matrix2map", "(", "data_matrix", ",", "map_shape", ")", ":", "map_shape", "=", "np", ".", "array", "(", "map_shape", ")", "# Get the shape and layout of the images", "image_shape", "=", "np", ".", "sqrt", "(", "data_matrix", ".", "shape", "[", "0", "]"...
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 invalid layout Examples -------- >>> from modopt.base.transform import matrix2map >>> a = np.array([[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15]]) >>> matrix2map(a, (2, 2)) array([[ 0, 1, 4, 5], [ 2, 3, 6, 7], [ 8, 9, 12, 13], [10, 11, 14, 15]])
[ "r", "Matrix", "to", "Map" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L172-L224
train
25,389
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 cube2matrix >>> a = np.arange(16).reshape((4, 2, 2)) >>> cube2matrix(a) array([[ 0, 4, 8, 12], [ 1, 5, 9, 13], [ 2, 6, 10, 14], [ 3, 7, 11, 15]]) """ return data_cube.reshape([data_cube.shape[0]] + [np.prod(data_cube.shape[1:])]).T
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 cube2matrix >>> a = np.arange(16).reshape((4, 2, 2)) >>> cube2matrix(a) array([[ 0, 4, 8, 12], [ 1, 5, 9, 13], [ 2, 6, 10, 14], [ 3, 7, 11, 15]]) """ return data_cube.reshape([data_cube.shape[0]] + [np.prod(data_cube.shape[1:])]).T
[ "def", "cube2matrix", "(", "data_cube", ")", ":", "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).reshape((4, 2, 2)) >>> cube2matrix(a) array([[ 0, 4, 8, 12], [ 1, 5, 9, 13], [ 2, 6, 10, 14], [ 3, 7, 11, 15]])
[ "r", "Cube", "to", "Matrix" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L227-L254
train
25,390
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 Examples -------- >>> from modopt.base.transform import matrix2cube >>> a = np.array([[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15]]) >>> matrix2cube(a, (2, 2)) array([[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]], [[ 8, 9], [10, 11]], [[12, 13], [14, 15]]]) """ return data_matrix.T.reshape([data_matrix.shape[1]] + list(im_shape))
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 Examples -------- >>> from modopt.base.transform import matrix2cube >>> a = np.array([[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15]]) >>> matrix2cube(a, (2, 2)) array([[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]], [[ 8, 9], [10, 11]], [[12, 13], [14, 15]]]) """ return data_matrix.T.reshape([data_matrix.shape[1]] + list(im_shape))
[ "def", "matrix2cube", "(", "data_matrix", ",", "im_shape", ")", ":", "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 modopt.base.transform import matrix2cube >>> a = np.array([[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15]]) >>> matrix2cube(a, (2, 2)) array([[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]], [[ 8, 9], [10, 11]], [[12, 13], [14, 15]]])
[ "r", "Matrix", "to", "Cube" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L257-L293
train
25,391
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)): file_name = 'cost_function.png' else: file_name = output + '_cost_function.png' plt.figure() plt.plot(np.log10(cost_list), 'r-') plt.title('Cost Function') plt.xlabel('Iteration') plt.ylabel(r'$\log_{10}$ Cost') plt.savefig(file_name) plt.close() print(' - Saving cost function data to:', file_name) else: warn('Matplotlib not installed.')
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)): file_name = 'cost_function.png' else: file_name = output + '_cost_function.png' plt.figure() plt.plot(np.log10(cost_list), 'r-') plt.title('Cost Function') plt.xlabel('Iteration') plt.ylabel(r'$\log_{10}$ Cost') plt.savefig(file_name) plt.close() print(' - Saving cost function data to:', file_name) else: warn('Matplotlib not installed.')
[ "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
25,392
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) Returns ------- float Gaussian filtered data point Examples -------- >>> from modopt.signal.filter import Gaussian_filter >>> Gaussian_filter(1, 1) 0.24197072451914337 >>> Gaussian_filter(1, 1, False) 0.60653065971263342 """ x = check_float(x) sigma = check_float(sigma) val = np.exp(-0.5 * (x / sigma) ** 2) if norm: return val / (np.sqrt(2 * np.pi) * sigma) else: return val
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) Returns ------- float Gaussian filtered data point Examples -------- >>> from modopt.signal.filter import Gaussian_filter >>> Gaussian_filter(1, 1) 0.24197072451914337 >>> Gaussian_filter(1, 1, False) 0.60653065971263342 """ x = check_float(x) sigma = check_float(sigma) val = np.exp(-0.5 * (x / sigma) ** 2) if norm: return val / (np.sqrt(2 * np.pi) * sigma) else: return val
[ "def", "Gaussian_filter", "(", "x", ",", "sigma", ",", "norm", "=", "True", ")", ":", "x", "=", "check_float", "(", "x", ")", "sigma", "=", "check_float", "(", "sigma", ")", "val", "=", "np", ".", "exp", "(", "-", "0.5", "*", "(", "x", "/", "si...
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 filtered data point Examples -------- >>> from modopt.signal.filter import Gaussian_filter >>> Gaussian_filter(1, 1) 0.24197072451914337 >>> Gaussian_filter(1, 1, False) 0.60653065971263342
[ "r", "Gaussian", "filter" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/filter.py#L16-L54
train
25,393
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 -------- >>> from modopt.signal.filter import mex_hat >>> mex_hat(2, 1) -0.35213905225713371 """ x = check_float(x) sigma = check_float(sigma) xs = (x / sigma) ** 2 val = 2 * (3 * sigma) ** -0.5 * np.pi ** -0.25 return val * (1 - xs) * np.exp(-0.5 * xs)
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 -------- >>> from modopt.signal.filter import mex_hat >>> mex_hat(2, 1) -0.35213905225713371 """ x = check_float(x) sigma = check_float(sigma) xs = (x / sigma) ** 2 val = 2 * (3 * sigma) ** -0.5 * np.pi ** -0.25 return val * (1 - xs) * np.exp(-0.5 * xs)
[ "def", "mex_hat", "(", "x", ",", "sigma", ")", ":", "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 modopt.signal.filter import mex_hat >>> mex_hat(2, 1) -0.35213905225713371
[ "r", "Mexican", "hat" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/filter.py#L57-L87
train
25,394
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 (filter scale) Returns ------- float directional Mexican hat filtered data point Examples -------- >>> from modopt.signal.filter import mex_hat_dir >>> mex_hat_dir(1, 2, 1) 0.17606952612856686 """ x = check_float(x) sigma = check_float(sigma) return -0.5 * (x / sigma) ** 2 * mex_hat(y, sigma)
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 (filter scale) Returns ------- float directional Mexican hat filtered data point Examples -------- >>> from modopt.signal.filter import mex_hat_dir >>> mex_hat_dir(1, 2, 1) 0.17606952612856686 """ x = check_float(x) sigma = check_float(sigma) return -0.5 * (x / sigma) ** 2 * mex_hat(y, sigma)
[ "def", "mex_hat_dir", "(", "x", ",", "y", ",", "sigma", ")", ":", "x", "=", "check_float", "(", "x", ")", "sigma", "=", "check_float", "(", "sigma", ")", "return", "-", "0.5", "*", "(", "x", "/", "sigma", ")", "**", "2", "*", "mex_hat", "(", "y...
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 ------- float directional Mexican hat filtered data point Examples -------- >>> from modopt.signal.filter import mex_hat_dir >>> mex_hat_dir(1, 2, 1) 0.17606952612856686
[ "r", "Directional", "Mexican", "hat" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/filter.py#L90-L119
train
25,395
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 : np.ndarray Input kernel array, normally a 2D kernel method : str {'astropy', 'scipy'}, optional Convolution method (default is 'scipy') Returns ------- np.ndarray convolved data Raises ------ ValueError If `data` and `kernel` do not have the same number of dimensions ValueError If `method` is not 'astropy' or 'scipy' Notes ----- The convolution methods are: 'astropy': Uses the astropy.convolution.convolve_fft method provided in Astropy (http://www.astropy.org/) 'scipy': Uses the scipy.signal.fftconvolve method provided in SciPy (https://www.scipy.org/) Examples -------- >>> from math.convolve import convolve >>> import numpy as np >>> a = np.arange(9).reshape(3, 3) >>> b = a + 10 >>> convolve(a, b) array([[ 534., 525., 534.], [ 453., 444., 453.], [ 534., 525., 534.]]) >>> convolve(a, b, method='scipy') array([[ 86., 170., 146.], [ 246., 444., 354.], [ 290., 494., 374.]]) """ if data.ndim != kernel.ndim: raise ValueError('Data and kernel must have the same dimensions.') if method not in ('astropy', 'scipy'): raise ValueError('Invalid method. Options are "astropy" or "scipy".') if not import_astropy: # pragma: no cover method = 'scipy' if method == 'astropy': return convolve_fft(data, kernel, boundary='wrap', crop=False, nan_treatment='fill', normalize_kernel=False) elif method == 'scipy': return scipy.signal.fftconvolve(data, kernel, mode='same')
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 : np.ndarray Input kernel array, normally a 2D kernel method : str {'astropy', 'scipy'}, optional Convolution method (default is 'scipy') Returns ------- np.ndarray convolved data Raises ------ ValueError If `data` and `kernel` do not have the same number of dimensions ValueError If `method` is not 'astropy' or 'scipy' Notes ----- The convolution methods are: 'astropy': Uses the astropy.convolution.convolve_fft method provided in Astropy (http://www.astropy.org/) 'scipy': Uses the scipy.signal.fftconvolve method provided in SciPy (https://www.scipy.org/) Examples -------- >>> from math.convolve import convolve >>> import numpy as np >>> a = np.arange(9).reshape(3, 3) >>> b = a + 10 >>> convolve(a, b) array([[ 534., 525., 534.], [ 453., 444., 453.], [ 534., 525., 534.]]) >>> convolve(a, b, method='scipy') array([[ 86., 170., 146.], [ 246., 444., 354.], [ 290., 494., 374.]]) """ if data.ndim != kernel.ndim: raise ValueError('Data and kernel must have the same dimensions.') if method not in ('astropy', 'scipy'): raise ValueError('Invalid method. Options are "astropy" or "scipy".') if not import_astropy: # pragma: no cover method = 'scipy' if method == 'astropy': return convolve_fft(data, kernel, boundary='wrap', crop=False, nan_treatment='fill', normalize_kernel=False) elif method == 'scipy': return scipy.signal.fftconvolve(data, kernel, mode='same')
[ "def", "convolve", "(", "data", ",", "kernel", ",", "method", "=", "'scipy'", ")", ":", "if", "data", ".", "ndim", "!=", "kernel", ".", "ndim", ":", "raise", "ValueError", "(", "'Data and kernel must have the same dimensions.'", ")", "if", "method", "not", "...
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 2D kernel method : str {'astropy', 'scipy'}, optional Convolution method (default is 'scipy') Returns ------- np.ndarray convolved data Raises ------ ValueError If `data` and `kernel` do not have the same number of dimensions ValueError If `method` is not 'astropy' or 'scipy' Notes ----- The convolution methods are: 'astropy': Uses the astropy.convolution.convolve_fft method provided in Astropy (http://www.astropy.org/) 'scipy': Uses the scipy.signal.fftconvolve method provided in SciPy (https://www.scipy.org/) Examples -------- >>> from math.convolve import convolve >>> import numpy as np >>> a = np.arange(9).reshape(3, 3) >>> b = a + 10 >>> convolve(a, b) array([[ 534., 525., 534.], [ 453., 444., 453.], [ 534., 525., 534.]]) >>> convolve(a, b, method='scipy') array([[ 86., 170., 146.], [ 246., 444., 354.], [ 290., 494., 374.]])
[ "r", "Convolve", "data", "with", "kernel" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/convolve.py#L33-L103
train
25,396
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 data array, normally a 2D image kernel : np.ndarray Input kernel array, normally a 2D kernel rot_kernel : bool Option to rotate kernels by 180 degrees method : str {'astropy', 'scipy'}, optional Convolution method (default is 'scipy') Returns ------- np.ndarray convolved data Examples -------- >>> from math.convolve import convolve >>> import numpy as np >>> a = np.arange(18).reshape(2, 3, 3) >>> b = a + 10 >>> convolve_stack(a, b) array([[[ 534., 525., 534.], [ 453., 444., 453.], [ 534., 525., 534.]], <BLANKLINE> [[ 2721., 2712., 2721.], [ 2640., 2631., 2640.], [ 2721., 2712., 2721.]]]) >>> convolve_stack(a, b, rot_kernel=True) array([[[ 474., 483., 474.], [ 555., 564., 555.], [ 474., 483., 474.]], <BLANKLINE> [[ 2661., 2670., 2661.], [ 2742., 2751., 2742.], [ 2661., 2670., 2661.]]]) See Also -------- convolve : The convolution function called by convolve_stack """ if rot_kernel: kernel = rotate_stack(kernel) return np.array([convolve(data_i, kernel_i, method=method) for data_i, kernel_i in zip(data, kernel)])
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 data array, normally a 2D image kernel : np.ndarray Input kernel array, normally a 2D kernel rot_kernel : bool Option to rotate kernels by 180 degrees method : str {'astropy', 'scipy'}, optional Convolution method (default is 'scipy') Returns ------- np.ndarray convolved data Examples -------- >>> from math.convolve import convolve >>> import numpy as np >>> a = np.arange(18).reshape(2, 3, 3) >>> b = a + 10 >>> convolve_stack(a, b) array([[[ 534., 525., 534.], [ 453., 444., 453.], [ 534., 525., 534.]], <BLANKLINE> [[ 2721., 2712., 2721.], [ 2640., 2631., 2640.], [ 2721., 2712., 2721.]]]) >>> convolve_stack(a, b, rot_kernel=True) array([[[ 474., 483., 474.], [ 555., 564., 555.], [ 474., 483., 474.]], <BLANKLINE> [[ 2661., 2670., 2661.], [ 2742., 2751., 2742.], [ 2661., 2670., 2661.]]]) See Also -------- convolve : The convolution function called by convolve_stack """ if rot_kernel: kernel = rotate_stack(kernel) return np.array([convolve(data_i, kernel_i, method=method) for data_i, kernel_i in zip(data, kernel)])
[ "def", "convolve_stack", "(", "data", ",", "kernel", ",", "rot_kernel", "=", "False", ",", "method", "=", "'scipy'", ")", ":", "if", "rot_kernel", ":", "kernel", "=", "rotate_stack", "(", "kernel", ")", "return", "np", ".", "array", "(", "[", "convolve",...
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 kernel array, normally a 2D kernel rot_kernel : bool Option to rotate kernels by 180 degrees method : str {'astropy', 'scipy'}, optional Convolution method (default is 'scipy') Returns ------- np.ndarray convolved data Examples -------- >>> from math.convolve import convolve >>> import numpy as np >>> a = np.arange(18).reshape(2, 3, 3) >>> b = a + 10 >>> convolve_stack(a, b) array([[[ 534., 525., 534.], [ 453., 444., 453.], [ 534., 525., 534.]], <BLANKLINE> [[ 2721., 2712., 2721.], [ 2640., 2631., 2640.], [ 2721., 2712., 2721.]]]) >>> convolve_stack(a, b, rot_kernel=True) array([[[ 474., 483., 474.], [ 555., 564., 555.], [ 474., 483., 474.]], <BLANKLINE> [[ 2661., 2670., 2661.], [ 2742., 2751., 2742.], [ 2661., 2670., 2661.]]]) See Also -------- convolve : The convolution function called by convolve_stack
[ "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
25,397
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 add_agrs : bool, optional Option to add support for agrs and kwargs Returns ------- func wrapped by `add_args_kwargs` Raises ------ TypeError For invalid input type """ if not callable(val): raise TypeError('The input object must be a callable function.') if add_agrs: val = add_args_kwargs(val) return val
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 add_agrs : bool, optional Option to add support for agrs and kwargs Returns ------- func wrapped by `add_args_kwargs` Raises ------ TypeError For invalid input type """ if not callable(val): raise TypeError('The input object must be a callable function.') if add_agrs: val = add_args_kwargs(val) return val
[ "def", "check_callable", "(", "val", ",", "add_agrs", "=", "True", ")", ":", "if", "not", "callable", "(", "val", ")", ":", "raise", "TypeError", "(", "'The input object must be a callable function.'", ")", "if", "add_agrs", ":", "val", "=", "add_args_kwargs", ...
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 Option to add support for agrs and kwargs Returns ------- func wrapped by `add_args_kwargs` Raises ------ TypeError For invalid input type
[ "r", "Check", "input", "object", "is", "callable" ]
019b189cb897cbb4d210c44a100daaa08468830c
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/types.py#L16-L47
train
25,398
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 = np.arange(5) >>> a array([0, 1, 2, 3, 4]) >>> check_float(a) array([ 0., 1., 2., 3., 4.]) """ if not isinstance(val, (int, float, list, tuple, np.ndarray)): raise TypeError('Invalid input type.') if isinstance(val, int): val = float(val) elif isinstance(val, (list, tuple)): val = np.array(val, dtype=float) elif isinstance(val, np.ndarray) and (not np.issubdtype(val.dtype, np.floating)): val = val.astype(float) return val
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 = np.arange(5) >>> a array([0, 1, 2, 3, 4]) >>> check_float(a) array([ 0., 1., 2., 3., 4.]) """ if not isinstance(val, (int, float, list, tuple, np.ndarray)): raise TypeError('Invalid input type.') if isinstance(val, int): val = float(val) elif isinstance(val, (list, tuple)): val = np.array(val, dtype=float) elif isinstance(val, np.ndarray) and (not np.issubdtype(val.dtype, np.floating)): val = val.astype(float) return val
[ "def", "check_float", "(", "val", ")", ":", "if", "not", "isinstance", "(", "val", ",", "(", "int", ",", "float", ",", "list", ",", "tuple", ",", "np", ".", "ndarray", ")", ")", ":", "raise", "TypeError", "(", "'Invalid input type.'", ")", "if", "isi...
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 array([0, 1, 2, 3, 4]) >>> check_float(a) array([ 0., 1., 2., 3., 4.])
[ "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
25,399