idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
25,300
def update ( self , portfolio , date , perfs = None ) : self . portfolio = portfolio self . perfs = perfs self . date = date
Actualizes the portfolio universe with the alog state
25,301
def trade_signals_handler ( self , signals ) : alloc = { } if signals [ 'buy' ] or signals [ 'sell' ] : try : alloc , e_ret , e_risk = self . optimize ( self . date , signals [ 'buy' ] , signals [ 'sell' ] , self . _optimizer_parameters ) except Exception , error : raise PortfolioOptimizationFailed ( reason = error , d...
Process buy and sell signals from the simulation
25,302
def historical_pandas_yahoo ( symbol , source = 'yahoo' , start = None , end = None ) : return DataReader ( symbol , source , start = start , end = end )
Fetch from yahoo! finance historical quotes
25,303
def average_returns ( ts , ** kwargs ) : average_type = kwargs . get ( 'type' , 'net' ) if average_type == 'net' : relative = 0 else : relative = - 1 period = kwargs . get ( 'period' , None ) if isinstance ( period , int ) : pass avg_ret = 1 for idx in range ( len ( ts . index ) ) : if idx % period == 0 : avg_ret *= ( ...
Compute geometric average returns from a returns time serie
25,304
def returns ( ts , ** kwargs ) : returns_type = kwargs . get ( 'type' , 'net' ) cumulative = kwargs . get ( 'cumulative' , False ) if returns_type == 'net' : relative = 0 else : relative = 1 start = kwargs . get ( 'start' , None ) end = kwargs . get ( 'end' , dt . datetime . today ( ) ) period = kwargs . get ( 'period'...
Compute returns on the given period
25,305
def daily_returns ( ts , ** kwargs ) : relative = kwargs . get ( 'relative' , 0 ) return returns ( ts , delta = BDay ( ) , relative = relative )
re - compute ts on a daily basis
25,306
def list_files ( path , extension = ".cpp" , exclude = "S.cpp" ) : return [ "%s/%s" % ( path , f ) for f in listdir ( path ) if f . endswith ( extension ) and ( not f . endswith ( exclude ) ) ]
List paths to all files that ends with a given extension
25,307
def intuition ( args ) : with setup . Context ( args [ 'context' ] ) as context : simulation = Simulation ( ) modules = context [ 'config' ] [ 'modules' ] simulation . configure_environment ( context [ 'config' ] [ 'index' ] [ - 1 ] , context [ 'market' ] . benchmark , context [ 'market' ] . timezone ) simulation . bui...
Main simulation wrapper Load the configuration run the engine and return the analyze .
25,308
def _is_interactive ( self ) : return not ( self . realworld and ( dt . date . today ( ) > self . datetime . date ( ) ) )
Prevent middlewares and orders to work outside live mode
25,309
def use ( self , func , when = 'whenever' ) : print ( 'registering middleware {}' . format ( func . __name__ ) ) self . middlewares . append ( { 'call' : func , 'name' : func . __name__ , 'args' : func . func_code . co_varnames , 'when' : when } )
Append a middleware to the algorithm
25,310
def process_orders ( self , orderbook ) : 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 : s...
Default and costant orders processor . Overwrite it for more sophisticated strategies
25,311
def _call_one_middleware ( self , middleware ) : args = { } for arg in middleware [ 'args' ] : if hasattr ( self , arg ) : args [ arg ] = reduce ( getattr , arg . split ( '.' ) , self ) self . logger . debug ( 'calling middleware event {}' . format ( middleware [ 'name' ] ) ) middleware [ 'call' ] ( ** args )
Evaluate arguments and execute the middleware function
25,312
def _call_middlewares ( self ) : for middleware in self . middlewares : if self . _check_condition ( middleware [ 'when' ] ) : self . _call_one_middleware ( middleware )
Execute the middleware stack
25,313
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
25,314
def _load_market_scheme ( self ) : try : self . scheme = yaml . load ( open ( self . scheme_path , 'r' ) ) except Exception , error : raise LoadMarketSchemeFailed ( reason = error )
Load market yaml description
25,315
def fetch ( self , code , ** kwargs ) : log . debug ( 'fetching QuanDL data (%s)' % code ) if 'authtoken' in kwargs : self . quandl_key = kwargs . pop ( 'authtoken' ) if 'start' in kwargs : kwargs [ 'trim_start' ] = kwargs . pop ( 'start' ) if 'end' in kwargs : kwargs [ 'trim_end' ] = kwargs . pop ( 'end' ) try : data ...
Quandl entry point in datafeed object
25,316
def rolling_performances ( self , timestamp = 'one_month' ) : 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' ...
Filters self . perfs
25,317
def overall_metrics ( self , timestamp = 'one_month' , metrics = None ) : perfs = dict ( ) 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' ]...
Use zipline results to compute some performance indicators
25,318
def _normalize_data_types ( self , strategy ) : for k , v in strategy . iteritems ( ) : if not isinstance ( v , str ) : 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 ...
some contexts only retrieves strings giving back right type
25,319
def _get_benchmark_handler ( self , last_trade , freq = 'minutely' ) : return LiveBenchmark ( last_trade , frequency = freq ) . surcharge_market_data if utils . is_live ( last_trade ) else None
Setup a custom benchmark handler or let zipline manage it
25,320
def configure_environment ( self , last_trade , benchmark , timezone ) : if last_trade . tzinfo is None : last_trade = pytz . utc . localize ( last_trade ) self . benchmark = benchmark self . context = TradingEnvironment ( bm_symbol = benchmark , exchange_tz = timezone , load = self . _get_benchmark_handler ( last_trad...
Prepare benchmark loader and trading context
25,321
def apply_mapping ( raw_row , mapping ) : row = { target : mapping_func ( raw_row [ source_key ] ) for target , ( mapping_func , source_key ) in mapping . fget ( ) . items ( ) } return row
Override this to hand craft conversion of row .
25,322
def invert_dataframe_axis ( fct ) : 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
Make dataframe index column names and vice et versa
25,323
def use_google_symbol ( fct ) : def decorator ( symbols ) : google_symbols = [ ] 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 ( googl...
Removes . PA or other market indicator from yahoo symbol convention to suit google convention
25,324
def get_sector ( symbol ) : 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
Uses BeautifulSoup to scrape stock sector from Yahoo! Finance website
25,325
def get_industry ( symbol ) : 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
Uses BeautifulSoup to scrape stock industry from Yahoo! Finance website
25,326
def get_type ( symbol ) : 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 : ass...
Uses BeautifulSoup to scrape symbol category from Yahoo! Finance website
25,327
def get_historical_prices ( symbol , start_date , end_date ) : 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...
Get historical prices for the given ticker symbol . Date format is YYYY - MM - DD
25,328
def _fx_mapping ( raw_rates ) : 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 ) }
Map raw output to clearer labels
25,329
def query_rates ( self , pairs = [ ] ) : 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_dat...
Perform a request against truefx data
25,330
def next_tick ( date , interval = 15 ) : now = dt . datetime . now ( pytz . utc ) live = False while now < date : time . sleep ( interval ) now = dt . datetime . now ( pytz . utc ) live = True return live
Only return when we reach given datetime
25,331
def intuition_module ( location ) : path = location . split ( '.' ) obj = path . pop ( - 1 ) return dna . utils . dynamic_import ( '.' . join ( path ) , obj )
Build the module path and import it
25,332
def build_trading_timeline ( start , end ) : 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 : bt_dates = EMPTY_DATES live_dates = pd . date_range ( start = now , end = normalize_date_format ( '23h59' ) ) else : end =...
Build the daily - based index we will trade on
25,333
def is_leap ( year ) : x = math . fmod ( year , 4 ) y = math . fmod ( year , 100 ) z = math . fmod ( year , 400 ) return not x and ( y or not z )
Leap year or not in the Gregorian calendar .
25,334
def gcal2jd ( year , month , day ) : 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 +=...
Gregorian calendar date to Julian date .
25,335
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 + jd2_f 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 ( ( ( 14...
Julian date to Gregorian calendar date and time of day .
25,336
def jcal2jd ( year , month , day ) : 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 jd -= 0.5 return MJD_0 , jd
Julian calendar date to Julian date .
25,337
def add_args_kwargs ( func ) : @ wraps ( func ) def wrapper ( * args , ** kwargs ) : props = argspec ( func ) 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 fun...
Add Args and Kwargs
25,338
def set_up_log ( filename , verbose = True ) : filename += '.log' if verbose : print ( 'Preparing log file:' , filename ) logging . captureWarnings ( True ) formatter = logging . Formatter ( fmt = '%(asctime)s %(message)s' , datefmt = '%d/%m/%Y %H:%M:%S' ) fh = logging . FileHandler ( filename = filename , mode = 'w' )...
Set up log
25,339
def add_observer ( self , signal , observer ) : self . _is_allowed_signal ( signal ) self . _add_observer ( signal , observer )
Add an observer to the object .
25,340
def remove_observer ( self , signal , observer ) : self . _is_allowed_event ( signal ) self . _remove_observer ( signal , observer )
Remove an observer from the object .
25,341
def notify_observers ( self , signal , ** kwargs ) : if self . _locked : return False self . _locked = True 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_n...
Notify observers of a given signal .
25,342
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 .
25,343
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 .
25,344
def _remove_observer ( self , signal , observer ) : if observer in self . _observers [ signal ] : self . _observers [ signal ] . remove ( observer )
Remove an observer to a valid signal .
25,345
def is_converge ( self ) : 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...
Return True if the convergence criteria is matched .
25,346
def retrieve_metrics ( self ) : 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 }
Return the convergence metrics saved with the corresponding iterations .
25,347
def _check_cost ( self ) : self . _test_list . append ( self . cost ) if len ( self . _test_list ) == self . _test_range : t1 = np . mean ( self . _test_list [ len ( self . _test_list ) // 2 : ] , axis = 0 ) t2 = np . mean ( self . _test_list [ : len ( self . _test_list ) // 2 ] , axis = 0 ) if not np . around ( t1 , d...
Check cost function
25,348
def _calc_cost ( self , * args , ** kwargs ) : return np . sum ( [ op . cost ( * args , ** kwargs ) for op in self . _operators ] )
Calculate the cost
25,349
def get_cost ( self , * args , ** kwargs ) : if self . _iteration % self . _cost_interval : test_result = False else : if self . _verbose : print ( ' - ITERATION:' , self . _iteration ) self . cost = self . _calc_cost ( verbose = self . _verbose , * args , ** kwargs ) self . _cost_list . append ( self . cost ) if self ...
Get cost function
25,350
def add_noise ( data , sigma = 1.0 , noise_type = 'gauss' ) : r 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 ] : rai...
r Add noise to data
25,351
def thresh ( data , threshold , threshold_type = 'hard' ) : r 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 . ...
r Threshold data
25,352
def _get_grad_method ( self , data ) : r self . grad = self . trans_op ( self . op ( data ) - self . obs_data )
r Get the gradient
25,353
def _cost_method ( self , * args , ** kwargs ) : 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
Calculate gradient component of the cost
25,354
def _cost_method ( self , * args , ** kwargs ) : if 'verbose' in kwargs and kwargs [ 'verbose' ] : print ( ' - Min (X):' , np . min ( args [ 0 ] ) ) return 0.0
Calculate positivity component of the cost
25,355
def _cost_method ( self , * args , ** kwargs ) : 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
Calculate sparsity component of the cost
25,356
def _cost_method ( self , * args , ** kwargs ) : 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
Calculate low - rank component of the cost
25,357
def _op_method ( self , data , extra_factor = 1.0 ) : r return self . linear_op . adj_op ( self . prox_op . op ( self . linear_op . op ( data ) , extra_factor = extra_factor ) )
r Operator method
25,358
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
25,359
def _cost_method ( self , * args , ** kwargs ) : return np . sum ( [ operator . cost ( data ) for operator , data in zip ( self . operators , args [ 0 ] ) ] )
Calculate combined proximity operator components of the cost
25,360
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 .
25,361
def _preprocess_input ( test , ref , mask = None ) : 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 ...
Wrapper to the metric
25,362
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 . isfile ( file_name ) : raise IOError ( 'Input file name [%s] not found!' % file_name )
File name error
25,363
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 . 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 ...
Check if Input is Executable
25,364
def _check_operator ( self , operator ) : 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__ ...
Check Set - Up
25,365
def _check_restart_params ( self , restart_strategy , min_beta , s_greedy , xi_restart ) : r if restart_strategy is None : return True if self . mode != 'regular' : raise ValueError ( 'Restarting strategies can only be used with ' 'regular mode.' ) greedy_params_check = ( min_beta is None or s_greedy is None or s_greed...
r Check restarting parameters
25,366
def is_restart ( self , z_old , x_new , x_old ) : r if self . restart_strategy is None : return False criterion = np . vdot ( z_old - x_new , x_new - 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' ] :...
r Check whether the algorithm needs to restart
25,367
def update_beta ( self , beta ) : r if self . _safeguard : beta *= self . xi_restart beta = max ( beta , self . min_beta ) return beta
r Update beta
25,368
def update_lambda ( self , * args , ** kwargs ) : r if self . restart_strategy == 'greedy' : return 2 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...
r Update lambda
25,369
def call_mr_transform ( data , opt = '' , path = './' , remove_files = True ) : r 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' is_...
r Call mr_transform
25,370
def get_mr_filters ( data_shape , opt = '' , coarse = False ) : data_shape = np . array ( data_shape ) data_shape += data_shape % 2 - 1 fake_data = np . zeros ( data_shape ) fake_data [ tuple ( zip ( data_shape // 2 ) ) ] = 1 mr_filters = call_mr_transform ( fake_data , opt = opt ) if coarse : return mr_filters else : ...
Get mr_transform filters
25,371
def gram_schmidt ( matrix , return_opt = 'orthonormal' ) : r 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 -...
r Gram - Schmit
25,372
def nuclear_norm ( data ) : r u , s , v = np . linalg . svd ( data ) return np . sum ( s )
r Nuclear norm
25,373
def project ( u , v ) : r return np . inner ( v , u ) / np . inner ( u , u ) * u
r Project vector
25,374
def rot_matrix ( angle ) : r return np . around ( np . array ( [ [ np . cos ( angle ) , - np . sin ( angle ) ] , [ np . sin ( angle ) , np . cos ( angle ) ] ] , dtype = 'float' ) , 10 )
r Rotation matrix
25,375
def _set_initial_x ( self ) : return np . random . random ( self . _data_shape ) . astype ( self . _data_type )
Set initial value of x
25,376
def get_spec_rad ( self , tolerance = 1e-6 , max_iter = 20 , extra_factor = 1.0 ) : x_old = self . _set_initial_x ( ) for i in range ( max_iter ) : x_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 ...
Get spectral radius
25,377
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 ' 'or numpy array.' ) input_val = np . array ( input_val ) if not input_val . size : raise ValueError ( 'Input list is empty.' ) return input_val
Check Input Type
25,378
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 be perfect square.' ) array_shape = np . repeat ( np . int ( np . sqrt ( u . shape [ 0 ] ) ) , 2 ) u_auto = [ convolve ( a . reshape ( array_shape ) , ...
Find number of principal components
25,379
def calculate_svd ( data ) : 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 )
Calculate Singular Value Decomposition
25,380
def svd_thresh ( data , threshold = None , n_pc = None , thresh_type = 'hard' ) : r 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 ' 'i...
r Threshold the singular values
25,381
def svd_thresh_coef ( data , operator , threshold , thresh_type = 'hard' ) : if not callable ( operator ) : raise TypeError ( 'Operator must be a callable function.' ) u , s , v = calculate_svd ( data ) s = np . diag ( s ) a = np . dot ( s , v ) array_shape = np . repeat ( np . int ( np . sqrt ( u . shape [ 0 ] ) ) , 2...
Threshold the singular values coefficients
25,382
def gaussian_kernel ( data_shape , sigma , norm = 'max' ) : r if not import_astropy : raise ImportError ( 'Astropy package not found.' ) if norm not in ( 'max' , 'sum' , 'none' ) : raise ValueError ( 'Invalid norm, options are "max", "sum" or "none".' ) kernel = np . array ( Gaussian2DKernel ( sigma , x_size = data_sha...
r Gaussian kernel
25,383
def mad ( data ) : r return np . median ( np . abs ( data - np . median ( data ) ) )
r Median absolute deviation
25,384
def psnr ( data1 , data2 , method = 'starck' , max_pix = 255 ) : r 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 (...
r Peak Signal - to - Noise Ratio
25,385
def psnr_stack ( data1 , data2 , metric = np . mean , method = 'starck' ) : r 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 ) ] )
r Peak Signa - to - Noise for stack of images
25,386
def cube2map ( data_cube , layout ) : r if data_cube . ndim != 3 : raise ValueError ( 'The input data must have 3 dimensions.' ) if data_cube . shape [ 0 ] != np . prod ( layout ) : raise ValueError ( 'The desired layout must match the number of input ' 'data layers.' ) return np . vstack ( [ np . hstack ( data_cube [ ...
r Cube to Map
25,387
def map2cube ( data_map , layout ) : r 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 [ ( sli...
r Map to cube
25,388
def map2matrix ( data_map , layout ) : r layout = np . array ( layout ) n_obj = np . prod ( layout ) image_shape = ( np . array ( data_map . shape ) // layout ) [ 0 ] data_matrix = [ ] for i in range ( n_obj ) : lower = ( image_shape * ( i // layout [ 1 ] ) , image_shape * ( i % layout [ 1 ] ) ) upper = ( image_shape *...
r Map to Matrix
25,389
def matrix2map ( data_matrix , map_shape ) : r map_shape = np . array ( map_shape ) image_shape = np . sqrt ( data_matrix . shape [ 0 ] ) . astype ( int ) layout = np . array ( map_shape // np . repeat ( image_shape , 2 ) , dtype = 'int' ) data_map = np . zeros ( map_shape ) temp = data_matrix . reshape ( image_shape ,...
r Matrix to Map
25,390
def cube2matrix ( data_cube ) : r return data_cube . reshape ( [ data_cube . shape [ 0 ] ] + [ np . prod ( data_cube . shape [ 1 : ] ) ] ) . T
r Cube to Matrix
25,391
def matrix2cube ( data_matrix , im_shape ) : r return data_matrix . T . reshape ( [ data_matrix . shape [ 1 ] ] + list ( im_shape ) )
r Matrix to Cube
25,392
def plotCost ( cost_list , output = None ) : 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 ....
Plot cost function
25,393
def Gaussian_filter ( x , sigma , norm = True ) : r 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
r Gaussian filter
25,394
def mex_hat ( x , sigma ) : r 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 )
r Mexican hat
25,395
def mex_hat_dir ( x , y , sigma ) : r x = check_float ( x ) sigma = check_float ( sigma ) return - 0.5 * ( x / sigma ) ** 2 * mex_hat ( y , sigma )
r Directional Mexican hat
25,396
def convolve ( data , kernel , method = 'scipy' ) : r 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 : method = 'scipy' if me...
r Convolve data with kernel
25,397
def convolve_stack ( data , kernel , rot_kernel = False , method = 'scipy' ) : r 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 ) ] )
r Convolve stack of data with stack of kernels
25,398
def check_callable ( val , add_agrs = True ) : r if not callable ( val ) : raise TypeError ( 'The input object must be a callable function.' ) if add_agrs : val = add_args_kwargs ( val ) return val
r Check input object is callable
25,399
def check_float ( val ) : r 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 )...
r Check if input value is a float or a np . ndarray of floats if not convert .