LILY-QML / LLY-DML

LLY-DML is part of the LILY project and is a Quantum Machine Learning model. It uses so-called L-Gates. These gates are Machine Learning gates that modify their state based on an input to map to a desired state of an input.
https://www.lilyqml.de
2 stars 5 forks source link

Class Description: Circuit #19

Open xleonplayz opened 2 weeks ago

xleonplayz commented 2 weeks ago

The Circuit class is used to create, manage, and validate quantum circuits based on input data from JSON files. Additionally, it allows for performing measurements at the end of the circuit.

Class Attributes

Method Descriptions

1. __init__(self, data_path='data.json', train_path='train.json')

Description:

Initializes a new instance of the Circuit class.

Parameters:

Functionality:

Return:


2. read_data(self)

Description:

Reads data from the data.json and train.json files. Extracts basic circuit parameters and activation/training matrices.

Parameters:

Functionality:

  1. Reading data.json:
    • Opens and loads the content of data.json.
    • Extracts qubits (number of qubits) and depth (circuit depth).
    • Outputs a success message with success code 2060.
    • Error handling for missing file or invalid JSON with error code 1060.
  2. Reading train.json:
    • Opens and loads the content of train.json.
    • Extracts activation_matrices and training_matrices.
    • Outputs a success message with success code 2061.
    • Error handling for missing file or invalid JSON with specific error codes (1061).

Return:

Error Handling:


3. convert_input_data(self, option='empty', matrix_name=None)

Description:

Converts raw input data from JSON files into a structured form for circuit creation. There are two options:

Parameters:

Functionality:

  1. Option 'empty':
    • Creates an activation matrix filled with zeros of size [qubits][depth * 3].
    • Verifies if the matrix is indeed empty (_is_empty_matrix).
    • In case of inconsistency, error code 1064 is returned, and the method ends.
  2. Option 'named':
    • Checks if matrix_name is provided. If not, error code 1066 is returned.
    • Retrieves the activation matrix from activation_matrices based on matrix_name.
    • Verifies the matrix's consistency (_is_matrix_consistent).
    • In case of inconsistency, error code 1063 is returned, and the method ends.
  3. Reformatting:
    • Iterates over each row (qubit) and each position (depth), extracts the respective segments of activation and training values.
    • Splits each row of a matrix into 3-part pairs.
    • Creates entries in input_data with the following keys:
      • Row: Specifies the row where the 3-part pair is located.
      • Position: Specifies which 3-part pair it is in the row.
      • ActivationTriple: 3-part pair from the activation matrix.
      • TrainingTriple: 3-part pair from the training matrix.
  4. Verification:
    • Verifies the consistency of the formatted input_data with check_input_data.
    • In case of inconsistency, error code 1061 is returned, and input_data is cleared.

Return:

Error Handling:


4. _is_matrix_consistent(self, matrix)

Description:

Verifies the consistency of a given activation matrix in terms of the number of rows, columns, and data types.

Parameters:

Functionality:

Return:


5. _is_empty_matrix(self, matrix)

Description:

Checks if the given matrix consists solely of zeros.

Parameters:

Functionality:

Return:


6. check_input_data(self)

Description:

Verifies the structure and consistency of input_data.

Parameters:

Functionality:

Return:


7. create_L_gate(self, entry)

Description:

This method creates the parameters for a single L-gate within the quantum circuit based on an entry from input_data. It processes the activation and training data, creates a circuit blueprint for the L-gate, and manages the incrementation of the current position and row. Throughout the process, success codes and error codes are returned to monitor execution status.

Parameters:

Functionality:

  1. Entry Initialization and Validation:

    a. Entry Validation:

    • Description: Ensures entry is a valid dictionary containing all required keys (Row, Position, ActivationTriple, TrainingTriple).
    • Success Code: 2060 – Entry successfully validated.
    • Error Code: 1060 – Invalid entry or missing keys.

    b. List Length Validation:

    • Description: Checks if both ActivationTriple and TrainingTriple are lists with exactly three elements.
    • Success Code: 2061 – List lengths are correct.
    • Error Code: 1061 – Invalid list lengths in ActivationTriple or TrainingTriple.
  2. L-Gate Circuit Creation:

    a. Data Extraction:

    • Description:
      • Retrieves the relevant segment from input_data based on the current Row and Position.
      • Extracts data from the activation matrix (ActivationTriple) and the training matrix (TrainingTriple).
    • Success Code: 2062 – Data successfully extracted.
    • Error Code: 1062 – Error in data extraction.

    b. Data Merging:

    • Description:
      • Combines activation and training values to create parameters for phase gates.
      • Creates a circuit blueprint with the following structure:
        • P(ActivationValue 1)
        • P(TrainingValue 1)
        • H
        • P(ActivationValue 2)
        • P(TrainingValue 2)
        • H
        • P(ActivationValue 3)
        • P(TrainingValue 3)
    • Success Code: 2063 – Circuit blueprint successfully created.
    • Error Code: 1063 – Error in merging data or creating the blueprint.
  3. Position and Row Incrementation:

    a. Position Incrementation:

    • Description: Increments the position counter by 1 to move to the next position within the current row.
    • Success Code: 2064 – Position successfully incremented.
    • Error Code: 1064 – Position exceeds the number of available 3-part pairs in the current row.

    b. Row Incrementation:

    • Description:
      • When the last position of the current row is reached, resets the position counter to 0 and increments the row counter by 1.
      • Starts processing the new row from position 0.
    • Success Code: 2065 – Row successfully incremented and switched to the next row.
    • Error Code: 1065 – No more rows available in input_data (end of data structure).
  4. Circuit Blueprint and Status Code Return:

    a. Successful Creation:

    • Description: Returns the created circuit blueprint for the L-gate along with the appropriate success code.
    • Success Code: 2060 – General success; specific codes like 2061-2065 for intermediate factors.

    b. Error Case:

    • Description: Returns the corresponding error code and an error message if any step fails.
    • Error Code: 1060-1065 – Depending on the encountered error.

Return:

Intermediate Factors and Codes:

Code Description
2060 Entry successfully validated.
2061 Activation and training data list lengths are correct.
2062 Data successfully extracted.
2063 Circuit blueprint successfully created.
2064 Position successfully incremented.
2065 Row successfully incremented and switched to the next row.
1060 Invalid entry or missing keys.
1061 Invalid list lengths in ActivationTriple or TrainingTriple.
1062 Error in data extraction.
1063 Error in merging data or creating the blueprint.
1064 Position exceeds the number of available 3-part pairs.
1065 No more rows available in input_data (end of data structure).

Additional Notes:


Sample Execution:

Successful L-Gate Creation

Input Data (entry):


entry = {
    "Row": 1,
    "Position": 0,
    "ActivationTriple": [10, 20, 30],
    "TrainingTriple": [40, 50, 60]
}
**Sample Execution:**

### Successful L-Gate Creation

**Input Data (`entry`):**

```python
entry = {
    "Row": 1,
    "Position": 0,
    "ActivationTriple": [10, 20, 30],
    "TrainingTriple": [40, 50, 60]
}
Return Value:

json
Code kopieren
{
    "Row": 1,
    "End": true,
    "Gates": [
        "P(10)",
        "P(40)",
        "H",
        "P(20)",
        "P(50)",
        "H",
        "P(30)",
        "P(60)"
    ]
}
Failed L-Gate Creation
Input Data (entry):

python
Code kopieren
entry = {
    "Row": 0,
    "Position": 1,
    "ActivationTriple": [5, 15],  # Missing element
    "TrainingTriple": [25, 35, 45]
}
Return Value:

json
Code kopieren
{
    "ErrorCode": 1061,
    "ErrorMessage": "Invalid list lengths in 'ActivationTriple' or 'TrainingTriple'."
}

### 8. `create_initial_circuit(self)`

**Description:**

This method creates the initial circuit (`circuit`). The following steps are carried out:

1. **Pass Matrix Name:**
    - Pass the matrix name.
2. **Read Data:**
    - Call the `read_data` method.
3. **Check Consistency:**
    - Check the consistency of the activation matrix.
4. **Convert Data:**
    - Convert data using the `convert_input_data` method.
5. **Check Input Data:**
    - Check `input_data` using the `check_input_data` method.
6. **Create Circuit:**
    - Initialize the `circuit` with the number of qubits.
    - Loop to create L-gates:
        - Use the `create_L_gate` method, which returns the subcircuit.
        - Append the subcircuit to the corresponding qubit in the `circuit`.
        - Continue until the row flag (`End`) is reached.
        - Switch to the next qubit and start circuit realization.
7. **Check Circuit:**
    - Call the `check_circuit` method, which checks the following parameters:
        - Number of qubits matches the value `qubits`.
        - Each qubit has `6 * depth` phase gates.
        - Number of Hadamard gates matches `3 * depth`.

**Error Handling:**

- Error codes `1066` to `1069` for specific errors during circuit creation.

---

### `check_circuit(self)`

**Description:**

This method verifies the created circuit (`circuit`) for consistency in terms of the number of qubits, phase gates, and Hadamard gates.

**Parameters:**

- None.

**Functionality:**

- Verifies that the number of qubits in the `circuit` matches the `qubits` attribute.
- For each qubit:
    - Verifies the number of phase gates (`P` gates) is equal to `6 * depth`.
    - Verifies the number of Hadamard gates (`H`) is equal to `3 * depth`.

**Return:**

- `True` if the circuit is consistent, otherwise `False`.

**Error Handling:**

- Error code `1066`: Incorrect number of qubits in the circuit.
- Error code `1067`: Incorrect number of phase gates on a qubit.
- Error code `1068`: Incorrect number of Hadamard gates on a qubit.

---

### `measure(self, shots)`

**Description:**

This method performs measurements on the circuit.

**Parameters:**

- `shots` (`int`): Specifies how many times the circuit is executed.

**Functionality:**

- Executes the circuit `shots` times.
- Stores the measurement results in the `measurements` list.

**Return:**

- Returns the measurement results.

**Success Code:**

- `2066` – Measurements successfully performed.

**Error Code:**

- `1069` – Error during measurements.

---

## Method Overview

Here is a summary of all methods in the `Circuit` class with their associated success and error codes:

| Method                  | Description                                              | Codes                   |
|-------------------------|----------------------------------------------------------|-------------------------|
| `__init__`               | Initializes a new instance of the `Circuit` class.       | -                       |
| `read_data`              | Reads and extracts data from `data.json` and `train.json`. | 2060, 2061 / 1060, 1061 |
| `convert_input_data`     | Converts input data based on the options.                | 2064, 2063 / 1061, 1063, 1064 |
| `_is_matrix_consistent`  | Checks the consistency of an activation matrix.          | -                       |
| `_is_empty_matrix`       | Checks if a matrix consists solely of zeros.             | -                       |
| `check_input_data`       | Checks the structure and consistency of `input_data`.    | -                       |
| `create_L_gate`          | Creates a circuit blueprint for an L-gate based on an entry. | 2060-2065 / 1060-1065 |
| `create_initial_circuit` | Creates the initial circuit based on the converted data. | 2066 / 1066-1069        |
| `check_circuit`          | Checks the consistency of the created circuit.           | 1066-1068               |
| `measure`                | Performs measurements on the circuit and returns the results. | 2066 / 1069        |