<commit_before>/*
 * MarkovChain.java
 *
 * Copyright (C) 2002-2006 <NAME> and <NAME>
 *
 * This file is part of BEAST.
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership and licensing.
 *
 * BEAST is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 *  BEAST is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with BEAST; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA  02110-1301  USA
 */

package dr.inference.markovchain;

import dr.evomodel.operators.AbstractImportanceDistributionOperator;
import dr.evomodel.operators.SimpleMetropolizedGibbsOperator;
import dr.inference.model.Likelihood;
import dr.inference.model.Model;
import dr.inference.model.CompoundLikelihood;
import dr.inference.operators.*;
import dr.inference.prior.Prior;

import java.util.ArrayList;
import java.util.logging.Logger;

/**
 * A concrete markov chain. This is final as the only things that should need
 * overriding are in the delegates (prior, likelihood, schedule and acceptor).
 * The design of this class is to be fairly immutable as far as settings goes.
 *
 * @author <NAME>
 * @author <NAME>
 * @version $Id: MarkovChain.java,v 1.10 2006/06/21 13:34:42 rambaut Exp $
 */
public final class MarkovChain {

    private final static boolean DEBUG = false;

    private final OperatorSchedule schedule;
    private final Acceptor acceptor;
    private final Prior prior;
    private final Likelihood likelihood;

    private boolean pleaseStop = false;
    private boolean isStopped = false;
    private double bestScore, currentScore, initialScore;
    private int currentLength;

    private boolean useCoercion = true;

    private final int fullEvaluationCount;
    private final int minOperatorCountForFullEvaluation = 1;

    public MarkovChain(Prior prior, Likelihood likelihood,
                       OperatorSchedule schedule, Acceptor acceptor,
                       int fullEvaluationCount, boolean useCoercion) {
        currentLength = 0;
        this.prior = prior;
        this.likelihood = likelihood;
        this.schedule = schedule;
        this.acceptor = acceptor;
        this.useCoercion = useCoercion;

        this.fullEvaluationCount = fullEvaluationCount;

        currentScore = evaluate(likelihood, prior);
    }

    /**
     * Resets the markov chain
     */
    public void reset() {
        currentLength = 0;

        // reset operator acceptance levels
        for(int i = 0; i < schedule.getOperatorCount(); i++) {
            schedule.getOperator(i).reset();
        }
    }

