Skip to content
This repository has been archived by the owner on Dec 15, 2023. It is now read-only.

Commit

Permalink
Merge branch 'dev' into feat/ci_39
Browse files Browse the repository at this point in the history
  • Loading branch information
peendebak authored Sep 10, 2021
2 parents b269c18 + 2eda652 commit 17fbf28
Show file tree
Hide file tree
Showing 13 changed files with 239 additions and 120 deletions.
3 changes: 3 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
language: python

cache: pip

matrix:
include:
- name: Minimal installation 3.9
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added

- Add measure_time context for measuring exection time (#765)
- Add method to combine legends of multiple matplotlib axes (#782)
- Functionality plot onto a matplotlib Axes object (#785)

### Changed

Expand All @@ -22,6 +24,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Deprecated

- Deprecated instrument adapters. Deprecated post-processing tools in qtt.measurements.post_processing (#777)
- Deprecated functionality to store system states with h5py (#780)
- Deprecated methods in qtt.instrument_storage (#783)

### Fixed

## \[1.2.3] - 22-3-2021
Expand Down
3 changes: 2 additions & 1 deletion pytest.ini
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ python_functions = test_*
addopts = --pyargs src/tests/unittests src/tests/integration

# exclude some directories from searching to save time
norecursedirs = .svn _build tmp* .git docs untitled* deprecated* build dist .cache
norecursedirs = .svn _build tmp* .git docs untitled* deprecated* build dist .cache *.egg-info __pycache__

# ignore deprecation warnings from external packages
filterwarnings =
ignore:.*invalid escape sequence.*:DeprecationWarning
ignore:.*Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working*:DeprecationWarning
ignore:.*time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8*:DeprecationWarning
ignore:.*No module named '_tifffile'*:UserWarning
ignore:.*Call to deprecated create function FileDescriptor().*:DeprecationWarning
2 changes: 1 addition & 1 deletion requirements_lock.txt
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ nbformat==5.1.2
nest-asyncio==1.5.1
netCDF4==1.5.6
networkx==2.5
notebook==6.2.0
notebook==6.4.1
numdifftools==0.9.39
numpy==1.20.1
opencensus==0.7.12
Expand Down
37 changes: 20 additions & 17 deletions src/qtt/algorithms/allxy.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
from typing import Dict, Any, List, Union, Optional
from typing import Any, Dict, List, Optional, Union

import numpy as np
import matplotlib.pyplot as plt
from lmfit import Model

from qcodes.data.data_set import DataSet
from matplotlib.axes import Axes
from qcodes.data.data_array import DataArray
from qtt.utilities.visualization import plot_vertical_line
from qcodes.data.data_set import DataSet

from qtt.algorithms.fitting import extract_lmfit_parameters
from qtt.utilities.visualization import get_axis, plot_vertical_line


def generate_allxy_combinations() -> List[Any]:
""" Generate all combinations of the AllXY sequence from Reed 2013 """
Expand Down Expand Up @@ -89,42 +91,43 @@ def fit_allxy(dataset: DataSet, initial_parameters: Optional[np.ndarray] = None)
return analysis_results


def plot_allxy(dataset: DataSet, result: Dict[str, Any], fig: int = 1, plot_initial_estimate: bool = False):
def plot_allxy(dataset: DataSet, result: Dict[str, Any], fig: Union[int, Axes, None] = 1, plot_initial_estimate: bool = False):
""" Plot the results of an AllXY fit
Args:
dataset: Dataset containing the measurement data
result: Fitting result of fit_allxy
int: Figure handle
fig: Figure or axis handle. Is passed on to `get_axis`
plot_initial_guess: If True, then plot the initial estimate of the model
"""
allxy_data = _default_measurement_array(dataset)
xy_pairs = generate_allxy_combinations()
x_data = np.arange(21)

plt.figure(fig)
plt.clf()
ax = get_axis(fig)
fitted_parameters = result['fitted_parameters']
xfine = np.arange(0, 21, 1e-3)
plt.plot(xfine, allxy_model(xfine, *fitted_parameters), 'm', label='fitted allxy', alpha=.5)
ax.plot(xfine, allxy_model(xfine, *fitted_parameters), 'm', label='fitted allxy', alpha=.5)

plt.plot(x_data, allxy_data, '.b', label='allxy data')
ax.plot(x_data, allxy_data, '.b', label='allxy data')

if plot_initial_estimate:
p = [0, 0, .5, 0, 1, 0]
plt.plot(xfine, allxy_model(xfine, *p), 'c', label='baseline', alpha=.5)
ax.plot(xfine, allxy_model(xfine, *p), 'c', label='baseline', alpha=.5)

initial_params = _estimate_allxy_parameters(allxy_data)
plt.plot(xfine, allxy_model(xfine, *initial_params), 'g', label='initial estimate', alpha=.35)
ax.plot(xfine, allxy_model(xfine, *initial_params), 'g', label='initial estimate', alpha=.35)

initial_parameters = result['initial_parameters']
plt.plot(xfine, allxy_model(xfine, *initial_parameters), ':g', label='initial estimate', alpha=.35)
ax.plot(xfine, allxy_model(xfine, *initial_parameters), ':g', label='initial estimate', alpha=.35)

ax.set_xticks(x_data)
ax.set_xticklabels([v[0] + "," + v[1] for v in xy_pairs], rotation='vertical')

plt.xticks(x_data, [v[0] + "," + v[1] for v in xy_pairs], rotation='vertical')
vl = plot_vertical_line(4.5)
vl.set_linestyle(':')
vl = plot_vertical_line(16.5)
vl.set_linestyle(':')
plt.title('AllXY')
ax.set_title('AllXY')

plt.legend()
ax.legend()
26 changes: 14 additions & 12 deletions src/qtt/algorithms/functions.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
""" Mathematical functions and models """

from typing import Union

import matplotlib.pyplot as plt
import numpy as np
import scipy
import scipy.constants
from typing import Union
import matplotlib.pyplot as plt
from lmfit import Model
from matplotlib.axes import Axes

import qtt.pgeometry
import qtt.utilities.tools
from qtt.utilities.visualization import plot_vertical_line
from qtt.algorithms.generic import subpixelmax
from qtt.utilities.visualization import get_axis, plot_vertical_line


def gaussian(x, mean, std, amplitude=1, offset=0):
Expand Down Expand Up @@ -392,26 +394,26 @@ def gauss_ramsey_model(x, amplitude, decay_time, frequency, phase, offset):
return result_dict['fitted_parameters'], result_dict


def plot_gauss_ramsey_fit(x_data, y_data, fit_parameters, fig):
def plot_gauss_ramsey_fit(x_data, y_data, fit_parameters, fig: Union[int, Axes, None]):
""" Plot Gauss Ramsey fit
Args:
x_data: Input array with time variable (in seconds)
y_data: Input array with signal
fit_parameters: Result of fit_gauss_ramsey (fitting units in seconds)
fig: Figure or axis handle. Is passed to `get_axis`
"""
test_x = np.linspace(0, np.max(x_data), 200)
freq_fit = abs(fit_parameters[2] * 1e-6)
t2star_fit = fit_parameters[1] * 1e6

plt.figure(fig)
plt.clf()
plt.plot(x_data * 1e6, y_data, 'o', label='Data')
plt.plot(test_x * 1e6, gauss_ramsey(test_x, fit_parameters), label='Fit')
plt.title(r'Gauss Ramsey fit: %.2f MHz / $T_2^*$: %.1f $\mu$s' % (freq_fit, t2star_fit))
plt.xlabel(r'time ($\mu$s)')
plt.ylabel('Spin-up probability')
plt.legend()
ax = get_axis(fig)
ax.plot(x_data * 1e6, y_data, 'o', label='Data')
ax.plot(test_x * 1e6, gauss_ramsey(test_x, fit_parameters), label='Fit')
ax.set_title(r'Gauss Ramsey fit: %.2f MHz / $T_2^*$: %.1f $\mu$s' % (freq_fit, t2star_fit))
ax.set_xlabel(r'time ($\mu$s)')
ax.set_ylabel('Spin-up probability')
ax.legend()


def linear_function(x, a, b):
Expand Down
14 changes: 10 additions & 4 deletions src/qtt/instrument_storage.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
""" Functionality to store instrument data in a configuration file """
import numpy as np
import configparser
import json
import numbers
import configparser

import numpy as np

import qtt.utilities.tools
from qtt.utilities.tools import rdeprecated


@rdeprecated(txt='This method will be removed in a future release', expire='Sep 1 2021')
def save_instrument_configparser(instr, ifile, verbose=1):
""" Save instrument configuration to configparser structure
Args:
instr (Instrument): instrument to apply settings to
ifile (str): configuration file
ifile (str): configuration file
"""
jdict = configparser.ConfigParser()
jdict.read(ifile)
Expand All @@ -30,12 +34,13 @@ def save_instrument_configparser(instr, ifile, verbose=1):
jdict.write(fid)


@rdeprecated(txt='This method will be removed in a future release', expire='Sep 1 2021')
def load_instrument_configparser(instr, ifile, verbose=1):
""" Load instrument configuration from configparser structure
Args:
instr (Instrument): instrument to apply settings to
ifile (str): configuration file
ifile (str): configuration file
"""
jdict = configparser.ConfigParser()
jdict.read(ifile)
Expand Down Expand Up @@ -65,6 +70,7 @@ def load_instrument_configparser(instr, ifile, verbose=1):

if __name__ == '__main__':
import os

from stationV2.tools import V2hardware
v2hardware = V2hardware(name='v2hardware', server_name=None)

Expand Down
13 changes: 9 additions & 4 deletions src/qtt/measurements/storage.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
# %%
from datetime import datetime
import os
import h5py
import logging
import os
import warnings
from datetime import datetime

import h5py
import qcodes

import qtt.instrument_drivers.virtual_gates
from qtt.utilities.tools import rdeprecated

try:
import hickle
Expand All @@ -18,6 +20,7 @@
# %%


@rdeprecated(txt='Method will be removed in a future version', expire='Jun 1 2022')
def list_states(verbose=1):
""" List available states of the system
Expand Down Expand Up @@ -53,6 +56,7 @@ def _get_statefile(statefile=None):
return statefile


@rdeprecated(txt='Method will be removed in a future version', expire='Jun 1 2022')
def load_state(tag=None, station=None, verbose=1, statefile=None):
""" Load state of the system from disk
Expand Down Expand Up @@ -94,6 +98,7 @@ def load_state(tag=None, station=None, verbose=1, statefile=None):
return obj, virtual_gates


@rdeprecated(txt='Method will be removed in a future version', expire='Jun 1 2022')
def save_state(station, tag=None, overwrite=False, virtual_gates=None, data=None, verbose=1, statefile=None):
""" Save current state of the system to disk
Expand All @@ -119,7 +124,7 @@ def save_state(station, tag=None, overwrite=False, virtual_gates=None, data=None
snapshot = station.snapshot()
gv = station.gates.allvalues()

date_string = "{:%Y%m%d-%H%M%S}".format(datetime.now())
date_string = f"{datetime.now():%Y%m%d-%H%M%S}"

if verbose >= 2:
print(date_string)
Expand Down
35 changes: 16 additions & 19 deletions src/qtt/pgeometry.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
pgeometry
Expand All @@ -20,25 +19,25 @@
@author: eendebakpt
"""

import logging
import math
# %% Load necessary packages
import os
import pickle
import pkgutil
import re
import subprocess
import sys
import tempfile
import math
import time
import warnings
import pickle
import subprocess
import re
import logging
import pkgutil
from functools import wraps

import numpy
import numpy as np
import scipy.io
import scipy.ndimage.morphology as morphology
import scipy.ndimage.filters as filters
import scipy.ndimage.morphology as morphology
import shapely.geometry

__version__ = '0.7.0'
Expand Down Expand Up @@ -66,9 +65,7 @@ def qtModules(verbose=0):
import qtpy.QtCore as QtCore
import qtpy.QtGui as QtGui
import qtpy.QtWidgets as QtWidgets
from qtpy.QtCore import QObject
from qtpy.QtCore import Slot
from qtpy.QtCore import Signal
from qtpy.QtCore import QObject, Signal, Slot
except ImportError:
_haveqtpy = False
warnings.warn('could not import qtpy, not all functionality available')
Expand Down Expand Up @@ -123,8 +120,9 @@ def go(self):
pass

try:
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.pyplot as plt

# needed for 3d plot points, do not remove!
try:
from mpl_toolkits.mplot3d import Axes3D
Expand All @@ -147,9 +145,9 @@ def go(self):
try:
import cv2
_haveOpenCV = True
except ModuleNotFoundError:
except (ModuleNotFoundError, ImportError):
_haveOpenCV = False
warnings.warn('could not find OpenCV, not all functionality is available')
warnings.warn('could not find or load OpenCV, not all functionality is available')
pass

# %% Utils
Expand Down Expand Up @@ -177,8 +175,9 @@ def memory():
Returns:
float: memory usage in mb
"""
import psutil
import os

import psutil
process = psutil.Process(os.getpid())
mem = process.memory_info().rss / (1024. * 1024.)
return mem
Expand Down Expand Up @@ -624,7 +623,7 @@ def RBE2euler(Rbe):

def pg_rotation2H(R):
""" Convert rotation matrix to homogenous transform matrix """
X = np.array(np.eye((R.shape[0] + 1)))
X = np.array(np.eye(R.shape[0] + 1))
X[0:-1, 0:-1] = R
return X

Expand Down Expand Up @@ -1547,9 +1546,7 @@ def deprecation(message):
# %%
try:
import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
from PIL import Image, ImageDraw, ImageFont

def writeTxt(im, txt, pos=(10, 10), fontsize=25, color=(0, 0, 0), fonttype=None):
""" Write text on image using PIL """
Expand Down
Loading

0 comments on commit 17fbf28

Please sign in to comment.