I have total 335 data of four columns has values of the metrics, gain, bandwidth, unitygainfrequency and phasemargin. which has its own min and max values (45.1211, 57.941), (4133.38, 194990), (2392690, 42348400), and (60.007, 74.9746) respectively for each individual metrics.
the data is present in the xls(excel file), all these four metrics are independent and each having its own scaling factor.
I am doing reinforcement learning, for that i need target metrics. from the 355 data i need to choose the optimal bounds for each metrics, i.e., i need to calculate the bounds for each metrics and that bounds should be with in the other three bounds. i need to get the optimal values of the bounds of these four metrics all together, the bound region must be not worst case it must be best case and it should be achievable during training. how to do this.
i tested by choosing random bounds with in the values for each metrics, for this case during training only few(lessthan four) metrics are able to reach the target. not four random pick are able to reach the target. if we choose the values properly with in the optimal bounds then we can able to achieve all the target metrics during training and testing.
Assistant
To determine the optimal bounds for each metric in your reinforcement learning task, you need to find a region within the 335 samples where all four metrics can achieve their targets simultaneously. Here's a step-by-step approach to determine these optimal bounds.
Step 1: Data Preprocessing
First, load and preprocess the data from your Excel file:
python
import pandas as pd
# Load the data
data = pd.read_excel('your_data_file.xlsx')
# Assuming column names are 'gain', 'bandwidth', 'unitygainfrequency', 'phasemargin'
gain = data['gain']
bandwidth = data['bandwidth']
unitygainfrequency = data['unitygainfrequency']
phasemargin = data['phasemargin']
Step 2: Explore Data Distribution
Visualize the distribution of each metric to understand the data better:
python
import seaborn as sns
import matplotlib.pyplot as plt
sns.histplot(gain, kde=True)
plt.title('Gain Distribution')
plt.show()
sns.histplot(bandwidth, kde=True)
plt.title('Bandwidth Distribution')
plt.show()
sns.histplot(unitygainfrequency, kde=True)
plt.title('Unity Gain Frequency Distribution')
plt.show()
sns.histplot(phasemargin, kde=True)
plt.title('Phase Margin Distribution')
plt.show()
Step 3: Define Initial Bounds
Based on the histogram plots and provided min and max values, set the initial bounds:
python
gain_bounds = (45.1211, 57.941) # Given min and max
bandwidth_bounds = (4133.38, 194990) # Given min and max
unitygainfrequency_bounds = (2392690, 42348400) # Given min and max
phasemargin_bounds = (60.007, 74.9746) # Given min and max
Step 4: Search for Optimal Bounds
Create a method to iterate over possible bounds within the provided ranges, looking for regions where all four metrics can reach their targets simultaneously. Here's an example using a grid search approach:
python
import numpy as np
# Define a function to check if a given set of bounds is feasible
def is_feasible(gain_range, bandwidth_range, unitygainfrequency_range, phasemargin_range):
return all([
(gain >= gain_range[0]) & (gain <= gain_range[1]),
(bandwidth >= bandwidth_range[0]) & (bandwidth <= bandwidth_range[1]),
(unitygainfrequency >= unitygainfrequency_range[0]) & (unitygainfrequency <= unitygainfrequency_range[1]),
(phasemargin >= phasemargin_range[0]) & (phasemargin <= phasemargin_range[1])
])
# Example iteration
best_bounds = None
best_count = 0
step_size = 10 # Define the granularity of the search
# Iterate over possible ranges
for gain_min in np.arange(gain_bounds[0], gain_bounds[1], step_size):
for gain_max in np.arange(gain_min + step_size, gain_bounds[1] + step_size, step_size):
for bandwidth_min in np.arange(bandwidth_bounds[0], bandwidth_bounds[1], step_size):
for bandwidth_max in np.arange(bandwidth_min + step_size, bandwidth_bounds[1] + step_size, step_size):
for unitygainfrequency_min in np.arange(unitygainfrequency_bounds[0], unitygainfrequency_bounds[1], step_size):
for unitygainfrequency_max in np.arange(unitygainfrequency_min + step_size, unitygainfrequency_bounds[1] + step_size, step_size):
for phasemargin_min in np.arange(phasemargin_bounds[0], phasemargin_bounds[1], step_size):
for phasemargin_max in np.arange(phasemargin_min + step_size, phasemargin_bounds[1] + step_size, step_size):
feasible_count = is_feasible((gain_min, gain_max), (bandwidth_min, bandwidth_max), (unitygainfrequency_min, unitygainfrequency_max), (phasemargin_min, phasemargin_max)).sum()
if best_bounds is None or feasible_count > best_count:
best_bounds = ((gain_min, gain_max), (bandwidth_min, bandwidth_max), (unitygainfrequency_min, unitygainfrequency_max), (phasemargin_min, phasemargin_max))
best_count = feasible_count
print(f'Optimal bounds: {best_bounds}')
print(f'Number of feasible samples: {best_count}')
Step 5: Validate the Optimal Bounds
Once you have determined the optimal bounds, validate the result by checking the proportion of data samples that fall within these bounds:
Step 6: Integrate with Your Reinforcement Learning Task
Using the determined bounds, integrate them into your reinforcement learning training setup:
python
optimal_bounds = {
'gain': gain_range,
'bandwidth': bandwidth_range,
'unitygainfrequency': unitygainfrequency_range,
'phasemargin': phasemargin_range
}
# Use these bounds to define your reward function or constraints in RL
By following this approach, you can determine optimal bounds for each metric that are feasible and lead to achievable training targets in your reinforcement learning task.
User
all these four metrics are independent with each other and all these four metrics are dependent with the circuit design parameters which are my input action space
Assistant
Given that all four metrics are independent of each other with respect to their values, but are all influenced by the circuit design parameters (your action space), you can leverage optimization techniques to search for the optimal bounds for these metrics. These bounds should ensure that the design parameters can achieve the desired performance metrics reliably.
The following approach will outline the steps to determine the optimal bounds and integrate this insight into your reinforcement learning (RL) framework.
Step 1: Load and Preprocess Data
We will start by loading the data from your Excel file and examining the distributions of each metric.
python
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Load the data
data = pd.read_excel('your_data_file.xlsx')
# Inspect the dataframe
print(data.head())
# Plot distributions
sns.histplot(data['gain'], kde=True)
plt.title('Gain Distribution')
plt.show()
sns.histplot(data['bandwidth'], kde=True)
plt.title('Bandwidth Distribution')
plt.show()
sns.histplot(data['unitygainfrequency'], kde=True)
plt.title('Unity Gain Frequency Distribution')
plt.show()
sns.histplot(data['phasemargin'], kde=True)
plt.title('Phase Margin Distribution')
plt.show()
Step 2: Extract Initial Bounds
Let's review the provided min and max values to define the initial candidate bounds.
Getting the following error:
Traceback (most recent call last):
File "D:\OPAMP CIRCUITS\RLGNN_LTSpice\Bounds_Predict.py", line 80, in
feasible_count = is_feasible((gain_min, gain_max), (bandwidth_min, bandwidth_max), (unitygainfrequency_min, unitygainfrequency_max), (phasemargin_min, phasemargin_max)).sum()
File "D:\OPAMP CIRCUITS\RLGNN_LTSpice\Bounds_Predict.py", line 59, in is_feasible
return all([
File "C:\Users\neosr\AppData\Roaming\Python\Python310\site-packages\pandas\core\generic.py", line 1527, in nonzero
raise ValueError(
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Assistant
The error you are encountering is because you are trying to use the all function on a list of pandas Series objects, which is not directly supported in this way. Each comparison inside the all function returns a Series, and all is attempting to evaluate the truth value of a Series, which is ambiguous.
Instead, you should use the & operator to combine all the boolean Series results, and then use .sum() and .shape[0] as appropriate to count the number of feasible samples.
Here's how you can modify the is_feasible function to properly handle pandas Series:
python
User
i have seen in one research paper that they having two input parameters and they are changing that input and getting two output parameters, they plot the two output parameter with each other and calculating the entire output space region and with in the boundary, they select small region as a target values(bounds/region of two target metrics). In my case i am having four output performance metrics. how ca i do it.
Assistant
To handle four output performance metrics and determine an optimal region within the output space, you can follow a similar process to the one described in the research paper you mentioned. However, because visualizing four-dimensional output space is more complex, we'll break down the steps to plot and select a feasible region.
Here's a step-by-step approach:
Step 1: Load and Preprocess Data
Start by loading your data.
python
import pandas as pd
# Load the data
data = pd.read_excel('your_data_file.xlsx')
print(data.head())
Step 2: Visualize Pairwise Relationships
Visualizing pairwise relationships between the four metrics can help you understand the data distribution and dependencies.
python
import seaborn as sns
import matplotlib.pyplot as plt
# Creating pairplot
sns.pairplot(data)
plt.show()
Step 3: Identify Feasible Regions
You can use clustering techniques such as K-means or DBSCAN to identify dense regions in the data that could serve as feasible regions.
python
from sklearn.cluster import KMeans
# Example using KMeans
num_clusters = 5
kmeans = KMeans(n_clusters=num_clusters)
clusters = kmeans.fit_predict(data)
data['Cluster'] = clusters
# Plot the clusters for visual inspection
sns.pairplot(data, hue='Cluster')
plt.show()
Step 4: Select the Optimal Region
Select the cluster (or clusters) that represent the optimal region for your metrics. You can plot the data points and highlight clusters to identify the best one manually or automated.
python
User
i got the following results
Optimal bounds:
Gain: (45.3072, 57.8757)
Bandwidth: (8665.52, 52868.0)
Unity Gain Frequency: (6718930, 11033300)
Phase Margin: (60.041, 74.9746)
Number of feasible samples: 104
here it gives 104 feasible samples, can i able to get the training target and testing target from the samples both are need to be cover entire region with in the feasible samples and testing target must not repeated in training target( training target from feasible sample must cover all the region with in the feasible sample space and the testing target from the feasible sample must cover all the region with in the feasible sample space but target and training sample must not same)
Assistant
Yes, you can split the feasible samples into training and testing sets such that both sets cover the entire feasible region, without any overlap between them. Here's how you can do this:
Sample the Feasible Data: Identify the feasible samples within the bounds.
Split the Feasible Data: Divide the feasible samples into training and testing sets.
Ensure Coverage: Make sure both training and testing sets cover the entire feasible region.
Here's a step-by-step implementation in Python:
Step 1: Identify Feasible Samples
First, let's identify the feasible samples based on the obtained bounds:
python
import pandas as pd
# Assuming optimal bounds
optimal_bounds = {
'gain': (45.3072, 57.8757),
'bandwidth': (8665.52, 52868.0),
'unitygainfrequency': (6718930, 11033300),
'phasemargin': (60.041, 74.9746)
}
# Load the data if not already loaded
data = pd.read_excel('your_data_file.xlsx')
# Filtering the feasible samples
feasible_samples = data[
(data['gain'] >= optimal_bounds['gain'][0]) & (data['gain'] <= optimal_bounds['gain'][1]) &
(data['bandwidth'] >= optimal_bounds['bandwidth'][0]) & (data['bandwidth'] <= optimal_bounds['bandwidth'][1]) &
(data['unitygainfrequency'] >= optimal_bounds['unitygainfrequency'][0]) & (data['unitygainfrequency'] <= optimal_bounds['unitygainfrequency'][1]) &
(data['phasemargin'] >= optimal_bounds['phasemargin'][0]) & (data['phasemargin'] <= optimal_bounds['phasemargin'][1])
]
print(f'Number of feasible samples: {feasible_samples.shape[0]}')
Step 2: Split the Feasible Data Into Training and Testing Sets
We can use stratified sampling to ensure both sets cover the feasible region. A common way to ensure stratification is by using K-means clustering to group similar samples and then split the clusters.
python
User
This is how my existing code is implemented for generating training and testing target metrics an the selected target metrics are save and load in both training and testing functions, in this implementation i need to replace the exising 'generate_random_targets' function in to selective feasible sample for both training and testing process which covers entire region of feasible sample region and should not be repeated in both training and testing target
def load_training_state(filepath='training_state_TrainTest5.pt'):
if os.path.isfile(filepath):
state = torch.load(filepath)
return state
else:
return None
Assistant
To replace your existing generate_random_targets function with a new function that selects feasible samples for both training and testing such that they cover the entire feasible sample region without overlap, you'll need to:
Identify the feasible samples based on the provided bounds.
Divide these feasible samples into training and testing sets to ensure coverage of the entire region.
Implement the new function to replace generate_random_targets in both the training and testing code.
Step-by-Step Implementation
Step 1: Identify Feasible Samples
First, we update the generate_feasible_targets function to identify feasible samples:
We will perform a grid search over possible metric ranges to find a set of ranges that maximizes the number of feasible samples.
python
import itertools
best_bounds = None
best_count = 0
# Example iteration using grid search
step_size = 10 # Define the granularity of the search
# Define possible ranges for each metric
gain_values = np.linspace(gain_bounds[0], gain_bounds[1], step_size)
bandwidth_values = np.linspace(bandwidth_bounds[0], bandwidth_bounds[1], step_size)
unitygainfrequency_values = np.linspace(unitygainfrequency_bounds[0], unitygainfrequency_bounds[1], step_size)
phasemargin_values = np.linspace(phasemargin_bounds[0], phasemargin_bounds[1], step_size)
# Generate combinations of min and max values within the given ranges
for gain_min, gain_max in itertools.combinations(gain_values, 2):
for bandwidth_min, bandwidth_max in itertools.combinations(bandwidth_values, 2):
for unitygainfrequency_min, unitygainfrequency_max in itertools.combinations(unitygainfrequency_values, 2):
for phasemargin_min, phasemargin_max in itertools.combinations(phasemargin_values, 2):
feasible_count = is_feasible(data, (gain_min, gain_max),
(bandwidth_min, bandwidth_max),
(unitygainfrequency_min, unitygainfrequency_max),
(phasemargin_min, phasemargin_max)).sum()
if feasible_count > best_count:
best_bounds = ((gain_min, gain_max),
(bandwidth_min, bandwidth_max),
(unitygainfrequency_min, unitygainfrequency_max),
(phasemargin_min, phasemargin_max))
best_count = feasible_count
print(f'Optimal bounds: {best_bounds}')
print(f'Number of feasible samples: {best_count}')
Step 5: Validate Optimal Bounds
Once you determine the optimal bounds, validate them to ensure that these bounds are achievable and practical.
Step 6: Integrate Optimal Bounds into RL Framework
Finally, incorporate these bounds into your reinforcement learning environment. You can use these bounds to define your reward function, constrain your action space, or guide the exploration strategy.
python
optimal_bounds = {
'gain': gain_range,
'bandwidth': bandwidth_range,
'unitygainfrequency': unity_gain_range,
'phasemargin': phase_margin_range
}
# Example of using in a reward function
def reward_function(state):
gain, bandwidth, unitygainfrequency, phasemargin = state
reward = 0
if gain_range[0] <= gain <= gain_range[1]:
reward += 1
if bandwidth_range[0] <= bandwidth <= bandwidth_range[1]:
reward += 1
if unity_gain_range[0] <= unitygainfrequency <= unity_gain_range[1]:
reward += 1
if phase_margin_range[0] <= phasemargin <= phase_margin_range[1]:
reward += 1
return reward
# Example of using in action constraints
def sample_action_within_bounds(action_space, optimal_bounds):
# Sample an action within the optimal bounds
action = np.random.uniform(action_space.low, action_space.high)
action = np.clip(action, optimal_bounds['gain'][0], optimal_bounds['gain'][1]) # ... and similarly for other metrics
return action
# In the training loop
# for each episode:
# action = sample_action_within_bounds(action_space, optimal_bounds)
By following these steps, you can systematically determine the optimal bounds for your metrics, ensuring that your RL agent can achieve its target metrics during training and testing.
def is_feasible(data, gain_range, bandwidth_range, unitygainfrequency_range, phasemargin_range):
gain_check = (data['gain'] >= gain_range[0]) & (data['gain'] <= gain_range[1])
bandwidth_check = (data['bandwidth'] >= bandwidth_range[0]) & (data['bandwidth'] <= bandwidth_range[1])
unitygainfrequency_check = (data['unitygainfrequency'] >= unitygainfrequency_range[0]) & (data['unitygainfrequency'] <= unitygainfrequency_range[1])
phasemargin_check = (data['phasemargin'] >= phasemargin_range[0]) & (data['phasemargin'] <= phasemargin_range[1])
return gain_check & bandwidth_check & unitygainfrequency_check & phasemargin_check
# Example usage in your grid search
best_bounds = None
best_count = 0
step_size = 10 # Define the granularity of the search
# Define possible ranges for each metric
gain_values = np.linspace(gain_bounds[0], gain_bounds[1], step_size)
bandwidth_values = np.linspace(bandwidth_bounds[0], bandwidth_bounds[1], step_size)
unitygainfrequency_values = np.linspace(unitygainfrequency_bounds[0], unitygainfrequency_bounds[1], step_size)
phasemargin_values = np.linspace(phasemargin_bounds[0], phasemargin_bounds[1], step_size)
# Generate combinations of min and max values within the given ranges
for gain_min, gain_max in itertools.combinations(gain_values, 2):
for bandwidth_min, bandwidth_max in itertools.combinations(bandwidth_values, 2):
for unitygainfrequency_min, unitygainfrequency_max in itertools.combinations(unitygainfrequency_values, 2):
for phasemargin_min, phasemargin_max in itertools.combinations(phasemargin_values, 2):
feasible_count = is_feasible(data, (gain_min, gain_max),
(bandwidth_min, bandwidth_max),
(unitygainfrequency_min, unitygainfrequency_max),
(phasemargin_min, phasemargin_max)).sum()
if feasible_count > best_count:
best_bounds = ((gain_min, gain_max),
(bandwidth_min, bandwidth_max),
(unitygainfrequency_min, unitygainfrequency_max),
(phasemargin_min, phasemargin_max))
best_count = feasible_count
print(f'Optimal bounds: {best_bounds}')
print(f'Number of feasible samples: {best_count}')
This approach properly handles the boolean series for each metric check and combines them using the & operator. Then the resulting feasible samples are counted using .sum() which aggregates the boolean results. This should resolve the ValueError you were encountering.
Note:
Here, itertools.combinations is used to generate pairs of min and max values over the search range.
data should be the pandas DataFrame containing your metrics. Make sure the DataFrame is correctly loaded and passed to the is_feasible function.
# Determine the metrics range for the selected cluster
optimal_cluster = 0 # Example, you decide the optimal cluster after visual inspection or objective metrics
optimal_data = data[data['Cluster'] == optimal_cluster]
gain_range = (optimal_data['gain'].min(), optimal_data['gain'].max())
bandwidth_range = (optimal_data['bandwidth'].min(), optimal_data['bandwidth'].max())
unitygainfrequency_range = (optimal_data['unitygainfrequency'].min(), optimal_data['unitygainfrequency'].max())
phasemargin_range = (optimal_data['phasemargin'].min(), optimal_data['phasemargin'].max())
print(f'Optimal bounds:')
print(f'Gain: {gain_range}')
print(f'Bandwidth: {bandwidth_range}')
print(f'Unity Gain Frequency: {unitygainfrequency_range}')
print(f'Phase Margin: {phasemargin_range}')
Step 5: Validate Optimal Bounds
Validate the selected bounds to ensure they encompass a significant portion of the feasible data.
Step 6: Integrate Optimal Bounds into RL Framework
Integrate the identified optimal bounds into your reinforcement learning setup as target values.
python
optimal_bounds = {
'gain': gain_range,
'bandwidth': bandwidth_range,
'unitygainfrequency': unitygainfrequency_range,
'phasemargin': phasemargin_range
}
# Example of using in a reward function
def reward_function(state):
gain, bandwidth, unitygainfrequency, phasemargin = state
reward = 0
if gain_range[0] <= gain <= gain_range[1]:
reward += 1
if bandwidth_range[0] <= bandwidth <= bandwidth_range[1]:
reward += 1
if unitygainfrequency_range[0] <= unitygainfrequency <= unitygainfrequency_range[1]:
reward += 1
if phasemargin_range[0] <= phasemargin <= phasemargin_range[1]:
reward += 1
return reward
# Example of using in action constraints
def sample_action_within_bounds(action_space, optimal_bounds):
# Sample an action within the optimal bounds
action = np.random.uniform(action_space.low, action_space.high)
action = np.clip(action, optimal_bounds['gain'][0], optimal_bounds['gain'][1]) # ... and similarly for other metrics
return action
# In the training loop
# for each episode:
# action = sample_action_within_bounds(action_space, optimal_bounds)
Notes:
Clustering: Use clustering techniques to find dense regions in your data. Adjust the number of clusters and clustering method based on the specific characteristics of your data.
Feasibility Check: After identifying the optimal bounds, always validate them to ensure a significant portion of your data falls within these bounds.
RL Integration: Use the identified bounds to guide your RL exploration and reward mechanisms, ensuring the agent aims to achieve values within these feasible and optimal regions.
from sklearn.cluster import KMeans
from sklearn.model_selection import train_test_split
# K-means clustering to ensure coverage
num_clusters = min(10, feasible_samples.shape[0]) # Adjust the number of clusters as needed
kmeans = KMeans(n_clusters=num_clusters, random_state=42)
clusters = kmeans.fit_predict(feasible_samples[['gain', 'bandwidth', 'unitygainfrequency', 'phasemargin']])
feasible_samples['Cluster'] = clusters
# Split each cluster into training and testing set
train_samples = pd.DataFrame()
test_samples = pd.DataFrame()
for cluster in range(num_clusters):
cluster_data = feasible_samples[feasible_samples['Cluster'] == cluster]
train_cluster, test_cluster = train_test_split(cluster_data, test_size=0.3, random_state=42)
train_samples = train_samples.append(train_cluster)
test_samples = test_samples.append(test_cluster)
# Drop the 'Cluster' column as it's no longer needed
train_samples = train_samples.drop(columns=['Cluster'])
test_samples = test_samples.drop(columns=['Cluster'])
print(f'Training samples: {train_samples.shape[0]}')
print(f'Testing samples: {test_samples.shape[0]}')
# Ensure the regions are covered by checking stats
print('\nTraining Set Coverage:')
print(train_samples.describe())
print('\nTesting Set Coverage:')
print(test_samples.describe())
Step 3: Validate Coverage
Ensure that both training and testing sets adequately cover the entire feasible region:
Clustering: K-means clustering is used here for ensuring region coverage. You can adjust the number of clusters based on the complexity of your data.
Splitting: The train_test_split function is used to evenly split each cluster into training and testing sets. Adjust test_size based on your requirements.
Plotting: The plot_coverage function helps visually inspect the coverage of training and testing sets in pairwise dimensions to ensure they span the feasible region adequately.
This method ensures that both training and testing sets cover the entire feasible sample space, satisfying your requirement that each set must not have overlapping data but should cover the feasible region completely.
# Load test state if exists
saved_test_state = load_test_state()
if saved_test_state:
test_targets = saved_test_state['test_targets']
rewards_log = saved_test_state['rewards_log']
metrics_log = saved_test_state['metrics_log']
start_target_index = saved_test_state['current_target_index'] + 1
print(f"Resuming from target index {start_target_index}")
else:
start_target_index = 0
if not test_targets:
saved_state = load_training_state()
if saved_state and 'test_targets' in saved_state:
test_targets = saved_state['test_targets']
else:
test_targets = CircuitEnvironment.generate_random_targets(num_targets=num_targets, seed=1)
for i in range(start_target_index, num_targets):
target = test_targets[i]
node_features_tensor, edge_index, performance_metrics = env.reset(target)
# remaining codes
save_test_state(test_targets, rewards_log, metrics_log, i, filepath='test_state_TrainTest5.pt')
Step 4: Use the New Function in Training and Testing
Update your training and testing functions to use the new methods:
python
# Updated Training Function
def train(env, agent, num_episodes, max_timesteps):
data = pd.read_excel('your_data_file.xlsx') # Load your data
optimal_bounds = {
'gain': (45.3072, 57.8757),
'bandwidth': (8665.52, 52868.0),
'unitygainfrequency': (6718930, 11033300),
'phasemargin': (60.041, 74.9746)
}
feasible_samples = CircuitEnvironment.generate_feasible_targets(data,
optimal_bounds['gain'],
optimal_bounds['bandwidth'],
optimal_bounds['unitygainfrequency'],
optimal_bounds['phasemargin'])
train_samples, test_samples = CircuitEnvironment.split_feasible_samples(feasible_samples)
train_targets = train_samples[['gain', 'bandwidth', 'unitygainfrequency', 'phasemargin']].values
test_targets = test_samples[['gain', 'bandwidth', 'unitygainfrequency', 'phasemargin']].values
# Initialize the episode to start from and log lists
start_episode = 0
rewards_log = []
losses_log = []
metrics_log = []
episode_lengths = []
# Attempt to load the saved state
saved_state = load_training_state()
if saved_state:
start_episode = saved_state['episode'] + 1 # Start from the next episode
agent.actor.load_state_dict(saved_state['actor_state_dict'])
agent.critic.load_state_dict(saved_state['critic_state_dict'])
agent.optimizer_actor.load_state_dict(saved_state['optimizer_actor_state_dict'])
agent.optimizer_critic.load_state_dict(saved_state['optimizer_critic_state_dict'])
rewards_log = saved_state['rewards_log']
losses_log = saved_state['losses_log']
metrics_log = saved_state['metrics_log']
train_targets = saved_state['train_targets']
test_targets = saved_state['test_targets']
print(f"Resuming from episode {start_episode}")
for episode in range(start_episode, num_episodes):
target = train_targets[episode % len(train_targets)]
node_features_tensor, edge_index, performance_metrics = env.reset(target)
# remaining codes
save_training_state(agent, episode, rewards_log, losses_log, metrics_log, train_targets, test_targets)
# Updated Test Function
def test(env, agent, num_targets, max_timesteps_per_target=300, test_targets=None):
rewards_log = []
metrics_log = []
# Load test state if exists
saved_test_state = load_test_state()
if saved_test_state:
test_targets = saved_test_state['test_targets']
rewards_log = saved_test_state['rewards_log']
metrics_log = saved_test_state['metrics_log']
start_target_index = saved_test_state['current_target_index'] + 1
print(f"Resuming from target index {start_target_index}")
else:
start_target_index = 0
if test_targets is None:
data = pd.read_excel('your_data_file.xlsx')
optimal_bounds = {
'gain': (45.3072, 57.8757),
'bandwidth': (8665.52, 52868.0),
'unitygainfrequency': (6718930, 11033300),
'phasemargin': (60.041, 74.9746)
}
feasible_samples = CircuitEnvironment.generate_feasible_targets(data,
optimal_bounds['gain'],
optimal_bounds['bandwidth'],
optimal_bounds['unitygainfrequency'],
optimal_bounds['phasemargin'])
train_samples, test_samples = CircuitEnvironment.split_feasible_samples(feasible_samples)
test_targets = test_samples[['gain', 'bandwidth', 'unitygainfrequency', 'phasemargin']].values
for i in range(start_target_index, num_targets):
target = test_targets[i]
node_features_tensor, edge_index, performance_metrics = env.reset(target)
# remaining codes
save_test_state(test_targets, rewards_log, metrics_log, i, filepath='test_state_TrainTest5.pt')
Summary:
Feasible targets are generated based on the optimal bounds.
Feasible samples are split into training and testing sets, ensuring coverage of the entire region.
The generate_random_targets function is replaced by methods that leverage feasible samples and split them appropriately.
The training and testing functions are updated to use the new methods, ensuring no overlap between training and testing targets while covering the feasible region.