Skip to content

Commit

Permalink
pre-commit.ci formatting (#144)
Browse files Browse the repository at this point in the history
* trigger pre-commit.ci

* trigger ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

* Update .pre-commit-config.yaml

^(.github/|.devcontainer/|doc/_static/|pyriemann_qiskit/_version.py|setup.py)

* Revert "[pre-commit.ci] auto fixes from pre-commit.com hooks"

This reverts commit 51757d9.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

* [pre-commit.ci] auto fixes from pre-commit.com hooks

* Revert "[pre-commit.ci] auto fixes from pre-commit.com hooks"

This reverts commit fae2eaa.

* Revert "[pre-commit.ci] auto fixes from pre-commit.com hooks"

This reverts commit 6a3e502.

* pre-commit-config.yaml

* [pre-commit.ci] auto fixes from pre-commit.com hooks

* Update .pre-commit-config.yaml

remove isort

* remove isort

* Revert "[pre-commit.ci] auto fixes from pre-commit.com hooks"

This reverts commit edc16a5.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

* Update .pre-commit-config.yaml

* flake8 bugbear

* Revert "[pre-commit.ci] auto fixes from pre-commit.com hooks"

This reverts commit 75ef925.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

* Revert "[pre-commit.ci] auto fixes from pre-commit.com hooks"

This reverts commit a94f742.

* Revert "flake8 bugbear"

This reverts commit 6d3ae33.

* Update setup.cfg

* [pre-commit.ci] auto fixes from pre-commit.com hooks

* Update .pre-commit-config.yaml

* flake8 number of line

* [pre-commit.ci] auto fixes from pre-commit.com hooks

* Revert "[pre-commit.ci] auto fixes from pre-commit.com hooks"

This reverts commit 31f1dea.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

* Update test_classification.py

* [pre-commit.ci] auto fixes from pre-commit.com hooks

* Update .pre-commit-config.yaml

* Update .pre-commit-config.yaml

* Update setup.cfg

* Revert "[pre-commit.ci] auto fixes from pre-commit.com hooks"

This reverts commit 5e1906c.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

---------

Co-authored-by: Gregoire Cattan <gregoire.cattan@ibm.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
3 people authored Jun 2, 2023
1 parent 0188917 commit aa1d41b
Show file tree
Hide file tree
Showing 32 changed files with 756 additions and 604 deletions.
1 change: 0 additions & 1 deletion .github/workflows/testing.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,3 @@ jobs:
FIREBASE_CERTIFICATE: ${{ secrets.FIREBASE_CERTIFICATE }}
run: |
pytest
12 changes: 3 additions & 9 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,17 @@ repos:
rev: 23.3.0
hooks:
- id: black
exclude: ^(.github/|.devcontainer/|doc/_static/|_version.py|setup.py)

- repo: https://github.com/PyCQA/isort
rev: 5.12.0
hooks:
- id: isort
exclude: ^(.github/|.devcontainer/|doc/_static/|_version.py|setup.py)
exclude: ^(.github/|.devcontainer/|doc/_static/|doc/conf.py|pyriemann_qiskit/_version.py|setup.py)

- repo: https://github.com/pycqa/flake8
rev: 6.0.0
hooks:
- id: flake8
exclude: ^(.github/|.devcontainer/|doc/_static/|_version.py|setup.py)
exclude: ^(.github/|.devcontainer/|doc/_static/|doc/conf.py|pyriemann_qiskit/_version.py|setup.py)

- repo: https://github.com/pre-commit/mirrors-prettier
rev: v3.0.0-alpha.6
hooks:
- id: prettier
args: [--print-width=90, --prose-wrap=always]
exclude: ^(.github/|.devcontainer/|doc/_static/|_version.py|setup.py)
exclude: ^(.github/|.devcontainer/|doc/_static/|doc/conf.py|pyriemann_qiskit/_version.py|setup.py)
237 changes: 138 additions & 99 deletions README.md

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion doc/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -137,4 +137,3 @@ Quantum Provider
get_provider
get_devices
get_simulator

2 changes: 1 addition & 1 deletion doc/installing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
Installing pyRiemann-qiskit
===========================

There is no yet stable version of pyRiemann-qiskit.
There is no yet stable version of pyRiemann-qiskit.

Therefore, it is recommanded to clone the source code on `github <https://github.com/pyRiemann/pyRiemann-qiskit>`__ and install directly the package from source.

Expand Down
6 changes: 3 additions & 3 deletions doc/introduction.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Qiskit implements a quantum version of support vector
and varitional quantum classifier (VQC) [4]_. These classifiers likely offer
an advantage over classical SVM in situations where the classification task
is complex. Task complexity is raised by the encoding of the data into a
quantum state, the number of available data and the quality of the data. An initial
quantum state, the number of available data and the quality of the data. An initial
study is available in [5]_, and it can be downloaded from `here
<https://github.com/pyRiemann/pyRiemann-qiskit/blob/main/doc/Presentations/QuantumERPClassification.pdf>`_.
Although there is no study on this topic at the time of writting,
Expand All @@ -44,8 +44,8 @@ Quantum drawbacks

- Time complexity

A higher number of trials or dimension increases time to completion of the quantum algorithm, especially when running on a local machine. This is why the number of trials is limited in the examples we provided. However, you should avoid such practices in your own analysis.
A higher number of trials or dimension increases time to completion of the quantum algorithm, especially when running on a local machine. This is why the number of trials is limited in the examples we provided. However, you should avoid such practices in your own analysis.

Although these aspects are less important in a remote backend, it may happen that the quantum algorithm is queued depending on the number of concurrent users.

For all these aspects, the use of pyRiemann-qiskit should be limited to offline analysis only.
Expand Down
22 changes: 8 additions & 14 deletions examples/ERP/classify_P300_bi.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@
from moabb.datasets import bi2012
from moabb.evaluations import WithinSessionEvaluation
from moabb.paradigms import P300
from pyriemann_qiskit.classification import \
QuantumClassifierWithDefaultRiemannianPipeline
from pyriemann_qiskit.classification import (
QuantumClassifierWithDefaultRiemannianPipeline,
)
from sklearn.decomposition import PCA

print(__doc__)
Expand Down Expand Up @@ -84,7 +85,7 @@
# On a real Quantum computer (n_components = qubits)
dim_red=PCA(n_components=5),
# params={'q_account_token': '<IBM Quantum TOKEN>'}
)
)

