Project: s41467-025-59198-z | Function: feature_map_deterministic (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:** Computes deterministic feature maps for quantum circuit parameters using truncated trigonometric expansions with bounded Hamming weight. Implements the core feature mapping algorithm that transforms quantum circuit parameters into feature vectors weighted by powers of 2 based on frequency support size.

**KEY TERMS:** {
  "sampled_W": "frequency vectors w",
  "Lambda": "truncation parameter",
  "hamming_weights": "Hamming weight ||w||_0",
  "weight_factors": "exponential weights 2^||w||_0",
  "f_x_w": "trigonometric functions"
}

**CONTEXT CODE:** # Shadow data in

# Metrics

def evaluate_predictions(predictions, test_results):
    """
    Evaluate the relation between predictions and test results using R^2
    and Pearson correlation coefficient.

    Args:
    - predictions (numpy.ndarray): Predicted values.
    - test_results (numpy.ndarray): True test results.

    Returns:
    - dict: A dictionary containing R^2 and Pearson correlation coefficient.
    """
    # Compute R^2 score
    r2 = r2_score(test_results, predictions)

    # Compute Pearson correlation coefficient
    pearson_corr, _ = pearsonr(test_results, predictions)

    return {"R^2": r2, "Pearson Correlation": pearson_corr}

"""# Proposed ML Surrogates"""

def generate_frequency_vectors(input_dim, Lambda):
    """
    Generate frequency vectors with truncated Hamming weight up to Lambda.

    Args:
        input_dim (int): Dimensionality of the input data (number of features).
        Lambda (int): Maximum Hamming weight for the truncated frequency set.

    Returns:
        numpy.ndarray: Frequency matrix of shape (n_vectors, input_dim),
                       where n_vectors is determined by input_dim and Lambda.
    """
    frequency_vectors = []
    frequency_vectors.append(np.zeros(input_dim)) # frequence vector with zero Hamming weight
    for hamming_weight in range(1, Lambda + 1):
        for indices in combinations(range(input_dim), hamming_weight):
            for signs in product([-1, 1], repeat=hamming_weight):
                freq_vector = np.zeros(input_dim)
                for idx, sign in zip(indices, signs):
                    freq_vector[idx] = sign
                frequency_vectors.append(freq_vector)

    return np.array(frequency_vectors)

def feature_map_deterministic(data, Lambda):
    """
    Compute a deterministic feature map based on truncated Hamming weight.

    This function implements the deterministic feature mapping algorithm described in the paper
    "Efficient learning for linear properties of bounded-gate quantum circuits" (Nature Communications,
    s41467-025-59198-z) for truncated trigonometric expansion.

    Computes deterministic feature maps for quantum circuit parameters using truncated trigonometric
    expansions with bounded Hamming weight. Transforms quantum circuit parameters into feature vectors
    weighted by powers of 2 based on frequency support size.

    Paper reference: "the truncated trigonometric monomial kernel with Phi_omega(x) where omega in
    {0,1,-1}^d is the trigonometric monomial basis"

    Formula: features = 2^||w||_0 * Product_j[f_w_j(x_j)] where f_0=1, f_1=cos(x), f_{-1}=sin(x)

    Args:
        data (numpy.ndarray): Input matrix of shape (n_samples, input_dim).
        Lambda (int): Maximum Hamming weight for the truncated frequency set.

    Returns:
        numpy.ndarray: Feature map matrix of shape (n_samples, n_vectors),
                       where n_vectors is determined by input_dim and Lambda.
    """
    # MASKED: Deterministic feature mapping for quantum circuit prediction
    raise NotImplementedError(
        "This function is masked for testing purposes. "
        "Original function computes deterministic feature maps for quantum circuit parameters using "
        "truncated trigonometric expansions with bounded Hamming weight as described in Nature Communications "
        "article s41467-025-59198-z. Key operations: frequency vector generation, array broadcasting, "
        "conditional trigonometric function application, product computation, weighted transformations "
        "by exponential factors 2^||w||_0 for efficient quantum circuit learning."
    )

##################################
## Implementation of Surrogate ###
##################################


# Generate deterministic feature map by using the ideal_dataset and shadow_dataset
def ML_predictor(J_, h_, idea_setting_, num_train_, num_test_, Lambda_, results_file_path, model_file_path_):

    if idea_setting_ is True:
        data_all = load_dataset(dataset_file_path, J_, h_, True)

        train_data =  np.array(data_all['para'])[:num_train_]
        train_data = np.reshape(train_data, newshape = (num_train_, -1))
        train_labels = np.array(data_all['labels'])[:num_train_]

        test_data = np.array(data_all['para'])[-num_test_:]
        test_data = np.reshape(test_data, newshape = (num_test_, -1))
        test_labels = np.array(data_all['labels'])[-num_test_:]
    else:
        data_all = load_dataset(dataset_file_path, J_, h_, False)
        train_data =  np.array(data_all['parameters'])[:num_train_]
        train_data = np.reshape(train_data, newshape = (num_train_, -1))
        train_labels = np.array(data_all['shadow_labels'])[:num_train_]
        train_labels  = np.squeeze(train_labels)

        test_data = np.array(data_all['parameters'])[-num_test_:]
        test_data = np.reshape(test_data, newshape = (num_test_, -1))
        test_labels = np.array(data_all['shadow_labels'])[-num_test_:]
        test_labels  = np.squeeze(test_labels)

    # Feature map implementation
    feature_map_trunc = feature_map_deterministic(train_data, Lambda_)
    print("Feature Map Shape:", feature_map_trunc.shape)
    # Model training
    model_Trunc = Ridge(alpha=1)
    model_Trunc.fit(feature_map_trunc, train_labels)

    # Predict on new transformed data
    phi_new = feature_map_deterministic(test_data, Lambda_)
    predictions = model_Trunc.predict(phi_new)

    # Evaluate
    metrics = evaluate_predictions(predictions, test_labels)
    mse = mean_squared_error(test_labels, predictions)
    print(f"Mean Squared Error: {mse}")
    print("Evaluation Metrics:")
    print(f"R^2: {metrics['R^2']:.4f}")
    print(f"Pearson Correlation: {metrics['Pearson Correlation']:.4f}")

    # Prepare results for JSON
    result = {
        "J": J_,
        "h": h_,
        "mse": mse,
        "metrics": {
            "R^2": metrics["R^2"],
            "Pearson Correlation": metrics["Pearson Correlation"]
        }
    }

    # Save results to JSON
    try:
        with open(results_file_path, "r") as f:
            all_results = json.load(f)
    except FileNotFoundError:


Complete the function implementation replacing "raise NotImplementedError".