Project: s41467-025-62171-5 | Function: process_seqs (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:** Implements the core sequence processing algorithm that converts mRNA sequences to feature matrices for neural network input. This function performs sequence filtering, length normalization, one-hot encoding, and data preparation steps that are essential for the PAL-AI model's ability to predict poly(A) tail length changes from sequence information.

**KEY TERMS:** {
  "seq_3end_append": "poly(A) tail sequence appended to 3' end",
  "len_max": "maximum sequence length for model input",
  "len_min": "minimum sequence length threshold",
  "X_mat_lst": "encoded feature matrices for neural network",
  "encode_seq": "one-hot encoding transformation",
  "fa_string_filter": "filter for uncertain sequence annotations"
}

**CONTEXT CODE:** 	('l1_reg', 0.001),
	('l2_reg', 0.001),
	('optimizer', 'adam'),
	('learning_rate', 0.001),
	('loss', 'mse'),#custom_loss
	('metrics', 'mae'),
	('batch_size', 50),
	('epochs', 50),
	# resnet-specific parameters
	('resnet_trim', 'left'), # whether to trim input to the ResNet for addition
	('resnet_version', 2), 
	('resnet_n_group', 7), # number of ResNet groups
	('resnet_n_block', 4), # number of ResNet blocks per group
	('dilation_rate_lst', [1,2,4,8,4,2,1]), # dilation rate, length of the list must be the same as 'resnet_n_group'
	# inn-specific parameters
	('n_Conv1D_MaxPool_block', 1),
	('n_pool_size', 2),
	# cinn-specific parameters
	('n_Conv2D_filter', 32),
	('n_Conv2D_kernel', 5),
	('n_Conv2D_MaxPool_block', 1)
])

inn_params_opti = OrderedDict([
	('NAME', 'Optimization parameters'),
	# values are all categoriy lists except those for 'l1_reg', 'l2_reg', 'learning_rate'
	('n_Conv1D_filter', [32, 64, 128]),
	('n_Conv1D_kernel', [4, 5, 6]),
	('n_Conv1D_MaxPool_block', [1, 2, 3]),
 	('n_Conv2D_filter', [64]),
	('n_Conv2D_kernel', [5]),
	('n_Conv2D_MaxPool_block', [1]),
	('n_dense_neuron', [32, 64, 96]),
	('n_pool_size', [2]),
	('rnn_func', ['GRU', 'BiGRU', 'LSTM', 'BiLSTM']),
	('n_rnn_units', [32, 64, 128]),
	('resnet_version', [1, 2]),
	('resnet_n_group', [7]), 
	('resnet_n_block', [4]),
	('activation_func', ['selu', 'silu', 'leaky_relu']),
	('l1_reg', {'min': 0.000001, 'max': 0.01}),
	('l2_reg', {'min': 0.000001, 'max': 0.01}),
	('dropout_rate', [0.1, 0.2, 0.3]),
	('optimizer', ['adam', 'SGD']),
	('learning_rate', {'min': 0.00001, 'max': 0.01}),
	('loss', ['mse', 'mae']),
	('batch_size', [32, 64, 128]),
	('epochs', [30, 40, 50])
])

def process_seqs(line_lst):
	raise NotImplementedError("process_seqs function has been masked for testing purposes")

def model_nn(x_train, y_train, x_val, y_val, params, model_type = 'inn', best_model = False, early_stop = False, gpu_id = None):
	'''
	Train a neural network model with the specified parameters.

	Args:
		x_train, y_train: Training data and target values.
		x_val, y_val: Validation data and target values.
		params: Dictionary of hyperparameters.
		model_type: Type of model to train ('inn', 'resnet', etc.).
		best_model: If True, loads the best saved model after training.
		early_stop: If True, uses early stopping.
		gpu_id: GPU identifier.

	Returns:
		Tuple (training history, trained model, updated params).
	'''

	# Ensure global variables are initialized
	global global_config, inn_params, f_log
	
	# update missing parameters with defaults
	for key in inn_params:
		if key not in params:
			params.update({key: inn_params[key]})

	# make sure input shape is correct
	if params['flag_initial_tl']:
		assert params['input_shape'] == x_train[0].shape[1:]
	else:
		assert params['input_shape'] == x_train.shape[1:]
	
	# load the model for training
	if global_config['n_dimension'] == 3:
		model = inn_models.cinn_model(input_params = params)
	else:
		if model_type == 'resnet':
			# resnet model
			model = inn_models.resnet_model(input_params = params)
		else:
			# inn model
			model = inn_models.inn_model(input_params = params)

	# Print model summary if required
	if global_config['flag_print_model']:
		print(model.summary())
		model.summary(print_fn = lambda x: f_log.write(x + '\n'))
		global_config['flag_print_model'] = False

	# Define callbacks
	device = '_CPU' if gpu_id is None else f'_GPU_{gpu_id}'
	f_best_model = os.path.join(global_config['out_folder'], 'Models', f'{global_config["idf"]}{device}_callback_best_model.keras')
	callbacks = [keras.callbacks.ModelCheckpoint(f_best_model, monitor='val_loss', mode='min', save_best_only=True)]
	if early_stop:
		callbacks.append(keras.callbacks.EarlyStopping(monitor='val_loss', mode='min', patience=10))

	history = model.fit(
		x = x_train, y = y_train, 
		batch_size = params['batch_size'], 
		epochs = params['epochs'], 
		verbose = global_config['verbose'], 
		shuffle = True, 
		callbacks = callbacks, 
		validation_data=(x_val, y_val)
	)

	if best_model:
		pwrite(f_log, 'Return the best model...\n')
		try:
			model = keras.models.load_model(f_best_model)
			#model = keras.models.load_model(f_best_model, custom_objects={'custom_metric': inn_models.custom_metric})
		except Exception as e:
			pwrite(f_log, f"Error loading best model: {e}\n")
			pwrite(f_log, 'Return the final model...\n')
	else:
		pwrite(f_log, 'Return the final model...\n')

	return(history, model, params)
	
def optuna_objective(trial, x_train, y_train, x_val, y_val, params, model_type = 'inn', gpus = None, opti_log = None):
	'''
	Optuna objective function for hyperparameter optimization.

	Args:
		trial: Optuna trial object.
		x_train, y_train: Training data and target values.
		x_val, y_val: Validation data aand target values.
		params: Dictionary of hyperparameters.
		model_type: Type of model to train ('inn', 'resnet', etc.).
		gpus: List of available GPUs (optional).
		opti_log: Path to the log file for optimization results.

	Returns:
		Negative R-squared value for Optuna optimization.
	'''

	# Ensure global variables are initialized
	global global_config, tf_fitted, best_neg_r2, f_log


Complete the function implementation replacing "raise NotImplementedError".