Generates boolean matrices indicating which are the probes for each model
511837
def probes_used_generate_vector(probe_files_full, probe_files_model):
  """"""
  import numpy as np
  C_probesUsed = np.ndarray((len(probe_files_full),), 'bool')
  C_probesUsed.fill(False)
  c=0
  for k in sorted(probe_files_full.keys()):
    if probe_files_model.has_key(k): C_probesUsed[c] = True
    c+=1
  return C_probesUsed
513361
def show_sbridges(self):
        """"""
        for i, saltb in enumerate(self.plcomplex.saltbridges):
            if saltb.protispos:
                for patom in saltb.positive_atoms:
                    cmd.select('PosCharge-P', 'PosCharge-P or (id %i & %s)' % (patom, self.protname))
                for latom in saltb.negative_atoms:
                    cmd.select('NegCharge-L', 'NegCharge-L or (id %i & %s)' % (latom, self.ligname))
                for sbgroup in [['ps-sbl-1-%i' % i, 'Chargecenter-P', saltb.positive_center],
                                ['ps-sbl-2-%i' % i, 'Chargecenter-L', saltb.negative_center]]:
                    cmd.pseudoatom(sbgroup[0], pos=sbgroup[2])
                    cmd.pseudoatom(sbgroup[1], pos=sbgroup[2])
                cmd.distance('Saltbridges', 'ps-sbl-1-%i' % i, 'ps-sbl-2-%i' % i)
            else:
                for patom in saltb.negative_atoms:
                    cmd.select('NegCharge-P', 'NegCharge-P or (id %i & %s)' % (patom, self.protname))
                for latom in saltb.positive_atoms:
                    cmd.select('PosCharge-L', 'PosCharge-L or (id %i & %s)' % (latom, self.ligname))
                for sbgroup in [['ps-sbp-1-%i' % i, 'Chargecenter-P', saltb.negative_center],
                                ['ps-sbp-2-%i' % i, 'Chargecenter-L', saltb.positive_center]]:
                    cmd.pseudoatom(sbgroup[0], pos=sbgroup[2])
                    cmd.pseudoatom(sbgroup[1], pos=sbgroup[2])
                cmd.distance('Saltbridges', 'ps-sbp-1-%i' % i, 'ps-sbp-2-%i' % i)

        if self.object_exists('Saltbridges'):
            cmd.set('dash_color', 'yellow', 'Saltbridges')
            cmd.set('dash_gap', 0.5, 'Saltbridges')
1020302
def sample_observed_state(self, s: pd.Series) -> Dict:
        

        return {
            n[0]: {
                i.name: np.random.normal(s[n[0]] * i.mean, i.stdev)
                for i in n[1]["indicators"].values()
            }
            for n in self.nodes(data=True)
        }
217564
def _build_information(self):
        
        lag_time = float(self.lag_time)

        # only the "active set" of variables not at the bounds of the
        # feasible set.
        inds = np.where(self.theta_ != 0)[0]

        hessian = _ratematrix.hessian(
            self.theta_, self.countsmat_, t=lag_time, inds=inds)

        self.information_ = np.zeros((len(self.theta_), len(self.theta_)))
        self.information_[np.ix_(inds, inds)] = scipy.linalg.pinv(-hessian)
1353459
def matrix_check(table):
    
    try:
        if len(table.keys()) == 0:
            return False
        for i in table.keys():
            if table.keys() != table[i].keys() or vector_check(
                    list(table[i].values())) is False:
                return False
        return True
    except Exception:
        return False
488410
def _ic_matrix(ics, ic_i):
    """"""
    cols, _ = ics.shape
    rows = len(ics[ic_i].iloc[0])
    ic_i_val = np.zeros((rows, cols))

    for idx, val in enumerate(ics.index):
        ic = ics.loc[val][ic_i]

        if len(ic) != rows:
            raise ValueError("The number of observations should be the same across all models")

        ic_i_val[:, idx] = ic

    return rows, cols, ic_i_val
1248038
def sample_counters(mc, system_info):
    """"""
    return {
        (x, y): mc.get_router_diagnostics(x, y) for (x, y) in system_info
    }