    /**
     * Run the chain for a given number of states.
     *
     * @param length
     *            number of states to run the chain.
     * @param onTheFlyOperatorWeights
     */
    public int chain(int length, boolean disableCoerce,
                     int onTheFlyOperatorWeights) {

        currentScore = evaluate(likelihood, prior);

        int currentState = currentLength;

        final Model currentModel = likelihood.getModel();

        if( currentState == 0 ) {
            initialScore = currentScore;
            bestScore = currentScore;
            fireBestModel(currentState, currentModel);
        }

        if( currentScore == Double.NEGATIVE_INFINITY ) {

            // identify which component of the score is zero...
            if( prior != null ) {
                double logPrior = prior.getLogPrior(likelihood.getModel());

                if( logPrior == Double.NEGATIVE_INFINITY ) {
                    throw new IllegalArgumentException(
                            "The initial model is invalid because one of the priors has zero probability.");
                }
            }

            String message = "The initial likelihood is zero";
            if( likelihood instanceof CompoundLikelihood ) {
                message += ": " + ((CompoundLikelihood) likelihood).getDiagnosis();
            } else {
                message += "!";
            }
            throw new IllegalArgumentException(message);
        }

        pleaseStop = false;
        isStopped = false;

        int otfcounter = onTheFlyOperatorWeights > 0 ? onTheFlyOperatorWeights : 0;

        double[] logr = {0.0};

        boolean usingFullEvaluation = true;
        boolean fullEvaluationError = false;

        while( !pleaseStop && (currentState < (currentLength + length)) ) {

            // periodically log states
            fireCurrentModel(currentState, currentModel);

            if( pleaseStop ) {
                isStopped = true;
                break;
            }

            // Get the operator
            final int op = schedule.getNextOperatorIndex();
            final MCMCOperator mcmcOperator = schedule.getOperator(op);

            double oldScore = currentScore;

            // assert Profiler.startProfile("Store");

            // The current model is stored here in case the proposal fails
            if( currentModel != null ) {
                currentModel.storeModelState();
            }

            // assert Profiler.stopProfile("Store");

            boolean operatorSucceeded = true;
            double hastingsRatio = 1.0;
            boolean accept = false;<commit_msg>Temporary solution before full code review: if fullEvaluationCount == 0, then switch off usingFullEvaluation<commit_after>/*
 * MarkovChain.java
 *
 * Copyright (C) 2002-2006 <NAME> and <NAME>
 *
 * This file is part of BEAST.
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership and licensing.
 *
 * BEAST is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 *  BEAST is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with BEAST; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA  02110-1301  USA
 */

package dr.inference.markovchain;

import dr.evomodel.operators.AbstractImportanceDistributionOperator;
import dr.evomodel.operators.SimpleMetropolizedGibbsOperator;
import dr.inference.model.Likelihood;
import dr.inference.model.Model;
import dr.inference.model.CompoundLikelihood;
import dr.inference.operators.*;
import dr.inference.prior.Prior;

import java.util.ArrayList;
import java.util.logging.Logger;

/**
 * A concrete markov chain. This is final as the only things that should need
 * overriding are in the delegates (prior, likelihood, schedule and acceptor).
 * The design of this class is to be fairly immutable as far as settings goes.
 *
 * @author <NAME>
 * @author <NAME>
 * @version $Id: MarkovChain.java,v 1.10 2006/06/21 13:34:42 rambaut Exp $
 */
public final class MarkovChain {

    private final static boolean DEBUG = false;

    private final OperatorSchedule schedule;
    private final Acceptor acceptor;
    private final Prior prior;
    private final Likelihood likelihood;

    private boolean pleaseStop = false;
    private boolean isStopped = false;
    private double bestScore, currentScore, initialScore;
    private int currentLength;

    private boolean useCoercion = true;

    private final int fullEvaluationCount;
    private final int minOperatorCountForFullEvaluation = 1;

    public MarkovChain(Prior prior, Likelihood likelihood,
                       OperatorSchedule schedule, Acceptor acceptor,
                       int fullEvaluationCount, boolean useCoercion) {
        currentLength = 0;
        this.prior = prior;
        this.likelihood = likelihood;
        this.schedule = schedule;
        this.acceptor = acceptor;
        this.useCoercion = useCoercion;

        this.fullEvaluationCount = fullEvaluationCount;

        currentScore = evaluate(likelihood, prior);
    }

    /**
     * Resets the markov chain
     */
    public void reset() {
        currentLength = 0;

        // reset operator acceptance levels
        for(int i = 0; i < schedule.getOperatorCount(); i++) {
            schedule.getOperator(i).reset();
        }
    }

    /**
     * Run the chain for a given number of states.
     *
     * @param length
     *            number of states to run the chain.
     * @param onTheFlyOperatorWeights
     */
    public int chain(int length, boolean disableCoerce,
                     int onTheFlyOperatorWeights) {

        currentScore = evaluate(likelihood, prior);

        int currentState = currentLength;

        final Model currentModel = likelihood.getModel();

        if( currentState == 0 ) {
            initialScore = currentScore;
            bestScore = currentScore;
            fireBestModel(currentState, currentModel);
        }

        if( currentScore == Double.NEGATIVE_INFINITY ) {

            // identify which component of the score is zero...
            if( prior != null ) {
                double logPrior = prior.getLogPrior(likelihood.getModel());

                if( logPrior == Double.NEGATIVE_INFINITY ) {
                    throw new IllegalArgumentException(
                            "The initial model is invalid because one of the priors has zero probability.");
                }
            }

            String message = "The initial likelihood is zero";
            if( likelihood instanceof CompoundLikelihood ) {
                message += ": " + ((CompoundLikelihood) likelihood).getDiagnosis();
            } else {
                message += "!";
            }
            throw new IllegalArgumentException(message);
        }

        pleaseStop = false;
        isStopped = false;

        int otfcounter = onTheFlyOperatorWeights > 0 ? onTheFlyOperatorWeights : 0;

        double[] logr = {0.0};

        boolean usingFullEvaluation = true;
        if (fullEvaluationCount == 0) // Temporary solution until full code review
        	usingFullEvaluation = false;
        boolean fullEvaluationError = false;

        while( !pleaseStop && (currentState < (currentLength + length)) ) {

            // periodically log states
            fireCurrentModel(currentState, currentModel);

            if( pleaseStop ) {
                isStopped = true;
                break;
            }

            // Get the operator
            final int op = schedule.getNextOperatorIndex();
            final MCMCOperator mcmcOperator = schedule.getOperator(op);

            double oldScore = currentScore;

            // assert Profiler.startProfile("Store");

            // The current model is stored here in case the proposal fails
            if( currentModel != null ) {
                currentModel.storeModelState();
            }

            // assert Profiler.stopProfile("Store");

            boolean operatorSucceeded = true;
            double hastingsRatio = 1.0;
            boolean accept = false;
{'fraction_non_alphanumeric': 0.07532601235415237, 'fraction_numerical': 0.008407687028140013, 'mean_word_length': 2.352602818521714, 'pattern_counts': {'":': 2, '<': 15, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '666027', 'n_tokens_mistral': 3076, 'n_tokens_neox': 2818, 'n_words': 1016}