def moment_by_moment_schedule(device: Device, circuit: Circuit): """Returns a schedule aligned with the moment structure of the Circuit. This method attempts to create a schedule in which each moment of a circuit is scheduled starting at the same time. Given the constraints of the given device, such a schedule may not be possible, in this case the the method will raise a ValueError with a description of the conflict. The schedule that is produced will take each moments and schedule the operations in this moment in a time slice of length equal to the maximum time of an operation in the moment. Returns: A Schedule for the circuit. Raises: ValueError: if the scheduling cannot be done. """ schedule = Schedule(device) t = Timestamp() for moment in circuit.moments: if not moment.operations: continue for op in moment.operations: scheduled_op = ScheduledOperation.op_at_on(op, t, device) # Raises a ValueError describing the problem if this cannot be # scheduled. schedule.include(scheduled_operation=scheduled_op) # Raises ValueError at first sign of a device conflict. device.validate_scheduled_operation(schedule, scheduled_op) # Increment time for next moment by max of ops during this moment. max_duration = max(device.duration_of(op) for op in moment.operations) t += max_duration return schedule
def op_at_on(operation: ops.Operation, time: Timestamp, device: Device): """Creates a scheduled operation with a device-determined duration.""" return ScheduledOperation(time, device.duration_of(operation), operation)
def program_as_schedule(self, program: Union[Circuit, Schedule], device: Device = None) -> Schedule: if isinstance(program, Circuit): device = device or UnconstrainedDevice circuit_copy = Circuit(program.moments) ConvertToXmonGates().optimize_circuit(circuit_copy) DropEmptyMoments().optimize_circuit(circuit_copy) device.validate_circuit(circuit_copy) return moment_by_moment_schedule(device, circuit_copy) elif isinstance(program, Schedule): if device: raise ValueError( 'Device can not be provided when running a schedule.') return program else: raise TypeError('Unexpected program type.')