# Here we provide a pipeline for comparison:

Expand All @@ -97,7 +98,7 @@
nfilter=2,
classes=[labels_dict["Target"]],
estimator="lwf",
xdawn_estimator="scm"
xdawn_estimator="scm",
),
TangentSpace(),
PCA(n_components=10),
Expand All @@ -107,16 +108,13 @@
print("Total pipelines to evaluate: ", len(pipelines))

evaluation = WithinSessionEvaluation(
paradigm=paradigm,
datasets=datasets,
suffix="examples",
overwrite=overwrite
paradigm=paradigm, datasets=datasets, suffix="examples", overwrite=overwrite
)

results = evaluation.process(pipelines)

print("Averaging the session performance:")
print(results.groupby('pipeline').mean('score')[['score', 'time']])
print(results.groupby("pipeline").mean("score")[["score", "time"]])

##############################################################################
# Plot Results
Expand All @@ -136,11 +134,7 @@
zorder=1,
palette="Set1",
)
sns.pointplot(data=results,
y="score",
x="pipeline",
ax=ax, zorder=1,
palette="Set1")
sns.pointplot(data=results, y="score", x="pipeline", ax=ax, zorder=1, palette="Set1")

ax.set_ylabel("ROC AUC")
ax.set_ylim(0.3, 1)
Expand Down
32 changes: 17 additions & 15 deletions examples/ERP/compare_dim_red.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@
# License: BSD (3-clause)

