Project: s41467-025-57031-1 | Function: run (python)

system: You are an expert Python programmer implementing algorithms from scientific papers.
Complete the masked function based on the algorithm description.
Follow Python best practices and maintain consistent code style.
Return **only** the complete Python function code.

user: Complete this Python function:

**DESCRIPTION:** Main genetic algorithm implementation for regulatory sequence optimization. Performs iterative evolution with selection, mutation, crossover, and elite preservation over multiple generations.

**KEY TERMS:** {
  "MaxIter": "maximum iterations",
  "P_elite": "elite preservation ratio",
  "P_new": "new offspring ratio",
  "select_parent": "parent selection",
  "act": "genetic operations"
}

**CONTEXT CODE:** import Levenshtein

EPS = 2 ** (-5)

class GeneticAthm():
    def __init__(self,
                 generator_path,
                 predictor_ec_path,
                 predictor_pa_path,
                 z_dim=64,
                 mode="econly"):
        
        device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.z_dim = z_dim
        self.x = np.random.normal(size=(3200,z_dim))
        self.mode = mode
        
        self.Generator = AAE().to(device)
        self.Generator.load_state_dict(torch.load(generator_path))
        self.Generator.eval()
        _, self.Seqs = self.Generator.generate_seq_opt(sample_number=3200, z=torch.tensor(self.x, dtype=torch.float32))
        
        self.Predictor_EC = PredictorNet_language(model_name = "pred_ec", length=165)
        self.Predictor_PA = PredictorNet_language(model_name = "pred_pa", length=165)
        self.predictor_ec_path, self.predictor_pa_path = predictor_ec_path, predictor_pa_path
        
        self.Score = self.score_calculation(self.Seqs)
        self.oh = seq2onehot(self.Seqs, 165)
    
    def score_calculation(self, seqs):
        """
        Calculates optimization scores for regulatory sequences based on EC and PA predictions.

        This function implements the multi-task optimization scoring system for the DeepCROSS
        genetic algorithm. It calculates objective function values based on E. coli (EC) and
        P. aeruginosa (PA) predictions using different optimization modes (econly, paonly, ecpa).
        The scoring applies conditional logic with log2 transformations as described in the paper.

        Args:
            seqs: Input regulatory sequences for score calculation

        Returns:
            numpy.ndarray: Calculated optimization scores for the input sequences

        Raises:
            NotImplementedError: Function has been masked for testing purposes
        """
        raise NotImplementedError("This function has been masked for testing purposes")
            
        
    def run(self,
            outdir='../results/GAfinal',
            MaxPoolsize=2000,
            P_rep=0.3,
            P_new=0.25,
            P_elite=0.25,
            MaxIter=2000):
        """
        Main genetic algorithm implementation for regulatory sequence optimization.

        This function performs iterative evolution of regulatory sequences using a genetic
        algorithm approach as described in the DeepCROSS paper. It executes selection,
        mutation, crossover, and elite preservation operations over multiple generations
        to optimize sequences for species-preferred or cross-species regulatory activity.

        Args:
            outdir: Output directory for saving results (default: '../results/GAfinal')
            MaxPoolsize: Maximum population size for the genetic algorithm (default: 2000)
            P_rep: Repetition probability threshold for duplicate removal (default: 0.3)
            P_new: Proportion of new offspring generated each iteration (default: 0.25)
            P_elite: Proportion of elite individuals preserved (default: 0.25)
            MaxIter: Maximum number of iterations to run (default: 2000)

        Returns:
            None: Results are saved to output directory

        Raises:
            NotImplementedError: Function has been masked for testing purposes
        """
        raise NotImplementedError("This function has been masked for testing purposes")
    
    def PMutate(self, z): 
        p = np.random.randint(0,z.shape[0])
        z[p] = np.random.normal()
        return
    
    def Reorganize(self, z, Parent): 
        index = np.random.randint(0, 1,size=(z.shape[0]))
        j = np.random.randint(0, Parent.shape[0])
        for i in range(z.shape[0]):
            if index[i] == 1:
                z[i] = Parent[j,i].copy()
        return
    
    def select_parent(self,Nnew, Nelite, Poolsize):
        ParentFromElite = min(Nelite,Nnew//2)
        ParentFromNormal = min(Poolsize-Nelite, Nnew-ParentFromElite)
        I_e = random.sample([ i for i in range(Nelite)], ParentFromElite)
        I_n = random.sample([ i+Nelite for i in range(Poolsize - Nelite)], ParentFromNormal)
        I = I_e + I_n
        return I

    def act(self, Parent):
        for i in range(Parent.shape[0]):
            action = np.random.randint(0,1)
            if action == 0:
                self.PMutate(Parent[i,:])
            elif action == 1:
                self.Reorganize(Parent[i,:], Parent)
        return Parent
    
    def delRep(self, Onehot, p):
        I = set()
        n = Onehot.shape[0]
        i = 0
        while i < n-1:
            if i not in I:
                a = Onehot[i,:,:]
                a = np.reshape(a,((1,)+a.shape))
                a = np.repeat(a,n-i-1,axis=0)
                I_new = np.where(( np.sum(np.abs(a - Onehot[(i+1):,:,:]),axis=(1,2)) / (Onehot.shape[1]*2) ) < p)[0]
                I_new = I_new + i+1
                I = I|set(I_new)
            i += 1
        return list(I)


def plot_boxplot(plot_path, barplot_data):
    
    sns.set_style("darkgrid")
    font = {'size' : 8}
    matplotlib.rc('font', **font)
    rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) 
    fig, ax = plt.subplots(figsize = (20,10), dpi = 600) # (7,11)

    ax = sns.boxplot( x="label", y="prediction",  data=barplot_data,  boxprops=dict(alpha=.9), hue="species", 
                      fliersize=1, flierprops={"marker": 'x'}, palette=["cornflowerblue", "indianred"])
    h,_ = ax.get_legend_handles_labels()

    plt.xticks(rotation=270)
    
    ax.set_xlabel('Controlling', fontsize=10)
    ax.set_ylabel('Predictions', fontsize=10)
    ax.spines['left'].set_visible(True)
    ax.spines['bottom'].set_visible(True)
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)

    plt.title("")
    plt.tight_layout()


Complete the function implementation replacing "raise NotImplementedError".