### Initialize Circuit with Filters Source: https://docs.photontorch.com/_sources/examples/02_add_drop_filter.ipynb.txt This example shows how to initialize a Photontorch circuit with pre-defined filters. This is useful for setting up complex optical systems from the start. ```python from photontorch.circuit import Circuit from photontorch.components import Filter # Define filters to be included in the circuit filter1 = Filter(wavelength=1550, bandwidth=10, transmission=0.9) filter2 = Filter(wavelength=1610, bandwidth=5, transmission=0.8) # Initialize the circuit with the filters circuit = Circuit(components=[filter1, filter2]) ``` -------------------------------- ### Basic Photontorch Setup and Usage Source: https://docs.photontorch.com/_sources/examples/00_introduction_to_photontorch.ipynb.txt Demonstrates the initial setup and basic usage of Photontorch, including importing the library and creating a simple simulation. ```python import photontorch as pt import torch # Create a simple simulation sim = pt.Simulation() ``` -------------------------------- ### Install PhotonTorch Source: https://docs.photontorch.com/_sources/examples/00_introduction_to_photontorch.ipynb.txt Install PhotonTorch using pip. This is the first step to using the library. ```bash pip install -U photontorch ``` -------------------------------- ### Ring Network Example Source: https://docs.photontorch.com/_sources/examples/08_general_ring_networks.ipynb.txt This snippet demonstrates a basic ring network setup. Ensure all necessary libraries are imported before use. ```python import torch import torch.nn as nn class RingNetwork(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(RingNetwork, self).__init__() self.layer1 = nn.Linear(input_size, hidden_size) self.relu = nn.ReLU() self.layer2 = nn.Linear(hidden_size, hidden_size) self.output_layer = nn.Linear(hidden_size, output_size) def forward(self, x): x = self.relu(self.layer1(x)) x = self.relu(self.layer2(x)) x = self.output_layer(x) return x # Example Usage: input_size = 10 hidden_size = 20 output_size = 5 model = RingNetwork(input_size, hidden_size, output_size) print(model) ``` -------------------------------- ### Install Photontorch (Development) Source: https://docs.photontorch.com/_sources/index.rst.txt Install the development version of Photontorch by cloning the repository and linking with pip. Includes instructions for installing git hooks. ```bash git clone https://git.photontorch.com/photontorch.git ./install-git-hooks.sh # Unix [Linux/Mac/BSD/...] install-git-hooks.bat # Windows pip install -e photontorch ``` -------------------------------- ### Basic Crow Optimization Setup Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt This snippet shows the fundamental setup for a crow optimization algorithm. It includes necessary imports and the initialization of the optimizer. ```python from crow_optimization import CrowOptimizer # Initialize the optimizer with a function to minimize and bounds optimizer = CrowOptimizer(lambda x: x[0]**2 + x[1]**2, bounds=[(-5, 5), (-5, 5)]) ``` -------------------------------- ### Install Photon-Torch Source: https://docs.photontorch.com/_sources/examples/00_introduction_to_photontorch.ipynb.txt Install Photon-Torch using pip. This command installs the library and its dependencies. ```bash pip install "git+https://github.com/facebookresearch/photontorch.git" ``` -------------------------------- ### Basic Crow Optimization Setup Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt This snippet shows the basic setup for the Crow Optimization Algorithm, including necessary imports and initialization. ```python from crow_optimization import CrowOptimization import numpy as np def objective_function(x): return np.sum(x**2) # Define problem parameters num_variables = 10 lower_bound = -5 upper_bound = 5 population_size = 30 max_iterations = 100 # Initialize the optimizer optimizer = CrowOptimization( objective_function, num_variables, lower_bound, upper_bound, population_size, max_iterations ) ``` -------------------------------- ### Basic Crow Optimization Setup Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt This snippet shows the basic setup for Crow Optimization, including initialization and core parameters. It's useful for understanding the fundamental structure of the algorithm. ```python from crow_optimization import CrowOptimization # Define the objective function to minimize def objective_function(x): return sum(xi**2 for xi in x) # Initialize Crow Optimization optimizer = CrowOptimization( objective_function=objective_function, dimensions=2, lower_bound=-5, upper_bound=5, population_size=30, max_iterations=100, crow_memory_size=2 ) # Run the optimization best_solution, best_fitness = optimizer.optimize() print(f"Best solution found: {best_solution}") print(f"Best fitness: {best_fitness}") ``` -------------------------------- ### Basic Crow Optimization Setup Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt This snippet shows the basic setup for a crow optimization algorithm, including necessary imports and initial parameter definitions. ```python import numpy as np from crow_optimization import CrowOptimizer def objective_function(x): return np.sum(x**2) # Define problem parameters num_variables = 10 lower_bound = -5 upper_bound = 5 # Initialize the optimizer crow_optimizer = CrowOptimizer(objective_function, num_variables, lower_bound, upper_bound) ``` -------------------------------- ### Basic Crow Optimization Setup Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt Initializes and configures the Crow optimization algorithm. This snippet is useful for understanding the basic setup and parameters. ```python from crow_optimization import CrowOptimizer # Define the objective function to minimize def objective_function(x): return sum(xi**2 for xi in x) # Set the dimensions of the problem dimensions = 10 # Set the bounds for each dimension lower_bound = -5 upper_bound = 5 # Initialize the CrowOptimizer crow_optimizer = CrowOptimizer(objective_function, dimensions, lower_bound, upper_bound) ``` -------------------------------- ### Basic Crow Optimization Setup Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt This snippet shows the basic setup for a crow optimization algorithm, including initialization and parameter settings. Ensure all necessary libraries are imported. ```python import numpy as np import matplotlib.pyplot as plt from crow import CrowOptimizer def sphere(x): return np.sum(x**2) # Parameters num_crow = 20 num_dim = 2 max_iter = 100 # Initialize optimizer crow_optimizer = CrowOptimizer(num_crow, num_dim, sphere, max_iter) crow_optimizer.optimize() ``` -------------------------------- ### Initialize Quantum Circuit and Parameters Source: https://docs.photontorch.com/_sources/examples/03_circuit_optimization_by_backpropagation.ipynb.txt Sets up a basic quantum circuit with trainable parameters. This is the starting point for optimization. ```python import pennylane as qml from pennylane import numpy as np num_qubits = 2 qlayer_depth = 2 dev = qml.device("default.qubit", wires=num_qubits) def qlayer(weights): for i in range(num_qubits): qml.RY(weights[i, 0], wires=i) qml.RX(weights[i, 1], wires=i) for i in range(qlayer_depth): for j in range(num_qubits - 1): qml.CNOT(wires=[j, j + 1]) qml.CNOT(wires=[num_qubits - 1, 0]) for i in range(num_qubits): qml.RY(weights[i, 2], wires=i) qml.RX(weights[i, 3], wires=i) @qml.qnode(dev) def circuit(weights): qlayer(weights) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) # Initialize weights randomly np.random.seed(0) weights = np.random.uniform(0, 2 * np.pi, (num_qubits, 4)) ``` -------------------------------- ### Basic Crow Optimization Setup Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt This snippet shows the basic setup for a crow optimization algorithm. It involves defining the objective function and initializing the crow population. ```python import numpy as np def objective_function(x): return np.sum(x**2) # Parameters num_crows = 30 max_iter = 100 # Initialize crow positions randomly within bounds lower_bound = -5 upper_bound = 5 crow_position = np.random.uniform(lower_bound, upper_bound, (num_crows, 2)) # Assuming 2D problem crow_memory = np.copy(crow_position) # Initialize best position found so far best_position = crow_position[np.argmin(np.apply_along_axis(objective_function, 1, crow_position))] ``` -------------------------------- ### Install Photontorch (Stable) Source: https://docs.photontorch.com/_sources/index.rst.txt Install the stable version of Photontorch using pip. This is the recommended method for most users. ```bash pip install photontorch ``` -------------------------------- ### Basic Crow Optimization Setup Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt This snippet shows the basic setup for a crow optimization algorithm, including defining the objective function and initializing parameters. ```python from crow_optimization import CrowOptimization def objective_function(x): return sum(xi**2 for xi in x) # Initialize the optimizer optimizer = CrowOptimization(objective_function, bounds=[(-5, 5)], num_crows=20, max_iter=100) ``` -------------------------------- ### Basic Crow Optimization Setup Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt This snippet shows the basic setup for a crow optimization algorithm. It involves defining the objective function, crow population, and parameters. ```python import numpy as np def crow_optimization(objective_func, bounds, num_crows, max_iter, crow_memory_size): # Initialize crow positions randomly within bounds crow_positions = np.random.uniform(bounds[:, 0], bounds[:, 1], size=(num_crows, len(bounds))) crow_memory = np.copy(crow_positions) crow_food_pos = np.zeros_like(crow_positions) crow_food_num = np.zeros(num_crows, dtype=int) for t in range(max_iter): for i in range(num_crows): # Update crow's food position based on its own experience or a random crow's experience if np.random.rand() < 0.1: # Probability of exploring crow_food_pos[i] = np.random.uniform(bounds[:, 0], bounds[:, 1]) else: # Choose a random crow to learn from j = np.random.randint(num_crows) crow_food_pos[i] = crow_memory[j] # Calculate the step size step = np.random.rand() * (crow_memory[i] - crow_positions[i]) new_position = crow_positions[i] + step # Apply bounds new_position = np.clip(new_position, bounds[:, 0], bounds[:, 1]) # Evaluate the new position if objective_func(new_position) < objective_func(crow_positions[i]): crow_positions[i] = new_position crow_memory[i] = new_position # Update the best known position for each crow for i in range(num_crows): if objective_func(crow_memory[i]) < objective_func(crow_food_pos[i]): crow_food_num[i] += 1 else: crow_memory[i] = crow_food_pos[i] crow_food_num[i] = 0 # Find the best crow position overall best_crow_index = np.argmin([objective_func(m) for m in crow_memory]) best_position = crow_memory[best_crow_index] return best_position, objective_func(best_position) # Example usage: def sphere_function(x): return np.sum(x**2) # Define problem parameters bounds = np.array([[-5, 5], [-5, 5]]) # Bounds for each dimension num_crows = 20 max_iter = 100 crow_memory_size = 10 # This parameter is not used in the provided snippet but is part of the algorithm's concept # Run the optimization best_solution, best_fitness = crow_optimization(sphere_function, bounds, num_crows, max_iter, crow_memory_size) print(f"Best solution found: {best_solution}") print(f"Best fitness: {best_fitness}") ``` -------------------------------- ### Run Full Optical Readout Example Source: https://docs.photontorch.com/_sources/examples/05_optical_readout.ipynb.txt Executes the complete optical readout example pipeline, from loading to visualization. This is a convenience function for running the entire example. ```python from photon_torch.examples.optical_readout import run_optical_readout_example # Run the example with a placeholder file path # Replace 'path/to/your/optical_readout_data.npy' with an actual file path run_optical_readout_example("path/to/your/optical_readout_data.npy") ``` -------------------------------- ### Crow Optimization with Custom Parameters Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt This example demonstrates how to configure the Crow Optimization algorithm with custom parameters such as population size and number of iterations. Ensure the `crow_optimization` library is installed. ```python from crow_optimization import CrowOptimization def another_function(x): return sum([xi**2 for xi in x]) custom_optimizer = CrowOptimization(another_function, bounds=[(-10, 10)], population_size=50, iterations=200, crow_memory_size=10, crow_step_size=0.1) best_solution, best_fitness = custom_optimizer.optimize() print(f"Custom best solution: {best_solution}") print(f"Custom best fitness: {best_fitness}") ``` -------------------------------- ### Real-time Data Streaming Example Source: https://docs.photontorch.com/_sources/examples/05_optical_readout.ipynb.txt Demonstrates setting up the detector for real-time data streaming. This requires a compatible detector and sufficient bandwidth. ```python from photon_readout import Detector detector = Detector() detector.initialize() detector.start_streaming(callback=lambda frame: print(f"Received frame: {frame.shape}")) # Keep the script running to receive frames import time try: while True: time.sleep(1) except KeyboardInterrupt: detector.stop_streaming() print("Streaming stopped.") ``` -------------------------------- ### Basic Crow Optimization Setup Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt This snippet shows the basic setup for the Crow optimization algorithm, including importing necessary libraries and defining the objective function. ```python from crow_optimization import CrowOptimization import numpy as np def objective_function(x): return np.sum(x**2) # Define problem parameters num_variables = 10 lower_bound = -5 upper_bound = 5 population_size = 50 max_iterations = 100 ``` -------------------------------- ### Basic Crow Optimization Setup Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt This snippet shows the basic setup for the Crow optimization algorithm, including importing necessary libraries and defining the objective function. ```python import numpy as np from crow_optimization import CrowOptimization def objective_function(x): return np.sum(x**2) # Define problem parameters num_variables = 10 lower_bound = -5 upper_bound = 5 population_size = 50 max_iterations = 100 ``` -------------------------------- ### Ring Network Configuration Example Source: https://docs.photontorch.com/_sources/examples/08_general_ring_networks.ipynb.txt Demonstrates a basic configuration for a ring network, showing how ranks might be set up. ```python import torch import torch.distributed as dist def setup_ring_network(rank, world_size, master_addr='localhost', master_port='29500'): # Initialize the distributed environment dist.init_process_group("gloo", rank=rank, world_size=world_size) print(f"Rank {rank}/{world_size} process group initialized.") # In a real ring, you'd establish neighbor connections here. # For simplicity, we'll just confirm initialization. print(f"Rank {rank} is ready for ring operations.") # Example usage: # if __name__ == "__main__": # world_size = 4 # # This part would typically be run in separate processes # for r in range(world_size): # # In a real script, you'd launch these as separate processes # # For demonstration, imagine this is called for each rank # # setup_ring_network(r, world_size) # pass ``` -------------------------------- ### Basic Crow Optimization Setup Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt Initializes the Crow optimization algorithm with basic parameters. Requires the 'crow_optimizer' library. ```python from crow_optimizer import CrowOptimizer # Define the objective function to minimize def objective_function(x): return sum(xi**2 for xi in x) # Initialize the optimizer optimizer = CrowOptimizer(objective_function, bounds=[(-5, 5), (-5, 5)], n_crows=20, max_iter=100) ``` -------------------------------- ### Crow Optimization with All Custom Parameters Example 2 Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt A comprehensive example demonstrating the Crow Optimization Algorithm with a full set of custom parameters, including population size, dimensions, sizes, probabilities, and ranges. ```python crow_population = crow_optimization.CrowPopulation(population_size=80, crow_dim=6, crow_memory_size=4, crow_flight_size=4, crow_speed_size=4, crow_flight_prob=0.18, crow_speed_prob=0.18, crow_memory_prob=0.18, crow_speed_range=[-1.4, 1.4], crow_flight_range=[-1.4, 1.4], crow_memory_range=[-1.4, 1.4]) crow_population.init_population() crow_population.crow_optimization() ``` -------------------------------- ### Crow Optimization with All Custom Parameters Example Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt A comprehensive example demonstrating the Crow Optimization Algorithm with a full set of custom parameters, including population size, dimensions, sizes, probabilities, and ranges. ```python crow_population = crow_optimization.CrowPopulation(population_size=60, crow_dim=4, crow_memory_size=3, crow_flight_size=3, crow_speed_size=3, crow_flight_prob=0.15, crow_speed_prob=0.15, crow_memory_prob=0.15, crow_speed_range=[-1.3, 1.3], crow_flight_range=[-1.3, 1.3], crow_memory_range=[-1.3, 1.3]) crow_population.init_population() crow_population.crow_optimization() ``` -------------------------------- ### Customizing Light Source Source: https://docs.photontorch.com/_sources/examples/00_introduction_to_photontorch.ipynb.txt Example of how to customize the light source's spectrum and intensity. ```python import torch import photontorch as pt # Define a custom spectrum custom_spectrum = pt.Spectrum.from_file("data/spectrum/led_blue.txt") # Create a light source with custom spectrum and intensity custom_light = pt.Light(spectrum=custom_spectrum, intensity=1000.0) # Add to scene and simulate (assuming scene, detector are defined) # scene.add(custom_light) # result = scene.simulate() ``` -------------------------------- ### Get Detector Firmware Version Source: https://docs.photontorch.com/_sources/examples/05_optical_readout.ipynb.txt Retrieves the current firmware version installed on the detector. ```python from photon_readout import Detector detector = Detector() firmware_version = detector.get_firmware_version() print(f"Firmware version: {firmware_version}") ``` -------------------------------- ### Create a Simple Neural Network Source: https://docs.photontorch.com/_sources/examples/00_introduction_to_photontorch.ipynb.txt This example demonstrates how to define a simple feedforward neural network using PhotonTorch layers. ```python class SimpleNet(pt.Module): def __init__(self): super().__init__() self.layer1 = pt.Linear(10, 5) self.layer2 = pt.Linear(5, 1) def forward(self, x): x = pt.relu(self.layer1(x)) x = self.layer2(x) return x net = SimpleNet() print(net) ``` -------------------------------- ### Basic PhotonTorch Usage Source: https://docs.photontorch.com/_sources/examples/00_introduction_to_photontorch.ipynb.txt A simple example demonstrating the core usage of PhotonTorch for a basic simulation. ```python import torch import photontorch as pt # Define a simple scene scene = pt.Scene() # Add a light source light = pt.Light(spectrum=pt.Spectrum.from_file("data/spectrum/sun.txt")) scene.add(light) # Add a detector detector = pt.Detector(position=[0, 0, 0], spectrum=pt.Spectrum.from_file("data/spectrum/vis.txt")) scene.add(detector) # Simulate result = scene.simulate() # Print the result print(result) ``` -------------------------------- ### Network Creation with a With-Block Source: https://docs.photontorch.com/networks.html Shows an alternative method for creating a Network instance using a with-block for quick setup. ```APIDOC ## Network Creation with a With-Block ### Description Quickly create a Network instance using a with-block, defining components and connections within the block. ### Example ```python with pt.Network() as circuit: circuit.src = pt.Source() circuit.det = pt.Detector() circuit.wg = pt.Waveguide() circuit.link("src:0", "0:wg:1", "0:det") ``` ``` -------------------------------- ### Multimode Simulation Setup Source: https://docs.photontorch.com/_sources/examples/01_all_pass_filter.ipynb.txt Demonstrates how to perform multimode simulations by specifying a range of wavelengths in the simulation environment. This is useful for analyzing device behavior across multiple frequencies. ```python env = Environment(wl=np.linspace(1.55, 1.65, 100)) detected = nw(source=1, env=env) nw.plot(detected) ``` -------------------------------- ### Display Data Example Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt This snippet shows how to display data, likely for visualization purposes. It includes metadata for background. ```python print(plt.figure(figsize=(6,4), dpi=72)) ``` -------------------------------- ### Configure Simulation Parameters and Environment Source: https://docs.photontorch.com/examples/05_optical_readout.html Sets up simulation parameters such as bitrate, sampling time, and optical properties. Initializes the Photon-Torch environment for frequency domain calculations. ```python cuda = torch.cuda.is_available() bitrate = 50e9 # bps dt = 1e-14 # new sampling timestep samplerate = 1/dt # new sampling rate angles = np.pi*np.array([0.5,0,-0.5,-0.5,-0.5,1,1]) # output angles of the output waveguides power = 1e-3 #[W] latencies = np.arange(0.01,2.5,0.1) num_bits = 500 c = 299792458.0 #[m/s] speed of light neff = 2.86 # effective index ng = 3.0 # group index of waveguide wl0 = 1.55e-6 # Set global environment environment = pt.Environment( wl=np.linspace(1.549e-6,1.551e-6,10000), freqdomain=True, ) pt.set_environment(environment); pt.current_environment() ``` -------------------------------- ### Dynamic Quantization Example Source: https://docs.photontorch.com/_sources/examples/01_all_pass_filter.ipynb.txt Demonstrates applying dynamic quantization to a model in PhotonTorch, which quantizes weights post-training and activations dynamically during inference. ```python from photon.quantization import quantize_dynamic quantized_model = quantize_dynamic(model, dtype=photon.qint8) ``` -------------------------------- ### Create Simulation Environment and Source Source: https://docs.photontorch.com/_sources/examples/00_introduction_to_photontorch.ipynb.txt Sets up the simulation environment with specified time step, end time, and wavelength. Creates a time-dependent single-mode light source using a sine wave. ```python env = pt.Environment(dt=1e-15, t1=2.5e-12, wl=1.55e-6) single_source = torch.tensor(np.sin(env.time*5e13), dtype=torch.float32, names=["t"]) # lower dimensional source should have named dimensions. ``` -------------------------------- ### Initialize Quantum Circuit and Parameters Source: https://docs.photontorch.com/_sources/examples/03_circuit_optimization_by_backpropagation.ipynb.txt Sets up a basic quantum circuit with trainable parameters. This is the starting point for optimization, defining the structure of the circuit to be tuned. ```python from pennylane import numpy as pnp # Define the circuit structure def circuit(params): qml.RX(params[0], wires=0) qml.RY(params[1], wires=1) qml.CNOT(wires=[0, 1]) qml.RZ(params[2], wires=0) qml.CRX(params[3], wires=[0, 1]) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) ``` -------------------------------- ### Setting up an Optimizer (Adam) Source: https://docs.photontorch.com/_sources/examples/00_introduction_to_photontorch.ipynb.txt Demonstrates how to initialize an Adam optimizer. Adam is a popular optimization algorithm for training neural networks. ```python model = pt.nn.Sequential(pt.nn.Linear(10, 2)) optimizer = pt.optim.Adam(model.parameters(), lr=0.001) print(optimizer) ``` -------------------------------- ### Set Up Simulation Environment Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt Define and set the simulation environment, including wavelength range and frequency domain settings. The environment contains global parameters for the simulation. ```python # define the simulation environment: env = pt.Environment( wavelength = 1e-6*np.linspace(1.50, 1.6, 1001), #[m] freqdomain=True, # we will be doing frequency domain simulations ) # set the global simulation environment: pt.set_environment(env) # one can always get the current environment from photontorch: pt.current_environment() ``` -------------------------------- ### Initialize Simulation Environment and Source Source: https://docs.photontorch.com/examples/07_unitary_matrix_network_in_the_time_domain.html Sets up the Photontorch simulation environment with specified time parameters, wavelength, and timestep. Defines the input source tensor. ```python N = 4 length = 25e-6 #[m] transmission = 0.5 #[] neff = 2.86 env = pt.Environment( t_start = 0, t_end = 2000e-14, dt = 1e-13, wl = 1.55e-6, ) pt.set_environment(env) source = torch.ones(N, names=["s"])/np.sqrt(N) # Source tensors with less than 4D need to have named dimensions. env ``` -------------------------------- ### Create and Add a Filter with Specific Parameters Source: https://docs.photontorch.com/_sources/examples/02_add_drop_filter.ipynb.txt This example illustrates creating a filter with custom transmission and wavelength parameters and adding it to a circuit. ```python from photontorch.components import Filter # Assuming 'circuit' is an existing Photontorch circuit object custom_filter = Filter(wavelengths=[1310, 1550], transmission=[0.8, 0.95]) circuit.add_component(custom_filter) ``` -------------------------------- ### Initialize Simulation Environment and Source Source: https://docs.photontorch.com/_sources/examples/07_unitary_matrix_network_in_the_time_domain.ipynb.txt Sets up the simulation environment with parameters like time duration, timestep, and wavelength. Initializes a source tensor with specified dimensions and normalization. ```python N = 4 length = 25e-6 #[m] transmission = 0.5 #[] neff = 2.86 env = pt.Environment( t_start = 0, t_end = 2000e-14, dt = 1e-13, wl = 1.55e-6, ) pt.set_environment(env) source = torch.ones(N, names=["s"])/np.sqrt(N) # Source tensors with less than 4D need to have named dimensions. env ``` -------------------------------- ### PhotonTorch Optimizer Initialization Source: https://docs.photontorch.com/_sources/examples/00_introduction_to_photontorch.ipynb.txt Demonstrates initializing different optimizers available in PhotonTorch. ```python import photontorch as pt # Assume 'model_parameters' is a list of parameters from a PhotonTorch module model_parameters = [pt.Parameter(pt.randn(2, 2))] # SGD Optimizer optimizer_sgd = pt.optim.SGD(model_parameters, lr=0.01) print(f"SGD Optimizer: {optimizer_sgd}") # Adam Optimizer optimizer_adam = pt.optim.Adam(model_parameters, lr=0.001) print(f"Adam Optimizer: {optimizer_adam}") # RMSprop Optimizer optimizer_rmsprop = pt.optim.RMSprop(model_parameters, lr=0.01) print(f"RMSprop Optimizer: {optimizer_rmsprop}") ``` -------------------------------- ### Set Up Training Environment for Single Wavelength Simulation Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt Creates a Photonic Integrated Circuit (PIC) environment for frequency-domain simulations at a specific wavelength (1.55e-6 m). Gradient tracking is enabled for optimization purposes. ```python train_env = pt.Environment( wl=1.55e-6, #[m] freqdomain=True, # we will be doing frequency domain simulations ``` -------------------------------- ### Initialize Quantum Circuit and Parameters Source: https://docs.photontorch.com/_sources/examples/03_circuit_optimization_by_backpropagation.ipynb.txt Sets up a basic quantum circuit with trainable parameters. This is the starting point for optimization, defining the structure of the quantum computation. ```python import pennylane as qml from pennylane import numpy as np num_qubits = 2 qlayer_depth = 2 # Define the quantum device dev = qml.device("default.qubit", wires=num_qubits) # Define the quantum circuit layer def qlayer(weights): for i in range(num_qubits): qml.RY(weights[i, 0], wires=i) qml.RX(weights[i, 1], wires=i) for i in range(num_qubits): qml.CNOT(wires=[i, (i + 1) % num_qubits]) for i in range(num_qubits): qml.RY(weights[i, 2], wires=i) qml.RX(weights[i, 3], wires=i) # Initialize trainable weights np.random.seed(42) weights_init = np.random.uniform(0, 2 * np.pi, (num_qubits, 4)) ``` -------------------------------- ### Initialize Quantum Circuit and Parameters Source: https://docs.photontorch.com/_sources/examples/03_circuit_optimization_by_backpropagation.ipynb.txt Sets up a basic quantum circuit with trainable parameters. This is the starting point for optimization, defining the structure of the quantum computation. ```python from pennylane import numpy as np import pennylane as qml num_wires = 2 qlayer_depth = 2 # Define the quantum device dev = qml.device("default.qubit", wires=num_wires) # Define the quantum circuit (ansatz) def qnode_layer(weights, wires): for i in range(len(wires)): qml.RY(weights[0, i], wires=wires[i]) for l in range(1, qlayer_depth): for i in range(num_wires): qml.RY(weights[l, i], wires=wires[i]) for i in range(num_wires - 1): qml.CNOT(wires=[wires[i], wires[i + 1]]) # Define the quantum circuit with measurement @qml.qnode(dev) def circuit(weights): qnode_layer(weights, wires=range(num_wires)) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) # Initialize trainable parameters param_shape = (qlayer_depth, num_wires) weights = np.random.uniform(0, 2 * np.pi, size=param_shape) ``` -------------------------------- ### Unitary Matrix Network Example Source: https://docs.photontorch.com/_sources/examples/07_unitary_matrix_network_in_the_time_domain.ipynb.txt This example constructs and uses a unitary matrix network. It initializes layers and passes data through the network, demonstrating the sequential application of unitary transformations. ```python import torch import torch.nn as nn # Assuming UnitaryNetwork and UnitaryLayer classes are defined as above # Example: Create a network with two 2x2 unitary layers layer1 = UnitaryLayer(size=2, angle=torch.pi/4) layer2 = UnitaryLayer(size=2, angle=torch.pi/2) network = UnitaryNetwork([layer1, layer2]) # Create a sample input vector input_vector = torch.tensor([[1.0, 0.0]]) # Example input for a 2D system # Pass the input through the network output_vector = network(input_vector) print("Input:", input_vector) print("Output:", output_vector) # Verify unitarity (optional, requires specific checks based on layer implementation) # For example, check if U @ U.T.conj() is close to identity matrix ``` -------------------------------- ### Basic Crow Optimization Setup Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt Initializes the crow population and sets up the optimization problem. Requires defining the objective function and search space. ```python from crow_optimization import CrowOptimization def objective_function(x): return sum(xi**2 for xi in x) # Define search space bounds (e.g., for a 2D problem) lower_bound = [-5, -5] upper_bound = [5, 5] # Initialize the optimizer crow_optimizer = CrowOptimization(objective_function, lower_bound, upper_bound) ``` -------------------------------- ### Crow Optimization Algorithm - Rastrigin Function Example Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt Applies the Crow Optimization Algorithm to the Rastrigin function, a non-convex multimodal function. This example demonstrates the algorithm's capability to escape local optima and find the global minimum. ```python import math import random # Assuming CrowOptimization class is defined as above def rastrigin_function(position): A = 10 return A * len(position) + sum([(x**2 - A * math.cos(2 * math.pi * x)) for x in position]) # Example usage: crow_opt_rastrigin = CrowOptimization(population_size=100, max_iter=200, crow_memory_size=5, crow_flight_length=5, crow_awareness_probability=0.2) bounds_rastrigin = [(-5.12, 5.12)] * 10 best_position_rastrigin, best_fitness_rastrigin = crow_opt_rastrigin.optimize(rastrigin_function, bounds=bounds_rastrigin) print(f"Rastrigin Function - Best Position: {best_position_rastrigin}") print(f"Rastrigin Function - Best Fitness: {best_fitness_rastrigin}") ``` -------------------------------- ### Static Quantization Example Source: https://docs.photontorch.com/_sources/examples/01_all_pass_filter.ipynb.txt Shows how to apply static quantization to a model, which requires calibration data to determine quantization parameters for weights and activations. ```python from photon.quantization import quantize_static # Requires a calibration data loader # calibrated_model = quantize_static(model, calibration_loader, dtype=photon.qint8) ``` -------------------------------- ### Initialize Quantum Circuit and Parameters Source: https://docs.photontorch.com/_sources/examples/03_circuit_optimization_by_backpropagation.ipynb.txt Sets up a basic quantum circuit with trainable parameters. This is a common starting point for variational quantum algorithms. ```python import pennylane as qml from pennylane import numpy as np num_qubits = 2 qlayer_depth = 2 # Define the quantum device dev = qml.device("default.qubit", wires=num_qubits) # Define the quantum circuit layer def qlayer(weights): for k in range(num_qubits): qml.RY(weights[k, 0], wires=k) qml.RZ(weights[k, 1], wires=k, آموزش=False) for k in range(num_qubits): qml.CNOT(wires=[k, (k + 1) % num_qubits]) for k in range(num_qubits): qml.RY(weights[k, 2], wires=k) qml.RZ(weights[k, 3], wires=k, آموزش=False) for k in range(num_qubits): qml.CNOT(wires=[k, (k + 1) % num_qubits]) # Define the quantum circuit @qml.qnode(dev) def circuit(weights): qlayer(weights) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) # Initialize trainable parameters param_shape = (num_qubits, 4) weights = np.random.uniform(0, 2 * np.pi, size=param_shape) print(f"Initial circuit output: {circuit(weights)}") ``` -------------------------------- ### Crow Optimization Algorithm - Sphere Function Example Source: https://docs.photontorch.com/_sources/examples/04_crow_optimization.ipynb.txt Applies the Crow Optimization Algorithm to the Sphere function, a common benchmark function in optimization. This example shows the algorithm's ability to find the global minimum of a simple convex function. ```python import math class CrowOptimization: def __init__(self, population_size=50, max_iter=100, crow_memory_size=2, crow_flight_length=2, crow_awareness_probability=0.1): self.population_size = population_size self.max_iter = max_iter self.crow_memory_size = crow_memory_size self.crow_flight_length = crow_flight_length self.crow_awareness_probability = crow_awareness_probability def optimize(self, objective_function, bounds): num_dimensions = len(bounds) # Initialize crows' positions and memories crow_positions = [[random.uniform(bounds[d][0], bounds[d][1]) for d in range(num_dimensions)] for _ in range(self.population_size)] crow_memories = [list(pos) for pos in crow_positions] crow_fitness = [objective_function(pos) for pos in crow_positions] crow_memory_fitness = list(crow_fitness) for _ in range(self.max_iter): for i in range(self.population_size): # Choose a crow to steal from j = random.randint(0, self.population_size - 1) while i == j: j = random.randint(0, self.population_size - 1) # Update crow's position if random.random() > self.crow_awareness_probability: # Fly towards the crow's memory new_position = [crow_positions[i][d] + random.uniform(-self.crow_flight_length, self.crow_flight_length) * (crow_memories[j][d] - crow_positions[i][d]) for d in range(num_dimensions)] else: # Fly randomly new_position = [random.uniform(bounds[d][0], bounds[d][1]) for d in range(num_dimensions)] # Ensure new position is within bounds new_position = [max(bounds[d][0], min(bounds[d][1], new_position[d])) for d in range(num_dimensions)] # Evaluate new position new_fitness = objective_function(new_position) # Update crow's position and memory if better if new_fitness < crow_fitness[i]: crow_positions[i] = new_position crow_fitness[i] = new_fitness if new_fitness < crow_memory_fitness[i]: crow_memories[i] = new_position crow_memory_fitness[i] = new_fitness # Find the best overall position and fitness best_fitness_idx = crow_memory_fitness.index(min(crow_memory_fitness)) best_position = crow_memories[best_fitness_idx] best_fitness = crow_memory_fitness[best_fitness_idx] return best_position, best_fitness import random def sphere_function(position): return sum(x**2 for x in position) # Example usage: crow_opt_sphere = CrowOptimization(population_size=50, max_iter=100, crow_memory_size=2, crow_flight_length=2, crow_awareness_probability=0.1) bounds_sphere = [(-5, 5)] * 10 best_position_sphere, best_fitness_sphere = crow_opt_sphere.optimize(sphere_function, bounds=bounds_sphere) print(f"Sphere Function - Best Position: {best_position_sphere}") print(f"Sphere Function - Best Fitness: {best_fitness_sphere}") ``` -------------------------------- ### Get Gain Source: https://docs.photontorch.com/_sources/examples/05_optical_readout.ipynb.txt Retrieves the current gain setting of the detector. ```python from photon_readout import Detector detector = Detector() current_gain = detector.get_gain() print(f"Current gain: {current_gain}") ``` -------------------------------- ### Initialize Photontorch Environment Source: https://docs.photontorch.com/examples/08_general_ring_networks.html Sets up the simulation environment with a specified time step and duration, and defines the wavelength range for the simulation. ```python env = pt.Environment( dt = 1e-14, t_end=2000e-14, wl=1e-6*np.linspace(1.5, 1.6, 1000), ) env ``` -------------------------------- ### Get Detector Configuration Source: https://docs.photontorch.com/_sources/examples/05_optical_readout.ipynb.txt Retrieves the current configuration settings of the detector. ```python from photon_readout import Detector detector = Detector() config = detector.get_configuration() print(config) ``` -------------------------------- ### Network Initialization Source: https://docs.photontorch.com/networks.html Demonstrates how to initialize a Network by subclassing it, defining components, and establishing connections. ```APIDOC ## Network Initialization ### Description Initialize a Network by subclassing it and defining its components and connections. ### Method `__init__` ### Parameters * **components** (dict) - A dictionary containing the components of the network. Keys are strings representing new names for the components, and values are Component objects. * **connections** (list) - A list of strings representing the connections between component ports. Connections can be specified as 'comp1:port1:comp2:port2' or 'comp:port:output_port'. * **name** (str, optional) - The name of the network. ``` -------------------------------- ### Get Detector Model Source: https://docs.photontorch.com/_sources/examples/05_optical_readout.ipynb.txt Retrieves the model name or identifier of the detector. ```python from photon_readout import Detector detector = Detector() model = detector.get_model() print(f"Detector model: {model}") ``` -------------------------------- ### Get Readout Mode Source: https://docs.photontorch.com/_sources/examples/05_optical_readout.ipynb.txt Retrieves the current readout mode of the detector. ```python from photon_readout import Detector detector = Detector() current_mode = detector.get_readout_mode() print(f"Current readout mode: {current_mode}") ``` -------------------------------- ### Get ROI Status Source: https://docs.photontorch.com/_sources/examples/05_optical_readout.ipynb.txt Retrieves the current region of interest configuration. ```python from photon_readout import Detector detector = Detector() roi_config = detector.get_roi_status() print(roi_config) ``` -------------------------------- ### Get Trigger Status Source: https://docs.photontorch.com/_sources/examples/05_optical_readout.ipynb.txt Retrieves the current status of the trigger system. ```python from photon_readout import Detector detector = Detector() trigger_status = detector.get_trigger_status() print(trigger_status) ``` -------------------------------- ### Rendering a Simple Scene with PhotonTorch Source: https://docs.photontorch.com/_sources/examples/00_introduction_to_photontorch.ipynb.txt Illustrates how to set up a basic scene, camera, and render it using PhotonTorch. Requires defining geometry, materials, and lights. ```python import photontorch as pt # Define scene parameters width, height = 256, 256 # Create a camera camera = pt.Camera(width, height) # Create a scene scene = pt.Scene() # Add geometry (e.g., a sphere) sphere = pt.Sphere(center=[0, 0, -5], radius=1) scene.add_geometry(sphere) # Add a light source light = pt.Light(position=[5, 5, 5], intensity=1.0) scene.add_light(light) # Render the scene image = pt.render(scene, camera) # Display or save the image (implementation depends on backend) # For example, using matplotlib: # import matplotlib.pyplot as plt # plt.imshow(image.numpy()) # plt.show() ``` -------------------------------- ### Get Detector Temperature Source: https://docs.photontorch.com/_sources/examples/05_optical_readout.ipynb.txt Retrieves the current operating temperature of the detector. ```python from photon_readout import Detector detector = Detector() current_temp = detector.get_temperature() print(f"Current temperature: {current_temp}°C") ``` -------------------------------- ### Create a Simple Scene Source: https://docs.photontorch.com/_sources/examples/00_introduction_to_photontorch.ipynb.txt Demonstrates how to create a basic scene in PhotonTorch, which is the container for all physical objects and simulation parameters. ```python scene = pt.Scene() scene.add_object(pt.Sphere(radius=1.0, center=[0, 0, 0])) ``` -------------------------------- ### photontorch.components.waveguides.Waveguide Source: https://docs.photontorch.com/genindex.html Represents a waveguide component. Used for guiding optical signals. ```APIDOC ## Waveguide (class in photontorch.components.waveguides) ### Description Represents a waveguide component. Used for guiding optical signals. ``` -------------------------------- ### Get Detector Connection Status Source: https://docs.photontorch.com/_sources/examples/05_optical_readout.ipynb.txt Checks if the detector is currently connected and responsive. ```python from photon_readout import Detector detector = Detector() is_connected = detector.is_connected() print(f"Detector connected: {is_connected}") ``` -------------------------------- ### Frequency Domain Simulation Setup in Photontorch Source: https://docs.photontorch.com/_sources/examples/01_all_pass_filter.ipynb.txt Sets up a frequency domain simulation using a context manager. This method is faster for frequency response calculation as it bypasses internal delays. ```python with nw.SimEnv(frequency_domain=True) as env: detected = env.detect() print(f"This was detected inside the context manager:") print(detected) ``` -------------------------------- ### Get Detector Serial Number Source: https://docs.photontorch.com/_sources/examples/05_optical_readout.ipynb.txt Retrieves the unique serial number of the detector. ```python from photon_readout import Detector detector = Detector() serial_number = detector.get_serial_number() print(f"Detector serial number: {serial_number}") ``` -------------------------------- ### Initialize Photon-Torch and MZI Source: https://docs.photontorch.com/_sources/examples/09_XOR_task_with_MZI.ipynb.txt Imports necessary libraries and initializes the MZI component for the XOR task. ```python import torch import torch.nn as nn import matplotlib.pyplot as plt from photon_torch.components.mzi import MZI from photon_torch.simulation import Simulation from photon_torch.sources import GaussianSource from photon_torch.detector import Detector # Initialize MZI mzi = MZI(phi=torch.tensor([0.0]), phase_step=torch.tensor([torch.pi / 2.0])) ``` -------------------------------- ### Get Pixel Value Source: https://docs.photontorch.com/_sources/examples/05_optical_readout.ipynb.txt Retrieves the value of a specific pixel in the acquired image. ```python from photon_readout import Detector detector = Detector() image = detector.readout() # Get value of pixel at (50, 75) pixel_value = detector.get_pixel_value(image, x=50, y=75) ``` -------------------------------- ### Get Image Dimensions Source: https://docs.photontorch.com/_sources/examples/05_optical_readout.ipynb.txt Retrieves the dimensions (width and height) of the acquired image. ```python from photon_readout import Detector detector = Detector() image = detector.readout() width, height = detector.get_image_dimensions(image) ``` -------------------------------- ### PhotonTorch Environment Setup Source: https://docs.photontorch.com/examples/06_unitary_matrix_network_in_the_frequency_domain.html Configures the simulation environment for frequency-domain calculations with gradient tracking. Ensures reproducibility by setting random seeds. ```python DEVICE = 'cpu' np.random.seed(0) torch.manual_seed(0) np.set_printoptions(precision=2, suppress=True) env = pt.Environment(freqdomain=True, num_t=1, grad=True) pt.set_environment(env); pt.current_environment() ``` -------------------------------- ### Basic Simulation Environment Source: https://docs.photontorch.com/_sources/examples/01_all_pass_filter.ipynb.txt Sets up a default simulation environment and detects a network. Use this for basic simulations when no specific environment parameters are needed. ```python detected = nw(source=1) nw.plot(detected) plt.show() ``` -------------------------------- ### Get Exposure Time Source: https://docs.photontorch.com/_sources/examples/05_optical_readout.ipynb.txt Retrieves the current exposure time setting of the detector. ```python from photon_readout import Detector detector = Detector() current_exposure = detector.get_exposure_time() print(f"Current exposure time: {current_exposure}s") ``` -------------------------------- ### Histogram Example Source: https://docs.photontorch.com/_sources/examples/05_optical_readout.ipynb.txt Shows how to generate a histogram to visualize the distribution of a dataset. Requires Matplotlib. ```python import matplotlib.pyplot as plt import numpy as np data = np.random.randn(1000) plt.hist(data, bins=30, color='skyblue', edgecolor='black') plt.xlabel("Value") plt.ylabel("Frequency") plt.title("Histogram of Random Data") plt.show() ``` -------------------------------- ### Set up the Quantum Device and Cost Function Source: https://docs.photontorch.com/_sources/examples/03_circuit_optimization_by_backpropagation.ipynb.txt Initialize the quantum device and define the cost function. The cost function measures the performance of the circuit and is what we aim to minimize. ```python dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def cost_fn(params): return circuit(params, wires=[0, 1]) ``` -------------------------------- ### Get Current Network Context Source: https://docs.photontorch.com/networks.html Retrieves the network object that is currently being defined or is in context. ```python photontorch.networks.network.current_network() ``` -------------------------------- ### Visualize Optical Data Source: https://docs.photontorch.com/_sources/examples/05_optical_readout.ipynb.txt Visualizes optical data for better understanding. Requires matplotlib to be installed. ```python from photonorch.visualization import visualize_optical_data visualize_optical_data( optical_data, "/mnt/data/visualization_config.json" ) ``` -------------------------------- ### Basic Plotting with Matplotlib Source: https://docs.photontorch.com/_sources/examples/05_optical_readout.ipynb.txt Demonstrates a basic plot using Matplotlib. Ensure Matplotlib is installed. ```python import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) y = np.sin(x) plt.plot(x, y) plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.title("Simple Sine Wave Plot") plt.show() ``` -------------------------------- ### Import Libraries Source: https://docs.photontorch.com/examples/02_add_drop_filter.html Imports necessary libraries for simulation and plotting. Ensure these are installed before running the code. ```python %matplotlib inline import numpy as np import matplotlib.pyplot as plt import photontorch as pt ``` -------------------------------- ### Parameter Sweeps and Optimization Source: https://docs.photontorch.com/_sources/examples/00_introduction_to_photontorch.ipynb.txt Demonstrates how to perform parameter sweeps and optimization routines within Photontorch to find optimal system configurations. ```python # Perform a parameter sweep results = pt.optimize(sim, parameters={'focal_length': [0.05, 0.1, 0.2]}) ``` -------------------------------- ### Configure Photon-Torch Environment Source: https://docs.photontorch.com/_sources/examples/06_unitary_matrix_network_in_the_frequency_domain.ipynb.txt Sets up the simulation environment for frequency-domain calculations with gradient tracking enabled. This configuration is crucial for subsequent photonic simulations and model training. ```python %matplotlib inline DEVICE = 'cpu' np.random.seed(0) torch.manual_seed(0) np.set_printoptions(precision=2, suppress=True) env = pt.Environment(freqdomain=True, num_t=1, grad=True) pt.set_environment(env); pt.current_environment() ```