qdk_chemistry.utils.telemetry module

Telemetry module for QDK Chemistry.

Module sends telemetry directly to Azure Monitor using a similar mechanism and format to the Azure Monitor OpenTelemetry Python SDK. It only supports custom metrics of type “counter” and “histogram” for now. Its goal is to be minimal in size and dependencies, and easy to read to understand exactly what data is being sent.

To use this API, simply call log_telemetry with the metric name, value, and any other optional properties. The telemetry will be batched and sent at a regular intervals (60 sec), and when the process is about to exit.

Disable qdk_chemistry Python telemetry by setting the environment variable QSHARP_PYTHON_TELEMETRY to one of the following: none, disabled, false, or 0.

class qdk_chemistry.utils.telemetry.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])

Bases: date

The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints.

astimezone()

tz -> convert to local time in new timezone tz

classmethod combine()

date, time -> datetime with same date and time fields

ctime()

Return ctime() style string.

date()

Return date object with same year, month and day.

dst()

Return self.tzinfo.dst(self).

fold
classmethod fromisoformat()

string -> datetime from a string in most ISO 8601 formats

classmethod fromtimestamp()

timestamp[, tz] -> tz’s local time from POSIX timestamp.

hour
isoformat()

[sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM]. sep is used to separate the year from the time, and defaults to ‘T’. The optional argument timespec specifies the number of additional terms of the time to include. Valid options are ‘auto’, ‘hours’, ‘minutes’, ‘seconds’, ‘milliseconds’ and ‘microseconds’.

max = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
microsecond
min = datetime.datetime(1, 1, 1, 0, 0)
minute
classmethod now(tz=None)

Returns new datetime object representing current time local to tz.

tz

Timezone object.

If no tz is specified, uses local timezone.

replace()

Return datetime with new specified fields.

resolution = datetime.timedelta(microseconds=1)
second
classmethod strptime()

string, format -> new datetime parsed from a string (like time.strptime()).

time()

Return time object with same time but with tzinfo=None.

timestamp()

Return POSIX timestamp as float.

timetuple()

Return time tuple, compatible with time.localtime().

timetz()

Return time object with same time and tzinfo.

tzinfo
tzname()

Return self.tzinfo.tzname(self).

classmethod utcfromtimestamp()

Construct a naive UTC datetime from a POSIX timestamp.

classmethod utcnow()

Return a new datetime representing UTC day and time.

utcoffset()

Return self.tzinfo.utcoffset(self).

utctimetuple()

Return UTC time tuple, compatible with time.localtime().

class qdk_chemistry.utils.telemetry.timezone

Bases: tzinfo

Fixed offset from UTC implementation of tzinfo.

dst()

Return None.

fromutc()

datetime in UTC -> datetime in local time.

max = datetime.timezone(datetime.timedelta(seconds=86340))
min = datetime.timezone(datetime.timedelta(days=-1, seconds=60))
tzname()

If name is specified when timezone is created, returns the name. Otherwise returns offset as ‘UTC(+|-)HH:MM’.

utc = datetime.timezone.utc
utcoffset()

Return fixed offset.

exception qdk_chemistry.utils.telemetry.PackageNotFoundError

Bases: ModuleNotFoundError

The package was not found.

property name

module name

qdk_chemistry.utils.telemetry.version(distribution_name)

Get the version string for the named package.

Parameters:

distribution_name – The name of the distribution package to query.

Returns:

The version string for the package as defined in the package’s “Version” metadata key.

exception qdk_chemistry.utils.telemetry.Empty

Bases: Exception

Exception raised by Queue.get(block=0)/get_nowait().

class qdk_chemistry.utils.telemetry.SimpleQueue

Bases: object

Simple, unbounded, reentrant FIFO queue.

empty()

Return True if the queue is empty, False otherwise (not reliable!).

get(block=True, timeout=None)

Remove and return an item from the queue.

If optional args ‘block’ is true and ‘timeout’ is None (the default), block if necessary until an item is available. If ‘timeout’ is a non-negative number, it blocks at most ‘timeout’ seconds and raises the Empty exception if no item was available within that time. Otherwise (‘block’ is false), return an item if one is immediately available, else raise the Empty exception (‘timeout’ is ignored in that case).

get_nowait()

Remove and return an item from the queue without blocking.

Only get an item if one is immediately available. Otherwise raise the Empty exception.

put(item, block=True, timeout=None)

Put the item on the queue.

The optional ‘block’ and ‘timeout’ arguments are ignored, as this method never blocks. They are provided for compatibility with the Queue class.

put_nowait(item)

Put an item into the queue without blocking.

This is exactly equivalent to put(item) and is only provided for compatibility with the Queue class.

qsize()

Return the approximate size of the queue (not reliable!).

class qdk_chemistry.utils.telemetry.Thread(group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None)

Bases: object

A class that represents a thread of control.

This class can be safely subclassed in a limited fashion. There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass.

__init__(group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None)

This constructor should always be called with keyword arguments. Arguments are:

group should be None; reserved for future extension when a ThreadGroup class is implemented.

target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.

name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.

args is a list or tuple of arguments for the target invocation. Defaults to ().

kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.

If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread.

start()

Start the thread’s activity.

It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

This method will raise a RuntimeError if called more than once on the same thread object.

run()

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

join(timeout=None)

Wait until the thread terminates.

This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

When the timeout argument is not present or None, the operation will block until the thread terminates.

A thread can be join()ed many times.

join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.

property name

A string used for identification purposes only.

It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.

property ident

Thread identifier of this thread or None if it has not been started.

This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited.

property native_id

Native integral thread ID of this thread, or None if it has not been started.

This is a non-negative integer. See the get_native_id() function. This represents the Thread ID as reported by the kernel.

is_alive()

Return whether the thread is alive.

This method returns True just before the run() method starts until just after the run() method terminates. See also the module function enumerate().

property daemon

A boolean value indicating whether this thread is a daemon thread.

This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

The entire Python program exits when only daemon threads are left.

isDaemon()

Return whether this thread is a daemon.

This method is deprecated, use the daemon attribute instead.

setDaemon(daemonic)

Set whether this thread is a daemon.

This method is deprecated, use the .daemon property instead.

getName()

Return a string used for identification purposes only.

This method is deprecated, use the name attribute instead.

setName(name)

Set the name string for this thread.

This method is deprecated, use the name attribute instead.

class qdk_chemistry.utils.telemetry.Metric[source]

Bases: TypedDict

Used internally for objects in the telemetry queue.

name: str
value: float
count: int
properties: dict[str, Any]
type: str
class qdk_chemistry.utils.telemetry.PendingMetric[source]

Bases: Metric

Used internally to aggregate metrics before sending.

min: float
max: float
name: str
value: float
count: int
properties: dict[str, Any]
type: str
qdk_chemistry.utils.telemetry.log_telemetry(name, value, count=1, properties=None, type='counter')[source]

Log a custom telemetry metric.

Logs a custom metric with the name provided. Properties are optional and can be used to capture additional context about the metric (but should be a relatively static set of values, as each unique set of properties will be sent as a separate metric and creates a separate ‘dimension’ in the backend telemetry store).

The type can be either ‘counter’ or ‘histogram’. A ‘counter’ is a simple value that is summed over time, such as how many times an event occurs, while a ‘histogram’ is used to track ‘quantitative’ values, such as the distribution of values over time, e.g., the duration of an operation.

Return type:

None

Parameters: