Skip to content

Commit

Permalink
fix: fix pre-commit
Browse files Browse the repository at this point in the history
  • Loading branch information
donghufeng committed Dec 2, 2024
1 parent 87a4e07 commit d79a3ca
Show file tree
Hide file tree
Showing 158 changed files with 8,143 additions and 8,379 deletions.
100 changes: 98 additions & 2 deletions .clang-format
Original file line number Diff line number Diff line change
@@ -1,2 +1,98 @@
DerivePointerAlignment: false
PointerAlignment: Left
BasedOnStyle: Google
AccessModifierOffset: -3
AlignConsecutiveMacros: true
AlignEscapedNewlines: Right
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakTemplateDeclarations: true
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterExternBlock: false
AfterFunction: false
AfterNamespace: false
AfterStruct: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
SplitEmptyFunction: false
SplitEmptyRecord: false
SplitEmptyNamespace: false
BreakBeforeBinaryOperators: All
BreakBeforeBraces: Custom
BreakBeforeConceptDeclarations: true
BreakBeforeInheritanceComma: true
BreakConstructorInitializers: BeforeComma
ColumnLimit: 120
CompactNamespaces: false
FixNamespaceComments: true
IncludeBlocks: Regroup
IncludeCategories:
# We define the include categories such that the header files are sorted and grouped as follows:
# 1. C standard headers
# 2. C++ standard headers
# 3. CUDA headers
# 4. Boost headers
# 5. Eigen headers
# 8. Other system headers
# 9. Any local config header
# 10. Local headers
# 11. Catch2 headers
- Regex: '[<"](catch2/([A-Za-z0-9.\/\-_])+)[>"]' # Make sure Catch2 is included last
Priority: 110
- Regex: '[<"]tweedledum/([A-Za-z0-9.\/\-_])+[>"]'
Priority: 60
- Regex: <boost\/
Priority: 40
- Regex: <(Eigen|Unsupported/Eigen)\/
Priority: 50
- Regex: '[<"]cuda[A-Za-z0-9.\/\-_]+[>"]'
Priority: 30
- Regex: '[<"](driver_types.h)[>"]'
Priority: 30
- Regex: >-
'<
(assert|complex|ctype|errno|fenv|float|inttypes|iso646|limits|locale|math|setjmp|signal|stdalign|stdarg
|stdatomic|stdbool|stddef|stdint|stdio|stdlib|stdnoreturn|string|tdmath|threads|time|uchar|wchar|wctype)
\.h>'
Priority: 10
- Regex: <[[:alnum:]_\.]+.h>
Priority: 10
- Regex: <[[:alnum:]_\.]+>
Priority: 20
- Regex: <[[:alnum:]_\.]+
Priority: 80
- Regex: '"config/[[:alnum:]\/\-_\.]+\.hpp"'
Priority: 90
- Regex: '"python/[[:alnum:]\/\-_\.]+"'
Priority: 110
- Regex: '"[[:alnum:]\/\-_\.]+"'
Priority: 100
IndentPPDirectives: AfterHash
IndentRequires: true
IndentWidth: 4
KeepEmptyLinesAtTheStartOfBlocks: false
NamespaceIndentation: None
PenaltyBreakAssignment: 40
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: true
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyParentheses: false
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
StatementMacros: []
TypenameMacros: []
Standard: Latest
TabWidth: 4
UseTab: Never
WhitespaceSensitiveMacros: [CLANG_DIAG_ON, CLANG_DIAG_OFF, GCC_DIAG_ON, GCC_DIAG_OFF, MSVC_DIAG_ON, MSVC_DIAG_OFF, MQ_DO_PRAGMA]
Empty file added .cppcheck.suppressions
Empty file.
76 changes: 62 additions & 14 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
repos:
- repo: https://github.com/Lucas-C/pre-commit-hooks.git
rev: v1.5.4
rev: v1.5.5
hooks:
- id: remove-crlf
files: (?!.*third_party)^.*$ | (?!.*book)^.*$
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v5.0.0
hooks:
- id: check-added-large-files
args:
Expand All @@ -18,36 +18,84 @@ repos:
- id: trailing-whitespace
- id: requirements-txt-fixer
- id: sort-simple-yaml
- repo: https://github.com/pylint-dev/pylint
rev: v3.0.0a6
- repo: https://gitee.com/mirrors_PyCQA/pylint
rev: v3.3.1
hooks:
- id: pylint
args:
- --disable=all
- --load-plugins=docstring_checker
- --enable=doc-string-one-line,doc-string-end-with,doc-string-with-all-args,doc-string-triple-quotes,doc-string-missing,doc-string-indent-error,doc-string-with-returns,doc-string-with-raises
name: pylint-strict
exclude: (test_.*\.py)$
args: [--score=n, --load-plugins=pylint_secure_coding_standard]
additional_dependencies: [pylint-secure-coding-standard, numpy, pytest, matplotlib, scipy, torch]
- repo: https://github.com/macisamuele/language-formatters-pre-commit-hooks.git
rev: v2.10.0
rev: v2.14.0
hooks:
- id: pretty-format-yaml
args: [--autofix, --indent, '4']
- repo: https://github.com/hadialqattan/pycln
rev: v2.2.2
rev: v2.4.0
hooks:
- id: pycln
- repo: https://github.com/pre-commit/mirrors-clang-format
rev: v15.0.7
rev: v19.1.4
hooks:
- id: clang-format
args: [-style=file]
# Using this mirror lets us use mypyc-compiled black, which is about 2x faster
# Using this mirror lets us use mypyc-compiled black, which is about 2x faster
- repo: https://github.com/psf/black-pre-commit-mirror
rev: 23.12.0
rev: 24.10.0
hooks:
- id: black
- repo: https://github.com/pycqa/isort
rev: 5.12.0
rev: 5.13.2
hooks:
- id: isort
name: isort (python)
args: [--profile, black, --filter-files]

- repo: https://gitee.com/dnguyen/cmake-pre-commit-hooks-mirror
rev: v1.5.3
hooks:
- id: clang-format
require_serial: false
args: [-i]
files: .*\.(h|hpp|tpp|cpp|cc)$
additional_dependencies: [clang-format==14.*]
- id: cpplint
require_serial: false
args: [--quiet]
files: .*\.(h|hpp|tpp|cpp|cc)$
additional_dependencies: [cpplint]
- id: lizard
require_serial: false
files: .*\.(h|hpp|tpp|cpp|cc|py)$
args: [-l, cpp, -l, python, -l, java, -C, '19', -L, '100', -x, '*/tests/*', -x, '*/test/*', -x, '*/third_party/*', -W.whitelizard.txt, -w]
additional_dependencies: [lizard]
# - id: clang-tidy
# stages: [manual]
# args: [-Bbuild, -B.pre-commit-build]
# exclude: >-
# (?x)^(
# .*/kernel[0-9]+\.hpp|
# .*third_party/.*|
# .*\.cu
# )$

- repo: https://gitee.com/btcong/pre-commit-hooks
rev: v1.3.5
hooks:
- id: cppcheck
files: .*\.(h|hpp|tpp|cpp|cc)$
args: [--force, --enable=all, --error-exitcode=1, --inline-suppr, --std=c++14, --language=c++, --suppressions-list=.cppcheck.suppressions]

