Project: s41467-025-56749-2 | Function: optimize (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:** Core genetic algorithm implementation for optimizing TFBS-context sequences. Takes initial sequences and iteratively applies mutation and recombination operations guided by deep learning model predictions to evolve sequences with target scores.

**KEY TERMS:** {
  "PMutate_withmask": "single nucleotide mutation",
  "Reorganize": "recombination/crossover",
  "select_parent": "parent selection strategy",
  "genetic algorithm": "optimization algorithm",
  "TFBS-context": "context sequences surrounding TFBSs"
}

**CONTEXT CODE:** 
        f = h5py.File('../0_prepare_training_sample/data_dir/step4_HepG2_motif_center_seq_mask_'+str(seq_len)+'_'+TF_name+'_data.h5', 'r')


        Neg_seqs = f['neg_' + self.TF_name][:]
        Pos_seqs = f['pos_' + self.TF_name][:]
        
        np.random.seed(42)
        np.random.shuffle(Neg_seqs)
        np.random.seed(42)
        np.random.shuffle(Pos_seqs)

        
        dataset_size = min(len(Neg_seqs),len(Pos_seqs))
        self.data_size = dataset_size
        Neg_seq_train = Neg_seqs[0:int(dataset_size*0.8)]
        Pos_seq_train = Pos_seqs[0:int(dataset_size*0.8)]
        Neg_seq_val = Neg_seqs[int(dataset_size*0.8):int(dataset_size*0.9)]
        Pos_seq_val = Pos_seqs[int(dataset_size*0.8):int(dataset_size*0.9)]
        Neg_seq_test = Neg_seqs[int(dataset_size*0.9):dataset_size]
        Pos_seq_test = Pos_seqs[int(dataset_size*0.9):dataset_size]

        train_seq = np.concatenate((Neg_seq_train,Pos_seq_train))
        train_labels = np.concatenate((np.zeros(len(Neg_seq_train)),np.ones(len(Pos_seq_train))))
        val_seq = np.concatenate((Neg_seq_val,Pos_seq_val))
        val_labels = np.concatenate((np.zeros(len(Neg_seq_val)),np.ones(len(Pos_seq_val))))
        test_seq = np.concatenate((Neg_seq_test,Pos_seq_test))
        test_labels = np.concatenate((np.zeros(len(Neg_seq_test)),np.ones(len(Pos_seq_test))))
        self.opti_start_seq = np.copy(test_seq)


        self.dataset_train = DataLoader(dataset=ProbDataset(seq=train_seq,label=train_labels), batch_size=self.batch_size, shuffle=True)
        self.dataset_test = DataLoader(dataset=ProbDataset(seq=val_seq,label=val_labels), batch_size=self.batch_size, shuffle=False)
        self.dataset_test_final = DataLoader(dataset=ProbDataset(seq=test_seq,label=test_labels), batch_size=self.batch_size,shuffle=False)
        self.epoch = 1000


        self.total_train_num = 1
        # it's set to be 10 for ten replicated trained model in the paper
        self.models = []
        for i in range(self.total_train_num):
            model_temp = DenseLSTM_models(input_nc=4, seqL=seq_len, out_length=1, mode=self.mode)
            if self.gpu:
                model_temp=model_temp.cuda()
            model_temp = torch.load('./step0_HepG2_model_path/test_denselstm_mc_0.001_mask_168_'+self.TF_name+'.pth')
            # the path above should contain the variable 'i' as the replicated number in it
            model_temp.eval()
            self.models.append(model_temp)


    def optimize(self):
        """
        Core genetic algorithm implementation for optimizing TFBS-context sequences.

        This function takes initial sequences and iteratively applies mutation and
        recombination operations guided by deep learning model predictions to evolve
        sequences with target scores. The genetic algorithm introduces mutations and
        recombination into the sequences at each optimization step, with the
        TFBS-context model calculating evaluation metrics for each sequence, selecting
        those with higher scores to proceed to the next round.

        Returns:
            int: Status code (0 for successful completion)

        Raises:
            NotImplementedError: Function has been masked for testing purposes
        """
        raise NotImplementedError("This function has been masked for testing purposes")

    def PMutate_withmask(self, z): # single nucleotide mutaion
        z = list(z)
        p_result = np.random.randint(0,4)
        p = np.random.randint(0,len(z))
        while(z[p]=='N'):
            p = np.random.randint(0,len(z))
        list_nuc = ['A','C','G','T']   
        z[p] = list_nuc[p_result]
        z = ''.join(z)
        return z

    def Reorganize(self, z, parent):
        z = list(z)
        index = np.random.randint(0, 2,size=(len(z)))
        j = np.random.randint(0, parent.shape[0])
        z1 = list(parent[j])
        for i in range(len(z)):
            if index[i] == 1:
                z[i] = z1[i]
        z = ''.join(z)
        return z

    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,2)
            if action == 0:
                parent[i] = self.PMutate_withmask(parent[i])
            elif action == 1:
                parent[i] = self.Reorganize(parent[i], parent)
        return parent

    def one_hot_to_seq(self, one_hot):
        mapping = {0: 'A', 1: 'C', 2: 'G', 3: 'T', 4: 'N'}
        seq_lst = []
        for vec in one_hot:
            if sum(vec)==0:
                seq_lst.append('N')
            else:
                seq_lst.append(mapping[np.argmax(vec)])
        seq = ''.join(seq_lst)    
        return seq

    def seq_to_onehot(self, seq_list,length):
        data = np.zeros((len(seq_list),length,4))
        num_dic = {'A':0,'C':1,'G':2,'T':3}
        for i in range(len(seq_list)):
            for j in range(length):
                if seq_list[i][j]=='N':
                    continue
                data[i][j][num_dic[seq_list[i][j]]]=1
        return data



def main():
    os.makedirs('./step1_HepG2_GA_log', exist_ok=True)
    TF_list = ['GATA2']
    for TF_name in TF_list:
        print(TF_name)
        for aim in [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]:
            analysis = Seq2ScalarTraining(TF_name,aim)
            if analysis.data_size<10:
                continue
            analysis.optimize()

if __name__ == '__main__':
    mp.set_start_method('spawn')
    main()



Complete the function implementation replacing "raise NotImplementedError".