Skip to content

reformat Python files with Black 24.2.0 #1266

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 47 additions & 18 deletions build.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ def step_end():
if os.getenv("GITHUB_ACTIONS") == "true":
print(f"::endgroup::")


def use_python_env(folder):
# Check if in a virtual environment
if (
Expand Down Expand Up @@ -323,16 +324,22 @@ def use_python_env(folder):

if build_samples:
step_start("Building qsharp samples")
project_directories = [dir for dir in os.walk(samples_src) if "qsharp.json" in dir[2]]
single_file_directories = [candidate for candidate in os.walk(samples_src) if all([not proj_dir[0] in candidate[0] for proj_dir in project_directories])]
project_directories = [
dir for dir in os.walk(samples_src) if "qsharp.json" in dir[2]
]
single_file_directories = [
candidate
for candidate in os.walk(samples_src)
if all([not proj_dir[0] in candidate[0] for proj_dir in project_directories])
]

files = [
os.path.join(dp, f)
for dp, _, filenames in single_file_directories
for f in filenames
if os.path.splitext(f)[1] == ".qs"
]
projects = [
projects = [
os.path.join(dp, f)
for dp, _, filenames in project_directories
for f in filenames
Expand All @@ -344,7 +351,12 @@ def use_python_env(folder):
for file in files:
subprocess.run((cargo_args + ["--", file]), check=True, text=True, cwd=root_dir)
for project in projects:
subprocess.run((cargo_args + ["--", "--qsharp-json", project]), check=True, text=True, cwd=root_dir)
subprocess.run(
(cargo_args + ["--", "--qsharp-json", project]),
check=True,
text=True,
cwd=root_dir,
)
step_end()

if build_npm:
Expand Down Expand Up @@ -414,8 +426,13 @@ def use_python_env(folder):
step_start("Running notebook samples integration tests")
# Find all notebooks in the samples directory. Skip the basic sample and the azure submission sample, since those won't run
# nicely in automation.
notebook_files = [os.path.join(dp, f) for dp, _, filenames in os.walk(samples_src) for f in filenames if f.endswith(".ipynb")
and not (f.startswith("sample.") or f.startswith("azure_submission."))]
notebook_files = [
os.path.join(dp, f)
for dp, _, filenames in os.walk(samples_src)
for f in filenames
if f.endswith(".ipynb")
and not (f.startswith("sample.") or f.startswith("azure_submission."))
]
python_bin = use_python_env(samples_src)

# copy the process env vars
Expand All @@ -442,7 +459,9 @@ def use_python_env(folder):
"install",
widgets_src,
]
subprocess.run(pip_install_args, check=True, text=True, cwd=widgets_src, env=pip_env)
subprocess.run(
pip_install_args, check=True, text=True, cwd=widgets_src, env=pip_env
)

# Install other dependencies
pip_install_args = [
Expand All @@ -459,17 +478,27 @@ def use_python_env(folder):
for notebook in notebook_files:
print(f"Running {notebook}")
# Run the notebook process, capturing stdout and only displaying it if there is an error
result = subprocess.run([python_bin,
"-m",
"nbconvert",
"--to",
"notebook",
"--stdout",
"--ExecutePreprocessor.timeout=60",
"--sanitize-html",
"--execute",
notebook],
check=False, text=True, cwd=root_dir, env=pip_env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8")
result = subprocess.run(
[
python_bin,
"-m",
"nbconvert",
"--to",
"notebook",
"--stdout",
"--ExecutePreprocessor.timeout=60",
"--sanitize-html",
"--execute",
notebook,
],
check=False,
text=True,
cwd=root_dir,
env=pip_env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding="utf-8",
)
if result.returncode != 0:
print(result.stdout)
raise Exception(f"Error running {notebook}")
Expand Down
6 changes: 1 addition & 5 deletions jupyterlab/qsharp-jupyterlab/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,4 @@


def _jupyter_labextension_paths():
return [{
"src": "labextension",
"dest": "qsharp-jupyterlab"
}]

return [{"src": "labextension", "dest": "qsharp-jupyterlab"}]
2 changes: 1 addition & 1 deletion jupyterlab/setup.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__import__('setuptools').setup()
__import__("setuptools").setup()
10 changes: 5 additions & 5 deletions pip/qsharp/_fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ def map_dir(e: str) -> Dict[str, str]:
return {
"path": os.path.join(dir_path, e),
"entry_name": e,
"type": "file"
if os.path.isfile(os.path.join(dir_path, e))
else "folder"
if os.path.isdir(os.path.join(dir_path, e))
else "unknown",
"type": (
"file"
if os.path.isfile(os.path.join(dir_path, e))
else "folder" if os.path.isdir(os.path.join(dir_path, e)) else "unknown"
),
}

return list(map(map_dir, os.listdir(dir_path)))
Expand Down
11 changes: 8 additions & 3 deletions pip/qsharp/_native.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ class Interpreter:
:param list_directory: A function that lists the contents of a directory.
"""
...

def interpret(self, input: str, output_fn: Callable[[Output], None]) -> Any:
"""
Interprets Q# source code.
Expand All @@ -57,9 +58,8 @@ class Interpreter:
:raises QSharpError: If there is an error interpreting the input.
"""
...
def run(
self, entry_expr: str, output_fn: Callable[[Output], None]
) -> Any:

def run(self, entry_expr: str, output_fn: Callable[[Output], None]) -> Any:
"""
Runs the given Q# expression with an independent instance of the simulator.

Expand All @@ -71,6 +71,7 @@ class Interpreter:
:raises QSharpError: If there is an error interpreting the input.
"""
...

def qir(self, entry_expr: str) -> str:
"""
Generates QIR from Q# source code.
Expand All @@ -80,6 +81,7 @@ class Interpreter:
:returns qir: The QIR string.
"""
...

def estimate(self, entry_expr: str, params: str) -> str:
"""
Estimates resources for Q# source code.
Expand All @@ -90,6 +92,7 @@ class Interpreter:
:returns resources: The estimated resources.
"""
...

def set_quantum_seed(self, seed: Optional[int]) -> None:
"""
Sets the seed for the quantum random number generator.
Expand All @@ -98,6 +101,7 @@ class Interpreter:
the seed will be generated from entropy.
"""
...

def set_classical_seed(self, seed: Optional[int]) -> None:
"""
Sets the seed for the classical random number generator.
Expand All @@ -106,6 +110,7 @@ class Interpreter:
the seed will be generated from entropy.
"""
...

def dump_machine(self) -> StateDumpData:
"""
Returns the sparse state vector of the simulator as a StateDump object.
Expand Down
14 changes: 12 additions & 2 deletions pip/qsharp/_qsharp.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,16 @@ def init(
# if no features were passed in as an argument, use the features from the manifest.
# this way we prefer the features from the argument over those from the manifest.
if language_features == [] and manifest_descriptor != None:
language_features = manifest_descriptor["manifest"].get("languageFeatures") or []
language_features = (
manifest_descriptor["manifest"].get("languageFeatures") or []
)

_interpreter = Interpreter(
target_profile, language_features, manifest_descriptor, read_file, list_directory
target_profile,
language_features,
manifest_descriptor,
read_file,
list_directory,
)

# Return the configuration information to provide a hint to the
Expand Down Expand Up @@ -252,6 +258,7 @@ def estimate(
json.loads(get_interpreter().estimate(entry_expr, json.dumps(params)))
)


def set_quantum_seed(seed: Optional[int]) -> None:
"""
Sets the seed for the random number generator used for quantum measurements.
Expand All @@ -262,6 +269,7 @@ def set_quantum_seed(seed: Optional[int]) -> None:
"""
get_interpreter().set_quantum_seed(seed)


def set_classical_seed(seed: Optional[int]) -> None:
"""
Sets the seed for the random number generator used for standard
Expand All @@ -273,6 +281,7 @@ def set_classical_seed(seed: Optional[int]) -> None:
"""
get_interpreter().set_classical_seed(seed)


class StateDump:
"""
A state dump returned from the Q# interpreter.
Expand Down Expand Up @@ -309,6 +318,7 @@ def __str__(self) -> str:
def _repr_html_(self) -> str:
return self.__data._repr_html_()


def dump_machine() -> StateDump:
"""
Returns the sparse state vector of the simulator as a StateDump object.
Expand Down
17 changes: 16 additions & 1 deletion pip/qsharp/estimator/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

from ._estimator import EstimatorError, LogicalCounts, EstimatorResult, QubitParams, QECScheme, MeasurementErrorRate, EstimatorQubitParams, EstimatorQecScheme, ProtocolSpecificDistillationUnitSpecification, DistillationUnitSpecification, ErrorBudgetPartition, EstimatorConstraints, EstimatorInputParamsItem, EstimatorParams
from ._estimator import (
EstimatorError,
LogicalCounts,
EstimatorResult,
QubitParams,
QECScheme,
MeasurementErrorRate,
EstimatorQubitParams,
EstimatorQecScheme,
ProtocolSpecificDistillationUnitSpecification,
DistillationUnitSpecification,
ErrorBudgetPartition,
EstimatorConstraints,
EstimatorInputParamsItem,
EstimatorParams,
)

__all__ = [
"EstimatorError",
Expand Down
42 changes: 22 additions & 20 deletions pip/qsharp/estimator/_estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
except ImportError:
has_markdown = False


class EstimatorError(BaseException):
"""
An error returned from the resource estimation.
Expand All @@ -29,6 +30,7 @@ def __init__(self, code: str, message: str):
def __str__(self):
return self.message


@dataclass
class AutoValidatingParams:
"""
Expand Down Expand Up @@ -151,12 +153,12 @@ def check_instruction_set(name, value):
one_qubit_gate_time: Optional[str] = validating_field(check_time)
two_qubit_gate_time: Optional[str] = validating_field(check_time)
t_gate_time: Optional[str] = validating_field(check_time)
one_qubit_measurement_error_rate: Union[
None, float, MeasurementErrorRate
] = validating_field(_check_error_rate_or_process_and_readout)
two_qubit_joint_measurement_error_rate: Union[
None, float, MeasurementErrorRate
] = validating_field(_check_error_rate_or_process_and_readout)
one_qubit_measurement_error_rate: Union[None, float, MeasurementErrorRate] = (
validating_field(_check_error_rate_or_process_and_readout)
)
two_qubit_joint_measurement_error_rate: Union[None, float, MeasurementErrorRate] = (
validating_field(_check_error_rate_or_process_and_readout)
)
one_qubit_gate_error_rate: Optional[float] = validating_field(_check_error_rate)
two_qubit_gate_error_rate: Optional[float] = validating_field(_check_error_rate)
t_gate_error_rate: Optional[float] = validating_field(_check_error_rate)
Expand Down Expand Up @@ -206,16 +208,16 @@ def as_dict(self, validate=True) -> Dict[str, Any]:
qubit_params = super().as_dict(validate)
if len(qubit_params) != 0:
if isinstance(self.one_qubit_measurement_error_rate, MeasurementErrorRate):
qubit_params[
"oneQubitMeasurementErrorRate"
] = self.one_qubit_measurement_error_rate.as_dict(validate)
qubit_params["oneQubitMeasurementErrorRate"] = (
self.one_qubit_measurement_error_rate.as_dict(validate)
)

if isinstance(
self.two_qubit_joint_measurement_error_rate, MeasurementErrorRate
):
qubit_params[
"twoQubitJointMeasurementErrorRate"
] = self.two_qubit_joint_measurement_error_rate.as_dict(validate)
qubit_params["twoQubitJointMeasurementErrorRate"] = (
self.two_qubit_joint_measurement_error_rate.as_dict(validate)
)

return qubit_params

Expand Down Expand Up @@ -323,18 +325,18 @@ def as_dict(self, validate=True) -> Dict[str, Any]:
self.physical_qubit_specification.as_dict(validate)
)
if len(physical_qubit_specification_dict) != 0:
specification_dict[
"physicalQubitSpecification"
] = physical_qubit_specification_dict
specification_dict["physicalQubitSpecification"] = (
physical_qubit_specification_dict
)

if self.logical_qubit_specification is not None:
logical_qubit_specification_dict = (
self.logical_qubit_specification.as_dict(validate)
)
if len(logical_qubit_specification_dict) != 0:
specification_dict[
"logicalQubitSpecification"
] = logical_qubit_specification_dict
specification_dict["logicalQubitSpecification"] = (
logical_qubit_specification_dict
)

if self.logical_qubit_specification_first_round_override is not None:
logical_qubit_specification_first_round_override_dict = (
Expand Down Expand Up @@ -549,7 +551,7 @@ def __init__(self, data: Union[Dict, List]):
if isinstance(data, list) and len(data) == 1:
data = data[0]
if not EstimatorResult._is_succeeded(data):
raise EstimatorError(data['code'] ,data['message'])
raise EstimatorError(data["code"], data["message"])

if isinstance(data, dict):
self._data = data
Expand All @@ -561,7 +563,7 @@ def __init__(self, data: Union[Dict, List]):
self.summary = HTMLWrapper(self._item_result_summary_table())
self.diagram = EstimatorResultDiagram(self.data().copy())
else:
self._error = EstimatorError(data['code'] ,data['message'])
self._error = EstimatorError(data["code"], data["message"])

elif isinstance(data, list):
super().__init__(
Expand Down
7 changes: 6 additions & 1 deletion pip/qsharp/utils/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,10 @@ def dump_operation(operation: str, num_qubits: int) -> List[List[complex]]:
if entry is None:
matrix[i] += [complex(0, 0)]
else:
matrix[i] += [complex(round(factor * entry.real, ndigits), round(factor * entry.imag, ndigits))]
matrix[i] += [
complex(
round(factor * entry.real, ndigits),
round(factor * entry.imag, ndigits),
)
]
return matrix
Loading