- repo: https://gitee.com/mirrors/flake8
rev: 5.0.4
hooks:
- id: flake8
args: [--docstring-convention, google]
name: flake8-strict
exclude: (.*_test\.py)$
additional_dependencies: [flake8-breakpoint, flake8-builtins, flake8-comprehensions, flake8-continuation, flake8-docstrings, flake8-eradicate, flake8-mutable, flake8-return, pep8-naming, flake8-secure-coding-standard]
- id: flake8
name: flake8-test-files
files: (.*_test\.py)$
additional_dependencies: [flake8-breakpoint, flake8-builtins, flake8-comprehensions, flake8-continuation, flake8-eradicate, flake8-mutable, flake8-return]
Empty file added .whitelizard.txt
Empty file.
4 changes: 4 additions & 0 deletions CPPLINT.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
set noparent
headers=cuh,h,h++,hh,hpp,hxx,tpp
linelength=120
filter=-build/header_guard,-build/c++11
6 changes: 3 additions & 3 deletions doc/source/versions.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"0.4.0": {
"tag": "tags/v0.4.0"
}
"0.4.0": {
"tag": "tags/v0.4.0"
}
}
8 changes: 2 additions & 6 deletions examples/quantum_rl/misc/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,7 @@ def gather_episodes(

while not all(done):
unfinished_ids = [i for i in range(n_episodes) if not done[i]]
normalized_states = [
s / state_bounds for i, s in enumerate(states) if not done[i]
]
normalized_states = [s / state_bounds for i, s in enumerate(states) if not done[i]]
# height = [get_height(s[0]) for i, s in enumerate(states) if not done[i]]

for i, state in zip(unfinished_ids, normalized_states):
Expand All @@ -186,9 +184,7 @@ def gather_episodes(
action_probs = model([states])
elif backend == "quafu":
newtheta, newlamda = get_model_circuit_params(qubits, genotype, model)
circuit, _, _ = generate_circuit(
qubits, genotype, newtheta, newlamda, states.numpy()[0]
)
circuit, _, _ = generate_circuit(qubits, genotype, newtheta, newlamda, states.numpy()[0])
taskid, expectation = get_quafu_exp(circuit, n_qubits, backend_quafu, shots)
tasklist.append(taskid)
# print('gather_episodes_exp:', expectation)
Expand Down
12 changes: 3 additions & 9 deletions examples/quantum_rl/models/quantum_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,7 @@ def get_model_circuit_params(qubits, genotype, model):
class NSGANetPQC(tf.keras.layers.Layer):
"""Define NSGANet PQC based on keras layer"""

def __init__(
self, qubits, genotype, observables, activation="linear", name="nsganet_PQC"
):
def __init__(self, qubits, genotype, observables, activation="linear", name="nsganet_PQC"):
super(NSGANetPQC, self).__init__(name=name)
self.n_qubits = len(qubits)
_, pos_dpqc = zip(*genotype.dpqc)
Expand All @@ -97,9 +95,7 @@ def __init__(
)

lmbd_init = tf.ones(shape=(self.n_qubits * self.n_layers,))
self.lmbd = tf.Variable(
initial_value=lmbd_init, dtype="float32", trainable=True, name="lambdas"
)
self.lmbd = tf.Variable(initial_value=lmbd_init, dtype="float32", trainable=True, name="lambdas")

# Define explicit symbol order.
symbols = [str(symb) for symb in theta_symbols + input_symbols]
Expand Down Expand Up @@ -156,9 +152,7 @@ def call(self, inputs):

def generate_model_policy(qubits, genotype, n_actions, beta, observables, env):
"""Generate a Keras model for a NSGANet PQC policy."""
input_tensor = tf.keras.Input(
shape=(len(qubits),), dtype=tf.dtypes.float32, name="input"
)
input_tensor = tf.keras.Input(shape=(len(qubits),), dtype=tf.dtypes.float32, name="input")
nsganet_pqc = NSGANetPQC(qubits, genotype, observables)([input_tensor])
process = tf.keras.Sequential(
[
Expand Down
12 changes: 3 additions & 9 deletions examples/quantum_rl/models/quantum_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@

# Organize components defined below to quantum operations
OPS = {
"variationalPQC": lambda qubits, position, params: generate_vpqc(
qubits, position, params
),
"variationalPQC": lambda qubits, position, params: generate_vpqc(qubits, position, params),
"dataencodingPQC": lambda qubits, position, count, params, state: generate_dpqc(
qubits, position, count, params, state
),
Expand Down Expand Up @@ -43,9 +41,7 @@ def generate_vpqc(qubits, position, params=None):

# Sympy symbols or load parameters for variational angles
if params == None:
params = sympy.symbols(
f"theta({3*position*n_qubits}:{3*(position+1)*n_qubits})"
)
params = sympy.symbols(f"theta({3*position*n_qubits}:{3*(position+1)*n_qubits})")
else:
params = params[3 * position * n_qubits : 3 * (position + 1) * n_qubits]
params = np.asarray(params).reshape((n_qubits, 3))
Expand All @@ -54,9 +50,7 @@ def generate_vpqc(qubits, position, params=None):
circuit = cirq.Circuit()

# Variational layer
circuit += cirq.Circuit(
one_qubit_rotation(q, params[i]) for i, q in enumerate(qubits)
)
circuit += cirq.Circuit(one_qubit_rotation(q, params[i]) for i, q in enumerate(qubits))

return circuit, list(params.flat)

Expand Down
12 changes: 3 additions & 9 deletions examples/quantum_rl/search/nsganet.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,7 @@ def binary_tournament(pop, P, algorithm, **kwargs):
S[i] = b

elif tournament_type == "comp_by_rank_and_crowding":
S[i] = compare(
a, pop[a].rank, b, pop[b].rank, method="smaller_is_better"
)
S[i] = compare(a, pop[a].rank, b, pop[b].rank, method="smaller_is_better")

else:
raise Exception("Unknown tournament type.")
Expand Down Expand Up @@ -114,9 +112,7 @@ def _do(self, pop, n_survive, D=None, **kwargs):

# current front sorted by crowding distance if splitting
if len(survivors) + len(front) > n_survive:
I = randomized_argsort(
crowding_of_front, order="descending", method="numpy"
)
I = randomized_argsort(crowding_of_front, order="descending", method="numpy")
I = I[: (n_survive - len(survivors))]

# otherwise take the whole front unsorted
Expand Down Expand Up @@ -145,9 +141,7 @@ def calc_crowding_distance(F):
F = F[I, np.arange(n_obj)]

# get the distance to the last element in sorted list and replace zeros with actual values
dist = np.concatenate([F, np.full((1, n_obj), np.inf)]) - np.concatenate(
[np.full((1, n_obj), -np.inf), F]
)
dist = np.concatenate([F, np.full((1, n_obj), np.inf)]) - np.concatenate([np.full((1, n_obj), -np.inf), F])

index_dist_is_zero = np.where(dist == 0)

Expand Down
12 changes: 3 additions & 9 deletions examples/quantum_rl/search/quantum_evolution_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,8 @@

parser = argparse.ArgumentParser("Multi-objetive Genetic Algorithm for quantum NAS")
parser.add_argument("--save", type=str, default="quantumGA", help="experiment name")
parser.add_argument(
"--n_var", type=int, default=30, help="the maximum length of architecture"
)
parser.add_argument(
"--pop_size", type=int, default=10, help="population size of networks"
)
parser.add_argument("--n_var", type=int, default=30, help="the maximum length of architecture")
parser.add_argument("--pop_size", type=int, default=10, help="population size of networks")
parser.add_argument("--n_gens", type=int, default=10, help="number of generation")
parser.add_argument(
"--n_offspring",
Expand Down Expand Up @@ -179,9 +175,7 @@ def main(qubits, n_actions, observables):
)

# configure the nsga-net method
method = engine.nsganet(
pop_size=args.pop_size, n_offsprings=args.n_offspring, eliminate_duplicates=True
)
method = engine.nsganet(pop_size=args.pop_size, n_offsprings=args.n_offspring, eliminate_duplicates=True)

res = minimize(
problem,
Expand Down
Loading

0 comments on commit d79a3ca

Please sign in to comment.