code stringlengths 1 18.2k |
|---|
def p_primary_expr_no_brace_2(self, p): """primary_expr_no_brace : THIS""" p[0] = self.asttypes.This() p[0].setpos(p) |
def p_primary_expr_no_brace_4(self, p): """primary_expr_no_brace : LPAREN expr RPAREN""" if isinstance(p[2], self.asttypes.GroupingOp): # this reduces the grouping operator to one. p[0] = p[2] else: p[0] = self.asttypes.GroupingOp(expr=p[2]) p[0].setpos(p) |
def p_array_literal_1(self, p): """array_literal : LBRACKET elision_opt RBRACKET""" p[0] = self.asttypes.Array(items=p[2]) p[0].setpos(p) |
def p_array_literal_2(self, p): """array_literal : LBRACKET element_list RBRACKET | LBRACKET element_list COMMA elision_opt RBRACKET """ items = p[2] if len(p) == 6: items.extend(p[4]) p[0] = self.asttypes.Array(items=items) p[0].setpos(p) |
def p_element_list(self, p): """element_list : elision_opt assignment_expr | element_list COMMA elision_opt assignment_expr """ if len(p) == 3: p[0] = p[1] + [p[2]] else: p[1].extend(p[3]) p[1].append(p[4]) p[0] = p[1] |
def p_elision(self, p): """elision : COMMA | elision COMMA """ if len(p) == 2: p[0] = [self.asttypes.Elision(1)] p[0][0].setpos(p) else: # increment the Elision value. p[1][-1].value += 1 p[0] = p[1] # TODO there should be a cleaner API for the lexer and their # token types for ensuring that the mappings are available.... |
def p_object_literal(self, p): """object_literal : LBRACE RBRACE | LBRACE property_list RBRACE | LBRACE property_list COMMA RBRACE """ if len(p) == 3: p[0] = self.asttypes.Object() else: p[0] = self.asttypes.Object(properties=p[2]) p[0].setpos(p) |
def p_property_list(self, p): """property_list : property_assignment | property_list COMMA property_assignment """ if len(p) == 2: p[0] = [p[1]] else: p[1].append(p[3]) p[0] = p[1] |
def p_property_assignment(self, p): """property_assignment \ : property_name COLON assignment_expr | GETPROP property_name LPAREN RPAREN LBRACE function_body RBRACE | SETPROP property_name LPAREN property_set_parameter_list RPAREN\ LBRACE function_body RBRACE """ if len(p) == 4: p[0] = self.asttypes.Assign(left=p[1], o... |
def p_identifier_name_string(self, p): """identifier_name_string : identifier_name """ p[0] = asttypes.PropIdentifier(p[1].value) # manually clone the position attributes. for k in ('_token_map', 'lexpos', 'lineno', 'colno'): setattr(p[0], k, getattr(p[1], k)) |
def p_member_expr(self, p): """member_expr : primary_expr | function_expr | member_expr LBRACKET expr RBRACKET | member_expr PERIOD identifier_name_string | NEW member_expr arguments """ if len(p) == 2: p[0] = p[1] return if p[1] == 'new': p[0] = self.asttypes.NewExpr(p[2], p[3]) p[0].setpos(p) elif p[2] == '.': p[0] =... |
def p_new_expr(self, p): """new_expr : member_expr | NEW new_expr """ if len(p) == 2: p[0] = p[1] else: p[0] = self.asttypes.NewExpr(p[2]) p[0].setpos(p) |
def p_new_expr_nobf(self, p): """new_expr_nobf : member_expr_nobf | NEW new_expr """ if len(p) == 2: p[0] = p[1] else: p[0] = self.asttypes.NewExpr(p[2]) p[0].setpos(p) |
def p_call_expr(self, p): """call_expr : member_expr arguments | call_expr arguments | call_expr LBRACKET expr RBRACKET | call_expr PERIOD identifier_name_string """ if len(p) == 3: p[0] = self.asttypes.FunctionCall(p[1], p[2]) p[0].setpos(p) # require yacc_tracking elif len(p) == 4: p[0] = self.asttypes.DotAccessor(p[... |
def p_arguments(self, p): """arguments : LPAREN RPAREN | LPAREN argument_list RPAREN """ if len(p) == 4: p[0] = self.asttypes.Arguments(p[2]) else: p[0] = self.asttypes.Arguments([]) p[0].setpos(p) |
def p_argument_list(self, p): """argument_list : assignment_expr | argument_list COMMA assignment_expr """ if len(p) == 2: p[0] = [p[1]] else: p[1].append(p[3]) p[0] = p[1] |
def p_postfix_expr(self, p): """postfix_expr : left_hand_side_expr | left_hand_side_expr PLUSPLUS | left_hand_side_expr MINUSMINUS """ if len(p) == 2: p[0] = p[1] else: p[0] = self.asttypes.PostfixExpr(op=p[2], value=p[1]) p[0].setpos(p, 2) |
def p_unary_expr_common(self, p): """unary_expr_common : DELETE unary_expr | VOID unary_expr | TYPEOF unary_expr | PLUSPLUS unary_expr | MINUSMINUS unary_expr | PLUS unary_expr | MINUS unary_expr | BNOT unary_expr | NOT unary_expr """ p[0] = self.asttypes.UnaryExpr(p[1], p[2]) p[0].setpos(p) |
def p_multiplicative_expr(self, p): """multiplicative_expr : unary_expr | multiplicative_expr MULT unary_expr | multiplicative_expr DIV unary_expr | multiplicative_expr MOD unary_expr """ if len(p) == 2: p[0] = p[1] else: p[0] = self.asttypes.BinOp(op=p[2], left=p[1], right=p[3]) p[0].setpos(p, 2) |
def p_conditional_expr(self, p): """ conditional_expr \ : logical_or_expr | logical_or_expr CONDOP assignment_expr COLON assignment_expr """ if len(p) == 2: p[0] = p[1] else: p[0] = self.asttypes.Conditional( predicate=p[1], consequent=p[3], alternative=p[5]) p[0].setpos(p, 2) |
def p_assignment_expr_noin(self, p): """ assignment_expr_noin \ : conditional_expr_noin | left_hand_side_expr assignment_operator assignment_expr_noin """ if len(p) == 2: p[0] = p[1] else: p[0] = self.asttypes.Assign(left=p[1], op=p[2], right=p[3]) p[0].setpos(p, 2) |
def p_expr(self, p): """expr : assignment_expr | expr COMMA assignment_expr """ if len(p) == 2: p[0] = p[1] else: p[0] = self.asttypes.Comma(left=p[1], right=p[3]) p[0].setpos(p, 2) |
def p_variable_statement(self, p): """variable_statement : VAR variable_declaration_list SEMI | VAR variable_declaration_list AUTOSEMI """ p[0] = self.asttypes.VarStatement(p[2]) p[0].setpos(p) |
def p_variable_declaration_list(self, p): """ variable_declaration_list \ : variable_declaration | variable_declaration_list COMMA variable_declaration """ if len(p) == 2: p[0] = [p[1]] else: p[1].append(p[3]) p[0] = p[1] |
def p_variable_declaration_list_noin(self, p): """ variable_declaration_list_noin \ : variable_declaration_noin | variable_declaration_list_noin COMMA variable_declaration_noin """ if len(p) == 2: p[0] = [p[1]] else: p[1].append(p[3]) p[0] = p[1] |
def p_variable_declaration(self, p): """variable_declaration : identifier | identifier initializer """ if len(p) == 2: p[0] = self.asttypes.VarDecl(p[1]) p[0].setpos(p) # require yacc_tracking else: p[0] = self.asttypes.VarDecl(p[1], p[2]) p[0].setpos(p, additional=(('=', 2),)) |
def p_variable_declaration_noin(self, p): """variable_declaration_noin : identifier | identifier initializer_noin """ if len(p) == 2: p[0] = self.asttypes.VarDecl(p[1]) p[0].setpos(p) # require yacc_tracking else: p[0] = self.asttypes.VarDecl(p[1], p[2]) p[0].setpos(p, additional=(('=', 2),)) |
def p_empty_statement(self, p): """empty_statement : SEMI""" p[0] = self.asttypes.EmptyStatement(p[1]) p[0].setpos(p) |
def p_expr_statement(self, p): """expr_statement : expr_nobf SEMI | expr_nobf AUTOSEMI """ # In 12.4, expression statements cannot start with either the # 'function' keyword or '{'. However, the lexing and production # of the FuncExpr nodes can be done through further rules have # been done, so flag this as an exceptio... |
of such like for 'function_expr'. p[0] = self.asttypes.ExprStatement(p[1]) p[0].setpos(p) |
def p_if_statement_1(self, p): """if_statement : IF LPAREN expr RPAREN statement""" p[0] = self.asttypes.If(predicate=p[3], consequent=p[5]) p[0].setpos(p) |
def p_if_statement_2(self, p): """if_statement : IF LPAREN expr RPAREN statement ELSE statement""" p[0] = self.asttypes.If( predicate=p[3], consequent=p[5], alternative=p[7]) p[0].setpos(p) |
def p_iteration_statement_1(self, p): """ iteration_statement \ : DO statement WHILE LPAREN expr RPAREN SEMI | DO statement WHILE LPAREN expr RPAREN AUTOSEMI """ p[0] = self.asttypes.DoWhile(predicate=p[5], statement=p[2]) p[0].setpos(p) |
def p_iteration_statement_2(self, p): """iteration_statement : WHILE LPAREN expr RPAREN statement""" p[0] = self.asttypes.While(predicate=p[3], statement=p[5]) p[0].setpos(p) |
def p_iteration_statement_3(self, p): """ iteration_statement \ : FOR LPAREN expr_noin_opt SEMI expr_opt SEMI expr_opt RPAREN \ statement | FOR LPAREN VAR variable_declaration_list_noin SEMI expr_opt SEMI\ expr_opt RPAREN statement """ def wrap(node, key): if node is None: # work around bug with yacc tracking of empty ... |
def p_iteration_statement_4(self, p): """ iteration_statement \ : FOR LPAREN left_hand_side_expr IN expr RPAREN statement """ p[0] = self.asttypes.ForIn(item=p[3], iterable=p[5], statement=p[7]) p[0].setpos(p) |
def p_iteration_statement_5(self, p): """ iteration_statement : \ FOR LPAREN VAR identifier IN expr RPAREN statement """ vardecl = self.asttypes.VarDeclNoIn(identifier=p[4]) vardecl.setpos(p, 3) p[0] = self.asttypes.ForIn(item=vardecl, iterable=p[6], statement=p[8]) p[0].setpos(p) |
def p_iteration_statement_6(self, p): """ iteration_statement \ : FOR LPAREN VAR identifier initializer_noin IN expr RPAREN statement """ vardecl = self.asttypes.VarDeclNoIn( identifier=p[4], initializer=p[5]) vardecl.setpos(p, 3) p[0] = self.asttypes.ForIn(item=vardecl, iterable=p[7], statement=p[9]) p[0].setpos(p) |
def p_continue_statement_1(self, p): """continue_statement : CONTINUE SEMI | CONTINUE AUTOSEMI """ p[0] = self.asttypes.Continue() p[0].setpos(p) |
def p_continue_statement_2(self, p): """continue_statement : CONTINUE identifier SEMI | CONTINUE identifier AUTOSEMI """ p[0] = self.asttypes.Continue(p[2]) p[0].setpos(p) |
def p_break_statement_1(self, p): """break_statement : BREAK SEMI | BREAK AUTOSEMI """ p[0] = self.asttypes.Break() p[0].setpos(p) |
def p_break_statement_2(self, p): """break_statement : BREAK identifier SEMI | BREAK identifier AUTOSEMI """ p[0] = self.asttypes.Break(p[2]) p[0].setpos(p) |
def p_return_statement_1(self, p): """return_statement : RETURN SEMI | RETURN AUTOSEMI """ p[0] = self.asttypes.Return() p[0].setpos(p) |
def p_return_statement_2(self, p): """return_statement : RETURN expr SEMI | RETURN expr AUTOSEMI """ p[0] = self.asttypes.Return(expr=p[2]) p[0].setpos(p) |
def p_with_statement(self, p): """with_statement : WITH LPAREN expr RPAREN statement""" p[0] = self.asttypes.With(expr=p[3], statement=p[5]) p[0].setpos(p) |
def p_switch_statement(self, p): """switch_statement : SWITCH LPAREN expr RPAREN case_block""" # this uses a completely different type that corrects a # subtly wrong interpretation of this construct. # see: https://github.com/rspivak/slimit/issues/94 p[0] = self.asttypes.Switch(expr=p[3], case_block=p[5]) p[0].setpos(p... |
def p_case_block(self, p): """ case_block \ : LBRACE case_clauses_opt RBRACE | LBRACE case_clauses_opt default_clause case_clauses_opt RBRACE """ statements = [] for s in p[2:-1]: if isinstance(s, list): for i in s: statements.append(i) elif isinstance(s, self.asttypes.Default): statements.append(s) p[0] = self.asttype... |
def p_case_clauses(self, p): """case_clauses : case_clause | case_clauses case_clause """ if len(p) == 2: p[0] = [p[1]] else: p[1].append(p[2]) p[0] = p[1] |
def p_case_clause(self, p): """case_clause : CASE expr COLON source_elements""" p[0] = self.asttypes.Case(expr=p[2], elements=p[4]) p[0].setpos(p) |
def p_default_clause(self, p): """default_clause : DEFAULT COLON source_elements""" p[0] = self.asttypes.Default(elements=p[3]) p[0].setpos(p) |
def p_labelled_statement(self, p): """labelled_statement : identifier COLON statement""" p[0] = self.asttypes.Label(identifier=p[1], statement=p[3]) p[0].setpos(p, 2) |
def p_throw_statement(self, p): """throw_statement : THROW expr SEMI | THROW expr AUTOSEMI """ p[0] = self.asttypes.Throw(expr=p[2]) p[0].setpos(p) |
def p_try_statement_1(self, p): """try_statement : TRY block catch""" p[0] = self.asttypes.Try(statements=p[2], catch=p[3]) p[0].setpos(p) |
def p_try_statement_2(self, p): """try_statement : TRY block finally""" p[0] = self.asttypes.Try(statements=p[2], fin=p[3]) p[0].setpos(p) |
def p_try_statement_3(self, p): """try_statement : TRY block catch finally""" p[0] = self.asttypes.Try(statements=p[2], catch=p[3], fin=p[4]) p[0].setpos(p) |
def p_catch(self, p): """catch : CATCH LPAREN identifier RPAREN block""" p[0] = self.asttypes.Catch(identifier=p[3], elements=p[5]) p[0].setpos(p) |
def p_finally(self, p): """finally : FINALLY block""" p[0] = self.asttypes.Finally(elements=p[2]) p[0].setpos(p) |
def p_debugger_statement(self, p): """debugger_statement : DEBUGGER SEMI | DEBUGGER AUTOSEMI """ p[0] = self.asttypes.Debugger(p[1]) p[0].setpos(p) |
def p_function_declaration(self, p): """ function_declaration \ : FUNCTION identifier LPAREN RPAREN LBRACE function_body RBRACE | FUNCTION identifier LPAREN formal_parameter_list RPAREN LBRACE \ function_body RBRACE """ if len(p) == 8: p[0] = self.asttypes.FuncDecl( identifier=p[2], parameters=None, elements=p[6]) else... |
def p_function_expr_2(self, p): """ function_expr \ : FUNCTION identifier LPAREN RPAREN LBRACE function_body RBRACE | FUNCTION identifier LPAREN formal_parameter_list RPAREN \ LBRACE function_body RBRACE """ if len(p) == 8: p[0] = self.asttypes.FuncExpr( identifier=p[2], parameters=None, elements=p[6]) else: p[0] = sel... |
def p_formal_parameter_list(self, p): """formal_parameter_list : identifier | formal_parameter_list COMMA identifier """ if len(p) == 2: p[0] = [p[1]] else: p[1].append(p[3]) p[0] = p[1] |
def Y(self, value): """ set phenotype """ self._N = value.shape[0] self._P = value.shape[1] self._Y = value # missing data self._Iok = ~sp.isnan(value) self._veIok = vec(self._Iok)[:, 0] self._miss = (~self._Iok).any() # notify and clear_cached self.clear_cache('pheno') self._notify() self._notify('pheno') |
def setDesigns(self, F, A): """ set fixed effect designs """ F = to_list(F) A = to_list(A) assert len(A) == len(F), 'MeanKronSum: A and F must have same length!' n_terms = len(F) n_covs = 0 k = 0 l = 0 for ti in range(n_terms): assert F[ti].shape[0] == self._N, 'MeanKronSum: Dimension mismatch' assert A[ti].shape[1] ==... |
def Fstar(self, value): """ set fixed effect design for predictions """ if value is None: self._use_to_predict = False else: assert value.shape[1] == self._K, 'Dimension mismatch' self._use_to_predict = True self._Fstar = value self.clear_cache('predict') |
def standardize(Y,in_place=False): """ standardize Y in a way that is robust to missing values in_place: create a copy or carry out inplace opreations? """ if in_place: YY = Y else: YY = Y.copy() for i in range(YY.shape[1]): Iok = ~SP.isnan(YY[:,i]) Ym = YY[Iok,i].mean() YY[:,i]-=Ym Ys = YY[Iok,i].std() YY[:,i]/=Ys ret... |
def covar_rescaling_factor(C): """ Returns the rescaling factor for the Gower normalizion on covariance matrix C the rescaled covariance matrix has sample variance of 1 """ n = C.shape[0] P = sp.eye(n) - sp.ones((n,n))/float(n) trPCP = sp.trace(sp.dot(P,sp.dot(C,P))) r = (n-1) / trPCP return r |
def covar_rescaling_factor_efficient(C): """ Returns the rescaling factor for the Gower normalizion on covariance matrix C the rescaled covariance matrix has sample variance of 1 """ n = C.shape[0] P = sp.eye(n) - sp.ones((n,n))/float(n) CP = C - C.mean(0)[:, sp.newaxis] trPCP = sp.sum(P * CP) r = (n-1) / trPCP return ... |
def toRanks(A): """ converts the columns of A to ranks """ AA=sp.zeros_like(A) for i in range(A.shape[1]): AA[:,i] = st.rankdata(A[:,i]) AA=sp.array(sp.around(AA),dtype="int")-1 return AA |
def gaussianize(Y): """ Gaussianize X: [samples x phenotypes] - each phentoype is converted to ranks and transformed back to normal using the inverse CDF """ N,P = Y.shape YY=toRanks(Y) quantiles=(sp.arange(N)+0.5)/N gauss = st.norm.isf(quantiles) Y_gauss=sp.zeros((N,P)) for i in range(P): Y_gauss[:,i] = gauss[YY[:,i]]... |
def regressOut(Y, X, return_b=False): """ regresses out X from Y """ Xd = la.pinv(X) b = Xd.dot(Y) Y_out = Y-X.dot(b) if return_b: return Y_out, b else: return Y_out |
def remove_dependent_cols(M, tol=1e-6, display=False): """ Returns a matrix where dependent columsn have been removed """ R = la.qr(M, mode='r')[0][:M.shape[1], :] I = (abs(R.diagonal())>tol) if sp.any(~I) and display: print(('cols ' + str(sp.where(~I)[0]) + ' have been removed because linearly dependent on the others'... |
def boxcox(X): """ Gaussianize X using the Box-Cox transformation: [samples x phenotypes] - each phentoype is brought to a positive schale, by first subtracting the minimum value and adding 1. - Then each phenotype transformed by the boxcox transformation """ X_transformed = sp.zeros_like(X) maxlog = sp.zeros(X.shape[1... |
def setCovariance(self,cov): """ set hyperparameters from given covariance """ chol = LA.cholesky(cov,lower=True) params = chol[sp.tril_indices(self.dim)] self.setParams(params) |
def bias(mass, z, h=h, Om_M=Om_M, Om_L=Om_L): """Calculate halo bias, from Seljak & Warren 2004. Parameters ---------- mass : ndarray or float Halo mass to calculate bias for. z : ndarray or float Halo z, same type and size as mass. h : float, optional Hubble parameter, defaults to astropy.cosmology.Planck13.h Om_M : f... |
M.S. Warren, "Large-scale bias and stochasticity of haloes and dark matter," Monthly Notices of the Royal Astronomical Society, Volume 355, Issue 1, pp. 129-136 (2004). """ M_nl_0 = (8.73 / h) * (10. ** 12.) # nonlinear mass today [M_sun] M_nl = M_nl_0 * (Om_M + Om_L / ((1. + z) ** 3.)) # scaled to z_lens x = mass / M_... |
def shorten(text): """ Reduce text length for displaying / logging purposes. """ if len(text) >= MAX_DISPLAY_LEN: text = text[:MAX_DISPLAY_LEN//2]+"..."+text[-MAX_DISPLAY_LEN//2:] return text |
def get_logfile(logger=None): """ Return log file of first file handler associated with the (root) logger. None if no such handler is found. """ logger = logger or logging.getLogger() handlers = [i for i in logger.handlers if isinstance(i, logging.FileHandler)] return handlers[0].baseFilename if handlers else None |
def paid_at(self): '''Localized at America/Santiago datetime of ``TBK_FECHA_TRANSACCION``. ''' fecha_transaccion = self.data['TBK_FECHA_TRANSACCION'] hora_transaccion = self.data['TBK_HORA_TRANSACCION'] m = int(fecha_transaccion[:2]) d = int(fecha_transaccion[2:]) h = int(hora_transaccion[:2]) i = int(hora_transaccion[... |
def accountable_date(self): '''Accountable date of transaction, localized as America/Santiago ''' fecha_transaccion = self.data['TBK_FECHA_CONTABLE'] m = int(fecha_transaccion[:2]) d = int(fecha_transaccion[2:]) santiago = pytz.timezone('America/Santiago') today = santiago.localize(datetime.datetime.today()) year = tod... |
def is_success(self, check_timeout=True): ''' Check if Webpay response ``TBK_RESPUESTA`` is equal to ``0`` and if the lapse between initialization and this call is less than ``self.timeout`` when ``check_timeout`` is ``True`` (default). :param check_timeout: When ``True``, check time between initialization and call. ''... |
def is_timeout(self): ''' Check if the lapse between initialization and now is more than ``self.timeout``. ''' lapse = datetime.datetime.now() - self.init_time return lapse > datetime.timedelta(seconds=self.timeout) |
def init_app(self, app): """Initialize Flask application.""" app.config.from_pyfile('{0}.cfg'.format(app.name), silent=True) |
def improvise_step(oracle, i, lrs=0, weight=None, prune=False): """ Given the current time step, improvise (generate) the next time step based on the oracle structure. :param oracle: an indexed vmo object :param i: current improvisation time step :param lrs: the length of minimum longest repeated suffixes allowed to ju... |
= [s + 1 for s in oracle.latent[oracle.data[i]] if (oracle.lrs[s] >= lrs and (s + 1) < oracle.n_states)] if not trn_link: if i == oracle.n_states - 1: n = 1 else: n = i + 1 else: if weight == 'lrs': lrs_link = [oracle.lrs[s] for s in oracle.latent[oracle.data[i]] if (oracle.lrs[s] >= lrs and (s + 1) < oracle.n_states)]... |
def improvise(oracle, seq_len, k=1, LRS=0, weight=None, continuity=1): """ Given an oracle and length, generate an improvised sequence of the given length. :param oracle: an indexed vmo object :param seq_len: the length of the returned improvisation sequence :param k: the starting improvisation time step in oracle :par... |
k, LRS, weight)) k = s[-1] if k + 1 < oracle.n_states - 1: k += 1 else: k = 1 if k + continuity < oracle.n_states - 1: s.extend(range(k, k + continuity)) seq_len -= continuity k = s[-1] seq_len -= 1 return s |
def generate(oracle, seq_len, p=0.5, k=1, LRS=0, weight=None): """ Generate a sequence based on traversing an oracle. :param oracle: a indexed vmo object :param seq_len: the length of the returned improvisation sequence :param p: a float between (0,1) representing the probability using the forward links. :param k: the ... |
rsfx = oracle.rsfx[:] s = [] ktrace = [1] for _i in range(seq_len): # generate each state if sfx[k] != 0 and sfx[k] is not None: if (random.random() < p): # copy forward according to transitions I = trn[k] if len(I) == 0: # if last state, choose a suffix k = sfx[k] ktrace.append(k) I = trn[k] sym = I[int(np.floor(rando... |
= max_lrs - np.floor(random.expovariate(1)) if query_lrs in lrs_vec: _tmp = np.where(lrs_vec == query_lrs)[0] _tmp = _tmp[int( np.floor(random.random() * len(_tmp)))] sym = k_vec[_tmp] else: _tmp = np.argmin(abs( np.subtract(lrs_vec, query_lrs))) sym = k_vec[_tmp] elif weight == 'max': sym = k_vec[np.argmax([lrs[_i] fo... |
0 kend = k return s, kend, ktrace |
def _find_links(k_vec, sfx, rsfx, k): """Find sfx/rsfx recursively.""" k_vec.sort() if 0 in k_vec: return k_vec else: if sfx[k] not in k_vec: k_vec.append(sfx[k]) for i in range(len(rsfx[k])): if rsfx[k][i] not in k_vec: k_vec.append(rsfx[k][i]) for i in range(len(k_vec)): k_vec = _find_links(k_vec, sfx, rsfx, k_vec[i]... |
def _make_win(n, mono=False): """ Generate a window for a given length. :param n: an integer for the length of the window. :param mono: True for a mono window, False for a stereo window. :return: an numpy array containing the window value. """ if mono: win = np.hanning(n) + 0.00001 else: win = np.array([np.hanning(n) +... |
def singleton(wrapped, _, args, kwargs): """Return the single instance of wrapped. :param wrapped: the wrapped class. :param _: unused :param args: optional arguments for wrapped object. :param kwargs: optional arguments for wrapped object. """ if wrapped not in _INSTANCES: _INSTANCES[wrapped] = wrapped(*args, **kwargs... |
def filter(self, node, condition): """ This method accepts a node and the condition function; a generator will be returned to yield the nodes that got matched by the condition. """ if not isinstance(node, Node): raise TypeError('not a node') for child in node: if condition(child): yield child for subchild in self.filte... |
def extract(self, node, condition, skip=0): """ Extract a single node that matches the provided condition, otherwise a TypeError is raised. An optional skip parameter can be provided to specify how many matching nodes are to be skipped over. """ for child in self.filter(node, condition): if not skip: return child skip ... |
def walk( self, node, omit=( 'lexpos', 'lineno', 'colno', 'rowno'), indent=0, depth=-1, pos=False, _level=0): """ Accepts the standard node argument, along with an optional omit flag - it should be an iterable that lists out all attributes that should be omitted from the repr output. """ if not depth: return '<%s ...>'... |
omit, indent, depth - 1, pos, _level))) elif isinstance(v, list): items = [] for i in v: if id(i) in ids: ids.remove(id(i)) items.append(self.walk( i, omit, indent, depth - 1, pos, _level + 1)) attrs.append( (k, '[' + header + joiner.join(items) + tailer + ']')) else: attrs.append((k, repr_compat(v))) if ids: # for unn... |
k, v in sorted(attrs) if k not in omit_keys )) |
def directed_graph(trajectories, k=5, verbose=False, pruning_thresh=0, return_coords=False): '''Directed graph construction alg. from Johns & Mahadevan, ICML '07. trajectories: list of NxD arrays of ordered states ''' X = np.vstack(trajectories) G = neighbor_graph(X, k=k) if pruning_thresh > 0: traj_len = map(len, traj... |
def _prune_edges(G, X, traj_lengths, pruning_thresh=0.1, verbose=False): '''Prune edges in graph G via cosine distance with trajectory edges.''' W = G.matrix('dense', copy=True) degree = G.degree(kind='out', weighted=False) i = 0 num_bad = 0 for n in traj_lengths: s, t = np.nonzero(W[i:i+n-1]) graph_edges = X[t] - X[s+... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.