from pyriemann_qiskit.datasets import get_mne_sample
from pyriemann_qiskit.classification import \
QuantumClassifierWithDefaultRiemannianPipeline
from pyriemann_qiskit.classification import (
QuantumClassifierWithDefaultRiemannianPipeline,
)
from pyriemann_qiskit.utils.filtering import NaiveDimRed
from sklearn.decomposition import PCA
from sklearn.model_selection import StratifiedKFold, GridSearchCV
Expand All @@ -41,7 +42,7 @@
# This defines how we entangle the data into a quantum state
# the more complex is the kernel, the more outcomes we can expect from
# a quantum vs classical classifier.
"feature_entanglement": ['linear'], # ['linear', 'sca', 'full'],
"feature_entanglement": ["linear"], # ['linear', 'sca', 'full'],
# This parameter change the depth of the circuit when entangling data.
# There is a trade-off between accuracy and noise when the depth of the
# circuit increases.
Expand All @@ -55,7 +56,7 @@
# especially when using a simulated quantum machine.
# A quantum simulator is also limited to only 24qbits
# (and so is the size of the feature).
"dim_red": [PCA(n_components=10), NaiveDimRed()]
"dim_red": [PCA(n_components=10), NaiveDimRed()],
}

pipe = QuantumClassifierWithDefaultRiemannianPipeline()
Expand All @@ -64,14 +65,20 @@
def customize(custom_params: dict):
new_params = {}
for key in default_params:
new_params[key] = custom_params[key] if key in custom_params \
else default_params[key]
new_params[key] = (
custom_params[key] if key in custom_params else default_params[key]
)
return new_params


def search(params: dict):
grid = GridSearchCV(pipe, params, scoring='balanced_accuracy',
n_jobs=-1, cv=StratifiedKFold(n_splits=2))
grid = GridSearchCV(
pipe,
params,
scoring="balanced_accuracy",
n_jobs=-1,
cv=StratifiedKFold(n_splits=2),
)
grid.fit(X, y)
return grid.best_params_

Expand All @@ -84,13 +91,8 @@ def analyze_multiple(l_params: list[dict]):
print(best_params)


SVC = {
"shots": [None]
}
SVC = {"shots": [None]}
QSVC = {}
VQC = {
"spsa_trials": [40],
"two_local_reps": [2]
}
VQC = {"spsa_trials": [40], "two_local_reps": [2]}

analyze_multiple([SVC, QSVC, VQC])
43 changes: 18 additions & 25 deletions examples/ERP/firebase_moabb.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@
from pyriemann.estimation import XdawnCovariances
from pyriemann.tangentspace import TangentSpace
from pyriemann_qiskit.utils import (
generate_caches,
filter_subjects_by_incomplete_results,
add_moabb_dataframe_results_to_caches,
convert_caches_to_dataframes
)
generate_caches,
filter_subjects_by_incomplete_results,
add_moabb_dataframe_results_to_caches,
convert_caches_to_dataframes,
)
from sklearn.pipeline import make_pipeline
from matplotlib import pyplot as plt
import warnings
Expand All @@ -39,8 +39,9 @@
from moabb.datasets import bi2012
from moabb.evaluations import WithinSessionEvaluation
from moabb.paradigms import P300
from pyriemann_qiskit.classification import \
QuantumClassifierWithDefaultRiemannianPipeline
from pyriemann_qiskit.classification import (
QuantumClassifierWithDefaultRiemannianPipeline,
)
from sklearn.decomposition import PCA

print(__doc__)
Expand Down Expand Up @@ -92,7 +93,7 @@
# On a real Quantum computer (n_components = qubits)
dim_red=PCA(n_components=5),
# params={'q_account_token': '<IBM Quantum TOKEN>'}
)
)

