Examples and Quickstart¶
Astro Objects¶
Create a single image with a star¶
The astro module contain a number of astronomy objects. In this notebook, we will go over creating an instance of a star object, how to generate a star image with and without noise, and display the results.
import numpy as np
import matplotlib.pyplot as plt
from deepbench.astro_object import StarObject
from deepbench.image import SkyImage
from deepbench.collection import Collection
The first step is to initilize the star class¶
Inputs include the dimension of the image (a square), noise, radius, and amplitude. Here we introduce no noise:
star = StarObject(
image_dimensions = 28,
noise = 0.0,
radius= 0.2,
amplitude = 5.0
)
Generate multiple stars¶
The input is x and y positions. The output is an image of a star at that position.
First, generate random x and y positions.
x_position, y_position = np.random.default_rng().uniform(low=1, high=27, size=(2, 5))
plt.clf()
plt.scatter(x_position, y_position)
plt.xlabel('x_position')
plt.ylabel('y_position')
plt.title('5 randomly generated x and y positions')
#plt.aspect_ratio('square')
plt.show()
Generate stars for each randonly generated x and y position¶
generated_stars = []
for x_pos, y_pos in zip(x_position, y_position):
generated_stars.append(star.create_object(x_pos, y_pos))
Sum and plot the resulting images¶
With overlayed original x and y positions.
plt.clf()
plt.imshow(np.sum(generated_stars, axis = 0), origin = 'lower')
plt.scatter(x_position, y_position, color = 'red')
plt.show()
Repeat the analysis with noise¶
star_noisy = StarObject(
image_dimensions = 28,
noise = 0.1,
radius= 0.8,
amplitude = 5.0
)
generated_stars_noisy = []
for x_pos, y_pos in zip(x_position, y_position):
generated_stars_noisy.append(star_noisy.create_object(x_pos, y_pos))
plt.clf()
plt.imshow(np.sum(generated_stars_noisy, axis = 0), origin = 'lower')
plt.scatter(x_position, y_position, color = 'red')
plt.show()
# Now create a sky image with a combination of astro objects
sky_image = SkyImage(
image_shape=(28,28),
object_noise_level=0.1
) # Add .2 sigma of guassian noise
# A single star in a noisy image
noisy_star = sky_image.combine_objects(
objects=["star","galaxy"],
instance_params=[{'noise':0.2, 'radius':0.8, 'amplitude':1},
{'radius':5, 'amplitude':10}],
object_params=[{'center_x':14, 'center_y':14},
{'center_x':10, 'center_y':5}]
)
plt.imshow(noisy_star)
<matplotlib.image.AxesImage at 0x12b315e10>
Physics Objects¶
Newtonian Pendulum¶
The pendulum object is one of the physics objects. This notebook runs through a couple of examples of initilizing the pendulum class, creating realizations with and without noise, and plotting the result.
import numpy as np
import matplotlib.pyplot as plt
from deepbench.physics_object import Pendulum
The first step is to initilize the pendulum class¶
Inputs include the arm length, the starting angle, and the acceleration due to gravity. The acceleration due to gravity is not required if newton's gravitational constant and phi planet are provided. (We give an example of a hierarchical pendulum below.) The pendulum class also requires 'noise_std_percent', which is a dictionary with the percent error for each parameter.
pendulum = Pendulum(
pendulum_arm_length=10.0,
starting_angle_radians=np.pi / 4,
acceleration_due_to_gravity=9.8,
noise_std_percent={
"pendulum_arm_length": 0.0,
"starting_angle_radians": 0.1,
"acceleration_due_to_gravity": 0.1,
},
)
Generate positions¶
Next, create an array of times and use the 'create_object' to draw the position at all these points in time. The noiseless parameter determines whether noise is added to the positions in time.
time = np.array(np.linspace(0, 50, 200))
pendulum_noisy = pendulum.create_object(time, noiseless=False)
pendulum_noiseless = pendulum.create_object(time, noiseless=True)
plt.clf()
plt.plot(time, pendulum_noisy, color = '#832161')
plt.scatter(time, pendulum_noisy, label = 'Noisy draws', color = '#832161')
plt.plot(time, pendulum_noiseless, color = '#EDCBB1')
plt.scatter(time, pendulum_noiseless, label = 'Noise free draws', color = '#EDCBB1')
legend = plt.legend(loc="upper right", edgecolor="black")
legend.get_frame().set_alpha(1.0)
plt.xlabel('time [s]')
plt.ylabel('x position of pendulum')
plt.show()
Hamiltonian Pendulum¶
The Hamiltonian pendulum object is one of the physics objects. This notebook runs through a couple of examples in initilizing the pendulum class and plotting the result.
import numpy as np
import matplotlib.pyplot as plt
import sys, os
MAIN_DIR = os.path.dirname(os.path.abspath(''))
sys.path.insert(0, f'{MAIN_DIR}')
from deepbench.physics_object.hamiltonian_pendulum import HamiltonianPendulum
The first step is to initilize the pendulum class¶
Inputs include the arm length, the starting angle, and the acceleration due to gravity. The pendulum class also requires 'noise_std_percent', which is a dictionary with the percent error for each parameter.
pendulum = HamiltonianPendulum(
pendulum_arm_length=10.0,
starting_angle_radians=np.pi / 4,
acceleration_due_to_gravity=9.8,
noise_std_percent={
"pendulum_arm_length": 0.0,
"starting_angle_radians": 0.0,
"acceleration_due_to_gravity": 0.0,
},
)
Draw Diagrams¶
Next, create an array of times and use the 'create_object' returning an array containing q, p, dq/dt, dp/dt, and time steps respectively. Observe the phase space and position and time plots.
time = np.array(np.linspace(0, 50, 200))
pendulum_data = pendulum.create_object(time)
fig = plt.figure(figsize=(15, 5), facecolor='white')
ax = fig.add_subplot(1,2,1)
plt.scatter(pendulum_data[0], pendulum_data[1], label='Data', color = '#832161')
plt.xlabel("Position (q)", fontsize=14, labelpad=10)
plt.ylabel("Momentun (p)", fontsize=14, labelpad=10)
plt.title("Phase Space")
plt.legend(loc='upper right')
ax = fig.add_subplot(1,2,2)
plt.plot(pendulum_data[4], pendulum_data[0], label='Data', color = '#832161')
plt.ylabel("Position (q)", fontsize=14, labelpad=10)
plt.xlabel("Time", fontsize=14, labelpad=10)
plt.title("Position Vs. Time")
plt.legend(loc='upper right')
plt.show()
Shape Objects¶
Create a single image with shapes¶
The shape module contain a number of geometric shapes. In this notebook, we will go over creating a instance of Shapes
and how to generate shapes with and without noise, and display the results.
import matplotlib.pyplot as plt
from deepbench.shapes import Shapes
from deepbench.image import ShapeImage
from deepbench.collection import Collection
Noiseless Image¶
The first example shows how to create multiple objects without noise added to the image. We'll look at a couple of different objects and their parameters.
shapes = Shapes(image_shape=(28,28)) # Make an instance of the Shapes class
line = shapes.create_line() # Create a line using the random defaults
plt.imshow(line)
plt.show()
# Create a rectangle specifying the specific center and width/length
rectange = shapes.create_rectangle(
center=(10,10),
width=2,
height=8)
plt.imshow(rectange)
plt.show()
# Create a filled-in circle
circle = shapes.create_ellipse(center=(8, 6), width=12, height=12, fill=True)
plt.imshow(circle)
plt.show()
Noisy Image¶
Now, we'll add noise to all those images using the ShapeImage
class.
The ShapeImage
both combines shapes and adds noise to the image.
You can make either single shape images, or add many together.
shape_image = ShapeImage(
image_shape=(28,28),
object_noise_level=0.2
) # Add .2 sigma of guassian noise
# A single rectangle in a noisy image
noisy_rectangle = shape_image.combine_objects(
objects=["rectangle"],
instance_params={},
object_params={} # Using all the default values
)
plt.imshow(noisy_rectangle)
<matplotlib.image.AxesImage at 0x14853afe0>
# An image with both noise and multiple shapes
noisy_rectange = shape_image.combine_objects(
objects=["ellipse", "rectangle"],
instance_params=[{},{}],
object_params=[
{"center":(14,10), "fill":True}, # The circle parameters
{"center":(14,18)} # The rectangle parameters
]
)
plt.imshow(noisy_rectange)
<matplotlib.image.AxesImage at 0x14877caf0>
Using a collection¶
If you want to do this same thing, but keep track of the parameters and the default values, we recommend you use a Collection
.
This has a similar interface to the Image
type objects, but work through initializing the Collection
with the full parameters of your dataset.
import numpy as np
shape_config = {
"object_type": "shape", # Defines that this is a shape module
"object_name": "ShapeImage", # Class used to generate the image
"total_runs": 1,
"image_parameters": {
"image_shape": (28, 28),
"object_noise_level": 0.2 # Collection noise level
},
"object_parameters": {
"rectangle": { # First object in the image
"object": {
"width": np.random.default_rng().integers(2, 28),
"height": np.random.default_rng().integers(2, 28),
"fill": True
},
"instance": {}
},
"arc":{ # Second object in the image
"object": {
"radius": np.random.default_rng().integers(2, 6),
"theta1":np.random.default_rng().integers(0, 20),
"theta2":np.random.default_rng().integers(60, 180)
},
"instance":{}
}}
}
shape_collection = Collection(object_config=shape_config) # initalize
shape_collection() # generate the images
plt.imshow(shape_collection.objects[0]) # First and only image in the collection
plt.show()
shape_collection.object_params[0]
{'object_noise_type': 'gaussian', 'object_noise_level': 0.2, 'seed': 241557, 'rectangle': {'object': {'width': 16, 'height': 24, 'fill': True}, 'instance': {}}, 'arc': {'object': {'radius': 3, 'theta1': 5, 'theta2': 129}, 'instance': {}}, 'image_shape': (28, 28)}