Internal function to calculate and cache the profile likelihood
174375
def _profile_loglike(self, x):
        
        x = np.array(x, ndmin=1)

        z = []
        y = []

        for xtmp in x:
            def fn(t): return -self.loglike(xtmp, t)
            ytmp = opt.fmin(fn, 1.0, disp=False)[0]
            ztmp = self.loglike(xtmp, ytmp)
            z.append(ztmp)
            y.append(ytmp)

        self._prof_y = np.array(y)
        self._prof_z = np.array(z)
        self._prof_z = self._prof_z.max() - self._prof_z
        self._prof_interp = castro.Interpolator(x, self._prof_z)
        return self._prof_y, self._prof_z
622901
def _update_likelihood_model(self, inst, partition_parameters, tree):
        
        # Build transition matrix from dict
        model = partition_parameters['model']
        freqs = partition_parameters.get('frequencies')
        if model == 'LG':
            subs_model = phylo_utils.models.LG(freqs)
        elif model == 'WAG':
            subs_model = phylo_utils.models.WAG(freqs)
        elif model == 'GTR':
            rates = partition_parameters.get('rates')
            subs_model = phylo_utils.models.GTR(rates, freqs, True)
        else:
            raise ValueError("Can't handle this model: {}".format(model))
        tm = phylo_utils.markov.TransitionMatrix(subs_model)
        
        # Read alpha value
        alpha = partition_parameters['alpha']
        inst.set_tree(tree)
        inst.update_alpha(alpha)
        inst.update_transition_matrix(tm)
817678
def timeit_profile(stmt, number, repeat, setup,
                   profiler_factory, pickle_protocol, dump_filename, mono,
                   **_ignored):
    """"""
    del _ignored
    globals_ = {}
    exec_(setup, globals_)
    if number is None:
        # determine number so that 0.2 <= total time < 2.0 like timeit.
        dummy_profiler = profiler_factory()
        dummy_profiler.start()
        for x in range(1, 10):
            number = 10 ** x
            t = time.time()
            for y in range(number):
                exec_(stmt, globals_)
            if time.time() - t >= 0.2:
                break
        dummy_profiler.stop()
        del dummy_profiler
    code = compile('for _ in range(%d): %s' % (number, stmt),
                   'STATEMENT', 'exec')
    __profile__(stmt, code, globals_, profiler_factory,
                pickle_protocol=pickle_protocol, dump_filename=dump_filename,
                mono=mono)
687596
def forward_prediction(self, m):
        
        return self.infer(self.conf.m_dims, self.conf.s_dims, m)
1109626
def _build_likelihood(self):
        

        num_inducing = len(self.feature)
        num_data = tf.cast(tf.shape(self.Y)[0], settings.float_type)
        output_dim = tf.cast(tf.shape(self.Y)[1], settings.float_type)

        err = self.Y - self.mean_function(self.X)
        Kdiag = self.kern.Kdiag(self.X)
        Kuf = features.Kuf(self.feature, self.kern, self.X)
        Kuu = features.Kuu(self.feature, self.kern, jitter=settings.numerics.jitter_level)
        L = tf.cholesky(Kuu)
        sigma = tf.sqrt(self.likelihood.variance)

        # Compute intermediate matrices
        A = tf.matrix_triangular_solve(L, Kuf, lower=True) / sigma
        AAT = tf.matmul(A, A, transpose_b=True)
        B = AAT + tf.eye(num_inducing, dtype=settings.float_type)
        LB = tf.cholesky(B)
        Aerr = tf.matmul(A, err)
        c = tf.matrix_triangular_solve(LB, Aerr, lower=True) / sigma

        # compute log marginal bound
        bound = -0.5 * num_data * output_dim * np.log(2 * np.pi)
        bound += tf.negative(output_dim) * tf.reduce_sum(tf.log(tf.matrix_diag_part(LB)))
        bound -= 0.5 * num_data * output_dim * tf.log(self.likelihood.variance)
        bound += -0.5 * tf.reduce_sum(tf.square(err)) / self.likelihood.variance
        bound += 0.5 * tf.reduce_sum(tf.square(c))
        bound += -0.5 * output_dim * tf.reduce_sum(Kdiag) / self.likelihood.variance
        bound += 0.5 * output_dim * tf.reduce_sum(tf.matrix_diag_part(AAT))

        return bound