230977
def build_regression_matrix(H, model, build=None):
    
    ListOfTokens = model.split(' ')
    if H.shape[1]==1:
        size_index = len(str(H.shape[0]))
    else:
        size_index = len(str(H.shape[1]))
    
    if build is None:
        build = [True]*len(ListOfTokens)
    
    # Test if the vector has the wrong direction (lines instead of columns)
    if H.shape[0]==1:
        H = H.T
    
    # Collect the list of monomials
    Monom_Index = []
    for i in range(len(ListOfTokens)):
        if build[i]:
            Monom_Index += [grep(ListOfTokens, 'x' + str(0)*(size_index - \
            len(str(i))) + str(i))]
    
    Monom_Index = -np.sort(-Monom_Index)
    Monom_Index = np.unique(Monom_Index)
    
    if H.shape[1]==1:
        nb_var = H.shape[0]  # vector "mode": the number of vars is equal to the number of lines of H
        VectorMode = True
        
        for i in range(nb_var):
            for j in range(ListOfTokens.shape[0]):
                ListOfTokens[j] = ListOfTokens[j].replace(
                    'x' + str(0)*(size_index - len(str(i))) + str(i),
                    'H(' + str(i) + ')')
    else:
        nb_var = H.shape[0]  # matrix "mode": the number of vars is equal to the number of columns of H
        VectorMode = False
        
        for i in range(nb_var):
            for j in range(ListOfTokens.shape[0]):
                ListOfTokens[j] = ListOfTokens[j].replace(
                    'x' + str(0)*(size_index - len(str(i))) + str(i),
                    'H[i,' + str(i) + ')')
    
    # Now build the regression matrix
    if VectorMode:
        R = np.zeros((len(ListOfTokens), 1))
        for j in range(len(ListOfTokens)):
            R[j, 0] = eval(ListOfTokens[j])
    else:
        R = np.zeros((H.shape[0], len(ListOfTokens)))
        for i in range(H.shape[0]):
            for j in range(len(ListOfTokens)):
                R[i, j] = eval(ListOfTokens[j])
    
    return R
477223
def get_checkerboard_matrix(kernel_width):

    

    return np.vstack((
        np.hstack((
            -1 * np.ones((kernel_width, kernel_width)), np.ones((kernel_width, kernel_width))
        )),
        np.hstack((
            np.ones((kernel_width, kernel_width)), -1 * np.ones((kernel_width, kernel_width))
        ))
    ))
