Here's the refined code that properly handles batch generation with your single_data_generator() function:
import numpy as np
import tensorflow as tf
from concurrent.futures import ThreadPoolExecutor
import os
def generate_batch_dataset(
batch_size,
single_data_generator,
generator_kwargs=None
):
"""Generate a batch of synthetic data with numerical safeguards."""
if generator_kwargs is None:
generator_kwargs = {}
I_batch = []
dos_s_batch = []
z_batch = []
for i in range(batch_size):
I_V, dos_s, z = single_data_generator(**generator_kwargs)
I_batch.append(I_V)
dos_s_batch.append(dos_s)
z_batch.append(z)
# Convert lists to tensors
return (
tf.constant(I_batch, dtype=tf.float32),
tf.constant(dos_s_batch, dtype=tf.float32),
tf.constant(z_batch, dtype=tf.float32),
)
def generate_multiple_datasets(
single_data_generator,
num_datasets=5,
N_per_dataset=1000,
batch_size=100, # Process N_per_dataset samples in batches of batch_size
num_points=100,
V_max=10,
z_means=[7.5, 8.0, 6.5],
z_stds=[1.0, 0.8, 1.2],
noise_levels=[0.01, 0.02, 0.01],
rho_s_types=["gaussian", "step", "random"],
save_format="tfrecord",
output_dir="datasets",
normalize_data=True,
):
"""
Generate multiple synthetic datasets in batches with numerical safeguards.
Args:
single_data_generator: Function that generates a single (I, dos_s, z) sample
num_datasets: Number of datasets to generate.
N_per_dataset: Number of samples per dataset.
batch_size: Number of samples processed at once (accelerates CPU operations).
num_points: Number of points in E and V grids.
V_max: Maximum bias voltage (eV).
z_means: List of z means for each dataset.
z_stds: List of z stds for each dataset.
noise_levels: List of noise levels for each dataset.
rho_s_types: List of rho_s types for each dataset.
save_format: Format to save datasets ('tfrecord', 'numpy', or 'hdf5').
output_dir: Directory to save datasets.
normalize_data: Whether to normalize I and dos_s data
"""
# Create output directory
os.makedirs(output_dir, exist_ok=True)
def generate_and_save(i):
"""Helper function to generate and save a single dataset in batches."""
# Initialize arrays for the entire dataset
I_full = []
dos_s_full = []
z_full = []
# Prepare generator kwargs for this dataset
generator_kwargs = {
'num_points': num_points,
'V_max': V_max,
'z_mean': z_means[i % len(z_means)],
'z_std': z_stds[i % len(z_stds)],
'noise_level': noise_levels[i % len(noise_levels)],
'rho_s_type': rho_s_types[i % len(rho_s_types)],
}
# Process in batches
for batch_start in range(0, N_per_dataset, batch_size):
batch_end = min(batch_start + batch_size, N_per_dataset)
batch_N = batch_end - batch_start
# Generate batch
I_batch, dos_s_batch, z_batch = generate_batch_dataset(
batch_size=batch_N,
single_data_generator=single_data_generator,
generator_kwargs=generator_kwargs
)
# Store batch results
I_full.extend(I_batch.numpy())
dos_s_full.extend(dos_s_batch.numpy())
z_full.extend(z_batch.numpy())
# Convert to numpy arrays
I_full = np.array(I_full)
dos_s_full = np.array(dos_s_full)
z_full = np.array(z_full)
# Normalize and clip
if normalize_data:
# Avoid division by zero
I_max = np.max(I_full, axis=1, keepdims=True)
I_max[I_max < 1e-10] = 1.0
I_full = I_full / I_max
dos_s_max = np.max(dos_s_full, axis=1, keepdims=True)
dos_s_max[dos_s_max < 1e-10] = 1.0
dos_s_full = dos_s_full / dos_s_max
z_full = np.clip(z_full, 5.0, 10.0)
# Save based on format
if save_format == "tfrecord":
filename = os.path.join(output_dir, f"dataset_{i}.tfrecord")
write_tfrecord(filename, I_full, dos_s_full, z_full)
elif save_format == "numpy":
np.save(os.path.join(output_dir, f"I_{i}.npy"), I_full)
np.save(os.path.join(output_dir, f"dos_s_{i}.npy"), dos_s_full)
np.save(os.path.join(output_dir, f"z_{i}.npy"), z_full)
elif save_format == "hdf5":
import h5py
filename = os.path.join(output_dir, f"dataset_{i}.h5")
with h5py.File(filename, "w") as f:
f.create_dataset("I", data=I_full)
f.create_dataset("dos_s", data=dos_s_full)
f.create_dataset("z", data=z_full)
print(f"Dataset {i} generated: {len(I_full)} samples")
# Generate datasets in parallel
with ThreadPoolExecutor() as executor:
executor.map(generate_and_save, range(num_datasets))
def write_tfrecord(filename, I_data, dos_s_data, z_data):
"""Write data to TFRecord file."""
with tf.io.TFRecordWriter(filename) as writer:
for j in range(len(I_data)):
example = tf.train.Example(
features=tf.train.Features(
feature={
"I": tf.train.Feature(
float_list=tf.train.FloatList(value=I_data[j])
),
"dos_s": tf.train.Feature(
float_list=tf.train.FloatList(value=dos_s_data[j])
),
"z": tf.train.Feature(
float_list=tf.train.FloatList(value=[z_data[j]])
),
}
)
).SerializeToString()
writer.write(example)
# Example usage with a dummy single_data_generator
def example_single_data_generator(
num_points=100,
V_max=10,
z_mean=7.5,
z_std=1.0,
noise_level=0.01,
rho_s_type='gaussian'
):
"""Example single data generator function."""
# Generate synthetic I(V), dos_s(E), and z
E_grid = np.linspace(0, V_max, num_points)
V_grid = np.linspace(0, V_max, num_points)
# Random z
z = np.random.normal(z_mean, z_std)
z = np.maximum(z, 1e-10) # Ensure z > 0
# Generate dos_s based on type
if rho_s_type == 'gaussian':
dos_s = np.exp(-(E_grid - 3.0)**2 / 0.5)
elif rho_s_type == 'step':
dos_s = np.where(E_grid > 2.0, 1.0, 0.1)
else: # random
dos_s = np.random.uniform(0.1, 1.0, num_points)
# Simplified I(V) calculation (replace with your actual physics)
I_V = dos_s * np.exp(-z/10) # Simplified tunneling
I_V += noise_level * np.random.randn(num_points)
I_V = np.maximum(I_V, 1e-10) # Ensure positive
return I_V, dos_s, z
# Load function for TFRecord
def parse_tfrecord_fn(example):
"""Parse TFRecord example."""
feature_description = {
'I': tf.io.FixedLenFeature([100], tf.float32), # Adjust size as needed
'dos_s': tf.io.FixedLenFeature([100], tf.float32),
'z': tf.io.FixedLenFeature([1], tf.float32)
}
return tf.io.parse_single_example(example, feature_description)
def load_tfrecord_dataset(filename):
"""Load TFRecord dataset."""
dataset = tf.data.TFRecordDataset(filename)
dataset = dataset.map(parse_tfrecord_fn)
return dataset
# Run the generation
if __name__ == "__main__":
generate_multiple_datasets(
single_data_generator=example_single_data_generator,
num_datasets=3,
N_per_dataset=1000,
batch_size=100,
num_points=100,
V_max=10,
z_means=[7.5, 8.0, 6.5],
z_stds=[1.0, 0.8, 1.2],
noise_levels=[0.01, 0.02, 0.01],
rho_s_types=["gaussian", "step", "random"],
save_format="tfrecord",
output_dir="sts_datasets"
)