Project: s41467-025-57031-1 | Function: score_calculation (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:** Calculates optimization scores for regulatory sequences based on EC and PA predictions using different optimization modes (econly, paonly, ecpa). Applies conditional scoring logic with log2 transformations.

**KEY TERMS:** {
  "pred_ec": "E. coli predictions",
  "pred_pa": "P. aeruginosa predictions",
  "mode": "optimization task type",
  "scores": "objective function values"
}

**CONTEXT CODE:** from collections import Counter

import umap
from sklearn import metrics
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA
from sklearn.cluster import AgglomerativeClustering,DBSCAN,OPTICS, cluster_optics_dbscan
from sklearn.feature_extraction.image import grid_to_graph
from sklearn.neighbors import kneighbors_graph

import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import rc
from matplotlib.pyplot import MultipleLocator
from matplotlib.backends.backend_pdf import PdfPages

from utils.data import load_seq_data, load_supervise_data, split_data
from aae_genus import *

import re, random
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):
    


Complete the function implementation replacing "raise NotImplementedError".