113099
def eigenvalues_samples(self):
         """
        res = np.empty((self.nsamples, self.nstates), dtype=config.dtype)
        for i in range(self.nsamples):
            res[i, :] = self._sampled_hmms[i].eigenvalues
        return res
631710
def boolean(self):
        
        try:
            return self._boolean
        except AttributeError:
            nbits = len(self.bits)
            boolean = numpy.zeros((self.size, nbits), dtype=bool)
            for i, sample in enumerate(self.value):
                boolean[i, :] = [int(sample) >> j & 1 for j in range(nbits)]
            self._boolean = Array2D(boolean, name=self.name,
                                    x0=self.x0, dx=self.dx, y0=0, dy=1)
            return self.boolean
1181255
def _create_model_matrices(self):
        

        self.model_Y = np.array(self.data[self.max_lag:self.data.shape[0]])
        self.model_scores = np.zeros(self.model_Y.shape[0])
739306
def sample_from_prior(self):
        

        # simple_path_dict caches the results of the graph traversal that finds
        # simple paths between pairs of nodes, so that it doesn't have to be
        # executed for every sampled transition matrix.

        node_pairs = list(permutations(self.nodes(), 2))
        simple_path_dict = {
            node_pair: [
                list(pairwise(path))
                for path in nx.all_simple_paths(self, *node_pair)
            ]
            for node_pair in node_pairs
        }

        self.transition_matrix_collection = []

        elements = self.get_latent_state_components()

        for i in range(self.res):
            A = pd.DataFrame(
                np.identity(2 * len(self)), index=elements, columns=elements
            )

            for node in self.nodes:
                A[f"∂({node})/∂t"][node] = self.Δt

            for node_pair in node_pairs:
                A[f"∂({node_pair[0]})/∂t"][node_pair[1]] = sum(
                    np.prod(
                        [
                            self.edges[edge[0], edge[1]]["βs"][i]
                            for edge in simple_path_edge_list
                        ]
                    )
                    * self.Δt
                    for simple_path_edge_list in simple_path_dict[node_pair]
                )
            self.transition_matrix_collection.append(A)
1298652
def run_false_positive_experiment_dim(
                              numActive = 128,
                              dim = 500,
                              numSamples = 1000,
                              numDendrites = 500,
                              synapses = 24,
                              numTrials = 10000,
                              seed = 42,
                              nonlinearity = sigmoid_nonlinearity(11.5, 5)):
  
  numpy.random.seed(seed)
  fps = []
  fns = []
  totalUnclassified = 0

  for trial in range(numTrials):

    # data = generate_evenly_distributed_data_sparse(dim = dim,
    #                                                num_active = numActive,
    #                                                num_samples = numSamples)
    # labels = numpy.asarray([1 for i in range(numSamples / 2)] +
    #                        [-1 for i in range(numSamples / 2)])
    # flipped_labels = labels * -1

    negData = generate_evenly_distributed_data_sparse(dim = dim,
                                                   num_active = numActive,
                                                   num_samples = numSamples/2)
    posData = generate_evenly_distributed_data_sparse(dim = dim,
                                                   num_active = numActive,
                                                   num_samples = numSamples/2)
    halfLabels = numpy.asarray([1 for _ in range(numSamples / 2)])
    flippedHalfLabels = halfLabels * -1

    neuron = Neuron(size =synapses * numDendrites,
                    num_dendrites = numDendrites,
                    dendrite_length = synapses,
                    dim = dim, nonlinearity = nonlinearity)
    neg_neuron = Neuron(size =synapses * numDendrites,
                        num_dendrites = numDendrites,
                        dendrite_length = synapses,
                        dim = dim, nonlinearity = nonlinearity)

    neuron.HTM_style_initialize_on_positive_data(posData)
    neg_neuron.HTM_style_initialize_on_positive_data(negData)

    # Get error for positively labeled data
    fp, fn, uc = get_error(posData, halfLabels, [neuron], [neg_neuron])
    totalUnclassified += uc
    fps.append(fp)
    fns.append(fn)

    # Get error for negatively labeled data
    fp, fn, uc = get_error(negData, flippedHalfLabels, [neuron], [neg_neuron])
    totalUnclassified += uc
    fps.append(fp)
    fns.append(fn)


  print "Error with n = {} : {} FP, {} FN, {} unclassified".format(
    dim, sum(fps), sum(fns), totalUnclassified)

  result = {
    "dim": dim,
    "totalFP": sum(fps),
    "totalFN": sum(fns),
    "total mistakes": sum(fns + fps) + totalUnclassified,
    "error": float(sum(fns + fps) + totalUnclassified) / (numTrials * numSamples),
    "totalSamples": numTrials * numSamples,
    "a": numActive,
    "num_dendrites": numDendrites,
    "totalUnclassified": totalUnclassified,
    "synapses": 24,
    "seed": seed,
  }

  return result
566282
def confusion_matrix(self, slice_size:int=1):
        ""
        x=torch.arange(0,self.data.c)
        if slice_size is None: cm = ((self.pred_class==x[:,None]) & (self.y_true==x[:,None,None])).sum(2)
        else:
            cm = torch.zeros(self.data.c, self.data.c, dtype=x.dtype)
            for i in range(0, self.y_true.shape[0], slice_size):
                cm_slice = ((self.pred_class[i:i+slice_size]==x[:,None])
                            & (self.y_true[i:i+slice_size]==x[:,None,None])).sum(2)
                torch.add(cm, cm_slice, out=cm)
        return to_np(cm)
831202
def get_selections(self):
        """"""
        sm_selection, sm_filtered_selected_model_set = self.get_state_machine_selection()
        tree_selection, selected_model_list = self.get_view_selection()
        return tree_selection, selected_model_list, sm_selection, sm_filtered_selected_model_set
205281
def _find_models(self, constructor, table_name, constraints=None, *, columns=None,
                   order_by=None, limiting=None):
    """"""
    for record in self.find_all(table_name, constraints, columns=columns, order_by=order_by,
                                limiting=limiting):
      yield constructor(record)