1187803
def hessian_local_log_likelihood(self, x):
        
        T, D = self.T, self.D_latent
        assert x.shape == (T, D)

        hfun = hessian(self.local_log_likelihood)
        H_diag = np.zeros((T, D, D))
        for t in range(T):
            H_diag[t] = hfun(x[t], self.data[t], self.inputs[t])
        return H_diag
415381
def profile(func):
    
    def _f(*args, **kwargs):
        print("\n<<<---")
        pr = cProfile.Profile()
        pr.enable()
        res = func(*args, **kwargs)
        p = pstats.Stats(pr)
        p.strip_dirs().sort_stats('cumtime').print_stats(20)
        print("\n--->>>")
        return res
    return _f
620791
def profiler(profiles, projectpath,parameters,serviceid,servicename,serviceurl,printdebug=None):
    """"""

    parameters = sanitizeparameters(parameters)

    matched = []
    program = Program(projectpath)
    for profile in profiles:
        if profile.match(projectpath, parameters)[0]:
            matched.append(profile)
            program.update( profile.generate(projectpath,parameters,serviceid,servicename,serviceurl) )

    return matched, program
781132
def load_profile(self, profile_name):
        """"""
        data = self.storage.get_user_profiles(profile_name)

        for x in data.get_user_views():
            self._graph.add_edge(int(x[0]), int(x[1]), {'weight': float(x[2])})
            self.all_records[int(x[1])] += 1

        return self._graph
101609
def _build_likelihood(self):
        

        # Get prior KL.
        KL = self.build_prior_KL()

        # Get conditionals
        fmean, fvar = self._build_predict(self.X, full_cov=False, full_output_cov=False)

        # Get variational expectations.
        var_exp = self.likelihood.variational_expectations(fmean, fvar, self.Y)

        # re-scale for minibatch size
        scale = tf.cast(self.num_data, settings.float_type) / tf.cast(tf.shape(self.X)[0], settings.float_type)

        return tf.reduce_sum(var_exp) * scale - KL
1101668
def profile(self, func):
        
        pr = cProfile.Profile()
        pr.runcall(func)
        st = pstats.Stats(pr)
        st.stream = None  # make it picklable
        st.strip_dirs()

        # Adds a new profile to the existing accumulated value
        self._accumulator.add(st)
136753
def profileFromPNG(inp):
    
    r = png.Reader(file=inp)
    _, chunk = r.chunk('iCCP')
    i = chunk.index(b'\x00')
    name = chunk[: i]
    compression = chunk[i + 1]
    assert compression == 0
    profile = zlib.decompress(chunk[i + 2:])
    return profile, name
307513
def compute(self):
        """"""
        self._compute_window_size()
        smooth = []
        residual = []

        x, y = self.x, self.y

        # step through x and y data with a window window_size wide.
        self._update_values_in_window()
        self._update_mean_in_window()
        self._update_variance_in_window()
        for i, (xi, yi) in enumerate(zip(x, y)):
            if ((i - self._neighbors_on_each_side) > 0.0 and
                    (i + self._neighbors_on_each_side) < len(x)):
                self._advance_window()
            smooth_here = self._compute_smooth_during_construction(xi)
            residual_here = self._compute_cross_validated_residual_here(xi, yi, smooth_here)
            smooth.append(smooth_here)
            residual.append(residual_here)

        self._store_unsorted_results(smooth, residual)
861161
def default_profiler(f, _type, _value):
    ''' 
    '''
    try:
        profile_print(
            '\n'.join([
                get_frame_src(f),
                get_locals(f),
                '----------------------------------------'
            ])
        )
    except:
        pass
1322009
def update(self, z):
        

        # run update on each filter, and save the likelihood
        for i, f in enumerate(self.filters):
            f.update(z)
            self.likelihood[i] = f.likelihood

        # update mode probabilities from total probability * likelihood
        self.mu = self.cbar * self.likelihood
        self.mu /= np.sum(self.mu)  # normalize

        self._compute_mixing_probabilities()

        # compute mixed IMM state and covariance and save posterior estimate
        self._compute_state_estimate()
        self.x_post = self.x.copy()
        self.P_post = self.P.copy()
353366
def profileit(path=None):
    

    def inner(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            prof = cProfile.Profile()
            retval = prof.runcall(func, *args, **kwargs)
            if path is not None:
                print prof.print_stats()
                prof.dump_stats(os.path.expanduser(path))
            else:
                print prof.print_stats()
            return retval
        return wrapper
    return inner
109467
def profiler(self):
        """"""
        logging.info('Loading profiles')
        # Initialise variables
        profiledata = defaultdict(make_dict)
        reverse_profiledata = dict()
        profileset = set()
        # Find all the unique profiles to use with a set
        for sample in self.runmetadata.samples:
            if sample.general.bestassemblyfile != 'NA':
                if sample[self.analysistype].profile != 'NA':
                    profileset.add(sample[self.analysistype].profile)
        # Extract the profiles for each set
        for sequenceprofile in profileset:
            #
            if sequenceprofile not in self.meta_dict:
                self.meta_dict[sequenceprofile] = dict()
            reverse_profiledata[sequenceprofile] = dict()
            self.meta_dict[sequenceprofile]['ND'] = dict()
            # Clear the list of genes
            geneset = set()
            # Calculate the total number of genes in the typing scheme
            for sample in self.runmetadata.samples:
                if sample.general.bestassemblyfile != 'NA':
                    if sequenceprofile == sample[self.analysistype].profile:
                        geneset = {allele for allele in sample[self.analysistype].alleles}
            try:
                # Open the sequence profile file as a dictionary
                profile = DictReader(open(sequenceprofile), dialect='excel-tab')
            # Revert to standard comma separated values
            except KeyError:
                # Open the sequence profile file as a dictionary
                profile = DictReader(open(sequenceprofile))
            # Iterate through the rows
            for row in profile:
                # Populate the profile dictionary with profile number: {gene: allele}. Use the first field name,
                # which will be either ST, or rST as the key to determine the profile number value
                allele_comprehension = {gene: allele for gene, allele in row.items() if gene in geneset}
                st = row[profile.fieldnames[0]]
                for header, value in row.items():
                    value = value if value else 'ND'
                    if header not in geneset and header not in ['ST', 'rST']:
                        if st not in self.meta_dict[sequenceprofile]:
                            self.meta_dict[sequenceprofile][st] = dict()
                        if header == 'CC' or header == 'clonal_complex':
                            header = 'CC'
                        self.meta_dict[sequenceprofile][st][header] = value
                        self.meta_dict[sequenceprofile]['ND'][header] = 'ND'
                        self.meta_dict[sequenceprofile][st]['PredictedSerogroup'] = 'ND'
                        if header not in self.meta_headers:
                            self.meta_headers.append(header)
                profiledata[sequenceprofile][st] = allele_comprehension
                # Create a 'reverse' dictionary using the the allele comprehension as the key, and
                # the sequence type as the value - can be used if exact matches are ever desired
                reverse_profiledata[sequenceprofile].update({frozenset(allele_comprehension.items()): st})
            # Add the profile data, and gene list to each sample
            for sample in self.runmetadata.samples:
                if sample.general.bestassemblyfile != 'NA':
                    if sequenceprofile == sample[self.analysistype].profile:
                        # Populate the metadata with the profile data
                        sample[self.analysistype].profiledata = profiledata[sample[self.analysistype].profile]
                        sample[self.analysistype].reverse_profiledata = reverse_profiledata[sequenceprofile]
                        sample[self.analysistype].meta_dict = self.meta_dict[sequenceprofile]
                else:
                    sample[self.analysistype].profiledata = 'NA'
                    sample[self.analysistype].reverse_profiledata = 'NA'
                    sample[self.analysistype].meta_dict = 'NA'