# Here we provide a pipeline for comparison:

Expand All @@ -105,7 +106,7 @@
nfilter=2,
classes=[labels_dict["Target"]],
estimator="lwf",
xdawn_estimator="scm"
xdawn_estimator="scm",
),
TangentSpace(),
PCA(n_components=10),
Expand All @@ -122,28 +123,24 @@
filter_subjects_by_incomplete_results(caches, copy_datasets, pipelines)

print("Total pipelines to evaluate: ", len(pipelines))
print("Subjects to evaluate",
sum([len(dataset.subject_list) for dataset in copy_datasets]))
print(
"Subjects to evaluate",
sum([len(dataset.subject_list) for dataset in copy_datasets]),
)
evaluation = WithinSessionEvaluation(
paradigm=paradigm,
datasets=copy_datasets,
suffix="examples",
overwrite=overwrite
paradigm=paradigm, datasets=copy_datasets, suffix="examples", overwrite=overwrite
)

try:
results = evaluation.process(pipelines)
add_moabb_dataframe_results_to_caches(results,
copy_datasets,
pipelines,
caches)
add_moabb_dataframe_results_to_caches(results, copy_datasets, pipelines, caches)
except ValueError:
print("No subjects left to evaluate.")

df = convert_caches_to_dataframes(caches, datasets, pipelines)

print("Averaging the session performance:")
print(df.groupby('pipeline').mean('score')[['score', 'time']])
print(df.groupby("pipeline").mean("score")[["score", "time"]])

##############################################################################
# Plot Results
Expand All @@ -164,11 +161,7 @@
palette="Set1",
)

sns.pointplot(data=df,
y="score",
x="pipeline",
ax=ax,
palette="Set1")
sns.pointplot(data=df, y="score", x="pipeline", ax=ax, palette="Set1")

ax.set_ylabel("ROC AUC")
ax.set_ylim(0.3, 1)
Expand Down
19 changes: 10 additions & 9 deletions examples/ERP/plot_classify_EEG_quantum.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,11 @@
from pyriemann_qiskit.datasets import get_mne_sample
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import (confusion_matrix, ConfusionMatrixDisplay,
balanced_accuracy_score)
from sklearn.metrics import (
confusion_matrix,
ConfusionMatrixDisplay,
balanced_accuracy_score,
)
from matplotlib import pyplot as plt


Expand All @@ -31,8 +34,7 @@
X, y = get_mne_sample(n_trials=-1)

# ...skipping the KFold validation parts (for the purpose of the test only)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)

###############################################################################
# Decoding in tangent space with a quantum classifier
Expand All @@ -53,13 +55,12 @@


# https://stackoverflow.com/questions/61825227/plotting-multiple-confusion-matrix-side-by-side
f, axes = plt.subplots(1, 2, sharey='row')
f, axes = plt.subplots(1, 2, sharey="row")

disp = None

# Results will be computed for QuanticSVM versus SKLearnSVM for comparison
for quantum in [True, False]:

qsvm = QuanticSVM(verbose=True, quantum=quantum)
clf = make_pipeline(sf, tg, dim_red, qsvm)
clf.fit(X_train, y_train)
Expand All @@ -77,12 +78,12 @@
disp.plot(ax=axe, xticks_rotation=45)
disp.ax_.set_title(title)
disp.im_.colorbar.remove()
disp.ax_.set_xlabel('')
disp.ax_.set_xlabel("")
if not quantum:
disp.ax_.set_ylabel('')
disp.ax_.set_ylabel("")

if disp:
f.text(0.4, 0.1, 'Predicted label', ha='left')
f.text(0.4, 0.1, "Predicted label", ha="left")
plt.subplots_adjust(wspace=0.40, hspace=0.1)
f.colorbar(disp.im_, ax=axes)
plt.show()
Loading

0 comments on commit aa1d41b

Please sign in to comment.