hexsha stringlengths 40 40 | size int64 2 1.02M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 1.02M | avg_line_length float64 1 417k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 1
class | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f727fdadcd3bc9ccad0ae50f7d825827d2eb27e6 | 1,146 | py | Python | manage-api/server/main.py | lisy09/spark-dev-box | ed362cb5b19400a798995e270869df14805600a0 | [
"MIT"
] | null | null | null | manage-api/server/main.py | lisy09/spark-dev-box | ed362cb5b19400a798995e270869df14805600a0 | [
"MIT"
] | null | null | null | manage-api/server/main.py | lisy09/spark-dev-box | ed362cb5b19400a798995e270869df14805600a0 | [
"MIT"
] | null | null | null | from fastapi import FastAPI
import logging
from .routers import routers
from .core.config import get_config, get_gunicorn_config
from .core.logger import setup_logger, StubbedGunicornLogger
import gunicorn.app.base
def createSimpleFastapi():
app = FastAPI()
app.include_router(routers.router)
return app
def createFastapi(conf):
app = createSimpleFastapi()
app.state.config = conf
return app
class GunicornApplication(gunicorn.app.base.BaseApplication):
def __init__(self, app, options=None):
self.options = options or {}
self.application = app
super().__init__()
def load_config(self):
config = {key: value for key, value in self.options.items()
if key in self.cfg.settings and value is not None}
for key, value in config.items():
self.cfg.set(key.lower(), value)
def load(self):
return self.application
if __name__ == "__main__":
conf = get_config()
setup_logger()
app = createFastapi(conf)
gunicorn_options = get_gunicorn_config(StubbedGunicornLogger)
GunicornApplication(app, gunicorn_options).run() | 27.95122 | 68 | 0.696335 | from fastapi import FastAPI
import logging
from .routers import routers
from .core.config import get_config, get_gunicorn_config
from .core.logger import setup_logger, StubbedGunicornLogger
import gunicorn.app.base
def createSimpleFastapi():
app = FastAPI()
app.include_router(routers.router)
return app
def createFastapi(conf):
app = createSimpleFastapi()
app.state.config = conf
return app
class GunicornApplication(gunicorn.app.base.BaseApplication):
def __init__(self, app, options=None):
self.options = options or {}
self.application = app
super().__init__()
def load_config(self):
config = {key: value for key, value in self.options.items()
if key in self.cfg.settings and value is not None}
for key, value in config.items():
self.cfg.set(key.lower(), value)
def load(self):
return self.application
if __name__ == "__main__":
conf = get_config()
setup_logger()
app = createFastapi(conf)
gunicorn_options = get_gunicorn_config(StubbedGunicornLogger)
GunicornApplication(app, gunicorn_options).run() | true | true |
f727fdc01f072843395a369831bd24b9de4f8cb3 | 9,268 | py | Python | skimage/future/graph/graph_cut.py | portugueslab/scikit-image | 0fa3bcb118bb208a0cc7d3e8b96cd96c1ce7a75b | [
"BSD-3-Clause"
] | 2 | 2020-02-24T02:24:43.000Z | 2021-12-19T11:44:34.000Z | skimage/future/graph/graph_cut.py | portugueslab/scikit-image | 0fa3bcb118bb208a0cc7d3e8b96cd96c1ce7a75b | [
"BSD-3-Clause"
] | 30 | 2020-04-15T19:37:40.000Z | 2020-04-22T21:19:35.000Z | skimage/future/graph/graph_cut.py | portugueslab/scikit-image | 0fa3bcb118bb208a0cc7d3e8b96cd96c1ce7a75b | [
"BSD-3-Clause"
] | 2 | 2019-06-16T06:38:28.000Z | 2021-12-19T11:44:48.000Z | try:
import networkx as nx
except ImportError:
from ..._shared.utils import warn
warn('RAGs require networkx')
import numpy as np
from . import _ncut
from . import _ncut_cy
from scipy.sparse import linalg
def cut_threshold(labels, rag, thresh, in_place=True):
"""Combine regions separated by weight less than threshold.
Given an image's labels and its RAG, output new labels by
combining regions whose nodes are separated by a weight less
than the given threshold.
Parameters
----------
labels : ndarray
The array of labels.
rag : RAG
The region adjacency graph.
thresh : float
The threshold. Regions connected by edges with smaller weights are
combined.
in_place : bool
If set, modifies `rag` in place. The function will remove the edges
with weights less that `thresh`. If set to `False` the function
makes a copy of `rag` before proceeding.
Returns
-------
out : ndarray
The new labelled array.
Examples
--------
>>> from skimage import data, segmentation
>>> from skimage.future import graph
>>> img = data.astronaut()
>>> labels = segmentation.slic(img)
>>> rag = graph.rag_mean_color(img, labels)
>>> new_labels = graph.cut_threshold(labels, rag, 10)
References
----------
.. [1] Alain Tremeau and Philippe Colantoni
"Regions Adjacency Graph Applied To Color Image Segmentation"
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.11.5274
"""
if not in_place:
rag = rag.copy()
# Because deleting edges while iterating through them produces an error.
to_remove = [(x, y) for x, y, d in rag.edges(data=True)
if d['weight'] >= thresh]
rag.remove_edges_from(to_remove)
comps = nx.connected_components(rag)
# We construct an array which can map old labels to the new ones.
# All the labels within a connected component are assigned to a single
# label in the output.
map_array = np.arange(labels.max() + 1, dtype=labels.dtype)
for i, nodes in enumerate(comps):
for node in nodes:
for label in rag.node[node]['labels']:
map_array[label] = i
return map_array[labels]
def cut_normalized(labels, rag, thresh=0.001, num_cuts=10, in_place=True,
max_edge=1.0):
"""Perform Normalized Graph cut on the Region Adjacency Graph.
Given an image's labels and its similarity RAG, recursively perform
a 2-way normalized cut on it. All nodes belonging to a subgraph
that cannot be cut further are assigned a unique label in the
output.
Parameters
----------
labels : ndarray
The array of labels.
rag : RAG
The region adjacency graph.
thresh : float
The threshold. A subgraph won't be further subdivided if the
value of the N-cut exceeds `thresh`.
num_cuts : int
The number or N-cuts to perform before determining the optimal one.
in_place : bool
If set, modifies `rag` in place. For each node `n` the function will
set a new attribute ``rag.node[n]['ncut label']``.
max_edge : float, optional
The maximum possible value of an edge in the RAG. This corresponds to
an edge between identical regions. This is used to put self
edges in the RAG.
Returns
-------
out : ndarray
The new labeled array.
Examples
--------
>>> from skimage import data, segmentation
>>> from skimage.future import graph
>>> img = data.astronaut()
>>> labels = segmentation.slic(img)
>>> rag = graph.rag_mean_color(img, labels, mode='similarity')
>>> new_labels = graph.cut_normalized(labels, rag)
References
----------
.. [1] Shi, J.; Malik, J., "Normalized cuts and image segmentation",
Pattern Analysis and Machine Intelligence,
IEEE Transactions on, vol. 22, no. 8, pp. 888-905, August 2000.
"""
if not in_place:
rag = rag.copy()
for node in rag.nodes():
rag.add_edge(node, node, weight=max_edge)
_ncut_relabel(rag, thresh, num_cuts)
map_array = np.zeros(labels.max() + 1, dtype=labels.dtype)
# Mapping from old labels to new
for n, d in rag.nodes(data=True):
map_array[d['labels']] = d['ncut label']
return map_array[labels]
def partition_by_cut(cut, rag):
"""Compute resulting subgraphs from given bi-parition.
Parameters
----------
cut : array
A array of booleans. Elements set to `True` belong to one
set.
rag : RAG
The Region Adjacency Graph.
Returns
-------
sub1, sub2 : RAG
The two resulting subgraphs from the bi-partition.
"""
# `cut` is derived from `D` and `W` matrices, which also follow the
# ordering returned by `rag.nodes()` because we use
# nx.to_scipy_sparse_matrix.
# Example
# rag.nodes() = [3, 7, 9, 13]
# cut = [True, False, True, False]
# nodes1 = [3, 9]
# nodes2 = [7, 10]
nodes1 = [n for i, n in enumerate(rag.nodes()) if cut[i]]
nodes2 = [n for i, n in enumerate(rag.nodes()) if not cut[i]]
sub1 = rag.subgraph(nodes1)
sub2 = rag.subgraph(nodes2)
return sub1, sub2
def get_min_ncut(ev, d, w, num_cuts):
"""Threshold an eigenvector evenly, to determine minimum ncut.
Parameters
----------
ev : array
The eigenvector to threshold.
d : ndarray
The diagonal matrix of the graph.
w : ndarray
The weight matrix of the graph.
num_cuts : int
The number of evenly spaced thresholds to check for.
Returns
-------
mask : array
The array of booleans which denotes the bi-partition.
mcut : float
The value of the minimum ncut.
"""
mcut = np.inf
mn = ev.min()
mx = ev.max()
# If all values in `ev` are equal, it implies that the graph can't be
# further sub-divided. In this case the bi-partition is the the graph
# itself and an empty set.
min_mask = np.zeros_like(ev, dtype=np.bool)
if np.allclose(mn, mx):
return min_mask, mcut
# Refer Shi & Malik 2001, Section 3.1.3, Page 892
# Perform evenly spaced n-cuts and determine the optimal one.
for t in np.linspace(mn, mx, num_cuts, endpoint=False):
mask = ev > t
cost = _ncut.ncut_cost(mask, d, w)
if cost < mcut:
min_mask = mask
mcut = cost
return min_mask, mcut
def _label_all(rag, attr_name):
"""Assign a unique integer to the given attribute in the RAG.
This function assumes that all labels in `rag` are unique. It
picks up a random label from them and assigns it to the `attr_name`
attribute of all the nodes.
rag : RAG
The Region Adjacency Graph.
attr_name : string
The attribute to which a unique integer is assigned.
"""
node = min(rag.nodes())
new_label = rag.node[node]['labels'][0]
for n, d in rag.nodes(data=True):
d[attr_name] = new_label
def _ncut_relabel(rag, thresh, num_cuts):
"""Perform Normalized Graph cut on the Region Adjacency Graph.
Recursively partition the graph into 2, until further subdivision
yields a cut greater than `thresh` or such a cut cannot be computed.
For such a subgraph, indices to labels of all its nodes map to a single
unique value.
Parameters
----------
labels : ndarray
The array of labels.
rag : RAG
The region adjacency graph.
thresh : float
The threshold. A subgraph won't be further subdivided if the
value of the N-cut exceeds `thresh`.
num_cuts : int
The number or N-cuts to perform before determining the optimal one.
map_array : array
The array which maps old labels to new ones. This is modified inside
the function.
"""
d, w = _ncut.DW_matrices(rag)
m = w.shape[0]
if m > 2:
d2 = d.copy()
# Since d is diagonal, we can directly operate on its data
# the inverse of the square root
d2.data = np.reciprocal(np.sqrt(d2.data, out=d2.data), out=d2.data)
# Refer Shi & Malik 2001, Equation 7, Page 891
vals, vectors = linalg.eigsh(d2 * (d - w) * d2, which='SM',
k=min(100, m - 2))
# Pick second smallest eigenvector.
# Refer Shi & Malik 2001, Section 3.2.3, Page 893
vals, vectors = np.real(vals), np.real(vectors)
index2 = _ncut_cy.argmin2(vals)
ev = vectors[:, index2]
cut_mask, mcut = get_min_ncut(ev, d, w, num_cuts)
if (mcut < thresh):
# Sub divide and perform N-cut again
# Refer Shi & Malik 2001, Section 3.2.5, Page 893
sub1, sub2 = partition_by_cut(cut_mask, rag)
_ncut_relabel(sub1, thresh, num_cuts)
_ncut_relabel(sub2, thresh, num_cuts)
return
# The N-cut wasn't small enough, or could not be computed.
# The remaining graph is a region.
# Assign `ncut label` by picking any label from the existing nodes, since
# `labels` are unique, `new_label` is also unique.
_label_all(rag, 'ncut label')
| 31.416949 | 77 | 0.623867 | try:
import networkx as nx
except ImportError:
from ..._shared.utils import warn
warn('RAGs require networkx')
import numpy as np
from . import _ncut
from . import _ncut_cy
from scipy.sparse import linalg
def cut_threshold(labels, rag, thresh, in_place=True):
if not in_place:
rag = rag.copy()
to_remove = [(x, y) for x, y, d in rag.edges(data=True)
if d['weight'] >= thresh]
rag.remove_edges_from(to_remove)
comps = nx.connected_components(rag)
map_array = np.arange(labels.max() + 1, dtype=labels.dtype)
for i, nodes in enumerate(comps):
for node in nodes:
for label in rag.node[node]['labels']:
map_array[label] = i
return map_array[labels]
def cut_normalized(labels, rag, thresh=0.001, num_cuts=10, in_place=True,
max_edge=1.0):
if not in_place:
rag = rag.copy()
for node in rag.nodes():
rag.add_edge(node, node, weight=max_edge)
_ncut_relabel(rag, thresh, num_cuts)
map_array = np.zeros(labels.max() + 1, dtype=labels.dtype)
for n, d in rag.nodes(data=True):
map_array[d['labels']] = d['ncut label']
return map_array[labels]
def partition_by_cut(cut, rag):
nodes1 = [n for i, n in enumerate(rag.nodes()) if cut[i]]
nodes2 = [n for i, n in enumerate(rag.nodes()) if not cut[i]]
sub1 = rag.subgraph(nodes1)
sub2 = rag.subgraph(nodes2)
return sub1, sub2
def get_min_ncut(ev, d, w, num_cuts):
mcut = np.inf
mn = ev.min()
mx = ev.max()
# further sub-divided. In this case the bi-partition is the the graph
# itself and an empty set.
min_mask = np.zeros_like(ev, dtype=np.bool)
if np.allclose(mn, mx):
return min_mask, mcut
# Refer Shi & Malik 2001, Section 3.1.3, Page 892
# Perform evenly spaced n-cuts and determine the optimal one.
for t in np.linspace(mn, mx, num_cuts, endpoint=False):
mask = ev > t
cost = _ncut.ncut_cost(mask, d, w)
if cost < mcut:
min_mask = mask
mcut = cost
return min_mask, mcut
def _label_all(rag, attr_name):
node = min(rag.nodes())
new_label = rag.node[node]['labels'][0]
for n, d in rag.nodes(data=True):
d[attr_name] = new_label
def _ncut_relabel(rag, thresh, num_cuts):
d, w = _ncut.DW_matrices(rag)
m = w.shape[0]
if m > 2:
d2 = d.copy()
# Since d is diagonal, we can directly operate on its data
# the inverse of the square root
d2.data = np.reciprocal(np.sqrt(d2.data, out=d2.data), out=d2.data)
# Refer Shi & Malik 2001, Equation 7, Page 891
vals, vectors = linalg.eigsh(d2 * (d - w) * d2, which='SM',
k=min(100, m - 2))
# Pick second smallest eigenvector.
# Refer Shi & Malik 2001, Section 3.2.3, Page 893
vals, vectors = np.real(vals), np.real(vectors)
index2 = _ncut_cy.argmin2(vals)
ev = vectors[:, index2]
cut_mask, mcut = get_min_ncut(ev, d, w, num_cuts)
if (mcut < thresh):
# Sub divide and perform N-cut again
# Refer Shi & Malik 2001, Section 3.2.5, Page 893
sub1, sub2 = partition_by_cut(cut_mask, rag)
_ncut_relabel(sub1, thresh, num_cuts)
_ncut_relabel(sub2, thresh, num_cuts)
return
# The N-cut wasn't small enough, or could not be computed.
_label_all(rag, 'ncut label')
| true | true |
f727fddd3097c5ec42695160636f977e440b5a91 | 1,058 | py | Python | meijer/tests/test_meijer_list.py | sllawcj/python_Meijer | d8caf2e97ce30df565810bac9dff4d1cccc59022 | [
"MIT"
] | 6 | 2020-03-23T02:58:30.000Z | 2022-01-16T02:41:50.000Z | meijer/tests/test_meijer_list.py | sllawcj/python_Meijer | d8caf2e97ce30df565810bac9dff4d1cccc59022 | [
"MIT"
] | 1 | 2021-12-12T21:45:11.000Z | 2021-12-12T21:45:11.000Z | meijer/tests/test_meijer_list.py | sllawcj/python_Meijer | d8caf2e97ce30df565810bac9dff4d1cccc59022 | [
"MIT"
] | 3 | 2020-11-04T02:35:13.000Z | 2021-11-07T20:46:04.000Z | import pytest
from meijer import __version__
from meijer import Meijer
@pytest.fixture(scope="session")
def meijer():
with Meijer() as m:
m.login()
yield m
@pytest.fixture(scope="session")
def shopping_list(meijer):
shopping_list = meijer.list
shopping_list.clear()
yield shopping_list
shopping_list.clear()
def test_empty_list(shopping_list):
assert shopping_list.count == 0
def test_list_add(shopping_list, session_uuid):
for i in range(10):
shopping_list.add(f"pytest {str(i)} {session_uuid}")
assert shopping_list.count == 10
def test_list_complete(shopping_list):
for item in shopping_list.items:
if not item["isComplete"]:
shopping_list.complete(item)
def test_list_uncomplete(shopping_list):
for item in shopping_list.items:
if item["isComplete"]:
shopping_list.uncomplete(item)
def test_list_complete2(shopping_list):
for item in shopping_list.items:
if not item["isComplete"]:
shopping_list.complete(item)
| 22.041667 | 60 | 0.695652 | import pytest
from meijer import __version__
from meijer import Meijer
@pytest.fixture(scope="session")
def meijer():
with Meijer() as m:
m.login()
yield m
@pytest.fixture(scope="session")
def shopping_list(meijer):
shopping_list = meijer.list
shopping_list.clear()
yield shopping_list
shopping_list.clear()
def test_empty_list(shopping_list):
assert shopping_list.count == 0
def test_list_add(shopping_list, session_uuid):
for i in range(10):
shopping_list.add(f"pytest {str(i)} {session_uuid}")
assert shopping_list.count == 10
def test_list_complete(shopping_list):
for item in shopping_list.items:
if not item["isComplete"]:
shopping_list.complete(item)
def test_list_uncomplete(shopping_list):
for item in shopping_list.items:
if item["isComplete"]:
shopping_list.uncomplete(item)
def test_list_complete2(shopping_list):
for item in shopping_list.items:
if not item["isComplete"]:
shopping_list.complete(item)
| true | true |
f727febcbb7b6a2d542c6088719875fe0507db7e | 377 | py | Python | examples/using_R2018.py | jkjt/ezdxf | 2acc5611b81476ea16b98063b9f55446a9182b81 | [
"MIT"
] | 515 | 2017-01-25T05:46:52.000Z | 2022-03-29T09:52:27.000Z | examples/using_R2018.py | jkjt/ezdxf | 2acc5611b81476ea16b98063b9f55446a9182b81 | [
"MIT"
] | 417 | 2017-01-25T10:01:17.000Z | 2022-03-29T09:22:04.000Z | examples/using_R2018.py | jkjt/ezdxf | 2acc5611b81476ea16b98063b9f55446a9182b81 | [
"MIT"
] | 149 | 2017-02-01T15:52:02.000Z | 2022-03-17T10:33:38.000Z | # Copyright (c) 2017-2021 Manfred Moitzi
# License: MIT License
import ezdxf
doc = ezdxf.new("R2018", setup=True)
modelspace = doc.modelspace()
modelspace.add_circle(
center=(0, 0),
radius=1.5,
dxfattribs={
"layer": "test",
"linetype": "DASHED",
},
)
filename = "circle_R2018.dxf"
doc.saveas(filename)
print(f"DXF file '{filename}' created.")
| 19.842105 | 40 | 0.647215 |
import ezdxf
doc = ezdxf.new("R2018", setup=True)
modelspace = doc.modelspace()
modelspace.add_circle(
center=(0, 0),
radius=1.5,
dxfattribs={
"layer": "test",
"linetype": "DASHED",
},
)
filename = "circle_R2018.dxf"
doc.saveas(filename)
print(f"DXF file '{filename}' created.")
| true | true |
f727fee3fb973a4e34d1c41f7b2d1e4d3582c1bb | 43,980 | py | Python | DCT-Copula-Illustration.py | ibianka/HARK | 8678dbab0a0ace1520ac8f7ff5b33765122619f4 | [
"Apache-2.0"
] | null | null | null | DCT-Copula-Illustration.py | ibianka/HARK | 8678dbab0a0ace1520ac8f7ff5b33765122619f4 | [
"Apache-2.0"
] | null | null | null | DCT-Copula-Illustration.py | ibianka/HARK | 8678dbab0a0ace1520ac8f7ff5b33765122619f4 | [
"Apache-2.0"
] | null | null | null | # ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.2'
# jupytext_version: 1.1.3
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
# # Dimensionality Reduction in [Bayer and Luetticke (2018)](https://cepr.org/active/publications/discussion_papers/dp.php?dpno=13071)
#
# [](https://mybinder.org/v2/gh/econ-ark/HARK/BayerLuetticke?filepath=HARK%2FBayerLuetticke%2FDCT-Copula-Illustration.ipynb)
#
# This companion to the [main notebook](TwoAsset.ipynb) explains in more detail how the authors reduce the dimensionality of their problem
#
# - Based on original slides by Christian Bayer and Ralph Luetticke
# - Original Jupyter notebook by Seungcheol Lee
# - Further edits by Chris Carroll, Tao Wang
#
# %% [markdown]
# ### Preliminaries
#
# In Steady-state Equilibrium (StE) in the model, in any given period, a consumer in state $s$ (which comprises liquid assets $m$, illiquid assets $k$, and human capital $\newcommand{hLev}{h}\hLev$) has two key choices:
# 1. To adjust ('a') or not adjust ('n') their holdings of illiquid assets $k$
# 1. Contingent on that choice, decide the level of consumption, yielding consumption functions:
# * $c_n(s)$ - nonadjusters
# * $c_a(s)$ - adjusters
#
# The usual envelope theorem applies here, so marginal value wrt the liquid asset equals marginal utility with respect to consumption:
# $[\frac{d v}{d m} = \frac{d u}{d c}]$.
# In practice, the authors solve their problem using the marginal value of money $\texttt{Vm} = dv/dm$, but because the marginal utility function is invertible it is trivial to recover $\texttt{c}$ from $(u^{\prime})^{-1}(\texttt{Vm} )$. The consumption function is therefore computed from the $\texttt{Vm}$ function
# %% {"code_folding": [0]}
# Setup stuff
# This is a jupytext paired notebook that autogenerates a corresponding .py file
# which can be executed from a terminal command line via "ipython [name].py"
# But a terminal does not permit inline figures, so we need to test jupyter vs terminal
# Google "how can I check if code is executed in the ipython notebook"
def in_ipynb():
try:
if str(type(get_ipython())) == "<class 'ipykernel.zmqshell.ZMQInteractiveShell'>":
return True
else:
return False
except NameError:
return False
# Determine whether to make the figures inline (for spyder or jupyter)
# vs whatever is the automatic setting that will apply if run from the terminal
if in_ipynb():
# %matplotlib inline generates a syntax error when run from the shell
# so do this instead
get_ipython().run_line_magic('matplotlib', 'inline')
else:
get_ipython().run_line_magic('matplotlib', 'auto')
# The tools for navigating the filesystem
import sys
import os
# Find pathname to this file:
my_file_path = os.path.dirname(os.path.abspath("TwoAsset.ipynb"))
# Relative directory for pickled code
code_dir = os.path.join(my_file_path, "BayerLuetticke_code/TwoAssetCode")
sys.path.insert(0, code_dir)
sys.path.insert(0, my_file_path)
# %% {"code_folding": []}
# Load precalculated Stationary Equilibrium (StE) object EX3SS
import pickle
os.chdir(code_dir) # Go to the directory with pickled code
## EX3SS_20.p is the information in the stationary equilibrium
## (20: the number of illiquid and liquid weath gridpoints)
### The comments above are original, but it seems that there are 30 not 20 points now
EX3SS=pickle.load(open("EX3SS_20.p", "rb"))
# %% [markdown]
# ### Dimensions
#
# The imported StE solution to the problem represents the functions at a set of gridpoints of
# * liquid assets ($n_m$ points), illiquid assets ($n_k$), and human capital ($n_h$)
# * In the code these are $\{\texttt{nm,nk,nh}\}$
#
# So even if the grids are fairly sparse for each state variable, the total number of combinations of the idiosyncratic state gridpoints is large: $n = n_m \times n_k \times n_h$. So, e.g., $\bar{c}$ is a set of size $n$ containing the level of consumption at each possible _combination_ of gridpoints.
#
# In the "real" micro problem, it would almost never happen that a continuous variable like $m$ would end up being exactly equal to one of the prespecified gridpoints. But the functions need to be evaluated at such non-grid points. This is addressed by linear interpolation. That is, if, say, the grid had $m_{8} = 40$ and $m_{9} = 50$ then and a consumer ended up with $m = 45$ then the approximation is that $\tilde{c}(45) = 0.5 \bar{c}_{8} + 0.5 \bar{c}_{9}$.
#
# %% {"code_folding": []}
# Show dimensions of the consumer's problem (state space)
print('c_n is of dimension: ' + str(EX3SS['mutil_c_n'].shape))
print('c_a is of dimension: ' + str(EX3SS['mutil_c_a'].shape))
print('Vk is of dimension:' + str(EX3SS['Vk'].shape))
print('Vm is of dimension:' + str(EX3SS['Vm'].shape))
print('For convenience, these are all constructed from the same exogenous grids:')
print(str(len(EX3SS['grid']['m']))+' gridpoints for liquid assets;')
print(str(len(EX3SS['grid']['k']))+' gridpoints for illiquid assets;')
print(str(len(EX3SS['grid']['h']))+' gridpoints for individual productivity.')
print('')
print('Therefore, the joint distribution is of size: ')
print(str(EX3SS['mpar']['nm'])+
' * '+str(EX3SS['mpar']['nk'])+
' * '+str(EX3SS['mpar']['nh'])+
' = '+ str(EX3SS['mpar']['nm']*EX3SS['mpar']['nk']*EX3SS['mpar']['nh']))
# %% [markdown]
# ### Dimension Reduction
#
# The authors use different dimensionality reduction methods for the consumer's problem and the distribution across idiosyncratic states
# %% [markdown]
# #### Representing the consumer's problem with Basis Functions
#
# The idea is to find an efficient "compressed" representation of our functions (e.g., the consumption function), which BL do using tools originally developed for image compression. The analogy to image compression is that nearby pixels are likely to have identical or very similar colors, so we need only to find an efficient way to represent how the colors _change_ from one pixel to nearby ones. Similarly, consumption at a given point $s_{i}$ is likely to be close to consumption point at another point $s_{j}$ that is "close" in the state space (similar wealth, income, etc), so a function that captures that similarity efficiently can preserve most of the information without keeping all of the points.
#
# Like linear interpolation, the [DCT transformation](https://en.wikipedia.org/wiki/Discrete_cosine_transform) is a method of representing a continuous function using a finite set of numbers. It uses a set of independent [basis functions](https://en.wikipedia.org/wiki/Basis_function) to do this.
#
# But it turns out that some of those basis functions are much more important than others in representing the steady-state functions. Dimension reduction is accomplished by basically ignoring all basis functions that make "small enough" contributions to the representation of the function.
#
# ##### When might this go wrong?
#
# Suppose the consumption function changes in a recession in ways that change behavior radically at some states. Like, suppose unemployment almost never happens in steady state, but it can happen in temporary recessions. Suppose further that, even for employed people, in a recession, _worries_ about unemployment cause many of them to prudently withdraw some of their illiquid assets -- behavior opposite of what people in the same state would be doing during expansions. In that case, the basis functions that represented the steady state function would have had no incentive to be able to represent well the part of the space that is never seen in steady state, so any functions that might help do so might well have been dropped in the dimension reduction stage.
#
# On the whole, it seems unlikely that this kind of thing is a major problem, because the vast majority of the variation that people experience is idiosyncratic. There is always unemployment, for example; it just moves up and down a bit with aggregate shocks, but since the experience of unemployment is in fact well represented in the steady state the method should have no trouble capturing it.
#
# Where the method might have more trouble is in representing economies in which there are multiple equilibria in which behavior is quite different.
# %% [markdown]
# #### For the distribution of agents across states: Copula
#
# The other tool the authors use is the ["copula"](https://en.wikipedia.org/wiki/Copula_(probability_theory)), which allows us to represent the distribution of people across idiosyncratic states efficiently
#
# The copula is computed from the joint distribution of states in StE and will be used to transform the [marginal distributions](https://en.wikipedia.org/wiki/Marginal_distribution) back to joint distributions. (For an illustration of how the assumptions used when modeling asset price distributions using copulas can fail see [Salmon](https://www.wired.com/2009/02/wp-quant/))
#
# * A copula is a representation of the joint distribution expressed using a mapping between the uniform joint CDF and the marginal distributions of the variables
#
# * The crucial assumption is that what aggregate shocks do is to squeeze or distort the steady state distribution, but leave the rank structure of the distribution the same
# * An example of when this might not hold is the following. Suppose that in expansions, the people at the top of the distribution of illiquid assets (the top 1 percent, say) are also at the top 1 percent of liquid assets. But in recessions the bottom 99 percent get angry at the top 1 percent of illiquid asset holders and confiscate part of their liquid assets (the illiquid assets can't be confiscated quickly because they are illiquid). Now the people in the top 99 percent of illiquid assets might be in the _bottom_ 1 percent of liquid assets.
#
# - In this case we just need to represent how the mapping from ranks into levels of assets
#
# - This reduces the number of points for which we need to track transitions from $3600 = 30 \times 30 \times 4$ to $64 = 30+30+4$. Or the total number of points we need to contemplate goes from $3600^2 \approx 13 $million to $64^2=4096$.
# %% {"code_folding": []}
# Get some specs about the copula, which is precomputed in the EX3SS object
print('The copula consists of two parts: gridpoints and values at those gridpoints:'+ \
'\n gridpoints have dimensionality of '+str(EX3SS['Copula']['grid'].shape) + \
'\n where the first element is total number of gridpoints' + \
'\n and the second element is number of idiosyncratic state variables' + \
'\n whose values also are of dimension of '+str(EX3SS['Copula']['value'].shape[0]) + \
'\n each entry of which is the probability that all three of the'
'\n state variables are below the corresponding point.')
# %% {"code_folding": []}
## Import necessary libraries
from __future__ import print_function
import sys
sys.path.insert(0,'../')
import numpy as np
from numpy.linalg import matrix_rank
import scipy as sc
from scipy.stats import norm
from scipy.interpolate import interp1d, interp2d, griddata, RegularGridInterpolator, interpn
import multiprocessing as mp
from multiprocessing import Pool, cpu_count, Process
from math import ceil
import math as mt
from scipy import sparse as sp # used to work with sparse matrices
from scipy import linalg #linear algebra
from math import log, cos, pi, sqrt
import time
from SharedFunc3 import Transition, ExTransitions, GenWeight, MakeGridkm, Tauchen, Fastroot
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import scipy.io #scipy input and output
import scipy.fftpack as sf # scipy discrete fourier transforms
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from matplotlib import cm
import seaborn as sns
import copy as cp
# %% {"code_folding": []}
## State reduction and discrete cosine transformation
class StateReduc_Dct:
def __init__(self, par, mpar, grid, Output, targets, Vm, Vk,
joint_distr, Copula, c_n_guess, c_a_guess, psi_guess,
m_n_star, m_a_star, cap_a_star, mutil_c_n, mutil_c_a,mutil_c, P_H):
self.par = par # Parameters of the theoretical model
self.mpar = mpar # Parameters of the numerical representation
self.grid = grid # Discrete grid
self.Output = Output # Results of the calculations
self.targets = targets # Like, debt-to-GDP ratio or other desiderata
self.Vm = Vm # Marginal value from liquid cash-on-hand
self.Vk = Vk # Marginal value of capital
self.joint_distr = joint_distr # Multidimensional histogram
self.Copula = Copula # Encodes rank marginal correlation of joint distribution
self.mutil_c = mutil_c # Marginal utility of consumption
self.P_H = P_H # Transition matrix for macro states (not including distribution)
def StateReduc(self):
"""
input
-----
self: dict, stored results from a StE
output
------
Newly generated
===============
X_ss: ndarray, stacked states, including
Y_ss: ndarray, controls
Gamma_state: ndarray, marginal distributions of individual states
grid: ndarray, discrete grids
targets: ndarray, debt-to-GDP ratio or other desiderata
P_H: transition probability of
indexMUdct: ndarray, indices selected after dct operation on marginal utility of consumption
indexVKdct: ndarray, indices selected after dct operation on marginal value of capital
State: ndarray, dimension equal to reduced states
State_m: ndarray, dimension equal to reduced states
Contr: ndarray, dimension equal to reduced controls
Contr_m: ndarray, dimension equal to reduced controls
Passed down from the input
==========================
Copula: dict, grids and values
joint_distr: ndarray, nk x nm x nh
Output: dict, outputs from the model
par: dict, parameters of the theoretical model
mpar:dict, parameters of the numerical representation
aggrshock: string, type of aggregate shock used to purturb the StE
"""
# Inverse of CRRA on x for utility and marginal utility
invutil = lambda x : ((1-self.par['xi'])*x)**(1./(1-self.par['xi']))
invmutil = lambda x : (1./x)**(1./self.par['xi'])
# X=States
# Marg dist of liquid assets summing over pty and illiquid assets k
Xss=np.asmatrix(np.concatenate((np.sum(np.sum(self.joint_distr.copy(),axis=1),axis =1),
np.transpose(np.sum(np.sum(self.joint_distr.copy(),axis=0),axis=1)),# marg dist k
np.sum(np.sum(self.joint_distr.copy(),axis=1),axis=0), # marg dist pty (\approx income)
[np.log(self.par['RB'])],[ 0.]))).T # Given the constant interest rate
# Y="controls" (according to this literature's odd terminology)
# c = invmarg(marg(c)), so first bit gets consumption policy function
Yss=np.asmatrix(np.concatenate((invmutil(self.mutil_c.copy().flatten(order = 'F')),\
invmutil(self.Vk.copy().flatten(order = 'F')),
[np.log(self.par['Q'])], # Question: Price of the illiquid asset, right?
[ np.log(self.par['PI'])], # Inflation
[ np.log(self.Output)],
[np.log(self.par['G'])], # Gov spending
[np.log(self.par['W'])], # Wage
[np.log(self.par['R'])], # Nominal R
[np.log(self.par['PROFITS'])],
[np.log(self.par['N'])], # Hours worked
[np.log(self.targets['T'])], # Taxes
[np.log(self.grid['K'])], # Kapital
[np.log(self.targets['B'])]))).T # Government debt
# Mapping for Histogram
# Gamma_state matrix reduced set of states
# nm = number of gridpoints for liquid assets
# nk = number of gridpoints for illiquid assets
# nh = number of gridpoints for human capital (pty)
Gamma_state = np.zeros( # Create zero matrix of size [nm + nk + nh,nm + nk + nh - 4]
(self.mpar['nm']+self.mpar['nk']+self.mpar['nh'],
self.mpar['nm']+self.mpar['nk']+self.mpar['nh'] - 4))
# Question: Why 4? 4 = 3+1, 3: sum to 1 for m, k, h and 1: for entrepreneurs
# Impose adding-up conditions:
# In each of the block matrices, probabilities must add to 1
for j in range(self.mpar['nm']-1): # np.squeeze reduces one-dimensional matrix to vector
Gamma_state[0:self.mpar['nm'],j] = -np.squeeze(Xss[0:self.mpar['nm']])
Gamma_state[j,j]=1. - Xss[j] #
Gamma_state[j,j]=Gamma_state[j,j] - np.sum(Gamma_state[0:self.mpar['nm'],j])
bb = self.mpar['nm'] # Question: bb='bottom base'? because bb shorter to type than self.mpar['nm'] everywhere
for j in range(self.mpar['nk']-1):
Gamma_state[bb+np.arange(0,self.mpar['nk'],1), bb+j-1] = -np.squeeze(Xss[bb+np.arange(0,self.mpar['nk'],1)])
Gamma_state[bb+j,bb-1+j] = 1. - Xss[bb+j]
Gamma_state[bb+j,bb-1+j] = (Gamma_state[bb+j,bb-1+j] -
np.sum(Gamma_state[bb+np.arange(0,self.mpar['nk']),bb-1+j]))
bb = self.mpar['nm'] + self.mpar['nk']
for j in range(self.mpar['nh']-2):
# Question: Why -2? 1 for h sum to 1 and 1 for entrepreneur Some other symmetry/adding-up condition.
Gamma_state[bb+np.arange(0,self.mpar['nh']-1,1), bb+j-2] = -np.squeeze(Xss[bb+np.arange(0,self.mpar['nh']-1,1)])
Gamma_state[bb+j,bb-2+j] = 1. - Xss[bb+j]
Gamma_state[bb+j,bb-2+j] = Gamma_state[bb+j,bb-2+j] - np.sum(Gamma_state[bb+np.arange(0,self.mpar['nh']-1,1),bb-2+j])
# Number of other state variables not including the gridded -- here, just the interest rate
self.mpar['os'] = len(Xss) - (self.mpar['nm']+self.mpar['nk']+self.mpar['nh'])
# For each gridpoint there are two "regular" controls: consumption and illiquid saving
# Counts the number of "other" controls (PROFITS, Q, etc)
self.mpar['oc'] = len(Yss) - 2*(self.mpar['nm']*self.mpar['nk']*self.mpar['nh'])
aggrshock = self.par['aggrshock']
accuracy = self.par['accuracy']
# Do the dct on the steady state marginal utility
# Returns an array of indices for the used basis vectors
indexMUdct = self.do_dct(invmutil(self.mutil_c.copy().flatten(order='F')),
self.mpar,accuracy)
# Do the dct on the steady state marginal value of capital
# Returns an array of indices for the used basis vectors
indexVKdct = self.do_dct(invmutil(self.Vk.copy()),self.mpar,accuracy)
# Calculate the numbers of states and controls
aux = np.shape(Gamma_state)
self.mpar['numstates'] = np.int64(aux[1] + self.mpar['os'])
self.mpar['numcontrols'] = np.int64(len(indexMUdct) +
len(indexVKdct) +
self.mpar['oc'])
# Size of the reduced matrices to be used in the Fsys
# Set to zero because in steady state they are zero
State = np.zeros((self.mpar['numstates'],1))
State_m = State
Contr = np.zeros((self.mpar['numcontrols'],1))
Contr_m = Contr
return {'Xss': Xss, 'Yss':Yss, 'Gamma_state': Gamma_state,
'par':self.par, 'mpar':self.mpar, 'aggrshock':aggrshock,
'Copula':self.Copula,'grid':self.grid,'targets':self.targets,'P_H':self.P_H,
'joint_distr': self.joint_distr, 'Output': self.Output, 'indexMUdct':indexMUdct, 'indexVKdct':indexVKdct,
'State':State, 'State_m':State_m, 'Contr':Contr, 'Contr_m':Contr_m}
# Discrete cosine transformation magic happens here
# sf is scipy.fftpack tool
def do_dct(self, obj, mpar, level):
"""
input
-----
obj: ndarray nm x nk x nh
dimension of states before dct
mpar: dict
parameters in the numerical representaion of the model, e.g. nm, nk and nh
level: float
accuracy level for dct
output
------
index_reduced: ndarray n_dct x 1
an array of indices that select the needed grids after dct
"""
obj = np.reshape(obj.copy(),(mpar['nm'],mpar['nk'],mpar['nh']),order='F')
X1 = sf.dct(obj,norm='ortho',axis=0) # dct is operated along three dimensions axis=0/1/2
X2 = sf.dct(X1.copy(),norm='ortho',axis=1)
X3 = sf.dct(X2.copy(),norm='ortho',axis=2)
# Pick the coefficients that are big
XX = X3.flatten(order='F')
ind = np.argsort(abs(XX.copy()))[::-1]
# i will
i = 1
# Sort from smallest (=best) to biggest (=worst)
# and count how many are 'good enough to keep'
while linalg.norm(XX[ind[:i]].copy())/linalg.norm(XX) < level:
i += 1
needed = i # Question:Isn't this counting the ones that are NOT needed?
index_reduced = np.sort(ind[:i]) # Retrieve the good
return index_reduced
# %% {"code_folding": []}
## Choose an aggregate shock to perturb(one of three shocks: MP, TFP, Uncertainty)
EX3SS['par']['aggrshock'] = 'MP'
EX3SS['par']['rhoS'] = 0.0 # Persistence of variance
EX3SS['par']['sigmaS'] = 0.001 # STD of variance shocks
#EX3SS['par']['aggrshock'] = 'TFP'
#EX3SS['par']['rhoS'] = 0.95
#EX3SS['par']['sigmaS'] = 0.0075
#EX3SS['par']['aggrshock'] = 'Uncertainty'
#EX3SS['par']['rhoS'] = 0.84 # Persistence of variance
#EX3SS['par']['sigmaS'] = 0.54 # STD of variance shocks
# %% {"code_folding": []}
## Choose an accuracy of approximation with DCT
### Determines number of basis functions chosen -- enough to match this accuracy
### EX3SS is precomputed steady-state pulled in above
EX3SS['par']['accuracy'] = 0.99999
# %% {"code_folding": []}
## Implement state reduction and DCT
### Do state reduction on steady state
EX3SR=StateReduc_Dct(**EX3SS) # Takes StE result as input and get ready to invoke state reduction operation
SR=EX3SR.StateReduc() # StateReduc is operated
# %% {"code_folding": [0]}
# Measuring the effectiveness of the state reduction
print('What are the results from the state reduction?')
#print('Newly added attributes after the operation include \n'+str(set(SR.keys())-set(EX3SS.keys())))
print('\n')
print('To achieve an accuracy of '+str(EX3SS['par']['accuracy'])+'\n')
print('The dimension of the policy functions is reduced to '+str(SR['indexMUdct'].shape[0]) \
+' from '+str(EX3SS['mpar']['nm']*EX3SS['mpar']['nk']*EX3SS['mpar']['nh'])
)
print('The dimension of the marginal value functions is reduced to '+str(SR['indexVKdct'].shape[0]) \
+ ' from ' + str(EX3SS['Vk'].shape))
print('The total number of control variables is '+str(SR['Contr'].shape[0])+'='+str(SR['indexMUdct'].shape[0]) + \
'+'+str(SR['indexVKdct'].shape[0])+'+ # of other macro controls')
print('\n')
print('The copula represents the joint distribution with a vector of size '+str(SR['Gamma_state'].shape) )
print('The dimension of states including exogenous state, is ' +str(SR['Xss'].shape[0]))
print('It simply stacks all grids of different\
\n state variables regardless of their joint distributions.\
\n This is due to the assumption that the rank order remains the same.')
print('The total number of state variables is '+str(SR['State'].shape[0]) + '='+\
str(SR['Gamma_state'].shape[1])+'+ the number of macro states (like the interest rate)')
# %% [markdown]
# ### Graphical Illustration
#
# #### Policy/value functions
#
# Taking the consumption function as an example, we plot consumption by adjusters and non-adjusters over a range of $k$ and $m$ that encompasses x percent of the mass of the distribution function.
#
# We plot the functions for the top and bottom values of the wage $h$ distribution
#
# %% {"code_folding": []}
## Graphical illustration
xi = EX3SS['par']['xi']
invmutil = lambda x : (1./x)**(1./xi)
### convert marginal utilities back to consumption function
mut_StE = EX3SS['mutil_c']
mut_n_StE = EX3SS['mutil_c_n'] # marginal utility of non-adjusters
mut_a_StE = EX3SS['mutil_c_a'] # marginal utility of adjusters
c_StE = invmutil(mut_StE)
cn_StE = invmutil(mut_n_StE)
ca_StE = invmutil(mut_a_StE)
### grid values
dim_StE = mut_StE.shape
mgrid = EX3SS['grid']['m']
kgrid = EX3SS['grid']['k']
hgrid = EX3SS['grid']['h']
# %% {"code_folding": []}
## define some functions to be used next
def dct3d(x):
x0=sf.dct(x.copy(),axis=0,norm='ortho')
x1=sf.dct(x0.copy(),axis=1,norm='ortho')
x2=sf.dct(x1.copy(),axis=2,norm='ortho')
return x2
def idct3d(x):
x2 = sf.idct(x.copy(),axis=2,norm='ortho')
x1 = sf.idct(x2.copy(),axis=1,norm='ortho')
x0 = sf.idct(x1.copy(),axis=0,norm='ortho')
return x0
def DCTApprox(fullgrids,dct_index):
dim=fullgrids.shape
dctcoefs = dct3d(fullgrids)
dctcoefs_rdc = np.zeros(dim)
dctcoefs_rdc[dct_index]=dctcoefs[dct_index]
approxgrids = idct3d(dctcoefs_rdc)
return approxgrids
# %% [markdown]
# Depending on the accuracy level, the DCT operation choses the necessary number of basis functions used to approximate consumption function at the full grids. This is illustrated in the p31-p34 in this [slides](https://www.dropbox.com/s/46fdxh0aphazm71/presentation_method.pdf?dl=0). We show this for both 1-dimensional (m or k) or 2-dimenstional grids (m and k) in the following.
# %% {"code_folding": []}
## 2D graph of consumption function: c(m) fixing k and h
## list of accuracy levels
Accuracy_BL = 0.99999 # From BL
Accuracy_Less0 = 0.999
Accuracy_Less1 = 0.99
Accuracy_Less2 = 0.95
acc_lst = np.array([Accuracy_BL,Accuracy_Less0,Accuracy_Less1,Accuracy_Less2])
## c(m) fixing k and h
fig = plt.figure(figsize=(8,8))
fig.suptitle('c at full grids and c approximated by DCT in different accuracy levels'
'\n non-adjusters, fixing k and h',
fontsize=(13))
fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.3)
for idx in range(len(acc_lst)):
EX3SS_cp =cp.deepcopy(EX3SS)
EX3SS_cp['par']['accuracy'] = acc_lst[idx]
EX3SR_cp=StateReduc_Dct(**EX3SS_cp) # Takes StE result as input and get ready to invoke state reduction operation
SR_cp=EX3SR_cp.StateReduc()
mut_rdc_idx_flt_cp = SR_cp['indexMUdct']
mut_rdc_idx_cp = np.unravel_index(mut_rdc_idx_flt_cp,dim_StE,order='F')
nb_bf_cp = len(mut_rdc_idx_cp[0])
print(str(nb_bf_cp) +" basis functions used.")
c_n_approx_cp = DCTApprox(cn_StE,mut_rdc_idx_cp)
c_a_approx_cp = DCTApprox(ca_StE,mut_rdc_idx_cp)
cn_diff_cp = c_n_approx_cp-cn_StE
# choose the fix grid of h and k
hgrid_fix=2 # fix level of h as an example
kgrid_fix=10 # fix level of k as an example
# get the corresponding c function approximated by dct
cVec = c_a_approx_cp[:,kgrid_fix,hgrid_fix]
## plots
ax = fig.add_subplot(2,2,idx+1)
ax.plot(mgrid,cVec,label='c approximated by DCT')
ax.plot(mgrid,ca_StE[:,kgrid_fix,hgrid_fix],'--',label='c at full grids')
ax.plot(mgrid,cVec,'r*')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel(r'$c(m)$',fontsize=13)
ax.set_title(r'accuracy=${}$'.format(acc_lst[idx]))
ax.legend(loc=0)
# %% {"code_folding": []}
## 2D graph of consumption function: c(k) fixing m and h
fig = plt.figure(figsize=(8,8))
fig.suptitle('c at full grids and c approximated by DCT in different accuracy levels'
'\n non-adjusters, fixing m and h',
fontsize=(13))
fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.3)
for idx in range(len(acc_lst)):
EX3SS_cp =cp.deepcopy(EX3SS)
EX3SS_cp['par']['accuracy'] = acc_lst[idx]
EX3SR_cp=StateReduc_Dct(**EX3SS_cp) # Takes StE result as input and get ready to invoke state reduction operation
SR_cp=EX3SR_cp.StateReduc()
mut_rdc_idx_flt_cp= SR_cp['indexMUdct']
mut_rdc_idx_cp = np.unravel_index(mut_rdc_idx_flt_cp,dim_StE,order='F')
nb_bf_cp = len(mut_rdc_idx_cp[0])
print(str(nb_bf_cp) +" basis functions used.")
c_n_approx_cp = DCTApprox(cn_StE,mut_rdc_idx_cp)
c_a_approx_cp = DCTApprox(ca_StE,mut_rdc_idx_cp)
cn_diff_cp = c_n_approx_cp-cn_StE
# choose the fix grid of h and m
hgrid_fix=2 # fix level of h as an example
mgrid_fix=10 # fix level of k as an example
# get the corresponding c function approximated by dct
cVec = c_n_approx_cp[mgrid_fix,:,hgrid_fix]
## plots
ax = fig.add_subplot(2,2,idx+1)
ax.plot(kgrid,cVec,label='c approximated by DCT')
ax.plot(kgrid,cn_StE[mgrid_fix,:,hgrid_fix],'--',label='c at full grids')
ax.plot(kgrid,cVec,'r*')
ax.set_xlabel('k',fontsize=13)
ax.set_ylabel(r'$c(k)$',fontsize=13)
ax.set_title(r'accuracy=${}$'.format(acc_lst[idx]))
ax.legend(loc=0)
# %% {"code_folding": []}
# Restore the solution corresponding to the original BL accuracy
EX3SS['par']['accuracy'] = Accuracy_BL
EX3SR=StateReduc_Dct(**EX3SS) # Takes StE result as input and get ready to invoke state reduction operation
SR=EX3SR.StateReduc() # StateReduc is operated
## indexMUdct is one dimension, needs to be unraveled to 3 dimensions
mut_rdc_idx_flt = SR['indexMUdct']
mut_rdc_idx = np.unravel_index(mut_rdc_idx_flt,dim_StE,order='F')
nb_dct = len(mut_StE.flatten())
mut_rdc_bool = np.zeros(nb_dct) # boolean array of 30 x 30 x 4
for i in range(nb_dct):
mut_rdc_bool[i]=i in list(SR['indexMUdct'])
mut_rdc_bool_3d = (mut_rdc_bool==1).reshape(dim_StE)
mut_rdc_mask_3d = (mut_rdc_bool).reshape(dim_StE)
# Get the joint distribution calculated elsewhere
joint_distr = EX3SS['joint_distr']
marginal_mk = EX3SS['joint_distr'].sum(axis=2)
# Location at which to cut off the topmost part of the distributions
mass_pct = 0.9
## Again, for BL accuracy level, get dct compressed c functions at all grids
c_n_approx = DCTApprox(cn_StE,mut_rdc_idx)
c_a_approx = DCTApprox(ca_StE,mut_rdc_idx)
# %% {"code_folding": []}
# 3D surface plots of consumption function at full grids and approximated by DCT
## at all grids and grids after dct first for non-adjusters and then for adjusters
## for non-adjusters
## full grids now
## WangTao:
## After plotting for the entire set of gridpoints, next plot only for the bottom mass_pct of the distributions
mmgrid,kkgrid = np.meshgrid(mgrid,kgrid)
fig = plt.figure(figsize=(14,14))
fig.suptitle('Consumption of non-adjusters at grid points of m and k (for each h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
## prepare the reduced grids
hgrid_fix=hgrid_id
## plots
ax = fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.scatter(mmgrid,kkgrid,c_n_approx[:,:,hgrid_fix],marker='v',color='red',
label='StE(after dct):non-adjuster')
ax.plot_surface(mmgrid,kkgrid,cn_StE[:,:,hgrid_fix],cmap='Blues',
label='StE(before dct): non-adjuster')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_n(m,k)$',fontsize=13)
plt.gca().invert_yaxis()
#ax.set_xlim([0,mmax])
#ax.set_ylim([0,kmax])
ax.set_title(r'$h({})$'.format(hgrid_fix))
ax.view_init(20, 100)
# %% {"code_folding": []}
## Same thing in a different way: image plots of c functions at full grids and c approximated by DCT
## for non-adjusters
## full grids
mmgrid,kkgrid = np.meshgrid(mgrid,kgrid)
### for adjusters
fig = plt.figure(figsize=(14,14))
fig.suptitle('Consumption of non-adjusters at grid points of m and k(for different h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
## prepare the reduced grids
hgrid_fix=hgrid_id
## plots
ax = fig.add_subplot(2,2,hgrid_id+1)
ax.imshow(np.hstack((cn_StE[:,:,hgrid_fix],c_n_approx[:,:,hgrid_fix])))
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_title(r'$h({})$'.format(hgrid_fix))
# %% {"code_folding": []}
## 3D scatter plots of the difference of full-grid c and approximated c
## for non-adjusters
## full grids
mmgrid,kkgrid = np.meshgrid(mgrid,kgrid)
### for adjusters
fig = plt.figure(figsize=(14,14))
fig.suptitle('Consumption of non-adjusters at grid points of m and k (for each h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
## prepare the reduced grids
hgrid_fix=hgrid_id
cn_diff = c_n_approx-cn_StE
## plots
ax = fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,cn_diff[:,:,hgrid_fix], rstride=1,
cstride=1,cmap=cm.coolwarm, edgecolor='none',
label='Difference of full-grid and approximated consumption function')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_a(m,k)$',fontsize=13)
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
#ax.set_xlim([0,mmax])
#ax.set_ylim([0,kmax])
ax.set_title(r'$h({})$'.format(hgrid_fix))
ax.view_init(20, 40)
# %% {"code_folding": []}
# Difference of full-grid c and DCT compressed c for difference levels of accuracy
fig = plt.figure(figsize=(14,14))
fig.suptitle('Differences of c at full grids and c approximated by DCT in different accuracy levels(non-adjusters)',
fontsize=(13))
for idx in range(len(acc_lst)):
EX3SS_cp =cp.deepcopy(EX3SS)
EX3SS_cp['par']['accuracy'] = acc_lst[idx]
EX3SR_cp=StateReduc_Dct(**EX3SS_cp) # Takes StE result as input and get ready to invoke state reduction operation
SR_cp=EX3SR_cp.StateReduc()
mut_rdc_idx_flt_cp = SR_cp['indexMUdct']
mut_rdc_idx_cp = np.unravel_index(mut_rdc_idx_flt_cp,dim_StE,order='F')
nb_bf_cp = len(mut_rdc_idx_cp[0])
print(str(nb_bf_cp) +" basis functions used.")
c_n_approx_cp = DCTApprox(cn_StE,mut_rdc_idx_cp)
c_a_approx_cp = DCTApprox(ca_StE,mut_rdc_idx_cp)
cn_diff_cp = c_n_approx_cp-cn_StE
hgrid_fix=1 # fix level of h as an example
## plots
ax = fig.add_subplot(2,2,idx+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,cn_diff_cp[:,:,hgrid_fix], rstride=1,
cstride=1,cmap=cm.summer, edgecolor='none',
label='Difference of full-grid and approximated consumption functions')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel('Difference of c functions',fontsize=13)
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
#ax.set_xlim([0,mmax])
#ax.set_ylim([0,kmax])
ax.set_zlim([-8,2])
ax.set_title(r'accuracy=${}$'.format(acc_lst[idx]))
ax.view_init(10, 60)
# %% {"code_folding": []}
# for adjusters
fig = plt.figure(figsize=(14,14))
fig.suptitle('Consumption of adjusters at grid points of m and k(for different h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
## prepare the reduced grids
hgrid_fix=hgrid_id
## plots
ax = fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.scatter(mmgrid,kkgrid,c_a_approx[:,:,hgrid_fix],marker='v',color='red',
label='StE(after dct):adjuster')
ax.plot_surface(mmgrid,kkgrid,ca_StE[:,:,hgrid_fix],cmap='Blues',
label='StE(before dct): adjuster')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_a(m,k)$',fontsize=13)
plt.gca().invert_yaxis()
#ax.set_xlim([0,mmax])
#ax.set_ylim([0,kmax])
ax.set_title(r'$h({})$'.format(hgrid_fix))
ax.view_init(20, 150)
# %% {"code_folding": []}
# Compare consumption functions of adjusters and non-adjusters approximated by DCT
fig = plt.figure(figsize=(14,14))
fig.suptitle('Consumption of adjusters (yellow)/non-adjusters (blue) at grid points of m and k (for each h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
## prepare the reduced grids
hgrid_fix=hgrid_id
## plots
ax = fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,c_n_approx[:,:,hgrid_fix],cmap=cm.winter,
label='StE(after dct):non-adjuster')
ax.plot_surface(mmgrid,kkgrid,c_a_approx[:,:,hgrid_fix],cmap=cm.autumn,
label='StE(after dct):adjuster')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_a(m,k)$',fontsize=13)
ax.set_title(r'$h({})$'.format(hgrid_fix))
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
#ax.set_xlim(0,mmax)
#ax.set_ylim(0,kmax)
ax.view_init(20, 60)
# %% {"code_folding": []}
## the differences of c functions of adjusters and non-adjusters approximated by DCT.
c_diff_approx=c_n_approx-c_a_approx
fig = plt.figure(figsize=(14,14))
fig.suptitle('Consumption of adjusters/non-adjusters at grid points of m and k(for different h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
## prepare the reduced grids
hgrid_fix=hgrid_id
## plots
ax = fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,c_diff_approx[:,:,hgrid_fix],cmap=cm.coolwarm,
label='StE(after dct):difference of non-adjuster and adjusters')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_n(m,k)-c_a(m,k)$',fontsize=12)
ax.set_title(r'$h({})$'.format(hgrid_fix))
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
#ax.set_xlim(0,mmax)
#ax.set_ylim(0,kmax)
ax.view_init(20, 80)
# %% [markdown]
# ##### Observation
#
# - For a given grid value of productivity, the remaining grid points after DCT to represent the whole consumption function are concentrated in low values of $k$ and $m$. This is because the slopes of the surfaces of marginal utility are changing the most in these regions. For larger values of $k$ and $m$ the functions become smooth and only slightly concave, so they can be represented by many fewer points
# - For different grid values of productivity (2 sub plots), the numbers of grid points in the DCT operation differ. From the lowest to highest values of productivity, there are 78, 33, 25 and 18 grid points, respectively. They add up to the total number of gridpoints of 154 after DCT operation, as we noted above for marginal utility function.
# %% [markdown]
# #### Distribution of states
#
# - We first plot the distribution of $k$ fixing $m$ and $h$. Next, we plot the joint distribution of $m$ and $k$ only fixing $h$ in 3-dimenstional space.
# - The joint-distribution can be represented by marginal distributions of $m$, $k$ and $h$ and a copula that describes the correlation between the three states. The former is straightfoward. We plot the copula only. The copula is essentially a multivariate cummulative distribution function where each marginal is uniform. (Translation from the uniform to the appropriate nonuniform distribution is handled at a separate stage).
#
# %% {"code_folding": []}
### Marginalize along h grids
joint_distr = EX3SS['joint_distr']
joint_distr_km = EX3SS['joint_distr'].sum(axis=2)
### Plot distributions in 2 dimensional graph
fig = plt.figure(figsize=(10,10))
plt.suptitle('Marginal distribution of k at different m')
for hgrid_id in range(EX3SS['mpar']['nh']):
ax = plt.subplot(2,2,hgrid_id+1)
ax.set_title(r'$h({})$'.format(hgrid_id))
ax.set_xlabel('k',size=12)
for id in range(EX3SS['mpar']['nm']):
ax.plot(kgrid,joint_distr[id,:,hgrid_id])
# %% {"code_folding": []}
## Plot joint distribution of k and m in 3d graph
fig = plt.figure(figsize=(14,14))
fig.suptitle('Joint distribution of m and k(for different h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
## plots
ax = fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,joint_distr[:,:,hgrid_fix], rstride=1, cstride=1,
cmap='viridis', edgecolor='none')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
plt.gca().invert_yaxis()
#ax.set_zlabel(r'$p(m,k)$',fontsize=10)
ax.set_title(r'$h({})$'.format(hgrid_id))
ax.set_xlim(0,400)
ax.view_init(20, 40)
# %% [markdown]
# Notice the CDFs in StE copula have 4 modes, corresponding to the number of $h$ gridpoints. Each of the four parts of the cdf is a joint-distribution of $m$ and $k$. It can be presented in 3-dimensional graph as below.
# %% {"code_folding": []}
## Plot the copula
cdf=EX3SS['Copula']['value'].reshape(4,30,30) # important: 4,30,30 not 30,30,4?
fig = plt.figure(figsize=(14,14))
fig.suptitle('Copula of m and k(for different h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
## plots
ax = fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,cdf[hgrid_id,:,:], rstride=1, cstride=1,
cmap='viridis', edgecolor='None')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_title(r'$h({})$'.format(hgrid_id))
## for each h grid, take the 95% mass of m and k as the maximum of the m and k axis
marginal_mk = joint_distr[:,:,hgrid_id]
marginal_m = marginal_mk.sum(axis=0)
marginal_k = marginal_mk.sum(axis=1)
mmax = mgrid[(np.abs(marginal_m.cumsum()-mass_pct*marginal_m.cumsum().max())).argmin()]
kmax = kgrid[(np.abs(marginal_k.cumsum()-mass_pct*marginal_k.cumsum().max())).argmin()]
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
#ax.set_xlim(0,mmax)
#ax.set_ylim(0,kmax)
ax.view_init(30, 60)
# %% [markdown]
# # To Do:
#
# 1. Plot the _difference_ in the _approximation errors_ for adjusters and nonadjusters
# 1. Make color or transparency be determined by the population density from the copula
# 1. Make extra versions of the figures where the color is determined by the population density at that location (given by the copula)
# 1. Differences _between_ adjusters and nonadjusters in consumption are not interesting and should be deleted
# 1. Eliminate "magic numbers"
# 1. Improve comments so a new reader can understand what is being done
# %% [markdown]
# Given the assumption that the copula remains the same after aggregate risk is introduced, we can use the same copula and the marginal distributions to recover the full joint-distribution of the states.
# %% [markdown]
# ### Summary: what do we achieve after the transformation?
#
# - Using the DCT, the dimension of the policy and value functions are reduced from 3600 to 154 and 94, respectively.
# - By marginalizing the joint distribution with the fixed copula assumption, the marginal distribution is of dimension 64 compared to its joint distribution of a dimension of 3600.
#
#
#
| 46.392405 | 769 | 0.670646 |
lse:
return False
except NameError:
return False
if in_ipynb():
get_ipython().run_line_magic('matplotlib', 'inline')
else:
get_ipython().run_line_magic('matplotlib', 'auto')
import sys
import os
my_file_path = os.path.dirname(os.path.abspath("TwoAsset.ipynb"))
code_dir = os.path.join(my_file_path, "BayerLuetticke_code/TwoAssetCode")
sys.path.insert(0, code_dir)
sys.path.insert(0, my_file_path)
import pickle
os.chdir(code_dir)
ese are all constructed from the same exogenous grids:')
print(str(len(EX3SS['grid']['m']))+' gridpoints for liquid assets;')
print(str(len(EX3SS['grid']['k']))+' gridpoints for illiquid assets;')
print(str(len(EX3SS['grid']['h']))+' gridpoints for individual productivity.')
print('')
print('Therefore, the joint distribution is of size: ')
print(str(EX3SS['mpar']['nm'])+
' * '+str(EX3SS['mpar']['nk'])+
' * '+str(EX3SS['mpar']['nh'])+
' = '+ str(EX3SS['mpar']['nm']*EX3SS['mpar']['nk']*EX3SS['mpar']['nh']))
# %% [markdown]
# ### Dimension Reduction
#
# The authors use different dimensionality reduction methods for the consumer's problem and the distribution across idiosyncratic states
ls are likely to have identical or very similar colors, so we need only to find an efficient way to represent how the colors _change_ from one pixel to nearby ones. Similarly, consumption at a given point $s_{i}$ is likely to be close to consumption point at another point $s_{j}$ that is "close" in the state space (similar wealth, income, etc), so a function that captures that similarity efficiently can preserve most of the information without keeping all of the points.
#
# Like linear interpolation, the [DCT transformation](https://en.wikipedia.org/wiki/Discrete_cosine_transform) is a method of representing a continuous function using a finite set of numbers. It uses a set of independent [basis functions](https://en.wikipedia.org/wiki/Basis_function) to do this.
#
# But it turns out that some of those basis functions are much more important than others in representing the steady-state functions. Dimension reduction is accomplished by basically ignoring all basis functions that make "small enough" contributions to the representation of the function.
#
# ##### When might this go wrong?
#
# Suppose the consumption function changes in a recession in ways that change behavior radically at some states. Like, suppose unemployment almost never happens in steady state, but it can happen in temporary recessions. Suppose further that, even for employed people, in a recession, _worries_ about unemployment cause many of them to prudently withdraw some of their illiquid assets -- behavior opposite of what people in the same state would be doing during expansions. In that case, the basis functions that represented the steady state function would have had no incentive to be able to represent well the part of the space that is never seen in steady state, so any functions that might help do so might well have been dropped in the dimension reduction stage.
#
# On the whole, it seems unlikely that this kind of thing is a major problem, because the vast majority of the variation that people experience is idiosyncratic. There is always unemployment, for example; it just moves up and down a bit with aggregate shocks, but since the experience of unemployment is in fact well represented in the steady state the method should have no trouble capturing it.
#
# Where the method might have more trouble is in representing economies in which there are multiple equilibria in which behavior is quite different.
# %% [markdown]
# #### For the distribution of agents across states: Copula
#
# The other tool the authors use is the ["copula"](https://en.wikipedia.org/wiki/Copula_(probability_theory)), which allows us to represent the distribution of people across idiosyncratic states efficiently
#
# The copula is computed from the joint distribution of states in StE and will be used to transform the [marginal distributions](https://en.wikipedia.org/wiki/Marginal_distribution) back to joint distributions. (For an illustration of how the assumptions used when modeling asset price distributions using copulas can fail see [Salmon](https://www.wired.com/2009/02/wp-quant/))
#
# * A copula is a representation of the joint distribution expressed using a mapping between the uniform joint CDF and the marginal distributions of the variables
#
# * The crucial assumption is that what aggregate shocks do is to squeeze or distort the steady state distribution, but leave the rank structure of the distribution the same
# * An example of when this might not hold is the following. Suppose that in expansions, the people at the top of the distribution of illiquid assets (the top 1 percent, say) are also at the top 1 percent of liquid assets. But in recessions the bottom 99 percent get angry at the top 1 percent of illiquid asset holders and confiscate part of their liquid assets (the illiquid assets can't be confiscated quickly because they are illiquid). Now the people in the top 99 percent of illiquid assets might be in the _bottom_ 1 percent of liquid assets.
print('The copula consists of two parts: gridpoints and values at those gridpoints:'+ \
'\n gridpoints have dimensionality of '+str(EX3SS['Copula']['grid'].shape) + \
'\n where the first element is total number of gridpoints' + \
'\n and the second element is number of idiosyncratic state variables' + \
'\n whose values also are of dimension of '+str(EX3SS['Copula']['value'].shape[0]) + \
'\n each entry of which is the probability that all three of the'
'\n state variables are below the corresponding point.')
nt_function
import sys
sys.path.insert(0,'../')
import numpy as np
from numpy.linalg import matrix_rank
import scipy as sc
from scipy.stats import norm
from scipy.interpolate import interp1d, interp2d, griddata, RegularGridInterpolator, interpn
import multiprocessing as mp
from multiprocessing import Pool, cpu_count, Process
from math import ceil
import math as mt
from scipy import sparse as sp
from scipy import linalg
from math import log, cos, pi, sqrt
import time
from SharedFunc3 import Transition, ExTransitions, GenWeight, MakeGridkm, Tauchen, Fastroot
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import scipy.io
import scipy.fftpack as sf
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from matplotlib import cm
import seaborn as sns
import copy as cp
par, mpar, grid, Output, targets, Vm, Vk,
joint_distr, Copula, c_n_guess, c_a_guess, psi_guess,
m_n_star, m_a_star, cap_a_star, mutil_c_n, mutil_c_a,mutil_c, P_H):
self.par = par
self.mpar = mpar
self.grid = grid
self.Output = Output
self.targets = targets
self.Vm = Vm
self.Vk = Vk
self.joint_distr = joint_distr
self.Copula = Copula
self.mutil_c = mutil_c
self.P_H = P_H
def StateReduc(self):
invutil = lambda x : ((1-self.par['xi'])*x)**(1./(1-self.par['xi']))
invmutil = lambda x : (1./x)**(1./self.par['xi'])
Xss=np.asmatrix(np.concatenate((np.sum(np.sum(self.joint_distr.copy(),axis=1),axis =1),
np.transpose(np.sum(np.sum(self.joint_distr.copy(),axis=0),axis=1)),
np.sum(np.sum(self.joint_distr.copy(),axis=1),axis=0),
[np.log(self.par['RB'])],[ 0.]))).T
# c = invmarg(marg(c)), so first bit gets consumption policy function
Yss=np.asmatrix(np.concatenate((invmutil(self.mutil_c.copy().flatten(order = 'F')),\
invmutil(self.Vk.copy().flatten(order = 'F')),
[np.log(self.par['Q'])], # Question: Price of the illiquid asset, right?
[ np.log(self.par['PI'])], # Inflation
[ np.log(self.Output)],
[np.log(self.par['G'])], # Gov spending
[np.log(self.par['W'])], # Wage
[np.log(self.par['R'])], # Nominal R
[np.log(self.par['PROFITS'])],
[np.log(self.par['N'])], # Hours worked
[np.log(self.targets['T'])], # Taxes
[np.log(self.grid['K'])], # Kapital
[np.log(self.targets['B'])]))).T # Government debt
# Mapping for Histogram
# Gamma_state matrix reduced set of states
# nm = number of gridpoints for liquid assets
# nk = number of gridpoints for illiquid assets
# nh = number of gridpoints for human capital (pty)
Gamma_state = np.zeros( # Create zero matrix of size [nm + nk + nh,nm + nk + nh - 4]
(self.mpar['nm']+self.mpar['nk']+self.mpar['nh'],
self.mpar['nm']+self.mpar['nk']+self.mpar['nh'] - 4))
# Question: Why 4? 4 = 3+1, 3: sum to 1 for m, k, h and 1: for entrepreneurs
# Impose adding-up conditions:
# In each of the block matrices, probabilities must add to 1
for j in range(self.mpar['nm']-1): # np.squeeze reduces one-dimensional matrix to vector
Gamma_state[0:self.mpar['nm'],j] = -np.squeeze(Xss[0:self.mpar['nm']])
Gamma_state[j,j]=1. - Xss[j] #
Gamma_state[j,j]=Gamma_state[j,j] - np.sum(Gamma_state[0:self.mpar['nm'],j])
bb = self.mpar['nm'] # Question: bb='bottom base'? because bb shorter to type than self.mpar['nm'] everywhere
for j in range(self.mpar['nk']-1):
Gamma_state[bb+np.arange(0,self.mpar['nk'],1), bb+j-1] = -np.squeeze(Xss[bb+np.arange(0,self.mpar['nk'],1)])
Gamma_state[bb+j,bb-1+j] = 1. - Xss[bb+j]
Gamma_state[bb+j,bb-1+j] = (Gamma_state[bb+j,bb-1+j] -
np.sum(Gamma_state[bb+np.arange(0,self.mpar['nk']),bb-1+j]))
bb = self.mpar['nm'] + self.mpar['nk']
for j in range(self.mpar['nh']-2):
# Question: Why -2? 1 for h sum to 1 and 1 for entrepreneur Some other symmetry/adding-up condition.
Gamma_state[bb+np.arange(0,self.mpar['nh']-1,1), bb+j-2] = -np.squeeze(Xss[bb+np.arange(0,self.mpar['nh']-1,1)])
Gamma_state[bb+j,bb-2+j] = 1. - Xss[bb+j]
Gamma_state[bb+j,bb-2+j] = Gamma_state[bb+j,bb-2+j] - np.sum(Gamma_state[bb+np.arange(0,self.mpar['nh']-1,1),bb-2+j])
# Number of other state variables not including the gridded -- here, just the interest rate
self.mpar['os'] = len(Xss) - (self.mpar['nm']+self.mpar['nk']+self.mpar['nh'])
# For each gridpoint there are two "regular" controls: consumption and illiquid saving
# Counts the number of "other" controls (PROFITS, Q, etc)
self.mpar['oc'] = len(Yss) - 2*(self.mpar['nm']*self.mpar['nk']*self.mpar['nh'])
aggrshock = self.par['aggrshock']
accuracy = self.par['accuracy']
# Do the dct on the steady state marginal utility
# Returns an array of indices for the used basis vectors
indexMUdct = self.do_dct(invmutil(self.mutil_c.copy().flatten(order='F')),
self.mpar,accuracy)
# Do the dct on the steady state marginal value of capital
# Returns an array of indices for the used basis vectors
indexVKdct = self.do_dct(invmutil(self.Vk.copy()),self.mpar,accuracy)
# Calculate the numbers of states and controls
aux = np.shape(Gamma_state)
self.mpar['numstates'] = np.int64(aux[1] + self.mpar['os'])
self.mpar['numcontrols'] = np.int64(len(indexMUdct) +
len(indexVKdct) +
self.mpar['oc'])
# Size of the reduced matrices to be used in the Fsys
# Set to zero because in steady state they are zero
State = np.zeros((self.mpar['numstates'],1))
State_m = State
Contr = np.zeros((self.mpar['numcontrols'],1))
Contr_m = Contr
return {'Xss': Xss, 'Yss':Yss, 'Gamma_state': Gamma_state,
'par':self.par, 'mpar':self.mpar, 'aggrshock':aggrshock,
'Copula':self.Copula,'grid':self.grid,'targets':self.targets,'P_H':self.P_H,
'joint_distr': self.joint_distr, 'Output': self.Output, 'indexMUdct':indexMUdct, 'indexVKdct':indexVKdct,
'State':State, 'State_m':State_m, 'Contr':Contr, 'Contr_m':Contr_m}
# Discrete cosine transformation magic happens here
# sf is scipy.fftpack tool
def do_dct(self, obj, mpar, level):
obj = np.reshape(obj.copy(),(mpar['nm'],mpar['nk'],mpar['nh']),order='F')
X1 = sf.dct(obj,norm='ortho',axis=0) # dct is operated along three dimensions axis=0/1/2
X2 = sf.dct(X1.copy(),norm='ortho',axis=1)
X3 = sf.dct(X2.copy(),norm='ortho',axis=2)
# Pick the coefficients that are big
XX = X3.flatten(order='F')
ind = np.argsort(abs(XX.copy()))[::-1]
# i will
i = 1
# Sort from smallest (=best) to biggest (=worst)
# and count how many are 'good enough to keep'
while linalg.norm(XX[ind[:i]].copy())/linalg.norm(XX) < level:
i += 1
needed = i # Question:Isn't this counting the ones that are NOT needed?
index_reduced = np.sort(ind[:i])
return index_reduced
EX3SS['par']['sigmaS'] = 0.001
n of the marginal value functions is reduced to '+str(SR['indexVKdct'].shape[0]) \
+ ' from ' + str(EX3SS['Vk'].shape))
print('The total number of control variables is '+str(SR['Contr'].shape[0])+'='+str(SR['indexMUdct'].shape[0]) + \
'+'+str(SR['indexVKdct'].shape[0])+'+ # of other macro controls')
print('\n')
print('The copula represents the joint distribution with a vector of size '+str(SR['Gamma_state'].shape) )
print('The dimension of states including exogenous state, is ' +str(SR['Xss'].shape[0]))
print('It simply stacks all grids of different\
\n state variables regardless of their joint distributions.\
\n This is due to the assumption that the rank order remains the same.')
print('The total number of state variables is '+str(SR['State'].shape[0]) + '='+\
str(SR['Gamma_state'].shape[1])+'+ the number of macro states (like the interest rate)')
id = EX3SS['grid']['h']
axis=0,norm='ortho')
x1=sf.dct(x0.copy(),axis=1,norm='ortho')
x2=sf.dct(x1.copy(),axis=2,norm='ortho')
return x2
def idct3d(x):
x2 = sf.idct(x.copy(),axis=2,norm='ortho')
x1 = sf.idct(x2.copy(),axis=1,norm='ortho')
x0 = sf.idct(x1.copy(),axis=0,norm='ortho')
return x0
def DCTApprox(fullgrids,dct_index):
dim=fullgrids.shape
dctcoefs = dct3d(fullgrids)
dctcoefs_rdc = np.zeros(dim)
dctcoefs_rdc[dct_index]=dctcoefs[dct_index]
approxgrids = idct3d(dctcoefs_rdc)
return approxgrids
y_Less2 = 0.95
acc_lst = np.array([Accuracy_BL,Accuracy_Less0,Accuracy_Less1,Accuracy_Less2])
size=(8,8))
fig.suptitle('c at full grids and c approximated by DCT in different accuracy levels'
'\n non-adjusters, fixing k and h',
fontsize=(13))
fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.3)
for idx in range(len(acc_lst)):
EX3SS_cp =cp.deepcopy(EX3SS)
EX3SS_cp['par']['accuracy'] = acc_lst[idx]
EX3SR_cp=StateReduc_Dct(**EX3SS_cp)
SR_cp=EX3SR_cp.StateReduc()
mut_rdc_idx_flt_cp = SR_cp['indexMUdct']
mut_rdc_idx_cp = np.unravel_index(mut_rdc_idx_flt_cp,dim_StE,order='F')
nb_bf_cp = len(mut_rdc_idx_cp[0])
print(str(nb_bf_cp) +" basis functions used.")
c_n_approx_cp = DCTApprox(cn_StE,mut_rdc_idx_cp)
c_a_approx_cp = DCTApprox(ca_StE,mut_rdc_idx_cp)
cn_diff_cp = c_n_approx_cp-cn_StE
hgrid_fix=2
kgrid_fix=10
cVec = c_a_approx_cp[:,kgrid_fix,hgrid_fix]
= fig.add_subplot(2,2,idx+1)
ax.plot(mgrid,cVec,label='c approximated by DCT')
ax.plot(mgrid,ca_StE[:,kgrid_fix,hgrid_fix],'--',label='c at full grids')
ax.plot(mgrid,cVec,'r*')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel(r'$c(m)$',fontsize=13)
ax.set_title(r'accuracy=${}$'.format(acc_lst[idx]))
ax.legend(loc=0)
ll grids and c approximated by DCT in different accuracy levels'
'\n non-adjusters, fixing m and h',
fontsize=(13))
fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.3)
for idx in range(len(acc_lst)):
EX3SS_cp =cp.deepcopy(EX3SS)
EX3SS_cp['par']['accuracy'] = acc_lst[idx]
EX3SR_cp=StateReduc_Dct(**EX3SS_cp)
SR_cp=EX3SR_cp.StateReduc()
mut_rdc_idx_flt_cp= SR_cp['indexMUdct']
mut_rdc_idx_cp = np.unravel_index(mut_rdc_idx_flt_cp,dim_StE,order='F')
nb_bf_cp = len(mut_rdc_idx_cp[0])
print(str(nb_bf_cp) +" basis functions used.")
c_n_approx_cp = DCTApprox(cn_StE,mut_rdc_idx_cp)
c_a_approx_cp = DCTApprox(ca_StE,mut_rdc_idx_cp)
cn_diff_cp = c_n_approx_cp-cn_StE
hgrid_fix=2
mgrid_fix=10
cVec = c_n_approx_cp[mgrid_fix,:,hgrid_fix]
= fig.add_subplot(2,2,idx+1)
ax.plot(kgrid,cVec,label='c approximated by DCT')
ax.plot(kgrid,cn_StE[mgrid_fix,:,hgrid_fix],'--',label='c at full grids')
ax.plot(kgrid,cVec,'r*')
ax.set_xlabel('k',fontsize=13)
ax.set_ylabel(r'$c(k)$',fontsize=13)
ax.set_title(r'accuracy=${}$'.format(acc_lst[idx]))
ax.legend(loc=0)
EX3SS['par']['accuracy'] = Accuracy_BL
EX3SR=StateReduc_Dct(**EX3SS)
SR=EX3SR.StateReduc()
ut_rdc_idx_flt,dim_StE,order='F')
nb_dct = len(mut_StE.flatten())
mut_rdc_bool = np.zeros(nb_dct)
for i in range(nb_dct):
mut_rdc_bool[i]=i in list(SR['indexMUdct'])
mut_rdc_bool_3d = (mut_rdc_bool==1).reshape(dim_StE)
mut_rdc_mask_3d = (mut_rdc_bool).reshape(dim_StE)
joint_distr = EX3SS['joint_distr']
marginal_mk = EX3SS['joint_distr'].sum(axis=2)
mass_pct = 0.9
ut_rdc_idx)
= fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.scatter(mmgrid,kkgrid,c_n_approx[:,:,hgrid_fix],marker='v',color='red',
label='StE(after dct):non-adjuster')
ax.plot_surface(mmgrid,kkgrid,cn_StE[:,:,hgrid_fix],cmap='Blues',
label='StE(before dct): non-adjuster')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_n(m,k)$',fontsize=13)
plt.gca().invert_yaxis()
ax.set_title(r'$h({})$'.format(hgrid_fix))
ax.view_init(20, 100)
t h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
= fig.add_subplot(2,2,hgrid_id+1)
ax.imshow(np.hstack((cn_StE[:,:,hgrid_fix],c_n_approx[:,:,hgrid_fix])))
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_title(r'$h({})$'.format(hgrid_fix))
ints of m and k (for each h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
cn_diff = c_n_approx-cn_StE
= fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,cn_diff[:,:,hgrid_fix], rstride=1,
cstride=1,cmap=cm.coolwarm, edgecolor='none',
label='Difference of full-grid and approximated consumption function')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_a(m,k)$',fontsize=13)
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
ax.set_title(r'$h({})$'.format(hgrid_fix))
ax.view_init(20, 40)
fig = plt.figure(figsize=(14,14))
fig.suptitle('Differences of c at full grids and c approximated by DCT in different accuracy levels(non-adjusters)',
fontsize=(13))
for idx in range(len(acc_lst)):
EX3SS_cp =cp.deepcopy(EX3SS)
EX3SS_cp['par']['accuracy'] = acc_lst[idx]
EX3SR_cp=StateReduc_Dct(**EX3SS_cp)
SR_cp=EX3SR_cp.StateReduc()
mut_rdc_idx_flt_cp = SR_cp['indexMUdct']
mut_rdc_idx_cp = np.unravel_index(mut_rdc_idx_flt_cp,dim_StE,order='F')
nb_bf_cp = len(mut_rdc_idx_cp[0])
print(str(nb_bf_cp) +" basis functions used.")
c_n_approx_cp = DCTApprox(cn_StE,mut_rdc_idx_cp)
c_a_approx_cp = DCTApprox(ca_StE,mut_rdc_idx_cp)
cn_diff_cp = c_n_approx_cp-cn_StE
hgrid_fix=1
= fig.add_subplot(2,2,idx+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,cn_diff_cp[:,:,hgrid_fix], rstride=1,
cstride=1,cmap=cm.summer, edgecolor='none',
label='Difference of full-grid and approximated consumption functions')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel('Difference of c functions',fontsize=13)
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
ax.set_zlim([-8,2])
ax.set_title(r'accuracy=${}$'.format(acc_lst[idx]))
ax.view_init(10, 60)
fig = plt.figure(figsize=(14,14))
fig.suptitle('Consumption of adjusters at grid points of m and k(for different h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
= fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.scatter(mmgrid,kkgrid,c_a_approx[:,:,hgrid_fix],marker='v',color='red',
label='StE(after dct):adjuster')
ax.plot_surface(mmgrid,kkgrid,ca_StE[:,:,hgrid_fix],cmap='Blues',
label='StE(before dct): adjuster')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_a(m,k)$',fontsize=13)
plt.gca().invert_yaxis()
ax.set_title(r'$h({})$'.format(hgrid_fix))
ax.view_init(20, 150)
fig = plt.figure(figsize=(14,14))
fig.suptitle('Consumption of adjusters (yellow)/non-adjusters (blue) at grid points of m and k (for each h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
= fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,c_n_approx[:,:,hgrid_fix],cmap=cm.winter,
label='StE(after dct):non-adjuster')
ax.plot_surface(mmgrid,kkgrid,c_a_approx[:,:,hgrid_fix],cmap=cm.autumn,
label='StE(after dct):adjuster')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_a(m,k)$',fontsize=13)
ax.set_title(r'$h({})$'.format(hgrid_fix))
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
ax.view_init(20, 60)
e('Consumption of adjusters/non-adjusters at grid points of m and k(for different h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
= fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,c_diff_approx[:,:,hgrid_fix],cmap=cm.coolwarm,
label='StE(after dct):difference of non-adjuster and adjusters')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_n(m,k)-c_a(m,k)$',fontsize=12)
ax.set_title(r'$h({})$'.format(hgrid_fix))
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
ax.view_init(20, 80)
ax.set_xlabel('k',size=12)
for id in range(EX3SS['mpar']['nm']):
ax.plot(kgrid,joint_distr[id,:,hgrid_id])
('Joint distribution of m and k(for different h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
= fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,joint_distr[:,:,hgrid_fix], rstride=1, cstride=1,
cmap='viridis', edgecolor='none')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
plt.gca().invert_yaxis()
ax.set_title(r'$h({})$'.format(hgrid_id))
ax.set_xlim(0,400)
ax.view_init(20, 40)
a']['value'].reshape(4,30,30)
fig = plt.figure(figsize=(14,14))
fig.suptitle('Copula of m and k(for different h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
= fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,cdf[hgrid_id,:,:], rstride=1, cstride=1,
cmap='viridis', edgecolor='None')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_title(r'$h({})$'.format(hgrid_id))
axis=0)
marginal_k = marginal_mk.sum(axis=1)
mmax = mgrid[(np.abs(marginal_m.cumsum()-mass_pct*marginal_m.cumsum().max())).argmin()]
kmax = kgrid[(np.abs(marginal_k.cumsum()-mass_pct*marginal_k.cumsum().max())).argmin()]
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
ax.view_init(30, 60)
| true | true |
f7280032dc7383b07665e3f89cd4ed34380fc45e | 146 | py | Python | 20180609/python_lines_04_with.py | bijitchakraborty12/MyProjects01 | 503af4cd6e8fa0576add7ac64393f1b4a16456c7 | [
"MIT"
] | null | null | null | 20180609/python_lines_04_with.py | bijitchakraborty12/MyProjects01 | 503af4cd6e8fa0576add7ac64393f1b4a16456c7 | [
"MIT"
] | null | null | null | 20180609/python_lines_04_with.py | bijitchakraborty12/MyProjects01 | 503af4cd6e8fa0576add7ac64393f1b4a16456c7 | [
"MIT"
] | null | null | null |
with open('C:\\Python Practice\\MyProjects01\\MyProjects01\\20180609\\poem_01.txt') as f:
for k in f.readlines():
print(k.strip().split())
| 18.25 | 89 | 0.684932 |
with open('C:\\Python Practice\\MyProjects01\\MyProjects01\\20180609\\poem_01.txt') as f:
for k in f.readlines():
print(k.strip().split())
| true | true |
f728009e660bb4cab8c59f04834fb694b6e46262 | 16,687 | py | Python | espnet2/bin/enh_inference.py | arceushui/Keyword-Spotting-Alibaba | 10e718491075dee8f875c7860385bc4eef22a790 | [
"Apache-2.0"
] | null | null | null | espnet2/bin/enh_inference.py | arceushui/Keyword-Spotting-Alibaba | 10e718491075dee8f875c7860385bc4eef22a790 | [
"Apache-2.0"
] | null | null | null | espnet2/bin/enh_inference.py | arceushui/Keyword-Spotting-Alibaba | 10e718491075dee8f875c7860385bc4eef22a790 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python3
import argparse
import logging
from pathlib import Path
import sys
from typing import List
from typing import Optional
from typing import Sequence
from typing import Tuple
from typing import Union
import humanfriendly
import numpy as np
import torch
from tqdm import trange
from typeguard import check_argument_types
from espnet.utils.cli_utils import get_commandline_args
from espnet2.fileio.sound_scp import SoundScpWriter
from espnet2.tasks.enh import EnhancementTask
from espnet2.torch_utils.device_funcs import to_device
from espnet2.torch_utils.set_all_random_seed import set_all_random_seed
from espnet2.utils import config_argparse
from espnet2.utils.types import str2bool
from espnet2.utils.types import str2triple_str
from espnet2.utils.types import str_or_none
EPS = torch.finfo(torch.get_default_dtype()).eps
class SeparateSpeech:
"""SeparateSpeech class
Examples:
>>> import soundfile
>>> separate_speech = SeparateSpeech("enh_config.yml", "enh.pth")
>>> audio, rate = soundfile.read("speech.wav")
>>> separate_speech(audio)
[separated_audio1, separated_audio2, ...]
"""
def __init__(
self,
enh_train_config: Union[Path, str],
enh_model_file: Union[Path, str] = None,
segment_size: Optional[float] = None,
hop_size: Optional[float] = None,
normalize_segment_scale: bool = False,
show_progressbar: bool = False,
ref_channel: Optional[int] = None,
normalize_output_wav: bool = False,
device: str = "cpu",
dtype: str = "float32",
):
assert check_argument_types()
# 1. Build Enh model
enh_model, enh_train_args = EnhancementTask.build_model_from_file(
enh_train_config, enh_model_file, device
)
enh_model.to(dtype=getattr(torch, dtype)).eval()
self.device = device
self.dtype = dtype
self.enh_train_args = enh_train_args
self.enh_model = enh_model
# only used when processing long speech, i.e.
# segment_size is not None and hop_size is not None
self.segment_size = segment_size
self.hop_size = hop_size
self.normalize_segment_scale = normalize_segment_scale
self.normalize_output_wav = normalize_output_wav
self.show_progressbar = show_progressbar
self.num_spk = enh_model.num_spk
task = "enhancement" if self.num_spk == 1 else "separation"
# reference channel for processing multi-channel speech
if ref_channel is not None:
logging.info(
"Overwrite enh_model.separator.ref_channel with {}".format(ref_channel)
)
enh_model.separator.ref_channel = ref_channel
self.ref_channel = ref_channel
else:
self.ref_channel = enh_model.ref_channel
self.segmenting = segment_size is not None and hop_size is not None
if self.segmenting:
logging.info("Perform segment-wise speech %s" % task)
logging.info(
"Segment length = {} sec, hop length = {} sec".format(
segment_size, hop_size
)
)
else:
logging.info("Perform direct speech %s on the input" % task)
@torch.no_grad()
def __call__(
self, speech_mix: Union[torch.Tensor, np.ndarray], fs: int = 8000
) -> List[torch.Tensor]:
"""Inference
Args:
speech_mix: Input speech data (Batch, Nsamples [, Channels])
fs: sample rate
Returns:
[separated_audio1, separated_audio2, ...]
"""
assert check_argument_types()
# Input as audio signal
if isinstance(speech_mix, np.ndarray):
speech_mix = torch.as_tensor(speech_mix)
assert speech_mix.dim() > 1, speech_mix.size()
batch_size = speech_mix.size(0)
speech_mix = speech_mix.to(getattr(torch, self.dtype))
# lenghts: (B,)
lengths = speech_mix.new_full(
[batch_size], dtype=torch.long, fill_value=speech_mix.size(1)
)
# a. To device
speech_mix = to_device(speech_mix, device=self.device)
lengths = to_device(lengths, device=self.device)
if self.segmenting and lengths[0] > self.segment_size * fs:
# Segment-wise speech enhancement/separation
overlap_length = int(np.round(fs * (self.segment_size - self.hop_size)))
num_segments = int(
np.ceil((speech_mix.size(1) - overlap_length) / (self.hop_size * fs))
)
t = T = int(self.segment_size * fs)
pad_shape = speech_mix[:, :T].shape
enh_waves = []
range_ = trange if self.show_progressbar else range
for i in range_(num_segments):
st = int(i * self.hop_size * fs)
en = st + T
if en >= lengths[0]:
# en - st < T (last segment)
en = lengths[0]
speech_seg = speech_mix.new_zeros(pad_shape)
t = en - st
speech_seg[:, :t] = speech_mix[:, st:en]
else:
t = T
speech_seg = speech_mix[:, st:en] # B x T [x C]
lengths_seg = speech_mix.new_full(
[batch_size], dtype=torch.long, fill_value=T
)
# b. Enhancement/Separation Forward
feats, f_lens = self.enh_model.encoder(speech_seg, lengths_seg)
feats, _, _ = self.enh_model.separator(feats, f_lens)
processed_wav = [
self.enh_model.decoder(f, lengths_seg)[0] for f in feats
]
if speech_seg.dim() > 2:
# multi-channel speech
speech_seg_ = speech_seg[:, self.ref_channel]
else:
speech_seg_ = speech_seg
if self.normalize_segment_scale:
# normalize the energy of each separated stream
# to match the input energy
processed_wav = [
self.normalize_scale(w, speech_seg_) for w in processed_wav
]
# List[torch.Tensor(num_spk, B, T)]
enh_waves.append(torch.stack(processed_wav, dim=0))
# c. Stitch the enhanced segments together
waves = enh_waves[0]
for i in range(1, num_segments):
# permutation between separated streams in last and current segments
perm = self.cal_permumation(
waves[:, :, -overlap_length:],
enh_waves[i][:, :, :overlap_length],
criterion="si_snr",
)
# repermute separated streams in current segment
for batch in range(batch_size):
enh_waves[i][:, batch] = enh_waves[i][perm[batch], batch]
if i == num_segments - 1:
enh_waves[i][:, :, t:] = 0
enh_waves_res_i = enh_waves[i][:, :, overlap_length:t]
else:
enh_waves_res_i = enh_waves[i][:, :, overlap_length:]
# overlap-and-add (average over the overlapped part)
waves[:, :, -overlap_length:] = (
waves[:, :, -overlap_length:] + enh_waves[i][:, :, :overlap_length]
) / 2
# concatenate the residual parts of the later segment
waves = torch.cat([waves, enh_waves_res_i], dim=2)
# ensure the stitched length is same as input
assert waves.size(2) == speech_mix.size(1), (waves.shape, speech_mix.shape)
waves = torch.unbind(waves, dim=0)
else:
# b. Enhancement/Separation Forward
feats, f_lens = self.enh_model.encoder(speech_mix, lengths)
feats, _, _ = self.enh_model.separator(feats, f_lens)
waves = [self.enh_model.decoder(f, lengths)[0] for f in feats]
assert len(waves) == self.num_spk, len(waves) == self.num_spk
assert len(waves[0]) == batch_size, (len(waves[0]), batch_size)
if self.normalize_output_wav:
waves = [
(w / abs(w).max(dim=1, keepdim=True)[0] * 0.9).cpu().numpy()
for w in waves
] # list[(batch, sample)]
else:
waves = [w.cpu().numpy() for w in waves]
return waves
@staticmethod
@torch.no_grad()
def normalize_scale(enh_wav, ref_ch_wav):
"""Normalize the energy of enh_wav to match that of ref_ch_wav.
Args:
enh_wav (torch.Tensor): (B, Nsamples)
ref_ch_wav (torch.Tensor): (B, Nsamples)
Returns:
enh_wav (torch.Tensor): (B, Nsamples)
"""
ref_energy = torch.sqrt(torch.mean(ref_ch_wav.pow(2), dim=1))
enh_energy = torch.sqrt(torch.mean(enh_wav.pow(2), dim=1))
return enh_wav * (ref_energy / enh_energy)[:, None]
@torch.no_grad()
def cal_permumation(self, ref_wavs, enh_wavs, criterion="si_snr"):
"""Calculate the permutation between seaprated streams in two adjacent segments.
Args:
ref_wavs (List[torch.Tensor]): [(Batch, Nsamples)]
enh_wavs (List[torch.Tensor]): [(Batch, Nsamples)]
criterion (str): one of ("si_snr", "mse", "corr)
Returns:
perm (torch.Tensor): permutation for enh_wavs (Batch, num_spk)
"""
loss_func = {
"si_snr": self.enh_model.si_snr_loss,
"mse": lambda enh, ref: torch.mean((enh - ref).pow(2), dim=1),
"corr": lambda enh, ref: (
(enh * ref).sum(dim=1)
/ (enh.pow(2).sum(dim=1) * ref.pow(2).sum(dim=1) + EPS)
).clamp(min=EPS, max=1 - EPS),
}[criterion]
_, perm = self.enh_model._permutation_loss(ref_wavs, enh_wavs, loss_func)
return perm
def humanfriendly_or_none(value: str):
if value in ("none", "None", "NONE"):
return None
return humanfriendly.parse_size(value)
def inference(
output_dir: str,
batch_size: int,
dtype: str,
fs: int,
ngpu: int,
seed: int,
num_workers: int,
log_level: Union[int, str],
data_path_and_name_and_type: Sequence[Tuple[str, str, str]],
key_file: Optional[str],
enh_train_config: str,
enh_model_file: str,
allow_variable_data_keys: bool,
segment_size: Optional[float],
hop_size: Optional[float],
normalize_segment_scale: bool,
show_progressbar: bool,
ref_channel: Optional[int],
normalize_output_wav: bool,
):
assert check_argument_types()
if batch_size > 1:
raise NotImplementedError("batch decoding is not implemented")
if ngpu > 1:
raise NotImplementedError("only single GPU decoding is supported")
logging.basicConfig(
level=log_level,
format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s",
)
if ngpu >= 1:
device = "cuda"
else:
device = "cpu"
# 1. Set random-seed
set_all_random_seed(seed)
# 2. Build separate_speech
separate_speech = SeparateSpeech(
enh_train_config=enh_train_config,
enh_model_file=enh_model_file,
segment_size=segment_size,
hop_size=hop_size,
normalize_segment_scale=normalize_segment_scale,
show_progressbar=show_progressbar,
ref_channel=ref_channel,
normalize_output_wav=normalize_output_wav,
device=device,
dtype=dtype,
)
# 3. Build data-iterator
loader = EnhancementTask.build_streaming_iterator(
data_path_and_name_and_type,
dtype=dtype,
batch_size=batch_size,
key_file=key_file,
num_workers=num_workers,
preprocess_fn=EnhancementTask.build_preprocess_fn(
separate_speech.enh_train_args, False
),
collate_fn=EnhancementTask.build_collate_fn(
separate_speech.enh_train_args, False
),
allow_variable_data_keys=allow_variable_data_keys,
inference=True,
)
# 4. Start for-loop
writers = []
for i in range(separate_speech.num_spk):
writers.append(
SoundScpWriter(f"{output_dir}/wavs/{i + 1}", f"{output_dir}/spk{i + 1}.scp")
)
for keys, batch in loader:
assert isinstance(batch, dict), type(batch)
assert all(isinstance(s, str) for s in keys), keys
_bs = len(next(iter(batch.values())))
assert len(keys) == _bs, f"{len(keys)} != {_bs}"
batch = {k: v for k, v in batch.items() if not k.endswith("_lengths")}
waves = separate_speech(**batch)
for (spk, w) in enumerate(waves):
for b in range(batch_size):
writers[spk][keys[b]] = fs, w[b]
print(w[b],file=sys.stderr)
for writer in writers:
writer.close()
def get_parser():
parser = config_argparse.ArgumentParser(
description="Frontend inference",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
# Note(kamo): Use '_' instead of '-' as separator.
# '-' is confusing if written in yaml.
parser.add_argument(
"--log_level",
type=lambda x: x.upper(),
default="INFO",
choices=("CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "NOTSET"),
help="The verbose level of logging",
)
parser.add_argument("--output_dir", type=str, required=True)
parser.add_argument(
"--ngpu",
type=int,
default=0,
help="The number of gpus. 0 indicates CPU mode",
)
parser.add_argument("--seed", type=int, default=0, help="Random seed")
parser.add_argument(
"--dtype",
default="float32",
choices=["float16", "float32", "float64"],
help="Data type",
)
parser.add_argument(
"--fs", type=humanfriendly_or_none, default=8000, help="Sampling rate"
)
parser.add_argument(
"--num_workers",
type=int,
default=1,
help="The number of workers used for DataLoader",
)
group = parser.add_argument_group("Input data related")
group.add_argument(
"--data_path_and_name_and_type",
type=str2triple_str,
required=True,
action="append",
)
group.add_argument("--key_file", type=str_or_none)
group.add_argument("--allow_variable_data_keys", type=str2bool, default=False)
group = parser.add_argument_group("Output data related")
group.add_argument(
"--normalize_output_wav",
type=str2bool,
default=False,
help="Whether to normalize the predicted wav to [-1~1]",
)
group = parser.add_argument_group("The model configuration related")
group.add_argument("--enh_train_config", type=str, required=True)
group.add_argument("--enh_model_file", type=str, required=True)
group = parser.add_argument_group("Data loading related")
group.add_argument(
"--batch_size",
type=int,
default=1,
help="The batch size for inference",
)
group = parser.add_argument_group("SeparateSpeech related")
group.add_argument(
"--segment_size",
type=float,
default=None,
help="Segment length in seconds for segment-wise speech enhancement/separation",
)
group.add_argument(
"--hop_size",
type=float,
default=None,
help="Hop length in seconds for segment-wise speech enhancement/separation",
)
group.add_argument(
"--normalize_segment_scale",
type=str2bool,
default=False,
help="Whether to normalize the energy of the separated streams in each segment",
)
group.add_argument(
"--show_progressbar",
type=str2bool,
default=False,
help="Whether to show a progress bar when performing segment-wise speech "
"enhancement/separation",
)
group.add_argument(
"--ref_channel",
type=int,
default=None,
help="If not None, this will overwrite the ref_channel defined in the "
"separator module (for multi-channel speech processing)",
)
return parser
def main(cmd=None):
print(get_commandline_args(), file=sys.stderr)
parser = get_parser()
args = parser.parse_args(cmd)
kwargs = vars(args)
kwargs.pop("config", None)
inference(**kwargs)
if __name__ == "__main__":
main()
| 34.620332 | 88 | 0.597231 |
import argparse
import logging
from pathlib import Path
import sys
from typing import List
from typing import Optional
from typing import Sequence
from typing import Tuple
from typing import Union
import humanfriendly
import numpy as np
import torch
from tqdm import trange
from typeguard import check_argument_types
from espnet.utils.cli_utils import get_commandline_args
from espnet2.fileio.sound_scp import SoundScpWriter
from espnet2.tasks.enh import EnhancementTask
from espnet2.torch_utils.device_funcs import to_device
from espnet2.torch_utils.set_all_random_seed import set_all_random_seed
from espnet2.utils import config_argparse
from espnet2.utils.types import str2bool
from espnet2.utils.types import str2triple_str
from espnet2.utils.types import str_or_none
EPS = torch.finfo(torch.get_default_dtype()).eps
class SeparateSpeech:
def __init__(
self,
enh_train_config: Union[Path, str],
enh_model_file: Union[Path, str] = None,
segment_size: Optional[float] = None,
hop_size: Optional[float] = None,
normalize_segment_scale: bool = False,
show_progressbar: bool = False,
ref_channel: Optional[int] = None,
normalize_output_wav: bool = False,
device: str = "cpu",
dtype: str = "float32",
):
assert check_argument_types()
enh_model, enh_train_args = EnhancementTask.build_model_from_file(
enh_train_config, enh_model_file, device
)
enh_model.to(dtype=getattr(torch, dtype)).eval()
self.device = device
self.dtype = dtype
self.enh_train_args = enh_train_args
self.enh_model = enh_model
self.segment_size = segment_size
self.hop_size = hop_size
self.normalize_segment_scale = normalize_segment_scale
self.normalize_output_wav = normalize_output_wav
self.show_progressbar = show_progressbar
self.num_spk = enh_model.num_spk
task = "enhancement" if self.num_spk == 1 else "separation"
if ref_channel is not None:
logging.info(
"Overwrite enh_model.separator.ref_channel with {}".format(ref_channel)
)
enh_model.separator.ref_channel = ref_channel
self.ref_channel = ref_channel
else:
self.ref_channel = enh_model.ref_channel
self.segmenting = segment_size is not None and hop_size is not None
if self.segmenting:
logging.info("Perform segment-wise speech %s" % task)
logging.info(
"Segment length = {} sec, hop length = {} sec".format(
segment_size, hop_size
)
)
else:
logging.info("Perform direct speech %s on the input" % task)
@torch.no_grad()
def __call__(
self, speech_mix: Union[torch.Tensor, np.ndarray], fs: int = 8000
) -> List[torch.Tensor]:
assert check_argument_types()
if isinstance(speech_mix, np.ndarray):
speech_mix = torch.as_tensor(speech_mix)
assert speech_mix.dim() > 1, speech_mix.size()
batch_size = speech_mix.size(0)
speech_mix = speech_mix.to(getattr(torch, self.dtype))
lengths = speech_mix.new_full(
[batch_size], dtype=torch.long, fill_value=speech_mix.size(1)
)
speech_mix = to_device(speech_mix, device=self.device)
lengths = to_device(lengths, device=self.device)
if self.segmenting and lengths[0] > self.segment_size * fs:
overlap_length = int(np.round(fs * (self.segment_size - self.hop_size)))
num_segments = int(
np.ceil((speech_mix.size(1) - overlap_length) / (self.hop_size * fs))
)
t = T = int(self.segment_size * fs)
pad_shape = speech_mix[:, :T].shape
enh_waves = []
range_ = trange if self.show_progressbar else range
for i in range_(num_segments):
st = int(i * self.hop_size * fs)
en = st + T
if en >= lengths[0]:
en = lengths[0]
speech_seg = speech_mix.new_zeros(pad_shape)
t = en - st
speech_seg[:, :t] = speech_mix[:, st:en]
else:
t = T
speech_seg = speech_mix[:, st:en]
lengths_seg = speech_mix.new_full(
[batch_size], dtype=torch.long, fill_value=T
)
feats, f_lens = self.enh_model.encoder(speech_seg, lengths_seg)
feats, _, _ = self.enh_model.separator(feats, f_lens)
processed_wav = [
self.enh_model.decoder(f, lengths_seg)[0] for f in feats
]
if speech_seg.dim() > 2:
speech_seg_ = speech_seg[:, self.ref_channel]
else:
speech_seg_ = speech_seg
if self.normalize_segment_scale:
processed_wav = [
self.normalize_scale(w, speech_seg_) for w in processed_wav
]
enh_waves.append(torch.stack(processed_wav, dim=0))
waves = enh_waves[0]
for i in range(1, num_segments):
perm = self.cal_permumation(
waves[:, :, -overlap_length:],
enh_waves[i][:, :, :overlap_length],
criterion="si_snr",
)
for batch in range(batch_size):
enh_waves[i][:, batch] = enh_waves[i][perm[batch], batch]
if i == num_segments - 1:
enh_waves[i][:, :, t:] = 0
enh_waves_res_i = enh_waves[i][:, :, overlap_length:t]
else:
enh_waves_res_i = enh_waves[i][:, :, overlap_length:]
waves[:, :, -overlap_length:] = (
waves[:, :, -overlap_length:] + enh_waves[i][:, :, :overlap_length]
) / 2
waves = torch.cat([waves, enh_waves_res_i], dim=2)
assert waves.size(2) == speech_mix.size(1), (waves.shape, speech_mix.shape)
waves = torch.unbind(waves, dim=0)
else:
feats, f_lens = self.enh_model.encoder(speech_mix, lengths)
feats, _, _ = self.enh_model.separator(feats, f_lens)
waves = [self.enh_model.decoder(f, lengths)[0] for f in feats]
assert len(waves) == self.num_spk, len(waves) == self.num_spk
assert len(waves[0]) == batch_size, (len(waves[0]), batch_size)
if self.normalize_output_wav:
waves = [
(w / abs(w).max(dim=1, keepdim=True)[0] * 0.9).cpu().numpy()
for w in waves
]
else:
waves = [w.cpu().numpy() for w in waves]
return waves
@staticmethod
@torch.no_grad()
def normalize_scale(enh_wav, ref_ch_wav):
ref_energy = torch.sqrt(torch.mean(ref_ch_wav.pow(2), dim=1))
enh_energy = torch.sqrt(torch.mean(enh_wav.pow(2), dim=1))
return enh_wav * (ref_energy / enh_energy)[:, None]
@torch.no_grad()
def cal_permumation(self, ref_wavs, enh_wavs, criterion="si_snr"):
loss_func = {
"si_snr": self.enh_model.si_snr_loss,
"mse": lambda enh, ref: torch.mean((enh - ref).pow(2), dim=1),
"corr": lambda enh, ref: (
(enh * ref).sum(dim=1)
/ (enh.pow(2).sum(dim=1) * ref.pow(2).sum(dim=1) + EPS)
).clamp(min=EPS, max=1 - EPS),
}[criterion]
_, perm = self.enh_model._permutation_loss(ref_wavs, enh_wavs, loss_func)
return perm
def humanfriendly_or_none(value: str):
if value in ("none", "None", "NONE"):
return None
return humanfriendly.parse_size(value)
def inference(
output_dir: str,
batch_size: int,
dtype: str,
fs: int,
ngpu: int,
seed: int,
num_workers: int,
log_level: Union[int, str],
data_path_and_name_and_type: Sequence[Tuple[str, str, str]],
key_file: Optional[str],
enh_train_config: str,
enh_model_file: str,
allow_variable_data_keys: bool,
segment_size: Optional[float],
hop_size: Optional[float],
normalize_segment_scale: bool,
show_progressbar: bool,
ref_channel: Optional[int],
normalize_output_wav: bool,
):
assert check_argument_types()
if batch_size > 1:
raise NotImplementedError("batch decoding is not implemented")
if ngpu > 1:
raise NotImplementedError("only single GPU decoding is supported")
logging.basicConfig(
level=log_level,
format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s",
)
if ngpu >= 1:
device = "cuda"
else:
device = "cpu"
set_all_random_seed(seed)
separate_speech = SeparateSpeech(
enh_train_config=enh_train_config,
enh_model_file=enh_model_file,
segment_size=segment_size,
hop_size=hop_size,
normalize_segment_scale=normalize_segment_scale,
show_progressbar=show_progressbar,
ref_channel=ref_channel,
normalize_output_wav=normalize_output_wav,
device=device,
dtype=dtype,
)
loader = EnhancementTask.build_streaming_iterator(
data_path_and_name_and_type,
dtype=dtype,
batch_size=batch_size,
key_file=key_file,
num_workers=num_workers,
preprocess_fn=EnhancementTask.build_preprocess_fn(
separate_speech.enh_train_args, False
),
collate_fn=EnhancementTask.build_collate_fn(
separate_speech.enh_train_args, False
),
allow_variable_data_keys=allow_variable_data_keys,
inference=True,
)
writers = []
for i in range(separate_speech.num_spk):
writers.append(
SoundScpWriter(f"{output_dir}/wavs/{i + 1}", f"{output_dir}/spk{i + 1}.scp")
)
for keys, batch in loader:
assert isinstance(batch, dict), type(batch)
assert all(isinstance(s, str) for s in keys), keys
_bs = len(next(iter(batch.values())))
assert len(keys) == _bs, f"{len(keys)} != {_bs}"
batch = {k: v for k, v in batch.items() if not k.endswith("_lengths")}
waves = separate_speech(**batch)
for (spk, w) in enumerate(waves):
for b in range(batch_size):
writers[spk][keys[b]] = fs, w[b]
print(w[b],file=sys.stderr)
for writer in writers:
writer.close()
def get_parser():
parser = config_argparse.ArgumentParser(
description="Frontend inference",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"--log_level",
type=lambda x: x.upper(),
default="INFO",
choices=("CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "NOTSET"),
help="The verbose level of logging",
)
parser.add_argument("--output_dir", type=str, required=True)
parser.add_argument(
"--ngpu",
type=int,
default=0,
help="The number of gpus. 0 indicates CPU mode",
)
parser.add_argument("--seed", type=int, default=0, help="Random seed")
parser.add_argument(
"--dtype",
default="float32",
choices=["float16", "float32", "float64"],
help="Data type",
)
parser.add_argument(
"--fs", type=humanfriendly_or_none, default=8000, help="Sampling rate"
)
parser.add_argument(
"--num_workers",
type=int,
default=1,
help="The number of workers used for DataLoader",
)
group = parser.add_argument_group("Input data related")
group.add_argument(
"--data_path_and_name_and_type",
type=str2triple_str,
required=True,
action="append",
)
group.add_argument("--key_file", type=str_or_none)
group.add_argument("--allow_variable_data_keys", type=str2bool, default=False)
group = parser.add_argument_group("Output data related")
group.add_argument(
"--normalize_output_wav",
type=str2bool,
default=False,
help="Whether to normalize the predicted wav to [-1~1]",
)
group = parser.add_argument_group("The model configuration related")
group.add_argument("--enh_train_config", type=str, required=True)
group.add_argument("--enh_model_file", type=str, required=True)
group = parser.add_argument_group("Data loading related")
group.add_argument(
"--batch_size",
type=int,
default=1,
help="The batch size for inference",
)
group = parser.add_argument_group("SeparateSpeech related")
group.add_argument(
"--segment_size",
type=float,
default=None,
help="Segment length in seconds for segment-wise speech enhancement/separation",
)
group.add_argument(
"--hop_size",
type=float,
default=None,
help="Hop length in seconds for segment-wise speech enhancement/separation",
)
group.add_argument(
"--normalize_segment_scale",
type=str2bool,
default=False,
help="Whether to normalize the energy of the separated streams in each segment",
)
group.add_argument(
"--show_progressbar",
type=str2bool,
default=False,
help="Whether to show a progress bar when performing segment-wise speech "
"enhancement/separation",
)
group.add_argument(
"--ref_channel",
type=int,
default=None,
help="If not None, this will overwrite the ref_channel defined in the "
"separator module (for multi-channel speech processing)",
)
return parser
def main(cmd=None):
print(get_commandline_args(), file=sys.stderr)
parser = get_parser()
args = parser.parse_args(cmd)
kwargs = vars(args)
kwargs.pop("config", None)
inference(**kwargs)
if __name__ == "__main__":
main()
| true | true |
f7280318fec0d22486693a1e350946abf99b5fec | 26,025 | py | Python | jade2/basic/structure/PythonPDB2.py | RosettaCommons/jade2 | 40affc7c4e0f1f6ee07030e72de284e3484946e7 | [
"BSD-3-Clause"
] | 1 | 2019-12-23T21:52:23.000Z | 2019-12-23T21:52:23.000Z | jade2/basic/structure/PythonPDB2.py | RosettaCommons/jade2 | 40affc7c4e0f1f6ee07030e72de284e3484946e7 | [
"BSD-3-Clause"
] | null | null | null | jade2/basic/structure/PythonPDB2.py | RosettaCommons/jade2 | 40affc7c4e0f1f6ee07030e72de284e3484946e7 | [
"BSD-3-Clause"
] | 1 | 2021-01-28T18:59:03.000Z | 2021-01-28T18:59:03.000Z |
## @author Jared Adolf-Bryfogle (jadolfbr@gmail.com)
#Python Imports
import copy
import pandas
import re, logging
from collections import defaultdict
from typing import Union, DefaultDict, List, Any, Dict
from pathlib import Path
from jade2.basic.path import *
class PythonPDB2:
def __init__(self, pdb_file_path: Union[str, Path] = ""):
"""
Lightweight PDB class specifically for manipulating pdbs in scripts and simple apps as well as obtaining subsets of data in the PDB.
2.0 Uses a vector of dictionaries as main pdb_map for easier manipulation of the pdb_map.
Notes:
Not Meant to be fast - written for ease of use!
ALL elements of the pdb_map data are stored as strings!
"""
self.elements = ("id", "atom_number", "atom_name", "alternate_location", \
"three_letter_code", "chain", "residue_number", "i_code", "x", "y", "z", \
"occupancy", "b_factor", "element", "charge")
self.pdb_file_path = str(pdb_file_path)
self.pdb_map: List[DefaultDict[str, str]] = [] #[int line]:[string element]:[string value]
self.header: List[str] = [] #Unparsed header, but the data is held here as a list of strings. - Everything NOT ATOM or HETATM is here
self.remarks: List[str] = [] #Only REMARK lines as strings
if pdb_file_path:
self.read_pdb_into_map()
else:
logging.info("Loading blank PythonPDB")
def set_pdb_map(self, pdb_map: List[DefaultDict[str, str]]):
self.pdb_map = pdb_map
####################################################################
# Getters + PDB_Map Subsets
#
#
def get_pdb_map(self) -> List[DefaultDict[str, str]]:
return self.pdb_map
def get_dataframe(self) -> pandas.DataFrame:
"""
Get the PDB Map as a dataframe dataframe
"""
return pandas.DataFrame(self.pdb_map)
def get_header(self) -> List[str]:
"""
Get 'header' of PDB as list of strings
"""
return self.header
def get_remarks(self) -> List[str]:
"""
Get 'REMARK' lines of PDB as a list of strings
"""
return self.remarks
def add_remark(self, remark: str):
remark = "REMARK "+remark
self.remarks.append(remark)
def get_chain(self, chain) -> List[DefaultDict[str, str]]:
"""
Get Chain data as pdb_map subset
"""
chain_data = []
for dat in self.pdb_map:
if dat["chain"] == chain:
chain_data.append(dat)
return chain_data
def rename_chain(self, old_chain, new_chain):
for i in range(0, len(self.pdb_map) ):
#print("CHAIN :",self.pdb_map[i]["chain"],":")
if self.pdb_map[i]["chain"] == old_chain:
#print("Chain found. Attempting to change")
self.pdb_map[i]["chain"] = new_chain
def get_waters(self) -> List[DefaultDict[str, str]]:
"""
Get water data as pdb_map subset
"""
water_data = []
for dat in self.pdb_map:
if dat["three_letter_code"] in ["HOH","TP3","TP5","TIP3","TIP5"]:
water_data.append(dat)
return water_data
def get_hetatms(self) -> List[DefaultDict[str, str]]:
"""
Get hetatm data as pdb_map subset
"""
het_data = []
for dat in self.pdb_map:
if dat["id"] == "HETATM":
het_data.append(dat)
return het_data
def get_bb_data(self) -> List[DefaultDict[str, str]]:
"""
Get pdb_map subset of only N, CA, and C atoms
"""
bb_data = []
for dat in self.pdb_map:
if dat["atom_name"] in ["N", "CA", "C"]:
bb_data.append(dat)
return bb_data
def get_all_residues_of_type(self, name3: str) -> List[DefaultDict[str, str]]:
"""
Get PDB_Map subset of all residues of specific type
"""
res_data = []
for dat in self.pdb_map:
if dat["three_letter_code"] == name3:
res_data.append(dat)
return res_data
def get_residue(self, resnum: int, chain: str, icode: str= "") -> List[DefaultDict[str, str]]:
"""
Get PDB_Map subset of a specific residue
"""
residue = []
for dat in self.pdb_map:
if dat["residue_number"] == str(resnum) and dat["chain"] == chain and dat["icode"] == "":
residue.append(dat)
return residue
####################################################################
# Main
#
#
def read_pdb_into_map(self):
"""
Reads PDB file path into a basic PDB map. All data is held as strings.
"""
FILE = open_file(self.pdb_file_path, 'r')
i = 0
for line in FILE:
line = line.strip()
line = line.strip('\n')
if not line: continue
if re.search("REMARK", line[0:6]):
self.remarks.append(line)
elif (re.search("END", line[0:6]) or re.search("TER", line[0:6])):
#We ignore END and TER for now.
pass
elif (re.search("ATOM", line[0:6]) or re.search("HETATM", line[0:6])):
self.pdb_map.append(defaultdict())
self.pdb_map[i]["id"]=line[0:6].strip()
self.pdb_map[i]["atom_number"]=line[6:11].strip(); self.pdb_map[i]["atom_name"] = line[12:16]
self.pdb_map[i]["alternate_location"]=line[16]; self.pdb_map[i]["three_letter_code"] = line[17:21].strip()
self.pdb_map[i]["chain"] = line[21]; self.pdb_map[i]["residue_number"]= line[22:26].strip()
self.pdb_map[i]["i_code"] = line[26]; self.pdb_map[i]["x"] = line[27:38].strip()
self.pdb_map[i]["y"]= line[38:46].strip(); self.pdb_map[i]["z"]= line[46:54].strip()
self.pdb_map[i]["occupancy"] = line[54:60].strip(); self.pdb_map[i]["b_factor"]=line[60:66].strip()
self.pdb_map[i]["element"]=line[66:78].strip(); self.pdb_map[i]["charge"]=line[78:79].strip()
i +=1
elif (re.search("REMARK", line[0:6])):
self.remarks.append(line)
else:
self.header.append(line)
FILE.close()
def save_PDB(self, filename: Union[Path, str], output_remarks: bool = True, output_header: bool= True) -> Union[Path, str]:
"""
Uses a the pdb_map to save the data as a PDB file.
Returns the filename
"""
#global_variables.current_directory = os.path.dirname(filename)
FILE = open_file(filename, 'w')
if output_remarks:
for line in self.remarks:
FILE.write(line+"\n")
if output_header:
for line in self.header:
FILE.write(line+"\n")
for entry in self.pdb_map:
line = self.morph_line_in_pdb_map_to_pdb_line(entry)
FILE.write(line+"\n")
FILE.close()
print("PDB File Written...")
return filename
def morph_line_in_pdb_map_to_pdb_line(self, entry: DefaultDict[str, str]) -> str:
"""
Oh What fun. ;)
Magic Numbers?: (6,5,4,3,1,4,8,8,8,4,5);
"""
#Here we fix the formating of atom name. If we stripped the atom name.
"""
atom_name = self.pdb_map[line_num]['atom_name']
if len(atom_name)==1:
atom_name=' '+atom_name+' '
elif len(atom_name)==2:
#Note that 2 letter elements like CA (calcium) differ from CA (C-Alpha)
#If calcium, would go @column 13. if C-Alpha, column 14.
atom_name=' '+atom_name+' '
elif len(atom_name)==3:
atom_name=' '+atom_name
elif len(atom_name)==4:
atom_name=atom_name
else:
print "Atom Name missing. Inserting spaces."
atom_name = ' '
"""
#Create the PDB line.
line = (entry['id']).ljust(6)+ (entry['atom_number']).rjust(5)+" "+ entry['atom_name']+ \
(entry['alternate_location'])+ ((entry['three_letter_code']).rjust(3)).ljust(4)+ (entry['chain'])+ \
(entry['residue_number']).rjust(4)+ (entry['i_code']) + \
(entry['x']).rjust(11)+ (entry['y']).rjust(8)+ (entry['z']).rjust(8) + \
(entry['occupancy']).rjust(6)+ (entry['b_factor']).rjust(6)
#Note three letter code is wonky due to DA residues. ljust(4) was not working.
return line
##################
# Addition
#
#
def add_ca_residue(self, x: str, y: str, z: str, restype: str = "ALA", b_fac: float = 0, chain="X"):
"""
Add a residue to the map that is only CA
:param x:
:param y:
:param z:
:param restype:
:param b_fac:
:return: None
"""
pass
####################################################################
# Removal
#
#
def remove_antigen(self):
"""
Remove Antigen from an LH only PDB
"""
temp_pdb_map = copy.deepcopy(self.pdb_map)
for dat in temp_pdb_map:
if dat["chain"] not in ['L', 'H']:
self.pdb_map.remove(dat)
def remove_chain(self, chain: str):
"""
Removes chain from pdb_map
"""
temp_pdb_map = copy.deepcopy(self.pdb_map)
for dat in temp_pdb_map:
if dat["chain"]==chain:
self.pdb_map.remove(dat)
def remove_residue_type(self, name3: str):
temp_pdb_map = copy.deepcopy(self.pdb_map)
for dat in temp_pdb_map:
if dat["three_letter_code"]==name3:
self.pdb_map.remove(dat)
def remove_hetatm_atoms(self):
temp_pdb_map = copy.deepcopy(self.pdb_map)
for dat in temp_pdb_map:
if dat["id"]=="HETATM":
self.pdb_map.remove(dat)
def remove_element_column(self):
"""
Removes the extra stuff in the element column, but not the element itself.
"""
for i in range(0, len(self.pdb_map)):
ele = self.pdb_map[i]["element"]
e = ele[11]
self.pdb_map[i]["element"]=" "+e
print("Extra stuff in Element Columns Removed")
return self.pdb_map
def remove_waters(self):
"""
Removes waters from pdb_map
"""
#codes = ["HOH","TP3","TP5","TIP3","TIP5"]
temp_pdb_map = copy.deepcopy(self.pdb_map) #This is to pop elements
for dat in temp_pdb_map:
if dat["three_letter_code"] in ["HOH","TP3","TP5","TIP3","TIP5"]:
#self.pdb_map.pop(num)
self.pdb_map.remove(dat)
def remove_alternate_residues(self):
"""
Removes any alternate residue codes and renumbers by renumbering from 1 and integrating any inserts.
"""
def get_residue_num(num): return int(self.pdb_map_copy[num]["residue_number"])
def set_residue_num(num, resnum): self.pdb_map[num]["residue_number"]=str(resnum)
def get_chain(num):return self.pdb_map_copy[num]["chain"]
def get_i_code(num):return self.pdb_map_copy[num]["i_code"]
def check_id(num):
if self.pdb_map_copy[num]['id']=="ATOM":
return True
else:
return False
def check_new_residue(old_num, num, insert_residue=False, pdb_map = False):
if insert_residue:
if get_i_code(old_num)==get_i_code(num):
return False
else:
return True
else:
if get_residue_num(old_num)==get_residue_num(num):
return False
else:
return True
def check_new_chain(old_num, num):
if get_chain(old_num)==get_chain(num):
return False
else:
return True
def check_insertion(num):
if not get_i_code(num)==" ":
return True
else:
return False
def renumber_from_one(chain_only, start_num):
resnum = 1
for num in sorted(chain_only):
insert = check_insertion(num)
#print repr(get_residue_num(num))+":"+repr(insert)
#This is so we don't check if it's a new residue with num-1 - Which won't actually be part of the chain!
if num==start_num:
set_residue_num(num, resnum)
#Iterate resnum if new residue
elif check_new_residue(num-1, num, insert):
resnum+=1
set_residue_num(num, resnum)
else:
set_residue_num(num, resnum)
#Set i code at the end, so we can tell if we have new residues or not.
for num in sorted(chain_only):
self.pdb_map[num]["i_code"]=" "
def renumber_from_insert(chain_only, start_num):
pass
self.pdb_map_copy = copy.deepcopy(self.pdb_map)
#Get chains with insertion codes - Now renumbers all chains. Will be an option later.
chains_with_inserts = dict();
for num in range(0, len(self.pdb_map)):
#if get_i_code(num)==" ":
chains_with_inserts[get_chain(num)]=True
#Iterate through all lines/atoms
#Initialize for scope
start_residue=0;
new_start=False
for chain in chains_with_inserts:
print("Renumbering chain "+chain)
chain_only=dict()
for num in range(0, len(self.pdb_map)):
if chain == get_chain(num) and check_id(num):
chain_only[num]=self.pdb_map[num]
lines = sorted(chain_only)
res_start = get_residue_num(lines[0])
renumber_from_one(chain_only, lines[0])
#For now, we only renumber from one.
#else:
#chain_only = renumber_from_insert(chain_only, lines[0])
####################################################################
# General Manipulation
#
#
def change_occupancy(self):
"""
Changes ALL occupancies in a PDB dictionary to 1.00
Returns PDB Dictionary.
"""
check = 0
for key in range(0, len(self.pdb_map)):
if self.pdb_map[key]["occupancy"].rfind("0.00")!=-1:
print("Changing occupancy of residue " + self.pdb_map[key]["residue_number"] + "To 1.00")
check =1
self.pdb_map[key]["occupancy"] = " 1.00"
if check ==1:
print("Occupancy Column OK for PyRosetta...")
def combine_pdb(self, py_pdb: 'PythonPDB2'):
"""
Combines pdb_map from instance of PyPDB to this one. Does not do any checks.
"""
m = py_pdb.get_pdb_map()
for dat in m:
self.pdb_map.append(dat)
def copy_chain_into_pdb_map(self, py_pdb: 'PythonPDB2', chain: str):
"""
Copies all data from one pdb_map of a py_pdb of a chain into the one held in this class. Useful for reordering chains.
"""
m = py_pdb.get_pdb_map()
for dat in m:
if dat["chain"] == chain:
self.pdb_map.append(dat)
def copy_all_but_chains_into_pdb_map(self, py_pdb:'PythonPDB2', chains):
"""
Copies all data from one pdb_map of a py_pdb of all data except the specified chains into this one. Useful for reordering chains.
"""
m = py_pdb.get_pdb_map()
for dat in m:
if not dat["chain"] in chains:
self.pdb_map.append(dat)
def combine_pdb_map(self, pdb_map: List[DefaultDict[str, str]]):
"""
Combines pdb_map passed with the PythonPDBs map
"""
for dat in pdb_map:
self.pdb_map.append(dat)
def pdb_alias(self, pairs: Dict[Any, Any], element: str):
"""
Replaces ALL occurances of old element with new from pair.
pair is a dictionary. In C++ it would be an array of pairs. [string old]:[string new]
For Specific functions, please see below.
"""
for num in range(0, len(self.pdb_map)):
for old in pairs:
if self.pdb_map[num][element] == old:
self.pdb_map[num][element] = pairs[old]
def pdb_atom_alias(self, line_num: int, pair: Dict[Any, Any]):
"""
Replaces atom_names with ones Rosetta is happy with.
pair is a dictionary. In C++ it would be an array of pairs. [string MD atom_name]:[string rosetta atom_name]
"""
for start in pair:
if self.pdb_map[line_num]["atom_name"] == start:
print(self.pdb_map[line_num]["three_letter_code"] + ":" + self.pdb_map[line_num]["atom_name"] + ":" +
pair[start])
self.pdb_map[line_num]["atom_name"] = pair[start]
def pdb_residue_alias(self, pairs: Dict[Any, Any]):
"""
Replaces ALL occurances of old residue with new residue.
pair is a dictionary. In C++ it would be an array of pairs. [string old residue_name]:[string new residue_name]
"""
for num in range(0, len(self.pdb_map)):
for old in pairs:
if self.pdb_map[num]["residue_name"] == old:
self.pdb_map[num]["residue_name"] = pairs[old]
def pdb_chain_alias(self, pairs: Dict[Any, Any]):
"""
Replaces ALL occurances of old chain with new chain.
pair is a dictionary. In C++ it would be an array of pairs. [string old chain]:[string new chain]
"""
for num in range(0, len(self.pdb_map)):
for old in pairs:
if self.pdb_map[num]["chain"] == old:
self.pdb_map[num]["chain"] = pairs[old]
def clean_PDB(self):
"""
Removes HSD, Waters: Tries to fix atom and residue name inconsistencies.
HAS worked for changing a single MD pdb (NAMD) frame to Rosetta file.
PLEASE Expand if possible to alias all residues for Rosetta compatability.
NOT gaurenteed, but SHOULD work ok.
"""
self.RESIDUES_aliased = False; self.WATER_aliased=False; self.IONS_aliased=False; self.DNA_aliased = False
waters: List[DefaultDict[str, str]] = [] #List of data that have waters
print("Attempting to change residue names, atom names, and water")
for n in range(0, len(self.pdb_map)):
dat = self.pdb_map[n]
#print self.pdb_map[key]["three_letter_code"]
def alias_dna():
if dat["three_letter_code"]=="DA":
self.DNA_aliased=True
dat["three_letter_code"]="A"
elif dat["three_letter_code"]=="DT":
self.DNA_aliased=True
dat["three_letter_code"]="T"
elif dat["three_letter_code"]=="DC":
self.DNA_aliased=True
dat["three_letter_code"]="C"
elif dat["three_letter_code"]=="DG":
self.DNA_aliased=True
dat["three_letter_code"]="G"
else:
return
def alias_water():
if dat["three_letter_code"] in ["HOH", "TIP3", "WAT", "TIP5"]:
self.WATER_aliased=True
dat["three_letter_code"]="TP3" #IO_STRING for TP3 is WAT...Buy still reads TP#?
dat["id"]="HETATM"
waters.append(dat)
#def alias_ions():
#if self.pdb_map[key]["chain"]=="I":
#IONS_aliased= True
#self.pdb_map[key]["id"]="HETATM"
def alias_residues():
if dat["three_letter_code"] == "HSD":
self.RESIDUES_aliased = True
dat["three_letter_code"]="HIS"
def alias_atoms():
if dat["three_letter_code"]== "SER ":
atom_pairs = {" HG1":" HG "}
elif dat["three_letter_code"]=="ILE ":
atom_pairs = {" CD ":" CD1"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="LEU ":
atom_pairs = {" OT1":" O ", " OT2":" OXT"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="VAL ":
atom_pairs = {" OT1":" O ", " OT2":" OXT"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="LYS ":
atom_pairs = {" HZ1":" 1HZ", " HZ2":" 2HZ", " HZ3":" 3HZ"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="ARG ":
atom_pairs = {" HH11":" 1HH1", " HH12":" 2HH1", " HH21":" 1HH2", " HH22":" 2HH2"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="ASN ":
atom_pairs = {"HD21":"1HD2", "HD22":"2HD2"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="PRO ":
atom_pairs = {" OT1":" O ", " OT2":" OXT", " HD1":" 1HD", " HD2":" 2HD", " HB1":" 1HB", " HG1":" 1HG", " HG2":" 2HG"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
#Unnessessary, but organized.
alias_water()
#alias_ions()
#alias_residues()
alias_atoms()
alias_dna()
#Removes Waters. Keeps Ions.
#for key in waters:
#self.pdb_map.pop(key)
#Outputs what was found:
if self.RESIDUES_aliased:
print("Residues Changed")
if self.WATER_aliased:
print("Water found...changed to TP3. Remove to decrease calculation time.")
if self.IONS_aliased:
print("Ions found. Most are able to be read into Rosetta")
if self.DNA_aliased:
print("DNA found, changed to single letter code.")
####################################################################
# B Factor Replacements
#
#
def read_file_and_replace_b_factors(self, deliminator: str, filename: str, resnum_column: int=1, chain_column:int=2, data_column: int=3, atomname_column=False):
"""
This function reads a deliminated file with data and inserts the data into the BFactor column. Used to visualize arbitrary data.
Use function options to control which column the data is in as well as where your resnums and chains are located.
If atomname column is given, will insert by atom instead of by residue
"""
INFILE = open_file(filename, 'r')
for line in INFILE:
if line[0] == "#":continue
line = line.strip()
lineSP = line.split(deliminator)
if len(lineSP)<3:
print("Could not read line. Must have resnum, chain, and data columns")
continue
if not atomname_column:
self.replace_residue_b_factor(lineSP[resnum_column-1], lineSP[chain_column-1], lineSP[data_column-1])
else:
if len(lineSP)<4:
print("Could not read line. Must have resnum, chain, atomname, and data columns")
continue
self.replace_atom_b_factor(lineSP[resnum_column-1], lineSP[chain_column-1], lineSP[atomname_column-1], lineSP[data_column-1])
INFILE.close()
def replace_residue_b_factor(self, resnum: int, chain: str, data: float):
"""
Replaces the b factor of each atom in the residue with data.
Can be all string representations or not.
"""
if type(resnum)!=str:
resnum = str(resnum)
if type(data)!=float:
data=float(data) #In case data is an integer.
#Need to make sure Bfactor column is adjusted correctly.
for line in range(0, len(self.pdb_map)):
if ((self.pdb_map[line]['residue_number']==resnum) and (self.pdb_map[line]['chain']==chain)):
self.pdb_map[line]['b_factor']="%.2f"%data
else:
continue
def replace_atom_b_factor(self, resnum: int, chain: str, atomname: str, data: float):
"""
Replaces the b factor of an atom.
Can be all string representations or not.
"""
if type(resnum)!=str:
resnum = str(resnum)
if type(data)!=float:
data=float(data)
#Need to make sure Bfactor column is adjusted correctly.
for line in range(0, len(self.pdb_map)):
if ((self.pdb_map[line]['residue_number']==resnum) and (self.pdb_map[line]['chain']==chain) and (self.pdb_map[line]["atom_name"]==atomname)):
self.pdb_map[line]['b_factor']="%.2f"%data
else:
continue
| 36.914894 | 164 | 0.528108 |
m collections import defaultdict
from typing import Union, DefaultDict, List, Any, Dict
from pathlib import Path
from jade2.basic.path import *
class PythonPDB2:
def __init__(self, pdb_file_path: Union[str, Path] = ""):
self.elements = ("id", "atom_number", "atom_name", "alternate_location", \
"three_letter_code", "chain", "residue_number", "i_code", "x", "y", "z", \
"occupancy", "b_factor", "element", "charge")
self.pdb_file_path = str(pdb_file_path)
self.pdb_map: List[DefaultDict[str, str]] = []
self.header: List[str] = []
self.remarks: List[str] = []
if pdb_file_path:
self.read_pdb_into_map()
else:
logging.info("Loading blank PythonPDB")
def set_pdb_map(self, pdb_map: List[DefaultDict[str, str]]):
self.pdb_map = pdb_map
line = (entry['id']).ljust(6)+ (entry['atom_number']).rjust(5)+" "+ entry['atom_name']+ \
(entry['alternate_location'])+ ((entry['three_letter_code']).rjust(3)).ljust(4)+ (entry['chain'])+ \
(entry['residue_number']).rjust(4)+ (entry['i_code']) + \
(entry['x']).rjust(11)+ (entry['y']).rjust(8)+ (entry['z']).rjust(8) + \
(entry['occupancy']).rjust(6)+ (entry['b_factor']).rjust(6)
return line
num(old_num)==get_residue_num(num):
return False
else:
return True
def check_new_chain(old_num, num):
if get_chain(old_num)==get_chain(num):
return False
else:
return True
def check_insertion(num):
if not get_i_code(num)==" ":
return True
else:
return False
def renumber_from_one(chain_only, start_num):
resnum = 1
for num in sorted(chain_only):
insert = check_insertion(num)
if num==start_num:
set_residue_num(num, resnum)
#Iterate resnum if new residue
elif check_new_residue(num-1, num, insert):
resnum+=1
set_residue_num(num, resnum)
else:
set_residue_num(num, resnum)
#Set i code at the end, so we can tell if we have new residues or not.
for num in sorted(chain_only):
self.pdb_map[num]["i_code"]=" "
def renumber_from_insert(chain_only, start_num):
pass
self.pdb_map_copy = copy.deepcopy(self.pdb_map)
#Get chains with insertion codes - Now renumbers all chains. Will be an option later.
chains_with_inserts = dict();
for num in range(0, len(self.pdb_map)):
#if get_i_code(num)==" ":
chains_with_inserts[get_chain(num)]=True
#Iterate through all lines/atoms
#Initialize for scope
start_residue=0;
new_start=False
for chain in chains_with_inserts:
print("Renumbering chain "+chain)
chain_only=dict()
for num in range(0, len(self.pdb_map)):
if chain == get_chain(num) and check_id(num):
chain_only[num]=self.pdb_map[num]
lines = sorted(chain_only)
res_start = get_residue_num(lines[0])
renumber_from_one(chain_only, lines[0])
#For now, we only renumber from one.
#else:
#chain_only = renumber_from_insert(chain_only, lines[0])
####################################################################
# General Manipulation
#
#
def change_occupancy(self):
check = 0
for key in range(0, len(self.pdb_map)):
if self.pdb_map[key]["occupancy"].rfind("0.00")!=-1:
print("Changing occupancy of residue " + self.pdb_map[key]["residue_number"] + "To 1.00")
check =1
self.pdb_map[key]["occupancy"] = " 1.00"
if check ==1:
print("Occupancy Column OK for PyRosetta...")
def combine_pdb(self, py_pdb: 'PythonPDB2'):
m = py_pdb.get_pdb_map()
for dat in m:
self.pdb_map.append(dat)
def copy_chain_into_pdb_map(self, py_pdb: 'PythonPDB2', chain: str):
m = py_pdb.get_pdb_map()
for dat in m:
if dat["chain"] == chain:
self.pdb_map.append(dat)
def copy_all_but_chains_into_pdb_map(self, py_pdb:'PythonPDB2', chains):
m = py_pdb.get_pdb_map()
for dat in m:
if not dat["chain"] in chains:
self.pdb_map.append(dat)
def combine_pdb_map(self, pdb_map: List[DefaultDict[str, str]]):
for dat in pdb_map:
self.pdb_map.append(dat)
def pdb_alias(self, pairs: Dict[Any, Any], element: str):
for num in range(0, len(self.pdb_map)):
for old in pairs:
if self.pdb_map[num][element] == old:
self.pdb_map[num][element] = pairs[old]
def pdb_atom_alias(self, line_num: int, pair: Dict[Any, Any]):
for start in pair:
if self.pdb_map[line_num]["atom_name"] == start:
print(self.pdb_map[line_num]["three_letter_code"] + ":" + self.pdb_map[line_num]["atom_name"] + ":" +
pair[start])
self.pdb_map[line_num]["atom_name"] = pair[start]
def pdb_residue_alias(self, pairs: Dict[Any, Any]):
for num in range(0, len(self.pdb_map)):
for old in pairs:
if self.pdb_map[num]["residue_name"] == old:
self.pdb_map[num]["residue_name"] = pairs[old]
def pdb_chain_alias(self, pairs: Dict[Any, Any]):
for num in range(0, len(self.pdb_map)):
for old in pairs:
if self.pdb_map[num]["chain"] == old:
self.pdb_map[num]["chain"] = pairs[old]
def clean_PDB(self):
self.RESIDUES_aliased = False; self.WATER_aliased=False; self.IONS_aliased=False; self.DNA_aliased = False
waters: List[DefaultDict[str, str]] = [] #List of data that have waters
print("Attempting to change residue names, atom names, and water")
for n in range(0, len(self.pdb_map)):
dat = self.pdb_map[n]
#print self.pdb_map[key]["three_letter_code"]
def alias_dna():
if dat["three_letter_code"]=="DA":
self.DNA_aliased=True
dat["three_letter_code"]="A"
elif dat["three_letter_code"]=="DT":
self.DNA_aliased=True
dat["three_letter_code"]="T"
elif dat["three_letter_code"]=="DC":
self.DNA_aliased=True
dat["three_letter_code"]="C"
elif dat["three_letter_code"]=="DG":
self.DNA_aliased=True
dat["three_letter_code"]="G"
else:
return
def alias_water():
if dat["three_letter_code"] in ["HOH", "TIP3", "WAT", "TIP5"]:
self.WATER_aliased=True
dat["three_letter_code"]="TP3" #IO_STRING for TP3 is WAT...Buy still reads TP#?
dat["id"]="HETATM"
waters.append(dat)
#def alias_ions():
#if self.pdb_map[key]["chain"]=="I":
#IONS_aliased= True
#self.pdb_map[key]["id"]="HETATM"
def alias_residues():
if dat["three_letter_code"] == "HSD":
self.RESIDUES_aliased = True
dat["three_letter_code"]="HIS"
def alias_atoms():
if dat["three_letter_code"]== "SER ":
atom_pairs = {" HG1":" HG "}
elif dat["three_letter_code"]=="ILE ":
atom_pairs = {" CD ":" CD1"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="LEU ":
atom_pairs = {" OT1":" O ", " OT2":" OXT"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="VAL ":
atom_pairs = {" OT1":" O ", " OT2":" OXT"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="LYS ":
atom_pairs = {" HZ1":" 1HZ", " HZ2":" 2HZ", " HZ3":" 3HZ"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="ARG ":
atom_pairs = {" HH11":" 1HH1", " HH12":" 2HH1", " HH21":" 1HH2", " HH22":" 2HH2"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="ASN ":
atom_pairs = {"HD21":"1HD2", "HD22":"2HD2"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="PRO ":
atom_pairs = {" OT1":" O ", " OT2":" OXT", " HD1":" 1HD", " HD2":" 2HD", " HB1":" 1HB", " HG1":" 1HG", " HG2":" 2HG"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
#Unnessessary, but organized.
alias_water()
#alias_ions()
#alias_residues()
alias_atoms()
alias_dna()
#Removes Waters. Keeps Ions.
#for key in waters:
#self.pdb_map.pop(key)
#Outputs what was found:
if self.RESIDUES_aliased:
print("Residues Changed")
if self.WATER_aliased:
print("Water found...changed to TP3. Remove to decrease calculation time.")
if self.IONS_aliased:
print("Ions found. Most are able to be read into Rosetta")
if self.DNA_aliased:
print("DNA found, changed to single letter code.")
####################################################################
# B Factor Replacements
#
#
def read_file_and_replace_b_factors(self, deliminator: str, filename: str, resnum_column: int=1, chain_column:int=2, data_column: int=3, atomname_column=False):
INFILE = open_file(filename, 'r')
for line in INFILE:
if line[0] == "#":continue
line = line.strip()
lineSP = line.split(deliminator)
if len(lineSP)<3:
print("Could not read line. Must have resnum, chain, and data columns")
continue
if not atomname_column:
self.replace_residue_b_factor(lineSP[resnum_column-1], lineSP[chain_column-1], lineSP[data_column-1])
else:
if len(lineSP)<4:
print("Could not read line. Must have resnum, chain, atomname, and data columns")
continue
self.replace_atom_b_factor(lineSP[resnum_column-1], lineSP[chain_column-1], lineSP[atomname_column-1], lineSP[data_column-1])
INFILE.close()
def replace_residue_b_factor(self, resnum: int, chain: str, data: float):
if type(resnum)!=str:
resnum = str(resnum)
if type(data)!=float:
data=float(data) #In case data is an integer.
#Need to make sure Bfactor column is adjusted correctly.
for line in range(0, len(self.pdb_map)):
if ((self.pdb_map[line]['residue_number']==resnum) and (self.pdb_map[line]['chain']==chain)):
self.pdb_map[line]['b_factor']="%.2f"%data
else:
continue
def replace_atom_b_factor(self, resnum: int, chain: str, atomname: str, data: float):
if type(resnum)!=str:
resnum = str(resnum)
if type(data)!=float:
data=float(data)
#Need to make sure Bfactor column is adjusted correctly.
for line in range(0, len(self.pdb_map)):
if ((self.pdb_map[line]['residue_number']==resnum) and (self.pdb_map[line]['chain']==chain) and (self.pdb_map[line]["atom_name"]==atomname)):
self.pdb_map[line]['b_factor']="%.2f"%data
else:
continue
| true | true |
f728036c65d2fb7c85eff44144bdd6548137164c | 3,985 | py | Python | setup.py | moonso/loqusdb | 3f2ab2bd458f83b1c408e8573036024986d0ed4c | [
"MIT"
] | 4 | 2018-06-04T12:42:45.000Z | 2021-03-29T20:36:12.000Z | setup.py | moonso/loqusdb | 3f2ab2bd458f83b1c408e8573036024986d0ed4c | [
"MIT"
] | 50 | 2016-02-26T07:54:39.000Z | 2021-10-12T07:52:01.000Z | setup.py | moonso/loqusdb | 3f2ab2bd458f83b1c408e8573036024986d0ed4c | [
"MIT"
] | 8 | 2016-02-29T13:50:46.000Z | 2020-04-22T10:15:23.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: To use the 'upload' functionality of this file, you must:
# $ pip install twine
"""Based on https://github.com/kennethreitz/setup.py"""
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
# Package meta-data.
NAME = 'loqusdb'
DESCRIPTION = 'Store observations of vcf variants in a mongodb'
URL = 'https://github.com/moonso/loqusdb'
EMAIL = 'mans.magnusson@scilifelab.com'
AUTHOR = 'Måns Magnusson'
REQUIRES_PYTHON = '>=3.6.0'
VERSION = "2.5.2"
# What packages are required for this module to be executed?
REQUIRED = [
'click',
'ped_parser',
'pymongo==3.7.1',
'mongomock==3.18',
'vcftoolbox==1.5',
'cyvcf2<0.10',
'coloredlogs',
'mongo_adapter>=0.2',
'pyyaml',
]
# What packages are optional?
EXTRAS = {
'tests':['pytest'],
}
# The rest you shouldn't have to touch too much :)
# ------------------------------------------------
# Except, perhaps the License and Trove Classifiers!
# If you do change the License, remember to change the Trove Classifier for that!
here = os.path.abspath(os.path.dirname(__file__))
# Import the README and use it as the long-description.
# Note: this will only work if 'README.md' is present in your MANIFEST.in file!
try:
with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = '\n' + f.read()
except FileNotFoundError:
long_description = DESCRIPTION
# Load the package's __version__.py module as a dictionary.
about = {}
if not VERSION:
with open(os.path.join(here, NAME, '__version__.py')) as f:
exec(f.read(), about)
else:
about['__version__'] = VERSION
class UploadCommand(Command):
"""Support setup.py upload."""
description = 'Build and publish the package.'
user_options = []
@staticmethod
def status(s):
"""Prints things in bold."""
print('\033[1m{0}\033[0m'.format(s))
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
try:
self.status('Removing previous builds…')
rmtree(os.path.join(here, 'dist'))
except OSError:
pass
self.status('Building Source and Wheel (universal) distribution…')
os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))
self.status('Uploading the package to PyPI via Twine…')
os.system('twine upload dist/*')
self.status('Pushing git tags…')
os.system('git tag v{0}'.format(about['__version__']))
os.system('git push --tags')
sys.exit()
# Where the magic happens:
setup(
name=NAME,
version=about['__version__'],
description=DESCRIPTION,
long_description=long_description,
long_description_content_type='text/markdown',
author=AUTHOR,
author_email=EMAIL,
python_requires=REQUIRES_PYTHON,
url=URL,
packages=find_packages(exclude=('tests',)),
entry_points={
'console_scripts': ["loqusdb = loqusdb.__main__:base_command"],
},
install_requires=REQUIRED,
extras_require=EXTRAS,
include_package_data=True,
license='MIT',
keywords = ['vcf', 'variants'],
classifiers=[
# Trove classifiers
# Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
"Operating System :: MacOS :: MacOS X",
"Operating System :: Unix",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering :: Bio-Informatics",
],
# $ setup.py publish support.
cmdclass={
'upload': UploadCommand,
},
)
| 27.673611 | 86 | 0.636386 |
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
NAME = 'loqusdb'
DESCRIPTION = 'Store observations of vcf variants in a mongodb'
URL = 'https://github.com/moonso/loqusdb'
EMAIL = 'mans.magnusson@scilifelab.com'
AUTHOR = 'Måns Magnusson'
REQUIRES_PYTHON = '>=3.6.0'
VERSION = "2.5.2"
REQUIRED = [
'click',
'ped_parser',
'pymongo==3.7.1',
'mongomock==3.18',
'vcftoolbox==1.5',
'cyvcf2<0.10',
'coloredlogs',
'mongo_adapter>=0.2',
'pyyaml',
]
EXTRAS = {
'tests':['pytest'],
}
# ------------------------------------------------
# Except, perhaps the License and Trove Classifiers!
# If you do change the License, remember to change the Trove Classifier for that!
here = os.path.abspath(os.path.dirname(__file__))
# Import the README and use it as the long-description.
# Note: this will only work if 'README.md' is present in your MANIFEST.in file!
try:
with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = '\n' + f.read()
except FileNotFoundError:
long_description = DESCRIPTION
# Load the package's __version__.py module as a dictionary.
about = {}
if not VERSION:
with open(os.path.join(here, NAME, '__version__.py')) as f:
exec(f.read(), about)
else:
about['__version__'] = VERSION
class UploadCommand(Command):
description = 'Build and publish the package.'
user_options = []
@staticmethod
def status(s):
print('\033[1m{0}\033[0m'.format(s))
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
try:
self.status('Removing previous builds…')
rmtree(os.path.join(here, 'dist'))
except OSError:
pass
self.status('Building Source and Wheel (universal) distribution…')
os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))
self.status('Uploading the package to PyPI via Twine…')
os.system('twine upload dist/*')
self.status('Pushing git tags…')
os.system('git tag v{0}'.format(about['__version__']))
os.system('git push --tags')
sys.exit()
setup(
name=NAME,
version=about['__version__'],
description=DESCRIPTION,
long_description=long_description,
long_description_content_type='text/markdown',
author=AUTHOR,
author_email=EMAIL,
python_requires=REQUIRES_PYTHON,
url=URL,
packages=find_packages(exclude=('tests',)),
entry_points={
'console_scripts': ["loqusdb = loqusdb.__main__:base_command"],
},
install_requires=REQUIRED,
extras_require=EXTRAS,
include_package_data=True,
license='MIT',
keywords = ['vcf', 'variants'],
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
"Operating System :: MacOS :: MacOS X",
"Operating System :: Unix",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering :: Bio-Informatics",
],
cmdclass={
'upload': UploadCommand,
},
)
| true | true |
f728044a58a0b35f5e119349ab2cfafc658bbc58 | 7,909 | py | Python | research/audioset/vggish/vggish_train_demo.py | SimiaCryptus/models | c652a23a650070b71e286f1ded93726670161940 | [
"Apache-2.0"
] | null | null | null | research/audioset/vggish/vggish_train_demo.py | SimiaCryptus/models | c652a23a650070b71e286f1ded93726670161940 | [
"Apache-2.0"
] | null | null | null | research/audioset/vggish/vggish_train_demo.py | SimiaCryptus/models | c652a23a650070b71e286f1ded93726670161940 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
r"""A simple demonstration of running VGGish in training mode.
This is intended as a toy example that demonstrates how to use the VGGish model
definition within a larger model that adds more layers on top, and then train
the larger model. If you let VGGish train as well, then this allows you to
fine-tune the VGGish model parameters for your application. If you don't let
VGGish train, then you use VGGish as a feature extractor for the layers above
it.
For this toy task, we are training a classifier to distinguish between three
classes: sine waves, constant signals, and white noise. We generate synthetic
waveforms from each of these classes, convert into shuffled batches of log mel
spectrogram examples with associated labels, and feed the batches into a model
that includes VGGish at the bottom and a couple of additional layers on top. We
also plumb in labels that are associated with the examples, which feed a label
loss used for training.
Usage:
# Run training for 100 steps using a model checkpoint in the default
# location (vggish_model.ckpt in the current directory). Allow VGGish
# to get fine-tuned.
$ python vggish_train_demo.py --num_batches 100
# Same as before but run for fewer steps and don't change VGGish parameters
# and use a checkpoint in a different location
$ python vggish_train_demo.py --num_batches 50 \
--train_vggish=False \
--checkpoint /path/to/model/checkpoint
"""
from __future__ import print_function
from random import shuffle
import numpy as np
import tensorflow as tf
import vggish_input
import vggish_params
import vggish_slim
flags = tf.app.flags
slim = tf.contrib.slim
flags.DEFINE_integer(
'num_batches', 30,
'Number of batches of examples to feed into the model. Each batch is of '
'variable size and contains shuffled examples of each class of audio.')
flags.DEFINE_boolean(
'train_vggish', True,
'If True, allow VGGish parameters to change during training, thus '
'fine-tuning VGGish. If False, VGGish parameters are fixed, thus using '
'VGGish as a fixed feature extractor.')
flags.DEFINE_string(
'checkpoint', 'vggish_model.ckpt',
'Path to the VGGish checkpoint file.')
FLAGS = flags.FLAGS
_NUM_CLASSES = 3
def _get_examples_batch():
"""Returns a shuffled batch of examples of all audio classes.
Note that this is just a toy function because this is a simple demo intended
to illustrate how the training code might work.
Returns:
a tuple (features, labels) where features is a NumPy array of shape
[batch_size, num_frames, num_bands] where the batch_size is variable and
each row is a log mel spectrogram patch of shape [num_frames, num_bands]
suitable for feeding VGGish, while labels is a NumPy array of shape
[batch_size, num_classes] where each row is a multi-hot label vector that
provides the labels for corresponding rows in features.
"""
# Make a waveform for each class.
num_seconds = 5
sr = 44100 # Sampling rate.
t = np.linspace(0, num_seconds, int(num_seconds * sr)) # Time axis.
# Random sine wave.
freq = np.random.uniform(100, 1000)
sine = np.sin(2 * np.pi * freq * t)
# Random constant signal.
magnitude = np.random.uniform(-1, 1)
const = magnitude * t
# White noise.
noise = np.random.normal(-1, 1, size=t.shape)
# Make examples of each signal and corresponding labels.
# Sine is class index 0, Const class index 1, Noise class index 2.
sine_examples = vggish_input.waveform_to_examples(sine, sr)
sine_labels = np.array([[1, 0, 0]] * sine_examples.shape[0])
const_examples = vggish_input.waveform_to_examples(const, sr)
const_labels = np.array([[0, 1, 0]] * const_examples.shape[0])
noise_examples = vggish_input.waveform_to_examples(noise, sr)
noise_labels = np.array([[0, 0, 1]] * noise_examples.shape[0])
# Shuffle (example, label) pairs across all classes.
all_examples = np.concatenate((sine_examples, const_examples, noise_examples))
all_labels = np.concatenate((sine_labels, const_labels, noise_labels))
labeled_examples = list(zip(all_examples, all_labels))
shuffle(labeled_examples)
# Separate and return the features and labels.
features = [example for (example, _) in labeled_examples]
labels = [label for (_, label) in labeled_examples]
return (features, labels)
def main(_):
with tf.Graph().as_default(), tf.Session() as sess:
# Define VGGish.
embeddings = vggish_slim.define_vggish_slim(FLAGS.train_vggish)
# Define a shallow classification model and associated training ops on top
# of VGGish.
with tf.variable_scope('mymodel'):
# Add a fully connected layer with 100 units.
num_units = 100
fc = slim.fully_connected(embeddings, num_units)
# Add a classifier layer at the end, consisting of parallel logistic
# classifiers, one per class. This allows for multi-class tasks.
logits = slim.fully_connected(
fc, _NUM_CLASSES, activation_fn=None, scope='logits')
tf.sigmoid(logits, name='prediction')
# Add training ops.
with tf.variable_scope('train'):
global_step = tf.Variable(
0, name='global_step', trainable=False,
collections=[tf.GraphKeys.GLOBAL_VARIABLES,
tf.GraphKeys.GLOBAL_STEP])
# Labels are assumed to be fed as a batch multi-hot vectors, with
# a 1 in the position of each positive class label, and 0 elsewhere.
labels = tf.placeholder(
tf.float32, shape=(None, _NUM_CLASSES), name='labels')
# Cross-entropy label loss.
xent = tf.nn.sigmoid_cross_entropy_with_logits(
logits=logits, labels=labels, name='xent')
loss = tf.reduce_mean(xent, name='loss_op')
tf.summary.scalar('loss', loss)
# We use the same optimizer and hyperparameters as used to train VGGish.
optimizer = tf.train.AdamOptimizer(
learning_rate=vggish_params.LEARNING_RATE,
epsilon=vggish_params.ADAM_EPSILON)
optimizer.minimize(loss, global_step=global_step, name='train_op')
# Initialize all variables in the model, and then load the pre-trained
# VGGish checkpoint.
sess.run(tf.global_variables_initializer())
vggish_slim.load_vggish_slim_checkpoint(sess, FLAGS.checkpoint)
# Locate all the tensors and ops we need for the training loop.
features_tensor = sess.graph.get_tensor_by_name(
vggish_params.INPUT_TENSOR_NAME)
labels_tensor = sess.graph.get_tensor_by_name('mymodel/train/labels:0')
global_step_tensor = sess.graph.get_tensor_by_name(
'mymodel/train/global_step:0')
loss_tensor = sess.graph.get_tensor_by_name('mymodel/train/loss_op:0')
train_op = sess.graph.get_operation_by_name('mymodel/train/train_op')
# The training loop.
for _ in range(FLAGS.num_batches):
(features, labels) = _get_examples_batch()
[num_steps, loss, _] = sess.run(
[global_step_tensor, loss_tensor, train_op],
feed_dict={features_tensor: features, labels_tensor: labels})
print('Step %d: loss %g' % (num_steps, loss))
if __name__ == '__main__':
tf.app.run()
| 40.979275 | 80 | 0.713491 |
from __future__ import print_function
from random import shuffle
import numpy as np
import tensorflow as tf
import vggish_input
import vggish_params
import vggish_slim
flags = tf.app.flags
slim = tf.contrib.slim
flags.DEFINE_integer(
'num_batches', 30,
'Number of batches of examples to feed into the model. Each batch is of '
'variable size and contains shuffled examples of each class of audio.')
flags.DEFINE_boolean(
'train_vggish', True,
'If True, allow VGGish parameters to change during training, thus '
'fine-tuning VGGish. If False, VGGish parameters are fixed, thus using '
'VGGish as a fixed feature extractor.')
flags.DEFINE_string(
'checkpoint', 'vggish_model.ckpt',
'Path to the VGGish checkpoint file.')
FLAGS = flags.FLAGS
_NUM_CLASSES = 3
def _get_examples_batch():
num_seconds = 5
sr = 44100
t = np.linspace(0, num_seconds, int(num_seconds * sr))
freq = np.random.uniform(100, 1000)
sine = np.sin(2 * np.pi * freq * t)
magnitude = np.random.uniform(-1, 1)
const = magnitude * t
noise = np.random.normal(-1, 1, size=t.shape)
sine_examples = vggish_input.waveform_to_examples(sine, sr)
sine_labels = np.array([[1, 0, 0]] * sine_examples.shape[0])
const_examples = vggish_input.waveform_to_examples(const, sr)
const_labels = np.array([[0, 1, 0]] * const_examples.shape[0])
noise_examples = vggish_input.waveform_to_examples(noise, sr)
noise_labels = np.array([[0, 0, 1]] * noise_examples.shape[0])
all_examples = np.concatenate((sine_examples, const_examples, noise_examples))
all_labels = np.concatenate((sine_labels, const_labels, noise_labels))
labeled_examples = list(zip(all_examples, all_labels))
shuffle(labeled_examples)
features = [example for (example, _) in labeled_examples]
labels = [label for (_, label) in labeled_examples]
return (features, labels)
def main(_):
with tf.Graph().as_default(), tf.Session() as sess:
embeddings = vggish_slim.define_vggish_slim(FLAGS.train_vggish)
with tf.variable_scope('mymodel'):
num_units = 100
fc = slim.fully_connected(embeddings, num_units)
logits = slim.fully_connected(
fc, _NUM_CLASSES, activation_fn=None, scope='logits')
tf.sigmoid(logits, name='prediction')
with tf.variable_scope('train'):
global_step = tf.Variable(
0, name='global_step', trainable=False,
collections=[tf.GraphKeys.GLOBAL_VARIABLES,
tf.GraphKeys.GLOBAL_STEP])
labels = tf.placeholder(
tf.float32, shape=(None, _NUM_CLASSES), name='labels')
xent = tf.nn.sigmoid_cross_entropy_with_logits(
logits=logits, labels=labels, name='xent')
loss = tf.reduce_mean(xent, name='loss_op')
tf.summary.scalar('loss', loss)
optimizer = tf.train.AdamOptimizer(
learning_rate=vggish_params.LEARNING_RATE,
epsilon=vggish_params.ADAM_EPSILON)
optimizer.minimize(loss, global_step=global_step, name='train_op')
sess.run(tf.global_variables_initializer())
vggish_slim.load_vggish_slim_checkpoint(sess, FLAGS.checkpoint)
features_tensor = sess.graph.get_tensor_by_name(
vggish_params.INPUT_TENSOR_NAME)
labels_tensor = sess.graph.get_tensor_by_name('mymodel/train/labels:0')
global_step_tensor = sess.graph.get_tensor_by_name(
'mymodel/train/global_step:0')
loss_tensor = sess.graph.get_tensor_by_name('mymodel/train/loss_op:0')
train_op = sess.graph.get_operation_by_name('mymodel/train/train_op')
for _ in range(FLAGS.num_batches):
(features, labels) = _get_examples_batch()
[num_steps, loss, _] = sess.run(
[global_step_tensor, loss_tensor, train_op],
feed_dict={features_tensor: features, labels_tensor: labels})
print('Step %d: loss %g' % (num_steps, loss))
if __name__ == '__main__':
tf.app.run()
| true | true |
f7280459bb1c11d05d44c03226ca1b7d0dd23522 | 449 | py | Python | python/sprint_12/tmp/code.py | Talgatovich/algorithms-templates | e7c6fd71451304ed0dacc393c3f30ca3f5282d46 | [
"MIT"
] | null | null | null | python/sprint_12/tmp/code.py | Talgatovich/algorithms-templates | e7c6fd71451304ed0dacc393c3f30ca3f5282d46 | [
"MIT"
] | null | null | null | python/sprint_12/tmp/code.py | Talgatovich/algorithms-templates | e7c6fd71451304ed0dacc393c3f30ca3f5282d46 | [
"MIT"
] | null | null | null | # Comment it before submitting
# class Node:
# def __init__(self, value, next_item=None):
# self.value = value
# self.next_item = next_item
def solution(node, idx):
# Your code
# ヽ(´▽`)/
pass
def test():
node3 = Node("node3", None)
node2 = Node("node2", node3)
node1 = Node("node1", node2)
node0 = Node("node0", node1)
new_head = solution(node0, 1)
# result is node0 -> node2 -> node3 | 23.631579 | 50 | 0.581292 |
def solution(node, idx):
pass
def test():
node3 = Node("node3", None)
node2 = Node("node2", node3)
node1 = Node("node1", node2)
node0 = Node("node0", node1)
new_head = solution(node0, 1)
| true | true |
f728047ed3f41d811f58d70ae10b6265a2be9524 | 2,529 | py | Python | tests/test_transport_datagram.py | zentropi/python-zentropi | 96cf714b1e0eeb7ee887298eca0f1c92e8b6958e | [
"BSD-3-Clause"
] | 14 | 2017-04-21T05:47:02.000Z | 2018-10-23T21:28:19.000Z | tests/test_transport_datagram.py | zentropi/python-zentropi | 96cf714b1e0eeb7ee887298eca0f1c92e8b6958e | [
"BSD-3-Clause"
] | 22 | 2017-04-11T23:35:16.000Z | 2017-05-20T04:32:44.000Z | tests/test_transport_datagram.py | zentropi/python-zentropi | 96cf714b1e0eeb7ee887298eca0f1c92e8b6958e | [
"BSD-3-Clause"
] | 5 | 2017-04-05T23:21:05.000Z | 2017-10-29T15:28:05.000Z | import pytest
from zentropi import Agent
from zentropi import Frame
from zentropi.transport import datagram
class MockDatagram(object):
def __init__(self, login_ok=True, send_ok=True, recv_ok=True):
self._login_ok = login_ok
self._send_ok = send_ok
self._recv_ok = recv_ok
self.frame = None
async def connect(self, endpoint):
return self
async def close(self):
pass
async def send(self, data):
if not self._send_ok:
raise ConnectionAbortedError()
frame = Frame.from_json(data.decode('utf-8'))
if frame.name == 'login':
if self._login_ok:
self.frame = frame.reply('login-ok').to_json().encode('utf-8')
else:
self.frame = frame.reply('login-failed').to_json().encode('utf-8')
return
self.frame = data
async def recv(self):
if not self._recv_ok:
raise ConnectionAbortedError()
return self.frame, '127.0.0.1:9999'
@pytest.mark.asyncio
async def test_datagram_transport(monkeypatch):
monkeypatch.setattr(datagram, 'asyncio_dgram', MockDatagram())
dt = datagram.DatagramTransport()
frame = Frame('test-frame')
await dt.connect('dgram://127.0.0.1:6789/', 'test-token')
assert dt.connected is True
await dt.send(frame)
assert dt.connection.frame
frame_recv = await dt.recv()
assert frame_recv.name == 'test-frame'
await dt.close()
assert dt.connected is False
@pytest.mark.asyncio
@pytest.mark.xfail(raises=PermissionError)
async def test_datagram_transport_login_fail(monkeypatch):
monkeypatch.setattr(datagram, 'asyncio_dgram', MockDatagram(login_ok=False))
dt = datagram.DatagramTransport()
frame = Frame('test-frame')
await dt.connect('dgram://127.0.0.1:6789/', 'test-token')
@pytest.mark.asyncio
@pytest.mark.xfail(raises=ConnectionError)
async def test_datagram_transport_send_fail(monkeypatch):
monkeypatch.setattr(datagram, 'asyncio_dgram', MockDatagram(send_ok=False))
dt = datagram.DatagramTransport()
frame = Frame('test-frame')
await dt.connect('dgram://127.0.0.1:6789/', 'test-token')
@pytest.mark.asyncio
@pytest.mark.xfail(raises=ConnectionError)
async def test_datagram_transport_recv_fail(monkeypatch):
monkeypatch.setattr(datagram, 'asyncio_dgram', MockDatagram(recv_ok=False))
dt = datagram.DatagramTransport()
frame = Frame('test-frame')
await dt.connect('dgram://127.0.0.1:6789/', 'test-token')
| 31.6125 | 82 | 0.680506 | import pytest
from zentropi import Agent
from zentropi import Frame
from zentropi.transport import datagram
class MockDatagram(object):
def __init__(self, login_ok=True, send_ok=True, recv_ok=True):
self._login_ok = login_ok
self._send_ok = send_ok
self._recv_ok = recv_ok
self.frame = None
async def connect(self, endpoint):
return self
async def close(self):
pass
async def send(self, data):
if not self._send_ok:
raise ConnectionAbortedError()
frame = Frame.from_json(data.decode('utf-8'))
if frame.name == 'login':
if self._login_ok:
self.frame = frame.reply('login-ok').to_json().encode('utf-8')
else:
self.frame = frame.reply('login-failed').to_json().encode('utf-8')
return
self.frame = data
async def recv(self):
if not self._recv_ok:
raise ConnectionAbortedError()
return self.frame, '127.0.0.1:9999'
@pytest.mark.asyncio
async def test_datagram_transport(monkeypatch):
monkeypatch.setattr(datagram, 'asyncio_dgram', MockDatagram())
dt = datagram.DatagramTransport()
frame = Frame('test-frame')
await dt.connect('dgram://127.0.0.1:6789/', 'test-token')
assert dt.connected is True
await dt.send(frame)
assert dt.connection.frame
frame_recv = await dt.recv()
assert frame_recv.name == 'test-frame'
await dt.close()
assert dt.connected is False
@pytest.mark.asyncio
@pytest.mark.xfail(raises=PermissionError)
async def test_datagram_transport_login_fail(monkeypatch):
monkeypatch.setattr(datagram, 'asyncio_dgram', MockDatagram(login_ok=False))
dt = datagram.DatagramTransport()
frame = Frame('test-frame')
await dt.connect('dgram://127.0.0.1:6789/', 'test-token')
@pytest.mark.asyncio
@pytest.mark.xfail(raises=ConnectionError)
async def test_datagram_transport_send_fail(monkeypatch):
monkeypatch.setattr(datagram, 'asyncio_dgram', MockDatagram(send_ok=False))
dt = datagram.DatagramTransport()
frame = Frame('test-frame')
await dt.connect('dgram://127.0.0.1:6789/', 'test-token')
@pytest.mark.asyncio
@pytest.mark.xfail(raises=ConnectionError)
async def test_datagram_transport_recv_fail(monkeypatch):
monkeypatch.setattr(datagram, 'asyncio_dgram', MockDatagram(recv_ok=False))
dt = datagram.DatagramTransport()
frame = Frame('test-frame')
await dt.connect('dgram://127.0.0.1:6789/', 'test-token')
| true | true |
f72805554c757480caa6c16f5ee9bd0c52c96825 | 19,827 | py | Python | ipython/3_Training_Predicting/prnn_cb12_train_predict.py | samuelru/session-knn-ae | c6232667dbe57f82391d487875b52f651ca08a21 | [
"MIT"
] | 6 | 2019-12-08T12:58:02.000Z | 2021-06-29T23:52:03.000Z | ipython/3_Training_Predicting/prnn_cb12_train_predict.py | samuelru/session-knn-ae | c6232667dbe57f82391d487875b52f651ca08a21 | [
"MIT"
] | 1 | 2021-01-20T14:52:02.000Z | 2022-02-24T08:43:11.000Z | ipython/3_Training_Predicting/prnn_cb12_train_predict.py | samuelru/session-knn-ae | c6232667dbe57f82391d487875b52f651ca08a21 | [
"MIT"
] | 5 | 2019-12-08T13:09:03.000Z | 2020-09-04T04:53:51.000Z | from keras.layers import Input, Dense, concatenate
from keras.layers.recurrent import GRU
from keras.utils import plot_model
from keras.models import Model, load_model
from keras.callbacks import ModelCheckpoint
import keras
import pandas as pd
import numpy as np
import keras.backend as K
from keras.utils import to_categorical
from keras.losses import categorical_crossentropy
from multiprocessing import Pool, cpu_count
import pickle
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
dataset = "cb12/"
path = "../../data/"
interim_path = path + dataset + "interim/"
processed_path = path + dataset + "processed/"
model_path = "models/"
model_path_valid = "models/valid/"
def TOP1(y_true, y_pred):
y1 = y_pred * y_true
y2 = K.sum(y1, axis=1)[:, np.newaxis]
y3 = y_true - y1
return (K.sum(K.sigmoid(y_pred - y2)) + y3 * y3) / tf.cast(tf.shape(y_true)[0], tf.float32)
loss = TOP1
def create_prnn_model(left_input_size, right_input_size, batch_size = 512, hidden_units = 100, o_activation='softmax', lr = 0.001):
emb_size = 50
size = emb_size
# left input - item vector
input_left = Input(batch_shape=(batch_size, 1, left_input_size), name='input_left')
gru_left, gru_left_states = GRU(hidden_units, stateful=True, return_state=True, name='gru_left')(input_left)
# right input - feature vector
input_right = Input(batch_shape=(batch_size, 1, right_input_size), name='input_right')
gru_right, gru_right_states = GRU(hidden_units, stateful=True, return_state=True, name='gru_right')(input_right)
# merging both layers and creating the model
merged = concatenate([gru_left, gru_right])
#change softmax per another activation funciton?
output = Dense(left_input_size, activation=o_activation, name='output')(merged)
model = Model(inputs=[input_left, input_right], outputs=output, name='gru4rec')
encoder = Model(inputs=[input_left, input_right], outputs=merged)
# define model's optimizer
#optimizer = optim.Optimizer(optimizer=self.optimizer, lr=self.lr)
#opt = keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
opt = keras.optimizers.Adagrad(lr=lr)
# define model's loss function --> implement here the top1 loss function
# loss_function = loss.LossFunction(loss_type=self.loss_function)
#model.compile(loss=loss_function, optimizer=opt, metrics=['accuracy'])
model.compile(loss=loss, optimizer=opt, metrics=['accuracy'])
filepath = model_path_valid + 'prnn_cb12_checkpoint.h5'
checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=2, save_best_only=True, mode='min')
callbacks_list = []
model.summary()
#plot_model(model, show_shapes=True, to_file='rnn-structure.png')
return model, encoder
def get_states(model):
#return the actual states of the layers
return [K.get_value(s) for s,_ in model.state_updates]
def freeze_layer(model, layer_name, lr):
if layer_name == 'gru_left':
# gru left layer will not be trained this mini batch
model.get_layer(layer_name).trainable = False
# but gru right will
model.get_layer('gru_right').trainable = True
elif layer_name == 'gru_right':
# gru right layer will not be trained this mini batch
model.get_layer(layer_name).trainable = False
# but gru left will
model.get_layer('gru_left').trainable = True
else:
raise NotImplementedError
# opt = keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
opt = keras.optimizers.Adagrad(lr=lr)
model.compile(loss=loss, optimizer=opt, metrics=['accuracy'])
return model
class SessionDataset:
"""Credit to yhs-968/pyGRU4REC."""
def __init__(self, data, sep='\t', session_key='session_id', item_key='item_id', time_key='created_at', n_samples=-1, itemmap=None, time_sort=False):
"""
Args:
path: path of the csv file
sep: separator for the csv
session_key, item_key, time_key: name of the fields corresponding to the sessions, items, time
n_samples: the number of samples to use. If -1, use the whole dataset.
itemmap: mapping between item IDs and item indices
time_sort: whether to sort the sessions by time or not
"""
self.df = data
self.session_key = session_key
self.item_key = item_key
self.time_key = time_key
self.time_sort = time_sort
self.add_item_indices(itemmap=itemmap)
self.df.sort_values([session_key, time_key], inplace=True)
# Sort the df by time, and then by session ID. That is, df is sorted by session ID and
# clicks within a session are next to each other, where the clicks within a session are time-ordered.
self.click_offsets = self.get_click_offsets()
#array of the positions where there is a change of session.
#len = len(session_idx_arr) + 1
self.session_idx_arr = self.order_session_idx()
#array of sessions [0 1 2 3 4 .... n-1]
def get_click_offsets(self):
"""
Return the offsets of the beginning clicks of each session IDs,
where the offset is calculated against the first click of the first session ID.
"""
offsets = np.zeros(self.df[self.session_key].nunique() + 1, dtype=np.int32)
# group & sort the df by session_key and get the offset values
offsets[1:] = self.df.groupby(self.session_key).size().cumsum()
return offsets
def order_session_idx(self):
""" Order the session indices """
if self.time_sort:
# starting time for each sessions, sorted by session IDs
sessions_start_time = self.df.groupby(self.session_key)[self.time_key].min().values
# order the session indices by session starting times
session_idx_arr = np.argsort(sessions_start_time)
else:
session_idx_arr = np.arange(self.df[self.session_key].nunique())
return session_idx_arr
def add_item_indices(self, itemmap=None):
"""
Add item index column named "item_idx" to the df
Args:
itemmap (pd.DataFrame): mapping between the item Ids and indices
"""
if itemmap is None:
item_ids = self.df[self.item_key].unique() # unique item ids
item2idx = pd.Series(data=np.arange(len(item_ids)),
index=item_ids)
itemmap = pd.DataFrame({self.item_key:item_ids,
'item_idx':item2idx[item_ids].values})
self.itemmap = itemmap
self.df = pd.merge(self.df, self.itemmap, on=self.item_key, how='inner')
@property
def items(self):
return self.itemmap.item_id.unique()
class SessionDataLoader:
"""Credit to yhs-968/pyGRU4REC."""
def __init__(self, dataset, batch_size):
"""
A class for creating session-parallel mini-batches.
Args:
dataset (SessionDataset): the session dataset to generate the batches from
batch_size (int): size of the batch
"""
self.dataset = dataset
self.batch_size = batch_size
self.done_sessions_counter = 0
def __iter__(self):
""" Returns the iterator for producing session-parallel training mini-batches.
Yields:
input (B,): Item indices that will be encoded as one-hot vectors later.
target (B,): a Variable that stores the target item indices
masks: Numpy array indicating the positions of the sessions to be terminated
"""
df = self.dataset.df
session_key='session_id'
item_key='item_id'
time_key='created_at'
self.n_items = df[item_key].nunique()
click_offsets = self.dataset.click_offsets
#print(click_offsets)
session_idx_arr = self.dataset.session_idx_arr
#print(session_idx_arr)
iters = np.arange(self.batch_size)
#iters = np.arange(1)
maxiter = iters.max()
start = click_offsets[session_idx_arr[iters]]
end = click_offsets[session_idx_arr[iters] + 1]
#print(start)
#print(end)
mask = [] # indicator for the sessions to be terminated
finished = False
while not finished:
#minimum lenght of all the sessions
minlen = (end - start).min()
# Item indices (for embedding) for clicks where the first sessions start
idx_target = df.item_idx.values[start]
for i in range(minlen - 1):
# Build inputs & targets
idx_input = idx_target
idx_target = df.item_idx.values[start + i + 1]
inp = idx_input
target = idx_target
yield inp, target, mask
# click indices where a particular session meets second-to-last element
start = start + (minlen - 1)
# see if how many sessions should terminate
mask = np.arange(len(iters))[(end - start) <= 1]
self.done_sessions_counter = len(mask)
for idx in mask:
maxiter += 1
if maxiter >= len(click_offsets) - 1:
finished = True
break
# update the next starting/ending point
iters[idx] = maxiter
start[idx] = click_offsets[session_idx_arr[maxiter]]
end[idx] = click_offsets[session_idx_arr[maxiter] + 1]
def train_prnn(model, lr, loader, layer_freezing_enabled = False, num_epochs = 10):
for epoch in range(0, num_epochs):
print("Epoch: " + str(epoch+1))
epoch_loss = 0
i = 0
for feat, target, mask in loader:
#feat = np array size BATCH_SIZE with the item indexes of the first items of the first BATCH_SIZE sessions
#comvert feat to an array size (BATCH_SIZE, 26723) of one hot encoding the indes with loader.n_items
input_oh = to_categorical(feat, num_classes=loader.n_items)
#convert from shape (BATCH_SIZE, 26723) to (BATCH_SIZE, 1, 26723)
input_oh = np.expand_dims(input_oh, axis=1)
# with the argmax function you get back again the feat/target np array (arg_input = feat)
### arg_input = np.argmax(to_categorical(feat, num_classes=loader.n_items), axis=1)
### arg_output = np.argmax(to_categorical(target, num_classes=loader.n_items), axis=1)
input_feature = np.array([])
for line in feat:
#result = int(mapitem[(mapitem.item_idx == line)].item_id.values)
result = str(mapitem[(mapitem.item_idx == line)].item_id.values[0])
#print(result)
# use empty feature vec if missing
feature_vector = empty_feature_vec
if result in item_encodings.keys():
feature_vector = item_encodings[result]
input_feature = np.append(input_feature, feature_vector)
input_feature = input_feature.reshape(batch_size, 1, feature_size)
#target = np array size BATCH_SIZE with the item indexes of the TARGET items of the feat array items
target_oh = to_categorical(target, num_classes=loader.n_items)
#calculate the loss between the input and the expected output
if layer_freezing_enabled:
if i % 2 is 0:
model = freeze_layer(model, 'gru_left', lr = lr)
else:
model = freeze_layer(model, 'gru_right', lr = lr)
tr_loss = model.train_on_batch([input_oh, input_feature], target_oh)
epoch_loss += tr_loss[0]
i = i + 1
print("Epoch loss: " + str(epoch_loss))
return model
# # Set data for final training
# set data
train_path = '../../data/' + dataset + 'processed/train_14d.csv'
train = pd.read_csv(train_path, sep='\t')[['session_id', 'item_id', 'created_at']]
interactions = pd.read_csv('../../data/' + dataset + 'interim/interactions.csv', header=0, sep='\t')
items = pd.read_csv('../../data/' + dataset + 'interim/items.csv', header=0, sep='\t')
view_fields = ["item_id", "state", "ReqTopic", "DescTopic", "TitTopic"]
common_items = items.merge(interactions, on=['item_id'])[view_fields].drop_duplicates()
item_count = len(train['item_id'].unique())
print(item_count)
session_count = len(train['created_at'].unique())
print(len(common_items))
# CB12 items need to be converted to dummies
common = common_items
common["item_id"] = common["item_id"].astype('str')
common["DescTopic"] = common["DescTopic"].astype('str')
common["TitTopic"] = common["TitTopic"].astype('str')
common["ReqTopic"] = common["ReqTopic"].astype('str')
df2 = pd.DataFrame(index=common.index)
s1 = pd.get_dummies(common["state"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="state").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
s1 = pd.get_dummies(common["ReqTopic"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="ReqTopic").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
df2 = df2.drop(["state_", "ReqTopic_"], axis=1, errors="ignore")
s1 = pd.get_dummies(common["DescTopic"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="DescTopic").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
s1 = pd.get_dummies(common["TitTopic"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="TitTopic").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
df2 = df2.drop(["DescTopic_", "TitTopic_"], axis=1, errors="ignore")
common = common.drop(["state", "ReqTopic", "DescTopic", "TitTopic"], axis=1)
df2 = pd.concat([common, df2], axis=1)
one_hot = df2
print(one_hot.shape)
# number of content features per item
feature_size = one_hot.shape[1] - 1
item_encodings = {}
for index, row in one_hot.iterrows():
item_id = row["item_id"]
item_encodings[item_id] = row.values[1:]
print(len(item_encodings))
empty_feature_vec = np.zeros(feature_size, dtype=int)
# load data
batch_size = 512
train_dataset = SessionDataset(train)
loader = SessionDataLoader(train_dataset, batch_size=batch_size)
mapitem = loader.dataset.itemmap
# # Train final model
# In[ ]:
# use best params
ls = 1000
act = "softmax"
lr = 0.001
# define model
model, encoder = create_prnn_model(item_count, feature_size, batch_size=batch_size, hidden_units = ls, o_activation = act, lr = lr)
# train model
model_name = "cb12_prnn_a_" + act + "_ls_" + str(ls) + "_lr_" + str(lr) + ".model2"
print("Starting to train: " + model_name)
model = train_prnn(model, lr, loader)
pickle.dump(model, open(model_path + model_name, 'wb'), protocol=4)
print("Stored model in: " + model_path + model_name)
# # Generate predictions
def predict_function(sid, test_session, pr, item_idx_map, idx_item_map, cut_off=20,
session_key='session_id', item_key='item_id', time_key='created_at'):
test_session.sort_values([time_key], inplace=True)
# get first and only session_id (as we grouped it before calling this method)
session_id = test_session[session_key].unique()[0]
log_columns = ["session_id", "input_items", "input_count", "position", "remaining_items", "remaining_count", "predictions"]
log_df = pd.DataFrame(columns = log_columns)
session_length = len(test_session)
il = a = np.zeros((batch_size, 1, len(item_idx_map)))
ir = a = np.zeros((batch_size, 1, 115))
for i in range(session_length -1):
# use current item as reference point (rest is for testing)
current_item_id = test_session[item_key].values[i]
item_vec = np.zeros(len(item_idx_map), dtype=int)
item_idx = item_idx_map[current_item_id]
item_vec[item_idx] = 1
# set vector in batch input
il[i, 0] = item_vec
#item_features = item_encodings[current_item_id]
# use empty feature vec if missing
item_features = empty_feature_vec
if current_item_id in item_encodings.keys():
item_features = item_encodings[result]
#item_features = item_features.reshape(1,1, len(item_features))
ir[i, 0] = item_features
# do batch prediction
pred = model.predict([il, ir], batch_size=batch_size)
# for every subsession prediction
for i in range(session_length-1):
preds = pred[i]
topn_idx_preds = preds.argsort()[-cut_off:][::-1]
predictions = []
# for every recommended item index
for item_idx in topn_idx_preds:
pred_item = idx_item_map[item_idx]
predictions.append(pred_item)
current_input_set = test_session[item_key].values[:i+1]
remaining_test_set = test_session[item_key].values[i+1:]
position = "MID"
if i == 0:
position = "FIRST"
if len(remaining_test_set) == 1:
position = "LAST"
log_df = log_df.append({
"session_id": sid,
"input_items": ','.join(map(str, current_input_set)),
"input_count": len(current_input_set),
"position": position,
"remaining_items": ','.join(map(str, remaining_test_set)),
"remaining_count": len(remaining_test_set),
"predictions": ','.join(map(str, predictions))
}, ignore_index=True)
log_df['input_count'] = log_df['input_count'].astype(int)
log_df['remaining_count'] = log_df['remaining_count'].astype(int)
return log_df
# In[ ]:
import keras.losses
keras.losses.TOP1 = TOP1
print("Preparing train data...")
train_dataset = SessionDataset(train)
loader = SessionDataLoader(train_dataset, batch_size=batch_size)
test_path = '../../data/' + dataset + 'processed/test_14d.csv'
test = pd.read_csv(test_path, sep='\t')[['session_id', 'item_id', 'created_at']]
test_dataset = SessionDataset(test)
test_generator = SessionDataLoader(test_dataset, batch_size=batch_size)
session_groups = test.groupby("session_id")
mapitem = loader.dataset.itemmap
item_idx_map = {}
idx_item_map = {}
for index, row in mapitem.iterrows():
item_id = row["item_id"]
item_idx = row["item_idx"]
item_idx_map[item_id] = item_idx
idx_item_map[item_idx] = item_id
predict_path = "../../data/cb12/interim/predict/base/"
model_name = "cb12_prnn_a_" + act + "_ls_" + str(ls) + "_lr_" + str(lr) + ".model2"
model = pickle.load(open(model_path + model_name, 'rb'))
print("Loaded: " + model_name)
res_list = []
# predict
report_freq = len(session_groups) // 5
count = 0
for sid, session in session_groups:
pred_df = predict_function(sid, session, model, item_idx_map, idx_item_map)
res_list.append(pred_df)
# reset states
model.get_layer('gru_left').reset_states()
model.get_layer('gru_right').reset_states()
# print progress
count += 1
if count % report_freq == 0:
print("Predicted for " + str(count) + " sessions. " + str(len(session_groups) - count) + " sessions to go." )
# concat results
res = pd.concat(res_list)
res = res.reindex(columns = ["session_id", "input_items", "input_count", "position", "remaining_items", "remaining_count", "predictions"])
res.to_csv(predict_path + "test_14d_prnn2.csv", sep='\t')
print("Stored predictions: " + predict_path + "test_14d_prnn2.csv")
# In[ ]:
| 37.338983 | 153 | 0.643214 | from keras.layers import Input, Dense, concatenate
from keras.layers.recurrent import GRU
from keras.utils import plot_model
from keras.models import Model, load_model
from keras.callbacks import ModelCheckpoint
import keras
import pandas as pd
import numpy as np
import keras.backend as K
from keras.utils import to_categorical
from keras.losses import categorical_crossentropy
from multiprocessing import Pool, cpu_count
import pickle
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
dataset = "cb12/"
path = "../../data/"
interim_path = path + dataset + "interim/"
processed_path = path + dataset + "processed/"
model_path = "models/"
model_path_valid = "models/valid/"
def TOP1(y_true, y_pred):
y1 = y_pred * y_true
y2 = K.sum(y1, axis=1)[:, np.newaxis]
y3 = y_true - y1
return (K.sum(K.sigmoid(y_pred - y2)) + y3 * y3) / tf.cast(tf.shape(y_true)[0], tf.float32)
loss = TOP1
def create_prnn_model(left_input_size, right_input_size, batch_size = 512, hidden_units = 100, o_activation='softmax', lr = 0.001):
emb_size = 50
size = emb_size
input_left = Input(batch_shape=(batch_size, 1, left_input_size), name='input_left')
gru_left, gru_left_states = GRU(hidden_units, stateful=True, return_state=True, name='gru_left')(input_left)
input_right = Input(batch_shape=(batch_size, 1, right_input_size), name='input_right')
gru_right, gru_right_states = GRU(hidden_units, stateful=True, return_state=True, name='gru_right')(input_right)
merged = concatenate([gru_left, gru_right])
output = Dense(left_input_size, activation=o_activation, name='output')(merged)
model = Model(inputs=[input_left, input_right], outputs=output, name='gru4rec')
encoder = Model(inputs=[input_left, input_right], outputs=merged)
#optimizer = optim.Optimizer(optimizer=self.optimizer, lr=self.lr)
#opt = keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
opt = keras.optimizers.Adagrad(lr=lr)
# define model's loss function --> implement here the top1 loss function
model.compile(loss=loss, optimizer=opt, metrics=['accuracy'])
filepath = model_path_valid + 'prnn_cb12_checkpoint.h5'
checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=2, save_best_only=True, mode='min')
callbacks_list = []
model.summary()
return model, encoder
def get_states(model):
return [K.get_value(s) for s,_ in model.state_updates]
def freeze_layer(model, layer_name, lr):
if layer_name == 'gru_left':
model.get_layer(layer_name).trainable = False
model.get_layer('gru_right').trainable = True
elif layer_name == 'gru_right':
model.get_layer(layer_name).trainable = False
model.get_layer('gru_left').trainable = True
else:
raise NotImplementedError
opt = keras.optimizers.Adagrad(lr=lr)
model.compile(loss=loss, optimizer=opt, metrics=['accuracy'])
return model
class SessionDataset:
def __init__(self, data, sep='\t', session_key='session_id', item_key='item_id', time_key='created_at', n_samples=-1, itemmap=None, time_sort=False):
self.df = data
self.session_key = session_key
self.item_key = item_key
self.time_key = time_key
self.time_sort = time_sort
self.add_item_indices(itemmap=itemmap)
self.df.sort_values([session_key, time_key], inplace=True)
self.click_offsets = self.get_click_offsets()
self.session_idx_arr = self.order_session_idx()
def get_click_offsets(self):
offsets = np.zeros(self.df[self.session_key].nunique() + 1, dtype=np.int32)
offsets[1:] = self.df.groupby(self.session_key).size().cumsum()
return offsets
def order_session_idx(self):
if self.time_sort:
sessions_start_time = self.df.groupby(self.session_key)[self.time_key].min().values
session_idx_arr = np.argsort(sessions_start_time)
else:
session_idx_arr = np.arange(self.df[self.session_key].nunique())
return session_idx_arr
def add_item_indices(self, itemmap=None):
if itemmap is None:
item_ids = self.df[self.item_key].unique()
item2idx = pd.Series(data=np.arange(len(item_ids)),
index=item_ids)
itemmap = pd.DataFrame({self.item_key:item_ids,
'item_idx':item2idx[item_ids].values})
self.itemmap = itemmap
self.df = pd.merge(self.df, self.itemmap, on=self.item_key, how='inner')
@property
def items(self):
return self.itemmap.item_id.unique()
class SessionDataLoader:
def __init__(self, dataset, batch_size):
self.dataset = dataset
self.batch_size = batch_size
self.done_sessions_counter = 0
def __iter__(self):
df = self.dataset.df
session_key='session_id'
item_key='item_id'
time_key='created_at'
self.n_items = df[item_key].nunique()
click_offsets = self.dataset.click_offsets
session_idx_arr = self.dataset.session_idx_arr
iters = np.arange(self.batch_size)
maxiter = iters.max()
start = click_offsets[session_idx_arr[iters]]
end = click_offsets[session_idx_arr[iters] + 1]
mask = []
finished = False
while not finished:
minlen = (end - start).min()
idx_target = df.item_idx.values[start]
for i in range(minlen - 1):
idx_input = idx_target
idx_target = df.item_idx.values[start + i + 1]
inp = idx_input
target = idx_target
yield inp, target, mask
start = start + (minlen - 1)
mask = np.arange(len(iters))[(end - start) <= 1]
self.done_sessions_counter = len(mask)
for idx in mask:
maxiter += 1
if maxiter >= len(click_offsets) - 1:
finished = True
break
iters[idx] = maxiter
start[idx] = click_offsets[session_idx_arr[maxiter]]
end[idx] = click_offsets[session_idx_arr[maxiter] + 1]
def train_prnn(model, lr, loader, layer_freezing_enabled = False, num_epochs = 10):
for epoch in range(0, num_epochs):
print("Epoch: " + str(epoch+1))
epoch_loss = 0
i = 0
for feat, target, mask in loader:
input_oh = to_categorical(feat, num_classes=loader.n_items)
input_oh = np.expand_dims(input_oh, axis=1)
.keys():
feature_vector = item_encodings[result]
input_feature = np.append(input_feature, feature_vector)
input_feature = input_feature.reshape(batch_size, 1, feature_size)
target_oh = to_categorical(target, num_classes=loader.n_items)
if layer_freezing_enabled:
if i % 2 is 0:
model = freeze_layer(model, 'gru_left', lr = lr)
else:
model = freeze_layer(model, 'gru_right', lr = lr)
tr_loss = model.train_on_batch([input_oh, input_feature], target_oh)
epoch_loss += tr_loss[0]
i = i + 1
print("Epoch loss: " + str(epoch_loss))
return model
' + dataset + 'processed/train_14d.csv'
train = pd.read_csv(train_path, sep='\t')[['session_id', 'item_id', 'created_at']]
interactions = pd.read_csv('../../data/' + dataset + 'interim/interactions.csv', header=0, sep='\t')
items = pd.read_csv('../../data/' + dataset + 'interim/items.csv', header=0, sep='\t')
view_fields = ["item_id", "state", "ReqTopic", "DescTopic", "TitTopic"]
common_items = items.merge(interactions, on=['item_id'])[view_fields].drop_duplicates()
item_count = len(train['item_id'].unique())
print(item_count)
session_count = len(train['created_at'].unique())
print(len(common_items))
common = common_items
common["item_id"] = common["item_id"].astype('str')
common["DescTopic"] = common["DescTopic"].astype('str')
common["TitTopic"] = common["TitTopic"].astype('str')
common["ReqTopic"] = common["ReqTopic"].astype('str')
df2 = pd.DataFrame(index=common.index)
s1 = pd.get_dummies(common["state"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="state").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
s1 = pd.get_dummies(common["ReqTopic"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="ReqTopic").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
df2 = df2.drop(["state_", "ReqTopic_"], axis=1, errors="ignore")
s1 = pd.get_dummies(common["DescTopic"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="DescTopic").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
s1 = pd.get_dummies(common["TitTopic"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="TitTopic").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
df2 = df2.drop(["DescTopic_", "TitTopic_"], axis=1, errors="ignore")
common = common.drop(["state", "ReqTopic", "DescTopic", "TitTopic"], axis=1)
df2 = pd.concat([common, df2], axis=1)
one_hot = df2
print(one_hot.shape)
feature_size = one_hot.shape[1] - 1
item_encodings = {}
for index, row in one_hot.iterrows():
item_id = row["item_id"]
item_encodings[item_id] = row.values[1:]
print(len(item_encodings))
empty_feature_vec = np.zeros(feature_size, dtype=int)
batch_size = 512
train_dataset = SessionDataset(train)
loader = SessionDataLoader(train_dataset, batch_size=batch_size)
mapitem = loader.dataset.itemmap
t = "softmax"
lr = 0.001
model, encoder = create_prnn_model(item_count, feature_size, batch_size=batch_size, hidden_units = ls, o_activation = act, lr = lr)
model_name = "cb12_prnn_a_" + act + "_ls_" + str(ls) + "_lr_" + str(lr) + ".model2"
print("Starting to train: " + model_name)
model = train_prnn(model, lr, loader)
pickle.dump(model, open(model_path + model_name, 'wb'), protocol=4)
print("Stored model in: " + model_path + model_name)
(sid, test_session, pr, item_idx_map, idx_item_map, cut_off=20,
session_key='session_id', item_key='item_id', time_key='created_at'):
test_session.sort_values([time_key], inplace=True)
session_id = test_session[session_key].unique()[0]
log_columns = ["session_id", "input_items", "input_count", "position", "remaining_items", "remaining_count", "predictions"]
log_df = pd.DataFrame(columns = log_columns)
session_length = len(test_session)
il = a = np.zeros((batch_size, 1, len(item_idx_map)))
ir = a = np.zeros((batch_size, 1, 115))
for i in range(session_length -1):
current_item_id = test_session[item_key].values[i]
item_vec = np.zeros(len(item_idx_map), dtype=int)
item_idx = item_idx_map[current_item_id]
item_vec[item_idx] = 1
il[i, 0] = item_vec
item_features = empty_feature_vec
if current_item_id in item_encodings.keys():
item_features = item_encodings[result]
ir[i, 0] = item_features
pred = model.predict([il, ir], batch_size=batch_size)
for i in range(session_length-1):
preds = pred[i]
topn_idx_preds = preds.argsort()[-cut_off:][::-1]
predictions = []
for item_idx in topn_idx_preds:
pred_item = idx_item_map[item_idx]
predictions.append(pred_item)
current_input_set = test_session[item_key].values[:i+1]
remaining_test_set = test_session[item_key].values[i+1:]
position = "MID"
if i == 0:
position = "FIRST"
if len(remaining_test_set) == 1:
position = "LAST"
log_df = log_df.append({
"session_id": sid,
"input_items": ','.join(map(str, current_input_set)),
"input_count": len(current_input_set),
"position": position,
"remaining_items": ','.join(map(str, remaining_test_set)),
"remaining_count": len(remaining_test_set),
"predictions": ','.join(map(str, predictions))
}, ignore_index=True)
log_df['input_count'] = log_df['input_count'].astype(int)
log_df['remaining_count'] = log_df['remaining_count'].astype(int)
return log_df
import keras.losses
keras.losses.TOP1 = TOP1
print("Preparing train data...")
train_dataset = SessionDataset(train)
loader = SessionDataLoader(train_dataset, batch_size=batch_size)
test_path = '../../data/' + dataset + 'processed/test_14d.csv'
test = pd.read_csv(test_path, sep='\t')[['session_id', 'item_id', 'created_at']]
test_dataset = SessionDataset(test)
test_generator = SessionDataLoader(test_dataset, batch_size=batch_size)
session_groups = test.groupby("session_id")
mapitem = loader.dataset.itemmap
item_idx_map = {}
idx_item_map = {}
for index, row in mapitem.iterrows():
item_id = row["item_id"]
item_idx = row["item_idx"]
item_idx_map[item_id] = item_idx
idx_item_map[item_idx] = item_id
predict_path = "../../data/cb12/interim/predict/base/"
model_name = "cb12_prnn_a_" + act + "_ls_" + str(ls) + "_lr_" + str(lr) + ".model2"
model = pickle.load(open(model_path + model_name, 'rb'))
print("Loaded: " + model_name)
res_list = []
report_freq = len(session_groups) // 5
count = 0
for sid, session in session_groups:
pred_df = predict_function(sid, session, model, item_idx_map, idx_item_map)
res_list.append(pred_df)
model.get_layer('gru_left').reset_states()
model.get_layer('gru_right').reset_states()
count += 1
if count % report_freq == 0:
print("Predicted for " + str(count) + " sessions. " + str(len(session_groups) - count) + " sessions to go." )
res = pd.concat(res_list)
res = res.reindex(columns = ["session_id", "input_items", "input_count", "position", "remaining_items", "remaining_count", "predictions"])
res.to_csv(predict_path + "test_14d_prnn2.csv", sep='\t')
print("Stored predictions: " + predict_path + "test_14d_prnn2.csv")
| true | true |
f728058691d28517eb5f80d44183878ec58ae0fc | 1,050 | py | Python | Structural/object_adapter.py | TheVikingGent/DesignPatterns4Python | ace9f577d9700fe290d80822230acb8e87833bc2 | [
"MIT"
] | null | null | null | Structural/object_adapter.py | TheVikingGent/DesignPatterns4Python | ace9f577d9700fe290d80822230acb8e87833bc2 | [
"MIT"
] | null | null | null | Structural/object_adapter.py | TheVikingGent/DesignPatterns4Python | ace9f577d9700fe290d80822230acb8e87833bc2 | [
"MIT"
] | null | null | null | # This is the object-based adapter pattern
# It allows us to take an outside class 'StrangeCreature' with a different interface,
# and squeeze that SOB into another hierachy.
# The good thing about the object version of this pattern is that if StrangeCreature had
# a lot of subtypes, we would not need to write an adapter for each subtype.
#(I don't think this is relevant considering Pythons Dynamic Typing, but it's good to know for something like C++ I'm guessing)
import abc
class StrangeCreature(object):
def make_horrible_noise(self):
print("Rawr")
class Animal(object, metaclass=abc.ABCMeta):
@abc.abstractmethod
def make_noise(self):
raise NotImplementedError
class Horse(Animal):
def make_noise(self):
print("Vrinsk")
class Platypus(Animal):
_strange_creature = None
def __init__(self):
self._strange_creature = StrangeCreature()
def make_noise(self):
return self._strange_creature.make_horrible_noise()
p = Platypus()
p.make_noise()
h = Horse()
h.make_noise() | 30 | 127 | 0.728571 |
import abc
class StrangeCreature(object):
def make_horrible_noise(self):
print("Rawr")
class Animal(object, metaclass=abc.ABCMeta):
@abc.abstractmethod
def make_noise(self):
raise NotImplementedError
class Horse(Animal):
def make_noise(self):
print("Vrinsk")
class Platypus(Animal):
_strange_creature = None
def __init__(self):
self._strange_creature = StrangeCreature()
def make_noise(self):
return self._strange_creature.make_horrible_noise()
p = Platypus()
p.make_noise()
h = Horse()
h.make_noise() | true | true |
f728064f24ce70cc0b19b13c3a4c9545b7424ef4 | 849 | py | Python | tests/admin/test_pages.py | KaitoRyouga/CTFd | 827a22e8ce9bdfd43ae0689e6cbcf2a6e253e920 | [
"Apache-2.0"
] | null | null | null | tests/admin/test_pages.py | KaitoRyouga/CTFd | 827a22e8ce9bdfd43ae0689e6cbcf2a6e253e920 | [
"Apache-2.0"
] | null | null | null | tests/admin/test_pages.py | KaitoRyouga/CTFd | 827a22e8ce9bdfd43ae0689e6cbcf2a6e253e920 | [
"Apache-2.0"
] | null | null | null | from tests.helpers import create_ctfd, destroy_ctfd, login_as_user
def test_previewing_pages_works():
"""Test that pages can be previewed properly"""
app = create_ctfd()
with app.app_context():
client = login_as_user(app, name="admin", password="password")
with client.session_transaction() as sess:
data = {
"title": "title",
"route": "route",
"content": "content_testing",
"nonce": sess.get("nonce"),
"draft": "y",
"hidden": "y",
"auth_required": "y",
}
r = client.post("/admin/pages/preview", data=data)
assert r.status_code == 200
resp = r.get_data(as_text=True)
assert "content_testing" in resp
destroy_ctfd(app)
| 31.444444 | 71 | 0.530035 | from tests.helpers import create_ctfd, destroy_ctfd, login_as_user
def test_previewing_pages_works():
app = create_ctfd()
with app.app_context():
client = login_as_user(app, name="admin", password="password")
with client.session_transaction() as sess:
data = {
"title": "title",
"route": "route",
"content": "content_testing",
"nonce": sess.get("nonce"),
"draft": "y",
"hidden": "y",
"auth_required": "y",
}
r = client.post("/admin/pages/preview", data=data)
assert r.status_code == 200
resp = r.get_data(as_text=True)
assert "content_testing" in resp
destroy_ctfd(app)
| true | true |
f72806f1b468e69088235a72960fae80ff004757 | 752 | py | Python | phase2_scripts/p2_inference_test25_1M_epoch16.py | socom20/facebook-image-similarity-challenge-2021 | bf4226241be30cdf99180543f214edf571043e8d | [
"MIT"
] | 8 | 2021-12-02T04:05:59.000Z | 2022-02-23T07:57:22.000Z | phase2_scripts/p2_inference_test25_1M_epoch16.py | socom20/facebook-image-similarity-challenge-2021 | bf4226241be30cdf99180543f214edf571043e8d | [
"MIT"
] | 1 | 2021-12-07T07:05:37.000Z | 2021-12-08T02:24:17.000Z | phase2_scripts/p2_inference_test25_1M_epoch16.py | socom20/facebook-image-similarity-challenge-2021 | bf4226241be30cdf99180543f214edf571043e8d | [
"MIT"
] | 4 | 2021-12-12T09:58:01.000Z | 2022-03-29T05:50:57.000Z | #!/usr/bin/env python
# coding: utf-8
# In[1]:
from model_inference import do_inference
# In[ ]:
from modules.Facebook_AF_model_v25 import ArgsT25_NfNetl1_ImageNet, FacebookModel
ckpt_filename = './checkpoints/smp_test25/FacebookModel_epoch=16_trn_loss_epoch=0.9023_trn_acc_epoch=0.0000_val_loss_epoch=0.4303_val_acc_epoch=0.9911.ckpt'
args = ArgsT25_NfNetl1_ImageNet()
args.BATCH_SIZE = 128
args.N_WORKERS = 7
args.DS_INPUT_DIR = f'./all_datasets/dataset'
args.pretrained_bb = False
args.arc_classnum = 40
args.ALL_FOLDERS = ['query_images', 'reference_images', 'training_images']
args.faiss_gpu_id = 0
args.phase_2 = True
model = FacebookModel(args)
_ = model.restore_checkpoint(ckpt_filename)
do_inference(model, args, ckpt_filename)
| 21.485714 | 156 | 0.793883 |
from model_inference import do_inference
from modules.Facebook_AF_model_v25 import ArgsT25_NfNetl1_ImageNet, FacebookModel
ckpt_filename = './checkpoints/smp_test25/FacebookModel_epoch=16_trn_loss_epoch=0.9023_trn_acc_epoch=0.0000_val_loss_epoch=0.4303_val_acc_epoch=0.9911.ckpt'
args = ArgsT25_NfNetl1_ImageNet()
args.BATCH_SIZE = 128
args.N_WORKERS = 7
args.DS_INPUT_DIR = f'./all_datasets/dataset'
args.pretrained_bb = False
args.arc_classnum = 40
args.ALL_FOLDERS = ['query_images', 'reference_images', 'training_images']
args.faiss_gpu_id = 0
args.phase_2 = True
model = FacebookModel(args)
_ = model.restore_checkpoint(ckpt_filename)
do_inference(model, args, ckpt_filename)
| true | true |
f7280780dc6c97a9f7524378205551ce5bb10c36 | 1,601 | py | Python | migrations/versions/0221_nullable_service_branding.py | tlwr/notifications-api | 88a6b7729edb9be41ce3e7c027f1452b7b6d00d2 | [
"MIT"
] | 51 | 2016-04-03T23:36:17.000Z | 2022-03-21T20:04:52.000Z | migrations/versions/0221_nullable_service_branding.py | tlwr/notifications-api | 88a6b7729edb9be41ce3e7c027f1452b7b6d00d2 | [
"MIT"
] | 1,335 | 2015-12-15T14:28:50.000Z | 2022-03-30T16:24:27.000Z | migrations/versions/0221_nullable_service_branding.py | tlwr/notifications-api | 88a6b7729edb9be41ce3e7c027f1452b7b6d00d2 | [
"MIT"
] | 30 | 2016-01-08T19:05:32.000Z | 2021-12-20T16:37:23.000Z | """
Revision ID: 0221_nullable_service_branding
Revises: 0220_email_brand_type_non_null
Create Date: 2018-08-24 13:36:49.346156
"""
from alembic import op
from app.models import BRANDING_ORG, BRANDING_GOVUK
revision = '0221_nullable_service_branding'
down_revision = '0220_email_brand_type_non_null'
def upgrade():
op.drop_constraint('services_branding_fkey', 'services', type_='foreignkey')
op.drop_index('ix_services_history_branding', table_name='services_history')
op.drop_index('ix_services_branding', table_name='services')
op.alter_column('services_history', 'branding', nullable=True)
op.alter_column('services', 'branding', nullable=True)
op.execute("""
update
email_branding
set
brand_type = '{}'
where
brand_type = '{}'
""".format(BRANDING_ORG, BRANDING_GOVUK))
op.execute("""
delete from
branding_type
where
name = '{}'
""".format(BRANDING_GOVUK))
def downgrade():
op.create_index(op.f('ix_services_branding'), 'services', ['branding'], unique=False)
op.create_index(op.f('ix_services_history_branding'), 'services_history', ['branding'], unique=False)
op.create_foreign_key(None, 'services', 'branding_type', ['branding'], ['name'])
op.alter_column('services', 'branding', nullable=False)
op.alter_column('services_history', 'branding', nullable=False)
op.execute("""
insert into
branding_type
(name)
values
('{}')
""".format(BRANDING_GOVUK))
| 27.603448 | 105 | 0.656465 | from alembic import op
from app.models import BRANDING_ORG, BRANDING_GOVUK
revision = '0221_nullable_service_branding'
down_revision = '0220_email_brand_type_non_null'
def upgrade():
op.drop_constraint('services_branding_fkey', 'services', type_='foreignkey')
op.drop_index('ix_services_history_branding', table_name='services_history')
op.drop_index('ix_services_branding', table_name='services')
op.alter_column('services_history', 'branding', nullable=True)
op.alter_column('services', 'branding', nullable=True)
op.execute("""
update
email_branding
set
brand_type = '{}'
where
brand_type = '{}'
""".format(BRANDING_ORG, BRANDING_GOVUK))
op.execute("""
delete from
branding_type
where
name = '{}'
""".format(BRANDING_GOVUK))
def downgrade():
op.create_index(op.f('ix_services_branding'), 'services', ['branding'], unique=False)
op.create_index(op.f('ix_services_history_branding'), 'services_history', ['branding'], unique=False)
op.create_foreign_key(None, 'services', 'branding_type', ['branding'], ['name'])
op.alter_column('services', 'branding', nullable=False)
op.alter_column('services_history', 'branding', nullable=False)
op.execute("""
insert into
branding_type
(name)
values
('{}')
""".format(BRANDING_GOVUK))
| true | true |
f728078abdd363c3b5a9fa5e8cb21ce1ecaa6d60 | 18,868 | py | Python | hashsum.py | avalentino/hashsum | 1bc36e78439ee066626d7875fc4e8ae20f0aa2f8 | [
"BSD-3-Clause"
] | 1 | 2016-01-12T13:23:16.000Z | 2016-01-12T13:23:16.000Z | hashsum.py | avalentino/hashsum | 1bc36e78439ee066626d7875fc4e8ae20f0aa2f8 | [
"BSD-3-Clause"
] | 1 | 2021-07-17T19:37:10.000Z | 2021-07-17T19:37:10.000Z | hashsum.py | avalentino/hashsum | 1bc36e78439ee066626d7875fc4e8ae20f0aa2f8 | [
"BSD-3-Clause"
] | 2 | 2021-07-17T18:50:53.000Z | 2021-07-30T03:48:27.000Z | #!/usr/bin/env python3
"""Compute and check message digest with different hash algorithms.
The sums are computed as described in [1].
When checking, the input should be a former output of this program.
The default mode is to print a line with checksum, a character indicating
input mode ('*' for binary, space for text), and name for each FILE.
[1] https://docs.python.org/3/library/hashlib.html
"""
import io
import os
import re
import sys
import enum
import codecs
import hashlib
import logging
import argparse
import warnings
import functools
try:
from os import EX_OK
except ImportError:
EX_OK = 0
EX_FAILURE = 1
EX_INTERRUPT = 130
try:
import argcomplete
except ImportError:
argcomplete = False
else:
PYTHON_ARGCOMPLETE_OK = True
__version__ = '1.4.2.dev0'
PROG = os.path.splitext(os.path.basename(__file__))[0]
LOGFMT = '%(levelname)s: %(message)s'
DIGEST_LINE_RE = re.compile(
r'^(?P<digest>\w+) (?P<binary>[ *])(?P<path>.+)$')
DIGEST_LINE_BSD_RE = re.compile(
r'^(?P<algo>\w+) ?\((?P<path>.+)\) ?= (?P<digest>\w+)$')
BLOCKSIZE = 1024 * 1024 # 1MB
_QUEUE_LEN = 50 # max 50MB
DEFAULT_ALGO = 'md5'
def blockiter(fd, blocksize=io.DEFAULT_BUFFER_SIZE):
"""Iterate on file-like objects reading blocks of the specified size.
The `fd` parameter must be a binary or text file-like object opened
for reading.
The `blocksize` parameter defaults to `io.DEFAULT_BUFFER_SIZE`.
"""
guard = '' if isinstance(fd, io.TextIOBase) else b''
return iter(functools.partial(fd.read, blocksize), guard)
class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
def __init__(self, errors='strict'):
super().__init__(errors=errors)
self.buffer = b''
self.from_ = os.linesep.encode('ascii')
self.to = b'\n'
def decode(self, data, final=False):
if self.buffer:
output = self.buffer + data
else:
output = data
self.buffer = b''
if len(self.from_) > 1:
assert(len(self.from_) == 2)
lastchar = self.from_[-2:-1]
if output.endswith(lastchar) and not final:
output = output[:-1]
self.buffer = lastchar
output = output.replace(self.from_, self.to)
return output
def reset(self):
super().reset()
self.buffer = b''
def getstate(self):
return self.buffer, 0
def setstate(self, state):
self.buffer = state[0]
class CheckResult(enum.Enum):
OK = 'OK'
FAILURE = 'FAILURE'
READ_FAILURE = 'READ_FAILURE'
BAD_FORMATTING = 'BAD_FORMATTING'
IGNORED = 'IGNORED'
# TODO: inherit form collections.Counter
class CheckResultData:
def __init__(self, n_ok=0, n_failures=0, n_read_failures=0,
n_improperly_formatted=0, n_ignored=0):
self.n_ok = n_ok
self.n_failures = n_failures
self.n_read_failures = n_read_failures
self.n_improperly_formatted = n_improperly_formatted
self.n_ignored = n_ignored
def update(self, ret):
if ret == CheckResult.OK:
self.n_ok += 1
elif ret == CheckResult.FAILURE:
self.n_failures += 1
elif ret == CheckResult.READ_FAILURE:
self.n_read_failures += 1
elif ret == CheckResult.BAD_FORMATTING:
self.n_improperly_formatted += 1
elif ret == CheckResult.IGNORED:
self.n_ignored += 1
else:
raise ValueError(f'unexpected value: {ret}')
def __repr__(self):
keys = [
'n_ok',
'n_failures',
'n_read_failures',
'n_improperly_formatted',
'n_ignored',
]
kvstr = ', '.join(f'{k}={getattr(self, k)}' for k in keys)
return f'CheckResultData({kvstr})'
def _compute_file_checksum_sequential(fd, algo=DEFAULT_ALGO, binary=True):
hash_obj = hashlib.new(algo)
if not binary and os.linesep != '\n':
decoder = IncrementalNewlineDecoder()
else:
decoder = None
for data in blockiter(fd, BLOCKSIZE):
if decoder:
data = decoder.decode(data)
hash_obj.update(data)
if decoder:
data = decoder.decode(b'', final=True)
hash_obj.update(data)
return hash_obj
class HashObjectData:
def __init__(self, hash_obj):
self.block_size = hash_obj.block_size
self.name = hash_obj.name
self.digest_size = hash_obj.digest_size
self._digest = hash_obj.digest()
self._hexdigest = hash_obj.hexdigest()
def digest(self):
return self._digest
def hexdigest(self):
return self._hexdigest
def _worker(tasks, results, algo=DEFAULT_ALGO, decoder=None):
try:
hash_obj = hashlib.new(algo)
for data in iter(tasks.get, None):
if decoder:
data = decoder.decode(data)
hash_obj.update(data)
tasks.task_done()
else:
if decoder:
data = decoder.decode(b'', final=True)
hash_obj.update(data)
tasks.task_done() # for None
results.put(HashObjectData(hash_obj))
except Exception as exc:
results.put(exc)
def _compute_file_checksum_threading(fd, algo=DEFAULT_ALGO, binary=True):
import queue
import threading
if not binary and os.linesep != '\n':
decoder = IncrementalNewlineDecoder()
else:
decoder = None
task_queue = queue.Queue(_QUEUE_LEN)
result_queue = queue.Queue()
args = (task_queue, result_queue, algo, decoder)
worker = threading.Thread(name='worker', target=_worker, args=args)
worker.start()
try:
for data in blockiter(fd, BLOCKSIZE):
task_queue.put(data)
if not result_queue.empty():
break # fail fast
finally:
task_queue.put(None)
result = result_queue.get()
worker.join()
if isinstance(result, Exception):
raise result
return result
class ChecksumVerifier:
def __init__(self, algo=None, quiet=False, status=False, warn=False,
strict=False, multi_thread=False):
self.algo = algo
self.quiet = quiet
self.status = status
self.warn = warn
self.strict = strict
self.multi_thread = multi_thread
self._log = logging.getLogger('hashsum')
def _compute_file_checksum(self, fd, algo, binary):
if self.multi_thread:
return _compute_file_checksum_threading(fd, algo, binary)
else:
return _compute_file_checksum_sequential(fd, algo, binary)
def _check_algorithm_compatibility(self, algo):
if self.algo is not None and self.algo.lower() != algo.lower():
raise ValueError(
'specified hashing algorithm ({}) is different form '
'the one used in the digest file ({})'.format(
self.algo, algo))
def decode_checksum_file_line(self, line):
mobj = DIGEST_LINE_BSD_RE.match(line)
if mobj:
self._check_algorithm_compatibility(mobj.group('algo'))
algo = mobj.group('algo')
path = mobj.group('path')
hexdigest = mobj.group('digest')
binary = True
else:
mobj = DIGEST_LINE_RE.match(line)
if not mobj:
raise ValueError(
f'unable to decode digest line: "{line}"')
path = mobj.group('path')
hexdigest = mobj.group('digest')
binary = True if mobj.group('binary') == '*' else False
if self.algo is None:
msg = f'no algorithm specified: using {DEFAULT_ALGO!r}'
warnings.warn(msg)
# self._log.warning(msg)
algo = DEFAULT_ALGO
else:
algo = self.algo
return path, hexdigest, binary, algo
def process_checksum_file_line(self, line):
if len(line.strip()) == 0 or line[0] == '#':
# support for comments in the digest-file
return CheckResult.IGNORED
path, hexdigest, binary, algo = self.decode_checksum_file_line(line)
try:
with open(path, 'rb') as fd:
hash_obj = self._compute_file_checksum(fd, algo, binary)
except OSError:
result = CheckResult.READ_FAILURE
if not self.quiet:
print(f'{path}: FAILED open or read')
else:
if hash_obj.hexdigest() == hexdigest:
result = CheckResult.OK
elif len(hash_obj.hexdigest()) != len(hexdigest):
result = CheckResult.BAD_FORMATTING
else:
result = CheckResult.FAILURE
if not self.status:
if (result != CheckResult.OK) or not self.quiet:
print(f'{path}: {result.value}')
return result
def print_check_results(self, check_result, filename):
ret = True
if check_result.n_failures > 0:
if not self.status:
self._log.warning(
'{} computed checksum do NOT match'.format(
check_result.n_failures))
ret = False
if check_result.n_read_failures > 0:
if not self.status:
self._log.warning(
'{} listed file(s) could not be read'.format(
check_result.n_read_failures))
ret = False
if check_result.n_improperly_formatted > 0:
if self.warn:
self._log.warning(
'{} improperly formatted checksum line'.format(
check_result.n_improperly_formatted))
if self.strict:
ret = False
if check_result.n_ok == 0:
self._log.info(
'{}: no properly formatted checksum lines found'.format(
filename))
ret = False
return ret
def verify_checksums(self, filenames):
result = True
if filenames:
if isinstance(filenames, str):
filenames = [filenames]
for filename in filenames:
check_result = CheckResultData()
with open(filename) as fd:
for line in fd:
ret = self.process_checksum_file_line(line)
check_result.update(ret)
ret = self.print_check_results(check_result, filename)
if not ret:
result = False
else:
# filenames is None or an empty list
filename = '-'
check_result = CheckResultData()
for line in sys.stdin:
ret = self.process_checksum_file_line(line)
check_result.update(ret)
ret = self.print_check_results(check_result, filename)
if not ret:
result = False
return result
class ChecksumCalculator:
def __init__(self, algo=None, binary=None, tag=False, multi_thread=False):
self.algo = algo
self.binary = binary
self.tag = tag
self.multi_thread = multi_thread
self._log = logging.getLogger('hashsum')
if self.algo is None:
msg = f'no algorithm specified: using {DEFAULT_ALGO!r}'
warnings.warn(msg)
# self._log.warning(msg)
self.algo = DEFAULT_ALGO
if self.tag and not self.binary:
raise ValueError(
'binary option set to False is incompatible with tag '
'option set to Ture')
def print_hash_line(self, filename, hash_obj):
if self.tag:
algo = hash_obj.name.upper()
print(f'{algo} ({filename}) = {hash_obj.hexdigest()}')
else:
marker = '*' if self.binary else ' '
print(f'{hash_obj.hexdigest()} {marker}{filename}')
def _compute_file_checksum(self, fd):
if self.multi_thread:
return _compute_file_checksum_threading(fd, self.algo, self.binary)
else:
return _compute_file_checksum_sequential(fd, self.algo,
self.binary)
def compute_checksums(self, filenames):
if filenames:
if isinstance(filenames, str):
filenames = [filenames]
for filename in filenames:
if os.path.isdir(filename):
self._log.info(f'{filename}: is a directory')
continue
with open(filename, 'rb') as fd:
hash_obj = self._compute_file_checksum(fd)
self.print_hash_line(filename, hash_obj)
else:
# filenames is None or an empty list
filename = '-'
# TODO: check
# stdin = io.open(sys.stdin.fileno(), mode='rb', closefd=False)
stdin = sys.stdin.buffer
hash_obj = self._compute_file_checksum(stdin)
self.print_hash_line(filename, hash_obj)
def get_parser():
"""Instantiate the command line argument parser."""
epilog = 'Copyright (C) 2016-2021, Antonio Valentino'
parser = argparse.ArgumentParser(prog=PROG, description=__doc__,
epilog=epilog)
parser.add_argument(
'-a', '--algorithm', choices=hashlib.algorithms_available,
default=None, metavar='',
help='specify the hashing algorithm '
'(default: {!r})'.format(DEFAULT_ALGO))
parser.add_argument(
'--tag', action='store_true', default=False,
help='create a BSD-style checksum')
mode_group = parser.add_mutually_exclusive_group()
mode_group.add_argument(
'-b', '--binary', action='store_true', default=None,
help='read input data in binary mode')
mode_group.add_argument(
'-t', '--text', dest='binary', action='store_false',
help='read input data in text mode (default)')
group = parser.add_mutually_exclusive_group()
group.add_argument(
'-c', '--check', action='store_true', default=False,
help='read checksum(s) form FILE and check them')
group.add_argument(
'-l', '--list-algorithms', action='store_true', default=False,
help='list available hashing algorithms')
check_group = parser.add_argument_group(
'check', 'Options that are useful only when verifying checksums')
check_group.add_argument(
'--quiet', action='store_true', default=False,
help="don't print OK for each successfully verified file")
check_group.add_argument(
'--status', action='store_true', default=False,
help="don't output anything, status code shows success")
check_group.add_argument(
'--strict', action='store_true', default=False,
help="exit non-zero for improperly formatted checksum lines")
check_group.add_argument(
'-w', '--warn', action='store_true', default=False,
help="warn about improperly formatted checksum lines")
parser.add_argument(
'-m', '--multi-thread', action='store_true', default=False,
help='perform I/O and hash computation in separate threads '
'(default=%(default)s). '
'Can speed-up computation on large files while it is not '
'recommended for small files.')
parser.add_argument(
'--version', action='version',
version=f'%(prog)s v{__version__}')
parser.add_argument(
'filenames', nargs='*', metavar='FILE',
help='name of file to process. '
'If not specified, or set to -, data are read form the '
'standard input')
if argcomplete:
argcomplete.autocomplete(parser)
return parser
def parse_args(args=None, namespace=None, parser=None):
"""Parse command line arguments."""
if parser is None:
parser = get_parser()
args = parser.parse_args(args)
if args.tag:
if args.binary is False:
parser.error('--tag does not support --text mode')
else:
args.binary = True
if args.tag and args.check:
parser.error(
'the --tag option is meaningless when verifying checksums')
if args.binary and args.check:
parser.error('the --binary and --text options are meaningless '
'when verifying checksums')
if args.status and not args.check:
parser.error('the --status option is meaningful only when '
'verifying checksums')
if args.warn and not args.check:
parser.error('the --warn option is meaningful only when '
'verifying checksums')
if args.quiet and not args.check:
parser.error('the --quiet option is meaningful only when '
'verifying checksums')
if args.strict and not args.check:
parser.error('the --strict option is meaningful only when '
'verifying checksums')
if '-' in args.filenames:
if len(args.filenames) > 1:
parser.error('"-" cannot be used if other file names have '
'been specified')
else:
args.filenames.remove('-')
return args
def main(*argv):
# setup logging
logging.basicConfig(format=LOGFMT, level=logging.DEBUG)
logging.captureWarnings(True)
log = logging.getLogger('hashsum')
# parse cmd line arguments
args = parse_args(argv if argv else None)
exitcode = EX_OK
try:
if args.list_algorithms:
algoset = hashlib.algorithms_available
algolist = sorted(
algo for algo in algoset
if algo.islower() or algo.lower() not in algoset
)
print('Available hash algoritms:')
print(' ', '\n '.join(algolist), sep='')
elif args.check:
tool = ChecksumVerifier(args.algorithm, args.quiet, args.status,
args.warn, args.strict, args.multi_thread)
result = tool.verify_checksums(args.filenames)
if not result:
exitcode = EX_FAILURE
else:
tool = ChecksumCalculator(
args.algorithm, args.binary, args.tag, args.multi_thread)
tool.compute_checksums(args.filenames)
except Exception as exc:
log.error(str(exc))
log.debug('stacktrace:', exc_info=True)
exitcode = EX_FAILURE
except KeyboardInterrupt:
log.warning('Keyboard interrupt received: exit the program')
exitcode = EX_INTERRUPT
return exitcode
if __name__ == '__main__':
sys.exit(main())
| 31.499165 | 79 | 0.586337 |
import io
import os
import re
import sys
import enum
import codecs
import hashlib
import logging
import argparse
import warnings
import functools
try:
from os import EX_OK
except ImportError:
EX_OK = 0
EX_FAILURE = 1
EX_INTERRUPT = 130
try:
import argcomplete
except ImportError:
argcomplete = False
else:
PYTHON_ARGCOMPLETE_OK = True
__version__ = '1.4.2.dev0'
PROG = os.path.splitext(os.path.basename(__file__))[0]
LOGFMT = '%(levelname)s: %(message)s'
DIGEST_LINE_RE = re.compile(
r'^(?P<digest>\w+) (?P<binary>[ *])(?P<path>.+)$')
DIGEST_LINE_BSD_RE = re.compile(
r'^(?P<algo>\w+) ?\((?P<path>.+)\) ?= (?P<digest>\w+)$')
BLOCKSIZE = 1024 * 1024
_QUEUE_LEN = 50
DEFAULT_ALGO = 'md5'
def blockiter(fd, blocksize=io.DEFAULT_BUFFER_SIZE):
guard = '' if isinstance(fd, io.TextIOBase) else b''
return iter(functools.partial(fd.read, blocksize), guard)
class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
def __init__(self, errors='strict'):
super().__init__(errors=errors)
self.buffer = b''
self.from_ = os.linesep.encode('ascii')
self.to = b'\n'
def decode(self, data, final=False):
if self.buffer:
output = self.buffer + data
else:
output = data
self.buffer = b''
if len(self.from_) > 1:
assert(len(self.from_) == 2)
lastchar = self.from_[-2:-1]
if output.endswith(lastchar) and not final:
output = output[:-1]
self.buffer = lastchar
output = output.replace(self.from_, self.to)
return output
def reset(self):
super().reset()
self.buffer = b''
def getstate(self):
return self.buffer, 0
def setstate(self, state):
self.buffer = state[0]
class CheckResult(enum.Enum):
OK = 'OK'
FAILURE = 'FAILURE'
READ_FAILURE = 'READ_FAILURE'
BAD_FORMATTING = 'BAD_FORMATTING'
IGNORED = 'IGNORED'
class CheckResultData:
def __init__(self, n_ok=0, n_failures=0, n_read_failures=0,
n_improperly_formatted=0, n_ignored=0):
self.n_ok = n_ok
self.n_failures = n_failures
self.n_read_failures = n_read_failures
self.n_improperly_formatted = n_improperly_formatted
self.n_ignored = n_ignored
def update(self, ret):
if ret == CheckResult.OK:
self.n_ok += 1
elif ret == CheckResult.FAILURE:
self.n_failures += 1
elif ret == CheckResult.READ_FAILURE:
self.n_read_failures += 1
elif ret == CheckResult.BAD_FORMATTING:
self.n_improperly_formatted += 1
elif ret == CheckResult.IGNORED:
self.n_ignored += 1
else:
raise ValueError(f'unexpected value: {ret}')
def __repr__(self):
keys = [
'n_ok',
'n_failures',
'n_read_failures',
'n_improperly_formatted',
'n_ignored',
]
kvstr = ', '.join(f'{k}={getattr(self, k)}' for k in keys)
return f'CheckResultData({kvstr})'
def _compute_file_checksum_sequential(fd, algo=DEFAULT_ALGO, binary=True):
hash_obj = hashlib.new(algo)
if not binary and os.linesep != '\n':
decoder = IncrementalNewlineDecoder()
else:
decoder = None
for data in blockiter(fd, BLOCKSIZE):
if decoder:
data = decoder.decode(data)
hash_obj.update(data)
if decoder:
data = decoder.decode(b'', final=True)
hash_obj.update(data)
return hash_obj
class HashObjectData:
def __init__(self, hash_obj):
self.block_size = hash_obj.block_size
self.name = hash_obj.name
self.digest_size = hash_obj.digest_size
self._digest = hash_obj.digest()
self._hexdigest = hash_obj.hexdigest()
def digest(self):
return self._digest
def hexdigest(self):
return self._hexdigest
def _worker(tasks, results, algo=DEFAULT_ALGO, decoder=None):
try:
hash_obj = hashlib.new(algo)
for data in iter(tasks.get, None):
if decoder:
data = decoder.decode(data)
hash_obj.update(data)
tasks.task_done()
else:
if decoder:
data = decoder.decode(b'', final=True)
hash_obj.update(data)
tasks.task_done()
results.put(HashObjectData(hash_obj))
except Exception as exc:
results.put(exc)
def _compute_file_checksum_threading(fd, algo=DEFAULT_ALGO, binary=True):
import queue
import threading
if not binary and os.linesep != '\n':
decoder = IncrementalNewlineDecoder()
else:
decoder = None
task_queue = queue.Queue(_QUEUE_LEN)
result_queue = queue.Queue()
args = (task_queue, result_queue, algo, decoder)
worker = threading.Thread(name='worker', target=_worker, args=args)
worker.start()
try:
for data in blockiter(fd, BLOCKSIZE):
task_queue.put(data)
if not result_queue.empty():
break
finally:
task_queue.put(None)
result = result_queue.get()
worker.join()
if isinstance(result, Exception):
raise result
return result
class ChecksumVerifier:
def __init__(self, algo=None, quiet=False, status=False, warn=False,
strict=False, multi_thread=False):
self.algo = algo
self.quiet = quiet
self.status = status
self.warn = warn
self.strict = strict
self.multi_thread = multi_thread
self._log = logging.getLogger('hashsum')
def _compute_file_checksum(self, fd, algo, binary):
if self.multi_thread:
return _compute_file_checksum_threading(fd, algo, binary)
else:
return _compute_file_checksum_sequential(fd, algo, binary)
def _check_algorithm_compatibility(self, algo):
if self.algo is not None and self.algo.lower() != algo.lower():
raise ValueError(
'specified hashing algorithm ({}) is different form '
'the one used in the digest file ({})'.format(
self.algo, algo))
def decode_checksum_file_line(self, line):
mobj = DIGEST_LINE_BSD_RE.match(line)
if mobj:
self._check_algorithm_compatibility(mobj.group('algo'))
algo = mobj.group('algo')
path = mobj.group('path')
hexdigest = mobj.group('digest')
binary = True
else:
mobj = DIGEST_LINE_RE.match(line)
if not mobj:
raise ValueError(
f'unable to decode digest line: "{line}"')
path = mobj.group('path')
hexdigest = mobj.group('digest')
binary = True if mobj.group('binary') == '*' else False
if self.algo is None:
msg = f'no algorithm specified: using {DEFAULT_ALGO!r}'
warnings.warn(msg)
algo = DEFAULT_ALGO
else:
algo = self.algo
return path, hexdigest, binary, algo
def process_checksum_file_line(self, line):
if len(line.strip()) == 0 or line[0] == '#':
return CheckResult.IGNORED
path, hexdigest, binary, algo = self.decode_checksum_file_line(line)
try:
with open(path, 'rb') as fd:
hash_obj = self._compute_file_checksum(fd, algo, binary)
except OSError:
result = CheckResult.READ_FAILURE
if not self.quiet:
print(f'{path}: FAILED open or read')
else:
if hash_obj.hexdigest() == hexdigest:
result = CheckResult.OK
elif len(hash_obj.hexdigest()) != len(hexdigest):
result = CheckResult.BAD_FORMATTING
else:
result = CheckResult.FAILURE
if not self.status:
if (result != CheckResult.OK) or not self.quiet:
print(f'{path}: {result.value}')
return result
def print_check_results(self, check_result, filename):
ret = True
if check_result.n_failures > 0:
if not self.status:
self._log.warning(
'{} computed checksum do NOT match'.format(
check_result.n_failures))
ret = False
if check_result.n_read_failures > 0:
if not self.status:
self._log.warning(
'{} listed file(s) could not be read'.format(
check_result.n_read_failures))
ret = False
if check_result.n_improperly_formatted > 0:
if self.warn:
self._log.warning(
'{} improperly formatted checksum line'.format(
check_result.n_improperly_formatted))
if self.strict:
ret = False
if check_result.n_ok == 0:
self._log.info(
'{}: no properly formatted checksum lines found'.format(
filename))
ret = False
return ret
def verify_checksums(self, filenames):
result = True
if filenames:
if isinstance(filenames, str):
filenames = [filenames]
for filename in filenames:
check_result = CheckResultData()
with open(filename) as fd:
for line in fd:
ret = self.process_checksum_file_line(line)
check_result.update(ret)
ret = self.print_check_results(check_result, filename)
if not ret:
result = False
else:
filename = '-'
check_result = CheckResultData()
for line in sys.stdin:
ret = self.process_checksum_file_line(line)
check_result.update(ret)
ret = self.print_check_results(check_result, filename)
if not ret:
result = False
return result
class ChecksumCalculator:
def __init__(self, algo=None, binary=None, tag=False, multi_thread=False):
self.algo = algo
self.binary = binary
self.tag = tag
self.multi_thread = multi_thread
self._log = logging.getLogger('hashsum')
if self.algo is None:
msg = f'no algorithm specified: using {DEFAULT_ALGO!r}'
warnings.warn(msg)
self.algo = DEFAULT_ALGO
if self.tag and not self.binary:
raise ValueError(
'binary option set to False is incompatible with tag '
'option set to Ture')
def print_hash_line(self, filename, hash_obj):
if self.tag:
algo = hash_obj.name.upper()
print(f'{algo} ({filename}) = {hash_obj.hexdigest()}')
else:
marker = '*' if self.binary else ' '
print(f'{hash_obj.hexdigest()} {marker}{filename}')
def _compute_file_checksum(self, fd):
if self.multi_thread:
return _compute_file_checksum_threading(fd, self.algo, self.binary)
else:
return _compute_file_checksum_sequential(fd, self.algo,
self.binary)
def compute_checksums(self, filenames):
if filenames:
if isinstance(filenames, str):
filenames = [filenames]
for filename in filenames:
if os.path.isdir(filename):
self._log.info(f'{filename}: is a directory')
continue
with open(filename, 'rb') as fd:
hash_obj = self._compute_file_checksum(fd)
self.print_hash_line(filename, hash_obj)
else:
filename = '-'
stdin = sys.stdin.buffer
hash_obj = self._compute_file_checksum(stdin)
self.print_hash_line(filename, hash_obj)
def get_parser():
epilog = 'Copyright (C) 2016-2021, Antonio Valentino'
parser = argparse.ArgumentParser(prog=PROG, description=__doc__,
epilog=epilog)
parser.add_argument(
'-a', '--algorithm', choices=hashlib.algorithms_available,
default=None, metavar='',
help='specify the hashing algorithm '
'(default: {!r})'.format(DEFAULT_ALGO))
parser.add_argument(
'--tag', action='store_true', default=False,
help='create a BSD-style checksum')
mode_group = parser.add_mutually_exclusive_group()
mode_group.add_argument(
'-b', '--binary', action='store_true', default=None,
help='read input data in binary mode')
mode_group.add_argument(
'-t', '--text', dest='binary', action='store_false',
help='read input data in text mode (default)')
group = parser.add_mutually_exclusive_group()
group.add_argument(
'-c', '--check', action='store_true', default=False,
help='read checksum(s) form FILE and check them')
group.add_argument(
'-l', '--list-algorithms', action='store_true', default=False,
help='list available hashing algorithms')
check_group = parser.add_argument_group(
'check', 'Options that are useful only when verifying checksums')
check_group.add_argument(
'--quiet', action='store_true', default=False,
help="don't print OK for each successfully verified file")
check_group.add_argument(
'--status', action='store_true', default=False,
help="don't output anything, status code shows success")
check_group.add_argument(
'--strict', action='store_true', default=False,
help="exit non-zero for improperly formatted checksum lines")
check_group.add_argument(
'-w', '--warn', action='store_true', default=False,
help="warn about improperly formatted checksum lines")
parser.add_argument(
'-m', '--multi-thread', action='store_true', default=False,
help='perform I/O and hash computation in separate threads '
'(default=%(default)s). '
'Can speed-up computation on large files while it is not '
'recommended for small files.')
parser.add_argument(
'--version', action='version',
version=f'%(prog)s v{__version__}')
parser.add_argument(
'filenames', nargs='*', metavar='FILE',
help='name of file to process. '
'If not specified, or set to -, data are read form the '
'standard input')
if argcomplete:
argcomplete.autocomplete(parser)
return parser
def parse_args(args=None, namespace=None, parser=None):
if parser is None:
parser = get_parser()
args = parser.parse_args(args)
if args.tag:
if args.binary is False:
parser.error('--tag does not support --text mode')
else:
args.binary = True
if args.tag and args.check:
parser.error(
'the --tag option is meaningless when verifying checksums')
if args.binary and args.check:
parser.error('the --binary and --text options are meaningless '
'when verifying checksums')
if args.status and not args.check:
parser.error('the --status option is meaningful only when '
'verifying checksums')
if args.warn and not args.check:
parser.error('the --warn option is meaningful only when '
'verifying checksums')
if args.quiet and not args.check:
parser.error('the --quiet option is meaningful only when '
'verifying checksums')
if args.strict and not args.check:
parser.error('the --strict option is meaningful only when '
'verifying checksums')
if '-' in args.filenames:
if len(args.filenames) > 1:
parser.error('"-" cannot be used if other file names have '
'been specified')
else:
args.filenames.remove('-')
return args
def main(*argv):
logging.basicConfig(format=LOGFMT, level=logging.DEBUG)
logging.captureWarnings(True)
log = logging.getLogger('hashsum')
args = parse_args(argv if argv else None)
exitcode = EX_OK
try:
if args.list_algorithms:
algoset = hashlib.algorithms_available
algolist = sorted(
algo for algo in algoset
if algo.islower() or algo.lower() not in algoset
)
print('Available hash algoritms:')
print(' ', '\n '.join(algolist), sep='')
elif args.check:
tool = ChecksumVerifier(args.algorithm, args.quiet, args.status,
args.warn, args.strict, args.multi_thread)
result = tool.verify_checksums(args.filenames)
if not result:
exitcode = EX_FAILURE
else:
tool = ChecksumCalculator(
args.algorithm, args.binary, args.tag, args.multi_thread)
tool.compute_checksums(args.filenames)
except Exception as exc:
log.error(str(exc))
log.debug('stacktrace:', exc_info=True)
exitcode = EX_FAILURE
except KeyboardInterrupt:
log.warning('Keyboard interrupt received: exit the program')
exitcode = EX_INTERRUPT
return exitcode
if __name__ == '__main__':
sys.exit(main())
| true | true |
f7280829cd5870fc25cdeff05cf7df3d0f29788d | 18,748 | py | Python | python/GafferUI/NodeGraph.py | Kthulhu/gaffer | 8995d579d07231988abc92c3ac2788c15c8bc75c | [
"BSD-3-Clause"
] | 1 | 2016-07-31T09:55:09.000Z | 2016-07-31T09:55:09.000Z | python/GafferUI/NodeGraph.py | Kthulhu/gaffer | 8995d579d07231988abc92c3ac2788c15c8bc75c | [
"BSD-3-Clause"
] | null | null | null | python/GafferUI/NodeGraph.py | Kthulhu/gaffer | 8995d579d07231988abc92c3ac2788c15c8bc75c | [
"BSD-3-Clause"
] | null | null | null | ##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import IECore
import Gaffer
import GafferUI
class NodeGraph( GafferUI.EditorWidget ) :
def __init__( self, scriptNode, **kw ) :
self.__gadgetWidget = GafferUI.GadgetWidget(
bufferOptions = set( [
GafferUI.GLWidget.BufferOptions.Double,
] ),
)
GafferUI.EditorWidget.__init__( self, self.__gadgetWidget, scriptNode, **kw )
graphGadget = GafferUI.GraphGadget( self.scriptNode() )
self.__rootChangedConnection = graphGadget.rootChangedSignal().connect( Gaffer.WeakMethod( self.__rootChanged ) )
self.__gadgetWidget.getViewportGadget().setPrimaryChild( graphGadget )
self.__gadgetWidget.getViewportGadget().setDragTracking( True )
self.__frame( scriptNode.selection() )
self.__buttonPressConnection = self.__gadgetWidget.buttonPressSignal().connect( Gaffer.WeakMethod( self.__buttonPress ) )
self.__keyPressConnection = self.__gadgetWidget.keyPressSignal().connect( Gaffer.WeakMethod( self.__keyPress ) )
self.__buttonDoubleClickConnection = self.__gadgetWidget.buttonDoubleClickSignal().connect( Gaffer.WeakMethod( self.__buttonDoubleClick ) )
self.__dragEnterConnection = self.__gadgetWidget.dragEnterSignal().connect( Gaffer.WeakMethod( self.__dragEnter ) )
self.__dropConnection = self.__gadgetWidget.dropSignal().connect( Gaffer.WeakMethod( self.__drop ) )
self.__preRenderConnection = self.__gadgetWidget.getViewportGadget().preRenderSignal().connect( Gaffer.WeakMethod( self.__preRender ) )
self.__nodeMenu = None
## Returns the internal GadgetWidget holding the GraphGadget.
def graphGadgetWidget( self ) :
return self.__gadgetWidget
## Returns the internal Gadget used to draw the graph. This may be
# modified directly to set up appropriate filters etc. This is just
# a convenience method returning graphGadgetWidget().getViewportGadget().getPrimaryChild().
def graphGadget( self ) :
return self.graphGadgetWidget().getViewportGadget().getPrimaryChild()
## Frames the specified nodes in the viewport. If extend is True
# then the current framing will be extended to include the specified
# nodes, if False then the framing will be reset to frame only the
# nodes specified.
def frame( self, nodes, extend=False ) :
self.__frame( nodes, extend )
def getTitle( self ) :
title = super( NodeGraph, self ).getTitle()
if title:
return title
result = IECore.CamelCase.toSpaced( self.__class__.__name__ )
root = self.graphGadget().getRoot()
if not root.isSame( self.scriptNode() ) :
result += " : " + root.relativeName( self.scriptNode() ).replace( ".", " / " )
return result
__plugContextMenuSignal = Gaffer.Signal3()
## Returns a signal which is emitted to create a context menu for a
# plug in the graph. Slots may connect to this signal to edit the
# menu definition on the fly - the signature for the signal is
# ( nodeGraph, plug, menuDefinition ) and the menu definition should just be
# edited in place.
@classmethod
def plugContextMenuSignal( cls ) :
return cls.__plugContextMenuSignal
__connectionContextMenuSignal = Gaffer.Signal3()
## Returns a signal which is emitted to create a context menu for a
# connection in the graph. Slots may connect to this signal to edit the
# menu definition on the fly - the signature for the signal is
# ( nodeGraph, destinationPlug, menuDefinition ) and the menu definition
# should just be edited in place.
@classmethod
def connectionContextMenuSignal( cls ) :
return cls.__connectionContextMenuSignal
__nodeContextMenuSignal = Gaffer.Signal3()
## Returns a signal which is emitted to create a context menu for a
# node in the graph. Slots may connect to this signal to edit the
# menu definition on the fly - the signature for the signal is
# ( nodeGraph, node, menuDefinition ) and the menu definition should just be
# edited in place. Typically you would add slots to this signal
# as part of a startup script.
@classmethod
def nodeContextMenuSignal( cls ) :
return cls.__nodeContextMenuSignal
## May be used from a slot attached to nodeContextMenuSignal() to install some
# standard menu items for modifying the connection visibility for a node.
@classmethod
def appendConnectionVisibilityMenuDefinitions( cls, nodeGraph, node, menuDefinition ) :
menuDefinition.append( "/ConnectionVisibilityDivider", { "divider" : True } )
menuDefinition.append(
"/Show Input Connections",
{
"checkBox" : IECore.curry( cls.__getNodeInputConnectionsVisible, nodeGraph.graphGadget(), node ),
"command" : IECore.curry( cls.__setNodeInputConnectionsVisible, nodeGraph.graphGadget(), node )
}
)
menuDefinition.append(
"/Show Output Connections",
{
"checkBox" : IECore.curry( cls.__getNodeOutputConnectionsVisible, nodeGraph.graphGadget(), node ),
"command" : IECore.curry( cls.__setNodeOutputConnectionsVisible, nodeGraph.graphGadget(), node )
}
)
## May be used from a slot attached to nodeContextMenuSignal() to install a
# standard menu item for modifying the enabled state of a node.
@classmethod
def appendEnabledPlugMenuDefinitions( cls, nodeGraph, node, menuDefinition ) :
enabledPlug = node.enabledPlug() if isinstance( node, Gaffer.DependencyNode ) else None
if enabledPlug is not None :
menuDefinition.append( "/EnabledDivider", { "divider" : True } )
menuDefinition.append(
"/Enabled",
{
"command" : IECore.curry( cls.__setEnabled, node ),
"checkBox" : enabledPlug.getValue(),
"active" : enabledPlug.settable()
}
)
__nodeDoubleClickSignal = Gaffer.Signal2()
## Returns a signal which is emitted whenever a node is double clicked.
# Slots should have the signature ( nodeGraph, node ).
@classmethod
def nodeDoubleClickSignal( cls ) :
return cls.__nodeDoubleClickSignal
## Ensures that the specified node has a visible NodeGraph viewing
# it, and returns that editor.
## \todo Consider how this relates to the todo items in NodeSetEditor.acquire().
@classmethod
def acquire( cls, rootNode ) :
if isinstance( rootNode, Gaffer.ScriptNode ) :
script = rootNode
else :
script = rootNode.scriptNode()
scriptWindow = GafferUI.ScriptWindow.acquire( script )
tabbedContainer = None
for editor in scriptWindow.getLayout().editors( type = GafferUI.NodeGraph ) :
if rootNode.isSame( editor.graphGadget().getRoot() ) :
editor.parent().setCurrent( editor )
return editor
editor = NodeGraph( script )
editor.graphGadget().setRoot( rootNode )
scriptWindow.getLayout().addEditor( editor )
return editor
def __repr__( self ) :
return "GafferUI.NodeGraph( scriptNode )"
def _nodeMenu( self ) :
if self.__nodeMenu is None :
self.__nodeMenu = GafferUI.Menu( GafferUI.NodeMenu.acquire( self.scriptNode().applicationRoot() ).definition(), searchable=True )
self.__nodeMenuVisibilityChangedConnection = self.__nodeMenu.visibilityChangedSignal().connect( Gaffer.WeakMethod( self.__nodeMenuVisibilityChanged ) )
return self.__nodeMenu
def __nodeMenuVisibilityChanged( self, widget ) :
assert( widget is self.__nodeMenu )
if not self.__nodeMenu.visible() :
# generally we steal focus on mouse enter (implemented in GadgetWidget),
# but when the node menu closes we may not get an enter event, so we have to steal
# the focus back here.
self.__gadgetWidget._qtWidget().setFocus()
def __buttonPress( self, widget, event ) :
if event.buttons & GafferUI.ButtonEvent.Buttons.Right :
# right click - display either the node creation popup menu
# or a menu specific to the node/plug/connection under the
# mouse if possible.
viewport = self.__gadgetWidget.getViewportGadget()
gadgets = viewport.gadgetsAt( IECore.V2f( event.line.p1.x, event.line.p1.y ) )
if len( gadgets ) :
overrideMenuDefinition = IECore.MenuDefinition()
overrideMenuTitle = None
if isinstance( gadgets[0], GafferUI.Nodule ) :
self.plugContextMenuSignal()( self, gadgets[0].plug(), overrideMenuDefinition )
overrideMenuTitle = gadgets[0].plug().relativeName( self.graphGadget().getRoot() )
elif isinstance( gadgets[0], GafferUI.ConnectionGadget ) :
self.connectionContextMenuSignal()( self, gadgets[0].dstNodule().plug(), overrideMenuDefinition )
overrideMenuTitle = "-> " + gadgets[0].dstNodule().plug().relativeName( self.graphGadget().getRoot() )
else :
nodeGadget = gadgets[0]
if not isinstance( nodeGadget, GafferUI.NodeGadget ) :
nodeGadget = nodeGadget.ancestor( GafferUI.NodeGadget )
if nodeGadget is not None :
self.nodeContextMenuSignal()( self, nodeGadget.node(), overrideMenuDefinition )
overrideMenuTitle = nodeGadget.node().getName()
if len( overrideMenuDefinition.items() ) :
menuDefinition = overrideMenuDefinition
self._m = GafferUI.Menu( menuDefinition, title=overrideMenuTitle )
self._m.popup( self )
return True
self._nodeMenu().popup( self )
return True
return False
def __nodeGadgetAt( self, position ) :
viewport = self.__gadgetWidget.getViewportGadget()
line = viewport.rasterToGadgetSpace( IECore.V2f( position.x, position.y ), gadget = self.graphGadget() )
return self.graphGadget().nodeGadgetAt( line )
def __keyPress( self, widget, event ) :
if event.key == "F" and not event.modifiers :
self.__frame( self.scriptNode().selection() )
return True
## \todo This cursor key navigation might not make sense for all applications,
# so we should move it into BoxUI and load it in a config file that the gui app uses.
# I think this implies that every Widget.*Signal() method should have a
# Widget.static*Signal() method to allow global handlers to be registered by widget type.
# We already have a mix of static/nonstatic signals for menus, so that might make a nice
# generalisation.
elif event.key == "Down" :
selection = self.scriptNode().selection()
if selection.size() :
if isinstance( selection[0], Gaffer.Box ) or event.modifiers == event.modifiers.Shift | event.modifiers.Control :
self.graphGadget().setRoot( selection[0] )
return True
elif event.key == "Up" :
root = self.graphGadget().getRoot()
if not isinstance( root, Gaffer.ScriptNode ) :
self.graphGadget().setRoot( root.parent() )
return True
elif event.key == "Tab" :
self._nodeMenu().popup( self )
return True
return False
def __frame( self, nodes, extend = False ) :
graphGadget = self.graphGadget()
# get the bounds of the nodes
bound = IECore.Box3f()
for node in nodes :
nodeGadget = graphGadget.nodeGadget( node )
if nodeGadget :
bound.extendBy( nodeGadget.transformedBound( graphGadget ) )
# if there were no nodes then use the bound of the whole
# graph.
if bound.isEmpty() :
bound = graphGadget.bound()
# if there's still nothing then an arbitrary area in the centre of the world
if bound.isEmpty() :
bound = IECore.Box3f( IECore.V3f( -10, -10, 0 ), IECore.V3f( 10, 10, 0 ) )
# pad it a little bit so
# it sits nicer in the frame
bound.min -= IECore.V3f( 1, 1, 0 )
bound.max += IECore.V3f( 1, 1, 0 )
if extend :
# we're extending the existing framing, which we assume the
# user was happy with other than it not showing the nodes in question.
# so we just take the union of the existing frame and the one for the nodes.
cb = self.__currentFrame()
bound.extendBy( IECore.Box3f( IECore.V3f( cb.min.x, cb.min.y, 0 ), IECore.V3f( cb.max.x, cb.max.y, 0 ) ) )
else :
# we're reframing from scratch, so the frame for the nodes is all we need.
# we do however want to make sure that we don't zoom in too far if the node
# bounds are small, as having a single node filling the screen is of little use -
# it's better to see some context around it.
boundSize = bound.size()
widgetSize = IECore.V3f( self._qtWidget().width(), self._qtWidget().height(), 0 )
pixelsPerUnit = widgetSize / boundSize
adjustedPixelsPerUnit = min( pixelsPerUnit.x, pixelsPerUnit.y, 10 )
newBoundSize = widgetSize / adjustedPixelsPerUnit
boundCenter = bound.center()
bound.min = boundCenter - newBoundSize / 2.0
bound.max = boundCenter + newBoundSize / 2.0
self.__gadgetWidget.getViewportGadget().frame( bound )
def __buttonDoubleClick( self, widget, event ) :
nodeGadget = self.__nodeGadgetAt( event.line.p1 )
if nodeGadget is not None :
return self.nodeDoubleClickSignal()( self, nodeGadget.node() )
def __dragEnter( self, widget, event ) :
if event.sourceWidget is self.__gadgetWidget :
return False
if self.__dropNodes( event.data ) :
return True
return False
def __drop( self, widget, event ) :
if event.sourceWidget is self.__gadgetWidget :
return False
dropNodes = self.__dropNodes( event.data )
if dropNodes :
self.__frame( dropNodes )
return True
return False
def __dropNodes( self, dragData ) :
if isinstance( dragData, Gaffer.Node ) :
return [ dragData ]
elif isinstance( dragData, Gaffer.Plug ) :
return [ dragData.node() ]
elif isinstance( dragData, Gaffer.Set ) :
return [ x for x in dragData if isinstance( x, Gaffer.Node ) ]
return []
def __currentFrame( self ) :
camera = self.graphGadgetWidget().getViewportGadget().getCamera()
frame = camera.parameters()["screenWindow"].value
translation = camera.getTransform().matrix.translation()
frame.min += IECore.V2f( translation.x, translation.y )
frame.max += IECore.V2f( translation.x, translation.y )
return frame
def __rootChanged( self, graphGadget, previousRoot ) :
# save/restore the current framing so jumping in
# and out of Boxes isn't a confusing experience.
Gaffer.Metadata.registerNodeValue( previousRoot, "ui:nodeGraph:framing", self.__currentFrame(), persistent = False )
frame = Gaffer.Metadata.nodeValue( self.graphGadget().getRoot(), "ui:nodeGraph:framing" )
if frame is not None :
self.graphGadgetWidget().getViewportGadget().frame(
IECore.Box3f( IECore.V3f( frame.min.x, frame.min.y, 0 ), IECore.V3f( frame.max.x, frame.max.y, 0 ) )
)
else :
self.__frame( self.graphGadget().getRoot().children( Gaffer.Node ) )
# do what we need to do to keep our title up to date.
if graphGadget.getRoot().isSame( self.scriptNode() ) :
self.__rootNameChangedConnection = None
self.__rootParentChangedConnection = None
else :
self.__rootNameChangedConnection = graphGadget.getRoot().nameChangedSignal().connect( Gaffer.WeakMethod( self.__rootNameChanged ) )
self.__rootParentChangedConnection = graphGadget.getRoot().parentChangedSignal().connect( Gaffer.WeakMethod( self.__rootParentChanged ) )
self.titleChangedSignal()( self )
def __rootNameChanged( self, root ) :
self.titleChangedSignal()( self )
def __rootParentChanged( self, root, oldParent ) :
# root has been deleted
## \todo I'm not sure if we should be responsible for removing ourselves or not.
# Perhaps we should just signal that we're not valid in some way and the CompoundEditor should
# remove us? Consider how this relates to NodeEditor.__deleteWindow() too.
self.parent().removeChild( self )
def __preRender( self, viewportGadget ) :
# Find all unpositioned nodes.
graphGadget = self.graphGadget()
nodes = [ g.node() for g in graphGadget.unpositionedNodeGadgets() ]
if not nodes :
return
nodes = Gaffer.StandardSet( nodes )
# Lay them out somewhere near the centre of frame.
gadgetWidget = self.graphGadgetWidget()
fallbackPosition = gadgetWidget.getViewportGadget().rasterToGadgetSpace(
IECore.V2f( gadgetWidget.size() ) / 2.0,
gadget = graphGadget
).p0
fallbackPosition = IECore.V2f( fallbackPosition.x, fallbackPosition.y )
graphGadget.getLayout().positionNodes( graphGadget, nodes, fallbackPosition )
graphGadget.getLayout().layoutNodes( graphGadget, nodes )
# And then extend the frame to include them, in case the
# layout has gone off screen.
self.frame( nodes, extend = True )
@classmethod
def __getNodeInputConnectionsVisible( cls, graphGadget, node ) :
return not graphGadget.getNodeInputConnectionsMinimised( node )
@classmethod
def __setNodeInputConnectionsVisible( cls, graphGadget, node, value ) :
with Gaffer.UndoContext( node.ancestor( Gaffer.ScriptNode ) ) :
graphGadget.setNodeInputConnectionsMinimised( node, not value )
@classmethod
def __getNodeOutputConnectionsVisible( cls, graphGadget, node ) :
return not graphGadget.getNodeOutputConnectionsMinimised( node )
@classmethod
def __setNodeOutputConnectionsVisible( cls, graphGadget, node, value ) :
with Gaffer.UndoContext( node.ancestor( Gaffer.ScriptNode ) ) :
graphGadget.setNodeOutputConnectionsMinimised( node, not value )
@classmethod
def __setEnabled( cls, node, value ) :
with Gaffer.UndoContext( node.ancestor( Gaffer.ScriptNode ) ) :
node.enabledPlug().setValue( value )
GafferUI.EditorWidget.registerType( "NodeGraph", NodeGraph )
| 37.722334 | 154 | 0.727864 | adget ) :
nodeGadget = nodeGadget.ancestor( GafferUI.NodeGadget )
if nodeGadget is not None :
self.nodeContextMenuSignal()( self, nodeGadget.node(), overrideMenuDefinition )
overrideMenuTitle = nodeGadget.node().getName()
if len( overrideMenuDefinition.items() ) :
menuDefinition = overrideMenuDefinition
self._m = GafferUI.Menu( menuDefinition, title=overrideMenuTitle )
self._m.popup( self )
return True
self._nodeMenu().popup( self )
return True
return False
def __nodeGadgetAt( self, position ) :
viewport = self.__gadgetWidget.getViewportGadget()
line = viewport.rasterToGadgetSpace( IECore.V2f( position.x, position.y ), gadget = self.graphGadget() )
return self.graphGadget().nodeGadgetAt( line )
def __keyPress( self, widget, event ) :
if event.key == "F" and not event.modifiers :
self.__frame( self.scriptNode().selection() )
return True
.selection()
if selection.size() :
if isinstance( selection[0], Gaffer.Box ) or event.modifiers == event.modifiers.Shift | event.modifiers.Control :
self.graphGadget().setRoot( selection[0] )
return True
elif event.key == "Up" :
root = self.graphGadget().getRoot()
if not isinstance( root, Gaffer.ScriptNode ) :
self.graphGadget().setRoot( root.parent() )
return True
elif event.key == "Tab" :
self._nodeMenu().popup( self )
return True
return False
def __frame( self, nodes, extend = False ) :
graphGadget = self.graphGadget()
bound = IECore.Box3f()
for node in nodes :
nodeGadget = graphGadget.nodeGadget( node )
if nodeGadget :
bound.extendBy( nodeGadget.transformedBound( graphGadget ) )
if bound.isEmpty() :
bound = graphGadget.bound()
if bound.isEmpty() :
bound = IECore.Box3f( IECore.V3f( -10, -10, 0 ), IECore.V3f( 10, 10, 0 ) )
# pad it a little bit so
# it sits nicer in the frame
bound.min -= IECore.V3f( 1, 1, 0 )
bound.max += IECore.V3f( 1, 1, 0 )
if extend :
# we're extending the existing framing, which we assume the
cb = self.__currentFrame()
bound.extendBy( IECore.Box3f( IECore.V3f( cb.min.x, cb.min.y, 0 ), IECore.V3f( cb.max.x, cb.max.y, 0 ) ) )
else :
# we do however want to make sure that we don't zoom in too far if the node
boundSize = bound.size()
widgetSize = IECore.V3f( self._qtWidget().width(), self._qtWidget().height(), 0 )
pixelsPerUnit = widgetSize / boundSize
adjustedPixelsPerUnit = min( pixelsPerUnit.x, pixelsPerUnit.y, 10 )
newBoundSize = widgetSize / adjustedPixelsPerUnit
boundCenter = bound.center()
bound.min = boundCenter - newBoundSize / 2.0
bound.max = boundCenter + newBoundSize / 2.0
self.__gadgetWidget.getViewportGadget().frame( bound )
def __buttonDoubleClick( self, widget, event ) :
nodeGadget = self.__nodeGadgetAt( event.line.p1 )
if nodeGadget is not None :
return self.nodeDoubleClickSignal()( self, nodeGadget.node() )
def __dragEnter( self, widget, event ) :
if event.sourceWidget is self.__gadgetWidget :
return False
if self.__dropNodes( event.data ) :
return True
return False
def __drop( self, widget, event ) :
if event.sourceWidget is self.__gadgetWidget :
return False
dropNodes = self.__dropNodes( event.data )
if dropNodes :
self.__frame( dropNodes )
return True
return False
def __dropNodes( self, dragData ) :
if isinstance( dragData, Gaffer.Node ) :
return [ dragData ]
elif isinstance( dragData, Gaffer.Plug ) :
return [ dragData.node() ]
elif isinstance( dragData, Gaffer.Set ) :
return [ x for x in dragData if isinstance( x, Gaffer.Node ) ]
return []
def __currentFrame( self ) :
camera = self.graphGadgetWidget().getViewportGadget().getCamera()
frame = camera.parameters()["screenWindow"].value
translation = camera.getTransform().matrix.translation()
frame.min += IECore.V2f( translation.x, translation.y )
frame.max += IECore.V2f( translation.x, translation.y )
return frame
def __rootChanged( self, graphGadget, previousRoot ) :
# save/restore the current framing so jumping in
# and out of Boxes isn't a confusing experience.
Gaffer.Metadata.registerNodeValue( previousRoot, "ui:nodeGraph:framing", self.__currentFrame(), persistent = False )
frame = Gaffer.Metadata.nodeValue( self.graphGadget().getRoot(), "ui:nodeGraph:framing" )
if frame is not None :
self.graphGadgetWidget().getViewportGadget().frame(
IECore.Box3f( IECore.V3f( frame.min.x, frame.min.y, 0 ), IECore.V3f( frame.max.x, frame.max.y, 0 ) )
)
else :
self.__frame( self.graphGadget().getRoot().children( Gaffer.Node ) )
if graphGadget.getRoot().isSame( self.scriptNode() ) :
self.__rootNameChangedConnection = None
self.__rootParentChangedConnection = None
else :
self.__rootNameChangedConnection = graphGadget.getRoot().nameChangedSignal().connect( Gaffer.WeakMethod( self.__rootNameChanged ) )
self.__rootParentChangedConnection = graphGadget.getRoot().parentChangedSignal().connect( Gaffer.WeakMethod( self.__rootParentChanged ) )
self.titleChangedSignal()( self )
def __rootNameChanged( self, root ) :
self.titleChangedSignal()( self )
def __rootParentChanged( self, root, oldParent ) :
poundEditor should
self.parent().removeChild( self )
def __preRender( self, viewportGadget ) :
graphGadget = self.graphGadget()
nodes = [ g.node() for g in graphGadget.unpositionedNodeGadgets() ]
if not nodes :
return
nodes = Gaffer.StandardSet( nodes )
gadgetWidget = self.graphGadgetWidget()
fallbackPosition = gadgetWidget.getViewportGadget().rasterToGadgetSpace(
IECore.V2f( gadgetWidget.size() ) / 2.0,
gadget = graphGadget
).p0
fallbackPosition = IECore.V2f( fallbackPosition.x, fallbackPosition.y )
graphGadget.getLayout().positionNodes( graphGadget, nodes, fallbackPosition )
graphGadget.getLayout().layoutNodes( graphGadget, nodes )
self.frame( nodes, extend = True )
@classmethod
def __getNodeInputConnectionsVisible( cls, graphGadget, node ) :
return not graphGadget.getNodeInputConnectionsMinimised( node )
@classmethod
def __setNodeInputConnectionsVisible( cls, graphGadget, node, value ) :
with Gaffer.UndoContext( node.ancestor( Gaffer.ScriptNode ) ) :
graphGadget.setNodeInputConnectionsMinimised( node, not value )
@classmethod
def __getNodeOutputConnectionsVisible( cls, graphGadget, node ) :
return not graphGadget.getNodeOutputConnectionsMinimised( node )
@classmethod
def __setNodeOutputConnectionsVisible( cls, graphGadget, node, value ) :
with Gaffer.UndoContext( node.ancestor( Gaffer.ScriptNode ) ) :
graphGadget.setNodeOutputConnectionsMinimised( node, not value )
@classmethod
def __setEnabled( cls, node, value ) :
with Gaffer.UndoContext( node.ancestor( Gaffer.ScriptNode ) ) :
node.enabledPlug().setValue( value )
GafferUI.EditorWidget.registerType( "NodeGraph", NodeGraph )
| true | true |
f728087f4eef364c01b64b3e6706780a87d04def | 69 | py | Python | enrichmentmanager/__init__.py | rectory-school/rectory-apps | 184021529ac9cadc3b7c0fbf93a023c82fc76b91 | [
"MIT"
] | null | null | null | enrichmentmanager/__init__.py | rectory-school/rectory-apps | 184021529ac9cadc3b7c0fbf93a023c82fc76b91 | [
"MIT"
] | 5 | 2020-06-05T17:33:12.000Z | 2021-06-10T19:04:41.000Z | enrichmentmanager/__init__.py | rectory-school/rectory-apps | 184021529ac9cadc3b7c0fbf93a023c82fc76b91 | [
"MIT"
] | 1 | 2016-02-08T15:53:28.000Z | 2016-02-08T15:53:28.000Z | default_app_config = 'enrichmentmanager.apps.EnrichmentManagerConfig' | 69 | 69 | 0.898551 | default_app_config = 'enrichmentmanager.apps.EnrichmentManagerConfig' | true | true |
f7280952fd1b6ce7de2b86889e2486b217763d23 | 10,395 | py | Python | setup.py | duanwujie/grpc-hacking | 4275e60eb686ceb202c042fe578c9cf992e590d0 | [
"BSD-3-Clause"
] | null | null | null | setup.py | duanwujie/grpc-hacking | 4275e60eb686ceb202c042fe578c9cf992e590d0 | [
"BSD-3-Clause"
] | null | null | null | setup.py | duanwujie/grpc-hacking | 4275e60eb686ceb202c042fe578c9cf992e590d0 | [
"BSD-3-Clause"
] | null | null | null | # Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""A setup module for the GRPC Python package."""
from distutils import cygwinccompiler
from distutils import extension as _extension
from distutils import util
import os
import os.path
import pkg_resources
import platform
import re
import shlex
import shutil
import sys
import sysconfig
import setuptools
from setuptools.command import egg_info
# Redirect the manifest template from MANIFEST.in to PYTHON-MANIFEST.in.
egg_info.manifest_maker.template = 'PYTHON-MANIFEST.in'
PY3 = sys.version_info.major == 3
PYTHON_STEM = os.path.join('src', 'python', 'grpcio')
CORE_INCLUDE = ('include', '.',)
BORINGSSL_INCLUDE = (os.path.join('third_party', 'boringssl', 'include'),)
ZLIB_INCLUDE = (os.path.join('third_party', 'zlib'),)
# Ensure we're in the proper directory whether or not we're being used by pip.
os.chdir(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.abspath(PYTHON_STEM))
# Break import-style to ensure we can actually find our in-repo dependencies.
import _spawn_patch
import commands
import grpc_core_dependencies
import grpc_version
_spawn_patch.monkeypatch_spawn()
LICENSE = '3-clause BSD'
# Environment variable to determine whether or not the Cython extension should
# *use* Cython or use the generated C files. Note that this requires the C files
# to have been generated by building first *with* Cython support. Even if this
# is set to false, if the script detects that the generated `.c` file isn't
# present, then it will still attempt to use Cython.
BUILD_WITH_CYTHON = os.environ.get('GRPC_PYTHON_BUILD_WITH_CYTHON', False)
# Environment variable to determine whether or not to enable coverage analysis
# in Cython modules.
ENABLE_CYTHON_TRACING = os.environ.get(
'GRPC_PYTHON_ENABLE_CYTHON_TRACING', False)
# There are some situations (like on Windows) where CC, CFLAGS, and LDFLAGS are
# entirely ignored/dropped/forgotten by distutils and its Cygwin/MinGW support.
# We use these environment variables to thus get around that without locking
# ourselves in w.r.t. the multitude of operating systems this ought to build on.
# We can also use these variables as a way to inject environment-specific
# compiler/linker flags. We assume GCC-like compilers and/or MinGW as a
# reasonable default.
EXTRA_ENV_COMPILE_ARGS = os.environ.get('GRPC_PYTHON_CFLAGS', None)
EXTRA_ENV_LINK_ARGS = os.environ.get('GRPC_PYTHON_LDFLAGS', None)
if EXTRA_ENV_COMPILE_ARGS is None:
EXTRA_ENV_COMPILE_ARGS = ''
if 'win32' in sys.platform and sys.version_info < (3, 5):
# We use define flags here and don't directly add to DEFINE_MACROS below to
# ensure that the expert user/builder has a way of turning it off (via the
# envvars) without adding yet more GRPC-specific envvars.
# See https://sourceforge.net/p/mingw-w64/bugs/363/
if '32' in platform.architecture()[0]:
EXTRA_ENV_COMPILE_ARGS += ' -D_ftime=_ftime32 -D_timeb=__timeb32 -D_ftime_s=_ftime32_s'
else:
EXTRA_ENV_COMPILE_ARGS += ' -D_ftime=_ftime64 -D_timeb=__timeb64'
elif "linux" in sys.platform or "darwin" in sys.platform:
EXTRA_ENV_COMPILE_ARGS += ' -fvisibility=hidden -fno-wrapv'
if EXTRA_ENV_LINK_ARGS is None:
EXTRA_ENV_LINK_ARGS = ''
if "linux" in sys.platform or "darwin" in sys.platform:
EXTRA_ENV_LINK_ARGS += ' -lpthread'
elif "win32" in sys.platform and sys.version_info < (3, 5):
msvcr = cygwinccompiler.get_msvcr()[0]
# TODO(atash) sift through the GCC specs to see if libstdc++ can have any
# influence on the linkage outcome on MinGW for non-C++ programs.
EXTRA_ENV_LINK_ARGS += (
' -static-libgcc -static-libstdc++ -mcrtdll={msvcr} '
'-static'.format(msvcr=msvcr))
if "linux" in sys.platform:
EXTRA_ENV_LINK_ARGS += ' -Wl,-wrap,memcpy'
EXTRA_COMPILE_ARGS = shlex.split(EXTRA_ENV_COMPILE_ARGS)
EXTRA_LINK_ARGS = shlex.split(EXTRA_ENV_LINK_ARGS)
CYTHON_EXTENSION_PACKAGE_NAMES = ()
CYTHON_EXTENSION_MODULE_NAMES = ('grpc._cython.cygrpc',)
CYTHON_HELPER_C_FILES = ()
CORE_C_FILES = tuple(grpc_core_dependencies.CORE_SOURCE_FILES)
EXTENSION_INCLUDE_DIRECTORIES = (
(PYTHON_STEM,) + CORE_INCLUDE + BORINGSSL_INCLUDE + ZLIB_INCLUDE)
EXTENSION_LIBRARIES = ()
if "linux" in sys.platform:
EXTENSION_LIBRARIES += ('rt',)
if not "win32" in sys.platform:
EXTENSION_LIBRARIES += ('m',)
if "win32" in sys.platform:
EXTENSION_LIBRARIES += ('advapi32', 'ws2_32',)
DEFINE_MACROS = (
('OPENSSL_NO_ASM', 1), ('_WIN32_WINNT', 0x600),
('GPR_BACKWARDS_COMPATIBILITY_MODE', 1),)
if "win32" in sys.platform:
DEFINE_MACROS += (('WIN32_LEAN_AND_MEAN', 1),)
if '64bit' in platform.architecture()[0]:
DEFINE_MACROS += (('MS_WIN64', 1),)
elif sys.version_info >= (3, 5):
# For some reason, this is needed to get access to inet_pton/inet_ntop
# on msvc, but only for 32 bits
DEFINE_MACROS += (('NTDDI_VERSION', 0x06000000),)
LDFLAGS = tuple(EXTRA_LINK_ARGS)
CFLAGS = tuple(EXTRA_COMPILE_ARGS)
if "linux" in sys.platform or "darwin" in sys.platform:
pymodinit_type = 'PyObject*' if PY3 else 'void'
pymodinit = '__attribute__((visibility ("default"))) {}'.format(pymodinit_type)
DEFINE_MACROS += (('PyMODINIT_FUNC', pymodinit),)
# By default, Python3 distutils enforces compatibility of
# c plugins (.so files) with the OSX version Python3 was built with.
# For Python3.4, this is OSX 10.6, but we need Thread Local Support (__thread)
if 'darwin' in sys.platform and PY3:
mac_target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
if mac_target and (pkg_resources.parse_version(mac_target) <
pkg_resources.parse_version('10.7.0')):
os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.7'
os.environ['_PYTHON_HOST_PLATFORM'] = re.sub(
r'macosx-[0-9]+\.[0-9]+-(.+)',
r'macosx-10.7-\1',
util.get_platform())
def cython_extensions_and_necessity():
cython_module_files = [os.path.join(PYTHON_STEM,
name.replace('.', '/') + '.pyx')
for name in CYTHON_EXTENSION_MODULE_NAMES]
extensions = [
_extension.Extension(
name=module_name,
sources=[module_file] + list(CYTHON_HELPER_C_FILES) + list(CORE_C_FILES),
include_dirs=list(EXTENSION_INCLUDE_DIRECTORIES),
libraries=list(EXTENSION_LIBRARIES),
define_macros=list(DEFINE_MACROS),
extra_compile_args=list(CFLAGS),
extra_link_args=list(LDFLAGS),
) for (module_name, module_file) in zip(list(CYTHON_EXTENSION_MODULE_NAMES), cython_module_files)
]
need_cython = BUILD_WITH_CYTHON
if not BUILD_WITH_CYTHON:
need_cython = need_cython or not commands.check_and_update_cythonization(extensions)
return commands.try_cythonize(extensions, linetracing=ENABLE_CYTHON_TRACING, mandatory=BUILD_WITH_CYTHON), need_cython
CYTHON_EXTENSION_MODULES, need_cython = cython_extensions_and_necessity()
PACKAGE_DIRECTORIES = {
'': PYTHON_STEM,
}
INSTALL_REQUIRES = (
'six>=1.5.2',
'enum34>=1.0.4',
'futures>=2.2.0',
# TODO(atash): eventually split the grpcio package into a metapackage
# depending on protobuf and the runtime component (independent of protobuf)
'protobuf>=3.0.0',
)
SETUP_REQUIRES = INSTALL_REQUIRES + (
'sphinx>=1.3',
'sphinx_rtd_theme>=0.1.8',
'six>=1.10',
)
if BUILD_WITH_CYTHON:
sys.stderr.write(
"You requested a Cython build via GRPC_PYTHON_BUILD_WITH_CYTHON, "
"but do not have Cython installed. We won't stop you from using "
"other commands, but the extension files will fail to build.\n")
elif need_cython:
sys.stderr.write(
'We could not find Cython. Setup may take 10-20 minutes.\n')
SETUP_REQUIRES += ('cython>=0.23',)
COMMAND_CLASS = {
'doc': commands.SphinxDocumentation,
'build_project_metadata': commands.BuildProjectMetadata,
'build_py': commands.BuildPy,
'build_ext': commands.BuildExt,
'gather': commands.Gather,
}
# Ensure that package data is copied over before any commands have been run:
credentials_dir = os.path.join(PYTHON_STEM, 'grpc', '_cython', '_credentials')
try:
os.mkdir(credentials_dir)
except OSError:
pass
shutil.copyfile(os.path.join('etc', 'roots.pem'),
os.path.join(credentials_dir, 'roots.pem'))
PACKAGE_DATA = {
# Binaries that may or may not be present in the final installation, but are
# mentioned here for completeness.
'grpc._cython': [
'_credentials/roots.pem',
'_windows/grpc_c.32.python',
'_windows/grpc_c.64.python',
],
}
PACKAGES = setuptools.find_packages(PYTHON_STEM)
setuptools.setup(
name='grpcio',
version=grpc_version.VERSION,
license=LICENSE,
ext_modules=CYTHON_EXTENSION_MODULES,
packages=list(PACKAGES),
package_dir=PACKAGE_DIRECTORIES,
package_data=PACKAGE_DATA,
install_requires=INSTALL_REQUIRES,
setup_requires=SETUP_REQUIRES,
cmdclass=COMMAND_CLASS,
)
| 39.675573 | 120 | 0.738432 |
from distutils import cygwinccompiler
from distutils import extension as _extension
from distutils import util
import os
import os.path
import pkg_resources
import platform
import re
import shlex
import shutil
import sys
import sysconfig
import setuptools
from setuptools.command import egg_info
egg_info.manifest_maker.template = 'PYTHON-MANIFEST.in'
PY3 = sys.version_info.major == 3
PYTHON_STEM = os.path.join('src', 'python', 'grpcio')
CORE_INCLUDE = ('include', '.',)
BORINGSSL_INCLUDE = (os.path.join('third_party', 'boringssl', 'include'),)
ZLIB_INCLUDE = (os.path.join('third_party', 'zlib'),)
os.chdir(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.abspath(PYTHON_STEM))
import _spawn_patch
import commands
import grpc_core_dependencies
import grpc_version
_spawn_patch.monkeypatch_spawn()
LICENSE = '3-clause BSD'
# present, then it will still attempt to use Cython.
BUILD_WITH_CYTHON = os.environ.get('GRPC_PYTHON_BUILD_WITH_CYTHON', False)
# Environment variable to determine whether or not to enable coverage analysis
# in Cython modules.
ENABLE_CYTHON_TRACING = os.environ.get(
'GRPC_PYTHON_ENABLE_CYTHON_TRACING', False)
# There are some situations (like on Windows) where CC, CFLAGS, and LDFLAGS are
# entirely ignored/dropped/forgotten by distutils and its Cygwin/MinGW support.
# We use these environment variables to thus get around that without locking
# ourselves in w.r.t. the multitude of operating systems this ought to build on.
# We can also use these variables as a way to inject environment-specific
# compiler/linker flags. We assume GCC-like compilers and/or MinGW as a
# reasonable default.
EXTRA_ENV_COMPILE_ARGS = os.environ.get('GRPC_PYTHON_CFLAGS', None)
EXTRA_ENV_LINK_ARGS = os.environ.get('GRPC_PYTHON_LDFLAGS', None)
if EXTRA_ENV_COMPILE_ARGS is None:
EXTRA_ENV_COMPILE_ARGS = ''
if 'win32' in sys.platform and sys.version_info < (3, 5):
# We use define flags here and don't directly add to DEFINE_MACROS below to
if '32' in platform.architecture()[0]:
EXTRA_ENV_COMPILE_ARGS += ' -D_ftime=_ftime32 -D_timeb=__timeb32 -D_ftime_s=_ftime32_s'
else:
EXTRA_ENV_COMPILE_ARGS += ' -D_ftime=_ftime64 -D_timeb=__timeb64'
elif "linux" in sys.platform or "darwin" in sys.platform:
EXTRA_ENV_COMPILE_ARGS += ' -fvisibility=hidden -fno-wrapv'
if EXTRA_ENV_LINK_ARGS is None:
EXTRA_ENV_LINK_ARGS = ''
if "linux" in sys.platform or "darwin" in sys.platform:
EXTRA_ENV_LINK_ARGS += ' -lpthread'
elif "win32" in sys.platform and sys.version_info < (3, 5):
msvcr = cygwinccompiler.get_msvcr()[0]
EXTRA_ENV_LINK_ARGS += (
' -static-libgcc -static-libstdc++ -mcrtdll={msvcr} '
'-static'.format(msvcr=msvcr))
if "linux" in sys.platform:
EXTRA_ENV_LINK_ARGS += ' -Wl,-wrap,memcpy'
EXTRA_COMPILE_ARGS = shlex.split(EXTRA_ENV_COMPILE_ARGS)
EXTRA_LINK_ARGS = shlex.split(EXTRA_ENV_LINK_ARGS)
CYTHON_EXTENSION_PACKAGE_NAMES = ()
CYTHON_EXTENSION_MODULE_NAMES = ('grpc._cython.cygrpc',)
CYTHON_HELPER_C_FILES = ()
CORE_C_FILES = tuple(grpc_core_dependencies.CORE_SOURCE_FILES)
EXTENSION_INCLUDE_DIRECTORIES = (
(PYTHON_STEM,) + CORE_INCLUDE + BORINGSSL_INCLUDE + ZLIB_INCLUDE)
EXTENSION_LIBRARIES = ()
if "linux" in sys.platform:
EXTENSION_LIBRARIES += ('rt',)
if not "win32" in sys.platform:
EXTENSION_LIBRARIES += ('m',)
if "win32" in sys.platform:
EXTENSION_LIBRARIES += ('advapi32', 'ws2_32',)
DEFINE_MACROS = (
('OPENSSL_NO_ASM', 1), ('_WIN32_WINNT', 0x600),
('GPR_BACKWARDS_COMPATIBILITY_MODE', 1),)
if "win32" in sys.platform:
DEFINE_MACROS += (('WIN32_LEAN_AND_MEAN', 1),)
if '64bit' in platform.architecture()[0]:
DEFINE_MACROS += (('MS_WIN64', 1),)
elif sys.version_info >= (3, 5):
DEFINE_MACROS += (('NTDDI_VERSION', 0x06000000),)
LDFLAGS = tuple(EXTRA_LINK_ARGS)
CFLAGS = tuple(EXTRA_COMPILE_ARGS)
if "linux" in sys.platform or "darwin" in sys.platform:
pymodinit_type = 'PyObject*' if PY3 else 'void'
pymodinit = '__attribute__((visibility ("default"))) {}'.format(pymodinit_type)
DEFINE_MACROS += (('PyMODINIT_FUNC', pymodinit),)
if 'darwin' in sys.platform and PY3:
mac_target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
if mac_target and (pkg_resources.parse_version(mac_target) <
pkg_resources.parse_version('10.7.0')):
os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.7'
os.environ['_PYTHON_HOST_PLATFORM'] = re.sub(
r'macosx-[0-9]+\.[0-9]+-(.+)',
r'macosx-10.7-\1',
util.get_platform())
def cython_extensions_and_necessity():
cython_module_files = [os.path.join(PYTHON_STEM,
name.replace('.', '/') + '.pyx')
for name in CYTHON_EXTENSION_MODULE_NAMES]
extensions = [
_extension.Extension(
name=module_name,
sources=[module_file] + list(CYTHON_HELPER_C_FILES) + list(CORE_C_FILES),
include_dirs=list(EXTENSION_INCLUDE_DIRECTORIES),
libraries=list(EXTENSION_LIBRARIES),
define_macros=list(DEFINE_MACROS),
extra_compile_args=list(CFLAGS),
extra_link_args=list(LDFLAGS),
) for (module_name, module_file) in zip(list(CYTHON_EXTENSION_MODULE_NAMES), cython_module_files)
]
need_cython = BUILD_WITH_CYTHON
if not BUILD_WITH_CYTHON:
need_cython = need_cython or not commands.check_and_update_cythonization(extensions)
return commands.try_cythonize(extensions, linetracing=ENABLE_CYTHON_TRACING, mandatory=BUILD_WITH_CYTHON), need_cython
CYTHON_EXTENSION_MODULES, need_cython = cython_extensions_and_necessity()
PACKAGE_DIRECTORIES = {
'': PYTHON_STEM,
}
INSTALL_REQUIRES = (
'six>=1.5.2',
'enum34>=1.0.4',
'futures>=2.2.0',
'protobuf>=3.0.0',
)
SETUP_REQUIRES = INSTALL_REQUIRES + (
'sphinx>=1.3',
'sphinx_rtd_theme>=0.1.8',
'six>=1.10',
)
if BUILD_WITH_CYTHON:
sys.stderr.write(
"You requested a Cython build via GRPC_PYTHON_BUILD_WITH_CYTHON, "
"but do not have Cython installed. We won't stop you from using "
"other commands, but the extension files will fail to build.\n")
elif need_cython:
sys.stderr.write(
'We could not find Cython. Setup may take 10-20 minutes.\n')
SETUP_REQUIRES += ('cython>=0.23',)
COMMAND_CLASS = {
'doc': commands.SphinxDocumentation,
'build_project_metadata': commands.BuildProjectMetadata,
'build_py': commands.BuildPy,
'build_ext': commands.BuildExt,
'gather': commands.Gather,
}
# Ensure that package data is copied over before any commands have been run:
credentials_dir = os.path.join(PYTHON_STEM, 'grpc', '_cython', '_credentials')
try:
os.mkdir(credentials_dir)
except OSError:
pass
shutil.copyfile(os.path.join('etc', 'roots.pem'),
os.path.join(credentials_dir, 'roots.pem'))
PACKAGE_DATA = {
# Binaries that may or may not be present in the final installation, but are
# mentioned here for completeness.
'grpc._cython': [
'_credentials/roots.pem',
'_windows/grpc_c.32.python',
'_windows/grpc_c.64.python',
],
}
PACKAGES = setuptools.find_packages(PYTHON_STEM)
setuptools.setup(
name='grpcio',
version=grpc_version.VERSION,
license=LICENSE,
ext_modules=CYTHON_EXTENSION_MODULES,
packages=list(PACKAGES),
package_dir=PACKAGE_DIRECTORIES,
package_data=PACKAGE_DATA,
install_requires=INSTALL_REQUIRES,
setup_requires=SETUP_REQUIRES,
cmdclass=COMMAND_CLASS,
)
| true | true |
f72809962a0c3afdf36566332c18dc62cdc19907 | 945 | py | Python | fake_rdp.py | cheeseandcereal/fake-rdp | c35bd69d2796417b68d938079806bf27f4393343 | [
"Unlicense"
] | 9 | 2020-09-07T16:50:13.000Z | 2021-09-25T21:19:54.000Z | fake_rdp.py | khast3x/fake-rdp | c35bd69d2796417b68d938079806bf27f4393343 | [
"Unlicense"
] | null | null | null | fake_rdp.py | khast3x/fake-rdp | c35bd69d2796417b68d938079806bf27f4393343 | [
"Unlicense"
] | 4 | 2020-10-31T08:52:08.000Z | 2021-10-05T17:17:36.000Z | #!/usr/bin/env python
"""Fake RDP Server"""
import socket
import time
def fake_server():
"""Start a socket on port 3389 and send init packets"""
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('0.0.0.0', 3389))
serversocket.listen(5)
while True:
try:
connection, address = serversocket.accept()
print('Recieved connection from {}'.format(address))
connection.recv(256)
# Init packet of an NLA-enabled RDP server
bts = bytearray.fromhex('030000130ed000001234000209080002000000')
connection.send(bts)
connection.recv(256)
bts = 'arbitrary string'
# Wait before sending a response (resulting in a client-side error)
time.sleep(2)
connection.send(bts.encode())
except Exception:
pass
if __name__ == "__main__":
fake_server()
| 30.483871 | 79 | 0.614815 |
import socket
import time
def fake_server():
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('0.0.0.0', 3389))
serversocket.listen(5)
while True:
try:
connection, address = serversocket.accept()
print('Recieved connection from {}'.format(address))
connection.recv(256)
bts = bytearray.fromhex('030000130ed000001234000209080002000000')
connection.send(bts)
connection.recv(256)
bts = 'arbitrary string'
time.sleep(2)
connection.send(bts.encode())
except Exception:
pass
if __name__ == "__main__":
fake_server()
| true | true |
f72809ec1a44d7488f09bb43c6c041ab9700adf5 | 6,188 | py | Python | CandlestickIndicators.py | MarcosVs98/candlestick-indicators | 5423b56751eead43569b15917d29519b4dd6f0e3 | [
"MIT"
] | null | null | null | CandlestickIndicators.py | MarcosVs98/candlestick-indicators | 5423b56751eead43569b15917d29519b4dd6f0e3 | [
"MIT"
] | null | null | null | CandlestickIndicators.py | MarcosVs98/candlestick-indicators | 5423b56751eead43569b15917d29519b4dd6f0e3 | [
"MIT"
] | null | null | null | import logging
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
class ChartIndicatorException(Exception):
pass
class PlottingExeception(ChartIndicatorException):
pass
class TraceCandlesException(ChartIndicatorException):
pass
class ErrorImplementingIndicator(ChartIndicatorException):
pass
log = logging.getLogger("candlestick-chart-indicator")
class CandlestickChartIndicator(ABC):
"""
Base class responsible for the implementation of candlestick graphics, and their data.
detail:
This class implements a "Chain of Responsibility" design pattern.
https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern.
"""
@abc.abstractmethod
def inicate(self):
pass
class MA(CandlestickChartIndicator):
"""
Class responsible for implementing a simple Moving Average that stops
filter out price fluctuations helping to identify trends.
"""
def indicate(self, data_frame, data=[], **kwargs):
try:
ma = data_frame['close'].rolling(window=kwargs.get("days", 21)).mean()
trace_avg = go.Scatter(x=ma.index, y=MA, name='MA', line=dict(color='#BEBECF'), opacity=0.8)
data.append(trace_avg)
except (ErrorImplementingIndicator, TypeError) as e:
log.warning(f"Error implementing 'ma' indicator: {e}")
finally:
return data
class EMA(CandlestickChartIndicator):
"""
Class responsible for implementing an exponential moving average
EMA = Price today * K + EMA yesterday x (1-k) where K = 2 /(N+1)
"""
def indicate(self, data_frame, data=[], **kwargs):
try:
k = (2 / (kwargs.get("days", 21) + 1))
ma = data_frame['close'].rolling(window=kwargs.get("days", 21)).mean()
ema_data = pd.DataFrame(index=ma.index)
ema_data['PRICE'] = data_frame['close']
ema_data['MA'] = ma
ema_data['EMA'] = np.NaN
ema_data['EMA'][0] = ema_data['MA'][1]
for i in range(1, len(ema_data)):
ema_data['EMA'][i] = (ema_data['PRICE'][i] * k) + ((1-k) * ema_data['EMA'][i-1])
trace_ema = go.Scatter(
x=ema_data.index, y=ema_data['MA'], name='EMA', line=dict(color='#17BECF'), opacity=0.8)
data.append(trace_ema)
except (ErrorImplementingIndicator, TypeError) as e:
log.warning(f"Error implementing 'ema' indicator: {e}")
finally:
return data
class CrossingMovingAvarege(CandlestickChartIndicator):
"""
Class responsible for implementing the crossing of moving averages that consists of indicating
buying and selling an asset whenever the averages cross.
detail:
This indicator consists of 2 sets of simple moving averages. an acquaintance
as short average or short and another known as long average or long whenever short crosses
the long down we make a sale, whenever the long crosses the short up we buy.
"""
def indicate(self, data_frame, data=[], **kwargs):
try:
short_rolling = data_frame['close'].rolling(window=kwargs.get("short_rolling", 9)).mean()
long_rolling = data_frame['close'].rolling(window=kwargs.get("long_rolling", 21)).mean()
trace_short_rolling = go.Scatter(
x=short_rolling.index, y=short_rolling, name='SHORT', line=dict(color='#17BECF'), opacity=0.5)
trace_long_rolling = go.Scatter(
x=long_rolling.index, y=long_rolling, name='LONG', line=dict(color='#17becf'), opacity=0.5)
data.append(trace_short_rolling)
data.append(trace_long_rolling)
except (ErrorImplementingIndicator, TypeError) as e:
log.warning(f"Error implementing 'crossing moving avarege' indicator: {e}")
finally:
return data
class MACD(CandlestickChartIndicator):
"""
Class responsible for implementing a MACD -> Convergence - Divergence
of the moving average, which uses 3 exponential moving averages.
"""
def indicator(self, data_frame, data=[], **kwargs):
try:
high_average = data_frame['max'].rolling(window=kwargs.get("high", 8)).mean()
low_average = data_frame['min'].rolling(window=kwargs.get("low", 8)).mean()
hilo_high = pd.DataFrame(index=data_frame.index)
hilo_low = pd.DataFrame(index=data_frame.index)
hilo_high['max'] = np.where(data_frame['close'] > high_average, low_average, np.NaN)
hilo_low['min'] = np.where(data_frame['close'] < low_average, high_average, np.NaN)
trace_high = go.Scatter(x=hilo_high.index, y=hilo_high, line=dict(color='#17BECF'), opacity=1)
trace_low = go.Scatter(x=hilo_low.index, y=hilo_low, line=dict(color='#B22222'), opacity=1)
data.append(trace_high)
data.append(trace_low)
except (ErrorImplementingIndicator, TypeError) as e:
log.warning(f"Error implementing 'macd' indicator: {e}")
finally:
return data
class BollingerBands(CandlestickChartIndicator):
"""
Class responsible for implementing boolinger bands based on variations
prices at standard deviation levels.
detail:
This indicator is able to measure price volatility.
"""
def indicate(self, data_frame, data=[], **kwargs):
try:
df_avg = data_frame['close'].rolling(window=kwargs.get("days", 21)).mean().dropna()
df_std = data_frame['close'].rolling(window=kwargs.get("days", 21)).std().dropna()
df_bollinger = pd.DataFrame(index=df_avg.index)
df_bollinger['mband'] = df_avg
df_bollinger['uband'] = df_avg + df_std.apply(lambda x: (x * 2))
df_bollinger['iband'] = df_avg - df_std.apply(lambda x: (x * 2))
df_price = data_frame[df_bollinger.index[0]:]
trace_prices = go.Candlestick(
x = df_price.index,
open = df_price['open'],
high = df_price['max'],
low = df_price['min'],
close = df_price['close'],
name='prices')
uband = go.Scatter(
x=df_bollinger.index, y=df_bollinger['uband'], name='Upper Band',
line=dict(color='#17BECF'), opacity=0.8)
mband = go.Scatter(
x=df_bollinger.index, y=df_bollinger['mband'], name='Moving Band',
line=dict(color='#B22222'), opacity=0.5)
iband = go.Scatter(
x=df_bollinger.index, y=df_bollinger['iband'], name='Lower Band',
line=dict(color='#17BECF'), opacity=0.8)
data.append(uband)
data.append(mband)
data.append(iband)
data.append(trace_prices)
except (ErrorImplementingIndicator, TypeError) as e:
log.warning(f"Error implementing 'bollinger bands' indicator: {e}")
finally:
return data
# end-of-file | 35.36 | 98 | 0.713478 | import logging
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
class ChartIndicatorException(Exception):
pass
class PlottingExeception(ChartIndicatorException):
pass
class TraceCandlesException(ChartIndicatorException):
pass
class ErrorImplementingIndicator(ChartIndicatorException):
pass
log = logging.getLogger("candlestick-chart-indicator")
class CandlestickChartIndicator(ABC):
@abc.abstractmethod
def inicate(self):
pass
class MA(CandlestickChartIndicator):
def indicate(self, data_frame, data=[], **kwargs):
try:
ma = data_frame['close'].rolling(window=kwargs.get("days", 21)).mean()
trace_avg = go.Scatter(x=ma.index, y=MA, name='MA', line=dict(color='#BEBECF'), opacity=0.8)
data.append(trace_avg)
except (ErrorImplementingIndicator, TypeError) as e:
log.warning(f"Error implementing 'ma' indicator: {e}")
finally:
return data
class EMA(CandlestickChartIndicator):
def indicate(self, data_frame, data=[], **kwargs):
try:
k = (2 / (kwargs.get("days", 21) + 1))
ma = data_frame['close'].rolling(window=kwargs.get("days", 21)).mean()
ema_data = pd.DataFrame(index=ma.index)
ema_data['PRICE'] = data_frame['close']
ema_data['MA'] = ma
ema_data['EMA'] = np.NaN
ema_data['EMA'][0] = ema_data['MA'][1]
for i in range(1, len(ema_data)):
ema_data['EMA'][i] = (ema_data['PRICE'][i] * k) + ((1-k) * ema_data['EMA'][i-1])
trace_ema = go.Scatter(
x=ema_data.index, y=ema_data['MA'], name='EMA', line=dict(color='#17BECF'), opacity=0.8)
data.append(trace_ema)
except (ErrorImplementingIndicator, TypeError) as e:
log.warning(f"Error implementing 'ema' indicator: {e}")
finally:
return data
class CrossingMovingAvarege(CandlestickChartIndicator):
def indicate(self, data_frame, data=[], **kwargs):
try:
short_rolling = data_frame['close'].rolling(window=kwargs.get("short_rolling", 9)).mean()
long_rolling = data_frame['close'].rolling(window=kwargs.get("long_rolling", 21)).mean()
trace_short_rolling = go.Scatter(
x=short_rolling.index, y=short_rolling, name='SHORT', line=dict(color='#17BECF'), opacity=0.5)
trace_long_rolling = go.Scatter(
x=long_rolling.index, y=long_rolling, name='LONG', line=dict(color='#17becf'), opacity=0.5)
data.append(trace_short_rolling)
data.append(trace_long_rolling)
except (ErrorImplementingIndicator, TypeError) as e:
log.warning(f"Error implementing 'crossing moving avarege' indicator: {e}")
finally:
return data
class MACD(CandlestickChartIndicator):
def indicator(self, data_frame, data=[], **kwargs):
try:
high_average = data_frame['max'].rolling(window=kwargs.get("high", 8)).mean()
low_average = data_frame['min'].rolling(window=kwargs.get("low", 8)).mean()
hilo_high = pd.DataFrame(index=data_frame.index)
hilo_low = pd.DataFrame(index=data_frame.index)
hilo_high['max'] = np.where(data_frame['close'] > high_average, low_average, np.NaN)
hilo_low['min'] = np.where(data_frame['close'] < low_average, high_average, np.NaN)
trace_high = go.Scatter(x=hilo_high.index, y=hilo_high, line=dict(color='#17BECF'), opacity=1)
trace_low = go.Scatter(x=hilo_low.index, y=hilo_low, line=dict(color='#B22222'), opacity=1)
data.append(trace_high)
data.append(trace_low)
except (ErrorImplementingIndicator, TypeError) as e:
log.warning(f"Error implementing 'macd' indicator: {e}")
finally:
return data
class BollingerBands(CandlestickChartIndicator):
def indicate(self, data_frame, data=[], **kwargs):
try:
df_avg = data_frame['close'].rolling(window=kwargs.get("days", 21)).mean().dropna()
df_std = data_frame['close'].rolling(window=kwargs.get("days", 21)).std().dropna()
df_bollinger = pd.DataFrame(index=df_avg.index)
df_bollinger['mband'] = df_avg
df_bollinger['uband'] = df_avg + df_std.apply(lambda x: (x * 2))
df_bollinger['iband'] = df_avg - df_std.apply(lambda x: (x * 2))
df_price = data_frame[df_bollinger.index[0]:]
trace_prices = go.Candlestick(
x = df_price.index,
open = df_price['open'],
high = df_price['max'],
low = df_price['min'],
close = df_price['close'],
name='prices')
uband = go.Scatter(
x=df_bollinger.index, y=df_bollinger['uband'], name='Upper Band',
line=dict(color='#17BECF'), opacity=0.8)
mband = go.Scatter(
x=df_bollinger.index, y=df_bollinger['mband'], name='Moving Band',
line=dict(color='#B22222'), opacity=0.5)
iband = go.Scatter(
x=df_bollinger.index, y=df_bollinger['iband'], name='Lower Band',
line=dict(color='#17BECF'), opacity=0.8)
data.append(uband)
data.append(mband)
data.append(iband)
data.append(trace_prices)
except (ErrorImplementingIndicator, TypeError) as e:
log.warning(f"Error implementing 'bollinger bands' indicator: {e}")
finally:
return data
| true | true |
f72809f71761b0df57021f843a5d34d9717f17ed | 5,673 | py | Python | App/controllers/users.py | shyyashowkat/flask_mongo | 72f48efdc9bcf5eb533dd834710e5c728afcf2eb | [
"MIT"
] | null | null | null | App/controllers/users.py | shyyashowkat/flask_mongo | 72f48efdc9bcf5eb533dd834710e5c728afcf2eb | [
"MIT"
] | null | null | null | App/controllers/users.py | shyyashowkat/flask_mongo | 72f48efdc9bcf5eb533dd834710e5c728afcf2eb | [
"MIT"
] | null | null | null | import email
import jwt
import datetime
from models.users import User
from bson.objectid import ObjectId
from utils.email_util import sent_email
from flask import jsonify, make_response
from special_variables import _secret_key
from utils.token_util import token_required
from flask_bcrypt import generate_password_hash, check_password_hash
def sign_up_controller(doc):
try:
user = User.objects(email = doc.get('email', None)).first()
if user:
return make_response(jsonify({'msg':'user already exists'}), 400)
if not (doc and doc.get('email', None)):
return make_response(jsonify({'msg':'email and password are required'}), 400)
token = jwt.encode({'email': doc.get('email'), 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes = 30)}, _secret_key, 'HS256')
subject = 'Registration Token'
return sent_email(subject, [doc.get('email')], token), 200
except Exception as e:
return make_response(jsonify({'msg': e.args }), 400)
@token_required
def registration_controller(data, doc):
try:
user = User.objects(email = data.get('email', None)).first()
if user:
return make_response(jsonify({'msg':'user already exists'}), 400)
if not (doc and doc.get('password', None)):
return make_response(jsonify({'msg':'password is required'}), 400)
user = User(email = data.get('email'), password = generate_password_hash(doc.get('password', None)), created_at = datetime.datetime.now(), updated_at = datetime.datetime.now())
user.save()
return make_response(jsonify({"msg": "user created successfully"}), 201)
except Exception as e:
return make_response(jsonify({'msg': e.args }), 400)
def get_users_controller():
try:
users = [{'email': user.email} for user in User.objects]
if not users:
return make_response(jsonify({'msg': "users list is empty"}), 404)
return make_response(jsonify({'users': users}), 200)
except Exception as e:
return make_response(jsonify({'msg': e.args }), 400)
def get_user_controller(id):
try:
user = User.objects(id = ObjectId(id)).first()
if not user:
return make_response(jsonify({"msg": f"user not found, with id: {id}"}), 404)
return make_response(jsonify({'email': user.email}), 200)
except Exception as e:
return make_response(jsonify({'msg':e.args }), 400)
@token_required
def delete_user_controller(data, id, doc):
try:
user = User.objects(id = ObjectId(id)).first()
if not user:
return make_response(jsonify({"msg": f"user not found, with id: {id}"}), 404)
if not (doc and doc.get('email', None) and doc.get('password', None)):
return make_response(jsonify({'msg':'email and password are required'}), 400)
if not (user.email == doc.get('email') and check_password_hash(user.password[2:-1], doc['password'])):
return make_response(jsonify({'msg':'wrong email or password'}), 400)
user.delete()
return make_response(jsonify({"msg": f"user deleted successfully, with id: {id}"}), 204)
except Exception as e:
return make_response(jsonify({'msg':e.args}), 400)
def user_login_controller(doc):
try:
user = User.objects(email = doc.get('email', None)).first()
if not (user and doc.get('password', None)):
return make_response(jsonify({"msg": f"user not exists or incorrect password", "required fields": ['email', 'password'] }), 404)
if user.password[0] != '$':
password = user.password.split("'")[1]
else:
password = user.password
if not check_password_hash(password, doc['password']):
return make_response(jsonify({"msg": "password is incorrect"}))
token = jwt.encode({'email': user.email, 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=24)}, _secret_key, 'HS256')
return make_response(jsonify({"msg": f"LoggedIn successfully", "token": token}), 200)
except Exception as e:
return make_response(jsonify({'msg':f'{e.args} or invalid data'}), 400)
def forget_password_controller(doc):
try:
email = doc.get('email', None)
user = User.objects(email = email).first()
if not user:
return make_response(jsonify({'msg':f'user not found, with email {email}' } ), 404)
token = jwt.encode({'email': user.email, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes = 20)}, _secret_key, 'HS256')
subject = 'Forget Password Token'
return sent_email(subject, [email], token)
except Exception as e:
return make_response(jsonify({'msg': 'invalid data'}), 400)
@token_required
def reset_password_controller(data, doc):
try:
new_password = doc.get('new_password', None)
if not new_password:
return make_response(jsonify({'msg': 'new password is required'}), 400)
user = User.objects(email = data['email']).first()
if not user:
return make_response(jsonify({"msg": f"user not found, with email: {data['email']}"}), 404)
user.update(email = user['email'], password = str(generate_password_hash(new_password)), updated_at = datetime.datetime.now())
subject = 'Password reset successful'
body = f'your password has been reset successfully, your new password is: {new_password}'
return sent_email(subject, [user.email], body)
except Exception as e:
return make_response(jsonify({'msg':e.args, 'status': 500}))
| 46.884298 | 184 | 0.640931 | import email
import jwt
import datetime
from models.users import User
from bson.objectid import ObjectId
from utils.email_util import sent_email
from flask import jsonify, make_response
from special_variables import _secret_key
from utils.token_util import token_required
from flask_bcrypt import generate_password_hash, check_password_hash
def sign_up_controller(doc):
try:
user = User.objects(email = doc.get('email', None)).first()
if user:
return make_response(jsonify({'msg':'user already exists'}), 400)
if not (doc and doc.get('email', None)):
return make_response(jsonify({'msg':'email and password are required'}), 400)
token = jwt.encode({'email': doc.get('email'), 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes = 30)}, _secret_key, 'HS256')
subject = 'Registration Token'
return sent_email(subject, [doc.get('email')], token), 200
except Exception as e:
return make_response(jsonify({'msg': e.args }), 400)
@token_required
def registration_controller(data, doc):
try:
user = User.objects(email = data.get('email', None)).first()
if user:
return make_response(jsonify({'msg':'user already exists'}), 400)
if not (doc and doc.get('password', None)):
return make_response(jsonify({'msg':'password is required'}), 400)
user = User(email = data.get('email'), password = generate_password_hash(doc.get('password', None)), created_at = datetime.datetime.now(), updated_at = datetime.datetime.now())
user.save()
return make_response(jsonify({"msg": "user created successfully"}), 201)
except Exception as e:
return make_response(jsonify({'msg': e.args }), 400)
def get_users_controller():
try:
users = [{'email': user.email} for user in User.objects]
if not users:
return make_response(jsonify({'msg': "users list is empty"}), 404)
return make_response(jsonify({'users': users}), 200)
except Exception as e:
return make_response(jsonify({'msg': e.args }), 400)
def get_user_controller(id):
try:
user = User.objects(id = ObjectId(id)).first()
if not user:
return make_response(jsonify({"msg": f"user not found, with id: {id}"}), 404)
return make_response(jsonify({'email': user.email}), 200)
except Exception as e:
return make_response(jsonify({'msg':e.args }), 400)
@token_required
def delete_user_controller(data, id, doc):
try:
user = User.objects(id = ObjectId(id)).first()
if not user:
return make_response(jsonify({"msg": f"user not found, with id: {id}"}), 404)
if not (doc and doc.get('email', None) and doc.get('password', None)):
return make_response(jsonify({'msg':'email and password are required'}), 400)
if not (user.email == doc.get('email') and check_password_hash(user.password[2:-1], doc['password'])):
return make_response(jsonify({'msg':'wrong email or password'}), 400)
user.delete()
return make_response(jsonify({"msg": f"user deleted successfully, with id: {id}"}), 204)
except Exception as e:
return make_response(jsonify({'msg':e.args}), 400)
def user_login_controller(doc):
try:
user = User.objects(email = doc.get('email', None)).first()
if not (user and doc.get('password', None)):
return make_response(jsonify({"msg": f"user not exists or incorrect password", "required fields": ['email', 'password'] }), 404)
if user.password[0] != '$':
password = user.password.split("'")[1]
else:
password = user.password
if not check_password_hash(password, doc['password']):
return make_response(jsonify({"msg": "password is incorrect"}))
token = jwt.encode({'email': user.email, 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=24)}, _secret_key, 'HS256')
return make_response(jsonify({"msg": f"LoggedIn successfully", "token": token}), 200)
except Exception as e:
return make_response(jsonify({'msg':f'{e.args} or invalid data'}), 400)
def forget_password_controller(doc):
try:
email = doc.get('email', None)
user = User.objects(email = email).first()
if not user:
return make_response(jsonify({'msg':f'user not found, with email {email}' } ), 404)
token = jwt.encode({'email': user.email, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes = 20)}, _secret_key, 'HS256')
subject = 'Forget Password Token'
return sent_email(subject, [email], token)
except Exception as e:
return make_response(jsonify({'msg': 'invalid data'}), 400)
@token_required
def reset_password_controller(data, doc):
try:
new_password = doc.get('new_password', None)
if not new_password:
return make_response(jsonify({'msg': 'new password is required'}), 400)
user = User.objects(email = data['email']).first()
if not user:
return make_response(jsonify({"msg": f"user not found, with email: {data['email']}"}), 404)
user.update(email = user['email'], password = str(generate_password_hash(new_password)), updated_at = datetime.datetime.now())
subject = 'Password reset successful'
body = f'your password has been reset successfully, your new password is: {new_password}'
return sent_email(subject, [user.email], body)
except Exception as e:
return make_response(jsonify({'msg':e.args, 'status': 500}))
| true | true |
f7280a26b72db20d7bf104af5bdb36d6c33c8284 | 1,883 | py | Python | utils/draw.py | NLP-Discourse-SoochowU/rst_dp2019Bottom2Up | ac1624127c9c8a3301685193ac8239357e01f6ca | [
"MIT"
] | 1 | 2020-08-18T01:28:07.000Z | 2020-08-18T01:28:07.000Z | utils/draw.py | NLP-Discourse-SoochowU/rst_dp2019 | ac1624127c9c8a3301685193ac8239357e01f6ca | [
"MIT"
] | null | null | null | utils/draw.py | NLP-Discourse-SoochowU/rst_dp2019 | ac1624127c9c8a3301685193ac8239357e01f6ca | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
@Author: lyzhang
@Date: 2018.5.23
@Description:
"""
from config import *
from parser_model.parser import Parser
from utils.file_util import *
from parser_model.form_data import form_data
from nltk.draw.util import CanvasFrame, TextWidget
from nltk.draw import TreeWidget
from nltk import Tree
def draw_gold_test():
"""
从文件读取数据创建rst_tree对象
:return:
"""
form_data_o = form_data()
parser = Parser()
for file_name in os.listdir(RST_DT_TEST_PATH):
if file_name.endswith('.out.dis'):
root = form_data_o.build_one_tree(RST_DT_TEST_PATH, file_name)
parser.tmp_edu = 1
strtree = parser.parse2strtree(root)
save_path = TREES_PARSED + "/gold_test_trees/" + root.file_name.split(".")[0] + ".ps"
draw_one_tree(strtree, save_path)
def draw_all_parsed():
"""
将生文本画出树
:return:
"""
strtrees_dict_path = TREES_PARSED + "/strtrees_dict.pkl"
strtrees_dict = load_data(strtrees_dict_path)
for draw_file in strtrees_dict.keys():
strtree = strtrees_dict[draw_file]
draw_one_tree(strtree, draw_file)
def draw_one_tree(strtree, draw_file):
cf = CanvasFrame()
t = Tree.fromstring(strtree)
tc = TreeWidget(cf.canvas(), t, draggable=1)
cf.add_widget(tc, 1200, 0) # (10,10) offsets
# edus 文本
edus_txt = ""
c = cf.canvas()
edu_path = RAW_TXT + "/" + draw_file.split("/")[2].split(".")[0] + ".out.edu"
with open(edu_path, "r") as f:
for line in f:
edus_txt += line
edus_txt = TextWidget(c, edus_txt, draggable=1)
cf.add_widget(edus_txt, 1400, 0)
user_choice = input("直接打印(a) or 存到文件(b): ")
if user_choice == "a":
cf.mainloop()
else:
cf.print_to_file(draw_file)
cf.destroy()
| 28.969231 | 98 | 0.6171 |
from config import *
from parser_model.parser import Parser
from utils.file_util import *
from parser_model.form_data import form_data
from nltk.draw.util import CanvasFrame, TextWidget
from nltk.draw import TreeWidget
from nltk import Tree
def draw_gold_test():
form_data_o = form_data()
parser = Parser()
for file_name in os.listdir(RST_DT_TEST_PATH):
if file_name.endswith('.out.dis'):
root = form_data_o.build_one_tree(RST_DT_TEST_PATH, file_name)
parser.tmp_edu = 1
strtree = parser.parse2strtree(root)
save_path = TREES_PARSED + "/gold_test_trees/" + root.file_name.split(".")[0] + ".ps"
draw_one_tree(strtree, save_path)
def draw_all_parsed():
strtrees_dict_path = TREES_PARSED + "/strtrees_dict.pkl"
strtrees_dict = load_data(strtrees_dict_path)
for draw_file in strtrees_dict.keys():
strtree = strtrees_dict[draw_file]
draw_one_tree(strtree, draw_file)
def draw_one_tree(strtree, draw_file):
cf = CanvasFrame()
t = Tree.fromstring(strtree)
tc = TreeWidget(cf.canvas(), t, draggable=1)
cf.add_widget(tc, 1200, 0)
edus_txt = ""
c = cf.canvas()
edu_path = RAW_TXT + "/" + draw_file.split("/")[2].split(".")[0] + ".out.edu"
with open(edu_path, "r") as f:
for line in f:
edus_txt += line
edus_txt = TextWidget(c, edus_txt, draggable=1)
cf.add_widget(edus_txt, 1400, 0)
user_choice = input("直接打印(a) or 存到文件(b): ")
if user_choice == "a":
cf.mainloop()
else:
cf.print_to_file(draw_file)
cf.destroy()
| true | true |
f7280a319b602b7ac5975fbaaf74eac97931a87b | 7,877 | py | Python | ros/src/tl_detector/tl_detector.py | nr-patel/NP-SDC-T3-P4-Capstone-Project | d20b4cb009c72f9d1b6fd8f36aca2af4c7bffb08 | [
"MIT"
] | 9 | 2018-03-11T20:07:40.000Z | 2021-04-16T06:29:36.000Z | ros/src/tl_detector/tl_detector.py | nr-patel/NP-SDC-T3-P4-Capstone-Project | d20b4cb009c72f9d1b6fd8f36aca2af4c7bffb08 | [
"MIT"
] | 7 | 2018-03-12T03:43:38.000Z | 2018-03-29T14:18:11.000Z | ros/src/tl_detector/tl_detector.py | nr-patel/NP-SDC-T3-P4-Capstone-Project | d20b4cb009c72f9d1b6fd8f36aca2af4c7bffb08 | [
"MIT"
] | 9 | 2018-03-11T20:36:49.000Z | 2019-08-28T09:59:29.000Z | #!/usr/bin/env python
import rospy
from std_msgs.msg import Int32, Float32MultiArray
from std_msgs.msg import MultiArrayDimension, MultiArrayDimension
from geometry_msgs.msg import PoseStamped, Pose
from styx_msgs.msg import TrafficLightArray, TrafficLight
from styx_msgs.msg import Lane
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
from light_classification.tl_classifier import TLClassifier
import tf
import cv2
import yaml
import math
import numpy as np
# For now state is ground truth, so no need to have a cnt threshold
STATE_COUNT_THRESHOLD = 0
class TLDetector(object):
def __init__(self):
rospy.init_node('tl_detector')
self.pose = None
self.waypoints = None
self.camera_image = None
self.lights = None
self.has_image = False # we don't have image yet
self.pose_wp_idx = None
self.tl_wp_idx = [] # Waypoint indices of traffic lights
self.tl_xy = [] # Stop line positions of traffic lights
config_string = rospy.get_param("/traffic_light_config")
self.config = yaml.load(config_string)
self.bridge = CvBridge()
self.use_simulator_classifier = rospy.get_param('~on_simulator')
rospy.loginfo("Is on simulator? %s" , self.use_simulator_classifier)
self.light_classifier = TLClassifier(isSimulator = self.use_simulator_classifier)
self.listener = tf.TransformListener()
self.state = TrafficLight.UNKNOWN
self.last_state = TrafficLight.UNKNOWN
self.state_count = 0
self.upcoming_red_light_pub = rospy.Publisher('/traffic_waypoint', Float32MultiArray, queue_size=15)
sub1 = rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb)
sub2 = rospy.Subscriber('/base_waypoints', Lane, self.waypoints_cb)
# Add closest waypoint subscriber to receive current closest waypoint from waypoint WaypointUpdater
sub4 = rospy.Subscriber('/closest_waypoint', Int32, self.closest_cb)
'''
/vehicle/traffic_lights provides you with the location of the traffic light in 3D map space and
helps you acquire an accurate ground truth data source for the traffic light
classifier by sending the current color state of all traffic lights in the
simulator. When testing on the vehicle, the color state will not be available. You'll need to
rely on the position of the light and the camera image to predict it.
'''
sub3 = rospy.Subscriber('/vehicle/traffic_lights', TrafficLightArray, self.traffic_cb)
sub6 = rospy.Subscriber('/image_color', Image, self.image_cb)
rospy.spin()
def pose_cb(self, msg):
self.pose = msg
def waypoints_cb(self, waypoints):
self.waypoints = waypoints.waypoints
N = len(self.waypoints)
# Waypoints are only loaded once so at boot find closest waypoint idx of each traffic light stop line
for x, y in self.config['stop_line_positions']:
ds = []
[ds.append(math.sqrt((x-self.waypoints[i].pose.pose.position.x)**2 + (y-self.waypoints[i].pose.pose.position.y)**2)) for i in range(N)]
best_idx = np.argmin(ds)
self.tl_wp_idx.append(best_idx)
self.tl_xy.append([x, y])
def closest_cb(self, msg):
self.pose_wp_idx = msg.data
def traffic_cb(self, msg):
self.lights = msg.lights
def image_cb(self, msg):
"""Identifies red lights in the incoming camera image and publishes the index
of the waypoint closest to the red light's stop line to /traffic_waypoint
Args:
msg (Image): image from car-mounted camera
"""
self.has_image = True
self.camera_image = msg
# Every time waypoint updater finds new closest waypoint, re-calculate location
# of nearest stop line, waypoint closest to nearest stop line, and state of nearest light
closest_tl_xy, light_wp, state = self.process_traffic_lights()
if state == TrafficLight.GREEN:
light_wp = -1
'''
Publish upcoming red lights at camera frequency.
Each predicted state has to occur `STATE_COUNT_THRESHOLD` number
of times till we start using it. Otherwise the previous stable state is
used.
'''
# Publish nearest waypoint and x-y coords of stop line so waypoint updater can slow if necessary
red_light_pub = Float32MultiArray()
red_light_pub.layout.dim.append(MultiArrayDimension())
red_light_pub.layout.dim[0].label = "length"
red_light_pub.layout.dim[0].size = 3
red_light_pub.layout.dim[0].stride = 3
red_light_pub.layout.data_offset = 0
red_light_pub.data = [light_wp, closest_tl_xy[0], closest_tl_xy[1]]
self.upcoming_red_light_pub.publish(red_light_pub)
def get_light_state(self, light):
"""Determines the current color of the traffic light
Args:
light (TrafficLight): light to classify
Returns:
int: ID of traffic light color (specified in styx_msgs/TrafficLight)
"""
if(not self.has_image):
self.prev_light_loc = None
return False
cv_image = self.bridge.imgmsg_to_cv2(self.camera_image, "bgr8")
image = np.asanyarray(cv_image)
# Get classification
return self.light_classifier.get_classification(image)
def get_state_string(self, state):
if (state == 0):
state_s = "RED"
elif (state == 1):
state_s = "YELLOW"
elif (state == 2):
state_s = "GREEN"
else:
state_s = "UNKNOWN"
return state_s
def process_traffic_lights(self):
"""Finds closest visible traffic light, if one exists, and determines its
location and color
Returns:
int: index of waypoint closest to the upcoming stop line for a traffic light (-1 if none exists)
int: ID of traffic light color (specified in styx_msgs/TrafficLight)
list (float): x,y coordinates of nearest traffic light stopline
"""
closest_tl_wp_idx = 0
# This assumes ego always travels around loop in start direction. Should be fixed to use Yuri's calculation from waypoint_updater.py.
closest_tl_wp_idx = min(self.tl_wp_idx)
closest_tl_xy = self.tl_xy[np.argmin(self.tl_wp_idx)]
if (self.pose_wp_idx):
for i in range(len(self.tl_wp_idx)):
if self.tl_wp_idx[i] > self.pose_wp_idx:
closest_tl_wp_idx = self.tl_wp_idx[i]
closest_tl_xy = self.tl_xy[i]
break
# We now have x,y position of stopline of closest traffic light.
# Initially, rather than use camera img and classifier, we can get ground truth state of that light from the simulator.
stop_x = closest_tl_xy[0]
stop_y = closest_tl_xy[1]
state = TrafficLight.UNKNOWN
if (self.lights):
n_lights = len(self.lights)
ds = []
[ds.append(math.sqrt((stop_x - self.lights[i].pose.pose.position.x)**2 + (stop_y - self.lights[i].pose.pose.position.y)**2)) for i in range(n_lights)]
if (self.use_simulator_classifier):
groundtruth = self.lights[np.argmin(ds)].state
rospy.loginfo('groundtruth is {}'.format(self.get_state_string(groundtruth)))
state = self.get_light_state(self.lights[np.argmin(ds)])
rospy.loginfo('state is {}'.format(self.get_state_string(state)))
return closest_tl_xy, closest_tl_wp_idx, state
if __name__ == '__main__':
try:
TLDetector()
except rospy.ROSInterruptException:
rospy.logerr('Could not start traffic node.')
| 39.582915 | 162 | 0.656849 |
import rospy
from std_msgs.msg import Int32, Float32MultiArray
from std_msgs.msg import MultiArrayDimension, MultiArrayDimension
from geometry_msgs.msg import PoseStamped, Pose
from styx_msgs.msg import TrafficLightArray, TrafficLight
from styx_msgs.msg import Lane
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
from light_classification.tl_classifier import TLClassifier
import tf
import cv2
import yaml
import math
import numpy as np
STATE_COUNT_THRESHOLD = 0
class TLDetector(object):
def __init__(self):
rospy.init_node('tl_detector')
self.pose = None
self.waypoints = None
self.camera_image = None
self.lights = None
self.has_image = False
self.pose_wp_idx = None
self.tl_wp_idx = [] # Waypoint indices of traffic lights
self.tl_xy = [] # Stop line positions of traffic lights
config_string = rospy.get_param("/traffic_light_config")
self.config = yaml.load(config_string)
self.bridge = CvBridge()
self.use_simulator_classifier = rospy.get_param('~on_simulator')
rospy.loginfo("Is on simulator? %s" , self.use_simulator_classifier)
self.light_classifier = TLClassifier(isSimulator = self.use_simulator_classifier)
self.listener = tf.TransformListener()
self.state = TrafficLight.UNKNOWN
self.last_state = TrafficLight.UNKNOWN
self.state_count = 0
self.upcoming_red_light_pub = rospy.Publisher('/traffic_waypoint', Float32MultiArray, queue_size=15)
sub1 = rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb)
sub2 = rospy.Subscriber('/base_waypoints', Lane, self.waypoints_cb)
# Add closest waypoint subscriber to receive current closest waypoint from waypoint WaypointUpdater
sub4 = rospy.Subscriber('/closest_waypoint', Int32, self.closest_cb)
sub3 = rospy.Subscriber('/vehicle/traffic_lights', TrafficLightArray, self.traffic_cb)
sub6 = rospy.Subscriber('/image_color', Image, self.image_cb)
rospy.spin()
def pose_cb(self, msg):
self.pose = msg
def waypoints_cb(self, waypoints):
self.waypoints = waypoints.waypoints
N = len(self.waypoints)
# Waypoints are only loaded once so at boot find closest waypoint idx of each traffic light stop line
for x, y in self.config['stop_line_positions']:
ds = []
[ds.append(math.sqrt((x-self.waypoints[i].pose.pose.position.x)**2 + (y-self.waypoints[i].pose.pose.position.y)**2)) for i in range(N)]
best_idx = np.argmin(ds)
self.tl_wp_idx.append(best_idx)
self.tl_xy.append([x, y])
def closest_cb(self, msg):
self.pose_wp_idx = msg.data
def traffic_cb(self, msg):
self.lights = msg.lights
def image_cb(self, msg):
self.has_image = True
self.camera_image = msg
# Every time waypoint updater finds new closest waypoint, re-calculate location
# of nearest stop line, waypoint closest to nearest stop line, and state of nearest light
closest_tl_xy, light_wp, state = self.process_traffic_lights()
if state == TrafficLight.GREEN:
light_wp = -1
# Publish nearest waypoint and x-y coords of stop line so waypoint updater can slow if necessary
red_light_pub = Float32MultiArray()
red_light_pub.layout.dim.append(MultiArrayDimension())
red_light_pub.layout.dim[0].label = "length"
red_light_pub.layout.dim[0].size = 3
red_light_pub.layout.dim[0].stride = 3
red_light_pub.layout.data_offset = 0
red_light_pub.data = [light_wp, closest_tl_xy[0], closest_tl_xy[1]]
self.upcoming_red_light_pub.publish(red_light_pub)
def get_light_state(self, light):
if(not self.has_image):
self.prev_light_loc = None
return False
cv_image = self.bridge.imgmsg_to_cv2(self.camera_image, "bgr8")
image = np.asanyarray(cv_image)
# Get classification
return self.light_classifier.get_classification(image)
def get_state_string(self, state):
if (state == 0):
state_s = "RED"
elif (state == 1):
state_s = "YELLOW"
elif (state == 2):
state_s = "GREEN"
else:
state_s = "UNKNOWN"
return state_s
def process_traffic_lights(self):
closest_tl_wp_idx = 0
# This assumes ego always travels around loop in start direction. Should be fixed to use Yuri's calculation from waypoint_updater.py.
closest_tl_wp_idx = min(self.tl_wp_idx)
closest_tl_xy = self.tl_xy[np.argmin(self.tl_wp_idx)]
if (self.pose_wp_idx):
for i in range(len(self.tl_wp_idx)):
if self.tl_wp_idx[i] > self.pose_wp_idx:
closest_tl_wp_idx = self.tl_wp_idx[i]
closest_tl_xy = self.tl_xy[i]
break
stop_x = closest_tl_xy[0]
stop_y = closest_tl_xy[1]
state = TrafficLight.UNKNOWN
if (self.lights):
n_lights = len(self.lights)
ds = []
[ds.append(math.sqrt((stop_x - self.lights[i].pose.pose.position.x)**2 + (stop_y - self.lights[i].pose.pose.position.y)**2)) for i in range(n_lights)]
if (self.use_simulator_classifier):
groundtruth = self.lights[np.argmin(ds)].state
rospy.loginfo('groundtruth is {}'.format(self.get_state_string(groundtruth)))
state = self.get_light_state(self.lights[np.argmin(ds)])
rospy.loginfo('state is {}'.format(self.get_state_string(state)))
return closest_tl_xy, closest_tl_wp_idx, state
if __name__ == '__main__':
try:
TLDetector()
except rospy.ROSInterruptException:
rospy.logerr('Could not start traffic node.')
| true | true |
f7280a5a37004164250aef97e15c2187d83ce87b | 16,962 | py | Python | nova/tests/unit/api/openstack/compute/test_create_backup.py | zjzh/nova | 7bb21723171c59b93e28f5d508c2b6df39220f13 | [
"Apache-2.0"
] | 1,874 | 2015-01-04T05:18:34.000Z | 2022-03-31T03:30:28.000Z | nova/tests/unit/api/openstack/compute/test_create_backup.py | zjzh/nova | 7bb21723171c59b93e28f5d508c2b6df39220f13 | [
"Apache-2.0"
] | 40 | 2015-04-13T02:32:42.000Z | 2022-02-16T02:28:06.000Z | nova/tests/unit/api/openstack/compute/test_create_backup.py | zjzh/nova | 7bb21723171c59b93e28f5d508c2b6df39220f13 | [
"Apache-2.0"
] | 1,996 | 2015-01-04T15:11:51.000Z | 2022-03-31T11:03:13.000Z | # Copyright 2011 OpenStack Foundation
# Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
from oslo_utils import timeutils
import webob
from nova.api.openstack import common
from nova.api.openstack.compute import create_backup \
as create_backup_v21
from nova.compute import api
from nova.compute import utils as compute_utils
from nova import exception
from nova import test
from nova.tests.unit.api.openstack.compute import admin_only_action_common
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import fake_instance
class CreateBackupTestsV21(admin_only_action_common.CommonMixin,
test.NoDBTestCase):
create_backup = create_backup_v21
controller_name = 'CreateBackupController'
validation_error = exception.ValidationError
def setUp(self):
super(CreateBackupTestsV21, self).setUp()
self.controller = getattr(self.create_backup, self.controller_name)()
self.compute_api = self.controller.compute_api
patch_get = mock.patch.object(self.compute_api, 'get')
self.mock_get = patch_get.start()
self.addCleanup(patch_get.stop)
@mock.patch.object(common, 'check_img_metadata_properties_quota')
@mock.patch.object(api.API, 'backup')
def test_create_backup_with_metadata(self, mock_backup, mock_check_image):
metadata = {'123': 'asdf'}
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': 1,
'metadata': metadata,
},
}
image = dict(id='fake-image-id', status='ACTIVE', name='Backup 1',
properties=metadata)
instance = fake_instance.fake_instance_obj(self.context)
self.mock_get.return_value = instance
mock_backup.return_value = image
res = self.controller._create_backup(self.req, instance.uuid,
body=body)
mock_check_image.assert_called_once_with(self.context, metadata)
mock_backup.assert_called_once_with(self.context, instance, 'Backup 1',
'daily', 1,
extra_properties=metadata)
self.assertEqual(202, res.status_int)
self.assertIn('fake-image-id', res.headers['Location'])
def test_create_backup_no_name(self):
# Name is required for backups.
body = {
'createBackup': {
'backup_type': 'daily',
'rotation': 1,
},
}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
def test_create_backup_name_with_leading_trailing_spaces(self):
body = {
'createBackup': {
'name': ' test ',
'backup_type': 'daily',
'rotation': 1,
},
}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
@mock.patch.object(common, 'check_img_metadata_properties_quota')
@mock.patch.object(api.API, 'backup')
def test_create_backup_name_with_leading_trailing_spaces_compat_mode(
self, mock_backup, mock_check_image):
body = {
'createBackup': {
'name': ' test ',
'backup_type': 'daily',
'rotation': 1,
},
}
image = dict(id='fake-image-id', status='ACTIVE', name='Backup 1',
properties={})
instance = fake_instance.fake_instance_obj(self.context)
self.mock_get.return_value = instance
mock_backup.return_value = image
self.req.set_legacy_v2()
self.controller._create_backup(self.req, instance.uuid,
body=body)
mock_check_image.assert_called_once_with(self.context, {})
mock_backup.assert_called_once_with(self.context, instance, 'test',
'daily', 1,
extra_properties={})
def test_create_backup_no_rotation(self):
# Rotation is required for backup requests.
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
},
}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
def test_create_backup_negative_rotation(self):
"""Rotation must be greater than or equal to zero
for backup requests
"""
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': -1,
},
}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
def test_create_backup_negative_rotation_with_string_number(self):
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': '-1',
},
}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
def test_create_backup_rotation_with_empty_string(self):
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': '',
},
}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
def test_create_backup_no_backup_type(self):
# Backup Type (daily or weekly) is required for backup requests.
body = {
'createBackup': {
'name': 'Backup 1',
'rotation': 1,
},
}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
def test_create_backup_non_dict_metadata(self):
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': 1,
'metadata': 'non_dict',
},
}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
def test_create_backup_bad_entity(self):
body = {'createBackup': 'go'}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
@mock.patch.object(common, 'check_img_metadata_properties_quota')
@mock.patch.object(api.API, 'backup')
def test_create_backup_rotation_is_zero(self, mock_backup,
mock_check_image):
# The happy path for creating backups if rotation is zero.
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': 0,
},
}
image = dict(id='fake-image-id', status='ACTIVE', name='Backup 1',
properties={})
instance = fake_instance.fake_instance_obj(self.context)
self.mock_get.return_value = instance
mock_backup.return_value = image
res = self.controller._create_backup(self.req, instance.uuid,
body=body)
mock_check_image.assert_called_once_with(self.context, {})
mock_backup.assert_called_once_with(self.context, instance, 'Backup 1',
'daily', 0,
extra_properties={})
self.assertEqual(202, res.status_int)
self.assertNotIn('Location', res.headers)
@mock.patch.object(common, 'check_img_metadata_properties_quota')
@mock.patch.object(api.API, 'backup')
def test_create_backup_rotation_is_positive(self, mock_backup,
mock_check_image):
# The happy path for creating backups if rotation is positive.
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': 1,
},
}
image = dict(id='fake-image-id', status='ACTIVE', name='Backup 1',
properties={})
instance = fake_instance.fake_instance_obj(self.context)
self.mock_get.return_value = instance
mock_backup.return_value = image
res = self.controller._create_backup(self.req, instance.uuid,
body=body)
mock_check_image.assert_called_once_with(self.context, {})
mock_backup.assert_called_once_with(self.context, instance, 'Backup 1',
'daily', 1,
extra_properties={})
self.assertEqual(202, res.status_int)
self.assertIn('fake-image-id', res.headers['Location'])
@mock.patch.object(common, 'check_img_metadata_properties_quota')
@mock.patch.object(api.API, 'backup')
def test_create_backup_rotation_is_string_number(
self, mock_backup, mock_check_image):
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': '1',
},
}
image = dict(id='fake-image-id', status='ACTIVE', name='Backup 1',
properties={})
instance = fake_instance.fake_instance_obj(self.context)
self.mock_get.return_value = instance
mock_backup.return_value = image
res = self.controller._create_backup(self.req, instance['uuid'],
body=body)
mock_check_image.assert_called_once_with(self.context, {})
mock_backup.assert_called_once_with(self.context, instance, 'Backup 1',
'daily', 1,
extra_properties={})
self.assertEqual(202, res.status_int)
self.assertIn('fake-image-id', res.headers['Location'])
@mock.patch.object(common, 'check_img_metadata_properties_quota')
@mock.patch.object(api.API, 'backup', return_value=dict(
id='fake-image-id', status='ACTIVE', name='Backup 1', properties={}))
def test_create_backup_v2_45(self, mock_backup, mock_check_image):
"""Tests the 2.45 microversion to ensure the Location header is not
in the response.
"""
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': '1',
},
}
instance = fake_instance.fake_instance_obj(self.context)
self.mock_get.return_value = instance
req = fakes.HTTPRequest.blank('', version='2.45')
res = self.controller._create_backup(req, instance['uuid'], body=body)
self.assertIsInstance(res, dict)
self.assertEqual('fake-image-id', res['image_id'])
@mock.patch.object(common, 'check_img_metadata_properties_quota')
@mock.patch.object(api.API, 'backup')
def test_create_backup_raises_conflict_on_invalid_state(self,
mock_backup, mock_check_image):
body_map = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': 1,
},
}
instance = fake_instance.fake_instance_obj(self.context)
self.mock_get.return_value = instance
mock_backup.side_effect = exception.InstanceInvalidState(
attr='vm_state', instance_uuid=instance.uuid,
state='foo', method='backup')
ex = self.assertRaises(webob.exc.HTTPConflict,
self.controller._create_backup,
self.req, instance.uuid,
body=body_map)
self.assertIn("Cannot 'createBackup' instance %(id)s"
% {'id': instance.uuid}, ex.explanation)
def test_create_backup_with_non_existed_instance(self):
body_map = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': 1,
},
}
uuid = fakes.FAKE_UUID
self.mock_get.side_effect = exception.InstanceNotFound(
instance_id=uuid)
self.assertRaises(webob.exc.HTTPNotFound,
self.controller._create_backup,
self.req, uuid, body=body_map)
def test_create_backup_with_invalid_create_backup(self):
body = {
'createBackupup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': 1,
},
}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
@mock.patch.object(common, 'check_img_metadata_properties_quota')
@mock.patch.object(compute_utils, 'is_volume_backed_instance',
return_value=True)
def test_backup_volume_backed_instance(self, mock_is_volume_backed,
mock_check_image):
body = {
'createBackup': {
'name': 'BackupMe',
'backup_type': 'daily',
'rotation': 3
},
}
updates = {'vm_state': 'active',
'task_state': None,
'launched_at': timeutils.utcnow()}
instance = fake_instance.fake_instance_obj(self.context, **updates)
instance.image_ref = None
self.mock_get.return_value = instance
ex = self.assertRaises(webob.exc.HTTPBadRequest,
self.controller._create_backup,
self.req, instance['uuid'], body=body)
mock_check_image.assert_called_once_with(self.context, {})
mock_is_volume_backed.assert_called_once_with(self.context, instance)
self.assertIn('Backup is not supported for volume-backed instances',
str(ex))
class CreateBackupTestsV239(test.NoDBTestCase):
def setUp(self):
super(CreateBackupTestsV239, self).setUp()
self.controller = create_backup_v21.CreateBackupController()
self.req = fakes.HTTPRequest.blank('', version='2.39')
@mock.patch.object(common, 'check_img_metadata_properties_quota')
@mock.patch.object(common, 'get_instance')
def test_create_backup_no_quota_checks(self, mock_get_instance,
mock_check_quotas):
# 'mock_get_instance' helps to skip the whole logic of the action,
# but to make the test
mock_get_instance.side_effect = webob.exc.HTTPNotFound
metadata = {'123': 'asdf'}
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': 1,
'metadata': metadata,
},
}
self.assertRaises(webob.exc.HTTPNotFound,
self.controller._create_backup, self.req,
fakes.FAKE_UUID, body=body)
# starting from version 2.39 no quota checks on Nova side are performed
# for 'createBackup' action after removing 'image-metadata' proxy API
mock_check_quotas.assert_not_called()
| 39.723653 | 79 | 0.557364 |
import mock
from oslo_utils import timeutils
import webob
from nova.api.openstack import common
from nova.api.openstack.compute import create_backup \
as create_backup_v21
from nova.compute import api
from nova.compute import utils as compute_utils
from nova import exception
from nova import test
from nova.tests.unit.api.openstack.compute import admin_only_action_common
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import fake_instance
class CreateBackupTestsV21(admin_only_action_common.CommonMixin,
test.NoDBTestCase):
create_backup = create_backup_v21
controller_name = 'CreateBackupController'
validation_error = exception.ValidationError
def setUp(self):
super(CreateBackupTestsV21, self).setUp()
self.controller = getattr(self.create_backup, self.controller_name)()
self.compute_api = self.controller.compute_api
patch_get = mock.patch.object(self.compute_api, 'get')
self.mock_get = patch_get.start()
self.addCleanup(patch_get.stop)
@mock.patch.object(common, 'check_img_metadata_properties_quota')
@mock.patch.object(api.API, 'backup')
def test_create_backup_with_metadata(self, mock_backup, mock_check_image):
metadata = {'123': 'asdf'}
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': 1,
'metadata': metadata,
},
}
image = dict(id='fake-image-id', status='ACTIVE', name='Backup 1',
properties=metadata)
instance = fake_instance.fake_instance_obj(self.context)
self.mock_get.return_value = instance
mock_backup.return_value = image
res = self.controller._create_backup(self.req, instance.uuid,
body=body)
mock_check_image.assert_called_once_with(self.context, metadata)
mock_backup.assert_called_once_with(self.context, instance, 'Backup 1',
'daily', 1,
extra_properties=metadata)
self.assertEqual(202, res.status_int)
self.assertIn('fake-image-id', res.headers['Location'])
def test_create_backup_no_name(self):
body = {
'createBackup': {
'backup_type': 'daily',
'rotation': 1,
},
}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
def test_create_backup_name_with_leading_trailing_spaces(self):
body = {
'createBackup': {
'name': ' test ',
'backup_type': 'daily',
'rotation': 1,
},
}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
@mock.patch.object(common, 'check_img_metadata_properties_quota')
@mock.patch.object(api.API, 'backup')
def test_create_backup_name_with_leading_trailing_spaces_compat_mode(
self, mock_backup, mock_check_image):
body = {
'createBackup': {
'name': ' test ',
'backup_type': 'daily',
'rotation': 1,
},
}
image = dict(id='fake-image-id', status='ACTIVE', name='Backup 1',
properties={})
instance = fake_instance.fake_instance_obj(self.context)
self.mock_get.return_value = instance
mock_backup.return_value = image
self.req.set_legacy_v2()
self.controller._create_backup(self.req, instance.uuid,
body=body)
mock_check_image.assert_called_once_with(self.context, {})
mock_backup.assert_called_once_with(self.context, instance, 'test',
'daily', 1,
extra_properties={})
def test_create_backup_no_rotation(self):
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
},
}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
def test_create_backup_negative_rotation(self):
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': -1,
},
}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
def test_create_backup_negative_rotation_with_string_number(self):
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': '-1',
},
}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
def test_create_backup_rotation_with_empty_string(self):
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': '',
},
}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
def test_create_backup_no_backup_type(self):
body = {
'createBackup': {
'name': 'Backup 1',
'rotation': 1,
},
}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
def test_create_backup_non_dict_metadata(self):
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': 1,
'metadata': 'non_dict',
},
}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
def test_create_backup_bad_entity(self):
body = {'createBackup': 'go'}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
@mock.patch.object(common, 'check_img_metadata_properties_quota')
@mock.patch.object(api.API, 'backup')
def test_create_backup_rotation_is_zero(self, mock_backup,
mock_check_image):
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': 0,
},
}
image = dict(id='fake-image-id', status='ACTIVE', name='Backup 1',
properties={})
instance = fake_instance.fake_instance_obj(self.context)
self.mock_get.return_value = instance
mock_backup.return_value = image
res = self.controller._create_backup(self.req, instance.uuid,
body=body)
mock_check_image.assert_called_once_with(self.context, {})
mock_backup.assert_called_once_with(self.context, instance, 'Backup 1',
'daily', 0,
extra_properties={})
self.assertEqual(202, res.status_int)
self.assertNotIn('Location', res.headers)
@mock.patch.object(common, 'check_img_metadata_properties_quota')
@mock.patch.object(api.API, 'backup')
def test_create_backup_rotation_is_positive(self, mock_backup,
mock_check_image):
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': 1,
},
}
image = dict(id='fake-image-id', status='ACTIVE', name='Backup 1',
properties={})
instance = fake_instance.fake_instance_obj(self.context)
self.mock_get.return_value = instance
mock_backup.return_value = image
res = self.controller._create_backup(self.req, instance.uuid,
body=body)
mock_check_image.assert_called_once_with(self.context, {})
mock_backup.assert_called_once_with(self.context, instance, 'Backup 1',
'daily', 1,
extra_properties={})
self.assertEqual(202, res.status_int)
self.assertIn('fake-image-id', res.headers['Location'])
@mock.patch.object(common, 'check_img_metadata_properties_quota')
@mock.patch.object(api.API, 'backup')
def test_create_backup_rotation_is_string_number(
self, mock_backup, mock_check_image):
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': '1',
},
}
image = dict(id='fake-image-id', status='ACTIVE', name='Backup 1',
properties={})
instance = fake_instance.fake_instance_obj(self.context)
self.mock_get.return_value = instance
mock_backup.return_value = image
res = self.controller._create_backup(self.req, instance['uuid'],
body=body)
mock_check_image.assert_called_once_with(self.context, {})
mock_backup.assert_called_once_with(self.context, instance, 'Backup 1',
'daily', 1,
extra_properties={})
self.assertEqual(202, res.status_int)
self.assertIn('fake-image-id', res.headers['Location'])
@mock.patch.object(common, 'check_img_metadata_properties_quota')
@mock.patch.object(api.API, 'backup', return_value=dict(
id='fake-image-id', status='ACTIVE', name='Backup 1', properties={}))
def test_create_backup_v2_45(self, mock_backup, mock_check_image):
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': '1',
},
}
instance = fake_instance.fake_instance_obj(self.context)
self.mock_get.return_value = instance
req = fakes.HTTPRequest.blank('', version='2.45')
res = self.controller._create_backup(req, instance['uuid'], body=body)
self.assertIsInstance(res, dict)
self.assertEqual('fake-image-id', res['image_id'])
@mock.patch.object(common, 'check_img_metadata_properties_quota')
@mock.patch.object(api.API, 'backup')
def test_create_backup_raises_conflict_on_invalid_state(self,
mock_backup, mock_check_image):
body_map = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': 1,
},
}
instance = fake_instance.fake_instance_obj(self.context)
self.mock_get.return_value = instance
mock_backup.side_effect = exception.InstanceInvalidState(
attr='vm_state', instance_uuid=instance.uuid,
state='foo', method='backup')
ex = self.assertRaises(webob.exc.HTTPConflict,
self.controller._create_backup,
self.req, instance.uuid,
body=body_map)
self.assertIn("Cannot 'createBackup' instance %(id)s"
% {'id': instance.uuid}, ex.explanation)
def test_create_backup_with_non_existed_instance(self):
body_map = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': 1,
},
}
uuid = fakes.FAKE_UUID
self.mock_get.side_effect = exception.InstanceNotFound(
instance_id=uuid)
self.assertRaises(webob.exc.HTTPNotFound,
self.controller._create_backup,
self.req, uuid, body=body_map)
def test_create_backup_with_invalid_create_backup(self):
body = {
'createBackupup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': 1,
},
}
self.assertRaises(self.validation_error,
self.controller._create_backup,
self.req, fakes.FAKE_UUID, body=body)
@mock.patch.object(common, 'check_img_metadata_properties_quota')
@mock.patch.object(compute_utils, 'is_volume_backed_instance',
return_value=True)
def test_backup_volume_backed_instance(self, mock_is_volume_backed,
mock_check_image):
body = {
'createBackup': {
'name': 'BackupMe',
'backup_type': 'daily',
'rotation': 3
},
}
updates = {'vm_state': 'active',
'task_state': None,
'launched_at': timeutils.utcnow()}
instance = fake_instance.fake_instance_obj(self.context, **updates)
instance.image_ref = None
self.mock_get.return_value = instance
ex = self.assertRaises(webob.exc.HTTPBadRequest,
self.controller._create_backup,
self.req, instance['uuid'], body=body)
mock_check_image.assert_called_once_with(self.context, {})
mock_is_volume_backed.assert_called_once_with(self.context, instance)
self.assertIn('Backup is not supported for volume-backed instances',
str(ex))
class CreateBackupTestsV239(test.NoDBTestCase):
def setUp(self):
super(CreateBackupTestsV239, self).setUp()
self.controller = create_backup_v21.CreateBackupController()
self.req = fakes.HTTPRequest.blank('', version='2.39')
@mock.patch.object(common, 'check_img_metadata_properties_quota')
@mock.patch.object(common, 'get_instance')
def test_create_backup_no_quota_checks(self, mock_get_instance,
mock_check_quotas):
mock_get_instance.side_effect = webob.exc.HTTPNotFound
metadata = {'123': 'asdf'}
body = {
'createBackup': {
'name': 'Backup 1',
'backup_type': 'daily',
'rotation': 1,
'metadata': metadata,
},
}
self.assertRaises(webob.exc.HTTPNotFound,
self.controller._create_backup, self.req,
fakes.FAKE_UUID, body=body)
mock_check_quotas.assert_not_called()
| true | true |
f7280a93cddae52a4b9914463d8e388bd3ec425f | 1,990 | py | Python | examples/pandas_chart_columns.py | Aeon1/XlsxWriter | 6871b6c3fe6c294632054ea91f23d9e27068bcc1 | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2019-06-12T15:34:25.000Z | 2019-06-12T15:34:25.000Z | examples/pandas_chart_columns.py | Aeon1/XlsxWriter | 6871b6c3fe6c294632054ea91f23d9e27068bcc1 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | examples/pandas_chart_columns.py | Aeon1/XlsxWriter | 6871b6c3fe6c294632054ea91f23d9e27068bcc1 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | ##############################################################################
#
# An example of converting a Pandas dataframe to an xlsx file with a grouped
# column chart using Pandas and XlsxWriter.
#
# Copyright 2013-2019, John McNamara, jmcnamara@cpan.org
#
import pandas as pd
# Some sample data to plot.
farm_1 = {'Apples': 10, 'Berries': 32, 'Squash': 21, 'Melons': 13, 'Corn': 18}
farm_2 = {'Apples': 15, 'Berries': 43, 'Squash': 17, 'Melons': 10, 'Corn': 22}
farm_3 = {'Apples': 6, 'Berries': 24, 'Squash': 22, 'Melons': 16, 'Corn': 30}
farm_4 = {'Apples': 12, 'Berries': 30, 'Squash': 15, 'Melons': 9, 'Corn': 15}
data = [farm_1, farm_2, farm_3, farm_4]
index = ['Farm 1', 'Farm 2', 'Farm 3', 'Farm 4']
# Create a Pandas dataframe from the data.
df = pd.DataFrame(data, index=index)
# Create a Pandas Excel writer using XlsxWriter as the engine.
sheet_name = 'Sheet1'
writer = pd.ExcelWriter('pandas_chart_columns.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name=sheet_name)
# Access the XlsxWriter workbook and worksheet objects from the dataframe.
workbook = writer.book
worksheet = writer.sheets[sheet_name]
# Create a chart object.
chart = workbook.add_chart({'type': 'column'})
# Some alternative colors for the chart.
colors = ['#E41A1C', '#377EB8', '#4DAF4A', '#984EA3', '#FF7F00']
# Configure the series of the chart from the dataframe data.
for col_num in range(1, len(farm_1) + 1):
chart.add_series({
'name': ['Sheet1', 0, col_num],
'categories': ['Sheet1', 1, 0, 4, 0],
'values': ['Sheet1', 1, col_num, 4, col_num],
'fill': {'color': colors[col_num - 1]},
'overlap': -10,
})
# Configure the chart axes.
chart.set_x_axis({'name': 'Total Produce'})
chart.set_y_axis({'name': 'Farms', 'major_gridlines': {'visible': False}})
# Insert the chart into the worksheet.
worksheet.insert_chart('H2', chart)
# Close the Pandas Excel writer and output the Excel file.
writer.save()
| 34.912281 | 78 | 0.635176 | true | true | |
f7280c2c71718777f3432e2a878f1bc6be839765 | 5,137 | py | Python | tests/test_database.py | theblazehen/starlette | 070d749f66999206c4c71cb203a2ea400e0b3c00 | [
"BSD-3-Clause"
] | 3 | 2021-06-26T17:27:36.000Z | 2021-07-11T15:01:51.000Z | tests/test_database.py | theblazehen/starlette | 070d749f66999206c4c71cb203a2ea400e0b3c00 | [
"BSD-3-Clause"
] | null | null | null | tests/test_database.py | theblazehen/starlette | 070d749f66999206c4c71cb203a2ea400e0b3c00 | [
"BSD-3-Clause"
] | null | null | null | import databases
import pytest
import sqlalchemy
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.testclient import TestClient
DATABASE_URL = "sqlite:///test.db"
metadata = sqlalchemy.MetaData()
notes = sqlalchemy.Table(
"notes",
metadata,
sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
sqlalchemy.Column("text", sqlalchemy.String(length=100)),
sqlalchemy.Column("completed", sqlalchemy.Boolean),
)
pytestmark = pytest.mark.usefixtures("no_trio_support")
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
app = Starlette()
database = databases.Database(DATABASE_URL, force_rollback=True)
@app.on_event("startup")
async def startup():
await database.connect()
@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
@app.route("/notes", methods=["GET"])
async def list_notes(request):
query = notes.select()
results = await database.fetch_all(query)
content = [
{"text": result["text"], "completed": result["completed"]} for result in results
]
return JSONResponse(content)
@app.route("/notes", methods=["POST"])
@database.transaction()
async def add_note(request):
data = await request.json()
query = notes.insert().values(text=data["text"], completed=data["completed"])
await database.execute(query)
if "raise_exc" in request.query_params:
raise RuntimeError()
return JSONResponse({"text": data["text"], "completed": data["completed"]})
@app.route("/notes/bulk_create", methods=["POST"])
async def bulk_create_notes(request):
data = await request.json()
query = notes.insert()
await database.execute_many(query, data)
return JSONResponse({"notes": data})
@app.route("/notes/{note_id:int}", methods=["GET"])
async def read_note(request):
note_id = request.path_params["note_id"]
query = notes.select().where(notes.c.id == note_id)
result = await database.fetch_one(query)
content = {"text": result["text"], "completed": result["completed"]}
return JSONResponse(content)
@app.route("/notes/{note_id:int}/text", methods=["GET"])
async def read_note_text(request):
note_id = request.path_params["note_id"]
query = sqlalchemy.select([notes.c.text]).where(notes.c.id == note_id)
result = await database.fetch_one(query)
return JSONResponse(result[0])
def test_database():
with TestClient(app) as client:
response = client.post(
"/notes", json={"text": "buy the milk", "completed": True}
)
assert response.status_code == 200
with pytest.raises(RuntimeError):
response = client.post(
"/notes",
json={"text": "you wont see me", "completed": False},
params={"raise_exc": "true"},
)
response = client.post(
"/notes", json={"text": "walk the dog", "completed": False}
)
assert response.status_code == 200
response = client.get("/notes")
assert response.status_code == 200
assert response.json() == [
{"text": "buy the milk", "completed": True},
{"text": "walk the dog", "completed": False},
]
response = client.get("/notes/1")
assert response.status_code == 200
assert response.json() == {"text": "buy the milk", "completed": True}
response = client.get("/notes/1/text")
assert response.status_code == 200
assert response.json() == "buy the milk"
def test_database_execute_many():
with TestClient(app) as client:
response = client.get("/notes")
data = [
{"text": "buy the milk", "completed": True},
{"text": "walk the dog", "completed": False},
]
response = client.post("/notes/bulk_create", json=data)
assert response.status_code == 200
response = client.get("/notes")
assert response.status_code == 200
assert response.json() == [
{"text": "buy the milk", "completed": True},
{"text": "walk the dog", "completed": False},
]
def test_database_isolated_during_test_cases():
"""
Using `TestClient` as a context manager
"""
with TestClient(app) as client:
response = client.post(
"/notes", json={"text": "just one note", "completed": True}
)
assert response.status_code == 200
response = client.get("/notes")
assert response.status_code == 200
assert response.json() == [{"text": "just one note", "completed": True}]
with TestClient(app) as client:
response = client.post(
"/notes", json={"text": "just one note", "completed": True}
)
assert response.status_code == 200
response = client.get("/notes")
assert response.status_code == 200
assert response.json() == [{"text": "just one note", "completed": True}]
| 30.217647 | 88 | 0.629161 | import databases
import pytest
import sqlalchemy
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.testclient import TestClient
DATABASE_URL = "sqlite:///test.db"
metadata = sqlalchemy.MetaData()
notes = sqlalchemy.Table(
"notes",
metadata,
sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
sqlalchemy.Column("text", sqlalchemy.String(length=100)),
sqlalchemy.Column("completed", sqlalchemy.Boolean),
)
pytestmark = pytest.mark.usefixtures("no_trio_support")
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
app = Starlette()
database = databases.Database(DATABASE_URL, force_rollback=True)
@app.on_event("startup")
async def startup():
await database.connect()
@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
@app.route("/notes", methods=["GET"])
async def list_notes(request):
query = notes.select()
results = await database.fetch_all(query)
content = [
{"text": result["text"], "completed": result["completed"]} for result in results
]
return JSONResponse(content)
@app.route("/notes", methods=["POST"])
@database.transaction()
async def add_note(request):
data = await request.json()
query = notes.insert().values(text=data["text"], completed=data["completed"])
await database.execute(query)
if "raise_exc" in request.query_params:
raise RuntimeError()
return JSONResponse({"text": data["text"], "completed": data["completed"]})
@app.route("/notes/bulk_create", methods=["POST"])
async def bulk_create_notes(request):
data = await request.json()
query = notes.insert()
await database.execute_many(query, data)
return JSONResponse({"notes": data})
@app.route("/notes/{note_id:int}", methods=["GET"])
async def read_note(request):
note_id = request.path_params["note_id"]
query = notes.select().where(notes.c.id == note_id)
result = await database.fetch_one(query)
content = {"text": result["text"], "completed": result["completed"]}
return JSONResponse(content)
@app.route("/notes/{note_id:int}/text", methods=["GET"])
async def read_note_text(request):
note_id = request.path_params["note_id"]
query = sqlalchemy.select([notes.c.text]).where(notes.c.id == note_id)
result = await database.fetch_one(query)
return JSONResponse(result[0])
def test_database():
with TestClient(app) as client:
response = client.post(
"/notes", json={"text": "buy the milk", "completed": True}
)
assert response.status_code == 200
with pytest.raises(RuntimeError):
response = client.post(
"/notes",
json={"text": "you wont see me", "completed": False},
params={"raise_exc": "true"},
)
response = client.post(
"/notes", json={"text": "walk the dog", "completed": False}
)
assert response.status_code == 200
response = client.get("/notes")
assert response.status_code == 200
assert response.json() == [
{"text": "buy the milk", "completed": True},
{"text": "walk the dog", "completed": False},
]
response = client.get("/notes/1")
assert response.status_code == 200
assert response.json() == {"text": "buy the milk", "completed": True}
response = client.get("/notes/1/text")
assert response.status_code == 200
assert response.json() == "buy the milk"
def test_database_execute_many():
with TestClient(app) as client:
response = client.get("/notes")
data = [
{"text": "buy the milk", "completed": True},
{"text": "walk the dog", "completed": False},
]
response = client.post("/notes/bulk_create", json=data)
assert response.status_code == 200
response = client.get("/notes")
assert response.status_code == 200
assert response.json() == [
{"text": "buy the milk", "completed": True},
{"text": "walk the dog", "completed": False},
]
def test_database_isolated_during_test_cases():
with TestClient(app) as client:
response = client.post(
"/notes", json={"text": "just one note", "completed": True}
)
assert response.status_code == 200
response = client.get("/notes")
assert response.status_code == 200
assert response.json() == [{"text": "just one note", "completed": True}]
with TestClient(app) as client:
response = client.post(
"/notes", json={"text": "just one note", "completed": True}
)
assert response.status_code == 200
response = client.get("/notes")
assert response.status_code == 200
assert response.json() == [{"text": "just one note", "completed": True}]
| true | true |
f7280c970e0c822fb30887a989c0e9ed85002df0 | 498 | py | Python | blog_project/urls.py | huseyinbicen/Python-Django-Example | b718492b3a09ba257e55a5a4bf2674573e1f51c0 | [
"MIT"
] | null | null | null | blog_project/urls.py | huseyinbicen/Python-Django-Example | b718492b3a09ba257e55a5a4bf2674573e1f51c0 | [
"MIT"
] | null | null | null | blog_project/urls.py | huseyinbicen/Python-Django-Example | b718492b3a09ba257e55a5a4bf2674573e1f51c0 | [
"MIT"
] | null | null | null | from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
path('about/', TemplateView.as_view(template_name = 'about.html')),
path('contact/', TemplateView.as_view(template_name = 'contact.html')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| 38.307692 | 75 | 0.748996 | from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
path('about/', TemplateView.as_view(template_name = 'about.html')),
path('contact/', TemplateView.as_view(template_name = 'contact.html')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| true | true |
f7280debda64b329f0fe426d6270e57bc1394d50 | 557 | py | Python | recipes/migrations/0003_recipe_thumbnail.py | capcom6/django-bread | db216dce17461debf26b2ec692d3e89eed5c80d7 | [
"Apache-2.0"
] | null | null | null | recipes/migrations/0003_recipe_thumbnail.py | capcom6/django-bread | db216dce17461debf26b2ec692d3e89eed5c80d7 | [
"Apache-2.0"
] | null | null | null | recipes/migrations/0003_recipe_thumbnail.py | capcom6/django-bread | db216dce17461debf26b2ec692d3e89eed5c80d7 | [
"Apache-2.0"
] | null | null | null | # Generated by Django 4.0.2 on 2022-02-23 05:35
import django.core.files.storage
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recipes', '0002_remove_recipe_ingredients_and_more'),
]
operations = [
migrations.AddField(
model_name='recipe',
name='thumbnail',
field=models.ImageField(blank=True, editable=False, null=True, storage=django.core.files.storage.FileSystemStorage(), upload_to='', verbose_name='фотография'),
),
]
| 27.85 | 171 | 0.667864 |
import django.core.files.storage
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recipes', '0002_remove_recipe_ingredients_and_more'),
]
operations = [
migrations.AddField(
model_name='recipe',
name='thumbnail',
field=models.ImageField(blank=True, editable=False, null=True, storage=django.core.files.storage.FileSystemStorage(), upload_to='', verbose_name='фотография'),
),
]
| true | true |
f7280e6baf0e8251adc36abab862c40151c328aa | 3,671 | py | Python | pyautospec/function_mps.py | lucamarx/pyAutoSpec | d57efb6ff4c37ede1377351fd3dd3a6ce362b551 | [
"MIT"
] | null | null | null | pyautospec/function_mps.py | lucamarx/pyAutoSpec | d57efb6ff4c37ede1377351fd3dd3a6ce362b551 | [
"MIT"
] | null | null | null | pyautospec/function_mps.py | lucamarx/pyAutoSpec | d57efb6ff4c37ede1377351fd3dd3a6ce362b551 | [
"MIT"
] | null | null | null | """
Mps based function compression algorithm
"""
import numpy as np
import itertools
from typing import List
from .mps import Mps
from .plots import function_wfa_comparison_chart
def word2real(s : List[int], x0 : float = 0.0, x1 : float = 1.0) -> float:
"""
Convert the binary representation s of xϵ[x0,x1) into the number itself
"""
s = [0] + s
return x0 + sum([s[i] * 2**(-i) for i in range(len(s))]) * (x1-x0)
def real2word(r : float, l : int = 8, x0 : float = 0.0, x1 : float = 1.0) -> List[int]:
"""
Convert a real number xϵ[x0,x1) into its binary representation (with
maximum length l)
"""
if r < x0 or r >= x1:
raise Exception("out of bounds")
r = (r - x0) / (x1 - x0)
w = []
for _ in range(0,l+1):
d = 1 if r >= 1 else 0
w.append(d)
r = (r-d)*2
return w[1:]
class FunctionMps():
"""
Mps based real function model
"""
def __init__(self, sequence_length : int = 8, max_bond_dim : int = 20):
"""
Intialize a model of a real function f: [x0,x1) → R
Parameters:
-----------
sequence_length : int
the underlying MPS length
max_bond_dim : int
the underlying MPS maximum bond dimension
"""
self.f, self.x0, self.x1 = None, None, None
self.model = Mps(sequence_length, 2, max_bond_dim)
def __repr__(self) -> str:
if self.f is None:
return " FunctionMps(N={}) <?>: [<?>,<?>] → R\n{}".format(len(self.model), self.model.__repr__())
else:
return " FunctionMps(N={}) {}: [{:.2f},{:.2f}] → R\n{}".format(len(self.model), self.f.__repr__(), self.x0, self.x1, self.model.__repr__())
def _one_hot(self, X : List[List[int]]) -> np.ndarray:
"""
Perform one-hot encoding
"""
idxs = np.array(X).reshape(-1)
return np.eye(self.model.part_d)[idxs].reshape((-1, len(self.model), self.model.part_d))
def __call__(self, x : float) -> float:
"""
Evaluate learned function at x
Parameters:
-----------
x : float
a point in [x0,x1)
Returns:
--------
the value of the function at x
"""
return self.model(self._one_hot([real2word(x, l=len(self.model), x0=self.x0, x1=self.x1)]))[0]
def comparison_chart(self, n_points : int = 50):
"""
Compare the two functions
Parameters:
-----------
n_points : int
the number of points in the plot
"""
function_wfa_comparison_chart(self, n_points, None, plot_derivative = False)
def fit(self, f, x0 : float = 0.0, x1 : float = 1.0, learn_rate : float = 0.1, batch_size : int = 32, epochs : int = 10):
"""
Fit the model to the function f defined on the interval [x0,x1)
Parameters:
-----------
f : function
the function to be fitted
x0 : float
x1 : float
the interval the function is defined on
learn_rate : float
the learning rate
batch_size : int
the batch size used at each step
epochs : int
the number of epochs
Returns:
--------
The object itself
"""
self.f = f
self.x0 = x0
self.x1 = x1
data = [(list(x), f(word2real(list(x), x0=x0, x1=x1))) for x in itertools.product(*([[0,1]] * len(self.model)))]
self.model.fit(self._one_hot(np.array([t[0] for t in data])), np.array([t[1] for t in data]), learn_rate=learn_rate, batch_size=batch_size, epochs=epochs)
return self
| 25.493056 | 162 | 0.542359 | import numpy as np
import itertools
from typing import List
from .mps import Mps
from .plots import function_wfa_comparison_chart
def word2real(s : List[int], x0 : float = 0.0, x1 : float = 1.0) -> float:
s = [0] + s
return x0 + sum([s[i] * 2**(-i) for i in range(len(s))]) * (x1-x0)
def real2word(r : float, l : int = 8, x0 : float = 0.0, x1 : float = 1.0) -> List[int]:
if r < x0 or r >= x1:
raise Exception("out of bounds")
r = (r - x0) / (x1 - x0)
w = []
for _ in range(0,l+1):
d = 1 if r >= 1 else 0
w.append(d)
r = (r-d)*2
return w[1:]
class FunctionMps():
def __init__(self, sequence_length : int = 8, max_bond_dim : int = 20):
self.f, self.x0, self.x1 = None, None, None
self.model = Mps(sequence_length, 2, max_bond_dim)
def __repr__(self) -> str:
if self.f is None:
return " FunctionMps(N={}) <?>: [<?>,<?>] → R\n{}".format(len(self.model), self.model.__repr__())
else:
return " FunctionMps(N={}) {}: [{:.2f},{:.2f}] → R\n{}".format(len(self.model), self.f.__repr__(), self.x0, self.x1, self.model.__repr__())
def _one_hot(self, X : List[List[int]]) -> np.ndarray:
idxs = np.array(X).reshape(-1)
return np.eye(self.model.part_d)[idxs].reshape((-1, len(self.model), self.model.part_d))
def __call__(self, x : float) -> float:
return self.model(self._one_hot([real2word(x, l=len(self.model), x0=self.x0, x1=self.x1)]))[0]
def comparison_chart(self, n_points : int = 50):
function_wfa_comparison_chart(self, n_points, None, plot_derivative = False)
def fit(self, f, x0 : float = 0.0, x1 : float = 1.0, learn_rate : float = 0.1, batch_size : int = 32, epochs : int = 10):
self.f = f
self.x0 = x0
self.x1 = x1
data = [(list(x), f(word2real(list(x), x0=x0, x1=x1))) for x in itertools.product(*([[0,1]] * len(self.model)))]
self.model.fit(self._one_hot(np.array([t[0] for t in data])), np.array([t[1] for t in data]), learn_rate=learn_rate, batch_size=batch_size, epochs=epochs)
return self
| true | true |
f7280ebe246bd0c4e3a1e4a83d501247c3ec9d7b | 1,560 | py | Python | setup.py | dpshelio/BayesianTracker | 0be7225f958b75540ec6957622c9dd6b96f809bb | [
"MIT"
] | 196 | 2017-11-27T03:05:19.000Z | 2022-03-23T20:04:28.000Z | setup.py | dpshelio/BayesianTracker | 0be7225f958b75540ec6957622c9dd6b96f809bb | [
"MIT"
] | 78 | 2018-07-14T14:30:02.000Z | 2022-03-30T15:11:02.000Z | setup.py | dpshelio/BayesianTracker | 0be7225f958b75540ec6957622c9dd6b96f809bb | [
"MIT"
] | 45 | 2017-11-27T03:05:20.000Z | 2022-03-15T05:57:18.000Z | """BayesianTracker (`btrack`) is a multi object tracking algorithm,
specifically used to reconstruct trajectories in crowded fields. New
observations are assigned to tracks by evaluating the posterior probability of
each potential linkage from a Bayesian belief matrix for all possible
linkages. """
from setuptools import find_packages, setup
def get_install_required():
with open("./requirements.txt", "r") as reqs:
requirements = reqs.readlines()
return [r.rstrip() for r in requirements]
def get_version():
with open("./btrack/VERSION.txt", "r") as ver:
version = ver.readline()
return version.rstrip()
DESCRIPTION = 'A framework for Bayesian multi-object tracking'
LONG_DESCRIPTION = __doc__
setup(
name='btrack',
version=get_version(),
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
long_description_content_type='text/markdown',
author='Alan R. Lowe',
author_email='a.lowe@ucl.ac.uk',
url='https://github.com/quantumjot/BayesianTracker',
packages=find_packages(),
package_data={'btrack': ['libs/libtracker*', 'VERSION.txt']},
install_requires=get_install_required(),
python_requires='>=3.6',
license='LICENSE.md',
classifiers=[
'Programming Language :: C++',
'Programming Language :: Python',
'Programming Language :: Python :: 3 :: Only',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Bio-Informatics',
'Topic :: Scientific/Engineering :: Image Recognition',
],
)
| 31.836735 | 78 | 0.694231 |
from setuptools import find_packages, setup
def get_install_required():
with open("./requirements.txt", "r") as reqs:
requirements = reqs.readlines()
return [r.rstrip() for r in requirements]
def get_version():
with open("./btrack/VERSION.txt", "r") as ver:
version = ver.readline()
return version.rstrip()
DESCRIPTION = 'A framework for Bayesian multi-object tracking'
LONG_DESCRIPTION = __doc__
setup(
name='btrack',
version=get_version(),
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
long_description_content_type='text/markdown',
author='Alan R. Lowe',
author_email='a.lowe@ucl.ac.uk',
url='https://github.com/quantumjot/BayesianTracker',
packages=find_packages(),
package_data={'btrack': ['libs/libtracker*', 'VERSION.txt']},
install_requires=get_install_required(),
python_requires='>=3.6',
license='LICENSE.md',
classifiers=[
'Programming Language :: C++',
'Programming Language :: Python',
'Programming Language :: Python :: 3 :: Only',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Bio-Informatics',
'Topic :: Scientific/Engineering :: Image Recognition',
],
)
| true | true |
f7280f19f5c8722b0886a42579dd2cdb8cc9e731 | 204 | py | Python | bin/selectCommands.py | mikiec84/linkshop | 72959ceca0003be226edeca6496f915502831596 | [
"Apache-2.0"
] | 6 | 2017-07-18T15:28:33.000Z | 2020-03-03T14:45:45.000Z | bin/selectCommands.py | mikiec84/linkshop | 72959ceca0003be226edeca6496f915502831596 | [
"Apache-2.0"
] | null | null | null | bin/selectCommands.py | mikiec84/linkshop | 72959ceca0003be226edeca6496f915502831596 | [
"Apache-2.0"
] | 3 | 2017-09-09T00:36:48.000Z | 2020-03-03T14:45:49.000Z | #!/usr/bin/env python3
"""Command-line wrapper for stats.cli_percentageOfLinks."""
import loadPath # Adds the project path.
import linkograph.commandUtils
linkograph.commandUtils.cli_selectCommands()
| 22.666667 | 59 | 0.79902 |
import loadPath
import linkograph.commandUtils
linkograph.commandUtils.cli_selectCommands()
| true | true |
f7280fed5c247e39bbef3d6ffde57f3181053fc2 | 3,371 | py | Python | Simulation_virus_BB.py | Cheese229/DataAssignmentCIS | 7e31892721aa2b3845df3e76296af500f29c9196 | [
"MIT"
] | null | null | null | Simulation_virus_BB.py | Cheese229/DataAssignmentCIS | 7e31892721aa2b3845df3e76296af500f29c9196 | [
"MIT"
] | null | null | null | Simulation_virus_BB.py | Cheese229/DataAssignmentCIS | 7e31892721aa2b3845df3e76296af500f29c9196 | [
"MIT"
] | null | null | null | """
Bigger scale simulation of a virus spread in a city.
This would have been the better opt for the project, as it uses geospatial visualisation (which is not in this code)
and data gathered from a a ride share, a specific city, their population, and their public transport data.
I still don't understand how geospatial visualisation works (I think I will look more into it in the holidays)
The simulation uses mathematical equations on how a virus would spread and includes its recovery rates.
Technically this code works (I think)...
It is just missing it's data and its visuals
"""
import numpy as np
from collections import namedtuple
Param = namedtuple('Param', 'R0 DE DI I0 HopitalisationRate HospitalIters')
# I0 is the distribution of infected people at time t=0, if None then randomly choose inf number of people
# flow is a 3D matrix of dimentions r x n x n (i.e., 84 x 549 x 549),
# flow[t mod r] is the desired OD matrix at time t.
def seir(par, distr, flow, alpha, iterations, inf):
r = flow.shape[0]
n = flow.shape[1]
N = distr[0].sum() #total population, we assume that N = sum(flow)
Svec = distr[0].copy()
Evec = np.zeros(n)
Ivec = np.zeros(n)
Rvec = np.zeros(n)
if par.I0 is None:
initial = np.zeros(n)
# randomly choose inf infections
for i in range(inf):
loc = np.random.randint(n)
if (Svec[loc] > initial[loc]):
initial[loc] += 1.0
else:
initial = par.I0
assert ((Svec < initial).sum() == 0)
Svec -= initial
Ivec += initial
res = np.zeros((iterations, 5))
res[0,:] = [Svec.sum(), Evec.sum(), Ivec.sum(), Rvec.sum(), 0]
realflow = flow.copy()
realflow = realflow / realflow.sum(axis=2)[:,:, np.newaxis]
realflow = alpha * realflow
history = np.zeros((iterations, 5, n))
history[0,0,:] = Svec
history[0,1,:] = Evec
history[0,2,:] = Ivec
history[0,3,:] = Rvec
eachIter = np.zeros(iterations + 1)
# run simulation
for iter in range(0, iterations - 1):
realOD = realflow[iter % r]
d = distr[iter % r] + 1
if ((d>N+1).any()):
print("Houston, we have a problem!")
return res, history
# N = S + E + I + R
newE = Svec * Ivec / d * (par.R0 / par.DI)
newI = Evec / par.DE
newR = Ivec / par.DI
Svec -= newE
Svec = (Svec + np.matmul(Svec.reshape(1,n), realOD) - Svec * realOD.sum(axis=1))
Evec = Evec + newE - newI
Evec = (Evec + np.matmul(Evec.reshape(1,n), realOD) - Evec * realOD.sum(axis=1))
Ivec = Ivec + newI - newR
Ivec = (Ivec + np.matmul(Ivec.reshape(1,n), realOD) - Ivec * realOD.sum(axis=1))
Rvec += newR
Rvec = (Rvec + np.matmul(Rvec.reshape(1,n), realOD) - Rvec * realOD.sum(axis=1))
res[iter + 1,:] = [Svec.sum(), Evec.sum(), Ivec.sum(), Rvec.sum(), 0]
eachIter[iter + 1] = newI.sum()
res[iter + 1, 4] = eachIter[max(0, iter - par.HospitalIters) : iter].sum() * par.HospitalisationRate
history[iter + 1,0,:] = Svec
history[iter + 1,1,:] = Evec
history[iter + 1,2,:] = Ivec
history[iter + 1,3,:] = Rvec
return res, history | 34.752577 | 121 | 0.576387 |
import numpy as np
from collections import namedtuple
Param = namedtuple('Param', 'R0 DE DI I0 HopitalisationRate HospitalIters')
def seir(par, distr, flow, alpha, iterations, inf):
r = flow.shape[0]
n = flow.shape[1]
N = distr[0].sum()
Svec = distr[0].copy()
Evec = np.zeros(n)
Ivec = np.zeros(n)
Rvec = np.zeros(n)
if par.I0 is None:
initial = np.zeros(n)
for i in range(inf):
loc = np.random.randint(n)
if (Svec[loc] > initial[loc]):
initial[loc] += 1.0
else:
initial = par.I0
assert ((Svec < initial).sum() == 0)
Svec -= initial
Ivec += initial
res = np.zeros((iterations, 5))
res[0,:] = [Svec.sum(), Evec.sum(), Ivec.sum(), Rvec.sum(), 0]
realflow = flow.copy()
realflow = realflow / realflow.sum(axis=2)[:,:, np.newaxis]
realflow = alpha * realflow
history = np.zeros((iterations, 5, n))
history[0,0,:] = Svec
history[0,1,:] = Evec
history[0,2,:] = Ivec
history[0,3,:] = Rvec
eachIter = np.zeros(iterations + 1)
for iter in range(0, iterations - 1):
realOD = realflow[iter % r]
d = distr[iter % r] + 1
if ((d>N+1).any()):
print("Houston, we have a problem!")
return res, history
newE = Svec * Ivec / d * (par.R0 / par.DI)
newI = Evec / par.DE
newR = Ivec / par.DI
Svec -= newE
Svec = (Svec + np.matmul(Svec.reshape(1,n), realOD) - Svec * realOD.sum(axis=1))
Evec = Evec + newE - newI
Evec = (Evec + np.matmul(Evec.reshape(1,n), realOD) - Evec * realOD.sum(axis=1))
Ivec = Ivec + newI - newR
Ivec = (Ivec + np.matmul(Ivec.reshape(1,n), realOD) - Ivec * realOD.sum(axis=1))
Rvec += newR
Rvec = (Rvec + np.matmul(Rvec.reshape(1,n), realOD) - Rvec * realOD.sum(axis=1))
res[iter + 1,:] = [Svec.sum(), Evec.sum(), Ivec.sum(), Rvec.sum(), 0]
eachIter[iter + 1] = newI.sum()
res[iter + 1, 4] = eachIter[max(0, iter - par.HospitalIters) : iter].sum() * par.HospitalisationRate
history[iter + 1,0,:] = Svec
history[iter + 1,1,:] = Evec
history[iter + 1,2,:] = Ivec
history[iter + 1,3,:] = Rvec
return res, history | true | true |
f72810ac5161b5ba7e97e6d85881891276be8a01 | 8,975 | py | Python | tests/st/summary/test_summary_collector.py | Greatpanc/mindspore_zhb | c2511f7d6815b9232ac4427e27e2c132ed03e0d9 | [
"Apache-2.0"
] | 3,200 | 2020-02-17T12:45:41.000Z | 2022-03-31T20:21:16.000Z | tests/st/summary/test_summary_collector.py | LaiYongqiang/mindspore | 1b7a38ccd86b55af50a0ea55c7f2f43813ed3e0e | [
"Apache-2.0"
] | 176 | 2020-02-12T02:52:11.000Z | 2022-03-28T22:15:55.000Z | tests/st/summary/test_summary_collector.py | LaiYongqiang/mindspore | 1b7a38ccd86b55af50a0ea55c7f2f43813ed3e0e | [
"Apache-2.0"
] | 621 | 2020-03-09T01:31:41.000Z | 2022-03-30T03:43:19.000Z | # Copyright 2020-2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""test SummaryCollector."""
import os
import re
import shutil
import tempfile
from collections import Counter
import pytest
from mindspore import nn, Tensor, context
from mindspore.common.initializer import Normal
from mindspore.nn.metrics import Loss
from mindspore.nn.optim import Momentum
from mindspore.ops import operations as P
from mindspore.train import Model
from mindspore.train.callback import SummaryCollector
from tests.st.summary.dataset import create_mnist_dataset
from tests.summary_utils import SummaryReader
from tests.security_utils import security_off_wrap
class LeNet5(nn.Cell):
"""
Lenet network
Args:
num_class (int): Number of classes. Default: 10.
num_channel (int): Number of channels. Default: 1.
Returns:
Tensor, output tensor
Examples:
>>> LeNet(num_class=10)
"""
def __init__(self, num_class=10, num_channel=1, include_top=True):
super(LeNet5, self).__init__()
self.conv1 = nn.Conv2d(num_channel, 6, 5, pad_mode='valid')
self.conv2 = nn.Conv2d(6, 16, 5, pad_mode='valid')
self.relu = nn.ReLU()
self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
self.include_top = include_top
if self.include_top:
self.flatten = nn.Flatten()
self.fc1 = nn.Dense(16 * 5 * 5, 120, weight_init=Normal(0.02))
self.fc2 = nn.Dense(120, 84, weight_init=Normal(0.02))
self.fc3 = nn.Dense(84, num_class, weight_init=Normal(0.02))
self.scalar_summary = P.ScalarSummary()
self.image_summary = P.ImageSummary()
self.histogram_summary = P.HistogramSummary()
self.tensor_summary = P.TensorSummary()
self.channel = Tensor(num_channel)
def construct(self, x):
"""construct."""
self.image_summary('image', x)
x = self.conv1(x)
self.histogram_summary('histogram', x)
x = self.relu(x)
self.tensor_summary('tensor', x)
x = self.relu(x)
x = self.max_pool2d(x)
self.scalar_summary('scalar', self.channel)
x = self.conv2(x)
x = self.relu(x)
x = self.max_pool2d(x)
if not self.include_top:
return x
x = self.flatten(x)
x = self.relu(self.fc1(x))
x = self.relu(self.fc2(x))
x = self.fc3(x)
return x
class TestSummary:
"""Test summary collector the basic function."""
base_summary_dir = ''
@classmethod
def setup_class(cls):
"""Run before test this class."""
device_id = int(os.getenv('DEVICE_ID')) if os.getenv('DEVICE_ID') else 0
context.set_context(mode=context.GRAPH_MODE, device_id=device_id)
cls.base_summary_dir = tempfile.mkdtemp(suffix='summary')
@classmethod
def teardown_class(cls):
"""Run after test this class."""
if os.path.exists(cls.base_summary_dir):
shutil.rmtree(cls.base_summary_dir)
def _run_network(self, dataset_sink_mode=False, num_samples=2, **kwargs):
"""run network."""
lenet = LeNet5()
loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
optim = Momentum(lenet.trainable_params(), learning_rate=0.1, momentum=0.9)
model = Model(lenet, loss_fn=loss, optimizer=optim, metrics={'loss': Loss()})
summary_dir = tempfile.mkdtemp(dir=self.base_summary_dir)
summary_collector = SummaryCollector(summary_dir=summary_dir, collect_freq=2, **kwargs)
ds_train = create_mnist_dataset("train", num_samples=num_samples)
model.train(1, ds_train, callbacks=[summary_collector], dataset_sink_mode=dataset_sink_mode)
ds_eval = create_mnist_dataset("test")
model.eval(ds_eval, dataset_sink_mode=dataset_sink_mode, callbacks=[summary_collector])
return summary_dir
@pytest.mark.level0
@pytest.mark.platform_x86_ascend_training
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
@security_off_wrap
def test_summary_with_sink_mode_false(self):
"""Test summary with sink mode false, and num samples is 64."""
summary_dir = self._run_network(num_samples=10)
tag_list = self._list_summary_tags(summary_dir)
expected_tag_set = {'conv1.weight/auto', 'conv2.weight/auto', 'fc1.weight/auto', 'fc1.bias/auto',
'fc2.weight/auto', 'input_data/auto', 'loss/auto',
'histogram', 'image', 'scalar', 'tensor'}
assert set(expected_tag_set) == set(tag_list)
# num samples is 10, batch size is 2, so step is 5, collect freq is 2,
# SummaryCollector will collect the first step and 2th, 4th step
tag_count = 3
for value in Counter(tag_list).values():
assert value == tag_count
@pytest.mark.level0
@pytest.mark.platform_x86_ascend_training
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
@security_off_wrap
def test_summary_with_sink_mode_true(self):
"""Test summary with sink mode true, and num samples is 64."""
summary_dir = self._run_network(dataset_sink_mode=True, num_samples=10)
tag_list = self._list_summary_tags(summary_dir)
# There will not record input data when dataset sink mode is True
expected_tags = {'conv1.weight/auto', 'conv2.weight/auto', 'fc1.weight/auto', 'fc1.bias/auto',
'fc2.weight/auto', 'loss/auto', 'histogram', 'image', 'scalar', 'tensor'}
assert set(expected_tags) == set(tag_list)
tag_count = 1
for value in Counter(tag_list).values():
assert value == tag_count
@pytest.mark.level0
@pytest.mark.platform_x86_ascend_training
@pytest.mark.platform_arm_ascend_training
@pytest.mark.env_onecard
@security_off_wrap
def test_summarycollector_user_defind(self):
"""Test SummaryCollector with user-defined."""
summary_dir = self._run_network(dataset_sink_mode=True, num_samples=2,
custom_lineage_data={'test': 'self test'},
export_options={'tensor_format': 'npy'})
tag_list = self._list_summary_tags(summary_dir)
file_list = self._list_tensor_files(summary_dir)
# There will not record input data when dataset sink mode is True
expected_tags = {'conv1.weight/auto', 'conv2.weight/auto', 'fc1.weight/auto', 'fc1.bias/auto',
'fc2.weight/auto', 'loss/auto', 'histogram', 'image', 'scalar', 'tensor'}
assert set(expected_tags) == set(tag_list)
expected_files = {'tensor_1.npy'}
assert set(expected_files) == set(file_list)
@staticmethod
def _list_summary_tags(summary_dir):
"""list summary tags."""
summary_file_path = ''
for file in os.listdir(summary_dir):
if re.search("_MS", file):
summary_file_path = os.path.join(summary_dir, file)
break
assert summary_file_path
tags = list()
with SummaryReader(summary_file_path) as summary_reader:
while True:
summary_event = summary_reader.read_event()
if not summary_event:
break
for value in summary_event.summary.value:
tags.append(value.tag)
return tags
@staticmethod
def _list_tensor_files(summary_dir):
"""list tensor tags."""
export_file_path = ''
for file in os.listdir(summary_dir):
if re.search("export_", file):
export_file_path = os.path.join(summary_dir, file)
break
assert export_file_path
tensor_file_path = os.path.join(export_file_path, "tensor")
assert tensor_file_path
tensors = list()
for file in os.listdir(tensor_file_path):
tensors.append(file)
return tensors
| 39.537445 | 106 | 0.630641 |
import os
import re
import shutil
import tempfile
from collections import Counter
import pytest
from mindspore import nn, Tensor, context
from mindspore.common.initializer import Normal
from mindspore.nn.metrics import Loss
from mindspore.nn.optim import Momentum
from mindspore.ops import operations as P
from mindspore.train import Model
from mindspore.train.callback import SummaryCollector
from tests.st.summary.dataset import create_mnist_dataset
from tests.summary_utils import SummaryReader
from tests.security_utils import security_off_wrap
class LeNet5(nn.Cell):
def __init__(self, num_class=10, num_channel=1, include_top=True):
super(LeNet5, self).__init__()
self.conv1 = nn.Conv2d(num_channel, 6, 5, pad_mode='valid')
self.conv2 = nn.Conv2d(6, 16, 5, pad_mode='valid')
self.relu = nn.ReLU()
self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
self.include_top = include_top
if self.include_top:
self.flatten = nn.Flatten()
self.fc1 = nn.Dense(16 * 5 * 5, 120, weight_init=Normal(0.02))
self.fc2 = nn.Dense(120, 84, weight_init=Normal(0.02))
self.fc3 = nn.Dense(84, num_class, weight_init=Normal(0.02))
self.scalar_summary = P.ScalarSummary()
self.image_summary = P.ImageSummary()
self.histogram_summary = P.HistogramSummary()
self.tensor_summary = P.TensorSummary()
self.channel = Tensor(num_channel)
def construct(self, x):
self.image_summary('image', x)
x = self.conv1(x)
self.histogram_summary('histogram', x)
x = self.relu(x)
self.tensor_summary('tensor', x)
x = self.relu(x)
x = self.max_pool2d(x)
self.scalar_summary('scalar', self.channel)
x = self.conv2(x)
x = self.relu(x)
x = self.max_pool2d(x)
if not self.include_top:
return x
x = self.flatten(x)
x = self.relu(self.fc1(x))
x = self.relu(self.fc2(x))
x = self.fc3(x)
return x
class TestSummary:
base_summary_dir = ''
@classmethod
def setup_class(cls):
device_id = int(os.getenv('DEVICE_ID')) if os.getenv('DEVICE_ID') else 0
context.set_context(mode=context.GRAPH_MODE, device_id=device_id)
cls.base_summary_dir = tempfile.mkdtemp(suffix='summary')
@classmethod
def teardown_class(cls):
if os.path.exists(cls.base_summary_dir):
shutil.rmtree(cls.base_summary_dir)
def _run_network(self, dataset_sink_mode=False, num_samples=2, **kwargs):
lenet = LeNet5()
loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
optim = Momentum(lenet.trainable_params(), learning_rate=0.1, momentum=0.9)
model = Model(lenet, loss_fn=loss, optimizer=optim, metrics={'loss': Loss()})
summary_dir = tempfile.mkdtemp(dir=self.base_summary_dir)
summary_collector = SummaryCollector(summary_dir=summary_dir, collect_freq=2, **kwargs)
ds_train = create_mnist_dataset("train", num_samples=num_samples)
model.train(1, ds_train, callbacks=[summary_collector], dataset_sink_mode=dataset_sink_mode)
ds_eval = create_mnist_dataset("test")
model.eval(ds_eval, dataset_sink_mode=dataset_sink_mode, callbacks=[summary_collector])
return summary_dir
@pytest.mark.level0
@pytest.mark.platform_x86_ascend_training
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
@security_off_wrap
def test_summary_with_sink_mode_false(self):
summary_dir = self._run_network(num_samples=10)
tag_list = self._list_summary_tags(summary_dir)
expected_tag_set = {'conv1.weight/auto', 'conv2.weight/auto', 'fc1.weight/auto', 'fc1.bias/auto',
'fc2.weight/auto', 'input_data/auto', 'loss/auto',
'histogram', 'image', 'scalar', 'tensor'}
assert set(expected_tag_set) == set(tag_list)
tag_count = 3
for value in Counter(tag_list).values():
assert value == tag_count
@pytest.mark.level0
@pytest.mark.platform_x86_ascend_training
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
@security_off_wrap
def test_summary_with_sink_mode_true(self):
summary_dir = self._run_network(dataset_sink_mode=True, num_samples=10)
tag_list = self._list_summary_tags(summary_dir)
expected_tags = {'conv1.weight/auto', 'conv2.weight/auto', 'fc1.weight/auto', 'fc1.bias/auto',
'fc2.weight/auto', 'loss/auto', 'histogram', 'image', 'scalar', 'tensor'}
assert set(expected_tags) == set(tag_list)
tag_count = 1
for value in Counter(tag_list).values():
assert value == tag_count
@pytest.mark.level0
@pytest.mark.platform_x86_ascend_training
@pytest.mark.platform_arm_ascend_training
@pytest.mark.env_onecard
@security_off_wrap
def test_summarycollector_user_defind(self):
summary_dir = self._run_network(dataset_sink_mode=True, num_samples=2,
custom_lineage_data={'test': 'self test'},
export_options={'tensor_format': 'npy'})
tag_list = self._list_summary_tags(summary_dir)
file_list = self._list_tensor_files(summary_dir)
expected_tags = {'conv1.weight/auto', 'conv2.weight/auto', 'fc1.weight/auto', 'fc1.bias/auto',
'fc2.weight/auto', 'loss/auto', 'histogram', 'image', 'scalar', 'tensor'}
assert set(expected_tags) == set(tag_list)
expected_files = {'tensor_1.npy'}
assert set(expected_files) == set(file_list)
@staticmethod
def _list_summary_tags(summary_dir):
summary_file_path = ''
for file in os.listdir(summary_dir):
if re.search("_MS", file):
summary_file_path = os.path.join(summary_dir, file)
break
assert summary_file_path
tags = list()
with SummaryReader(summary_file_path) as summary_reader:
while True:
summary_event = summary_reader.read_event()
if not summary_event:
break
for value in summary_event.summary.value:
tags.append(value.tag)
return tags
@staticmethod
def _list_tensor_files(summary_dir):
export_file_path = ''
for file in os.listdir(summary_dir):
if re.search("export_", file):
export_file_path = os.path.join(summary_dir, file)
break
assert export_file_path
tensor_file_path = os.path.join(export_file_path, "tensor")
assert tensor_file_path
tensors = list()
for file in os.listdir(tensor_file_path):
tensors.append(file)
return tensors
| true | true |
f72810def0eca1d7c73b251c7ad71dbceec4eebf | 4,527 | py | Python | EvoCluster/_objectives.py | soumitri2001/EvoCluster | 2f8e3f21c7045478394e7e02a22835f7c184c0c7 | [
"Apache-2.0"
] | 12 | 2019-12-21T16:29:15.000Z | 2022-01-03T01:24:14.000Z | EvoCluster/_objectives.py | soumitri2001/EvoCluster | 2f8e3f21c7045478394e7e02a22835f7c184c0c7 | [
"Apache-2.0"
] | 3 | 2020-06-07T07:52:40.000Z | 2021-10-08T16:13:49.000Z | EvoCluster/_objectives.py | RaneemQaddoura/EvoCluster | 001dfb4c1f00db84ad1c2f2228eed6112d7e65b1 | [
"Apache-2.0"
] | 14 | 2019-12-28T19:55:48.000Z | 2021-12-31T14:46:03.000Z | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 9 18:12:29 2019
@author: Raneem
"""
from sklearn import cluster, metrics
from scipy.spatial.distance import pdist, cdist
import numpy
import sys
def getLabelsPred(startpts, points, k):
labelsPred = [-1] * len(points)
for i in range(len(points)):
distances = numpy.linalg.norm(points[i]-startpts, axis = 1)
labelsPred[i] = numpy.argmin(distances)
return labelsPred
def SSE(startpts, points, k, metric):
labelsPred = getLabelsPred(startpts, points, k)
fitness = 0
if numpy.unique(labelsPred).size < k:
fitness = sys.float_info.max
else:
centroidsForPoints = startpts[labelsPred]
fitness = 0
for i in range(k):
indexes = [n for n,x in enumerate(labelsPred) if x==i]
fit = cdist(points[indexes], centroidsForPoints[indexes], metric)**2
fit = sum(fit)[0]
fitness += fit
return fitness, labelsPred
def TWCV(startpts, points, k):
labelsPred = getLabelsPred(startpts, points, k)
if numpy.unique(labelsPred).size < k:
fitness = sys.float_info.max
else:
sumAllFeatures = sum(sum(numpy.power(points,2)))
sumAllPairPointsCluster = 0
for clusterId in range(k):
indices = numpy.where(numpy.array(labelsPred) == clusterId)[0]
pointsInCluster = points[numpy.array(indices)]
sumPairPointsCluster = sum(pointsInCluster)
sumPairPointsCluster = numpy.power(sumPairPointsCluster,2)
sumPairPointsCluster = sum(sumPairPointsCluster)
sumPairPointsCluster = sumPairPointsCluster/len(pointsInCluster)
sumAllPairPointsCluster += sumPairPointsCluster
fitness = (sumAllFeatures - sumAllPairPointsCluster)
return fitness, labelsPred
def SC(startpts, points, k, metric):
labelsPred = getLabelsPred(startpts, points, k)
if numpy.unique(labelsPred).size < k:
fitness = sys.float_info.max
else:
silhouette = metrics.silhouette_score(points, labelsPred, metric=metric)
#silhouette = (silhouette - (-1)) / (1 - (-1))
silhouette = (silhouette + 1) / 2
fitness = 1 - silhouette
return fitness, labelsPred
def DB(startpts, points, k):
labelsPred = getLabelsPred(startpts, points, k)
if numpy.unique(labelsPred).size < k:
fitness = sys.float_info.max
else:
fitness = metrics.davies_bouldin_score(points, labelsPred)
return fitness, labelsPred
def CH(startpts, points, k):
labelsPred = getLabelsPred(startpts, points, k)
if numpy.unique(labelsPred).size < k:
fitness = sys.float_info.max
else:
ch = metrics.calinski_harabaz_score(points, labelsPred)
fitness = 1 / ch
return fitness, labelsPred
def delta_fast(ck, cl, distances):
values = distances[numpy.where(ck)][:, numpy.where(cl)]
values = values[numpy.nonzero(values)]
return numpy.min(values)
def big_delta_fast(ci, distances):
values = distances[numpy.where(ci)][:, numpy.where(ci)]
#values = values[numpy.nonzero(values)]
return numpy.max(values)
def dunn_fast(points, labels, metric):
v = pdist(points, metric)
size_X = len(points)
X = numpy.zeros((size_X,size_X))
X[numpy.triu_indices(X.shape[0], k = 1)] = v
distances = X + X.T
ks = numpy.sort(numpy.unique(labels))
deltas = numpy.ones([len(ks), len(ks)])*1000000
big_deltas = numpy.zeros([len(ks), 1])
l_range = list(range(0, len(ks)))
for k in l_range:
for l in (l_range[0:k]+l_range[k+1:]):
deltas[k, l] = delta_fast((labels == ks[k]), (labels == ks[l]), distances)
big_deltas[k] = big_delta_fast((labels == ks[k]), distances)
di = numpy.min(deltas)/numpy.max(big_deltas)
return di
def DI(startpts, points, k, metric):
labelsPred = getLabelsPred(startpts, points, k)
if numpy.unique(labelsPred).size < k:
fitness = sys.float_info.max
else:
dunn = dunn_fast(points, labelsPred, metric)
if(dunn < 0):
dunn = 0
fitness = 1 - dunn
return fitness, labelsPred
def getFunctionDetails(a):
# [name, lb, ub]
param = { 0: ["SSE",0,1],
1: ["TWCV",0,1],
2: ["SC",0,1],
3: ["DB",0,1],
#4: ["CH",0,1],
4: ["DI",0,1]
}
return param.get(a, "nothing") | 30.18 | 86 | 0.611663 |
from sklearn import cluster, metrics
from scipy.spatial.distance import pdist, cdist
import numpy
import sys
def getLabelsPred(startpts, points, k):
labelsPred = [-1] * len(points)
for i in range(len(points)):
distances = numpy.linalg.norm(points[i]-startpts, axis = 1)
labelsPred[i] = numpy.argmin(distances)
return labelsPred
def SSE(startpts, points, k, metric):
labelsPred = getLabelsPred(startpts, points, k)
fitness = 0
if numpy.unique(labelsPred).size < k:
fitness = sys.float_info.max
else:
centroidsForPoints = startpts[labelsPred]
fitness = 0
for i in range(k):
indexes = [n for n,x in enumerate(labelsPred) if x==i]
fit = cdist(points[indexes], centroidsForPoints[indexes], metric)**2
fit = sum(fit)[0]
fitness += fit
return fitness, labelsPred
def TWCV(startpts, points, k):
labelsPred = getLabelsPred(startpts, points, k)
if numpy.unique(labelsPred).size < k:
fitness = sys.float_info.max
else:
sumAllFeatures = sum(sum(numpy.power(points,2)))
sumAllPairPointsCluster = 0
for clusterId in range(k):
indices = numpy.where(numpy.array(labelsPred) == clusterId)[0]
pointsInCluster = points[numpy.array(indices)]
sumPairPointsCluster = sum(pointsInCluster)
sumPairPointsCluster = numpy.power(sumPairPointsCluster,2)
sumPairPointsCluster = sum(sumPairPointsCluster)
sumPairPointsCluster = sumPairPointsCluster/len(pointsInCluster)
sumAllPairPointsCluster += sumPairPointsCluster
fitness = (sumAllFeatures - sumAllPairPointsCluster)
return fitness, labelsPred
def SC(startpts, points, k, metric):
labelsPred = getLabelsPred(startpts, points, k)
if numpy.unique(labelsPred).size < k:
fitness = sys.float_info.max
else:
silhouette = metrics.silhouette_score(points, labelsPred, metric=metric)
silhouette = (silhouette + 1) / 2
fitness = 1 - silhouette
return fitness, labelsPred
def DB(startpts, points, k):
labelsPred = getLabelsPred(startpts, points, k)
if numpy.unique(labelsPred).size < k:
fitness = sys.float_info.max
else:
fitness = metrics.davies_bouldin_score(points, labelsPred)
return fitness, labelsPred
def CH(startpts, points, k):
labelsPred = getLabelsPred(startpts, points, k)
if numpy.unique(labelsPred).size < k:
fitness = sys.float_info.max
else:
ch = metrics.calinski_harabaz_score(points, labelsPred)
fitness = 1 / ch
return fitness, labelsPred
def delta_fast(ck, cl, distances):
values = distances[numpy.where(ck)][:, numpy.where(cl)]
values = values[numpy.nonzero(values)]
return numpy.min(values)
def big_delta_fast(ci, distances):
values = distances[numpy.where(ci)][:, numpy.where(ci)]
return numpy.max(values)
def dunn_fast(points, labels, metric):
v = pdist(points, metric)
size_X = len(points)
X = numpy.zeros((size_X,size_X))
X[numpy.triu_indices(X.shape[0], k = 1)] = v
distances = X + X.T
ks = numpy.sort(numpy.unique(labels))
deltas = numpy.ones([len(ks), len(ks)])*1000000
big_deltas = numpy.zeros([len(ks), 1])
l_range = list(range(0, len(ks)))
for k in l_range:
for l in (l_range[0:k]+l_range[k+1:]):
deltas[k, l] = delta_fast((labels == ks[k]), (labels == ks[l]), distances)
big_deltas[k] = big_delta_fast((labels == ks[k]), distances)
di = numpy.min(deltas)/numpy.max(big_deltas)
return di
def DI(startpts, points, k, metric):
labelsPred = getLabelsPred(startpts, points, k)
if numpy.unique(labelsPred).size < k:
fitness = sys.float_info.max
else:
dunn = dunn_fast(points, labelsPred, metric)
if(dunn < 0):
dunn = 0
fitness = 1 - dunn
return fitness, labelsPred
def getFunctionDetails(a):
param = { 0: ["SSE",0,1],
1: ["TWCV",0,1],
2: ["SC",0,1],
3: ["DB",0,1],
4: ["DI",0,1]
}
return param.get(a, "nothing") | true | true |
f7281187ed5c880e1f702c2aab3c172b60a8524a | 2,666 | py | Python | response/slack/action_handlers.py | qubitdigital/response | 9ac9d11f60d108739043697aa19478474cb94a09 | [
"MIT"
] | null | null | null | response/slack/action_handlers.py | qubitdigital/response | 9ac9d11f60d108739043697aa19478474cb94a09 | [
"MIT"
] | 9 | 2021-03-19T13:56:39.000Z | 2021-06-10T20:48:16.000Z | response/slack/action_handlers.py | qubitdigital/response | 9ac9d11f60d108739043697aa19478474cb94a09 | [
"MIT"
] | null | null | null | import json
from datetime import datetime
from django.conf import settings
from response.core.models.incident import Incident
from response.slack.settings import INCIDENT_EDIT_DIALOG
from response.slack.dialog_builder import Dialog, Text, TextArea, SelectWithOptions, SelectFromUsers
from response.slack.models import HeadlinePost, CommsChannel
from response.slack.decorators import action_handler, ActionContext
import logging
logger = logging.getLogger(__name__)
@action_handler(HeadlinePost.CLOSE_INCIDENT_BUTTON)
def handle_close_incident(ac: ActionContext):
ac.incident.end_time = datetime.now()
ac.incident.save()
@action_handler(HeadlinePost.CREATE_COMMS_CHANNEL_BUTTON)
def handle_create_comms_channel(ac: ActionContext):
if CommsChannel.objects.filter(incident=ac.incident).exists():
return
comms_channel = CommsChannel.objects.create_comms_channel(ac.incident)
# Invite the bot to the channel
try:
settings.SLACK_CLIENT.invite_user_to_channel(settings.INCIDENT_BOT_ID, comms_channel.channel_id)
except Exception as ex:
logger.error(ex)
# Un-invite the user who owns the Slack token,
# otherwise they'll be added to every incident channel
slack_token_owner = settings.SLACK_CLIENT.get_slack_token_owner()
if ac.incident.reporter != slack_token_owner:
settings.SLACK_CLIENT.leave_channel(comms_channel.channel_id)
# Update the headline post to link to this
headline_post = HeadlinePost.objects.get(
incident=ac.incident
)
headline_post.comms_channel = comms_channel
headline_post.save()
@action_handler(HeadlinePost.EDIT_INCIDENT_BUTTON)
def handle_edit_incident_button(ac: ActionContext):
dialog = Dialog(
title=f"Edit Incident {ac.incident.pk}",
submit_label="Save",
state=ac.incident.pk,
elements=[
Text(label="Report", name="report", value=ac.incident.report),
TextArea(label="Summary", name="summary", value=ac.incident.summary, optional=True, placeholder="Can you share any more details?"),
TextArea(label="Impact", name="impact", value=ac.incident.impact, optional=True, placeholder="Who or what might be affected?", hint="Think about affected people, systems, and processes"),
SelectFromUsers(label="Lead", name="lead", value=ac.incident.lead.external_id if ac.incident.lead else None, optional=True),
SelectWithOptions([(s.capitalize(), i) for i, s in Incident.SEVERITIES], value=ac.incident.severity, label="Severity", name="severity", optional=True)
]
)
dialog.send_open_dialog(INCIDENT_EDIT_DIALOG, ac.trigger_id)
| 41.015385 | 199 | 0.749437 | import json
from datetime import datetime
from django.conf import settings
from response.core.models.incident import Incident
from response.slack.settings import INCIDENT_EDIT_DIALOG
from response.slack.dialog_builder import Dialog, Text, TextArea, SelectWithOptions, SelectFromUsers
from response.slack.models import HeadlinePost, CommsChannel
from response.slack.decorators import action_handler, ActionContext
import logging
logger = logging.getLogger(__name__)
@action_handler(HeadlinePost.CLOSE_INCIDENT_BUTTON)
def handle_close_incident(ac: ActionContext):
ac.incident.end_time = datetime.now()
ac.incident.save()
@action_handler(HeadlinePost.CREATE_COMMS_CHANNEL_BUTTON)
def handle_create_comms_channel(ac: ActionContext):
if CommsChannel.objects.filter(incident=ac.incident).exists():
return
comms_channel = CommsChannel.objects.create_comms_channel(ac.incident)
try:
settings.SLACK_CLIENT.invite_user_to_channel(settings.INCIDENT_BOT_ID, comms_channel.channel_id)
except Exception as ex:
logger.error(ex)
slack_token_owner = settings.SLACK_CLIENT.get_slack_token_owner()
if ac.incident.reporter != slack_token_owner:
settings.SLACK_CLIENT.leave_channel(comms_channel.channel_id)
# Update the headline post to link to this
headline_post = HeadlinePost.objects.get(
incident=ac.incident
)
headline_post.comms_channel = comms_channel
headline_post.save()
@action_handler(HeadlinePost.EDIT_INCIDENT_BUTTON)
def handle_edit_incident_button(ac: ActionContext):
dialog = Dialog(
title=f"Edit Incident {ac.incident.pk}",
submit_label="Save",
state=ac.incident.pk,
elements=[
Text(label="Report", name="report", value=ac.incident.report),
TextArea(label="Summary", name="summary", value=ac.incident.summary, optional=True, placeholder="Can you share any more details?"),
TextArea(label="Impact", name="impact", value=ac.incident.impact, optional=True, placeholder="Who or what might be affected?", hint="Think about affected people, systems, and processes"),
SelectFromUsers(label="Lead", name="lead", value=ac.incident.lead.external_id if ac.incident.lead else None, optional=True),
SelectWithOptions([(s.capitalize(), i) for i, s in Incident.SEVERITIES], value=ac.incident.severity, label="Severity", name="severity", optional=True)
]
)
dialog.send_open_dialog(INCIDENT_EDIT_DIALOG, ac.trigger_id)
| true | true |
f728126172e0b228a0b705f40294c9a3ba4e189a | 12,409 | py | Python | azure-iot-device/tests/common/pipeline/test_pipeline_stages_http.py | olivakar/azure-iot-sdk-python | d8f2403030cf94510d381d8d5ac37af6e8d306f8 | [
"MIT"
] | null | null | null | azure-iot-device/tests/common/pipeline/test_pipeline_stages_http.py | olivakar/azure-iot-sdk-python | d8f2403030cf94510d381d8d5ac37af6e8d306f8 | [
"MIT"
] | null | null | null | azure-iot-device/tests/common/pipeline/test_pipeline_stages_http.py | olivakar/azure-iot-sdk-python | d8f2403030cf94510d381d8d5ac37af6e8d306f8 | [
"MIT"
] | null | null | null | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import logging
import pytest
import sys
import six
from azure.iot.device.common import transport_exceptions, handle_exceptions
from azure.iot.device.common.pipeline import (
pipeline_ops_base,
pipeline_stages_base,
pipeline_ops_http,
pipeline_stages_http,
pipeline_exceptions,
config,
)
from tests.common.pipeline.helpers import StageRunOpTestBase
from tests.common.pipeline import pipeline_stage_test
this_module = sys.modules[__name__]
logging.basicConfig(level=logging.DEBUG)
pytestmark = pytest.mark.usefixtures("fake_pipeline_thread")
###################
# COMMON FIXTURES #
###################
@pytest.fixture
def mock_transport(mocker):
return mocker.patch(
"azure.iot.device.common.pipeline.pipeline_stages_http.HTTPTransport", autospec=True
)
# Not a fixture, but used in parametrization
def fake_callback():
pass
########################
# HTTP TRANSPORT STAGE #
########################
class HTTPTransportStageTestConfig(object):
@pytest.fixture
def cls_type(self):
return pipeline_stages_http.HTTPTransportStage
@pytest.fixture
def init_kwargs(self, mocker):
return {}
@pytest.fixture
def stage(self, mocker, cls_type, init_kwargs):
stage = cls_type(**init_kwargs)
stage.send_op_down = mocker.MagicMock()
return stage
class HTTPTransportInstantiationTests(HTTPTransportStageTestConfig):
@pytest.mark.it("Initializes 'sas_token' attribute as None")
def test_sas_token(self, cls_type, init_kwargs):
stage = cls_type(**init_kwargs)
assert stage.sas_token is None
@pytest.mark.it("Initializes 'transport' attribute as None")
def test_transport(self, cls_type, init_kwargs):
stage = cls_type(**init_kwargs)
assert stage.transport is None
pipeline_stage_test.add_base_pipeline_stage_tests(
test_module=this_module,
stage_class_under_test=pipeline_stages_http.HTTPTransportStage,
stage_test_config_class=HTTPTransportStageTestConfig,
extended_stage_instantiation_test_class=HTTPTransportInstantiationTests,
)
@pytest.mark.describe(
"HTTPTransportStage - .run_op() -- Called with SetHTTPConnectionArgsOperation"
)
class TestHTTPTransportStageRunOpCalledWithSetHTTPConnectionArgsOperation(
HTTPTransportStageTestConfig, StageRunOpTestBase
):
@pytest.fixture
def op(self, mocker):
return pipeline_ops_http.SetHTTPConnectionArgsOperation(
hostname="fake_hostname",
server_verification_cert="fake_server_verification_cert",
client_cert="fake_client_cert",
sas_token="fake_sas_token",
callback=mocker.MagicMock(),
)
@pytest.mark.it("Stores the sas_token operation in the 'sas_token' attribute of the stage")
def test_stores_data(self, stage, op, mocker, mock_transport):
stage.run_op(op)
assert stage.sas_token == op.sas_token
# TODO: Should probably remove the requirement to set it on the root. This seems only needed by Horton
@pytest.mark.it(
"Creates an HTTPTransport object and sets it as the 'transport' attribute of the stage (and on the pipeline root)"
)
def test_creates_transport(self, mocker, stage, op, mock_transport):
assert stage.transport is None
stage.run_op(op)
assert mock_transport.call_count == 1
assert mock_transport.call_args == mocker.call(
hostname=op.hostname,
server_verification_cert=op.server_verification_cert,
x509_cert=op.client_cert,
)
assert stage.transport is mock_transport.return_value
@pytest.mark.it("Completes the operation with success, upon successful execution")
def test_succeeds(self, mocker, stage, op, mock_transport):
assert not op.completed
stage.run_op(op)
assert op.completed
# NOTE: The HTTPTransport object is not instantiated upon instantiation of the HTTPTransportStage.
# It is only added once the SetHTTPConnectionArgsOperation runs.
# The lifecycle of the HTTPTransportStage is as follows:
# 1. Instantiate the stage
# 2. Configure the stage with a SetHTTPConnectionArgsOperation
# 3. Run any other desired operations.
#
# This is to say, no operation should be running before SetHTTPConnectionArgsOperation.
# Thus, for the following tests, we will assume that the HTTPTransport has already been created,
# and as such, the stage fixture used will have already have one.
class HTTPTransportStageTestConfigComplex(HTTPTransportStageTestConfig):
# We add a pytest fixture parametrization between SAS an X509 since depending on the version of authentication, the op will be formatted differently.
@pytest.fixture(params=["SAS", "X509"])
def stage(self, mocker, request, cls_type, init_kwargs):
mock_transport = mocker.patch(
"azure.iot.device.common.pipeline.pipeline_stages_http.HTTPTransport", autospec=True
)
stage = cls_type(**init_kwargs)
stage.send_op_down = mocker.MagicMock()
# Set up the Transport on the stage
if request.param == "SAS":
op = pipeline_ops_http.SetHTTPConnectionArgsOperation(
hostname="fake_hostname",
server_verification_cert="fake_server_verification_cert",
sas_token="fake_sas_token",
callback=mocker.MagicMock(),
)
else:
op = pipeline_ops_http.SetHTTPConnectionArgsOperation(
hostname="fake_hostname",
server_verification_cert="fake_server_verification_cert",
client_cert="fake_client_cert",
callback=mocker.MagicMock(),
)
stage.run_op(op)
assert stage.transport is mock_transport.return_value
return stage
@pytest.mark.describe("HTTPTransportStage - .run_op() -- Called with UpdateSasTokenOperation")
class TestHTTPTransportStageRunOpCalledWithUpdateSasTokenOperation(
HTTPTransportStageTestConfigComplex, StageRunOpTestBase
):
@pytest.fixture
def op(self, mocker):
return pipeline_ops_base.UpdateSasTokenOperation(
sas_token="new_fake_sas_token", callback=mocker.MagicMock()
)
@pytest.mark.it(
"Updates the 'sas_token' attribute to be the new value contained in the operation"
)
def test_updates_token(self, stage, op):
assert stage.sas_token != op.sas_token
stage.run_op(op)
assert stage.sas_token == op.sas_token
@pytest.mark.it("Completes the operation with success, upon successful execution")
def test_completes_op(self, stage, op):
assert not op.completed
stage.run_op(op)
assert op.completed
fake_method = "__fake_method__"
fake_path = "__fake_path__"
fake_headers = {"__fake_key__": "__fake_value__"}
fake_body = "__fake_body__"
fake_query_params = "__fake_query_params__"
fake_sas_token = "fake_sas_token"
@pytest.mark.describe(
"HTTPTransportStage - .run_op() -- Called with HTTPRequestAndResponseOperation"
)
class TestHTTPTransportStageRunOpCalledWithHTTPRequestAndResponseOperation(
HTTPTransportStageTestConfigComplex, StageRunOpTestBase
):
@pytest.fixture
def op(self, mocker):
return pipeline_ops_http.HTTPRequestAndResponseOperation(
method=fake_method,
path=fake_path,
headers=fake_headers,
body=fake_body,
query_params=fake_query_params,
callback=mocker.MagicMock(),
)
@pytest.mark.it("Sends an HTTP request via the HTTPTransport")
def test_http_request(self, mocker, stage, op):
stage.run_op(op)
# We add this because the default stage here contains a SAS Token.
fake_headers["Authorization"] = fake_sas_token
assert stage.transport.request.call_count == 1
assert stage.transport.request.call_args == mocker.call(
method=fake_method,
path=fake_path,
headers=fake_headers,
body=fake_body,
query_params=fake_query_params,
callback=mocker.ANY,
)
@pytest.mark.it(
"Does not provide an Authorization header if the SAS Token is not set in the stage"
)
def test_header_with_no_sas(self, mocker, stage, op):
# Manually overwriting stage with no SAS Token.
stage.sas_token = None
stage.run_op(op)
assert stage.transport.request.call_count == 1
assert stage.transport.request.call_args == mocker.call(
method=fake_method,
path=fake_path,
headers=fake_headers,
body=fake_body,
query_params=fake_query_params,
callback=mocker.ANY,
)
@pytest.mark.it(
"Completes the operation unsucessfully if there is a failure requesting via the HTTPTransport, using the error raised by the HTTPTransport"
)
def test_fails_operation(self, mocker, stage, op, arbitrary_exception):
stage.transport.request.side_effect = arbitrary_exception
stage.run_op(op)
assert op.completed
assert op.error is arbitrary_exception
@pytest.mark.it(
"Completes the operation successfully if the request invokes the provided callback without an error"
)
def test_completes_callback(self, mocker, stage, op):
def mock_request_callback(method, path, headers, query_params, body, callback):
fake_response = {
"resp": "__fake_response__".encode("utf-8"),
"status_code": "__fake_status_code__",
"reason": "__fake_reason__",
}
return callback(response=fake_response)
# This is a way for us to mock the transport invoking the callback
stage.transport.request.side_effect = mock_request_callback
stage.run_op(op)
assert op.completed
@pytest.mark.it(
"Adds a reason, status code, and response body to the op if request invokes the provided callback without an error"
)
def test_formats_op_on_complete(self, mocker, stage, op):
def mock_request_callback(method, path, headers, query_params, body, callback):
fake_response = {
"resp": "__fake_response__".encode("utf-8"),
"status_code": "__fake_status_code__",
"reason": "__fake_reason__",
}
return callback(response=fake_response)
# This is a way for us to mock the transport invoking the callback
stage.transport.request.side_effect = mock_request_callback
stage.run_op(op)
assert op.reason == "__fake_reason__"
assert op.response_body == "__fake_response__".encode("utf-8")
assert op.status_code == "__fake_status_code__"
@pytest.mark.it(
"Completes the operation with an error if the request invokes the provided callback with the same error"
)
def test_completes_callback_with_error(self, mocker, stage, op, arbitrary_exception):
def mock_on_response_complete(method, path, headers, query_params, body, callback):
return callback(error=arbitrary_exception)
stage.transport.request.side_effect = mock_on_response_complete
stage.run_op(op)
assert op.completed
assert op.error is arbitrary_exception
# NOTE: This is not something that should ever happen in correct program flow
# There should be no operations that make it to the HTTPTransportStage that are not handled by it
@pytest.mark.describe("HTTPTransportStage - .run_op() -- called with arbitrary other operation")
class TestHTTPTransportStageRunOpCalledWithArbitraryOperation(
HTTPTransportStageTestConfigComplex, StageRunOpTestBase
):
@pytest.fixture
def op(self, arbitrary_op):
return arbitrary_op
@pytest.mark.it("Sends the operation down")
def test_sends_op_down(self, mocker, stage, op):
stage.run_op(op)
assert stage.send_op_down.call_count == 1
assert stage.send_op_down.call_args == mocker.call(op)
| 38.181538 | 153 | 0.6895 |
import logging
import pytest
import sys
import six
from azure.iot.device.common import transport_exceptions, handle_exceptions
from azure.iot.device.common.pipeline import (
pipeline_ops_base,
pipeline_stages_base,
pipeline_ops_http,
pipeline_stages_http,
pipeline_exceptions,
config,
)
from tests.common.pipeline.helpers import StageRunOpTestBase
from tests.common.pipeline import pipeline_stage_test
this_module = sys.modules[__name__]
logging.basicConfig(level=logging.DEBUG)
pytestmark = pytest.mark.usefixtures("fake_pipeline_thread")
k.it("Initializes 'transport' attribute as None")
def test_transport(self, cls_type, init_kwargs):
stage = cls_type(**init_kwargs)
assert stage.transport is None
pipeline_stage_test.add_base_pipeline_stage_tests(
test_module=this_module,
stage_class_under_test=pipeline_stages_http.HTTPTransportStage,
stage_test_config_class=HTTPTransportStageTestConfig,
extended_stage_instantiation_test_class=HTTPTransportInstantiationTests,
)
@pytest.mark.describe(
"HTTPTransportStage - .run_op() -- Called with SetHTTPConnectionArgsOperation"
)
class TestHTTPTransportStageRunOpCalledWithSetHTTPConnectionArgsOperation(
HTTPTransportStageTestConfig, StageRunOpTestBase
):
@pytest.fixture
def op(self, mocker):
return pipeline_ops_http.SetHTTPConnectionArgsOperation(
hostname="fake_hostname",
server_verification_cert="fake_server_verification_cert",
client_cert="fake_client_cert",
sas_token="fake_sas_token",
callback=mocker.MagicMock(),
)
@pytest.mark.it("Stores the sas_token operation in the 'sas_token' attribute of the stage")
def test_stores_data(self, stage, op, mocker, mock_transport):
stage.run_op(op)
assert stage.sas_token == op.sas_token
@pytest.mark.it(
"Creates an HTTPTransport object and sets it as the 'transport' attribute of the stage (and on the pipeline root)"
)
def test_creates_transport(self, mocker, stage, op, mock_transport):
assert stage.transport is None
stage.run_op(op)
assert mock_transport.call_count == 1
assert mock_transport.call_args == mocker.call(
hostname=op.hostname,
server_verification_cert=op.server_verification_cert,
x509_cert=op.client_cert,
)
assert stage.transport is mock_transport.return_value
@pytest.mark.it("Completes the operation with success, upon successful execution")
def test_succeeds(self, mocker, stage, op, mock_transport):
assert not op.completed
stage.run_op(op)
assert op.completed
class HTTPTransportStageTestConfigComplex(HTTPTransportStageTestConfig):
@pytest.fixture(params=["SAS", "X509"])
def stage(self, mocker, request, cls_type, init_kwargs):
mock_transport = mocker.patch(
"azure.iot.device.common.pipeline.pipeline_stages_http.HTTPTransport", autospec=True
)
stage = cls_type(**init_kwargs)
stage.send_op_down = mocker.MagicMock()
if request.param == "SAS":
op = pipeline_ops_http.SetHTTPConnectionArgsOperation(
hostname="fake_hostname",
server_verification_cert="fake_server_verification_cert",
sas_token="fake_sas_token",
callback=mocker.MagicMock(),
)
else:
op = pipeline_ops_http.SetHTTPConnectionArgsOperation(
hostname="fake_hostname",
server_verification_cert="fake_server_verification_cert",
client_cert="fake_client_cert",
callback=mocker.MagicMock(),
)
stage.run_op(op)
assert stage.transport is mock_transport.return_value
return stage
@pytest.mark.describe("HTTPTransportStage - .run_op() -- Called with UpdateSasTokenOperation")
class TestHTTPTransportStageRunOpCalledWithUpdateSasTokenOperation(
HTTPTransportStageTestConfigComplex, StageRunOpTestBase
):
@pytest.fixture
def op(self, mocker):
return pipeline_ops_base.UpdateSasTokenOperation(
sas_token="new_fake_sas_token", callback=mocker.MagicMock()
)
@pytest.mark.it(
"Updates the 'sas_token' attribute to be the new value contained in the operation"
)
def test_updates_token(self, stage, op):
assert stage.sas_token != op.sas_token
stage.run_op(op)
assert stage.sas_token == op.sas_token
@pytest.mark.it("Completes the operation with success, upon successful execution")
def test_completes_op(self, stage, op):
assert not op.completed
stage.run_op(op)
assert op.completed
fake_method = "__fake_method__"
fake_path = "__fake_path__"
fake_headers = {"__fake_key__": "__fake_value__"}
fake_body = "__fake_body__"
fake_query_params = "__fake_query_params__"
fake_sas_token = "fake_sas_token"
@pytest.mark.describe(
"HTTPTransportStage - .run_op() -- Called with HTTPRequestAndResponseOperation"
)
class TestHTTPTransportStageRunOpCalledWithHTTPRequestAndResponseOperation(
HTTPTransportStageTestConfigComplex, StageRunOpTestBase
):
@pytest.fixture
def op(self, mocker):
return pipeline_ops_http.HTTPRequestAndResponseOperation(
method=fake_method,
path=fake_path,
headers=fake_headers,
body=fake_body,
query_params=fake_query_params,
callback=mocker.MagicMock(),
)
@pytest.mark.it("Sends an HTTP request via the HTTPTransport")
def test_http_request(self, mocker, stage, op):
stage.run_op(op)
fake_headers["Authorization"] = fake_sas_token
assert stage.transport.request.call_count == 1
assert stage.transport.request.call_args == mocker.call(
method=fake_method,
path=fake_path,
headers=fake_headers,
body=fake_body,
query_params=fake_query_params,
callback=mocker.ANY,
)
@pytest.mark.it(
"Does not provide an Authorization header if the SAS Token is not set in the stage"
)
def test_header_with_no_sas(self, mocker, stage, op):
stage.sas_token = None
stage.run_op(op)
assert stage.transport.request.call_count == 1
assert stage.transport.request.call_args == mocker.call(
method=fake_method,
path=fake_path,
headers=fake_headers,
body=fake_body,
query_params=fake_query_params,
callback=mocker.ANY,
)
@pytest.mark.it(
"Completes the operation unsucessfully if there is a failure requesting via the HTTPTransport, using the error raised by the HTTPTransport"
)
def test_fails_operation(self, mocker, stage, op, arbitrary_exception):
stage.transport.request.side_effect = arbitrary_exception
stage.run_op(op)
assert op.completed
assert op.error is arbitrary_exception
@pytest.mark.it(
"Completes the operation successfully if the request invokes the provided callback without an error"
)
def test_completes_callback(self, mocker, stage, op):
def mock_request_callback(method, path, headers, query_params, body, callback):
fake_response = {
"resp": "__fake_response__".encode("utf-8"),
"status_code": "__fake_status_code__",
"reason": "__fake_reason__",
}
return callback(response=fake_response)
stage.transport.request.side_effect = mock_request_callback
stage.run_op(op)
assert op.completed
@pytest.mark.it(
"Adds a reason, status code, and response body to the op if request invokes the provided callback without an error"
)
def test_formats_op_on_complete(self, mocker, stage, op):
def mock_request_callback(method, path, headers, query_params, body, callback):
fake_response = {
"resp": "__fake_response__".encode("utf-8"),
"status_code": "__fake_status_code__",
"reason": "__fake_reason__",
}
return callback(response=fake_response)
stage.transport.request.side_effect = mock_request_callback
stage.run_op(op)
assert op.reason == "__fake_reason__"
assert op.response_body == "__fake_response__".encode("utf-8")
assert op.status_code == "__fake_status_code__"
@pytest.mark.it(
"Completes the operation with an error if the request invokes the provided callback with the same error"
)
def test_completes_callback_with_error(self, mocker, stage, op, arbitrary_exception):
def mock_on_response_complete(method, path, headers, query_params, body, callback):
return callback(error=arbitrary_exception)
stage.transport.request.side_effect = mock_on_response_complete
stage.run_op(op)
assert op.completed
assert op.error is arbitrary_exception
@pytest.mark.describe("HTTPTransportStage - .run_op() -- called with arbitrary other operation")
class TestHTTPTransportStageRunOpCalledWithArbitraryOperation(
HTTPTransportStageTestConfigComplex, StageRunOpTestBase
):
@pytest.fixture
def op(self, arbitrary_op):
return arbitrary_op
@pytest.mark.it("Sends the operation down")
def test_sends_op_down(self, mocker, stage, op):
stage.run_op(op)
assert stage.send_op_down.call_count == 1
assert stage.send_op_down.call_args == mocker.call(op)
| true | true |
f7281265449a1193fd08ea906ba96174e969eb2d | 1,914 | py | Python | loadmodel.py | shfshf/seq2annotation | d4bf88a869631b43fa2974c2ffa1c5dd6a7623ed | [
"Apache-2.0"
] | 90 | 2018-11-29T07:05:16.000Z | 2021-11-22T11:32:58.000Z | loadmodel.py | shfshf/seq2annotation | d4bf88a869631b43fa2974c2ffa1c5dd6a7623ed | [
"Apache-2.0"
] | 50 | 2019-06-27T07:11:18.000Z | 2022-02-10T00:01:02.000Z | loadmodel.py | lanSeFangZhou/seq2annotation | a824520d46f0b3d70268fae422976a5ce1b3f4ce | [
"Apache-2.0"
] | 23 | 2019-01-03T14:57:15.000Z | 2022-03-08T07:50:33.000Z | import tensorflow as tf
from tensorflow.python.platform import gfile
# only for bugfix
tf.contrib.rnn
output_graph_path = './model.pb'
graph = tf.Graph()
with gfile.FastGFile(output_graph_path, 'rb') as f:
output_graph_def = tf.GraphDef()
output_graph_def.ParseFromString(f.read())
with graph.as_default():
tf.import_graph_def(output_graph_def, name="")
with tf.Session(graph=graph) as sess:
init_all_tables = graph.get_operation_by_name('init_all_tables')
sess.run(init_all_tables)
# sess.run(tf.global_variables_initializer())
# sess.run(tf.local_variables_initializer())
# 得到当前图有几个操作节点
print("%d ops in the final graph." % len(output_graph_def.node))
tensor_name = [tensor.name for tensor in output_graph_def.node]
print(tensor_name)
print('---------------------------')
Placeholder = sess.graph.get_tensor_by_name('Placeholder:0')
Placeholder_1 = sess.graph.get_tensor_by_name('Placeholder_1:0')
# embedding层的输出
embedding_out = sess.graph.get_tensor_by_name('embedding_lookup:0')
enbedding_transpose = sess.graph.get_tensor_by_name('transpose:0')
# BiLSTM层的输出
BiLSTM_out = sess.graph.get_tensor_by_name('concat:0')
BiLSTM_transpose_1 = sess.graph.get_tensor_by_name('transpose_1:0')
a = sess.graph.get_tensor_by_name('Variable_1:0')
a_array = a.eval(session=sess)
for i in a_array[:1]:
print(i)
print('#####################')
input_words = [['唱', '一', '首', '不', '消', '失', '的', '回', '忆']]
input_words_len = [9]
b = sess.graph.get_tensor_by_name('hash_table_Lookup/hash_table_Lookup/LookupTableFindV2:0')
b = sess.run(b, {Placeholder: input_words, Placeholder_1: input_words_len})
for i in b:
print(i) | 36.807692 | 101 | 0.630617 | import tensorflow as tf
from tensorflow.python.platform import gfile
tf.contrib.rnn
output_graph_path = './model.pb'
graph = tf.Graph()
with gfile.FastGFile(output_graph_path, 'rb') as f:
output_graph_def = tf.GraphDef()
output_graph_def.ParseFromString(f.read())
with graph.as_default():
tf.import_graph_def(output_graph_def, name="")
with tf.Session(graph=graph) as sess:
init_all_tables = graph.get_operation_by_name('init_all_tables')
sess.run(init_all_tables)
print("%d ops in the final graph." % len(output_graph_def.node))
tensor_name = [tensor.name for tensor in output_graph_def.node]
print(tensor_name)
print('---------------------------')
Placeholder = sess.graph.get_tensor_by_name('Placeholder:0')
Placeholder_1 = sess.graph.get_tensor_by_name('Placeholder_1:0')
embedding_out = sess.graph.get_tensor_by_name('embedding_lookup:0')
enbedding_transpose = sess.graph.get_tensor_by_name('transpose:0')
BiLSTM_out = sess.graph.get_tensor_by_name('concat:0')
BiLSTM_transpose_1 = sess.graph.get_tensor_by_name('transpose_1:0')
a = sess.graph.get_tensor_by_name('Variable_1:0')
a_array = a.eval(session=sess)
for i in a_array[:1]:
print(i)
print('#####################')
input_words = [['唱', '一', '首', '不', '消', '失', '的', '回', '忆']]
input_words_len = [9]
b = sess.graph.get_tensor_by_name('hash_table_Lookup/hash_table_Lookup/LookupTableFindV2:0')
b = sess.run(b, {Placeholder: input_words, Placeholder_1: input_words_len})
for i in b:
print(i) | true | true |
f72814583f19fdfd0e5564abe74cf6998b30cf8c | 1,766 | py | Python | flowy/swf/history.py | severb/flowy | bb7c7df99b66e5ef8d7806210408487aed9db67a | [
"MIT"
] | 25 | 2015-03-24T08:59:21.000Z | 2021-01-08T13:39:00.000Z | flowy/swf/history.py | pbs/flowy | 9da8d5aa3b1efad84df0589402adeb770a034719 | [
"MIT"
] | 9 | 2015-01-08T04:25:34.000Z | 2016-10-06T08:54:50.000Z | flowy/swf/history.py | pbs/flowy | 9da8d5aa3b1efad84df0589402adeb770a034719 | [
"MIT"
] | 6 | 2015-01-22T08:00:38.000Z | 2021-01-05T20:31:24.000Z | from flowy.swf.decision import task_key, timer_key
class SWFExecutionHistory(object):
def __init__(self, running, timedout, results, errors, order):
self.running = running
self.timedout = timedout
self.results = results
self.errors = errors
self.order_ = order
def is_running(self, call_key):
return str(call_key) in self.running
def order(self, call_key):
return self.order_.index(str(call_key))
def has_result(self, call_key):
return str(call_key) in self.results
def result(self, call_key):
return self.results[str(call_key)]
def is_error(self, call_key):
return str(call_key) in self.errors
def error(self, call_key):
return self.errors[str(call_key)]
def is_timeout(self, call_key):
return str(call_key) in self.timedout
def is_timer_ready(self, call_key):
return timer_key(call_key) in self.results
def is_timer_running(self, call_key):
return timer_key(call_key) in self.running
class SWFTaskExecutionHistory(object):
def __init__(self, exec_history, identity):
self.exec_history = exec_history
self.identity = identity
def __getattr__(self, fname):
"""Compute the key and delegate to exec_history."""
if fname not in ['is_running', 'is_timeout', 'is_error', 'has_result',
'result', 'order', 'error']:
return getattr(super(SWFTaskExecutionHistory, self), fname)
delegate_to = getattr(self.exec_history, fname)
def clos(call_number, retry_number):
return delegate_to(task_key(self.identity, call_number, retry_number))
setattr(self, fname, clos) # cache it
return clos
| 30.448276 | 82 | 0.660249 | from flowy.swf.decision import task_key, timer_key
class SWFExecutionHistory(object):
def __init__(self, running, timedout, results, errors, order):
self.running = running
self.timedout = timedout
self.results = results
self.errors = errors
self.order_ = order
def is_running(self, call_key):
return str(call_key) in self.running
def order(self, call_key):
return self.order_.index(str(call_key))
def has_result(self, call_key):
return str(call_key) in self.results
def result(self, call_key):
return self.results[str(call_key)]
def is_error(self, call_key):
return str(call_key) in self.errors
def error(self, call_key):
return self.errors[str(call_key)]
def is_timeout(self, call_key):
return str(call_key) in self.timedout
def is_timer_ready(self, call_key):
return timer_key(call_key) in self.results
def is_timer_running(self, call_key):
return timer_key(call_key) in self.running
class SWFTaskExecutionHistory(object):
def __init__(self, exec_history, identity):
self.exec_history = exec_history
self.identity = identity
def __getattr__(self, fname):
if fname not in ['is_running', 'is_timeout', 'is_error', 'has_result',
'result', 'order', 'error']:
return getattr(super(SWFTaskExecutionHistory, self), fname)
delegate_to = getattr(self.exec_history, fname)
def clos(call_number, retry_number):
return delegate_to(task_key(self.identity, call_number, retry_number))
setattr(self, fname, clos)
return clos
| true | true |
f728147610d11a90efa14fbb6a821ac73ce691a8 | 1,334 | py | Python | exercises/practice/tree-building/.meta/example.py | samr1ddh1/python-1 | 8998d30bb0d6665dd233354670f21c4d11c2f1a0 | [
"MIT"
] | 1,177 | 2017-06-21T20:24:06.000Z | 2022-03-29T02:30:55.000Z | exercises/practice/tree-building/.meta/example.py | samr1ddh1/python-1 | 8998d30bb0d6665dd233354670f21c4d11c2f1a0 | [
"MIT"
] | 1,890 | 2017-06-18T20:06:10.000Z | 2022-03-31T18:35:51.000Z | exercises/practice/tree-building/.meta/example.py | samr1ddh1/python-1 | 8998d30bb0d6665dd233354670f21c4d11c2f1a0 | [
"MIT"
] | 1,095 | 2017-06-26T23:06:19.000Z | 2022-03-29T03:25:38.000Z | class Record:
def __init__(self, record_id, parent_id):
self.record_id = record_id
self.parent_id = parent_id
def equal_id(self):
return self.record_id == self.parent_id
class Node:
def __init__(self, node_id):
self.node_id = node_id
self.children = []
def validate_record(record):
if record.equal_id() and record.record_id != 0:
raise ValueError('Only root should have equal record and parent id.')
if not record.equal_id() and record.parent_id >= record.record_id:
raise ValueError("Node record_id should be smaller than it's parent_id.")
def BuildTree(records):
parent_dict = {}
node_dict = {}
ordered_id = sorted(idx.record_id for idx in records)
for record in records:
validate_record(record)
parent_dict[record.record_id] = record.parent_id
node_dict[record.record_id] = Node(record.record_id)
root_id = 0
root = None
for index, record_id in enumerate(ordered_id):
if index != record_id:
raise ValueError('Record id is invalid or out of order.')
if record_id == root_id:
root = node_dict[record_id]
else:
parent_id = parent_dict[record_id]
node_dict[parent_id].children.append(node_dict[record_id])
return root
| 27.791667 | 81 | 0.654423 | class Record:
def __init__(self, record_id, parent_id):
self.record_id = record_id
self.parent_id = parent_id
def equal_id(self):
return self.record_id == self.parent_id
class Node:
def __init__(self, node_id):
self.node_id = node_id
self.children = []
def validate_record(record):
if record.equal_id() and record.record_id != 0:
raise ValueError('Only root should have equal record and parent id.')
if not record.equal_id() and record.parent_id >= record.record_id:
raise ValueError("Node record_id should be smaller than it's parent_id.")
def BuildTree(records):
parent_dict = {}
node_dict = {}
ordered_id = sorted(idx.record_id for idx in records)
for record in records:
validate_record(record)
parent_dict[record.record_id] = record.parent_id
node_dict[record.record_id] = Node(record.record_id)
root_id = 0
root = None
for index, record_id in enumerate(ordered_id):
if index != record_id:
raise ValueError('Record id is invalid or out of order.')
if record_id == root_id:
root = node_dict[record_id]
else:
parent_id = parent_dict[record_id]
node_dict[parent_id].children.append(node_dict[record_id])
return root
| true | true |
f72814a675df3867ed79d00435689d65ca7e9ffb | 1,041 | py | Python | autoio-interfaces/chemkin_io/tests/test__species_write_read.py | lpratalimaffei/autoio | 57be6e4882af1841153c19e7353e2531e64ce47f | [
"Apache-2.0"
] | null | null | null | autoio-interfaces/chemkin_io/tests/test__species_write_read.py | lpratalimaffei/autoio | 57be6e4882af1841153c19e7353e2531e64ce47f | [
"Apache-2.0"
] | 1 | 2022-02-15T19:35:14.000Z | 2022-02-15T19:35:14.000Z | autoio-interfaces/chemkin_io/tests/test__species_write_read.py | lpratalimaffei/autoio | 57be6e4882af1841153c19e7353e2531e64ce47f | [
"Apache-2.0"
] | 13 | 2020-06-24T05:21:11.000Z | 2021-05-05T19:58:30.000Z | """ tests chemkin_io.writer.mechanism.species_block
"""
from chemkin_io.writer.mechanism import species_block as writer
from chemkin_io.parser.species import names as parser
SPC_IDENT_DCT = {
'O': {'smiles': 'smiles_1',
'inchi': 'inchi_1',
'charge': '',
'mult': '',
'sens': ''},
'H': {'smiles': 'smiles_2',
'inchi': 'inchi_2',
'charge': '',
'mult': '',
'sens': ''}
}
SPC_NAMES_STRING_1 = (
'SPECIES \n\nO ! SMILES: smiles_1 ' +
'InChi: inchi_1 \nH ! SMILES: smiles_2 ' +
'InChi: inchi_2 \n\nEND \n\n\n'
)
SPC_NAMES_STRING_2 = 'OH \nHO2 \nC3H8 \nN2O'
SPC_NAMES_TUPLE = ('OH', 'HO2', 'C3H8', 'N2O')
def test__write_spc_names():
""" Tests the species names writing
"""
spc_str = writer(SPC_IDENT_DCT)
assert spc_str == SPC_NAMES_STRING_1
def test__read_spc_names():
""" Tests the parsing of species names
"""
spc_tuple = parser(SPC_NAMES_STRING_2)
assert spc_tuple == SPC_NAMES_TUPLE
| 26.025 | 63 | 0.588857 |
from chemkin_io.writer.mechanism import species_block as writer
from chemkin_io.parser.species import names as parser
SPC_IDENT_DCT = {
'O': {'smiles': 'smiles_1',
'inchi': 'inchi_1',
'charge': '',
'mult': '',
'sens': ''},
'H': {'smiles': 'smiles_2',
'inchi': 'inchi_2',
'charge': '',
'mult': '',
'sens': ''}
}
SPC_NAMES_STRING_1 = (
'SPECIES \n\nO ! SMILES: smiles_1 ' +
'InChi: inchi_1 \nH ! SMILES: smiles_2 ' +
'InChi: inchi_2 \n\nEND \n\n\n'
)
SPC_NAMES_STRING_2 = 'OH \nHO2 \nC3H8 \nN2O'
SPC_NAMES_TUPLE = ('OH', 'HO2', 'C3H8', 'N2O')
def test__write_spc_names():
spc_str = writer(SPC_IDENT_DCT)
assert spc_str == SPC_NAMES_STRING_1
def test__read_spc_names():
spc_tuple = parser(SPC_NAMES_STRING_2)
assert spc_tuple == SPC_NAMES_TUPLE
| true | true |
f728168bbdf509e74ee76567b7e5122e0bcb5830 | 54 | py | Python | id_roles/__init__.py | W-DEJONG/id-roles | 3a45dc8a72ff434c9c180ddbffee1bd325aaa46c | [
"MIT"
] | null | null | null | id_roles/__init__.py | W-DEJONG/id-roles | 3a45dc8a72ff434c9c180ddbffee1bd325aaa46c | [
"MIT"
] | null | null | null | id_roles/__init__.py | W-DEJONG/id-roles | 3a45dc8a72ff434c9c180ddbffee1bd325aaa46c | [
"MIT"
] | null | null | null | from id_roles.roles import Roles
__all__ = ['Roles']
| 13.5 | 32 | 0.740741 | from id_roles.roles import Roles
__all__ = ['Roles']
| true | true |
f72816c9b2071c96c52217d26c72c08626519960 | 1,635 | py | Python | ch06-sgd/utils.py | GaoX2015/intro_ds | 38e239dcf0fbe4b98ca11534ff419af72417a272 | [
"Apache-2.0"
] | 314 | 2018-02-11T09:44:21.000Z | 2022-03-31T02:55:34.000Z | ch06-sgd/utils.py | jianyigengge/intro_ds | 886e678e5353e9b4c0d4f3da83a00d6b9a2f06a5 | [
"Apache-2.0"
] | 5 | 2018-05-27T07:18:09.000Z | 2019-03-29T14:07:55.000Z | ch06-sgd/utils.py | jianyigengge/intro_ds | 886e678e5353e9b4c0d4f3da83a00d6b9a2f06a5 | [
"Apache-2.0"
] | 262 | 2018-03-20T07:36:22.000Z | 2022-03-08T06:51:58.000Z | # -*- coding: UTF-8 -*-
"""
此脚本用于随机生成线性模型数据、定义模型以及其他工具
"""
import numpy as np
import tensorflow as tf
def generateLinearData(dimension, num):
"""
随机产生线性模型数据
参数
----
dimension :int,自变量个数
num :int,数据个数
返回
----
x :np.array,自变量
y :np.array,因变量
"""
np.random.seed(1024)
beta = np.array(range(dimension)) + 1
x = np.random.random((num, dimension))
epsilon = np.random.random((num, 1))
# 将被预测值写成矩阵形式,会极大加快速度
y = x.dot(beta).reshape((-1, 1)) + epsilon
return x, y
def createLinearModel(dimension):
"""
搭建模型,包括数据中的自变量,应变量和损失函数
参数
----
dimension : int,自变量的个数
返回
----
model :dict,里面包含模型的参数,损失函数,自变量,应变量
"""
np.random.seed(1024)
# 定义自变量和应变量
x = tf.placeholder(tf.float64, shape=[None, dimension], name='x')
## 将被预测值写成矩阵形式,会极大加快速度
y = tf.placeholder(tf.float64, shape=[None, 1], name="y")
# 定义参数估计值和预测值
betaPred = tf.Variable(np.random.random([dimension, 1]))
yPred = tf.matmul(x, betaPred, name="y_pred")
# 定义损失函数
loss = tf.reduce_mean(tf.square(yPred - y))
model = {"loss_function": loss, "independent_variable": x,
"dependent_variable": y, "prediction": yPred, "model_params": betaPred}
return model
def createSummaryWriter(logPath):
"""
检查所给路径是否已存在,如果存在删除原有日志。并创建日志写入对象
参数
----
logPath :string,日志存储路径
返回
----
summaryWriter :FileWriter,日志写入器
"""
if tf.gfile.Exists(logPath):
tf.gfile.DeleteRecursively(logPath)
summaryWriter = tf.summary.FileWriter(logPath, graph=tf.get_default_graph())
return summaryWriter
| 20.696203 | 80 | 0.619572 |
import numpy as np
import tensorflow as tf
def generateLinearData(dimension, num):
np.random.seed(1024)
beta = np.array(range(dimension)) + 1
x = np.random.random((num, dimension))
epsilon = np.random.random((num, 1))
y = x.dot(beta).reshape((-1, 1)) + epsilon
return x, y
def createLinearModel(dimension):
np.random.seed(1024)
x = tf.placeholder(tf.float64, shape=[None, dimension], name='x')
er(tf.float64, shape=[None, 1], name="y")
betaPred = tf.Variable(np.random.random([dimension, 1]))
yPred = tf.matmul(x, betaPred, name="y_pred")
loss = tf.reduce_mean(tf.square(yPred - y))
model = {"loss_function": loss, "independent_variable": x,
"dependent_variable": y, "prediction": yPred, "model_params": betaPred}
return model
def createSummaryWriter(logPath):
if tf.gfile.Exists(logPath):
tf.gfile.DeleteRecursively(logPath)
summaryWriter = tf.summary.FileWriter(logPath, graph=tf.get_default_graph())
return summaryWriter
| true | true |
f72817e33d667fa487e967a902485b50885a9271 | 2,408 | py | Python | mathdecathlon.py | blay800/personal-projects | dea248b3a503a1cc0e620eaa92d347d6e0f645d2 | [
"MIT"
] | null | null | null | mathdecathlon.py | blay800/personal-projects | dea248b3a503a1cc0e620eaa92d347d6e0f645d2 | [
"MIT"
] | null | null | null | mathdecathlon.py | blay800/personal-projects | dea248b3a503a1cc0e620eaa92d347d6e0f645d2 | [
"MIT"
] | null | null | null | name=input('Enter your name to costomize your personal Maths quiz decathlon:')
print(name,"""'s Maths quiz decathlon
Answer as many questions as possible to attain the maximum points""")
print('''USERS MANUAL
OPERATORS:
+ ==- ADDITION
- ==- SUBSTRACTION
x ==- MULTIPLICATION
/ ==- DIVISION''')
respond=input('Are you ready to do some Maths?(Yes or No):')
correct_response=['Yes','yes','Yes ','yes ',' Yes',' yes']
score_sheet=0
if respond in correct_response:
print("Let's get our Maths pants on!")
print('Test begins after countdown')
import time
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
t = 3
countdown(int(t))
emoji=chr(9786)
for i in range(10):
import random
num_1=random.randint(-100,100)
num_2=random.randint(1,10)
import random
list_of_operators=['plus','minus','multiplied by','divided by']
operator=random.choice(list_of_operators)
print('Compute ({}) {} ({})' .format(num_1,operator,num_2))
if operator==list_of_operators[0]:
answer_1=num_1+num_2
user_reply=int(input('Enter your answer here:'))
if operator==list_of_operators[1]:
answer_1=num_1-num_2
user_reply=int(input('Enter your answer here:'))
elif operator==list_of_operators[2]:
answer_1=num_1*num_2
user_reply=int(input('Enter your answer here:'))
elif operator==list_of_operators[3]:
answer_2=num_1/num_2
answer_1=round(answer_2, 2)
user_reply=float(input('Enter your answer here:'))
if answer_1==user_reply:
score_sheet=score_sheet+10
print("Excellent job!.You're a genius")
#for i in range(10):
print('You have {} points!' .format(score_sheet))
else:
print('That is incorrect!')
print('The right answer is',answer_1)
print("You've failed the math quiz decathlon.")
print('Try again later!')
print('Your final score is {} {}' .format(score_sheet,emoji))
break
else:
print("Let's try again some other time")
| 34.4 | 79 | 0.57392 | name=input('Enter your name to costomize your personal Maths quiz decathlon:')
print(name,"""'s Maths quiz decathlon
Answer as many questions as possible to attain the maximum points""")
print('''USERS MANUAL
OPERATORS:
+ ==- ADDITION
- ==- SUBSTRACTION
x ==- MULTIPLICATION
/ ==- DIVISION''')
respond=input('Are you ready to do some Maths?(Yes or No):')
correct_response=['Yes','yes','Yes ','yes ',' Yes',' yes']
score_sheet=0
if respond in correct_response:
print("Let's get our Maths pants on!")
print('Test begins after countdown')
import time
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
t = 3
countdown(int(t))
emoji=chr(9786)
for i in range(10):
import random
num_1=random.randint(-100,100)
num_2=random.randint(1,10)
import random
list_of_operators=['plus','minus','multiplied by','divided by']
operator=random.choice(list_of_operators)
print('Compute ({}) {} ({})' .format(num_1,operator,num_2))
if operator==list_of_operators[0]:
answer_1=num_1+num_2
user_reply=int(input('Enter your answer here:'))
if operator==list_of_operators[1]:
answer_1=num_1-num_2
user_reply=int(input('Enter your answer here:'))
elif operator==list_of_operators[2]:
answer_1=num_1*num_2
user_reply=int(input('Enter your answer here:'))
elif operator==list_of_operators[3]:
answer_2=num_1/num_2
answer_1=round(answer_2, 2)
user_reply=float(input('Enter your answer here:'))
if answer_1==user_reply:
score_sheet=score_sheet+10
print("Excellent job!.You're a genius")
#for i in range(10):
print('You have {} points!' .format(score_sheet))
else:
print('That is incorrect!')
print('The right answer is',answer_1)
print("You've failed the math quiz decathlon.")
print('Try again later!')
print('Your final score is {} {}' .format(score_sheet,emoji))
break
else:
print("Let's try again some other time")
| true | true |
f728184d482c02a5a1840ed94d4ff8a633201db2 | 6,204 | py | Python | federated_learning/FedaGrac/param_server.py | HarliWu/From-Deterioration-to-Acceleration-A-Calibration-Approach-to-Rehabilitating-Step-Asynchronism-in-Fe | 3a2f7196a2ca0446ce7ff7c8d15a0fa56a1d91d4 | [
"MIT"
] | null | null | null | federated_learning/FedaGrac/param_server.py | HarliWu/From-Deterioration-to-Acceleration-A-Calibration-Approach-to-Rehabilitating-Step-Asynchronism-in-Fe | 3a2f7196a2ca0446ce7ff7c8d15a0fa56a1d91d4 | [
"MIT"
] | null | null | null | federated_learning/FedaGrac/param_server.py | HarliWu/From-Deterioration-to-Acceleration-A-Calibration-Approach-to-Rehabilitating-Step-Asynchronism-in-Fe | 3a2f7196a2ca0446ce7ff7c8d15a0fa56a1d91d4 | [
"MIT"
] | null | null | null | import time, os, json, time
import numpy as np
import torch
from torch._C import device
import torch.distributed as dist
from torch.autograd import Variable
def test_model(model, test_data, dev):
correct, total = 0, 0
model.eval()
with torch.no_grad():
for data, target in test_data:
data, target = Variable(data).cuda(dev), Variable(target).cuda(dev)
output = model(data)
# get the index of the max log-probability
_, predictions = output.max(1)
total += predictions.size(0)
correct += torch.sum(predictions == target.data).float()
acc = correct / total
return acc.item()
def update_model(model, global_mu, size, cpu, gpu, args):
# all_param = model.state_dict()
# receive the parameter variance from workers
for param in model.parameters():
tensor = torch.zeros_like(param.data, device=cpu)
gather_list = [torch.zeros_like(param.data, device=cpu) for _ in range(size)]
dist.gather(tensor=tensor, gather_list=gather_list, dst=0)
param.data = torch.zeros_like(param.data, device=gpu)
for w in range(size):
# Suppose the model received from clients are well processed
param.data = param.data + gather_list[w].clone().detach().to(gpu)
# receive averaged K from workers
avg_k_list = [torch.tensor(0.0) for _ in range(size)]
dist.gather(tensor=torch.tensor(0.0), gather_list=avg_k_list, dst=0)
avg_k = sum(avg_k_list)
print('Averaged K:', avg_k)
# send averaged K to workers
avg_k_list = [avg_k if args.avg_k==-1 else torch.tensor(float(args.avg_k)) for _ in range(size)]
dist.scatter(tensor=avg_k, scatter_list=avg_k_list)
# receive the mu from clients
for idx, param in enumerate(global_mu):
tensor = torch.zeros_like(param.data, device=cpu)
gather_list = [torch.zeros_like(param.data, device=cpu) for _ in range(size)]
dist.gather(tensor=tensor, gather_list=gather_list, dst=0)
global_mu[idx] = torch.zeros_like(param.data, device=gpu)
for w in range(size):
# Suppose the model received from clients are well processed
global_mu[idx] = global_mu[idx] + gather_list[w].clone().detach().to(gpu)
# send the parameters to workers
for param in model.parameters():
tmp_p = param.clone().detach().to(cpu)
scatter_p_list = [tmp_p for _ in range(size)]
dist.scatter(tensor=tmp_p, scatter_list=scatter_p_list)
if torch.sum(torch.isnan(tmp_p)) > 0:
print("NaN occurs. Terminate. ")
exit(-1)
# send global_mu to workers
for param in global_mu:
tmp_p = param.clone().detach().to(cpu)
scatter_p_list = [tmp_p for _ in range(size)]
dist.scatter(tensor=tmp_p, scatter_list=scatter_p_list)
# model.load_state_dict(all_param)
def run(size, model, args, test_data, f_result, cpu, gpu):
# Receive the weights from all clients
temp_w = torch.tensor([0.0 for _ in range(args.num_workers+1)])
weights = [torch.tensor([0.0 for _ in range(args.num_workers+1)]) for _ in range(size)]
dist.gather(tensor=temp_w, gather_list=weights, dst=0)
weights = sum(weights)
weights = weights / torch.sum(weights)
print('weights:', weights)
# send weights to clients
weights_list = [weights.clone().detach().to(cpu) for _ in range(size)]
dist.scatter(tensor=temp_w, scatter_list=weights_list)
start = time.time()
model = model.cuda(gpu)
for p in model.parameters():
tmp_p = p.clone().detach().to(cpu)
scatter_p_list = [tmp_p for _ in range(size)]
# dist.scatter(tensor=tmp_p, scatter_list=scatter_p_list, group=group)
dist.scatter(tensor=tmp_p, scatter_list=scatter_p_list)
global_mu = [torch.zeros_like(param.data, device=gpu) for param in model.parameters()]
print('Model has sent to all nodes! ')
print('Begin!')
np.random.seed(42)
for t in range(args.T):
model.train()
# send participants to all clients
participants = np.random.choice(np.arange(len(weights)), size=args.num_part, replace=True, p=weights.numpy()) if args.partial else np.arange(len(weights))
print('Participants list:', list(participants))
participants = torch.tensor(participants).to(cpu)
part_list = [participants for _ in range(size)]
dist.scatter(tensor=participants, scatter_list=part_list)
# receive the list of train loss from workers
info_list = [torch.tensor(0.0) for _ in range(size)]
# dist.gather(tensor=torch.tensor([0.0]), gather_list=info_list, group=group)
dist.gather(tensor=torch.tensor(0.0), gather_list=info_list, dst=0)
# info_list = np.concatenate([list(a) for a in info_list])
# train_loss = sum(info_list).item() / args.num_part if args.partial else sum(info_list * weights).item()
train_loss = sum(info_list).item()
# if args.partial:
# update_model_partial(model, size, cpu, gpu, args.num_part)
# else:
# update_model_full(model, size, cpu, gpu, weights)
update_model(model, global_mu, size, cpu, gpu, args)
timestamp = time.time() - start
test_acc = test_model(model, test_data, gpu)
print("Epoch: {}\t\tLoss: {}\t\tAccuracy: {}".format(t, train_loss, test_acc))
f_result.write(str(t) + "\t" + str(timestamp) + "\t" + str(train_loss) + "\t" + str(test_acc) + "\n")
f_result.flush()
def init_processes(rank, size, model, args, test_data, cpu, gpu, backend='mpi'):
if backend == 'mpi':
dist.init_process_group(backend)
elif backend == 'gloo':
os.environ['MASTER_ADDR'] = '127.0.0.1'
os.environ['MASTER_PORT'] = '29500'
dist.init_process_group(backend, rank=rank, world_size=size)
if not os.path.exists(args.result):
os.makedirs(args.result)
result_file = os.path.join(args.result, '{}.txt'.format(len(os.listdir(args.result))))
f_result = open(result_file, 'w')
f_result.write(json.dumps(vars(args)) + '\n')
run(size, model, args, test_data, f_result, cpu, gpu) | 43.083333 | 162 | 0.653127 | import time, os, json, time
import numpy as np
import torch
from torch._C import device
import torch.distributed as dist
from torch.autograd import Variable
def test_model(model, test_data, dev):
correct, total = 0, 0
model.eval()
with torch.no_grad():
for data, target in test_data:
data, target = Variable(data).cuda(dev), Variable(target).cuda(dev)
output = model(data)
_, predictions = output.max(1)
total += predictions.size(0)
correct += torch.sum(predictions == target.data).float()
acc = correct / total
return acc.item()
def update_model(model, global_mu, size, cpu, gpu, args):
for param in model.parameters():
tensor = torch.zeros_like(param.data, device=cpu)
gather_list = [torch.zeros_like(param.data, device=cpu) for _ in range(size)]
dist.gather(tensor=tensor, gather_list=gather_list, dst=0)
param.data = torch.zeros_like(param.data, device=gpu)
for w in range(size):
param.data = param.data + gather_list[w].clone().detach().to(gpu)
avg_k_list = [torch.tensor(0.0) for _ in range(size)]
dist.gather(tensor=torch.tensor(0.0), gather_list=avg_k_list, dst=0)
avg_k = sum(avg_k_list)
print('Averaged K:', avg_k)
avg_k_list = [avg_k if args.avg_k==-1 else torch.tensor(float(args.avg_k)) for _ in range(size)]
dist.scatter(tensor=avg_k, scatter_list=avg_k_list)
for idx, param in enumerate(global_mu):
tensor = torch.zeros_like(param.data, device=cpu)
gather_list = [torch.zeros_like(param.data, device=cpu) for _ in range(size)]
dist.gather(tensor=tensor, gather_list=gather_list, dst=0)
global_mu[idx] = torch.zeros_like(param.data, device=gpu)
for w in range(size):
global_mu[idx] = global_mu[idx] + gather_list[w].clone().detach().to(gpu)
for param in model.parameters():
tmp_p = param.clone().detach().to(cpu)
scatter_p_list = [tmp_p for _ in range(size)]
dist.scatter(tensor=tmp_p, scatter_list=scatter_p_list)
if torch.sum(torch.isnan(tmp_p)) > 0:
print("NaN occurs. Terminate. ")
exit(-1)
for param in global_mu:
tmp_p = param.clone().detach().to(cpu)
scatter_p_list = [tmp_p for _ in range(size)]
dist.scatter(tensor=tmp_p, scatter_list=scatter_p_list)
def run(size, model, args, test_data, f_result, cpu, gpu):
temp_w = torch.tensor([0.0 for _ in range(args.num_workers+1)])
weights = [torch.tensor([0.0 for _ in range(args.num_workers+1)]) for _ in range(size)]
dist.gather(tensor=temp_w, gather_list=weights, dst=0)
weights = sum(weights)
weights = weights / torch.sum(weights)
print('weights:', weights)
weights_list = [weights.clone().detach().to(cpu) for _ in range(size)]
dist.scatter(tensor=temp_w, scatter_list=weights_list)
start = time.time()
model = model.cuda(gpu)
for p in model.parameters():
tmp_p = p.clone().detach().to(cpu)
scatter_p_list = [tmp_p for _ in range(size)]
dist.scatter(tensor=tmp_p, scatter_list=scatter_p_list)
global_mu = [torch.zeros_like(param.data, device=gpu) for param in model.parameters()]
print('Model has sent to all nodes! ')
print('Begin!')
np.random.seed(42)
for t in range(args.T):
model.train()
participants = np.random.choice(np.arange(len(weights)), size=args.num_part, replace=True, p=weights.numpy()) if args.partial else np.arange(len(weights))
print('Participants list:', list(participants))
participants = torch.tensor(participants).to(cpu)
part_list = [participants for _ in range(size)]
dist.scatter(tensor=participants, scatter_list=part_list)
info_list = [torch.tensor(0.0) for _ in range(size)]
dist.gather(tensor=torch.tensor(0.0), gather_list=info_list, dst=0)
train_loss = sum(info_list).item()
update_model(model, global_mu, size, cpu, gpu, args)
timestamp = time.time() - start
test_acc = test_model(model, test_data, gpu)
print("Epoch: {}\t\tLoss: {}\t\tAccuracy: {}".format(t, train_loss, test_acc))
f_result.write(str(t) + "\t" + str(timestamp) + "\t" + str(train_loss) + "\t" + str(test_acc) + "\n")
f_result.flush()
def init_processes(rank, size, model, args, test_data, cpu, gpu, backend='mpi'):
if backend == 'mpi':
dist.init_process_group(backend)
elif backend == 'gloo':
os.environ['MASTER_ADDR'] = '127.0.0.1'
os.environ['MASTER_PORT'] = '29500'
dist.init_process_group(backend, rank=rank, world_size=size)
if not os.path.exists(args.result):
os.makedirs(args.result)
result_file = os.path.join(args.result, '{}.txt'.format(len(os.listdir(args.result))))
f_result = open(result_file, 'w')
f_result.write(json.dumps(vars(args)) + '\n')
run(size, model, args, test_data, f_result, cpu, gpu) | true | true |
f72818f01aa173045e65dadc934e5291bffadedc | 898 | py | Python | doc/print_errors.py | stefsmeets/pyvista | 06b1ac01214a4c636395f139b681acea2543960c | [
"MIT"
] | 1,107 | 2019-05-13T06:40:26.000Z | 2022-03-31T22:16:32.000Z | doc/print_errors.py | stefsmeets/pyvista | 06b1ac01214a4c636395f139b681acea2543960c | [
"MIT"
] | 1,709 | 2019-05-13T05:52:42.000Z | 2022-03-31T18:16:53.000Z | doc/print_errors.py | stefsmeets/pyvista | 06b1ac01214a4c636395f139b681acea2543960c | [
"MIT"
] | 225 | 2019-05-16T04:24:20.000Z | 2022-03-31T18:14:02.000Z | """Read errors output from a sphinx build and remove duplicate groups"""
import os
import pathlib
import sys
sys.tracebacklimit = 0
my_path = pathlib.Path(__file__).parent.resolve()
errors = set()
error_file = os.path.join(my_path, 'build_errors.txt')
if os.path.isfile(error_file):
with open(error_file) as fid:
group = []
for line in fid.readlines():
line = line.strip()
if line:
group.append(line)
else:
errors.add('\n'.join(group))
group = []
for error in list(errors):
print(error)
print()
# There should be no errors here since sphinx will have exited
print()
if errors:
raise Exception(f'Sphinx reported unique {len(errors)} warnings\n\n')
else:
print(f'build_errors.txt not found at {my_path}')
print(f'Sphinx Reported no warnings\n\n')
| 26.411765 | 77 | 0.61804 | import os
import pathlib
import sys
sys.tracebacklimit = 0
my_path = pathlib.Path(__file__).parent.resolve()
errors = set()
error_file = os.path.join(my_path, 'build_errors.txt')
if os.path.isfile(error_file):
with open(error_file) as fid:
group = []
for line in fid.readlines():
line = line.strip()
if line:
group.append(line)
else:
errors.add('\n'.join(group))
group = []
for error in list(errors):
print(error)
print()
print()
if errors:
raise Exception(f'Sphinx reported unique {len(errors)} warnings\n\n')
else:
print(f'build_errors.txt not found at {my_path}')
print(f'Sphinx Reported no warnings\n\n')
| true | true |
f728191ba7a438605552750ad6806ecd257df742 | 64,373 | py | Python | fpga_interchange/populate_chip_info.py | litghost/python-fpga-interchange | 3809a19f2f9cf80f014e439f9ae8643543c4519f | [
"0BSD"
] | null | null | null | fpga_interchange/populate_chip_info.py | litghost/python-fpga-interchange | 3809a19f2f9cf80f014e439f9ae8643543c4519f | [
"0BSD"
] | null | null | null | fpga_interchange/populate_chip_info.py | litghost/python-fpga-interchange | 3809a19f2f9cf80f014e439f9ae8643543c4519f | [
"0BSD"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 The SymbiFlow Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
from enum import Enum
from collections import namedtuple
from fpga_interchange.chip_info import ChipInfo, BelInfo, TileTypeInfo, \
TileWireInfo, BelPort, PipInfo, TileInstInfo, SiteInstInfo, NodeInfo, \
TileWireRef, CellBelMap, ParameterPins, CellBelPin, ConstraintTag, \
CellConstraint, ConstraintType, Package, PackagePin
from fpga_interchange.constraints.model import Tag, Placement, \
ImpliesConstraint, RequiresConstraint
from fpga_interchange.constraint_generator import ConstraintPrototype
from fpga_interchange.nextpnr import PortType
class FlattenedWireType(Enum):
TILE_WIRE = 0
SITE_WIRE = 1
class FlattenedPipType(Enum):
TILE_PIP = 0
SITE_PIP = 1
SITE_PIN = 2
class BelCategory(Enum):
LOGIC = 0
ROUTING = 1
SITE_PORT = 2
def direction_to_type(direction):
if direction == 'input':
return PortType.PORT_IN
elif direction == 'output':
return PortType.PORT_OUT
else:
assert direction == 'inout'
return PortType.PORT_INOUT
BelPin = namedtuple('BelPin', 'port type wire')
class FlattenedBel():
def __init__(self, name, type, site_index, bel_index, bel_category):
self.name = name
self.type = type
self.site_index = site_index
self.bel_index = bel_index
self.bel_category = bel_category
self.ports = []
self.valid_cells = set()
def add_port(self, device, bel_pin, wire_index):
self.ports.append(
BelPin(
port=device.strs[bel_pin.name],
type=direction_to_type(bel_pin.dir),
wire=wire_index))
# Object that represents a flattened wire.
class FlattenedWire():
def __init__(self, type, name, wire_index, site_index):
self.type = type
self.name = name
self.wire_index = wire_index
self.site_index = site_index
self.bel_pins = []
self.pips_uphill = []
self.pips_downhill = []
class FlattenedPip(
namedtuple('FlattenedPip',
'type src_index dst_index site_index pip_index')):
pass
class FlattenedSite(
namedtuple(
'FlattenedSite',
'site_in_type_index site_type_index site_type site_type_name site_variant bel_to_bel_index bel_pin_to_site_wire_index bel_pin_index_to_bel_index'
)):
pass
def emit_constraints(tile_type, tile_constraints, cell_bel_mapper):
flat_tag_indicies = {}
flat_tag_state_indicies = {}
for idx, (tag_prefix, tag_data) in enumerate(
sorted(tile_constraints.tags.items())):
flat_tag_indicies[tag_prefix] = idx
flat_tag_state_indicies[tag_prefix] = {}
tag = ConstraintTag()
tag.tag_prefix = tag_prefix
tag.default_state = tag_data.default
tag.states = sorted(tag_data.states)
for idx, state in enumerate(tag.states):
flat_tag_state_indicies[tag_prefix][state] = idx
tile_type.tags.append(tag)
for (cell_type, site_index, site_type,
bel), constraints in tile_constraints.bel_cell_constraints.items():
idx = cell_bel_mapper.get_cell_bel_map_index(
cell_type, tile_type.name, site_index, site_type, bel)
outs = []
for tag_prefix, constraint in constraints:
out = CellConstraint()
out.tag = flat_tag_indicies[tag_prefix]
if isinstance(constraint, ImpliesConstraint):
out.constraint_type = ConstraintType.TAG_IMPLIES
out.states.append(
flat_tag_state_indicies[tag_prefix][constraint.state])
elif isinstance(constraint, RequiresConstraint):
out.constraint_type = ConstraintType.TAG_REQUIRES
for state in constraint.states:
out.states.append(
flat_tag_state_indicies[tag_prefix][state])
else:
assert False, type(constraint)
outs.append(out)
cell_bel_mapper.cell_to_bel_constraints[idx] = outs
class FlattenedTileType():
def __init__(self, device, tile_type_index, tile_type, cell_bel_mapper,
constraints):
self.tile_type_name = device.strs[tile_type.name]
self.tile_type = tile_type
self.tile_constraints = ConstraintPrototype()
self.sites = []
self.bels = []
self.bel_index_remap = {}
self.wires = []
self.pips = []
# Add tile wires
self.tile_wire_to_wire_in_tile_index = {}
for wire_in_tile_index, wire in enumerate(tile_type.wires):
name = device.strs[wire]
self.tile_wire_to_wire_in_tile_index[name] = wire_in_tile_index
flat_wire = FlattenedWire(
type=FlattenedWireType.TILE_WIRE,
name=name,
wire_index=wire_in_tile_index,
site_index=None)
self.add_wire(flat_wire)
# Add pips
for idx, pip in enumerate(tile_type.pips):
# TODO: Handle pseudoCells
self.add_tile_pip(idx, pip.wire0, pip.wire1)
if not pip.directional:
self.add_tile_pip(idx, pip.wire1, pip.wire0)
# Add all site variants
for site_in_type_index, site_type_in_tile_type in enumerate(
tile_type.siteTypes):
site_type_index = site_type_in_tile_type.primaryType
site_variant = -1
primary_site_type = device.device_resource_capnp.siteTypeList[
site_type_index]
self.add_site_type(device, site_type_in_tile_type,
site_in_type_index, site_type_index,
site_variant, cell_bel_mapper)
for site_variant, (alt_site_type_index, _) in enumerate(
zip(primary_site_type.altSiteTypes,
site_type_in_tile_type.altPinsToPrimaryPins)):
self.add_site_type(device, site_type_in_tile_type,
site_in_type_index, alt_site_type_index,
site_variant, cell_bel_mapper,
primary_site_type)
self.remap_bel_indicies()
self.generate_constraints(constraints)
def generate_constraints(self, constraints):
tags_for_tile_type = {}
available_placements = []
sites_in_tile_type = {}
for site_index, site in enumerate(self.sites):
if site.site_in_type_index not in sites_in_tile_type:
sites_in_tile_type[site.site_in_type_index] = []
sites_in_tile_type[site.site_in_type_index].append(site_index)
# Create tag to ensure that each site in the tile only has 1 type.
for site, possible_sites in sites_in_tile_type.items():
site_types = []
for site_index in possible_sites:
site_types.append(self.sites[site_index].site_type_name)
# Make sure there are no duplicate site types!
assert len(site_types) == len(set(site_types))
tag_prefix = 'type_of_site{:03d}'.format(site)
assert tag_prefix not in tags_for_tile_type
tags_for_tile_type[tag_prefix] = Tag(
name='TypeOfSite{}'.format(site),
states=site_types,
default=site_types[0],
matchers=[])
self.tile_constraints.add_tag(tag_prefix,
tags_for_tile_type[tag_prefix])
for bel in self.bels:
site = self.sites[bel.site_index]
placement = Placement(
tile=self.tile_type_name,
site='site{}_{}'.format(site.site_in_type_index,
site.site_type_name),
tile_type=self.tile_type_name,
site_type=site.site_type_name,
bel=bel.name)
available_placements.append(placement)
for tag_prefix, tag in constraints.yield_tags_at_placement(
placement):
if tag_prefix in tags_for_tile_type:
assert tags_for_tile_type[tag_prefix] is tag
continue
else:
tags_for_tile_type[tag_prefix] = tag
self.tile_constraints.add_tag(
tag_prefix, tags_for_tile_type[tag_prefix])
for cell_type in bel.valid_cells:
# When any valid cell type is placed here, make sure that
# the corrisponding TypeOfSite tag is implied.
self.tile_constraints.add_cell_placement_constraint(
cell_type=cell_type,
site_index=bel.site_index,
site_type=site.site_type_name,
bel=bel.name,
tag='type_of_site{:03d}'.format(
self.sites[bel.site_index].site_in_type_index),
constraint=ImpliesConstraint(
tag=None,
state=site.site_type_name,
matchers=None,
port=None))
for tag, constraint in constraints.yield_constraints_for_cell_type_at_placement(
cell_type, placement):
self.tile_constraints.add_cell_placement_constraint(
cell_type=cell_type,
site_index=bel.site_index,
site_type=site.site_type_name,
bel=bel.name,
tag=tag,
constraint=constraint)
def add_wire(self, wire):
wire_index = len(self.wires)
self.wires.append(wire)
return wire_index
def add_pip_common(self, flat_pip):
pip_index = len(self.pips)
self.pips.append(flat_pip)
self.wires[flat_pip.src_index].pips_downhill.append(pip_index)
self.wires[flat_pip.dst_index].pips_uphill.append(pip_index)
def add_tile_pip(self, tile_pip_index, src_wire, dst_wire):
assert self.wires[src_wire].type == FlattenedWireType.TILE_WIRE
assert self.wires[dst_wire].type == FlattenedWireType.TILE_WIRE
flat_pip = FlattenedPip(
type=FlattenedPipType.TILE_PIP,
src_index=src_wire,
dst_index=dst_wire,
site_index=None,
pip_index=tile_pip_index)
self.add_pip_common(flat_pip)
def add_site_type(self,
device,
site_type_in_tile_type,
site_in_type_index,
site_type_index,
site_variant,
cell_bel_mapper,
primary_site_type=None):
if site_variant == -1:
assert primary_site_type is None
else:
assert primary_site_type is not None
site_index = len(self.sites)
bel_to_bel_index = {}
bel_pin_to_site_wire_index = {}
bel_pin_index_to_bel_index = {}
site_type = device.device_resource_capnp.siteTypeList[site_type_index]
site_type_name = device.strs[site_type.name]
self.sites.append(
FlattenedSite(
site_in_type_index=site_in_type_index,
site_type_index=site_type_index,
site_type=site_type,
site_type_name=site_type_name,
site_variant=site_variant,
bel_to_bel_index=bel_to_bel_index,
bel_pin_to_site_wire_index=bel_pin_to_site_wire_index,
bel_pin_index_to_bel_index=bel_pin_index_to_bel_index))
# Add site wires
for idx, site_wire in enumerate(site_type.siteWires):
wire_name = device.strs[site_wire.name]
flat_wire = FlattenedWire(
type=FlattenedWireType.SITE_WIRE,
name=wire_name,
wire_index=idx,
site_index=site_index)
site_wire_index = self.add_wire(flat_wire)
for pin in site_wire.pins:
assert pin not in bel_pin_to_site_wire_index
bel_pin_to_site_wire_index[pin] = site_wire_index
# Add BELs
for bel_idx, bel in enumerate(site_type.bels):
if bel.category == 'logic':
bel_category = BelCategory.LOGIC
elif bel.category == 'routing':
bel_category = BelCategory.ROUTING
else:
assert bel.category == 'sitePort', bel.category
bel_category = BelCategory.SITE_PORT
flat_bel = FlattenedBel(
name=device.strs[bel.name],
type=device.strs[bel.type],
site_index=site_index,
bel_index=bel_idx,
bel_category=bel_category)
bel_index = len(self.bels)
bel_to_bel_index[bel_idx] = bel_index
self.bels.append(flat_bel)
bel_key = site_type_name, flat_bel.name
for cell in cell_bel_mapper.get_cells():
if bel_key in cell_bel_mapper.bels_for_cell(cell):
flat_bel.valid_cells.add(cell)
for pin_idx, pin in enumerate(bel.pins):
assert pin not in bel_pin_index_to_bel_index
bel_pin_index_to_bel_index[pin] = bel_idx, pin_idx
bel_pin = site_type.belPins[pin]
wire_idx = bel_pin_to_site_wire_index.get(pin, -1)
flat_bel.add_port(device, bel_pin, wire_idx)
if wire_idx != -1:
self.wires[wire_idx].bel_pins.append(
(bel_index, device.strs[bel_pin.name]))
# Add site pips
for idx, site_pip in enumerate(site_type.sitePIPs):
src_bel_pin = site_pip.inpin
bel_idx, src_pin_idx = bel_pin_index_to_bel_index[src_bel_pin]
src_site_wire_idx = bel_pin_to_site_wire_index[src_bel_pin]
dst_bel_pin = site_pip.outpin
dst_site_wire_idx = bel_pin_to_site_wire_index[dst_bel_pin]
self.add_site_pip(src_site_wire_idx, dst_site_wire_idx, site_index,
idx)
# Add site pins
for idx, site_pin in enumerate(site_type.pins):
# This site pin isn't connected in this site type, skip creating
# the edge.
if site_pin.belpin not in bel_pin_to_site_wire_index:
continue
site_wire = bel_pin_to_site_wire_index[site_pin.belpin]
if site_variant != -1:
# This is an alternative site, map to primary pin first
parent_pins = site_type_in_tile_type.altPinsToPrimaryPins[
site_variant]
primary_idx = parent_pins.pins[idx]
else:
# This is the primary site, directly lookup site tile wire.
primary_idx = idx
tile_wire_name = device.strs[site_type_in_tile_type.
primaryPinsToTileWires[primary_idx]]
tile_wire = self.tile_wire_to_wire_in_tile_index[tile_wire_name]
if site_pin.dir == 'input':
# Input site pins connect tile wires to site wires
src_wire = tile_wire
dst_wire = site_wire
else:
assert site_pin.dir == 'output'
# Output site pins connect site wires to tile wires
src_wire = site_wire
dst_wire = tile_wire
self.add_site_pin(src_wire, dst_wire, site_index, idx)
def add_site_pip(self, src_wire, dst_wire, site_index, site_pip_index):
assert self.wires[src_wire].type == FlattenedWireType.SITE_WIRE
assert self.wires[dst_wire].type == FlattenedWireType.SITE_WIRE
flat_pip = FlattenedPip(
type=FlattenedPipType.SITE_PIP,
src_index=src_wire,
dst_index=dst_wire,
site_index=site_index,
pip_index=site_pip_index)
self.add_pip_common(flat_pip)
def add_site_pin(self, src_wire, dst_wire, site_index, site_pin_index):
if self.wires[src_wire].type == FlattenedWireType.SITE_WIRE:
assert self.wires[dst_wire].type == FlattenedWireType.TILE_WIRE
else:
assert self.wires[src_wire].type == FlattenedWireType.TILE_WIRE
assert self.wires[dst_wire].type == FlattenedWireType.SITE_WIRE
flat_pip = FlattenedPip(
type=FlattenedPipType.SITE_PIN,
src_index=src_wire,
dst_index=dst_wire,
site_index=site_index,
pip_index=site_pin_index)
self.add_pip_common(flat_pip)
def remap_bel_indicies(self):
# Put logic BELs first before routing and site ports.
self.bel_index_remap = {}
self.bel_output_map = {}
for output_bel_idx, (bel_idx, _) in enumerate(
sorted(
enumerate(self.bels),
key=lambda value: (value[1].bel_category.value, value[0]))
):
self.bel_index_remap[bel_idx] = output_bel_idx
self.bel_output_map[output_bel_idx] = bel_idx
def create_tile_type_info(self, cell_bel_mapper):
tile_type = TileTypeInfo()
tile_type.name = self.tile_type_name
bels_used = set()
for bel_index in range(len(self.bels)):
mapped_idx = self.bel_output_map[bel_index]
assert mapped_idx not in bels_used
bels_used.add(mapped_idx)
bel = self.bels[mapped_idx]
bel_info = BelInfo()
bel_info.name = bel.name
bel_info.type = bel.type
for port in bel.ports:
bel_info.ports.append(port.port)
bel_info.types.append(port.type.value)
bel_info.wires.append(port.wire)
bel_info.site = bel.site_index
bel_info.site_variant = self.sites[bel.site_index].site_variant
bel_info.bel_category = bel.bel_category.value
site_type = self.sites[bel.site_index].site_type_name
bel_key = (site_type, bel.name)
bel_info.bel_bucket = cell_bel_mapper.bel_to_bel_bucket(*bel_key)
if bel.bel_category == BelCategory.LOGIC:
# Don't need pin_map for routing / site ports.
bel_info.pin_map = [-1 for _ in cell_bel_mapper.get_cells()]
for idx, cell in enumerate(cell_bel_mapper.get_cells()):
bel_info.pin_map[
idx] = cell_bel_mapper.get_cell_bel_map_index(
cell, tile_type.name, bel.site_index, site_type,
bel.name)
tile_type.bel_data.append(bel_info)
assert len(bels_used) == len(self.bel_output_map)
assert len(bels_used) == len(self.bel_index_remap)
for wire in self.wires:
wire_info = TileWireInfo()
wire_info.name = wire.name
wire_info.pips_uphill = wire.pips_uphill
wire_info.pips_downhill = wire.pips_downhill
for (bel_index, port) in wire.bel_pins:
bel_port = BelPort()
bel_port.bel_index = self.bel_index_remap[bel_index]
bel_port.port = port
wire_info.bel_pins.append(bel_port)
if wire.site_index is not None:
wire_info.site = wire.site_index
wire_info.site_variant = self.sites[wire.
site_index].site_variant
else:
wire_info.site = -1
wire_info.site_variant = -1
tile_type.wire_data.append(wire_info)
for pip in self.pips:
pip_info = PipInfo()
pip_info.src_index = pip.src_index
pip_info.dst_index = pip.dst_index
if pip.site_index is not None:
site = self.sites[pip.site_index]
site_type = site.site_type
pip_info.site = pip.site_index
pip_info.site_variant = site.site_variant
if pip.type == FlattenedPipType.SITE_PIP:
site_pip = site_type.sitePIPs[pip.pip_index]
bel_idx, pin_idx = site.bel_pin_index_to_bel_index[
site_pip.inpin]
orig_bel_index = site.bel_to_bel_index[bel_idx]
expected_category = self.bels[orig_bel_index].bel_category
assert expected_category in [
BelCategory.ROUTING, BelCategory.LOGIC
]
pip_info.bel = self.bel_index_remap[orig_bel_index]
assert tile_type.bel_data[
pip_info.bel].bel_category == expected_category.value
pip_info.extra_data = pin_idx
else:
assert pip.type == FlattenedPipType.SITE_PIN
site_pin = site_type.pins[pip.pip_index]
bel_idx, pin_idx = site.bel_pin_index_to_bel_index[
site_pin.belpin]
pip_info.bel = self.bel_index_remap[
site.bel_to_bel_index[bel_idx]]
pip_info.extra_data = pin_idx
assert tile_type.bel_data[
pip_info.
bel].bel_category == BelCategory.SITE_PORT.value
else:
assert pip.type == FlattenedPipType.TILE_PIP
pip_info.site = -1
pip_info.site_variant = -1
tile_type.pip_data.append(pip_info)
emit_constraints(tile_type, self.tile_constraints, cell_bel_mapper)
for site in self.sites:
tile_type.site_types.append(site.site_type_name)
return tile_type
class CellBelMapper():
def __init__(self, device, constids):
# Emit cell names so that they are compact list.
self.cells_in_order = []
self.cell_names = {}
self.bel_buckets = set()
self.cell_to_bel_buckets = {}
self.cell_to_bel_common_pins = {}
self.cell_to_bel_parameter_pins = {}
self.cell_site_bel_index = {}
self.cell_to_bel_constraints = {}
self.bel_to_bel_buckets = {}
for cell_bel_map in device.device_resource_capnp.cellBelMap:
cell_name = device.strs[cell_bel_map.cell]
self.cells_in_order.append(cell_name)
self.cell_names[cell_name] = constids.get_index(cell_name)
self.min_cell_index = min(self.cell_names.values())
self.max_cell_index = max(self.cell_names.values())
# Make sure cell names are a compact range.
assert (self.max_cell_index - self.min_cell_index + 1) == len(
self.cell_names)
# Remap cell_names as offset from min_cell_index.
for cell_name in self.cell_names.keys():
cell_index = self.cell_names[cell_name] - self.min_cell_index
self.cell_names[cell_name] = cell_index
assert self.cells_in_order[cell_index] == cell_name
self.cell_to_bel_map = {}
for cell_bel_map in device.device_resource_capnp.cellBelMap:
cell_type = device.strs[cell_bel_map.cell]
assert cell_type in self.cell_names
bels = set()
for common_pin in cell_bel_map.commonPins:
pins = []
for pin in common_pin.pins:
pins.append((device.strs[pin.cellPin],
device.strs[pin.belPin]))
for site_types_and_bels in common_pin.siteTypes:
site_type = device.strs[site_types_and_bels.siteType]
for bel_str_id in site_types_and_bels.bels:
bel = device.strs[bel_str_id]
bels.add((site_type, bel))
key = (cell_type, site_type, bel)
assert key not in self.cell_to_bel_common_pins
self.cell_to_bel_common_pins[key] = pins
for parameter_pin in cell_bel_map.parameterPins:
pins = []
for pin in parameter_pin.pins:
pins.append((device.strs[pin.cellPin],
device.strs[pin.belPin]))
for parameter in parameter_pin.parametersSiteTypes:
param_key = device.strs[parameter.parameter.key]
which = parameter.parameter.which()
assert which == 'textValue'
param_value = device.strs[parameter.parameter.textValue]
bel = device.strs[parameter.bel]
site_type = device.strs[parameter.siteType]
bels.add((site_type, bel))
key = cell_type, site_type, bel
if key not in self.cell_to_bel_parameter_pins:
self.cell_to_bel_parameter_pins[key] = {}
assert (param_key, param_value
) not in self.cell_to_bel_parameter_pins[key]
self.cell_to_bel_parameter_pins[key][(param_key,
param_value)] = pins
self.cell_to_bel_map[cell_type] = bels
self.bels = set()
for site_type in device.device_resource_capnp.siteTypeList:
for bel in site_type.bels:
self.bels.add((device.strs[site_type.name],
device.strs[bel.name]))
def get_cell_bel_map_index(self, cell_type, tile_type, site_index,
site_type, bel):
if cell_type not in self.cell_to_bel_map:
return -1
if (site_type, bel) not in self.cell_to_bel_map[cell_type]:
return -1
key = cell_type, tile_type, site_index, site_type, bel
if key not in self.cell_site_bel_index:
index = len(self.cell_site_bel_index)
self.cell_site_bel_index[key] = index
return self.cell_site_bel_index[key]
def make_bel_bucket(self, bel_bucket_name, cell_names):
assert bel_bucket_name not in self.bel_buckets
bels_in_bucket = set()
cells_in_bucket = set(cell_names)
while True:
pre_loop_counts = (len(bels_in_bucket), len(cells_in_bucket))
for cell_name in cells_in_bucket:
bels_in_bucket |= self.cell_to_bel_map[cell_name]
for bel in bels_in_bucket:
for cell, bels in self.cell_to_bel_map.items():
if bel in bels:
cells_in_bucket.add(cell)
post_loop_counts = (len(bels_in_bucket), len(cells_in_bucket))
if pre_loop_counts == post_loop_counts:
break
assert bel_bucket_name not in self.bel_buckets
self.bel_buckets.add(bel_bucket_name)
for cell in cells_in_bucket:
assert cell not in self.cell_to_bel_buckets, (bel_bucket_name,
cell)
self.cell_to_bel_buckets[cell] = bel_bucket_name
for bel in bels_in_bucket:
self.bel_to_bel_buckets[bel] = bel_bucket_name
def handle_remaining(self):
remaining_cells = set(self.cell_names.keys()) - set(
self.cell_to_bel_buckets.keys())
for cell in sorted(remaining_cells):
self.make_bel_bucket(cell, [cell])
remaining_bels = set(self.bels)
for bels in self.cell_to_bel_map.values():
remaining_bels -= bels
bel_bucket_name = 'UNPLACABLE_BELS'
assert bel_bucket_name not in self.bel_buckets
self.bel_buckets.add(bel_bucket_name)
for site_type, bel in remaining_bels:
self.bel_to_bel_buckets[site_type, bel] = bel_bucket_name
bel_bucket_name = 'IOPORTS'
assert bel_bucket_name not in self.bel_buckets
self.bel_buckets.add(bel_bucket_name)
def get_cells(self):
return self.cells_in_order
def get_cell_constids(self):
return range(self.min_cell_index, self.max_cell_index + 1)
def get_cell_index(self, cell_name):
return self.cell_names[cell_name]
def get_bel_buckets(self):
return self.bel_buckets
def cell_to_bel_bucket(self, cell_name):
return self.cell_to_bel_buckets[cell_name]
def get_bels(self):
return self.bel_to_bel_buckets.keys()
def bel_to_bel_bucket(self, site_type, bel):
return self.bel_to_bel_buckets[(site_type, bel)]
def bels_for_cell(self, cell):
return self.cell_to_bel_map[cell]
DEBUG_BEL_BUCKETS = False
def print_bel_buckets(cell_bel_mapper):
print('BEL buckets:')
for bel_bucket in cell_bel_mapper.get_bel_buckets():
print(' - {}'.format(bel_bucket))
print('')
print('Cell -> BEL bucket:')
for cell in sorted(
cell_bel_mapper.get_cells(),
key=lambda cell: (cell_bel_mapper.cell_to_bel_bucket(cell), cell)):
print(' - {} => {}'.format(cell,
cell_bel_mapper.cell_to_bel_bucket(cell)))
print('')
print('BEL -> BEL bucket:')
for site_type, bel in sorted(
cell_bel_mapper.get_bels(),
key=lambda key: (cell_bel_mapper.bel_to_bel_bucket(*key), *key)):
print(' - {}/{} => {}'.format(
site_type, bel, cell_bel_mapper.bel_to_bel_bucket(site_type, bel)))
class ConstantNetworkGenerator():
def __init__(self, device, chip_info, cell_bel_mapper):
self.device = device
self.chip_info = chip_info
self.constants = chip_info.constants
self.cell_bel_mapper = cell_bel_mapper
self.site_type = '$CONSTANTS'
self.site_name = '$CONSTANTS_X0Y0'
self.tile_type_name = '$CONSTANTS'
self.tile_name = '$CONSTANTS_X0Y0'
self.tile_type, gnd_bel, vcc_bel = self.create_initial_bels()
self.gnd_node_wire, self.vcc_node_wire = self.initialize_constant_network(
self.tile_type, gnd_bel, vcc_bel)
def create_initial_bels(self):
""" Create initial BELs that are the global constant sources. """
consts = self.device.get_constants()
self.constants.gnd_cell_name = consts.GND_CELL_TYPE
self.constants.gnd_cell_port = consts.GND_PORT
self.constants.vcc_cell_name = consts.VCC_CELL_TYPE
self.constants.vcc_cell_port = consts.VCC_PORT
self.constants.gnd_bel_index = 0
self.constants.gnd_bel_pin = self.constants.gnd_cell_port
self.constants.vcc_bel_index = 1
self.constants.vcc_bel_pin = self.constants.vcc_cell_port
self.constants.gnd_net_name = consts.GND_NET
self.constants.vcc_net_name = consts.VCC_NET
tile_type = TileTypeInfo()
self.tile_type_index = len(self.chip_info.tile_types)
self.chip_info.tile_types.append(tile_type)
tile_type.site_types.append(self.site_type)
self.cell_bel_mapper.cell_to_bel_map[
self.constants.gnd_cell_name] = set(
((self.site_type, self.constants.gnd_cell_name), ))
self.cell_bel_mapper.cell_to_bel_map[
self.constants.vcc_cell_name] = set(
((self.site_type, self.constants.vcc_cell_name), ))
# Create BELs to be the source of the constant networks.
gnd_bel = BelInfo()
gnd_bel.name = self.constants.gnd_cell_name
gnd_bel.type = self.constants.gnd_cell_name
gnd_bel.bel_bucket = self.cell_bel_mapper.cell_to_bel_bucket(
self.constants.gnd_cell_name)
gnd_bel.ports.append(self.constants.gnd_cell_port)
gnd_bel.types.append(PortType.PORT_OUT)
gnd_bel.wires.append(0)
gnd_bel.site = 0
gnd_bel.site_variant = -1
gnd_bel.bel_category = BelCategory.LOGIC.value
gnd_bel.synthetic = 1
gnd_bel.pin_map = [-1 for _ in self.cell_bel_mapper.get_cells()]
gnd_cell_idx = self.cell_bel_mapper.get_cell_index(
self.constants.gnd_cell_name)
gnd_bel.pin_map[
gnd_cell_idx] = self.cell_bel_mapper.get_cell_bel_map_index(
cell_type=self.constants.gnd_cell_name,
tile_type=self.tile_type_name,
site_index=0,
site_type=self.site_type,
bel=gnd_bel.name)
assert gnd_bel.pin_map[gnd_cell_idx] != -1
assert len(tile_type.bel_data) == self.constants.gnd_bel_index
tile_type.bel_data.append(gnd_bel)
vcc_bel = BelInfo()
vcc_bel.name = self.constants.vcc_cell_name
vcc_bel.type = self.constants.vcc_cell_name
vcc_bel.bel_bucket = self.cell_bel_mapper.cell_to_bel_bucket(
self.constants.vcc_cell_name)
vcc_bel.ports.append(self.constants.vcc_cell_port)
vcc_bel.types.append(PortType.PORT_OUT)
vcc_bel.wires.append(1)
vcc_bel.site = 0
vcc_bel.site_variant = -1
vcc_bel.bel_category = BelCategory.LOGIC.value
vcc_bel.synthetic = 1
vcc_bel.pin_map = [-1 for _ in self.cell_bel_mapper.get_cells()]
vcc_cell_idx = self.cell_bel_mapper.get_cell_index(
self.constants.vcc_cell_name)
vcc_bel.pin_map[
vcc_cell_idx] = self.cell_bel_mapper.get_cell_bel_map_index(
cell_type=self.constants.vcc_cell_name,
tile_type=self.tile_type_name,
site_index=0,
site_type=self.site_type,
bel=vcc_bel.name)
assert vcc_bel.pin_map[vcc_cell_idx] != -1
assert len(tile_type.bel_data) == self.constants.vcc_bel_index
tile_type.bel_data.append(vcc_bel)
self.cell_bel_mapper.bels.add((self.site_name, gnd_bel.name))
self.cell_bel_mapper.bels.add((self.site_name, vcc_bel.name))
key = (self.constants.gnd_cell_name, self.site_type, gnd_bel.name)
self.cell_bel_mapper.cell_to_bel_common_pins[key] = ((
self.constants.gnd_cell_port, self.constants.gnd_cell_port), )
key = (self.constants.vcc_cell_name, self.site_type, vcc_bel.name)
self.cell_bel_mapper.cell_to_bel_common_pins[key] = ((
self.constants.vcc_cell_port, self.constants.vcc_cell_port), )
tile_type.name = self.tile_type_name
return tile_type, gnd_bel, vcc_bel
def initialize_constant_network(self, tile_type, gnd_bel, vcc_bel):
""" Create site wiring to connect GND/VCC source to a node.
Create site pins (as if it were a real site).
"""
gnd_wire = TileWireInfo()
assert len(tile_type.wire_data) == gnd_bel.wires[0]
tile_type.wire_data.append(gnd_wire)
gnd_wire.name = '$GND_SOURCE'
gnd_wire.site = 0
gnd_wire.site_variant = -1
gnd_wire_bel_port = BelPort()
gnd_wire_bel_port.bel_index = self.constants.gnd_bel_index
gnd_wire_bel_port.port = gnd_bel.ports[0]
gnd_wire.bel_pins.append(gnd_wire_bel_port)
vcc_wire = TileWireInfo()
assert len(tile_type.wire_data) == vcc_bel.wires[0]
tile_type.wire_data.append(vcc_wire)
vcc_wire.name = '$VCC_SOURCE'
vcc_wire.site = 0
vcc_wire.site_variant = -1
vcc_wire_bel_port = BelPort()
vcc_wire_bel_port.bel_index = self.constants.vcc_bel_index
vcc_wire_bel_port.port = vcc_bel.ports[0]
vcc_wire.bel_pins.append(vcc_wire_bel_port)
# Construct site port for GND_SOURCE.
# Create the pip that is the edge between the site and the first wire in
# the graph
gnd_site_port = PipInfo()
gnd_site_port_pip_idx = len(tile_type.pip_data)
tile_type.pip_data.append(gnd_site_port)
# Populate the site port edge information
gnd_site_port.site = 0
gnd_site_port.site_variant = -1
gnd_site_port.extra_data = 0
gnd_site_port.src_index = gnd_bel.wires[0]
# Create the first wire for the ground graph.
gnd_site_port.dst_index = len(tile_type.wire_data)
gnd_node_wire = TileWireInfo()
tile_type.wire_data.append(gnd_node_wire)
# Update the wires upstream and downstream from the pip.
gnd_wire.pips_downhill.append(gnd_site_port_pip_idx)
gnd_node_wire.pips_uphill.append(gnd_site_port_pip_idx)
# Finish populating the first wire in the graph.
gnd_node_wire.name = '$GND_NODE'
gnd_node_wire.site = -1
# Create the site port BEL for the site port pip.
gnd_site_port.bel = len(tile_type.bel_data)
gnd_site_port_bel = BelInfo()
tile_type.bel_data.append(gnd_site_port_bel)
gnd_site_port_bel.name = '$GND'
gnd_site_port_bel.type = 'NA'
gnd_site_port_bel.bel_bucket = 'UNPLACABLE_BELS'
gnd_site_port_bel.ports.append(gnd_site_port_bel.name)
gnd_site_port_bel.types.append(PortType.PORT_IN.value)
gnd_site_port_bel.wires.append(gnd_bel.wires[0])
gnd_site_port_bel.site = 0
gnd_site_port_bel.site_variant = -1
gnd_site_port_bel.bel_category = BelCategory.SITE_PORT.value
gnd_site_port_bel.synthetic = 1
# Attach the site port to the site wire.
gnd_site_port_bel_port = BelPort()
gnd_site_port_bel_port.bel_index = gnd_site_port.bel
gnd_site_port_bel_port.port = gnd_site_port_bel.name
gnd_wire.bel_pins.append(gnd_site_port_bel_port)
# Construct site port for VCC_SOURCE.
# Create the pip that is the edge between the site and the first wire in
# the graph
vcc_site_port = PipInfo()
vcc_site_port_pip_idx = len(tile_type.pip_data)
tile_type.pip_data.append(vcc_site_port)
# Populate the site port edge information
vcc_site_port.site = 0
vcc_site_port.site_variant = -1
vcc_site_port.extra_data = 0
vcc_site_port.src_index = vcc_bel.wires[0]
# Create the first wire for the ground graph.
vcc_site_port.dst_index = len(tile_type.wire_data)
vcc_node_wire = TileWireInfo()
tile_type.wire_data.append(vcc_node_wire)
# Update the wires upstream and downstream from the pip.
vcc_wire.pips_downhill.append(vcc_site_port_pip_idx)
vcc_node_wire.pips_uphill.append(vcc_site_port_pip_idx)
# Finish populating the first wire in the graph.
vcc_node_wire.name = '$VCC_NODE'
vcc_node_wire.site = -1
# Create the site port BEL for the site port pip.
vcc_site_port.bel = len(tile_type.bel_data)
vcc_site_port_bel = BelInfo()
tile_type.bel_data.append(vcc_site_port_bel)
vcc_site_port_bel.name = '$VCC'
vcc_site_port_bel.type = 'NA'
vcc_site_port_bel.bel_bucket = 'UNPLACABLE_BELS'
vcc_site_port_bel.ports.append(vcc_site_port_bel.name)
vcc_site_port_bel.types.append(PortType.PORT_IN.value)
vcc_site_port_bel.wires.append(vcc_bel.wires[0])
vcc_site_port_bel.site = 0
vcc_site_port_bel.site_variant = -1
vcc_site_port_bel.bel_category = BelCategory.SITE_PORT.value
vcc_site_port_bel.synthetic = 1
# Attach the site port to the site wire.
vcc_site_port_bel_port = BelPort()
vcc_site_port_bel_port.bel_index = vcc_site_port.bel
vcc_site_port_bel_port.port = vcc_site_port_bel.name
vcc_wire.bel_pins.append(vcc_site_port_bel_port)
return (gnd_site_port.dst_index, vcc_site_port.dst_index)
def populate_constant_network(self):
""" Create nodes that reach every tile that needs the constant network.
Create a tile local wire for each tile that has a constant source.
Connect the constant node to that local wire. Then create an edge
from that local wire to the specific source.
The reason for this is to allow the router to intellegently search the
constant network.
"""
device = self.device
tile_idx = 0
# Overwrite tile at 0,0 assuming that it is a NULL tile.
tile_type_name = self.chip_info.tile_types[self.chip_info.
tiles[tile_idx].type].name
assert tile_type_name == 'NULL', tile_type_name
self.constants.gnd_bel_tile = tile_idx
self.constants.vcc_bel_tile = tile_idx
self.chip_info.tiles[tile_idx].name = self.tile_name
self.chip_info.tiles[tile_idx].type = self.tile_type_index
self.chip_info.tiles[tile_idx].sites = [len(self.chip_info.sites)]
site_inst = SiteInstInfo()
self.chip_info.sites.append(site_inst)
site_inst.name = '{}.{}'.format(self.site_name, self.site_type)
site_inst.site_name = self.site_name
site_inst.site_type = self.site_type
self.chip_info.tiles[tile_idx].tile_wire_to_node = [
-1 for _ in range(len(self.tile_type.wire_data))
]
# Create nodes for the global constant network
gnd_node_idx = len(self.chip_info.nodes)
self.chip_info.tiles[tile_idx].tile_wire_to_node[
self.gnd_node_wire] = gnd_node_idx
gnd_node = NodeInfo()
self.chip_info.nodes.append(gnd_node)
gnd_node.name = 'gnd_node'
gnd_node_ref = TileWireRef()
gnd_node.tile_wires.append(gnd_node_ref)
gnd_node_ref.tile = tile_idx
gnd_node_ref.index = self.gnd_node_wire
vcc_node_idx = len(self.chip_info.nodes)
self.chip_info.tiles[tile_idx].tile_wire_to_node[
self.vcc_node_wire] = vcc_node_idx
vcc_node = NodeInfo()
self.chip_info.nodes.append(vcc_node)
vcc_node.name = 'vcc_node'
vcc_node_ref = TileWireRef()
vcc_node.tile_wires.append(vcc_node_ref)
vcc_node_ref.tile = tile_idx
vcc_node_ref.index = self.vcc_node_wire
bel_pins_connected_to_gnd = set()
bel_pins_connected_to_vcc = set()
site_types_with_gnd = set()
site_types_with_vcc = set()
for site_source in device.device_resource_capnp.constants.siteSources:
site_type = device.strs[site_source.siteType]
bel = device.strs[site_source.bel]
bel_pin = device.strs[site_source.belPin]
if site_source.constant == 'gnd':
site_types_with_gnd.add(site_type)
bel_pins_connected_to_gnd.add((site_type, bel, bel_pin))
elif site_source.constant == 'vcc':
site_types_with_vcc.add(site_type)
bel_pins_connected_to_vcc.add((site_type, bel, bel_pin))
else:
assert False, site_source.constant
tile_types_with_gnd = set()
tile_types_with_vcc = set()
for tile_type_idx, tile_type in enumerate(self.chip_info.tile_types):
if tile_type_idx == self.tile_type_index:
continue
tile_type_data = device.device_resource_capnp.tileTypeList[
tile_type_idx]
assert device.strs[tile_type_data.name] == tile_type.name
for wire_constant in tile_type_data.constants:
if wire_constant.constant == 'gnd':
tile_types_with_gnd.add(tile_type_idx)
elif wire_constant.constant == 'vcc':
tile_types_with_vcc.add(tile_type_idx)
else:
assert False, wire_constant.constant
for site_in_tile_type in tile_type_data.siteTypes:
site_type = device.device_resource_capnp.siteTypeList[
site_in_tile_type.primaryType]
site_type_name = device.strs[site_type.name]
if site_type_name in site_types_with_gnd:
tile_types_with_gnd.add(tile_type_idx)
if site_type_name in site_types_with_vcc:
tile_types_with_vcc.add(tile_type_idx)
for alt_site_type_idx in site_type.altSiteTypes:
alt_site_type = device.device_resource_capnp.siteTypeList[
alt_site_type_idx]
site_type_name = device.strs[alt_site_type.name]
if site_type_name in site_types_with_gnd:
tile_types_with_gnd.add(tile_type_idx)
if site_type_name in site_types_with_vcc:
tile_types_with_vcc.add(tile_type_idx)
# Create gnd local wire in each type that needs it
tile_type_gnd_wires = {}
for tile_type_idx in tile_types_with_gnd:
tile_type = self.chip_info.tile_types[tile_type_idx]
gnd_wire_idx = len(tile_type.wire_data)
gnd_wire = TileWireInfo()
tile_type.wire_data.append(gnd_wire)
gnd_wire.name = '$GND_WIRE'
gnd_wire.site = -1
tile_type_gnd_wires[tile_type_idx] = gnd_wire_idx
# Add gnd local wire in each instance to node
for tile_idx, tile in enumerate(self.chip_info.tiles):
if tile.type not in tile_types_with_gnd:
continue
gnd_wire_idx = tile_type_gnd_wires[tile.type]
assert gnd_wire_idx >= len(
tile.tile_wire_to_node), (gnd_wire_idx,
len(tile.tile_wire_to_node),
len(tile_type.wire_data))
while gnd_wire_idx > len(tile.tile_wire_to_node):
tile.tile_wire_to_node.append(-1)
tile.tile_wire_to_node.append(gnd_node_idx)
wire_ref = TileWireRef()
wire_ref.tile = tile_idx
wire_ref.index = gnd_wire_idx
gnd_node.tile_wires.append(wire_ref)
# Create vcc local wire in each type that needs it
tile_type_vcc_wires = {}
for tile_type_idx in tile_types_with_vcc:
tile_type = self.chip_info.tile_types[tile_type_idx]
vcc_wire_idx = len(tile_type.wire_data)
vcc_wire = TileWireInfo()
tile_type.wire_data.append(vcc_wire)
vcc_wire.name = '$VCC_WIRE'
vcc_wire.site = -1
tile_type_vcc_wires[tile_type_idx] = vcc_wire_idx
# Add vcc local wire in each instance to node
for tile_idx, tile in enumerate(self.chip_info.tiles):
if tile.type not in tile_types_with_vcc:
continue
vcc_wire_idx = tile_type_vcc_wires[tile.type]
assert vcc_wire_idx >= len(tile.tile_wire_to_node)
while vcc_wire_idx > len(tile.tile_wire_to_node):
tile.tile_wire_to_node.append(-1)
tile.tile_wire_to_node.append(vcc_node_idx)
wire_ref = TileWireRef()
wire_ref.tile = tile_idx
wire_ref.index = vcc_wire_idx
vcc_node.tile_wires.append(wire_ref)
for tile_type_idx in (tile_types_with_gnd | tile_types_with_vcc):
gnd_wire_idx = tile_type_gnd_wires.get(tile_type_idx, None)
vcc_wire_idx = tile_type_vcc_wires.get(tile_type_idx, None)
self.connect_tile_type(tile_type_idx, gnd_wire_idx, vcc_wire_idx,
bel_pins_connected_to_gnd,
bel_pins_connected_to_vcc)
# FIXME: Implement node constant sources.
#
# Node constant sources are rarer, and less important, so don't
# import them right now.
def connect_tile_type(self, tile_type_idx, gnd_wire_idx, vcc_wire_idx,
bel_pins_connected_to_gnd,
bel_pins_connected_to_vcc):
device = self.device
tile_type = self.chip_info.tile_types[tile_type_idx]
tile_type_data = self.device.device_resource_capnp.tileTypeList[
tile_type_idx]
assert device.strs[tile_type_data.name] == tile_type.name
gnd_site_wires = {}
vcc_site_wires = {}
for bel_info in tile_type.bel_data:
site_type = tile_type.site_types[bel_info.site]
for bel_pin_idx, bel_pin in enumerate(bel_info.ports):
wire_idx = bel_info.wires[bel_pin_idx]
if wire_idx == -1:
continue
key = (site_type, bel_info.name, bel_pin)
src_wire_idx = None
if key in bel_pins_connected_to_gnd:
assert key not in bel_pins_connected_to_vcc
gnd_site_wire_idx = gnd_site_wires.get(bel_info.site, None)
if gnd_site_wire_idx is None:
gnd_site_wire_idx = self.build_input_site_port(
tile_type_idx=tile_type_idx,
port_name='$GND',
site_wire_name='$GND_SITE_WIRE',
tile_wire_idx=gnd_wire_idx,
site=bel_info.site,
site_variant=bel_info.site_variant)
gnd_site_wires[bel_info.site] = gnd_site_wire_idx
src_wire_idx = gnd_site_wire_idx
elif key in bel_pins_connected_to_vcc:
assert key not in bel_pins_connected_to_gnd
vcc_site_wire_idx = vcc_site_wires.get(bel_info.site, None)
if vcc_site_wire_idx is None:
vcc_site_wire_idx = self.build_input_site_port(
tile_type_idx=tile_type_idx,
port_name='$VCC',
site_wire_name='$VCC_SITE_WIRE',
tile_wire_idx=vcc_wire_idx,
site=bel_info.site,
site_variant=bel_info.site_variant)
vcc_site_wires[bel_info.site] = vcc_site_wire_idx
src_wire_idx = vcc_site_wire_idx
else:
continue
# Create pip connecting constant network to site wire source.
edge = PipInfo()
edge.site = bel_info.site
edge.site_variant = bel_info.site_variant
edge_idx = len(tile_type.pip_data)
tile_type.pip_data.append(edge)
assert src_wire_idx is not None
edge.src_index = src_wire_idx
edge.dst_index = wire_idx
edge.bel = len(tile_type.bel_data)
# Create site PIP BEL for edge between constant network site
# wire and site wire source.
site_pip_bel = BelInfo()
tile_type.bel_data.append(site_pip_bel)
site_pip_bel.name = '{}_{}'.format(
bel_info.name, tile_type.wire_data[src_wire_idx].name)
site_pip_bel.type = 'NA'
site_pip_bel.ports.append(bel_info.name)
site_pip_bel.types.append(PortType.PORT_IN.value)
site_pip_bel.wires.append(src_wire_idx)
site_pip_bel.ports.append(
tile_type.wire_data[src_wire_idx].name)
site_pip_bel.types.append(PortType.PORT_OUT.value)
site_pip_bel.wires.append(wire_idx)
in_bel_port = BelPort()
in_bel_port.bel_index = edge.bel
in_bel_port.port = site_pip_bel.ports[0]
tile_type.wire_data[src_wire_idx].bel_pins.append(in_bel_port)
out_bel_port = BelPort()
out_bel_port.bel_index = edge.bel
out_bel_port.port = site_pip_bel.ports[1]
tile_type.wire_data[wire_idx].bel_pins.append(out_bel_port)
site_pip_bel.bel_bucket = 'UNPLACABLE_BELS'
site_pip_bel.site = bel_info.site
site_pip_bel.site_variant = bel_info.site_variant
site_pip_bel.bel_category = BelCategory.ROUTING.value
site_pip_bel.synthetic = 1
# Update wire data pointing to new pip.
tile_type.wire_data[src_wire_idx].pips_downhill.append(
edge_idx)
tile_type.wire_data[wire_idx].pips_uphill.append(edge_idx)
for wire_constant in tile_type_data.constants:
if wire_constant.constant == 'gnd':
src_wire_idx = gnd_wire_idx
elif wire_constant.constant == 'vcc':
src_wire_idx = vcc_wire_idx
else:
assert False, wire_constant.constant
assert src_wire_idx is not None
for wire_idx in wire_constant.wires:
wire_name = device.strs[tile_type_data.wires[wire_idx]]
assert tile_type.wire_data[wire_idx].name == wire_name, (
tile_type.wire_data[wire_idx].name, wire_name)
# Create pip connecting constant network to wire source.
edge = PipInfo()
edge.site = -1
edge_idx = len(tile_type.pip_data)
tile_type.pip_data.append(edge)
edge.src_index = src_wire_idx
edge.dst_index = wire_idx
edge.extra_data = -1
# Update wire data pointing to new pip.
tile_type.wire_data[src_wire_idx].pips_downhill.append(
edge_idx)
tile_type.wire_data[wire_idx].pips_uphill.append(edge_idx)
def build_input_site_port(self, tile_type_idx, port_name, site_wire_name,
tile_wire_idx, site, site_variant):
tile_type = self.chip_info.tile_types[tile_type_idx]
site_port_edge_idx = len(tile_type.pip_data)
site_port_edge = PipInfo()
tile_type.pip_data.append(site_port_edge)
site_port_bel_idx = len(tile_type.bel_data)
site_port_bel = BelInfo()
tile_type.bel_data.append(site_port_bel)
site_wire_idx = len(tile_type.wire_data)
site_wire = TileWireInfo()
tile_type.wire_data.append(site_wire)
site_port_edge.site = site
site_port_edge.site_variant = site_variant
site_port_edge.bel = site_port_bel_idx
site_port_edge.src_index = tile_wire_idx
tile_type.wire_data[tile_wire_idx].pips_downhill.append(
site_port_edge_idx)
site_port_edge.dst_index = site_wire_idx
site_wire.pips_uphill.append(site_port_edge_idx)
site_port_bel.name = port_name
site_port_bel.type = 'NA'
site_port_bel.bel_bucket = 'UNPLACABLE_BELS'
site_port_bel.ports.append(port_name)
site_port_bel.types.append(PortType.PORT_OUT.value)
site_port_bel.wires.append(site_wire_idx)
site_port_bel.site = site
site_port_bel.site_variant = site_variant
site_port_bel.bel_category = BelCategory.SITE_PORT.value
site_port_bel.synthetic = 1
site_wire.name = site_wire_name
site_wire_bel_port = BelPort()
site_wire.bel_pins.append(site_wire_bel_port)
site_wire.site = site
site_wire.site_variant = site_variant
site_wire_bel_port.bel_index = site_port_bel_idx
site_wire_bel_port.port = port_name
return site_wire_idx
def populate_chip_info(device, constids, bel_bucket_seeds):
assert len(constids.values) == 0
cell_bel_mapper = CellBelMapper(device, constids)
# Make the BEL buckets.
for bucket in bel_bucket_seeds:
bel_bucket = bucket['bucket']
cells = bucket['cells']
cell_bel_mapper.make_bel_bucket(bel_bucket, cells)
cell_bel_mapper.handle_remaining()
if DEBUG_BEL_BUCKETS:
print_bel_buckets(cell_bel_mapper)
chip_info = ChipInfo()
chip_info.name = device.device_resource_capnp.name
chip_info.generator = 'python-fpga-interchange v0.x'
chip_info.version = 1
# Emit cells in const ID order to build cell map.
for cell_name in cell_bel_mapper.get_cells():
chip_info.cell_map.add_cell(
cell_name, cell_bel_mapper.cell_to_bel_bucket(cell_name))
for bel_bucket in sorted(set(cell_bel_mapper.get_bel_buckets())):
chip_info.bel_buckets.append(bel_bucket)
tile_wire_to_wire_in_tile_index = []
num_tile_wires = []
constraints = device.get_constraints()
for tile_type_index, tile_type in enumerate(
device.device_resource_capnp.tileTypeList):
flattened_tile_type = FlattenedTileType(
device, tile_type_index, tile_type, cell_bel_mapper, constraints)
tile_type_info = flattened_tile_type.create_tile_type_info(
cell_bel_mapper)
chip_info.tile_types.append(tile_type_info)
# Create map of tile wires to wire in tile id.
per_tile_map = {}
for idx, wire in enumerate(tile_type_info.wire_data):
if wire.site != -1:
# Only care about tile wires!
break
assert wire.name not in per_tile_map
per_tile_map[wire.name] = idx
tile_wire_to_wire_in_tile_index.append(per_tile_map)
num_tile_wires.append(max(per_tile_map.values()) + 1)
constants = ConstantNetworkGenerator(device, chip_info, cell_bel_mapper)
# Emit cell bel pin map.
for key, idx in sorted(
cell_bel_mapper.cell_site_bel_index.items(),
key=lambda item: item[1]):
cell_type, tile_type, site_index, site_type, bel = key
cell_bel_map = CellBelMap(cell_type, tile_type, site_index, bel)
chip_info.cell_map.cell_bel_map.append(cell_bel_map)
pin_key = (cell_type, site_type, bel)
if pin_key in cell_bel_mapper.cell_to_bel_common_pins:
for (cell_pin,
bel_pin) in cell_bel_mapper.cell_to_bel_common_pins[pin_key]:
cell_bel_map.common_pins.append(CellBelPin(cell_pin, bel_pin))
if pin_key in cell_bel_mapper.cell_to_bel_parameter_pins:
for (param_key, param_value
), pins in cell_bel_mapper.cell_to_bel_parameter_pins[
pin_key].items():
parameter = ParameterPins()
parameter.key = param_key
parameter.value = param_value
for (cell_pin, bel_pin) in pins:
cell_bel_map.parameter_pins.append(
CellBelPin(cell_pin, bel_pin))
cell_bel_map.parameter_pins.append(parameter)
cell_bel_map = chip_info.cell_map.cell_bel_map[idx]
if idx in cell_bel_mapper.cell_to_bel_constraints:
cell_bel_map.constraints = cell_bel_mapper.cell_to_bel_constraints[
idx]
tiles = {}
tile_name_to_tile_index = {}
for tile_index, tile in enumerate(device.device_resource_capnp.tileList):
tile_info = TileInstInfo()
tile_info.name = device.strs[tile.name]
tile_info.type = tile.type
tile_info.tile_wire_to_node = list(
[-1 for _ in range(num_tile_wires[tile.type])])
tile_type = device.device_resource_capnp.tileTypeList[tile.type]
for site_type_in_tile_type, site in zip(tile_type.siteTypes,
tile.sites):
site_name = device.strs[site.name]
# Emit primary type
site_info = SiteInstInfo()
site_type = device.device_resource_capnp.siteTypeList[
site_type_in_tile_type.primaryType]
site_type_name = device.strs[site_type.name]
site_info.name = '{}.{}'.format(site_name, site_type_name)
site_info.site_name = site_name
site_info.site_type = site_type_name
tile_info.sites.append(len(chip_info.sites))
chip_info.sites.append(site_info)
for site_variant, (alt_site_type_index, _) in enumerate(
zip(site_type.altSiteTypes,
site_type_in_tile_type.altPinsToPrimaryPins)):
alt_site_info = SiteInstInfo()
alt_site_type = device.device_resource_capnp.siteTypeList[
alt_site_type_index]
alt_site_type_name = device.strs[alt_site_type.name]
alt_site_info.name = '{}.{}'.format(site_name,
alt_site_type_name)
alt_site_info.site_name = site_name
alt_site_info.site_type = alt_site_type_name
tile_info.sites.append(len(chip_info.sites))
chip_info.sites.append(alt_site_info)
assert len(tile_info.sites) == len(
chip_info.tile_types[tile.type].site_types), (
tile_info.name, len(tile_info.sites),
len(chip_info.tile_types[tile.type].site_types))
# (x, y) = (col, row)
tiles[(tile.col, tile.row)] = (tile_index, tile_info)
# Compute dimensions of grid
xs, ys = zip(*tiles.keys())
width = max(xs) + 1
height = max(ys) + 1
chip_info.width = width
chip_info.height = height
# Add tile instances to chip_info in row major order (per arch.h).
for y in range(height):
for x in range(width):
key = x, y
_, tile_info = tiles[key]
tile_name_to_tile_index[tile_info.name] = len(chip_info.tiles)
chip_info.tiles.append(tile_info)
# Output nodes
for idx, node in enumerate(device.device_resource_capnp.nodes):
# Skip nodes with only 1 wire!
if len(node.wires) == 1:
continue
node_info = NodeInfo()
node_index = len(chip_info.nodes)
chip_info.nodes.append(node_info)
# FIXME: Replace with actual node name?
node_info.name = 'node_{}'.format(node_index)
for wire_index in node.wires:
wire = device.device_resource_capnp.wires[wire_index]
tile_name = device.strs[wire.tile]
wire_name = device.strs[wire.wire]
tile_index = tile_name_to_tile_index[tile_name]
tile_info = chip_info.tiles[tile_index]
# Make reference from tile to node.
wire_in_tile_id = tile_wire_to_wire_in_tile_index[tile_info.
type][wire_name]
assert wire_in_tile_id < len(tile_info.tile_wire_to_node), (
wire_in_tile_id, len(tile_info.tile_wire_to_node),
tile_info.type, wire_name)
assert tile_info.tile_wire_to_node[wire_in_tile_id] == -1
tile_info.tile_wire_to_node[wire_in_tile_id] = node_index
# Make reference from node to tile.
tile_wire = TileWireRef()
tile_wire.tile = tile_index
tile_wire.index = wire_in_tile_id
node_info.tile_wires.append(tile_wire)
constants.populate_constant_network()
for package in device.device_resource_capnp.packages:
package_data = Package()
package_data.package = device.strs[package.name]
chip_info.packages.append(package_data)
for package_pin in package.packagePins:
if package_pin.site.which() == 'noSite':
continue
if package_pin.site.which() == 'noBel':
continue
package_pin_data = PackagePin()
package_pin_data.package_pin = device.strs[package_pin.packagePin]
package_pin_data.site = device.strs[package_pin.site.site]
package_pin_data.bel = device.strs[package_pin.bel.bel]
package_data.package_pins.append(package_pin_data)
return chip_info
| 38.477585 | 157 | 0.614776 |
from enum import Enum
from collections import namedtuple
from fpga_interchange.chip_info import ChipInfo, BelInfo, TileTypeInfo, \
TileWireInfo, BelPort, PipInfo, TileInstInfo, SiteInstInfo, NodeInfo, \
TileWireRef, CellBelMap, ParameterPins, CellBelPin, ConstraintTag, \
CellConstraint, ConstraintType, Package, PackagePin
from fpga_interchange.constraints.model import Tag, Placement, \
ImpliesConstraint, RequiresConstraint
from fpga_interchange.constraint_generator import ConstraintPrototype
from fpga_interchange.nextpnr import PortType
class FlattenedWireType(Enum):
TILE_WIRE = 0
SITE_WIRE = 1
class FlattenedPipType(Enum):
TILE_PIP = 0
SITE_PIP = 1
SITE_PIN = 2
class BelCategory(Enum):
LOGIC = 0
ROUTING = 1
SITE_PORT = 2
def direction_to_type(direction):
if direction == 'input':
return PortType.PORT_IN
elif direction == 'output':
return PortType.PORT_OUT
else:
assert direction == 'inout'
return PortType.PORT_INOUT
BelPin = namedtuple('BelPin', 'port type wire')
class FlattenedBel():
def __init__(self, name, type, site_index, bel_index, bel_category):
self.name = name
self.type = type
self.site_index = site_index
self.bel_index = bel_index
self.bel_category = bel_category
self.ports = []
self.valid_cells = set()
def add_port(self, device, bel_pin, wire_index):
self.ports.append(
BelPin(
port=device.strs[bel_pin.name],
type=direction_to_type(bel_pin.dir),
wire=wire_index))
class FlattenedWire():
def __init__(self, type, name, wire_index, site_index):
self.type = type
self.name = name
self.wire_index = wire_index
self.site_index = site_index
self.bel_pins = []
self.pips_uphill = []
self.pips_downhill = []
class FlattenedPip(
namedtuple('FlattenedPip',
'type src_index dst_index site_index pip_index')):
pass
class FlattenedSite(
namedtuple(
'FlattenedSite',
'site_in_type_index site_type_index site_type site_type_name site_variant bel_to_bel_index bel_pin_to_site_wire_index bel_pin_index_to_bel_index'
)):
pass
def emit_constraints(tile_type, tile_constraints, cell_bel_mapper):
flat_tag_indicies = {}
flat_tag_state_indicies = {}
for idx, (tag_prefix, tag_data) in enumerate(
sorted(tile_constraints.tags.items())):
flat_tag_indicies[tag_prefix] = idx
flat_tag_state_indicies[tag_prefix] = {}
tag = ConstraintTag()
tag.tag_prefix = tag_prefix
tag.default_state = tag_data.default
tag.states = sorted(tag_data.states)
for idx, state in enumerate(tag.states):
flat_tag_state_indicies[tag_prefix][state] = idx
tile_type.tags.append(tag)
for (cell_type, site_index, site_type,
bel), constraints in tile_constraints.bel_cell_constraints.items():
idx = cell_bel_mapper.get_cell_bel_map_index(
cell_type, tile_type.name, site_index, site_type, bel)
outs = []
for tag_prefix, constraint in constraints:
out = CellConstraint()
out.tag = flat_tag_indicies[tag_prefix]
if isinstance(constraint, ImpliesConstraint):
out.constraint_type = ConstraintType.TAG_IMPLIES
out.states.append(
flat_tag_state_indicies[tag_prefix][constraint.state])
elif isinstance(constraint, RequiresConstraint):
out.constraint_type = ConstraintType.TAG_REQUIRES
for state in constraint.states:
out.states.append(
flat_tag_state_indicies[tag_prefix][state])
else:
assert False, type(constraint)
outs.append(out)
cell_bel_mapper.cell_to_bel_constraints[idx] = outs
class FlattenedTileType():
def __init__(self, device, tile_type_index, tile_type, cell_bel_mapper,
constraints):
self.tile_type_name = device.strs[tile_type.name]
self.tile_type = tile_type
self.tile_constraints = ConstraintPrototype()
self.sites = []
self.bels = []
self.bel_index_remap = {}
self.wires = []
self.pips = []
self.tile_wire_to_wire_in_tile_index = {}
for wire_in_tile_index, wire in enumerate(tile_type.wires):
name = device.strs[wire]
self.tile_wire_to_wire_in_tile_index[name] = wire_in_tile_index
flat_wire = FlattenedWire(
type=FlattenedWireType.TILE_WIRE,
name=name,
wire_index=wire_in_tile_index,
site_index=None)
self.add_wire(flat_wire)
for idx, pip in enumerate(tile_type.pips):
self.add_tile_pip(idx, pip.wire0, pip.wire1)
if not pip.directional:
self.add_tile_pip(idx, pip.wire1, pip.wire0)
for site_in_type_index, site_type_in_tile_type in enumerate(
tile_type.siteTypes):
site_type_index = site_type_in_tile_type.primaryType
site_variant = -1
primary_site_type = device.device_resource_capnp.siteTypeList[
site_type_index]
self.add_site_type(device, site_type_in_tile_type,
site_in_type_index, site_type_index,
site_variant, cell_bel_mapper)
for site_variant, (alt_site_type_index, _) in enumerate(
zip(primary_site_type.altSiteTypes,
site_type_in_tile_type.altPinsToPrimaryPins)):
self.add_site_type(device, site_type_in_tile_type,
site_in_type_index, alt_site_type_index,
site_variant, cell_bel_mapper,
primary_site_type)
self.remap_bel_indicies()
self.generate_constraints(constraints)
def generate_constraints(self, constraints):
tags_for_tile_type = {}
available_placements = []
sites_in_tile_type = {}
for site_index, site in enumerate(self.sites):
if site.site_in_type_index not in sites_in_tile_type:
sites_in_tile_type[site.site_in_type_index] = []
sites_in_tile_type[site.site_in_type_index].append(site_index)
for site, possible_sites in sites_in_tile_type.items():
site_types = []
for site_index in possible_sites:
site_types.append(self.sites[site_index].site_type_name)
assert len(site_types) == len(set(site_types))
tag_prefix = 'type_of_site{:03d}'.format(site)
assert tag_prefix not in tags_for_tile_type
tags_for_tile_type[tag_prefix] = Tag(
name='TypeOfSite{}'.format(site),
states=site_types,
default=site_types[0],
matchers=[])
self.tile_constraints.add_tag(tag_prefix,
tags_for_tile_type[tag_prefix])
for bel in self.bels:
site = self.sites[bel.site_index]
placement = Placement(
tile=self.tile_type_name,
site='site{}_{}'.format(site.site_in_type_index,
site.site_type_name),
tile_type=self.tile_type_name,
site_type=site.site_type_name,
bel=bel.name)
available_placements.append(placement)
for tag_prefix, tag in constraints.yield_tags_at_placement(
placement):
if tag_prefix in tags_for_tile_type:
assert tags_for_tile_type[tag_prefix] is tag
continue
else:
tags_for_tile_type[tag_prefix] = tag
self.tile_constraints.add_tag(
tag_prefix, tags_for_tile_type[tag_prefix])
for cell_type in bel.valid_cells:
self.tile_constraints.add_cell_placement_constraint(
cell_type=cell_type,
site_index=bel.site_index,
site_type=site.site_type_name,
bel=bel.name,
tag='type_of_site{:03d}'.format(
self.sites[bel.site_index].site_in_type_index),
constraint=ImpliesConstraint(
tag=None,
state=site.site_type_name,
matchers=None,
port=None))
for tag, constraint in constraints.yield_constraints_for_cell_type_at_placement(
cell_type, placement):
self.tile_constraints.add_cell_placement_constraint(
cell_type=cell_type,
site_index=bel.site_index,
site_type=site.site_type_name,
bel=bel.name,
tag=tag,
constraint=constraint)
def add_wire(self, wire):
wire_index = len(self.wires)
self.wires.append(wire)
return wire_index
def add_pip_common(self, flat_pip):
pip_index = len(self.pips)
self.pips.append(flat_pip)
self.wires[flat_pip.src_index].pips_downhill.append(pip_index)
self.wires[flat_pip.dst_index].pips_uphill.append(pip_index)
def add_tile_pip(self, tile_pip_index, src_wire, dst_wire):
assert self.wires[src_wire].type == FlattenedWireType.TILE_WIRE
assert self.wires[dst_wire].type == FlattenedWireType.TILE_WIRE
flat_pip = FlattenedPip(
type=FlattenedPipType.TILE_PIP,
src_index=src_wire,
dst_index=dst_wire,
site_index=None,
pip_index=tile_pip_index)
self.add_pip_common(flat_pip)
def add_site_type(self,
device,
site_type_in_tile_type,
site_in_type_index,
site_type_index,
site_variant,
cell_bel_mapper,
primary_site_type=None):
if site_variant == -1:
assert primary_site_type is None
else:
assert primary_site_type is not None
site_index = len(self.sites)
bel_to_bel_index = {}
bel_pin_to_site_wire_index = {}
bel_pin_index_to_bel_index = {}
site_type = device.device_resource_capnp.siteTypeList[site_type_index]
site_type_name = device.strs[site_type.name]
self.sites.append(
FlattenedSite(
site_in_type_index=site_in_type_index,
site_type_index=site_type_index,
site_type=site_type,
site_type_name=site_type_name,
site_variant=site_variant,
bel_to_bel_index=bel_to_bel_index,
bel_pin_to_site_wire_index=bel_pin_to_site_wire_index,
bel_pin_index_to_bel_index=bel_pin_index_to_bel_index))
for idx, site_wire in enumerate(site_type.siteWires):
wire_name = device.strs[site_wire.name]
flat_wire = FlattenedWire(
type=FlattenedWireType.SITE_WIRE,
name=wire_name,
wire_index=idx,
site_index=site_index)
site_wire_index = self.add_wire(flat_wire)
for pin in site_wire.pins:
assert pin not in bel_pin_to_site_wire_index
bel_pin_to_site_wire_index[pin] = site_wire_index
for bel_idx, bel in enumerate(site_type.bels):
if bel.category == 'logic':
bel_category = BelCategory.LOGIC
elif bel.category == 'routing':
bel_category = BelCategory.ROUTING
else:
assert bel.category == 'sitePort', bel.category
bel_category = BelCategory.SITE_PORT
flat_bel = FlattenedBel(
name=device.strs[bel.name],
type=device.strs[bel.type],
site_index=site_index,
bel_index=bel_idx,
bel_category=bel_category)
bel_index = len(self.bels)
bel_to_bel_index[bel_idx] = bel_index
self.bels.append(flat_bel)
bel_key = site_type_name, flat_bel.name
for cell in cell_bel_mapper.get_cells():
if bel_key in cell_bel_mapper.bels_for_cell(cell):
flat_bel.valid_cells.add(cell)
for pin_idx, pin in enumerate(bel.pins):
assert pin not in bel_pin_index_to_bel_index
bel_pin_index_to_bel_index[pin] = bel_idx, pin_idx
bel_pin = site_type.belPins[pin]
wire_idx = bel_pin_to_site_wire_index.get(pin, -1)
flat_bel.add_port(device, bel_pin, wire_idx)
if wire_idx != -1:
self.wires[wire_idx].bel_pins.append(
(bel_index, device.strs[bel_pin.name]))
for idx, site_pip in enumerate(site_type.sitePIPs):
src_bel_pin = site_pip.inpin
bel_idx, src_pin_idx = bel_pin_index_to_bel_index[src_bel_pin]
src_site_wire_idx = bel_pin_to_site_wire_index[src_bel_pin]
dst_bel_pin = site_pip.outpin
dst_site_wire_idx = bel_pin_to_site_wire_index[dst_bel_pin]
self.add_site_pip(src_site_wire_idx, dst_site_wire_idx, site_index,
idx)
for idx, site_pin in enumerate(site_type.pins):
# the edge.
if site_pin.belpin not in bel_pin_to_site_wire_index:
continue
site_wire = bel_pin_to_site_wire_index[site_pin.belpin]
if site_variant != -1:
# This is an alternative site, map to primary pin first
parent_pins = site_type_in_tile_type.altPinsToPrimaryPins[
site_variant]
primary_idx = parent_pins.pins[idx]
else:
# This is the primary site, directly lookup site tile wire.
primary_idx = idx
tile_wire_name = device.strs[site_type_in_tile_type.
primaryPinsToTileWires[primary_idx]]
tile_wire = self.tile_wire_to_wire_in_tile_index[tile_wire_name]
if site_pin.dir == 'input':
# Input site pins connect tile wires to site wires
src_wire = tile_wire
dst_wire = site_wire
else:
assert site_pin.dir == 'output'
# Output site pins connect site wires to tile wires
src_wire = site_wire
dst_wire = tile_wire
self.add_site_pin(src_wire, dst_wire, site_index, idx)
def add_site_pip(self, src_wire, dst_wire, site_index, site_pip_index):
assert self.wires[src_wire].type == FlattenedWireType.SITE_WIRE
assert self.wires[dst_wire].type == FlattenedWireType.SITE_WIRE
flat_pip = FlattenedPip(
type=FlattenedPipType.SITE_PIP,
src_index=src_wire,
dst_index=dst_wire,
site_index=site_index,
pip_index=site_pip_index)
self.add_pip_common(flat_pip)
def add_site_pin(self, src_wire, dst_wire, site_index, site_pin_index):
if self.wires[src_wire].type == FlattenedWireType.SITE_WIRE:
assert self.wires[dst_wire].type == FlattenedWireType.TILE_WIRE
else:
assert self.wires[src_wire].type == FlattenedWireType.TILE_WIRE
assert self.wires[dst_wire].type == FlattenedWireType.SITE_WIRE
flat_pip = FlattenedPip(
type=FlattenedPipType.SITE_PIN,
src_index=src_wire,
dst_index=dst_wire,
site_index=site_index,
pip_index=site_pin_index)
self.add_pip_common(flat_pip)
def remap_bel_indicies(self):
# Put logic BELs first before routing and site ports.
self.bel_index_remap = {}
self.bel_output_map = {}
for output_bel_idx, (bel_idx, _) in enumerate(
sorted(
enumerate(self.bels),
key=lambda value: (value[1].bel_category.value, value[0]))
):
self.bel_index_remap[bel_idx] = output_bel_idx
self.bel_output_map[output_bel_idx] = bel_idx
def create_tile_type_info(self, cell_bel_mapper):
tile_type = TileTypeInfo()
tile_type.name = self.tile_type_name
bels_used = set()
for bel_index in range(len(self.bels)):
mapped_idx = self.bel_output_map[bel_index]
assert mapped_idx not in bels_used
bels_used.add(mapped_idx)
bel = self.bels[mapped_idx]
bel_info = BelInfo()
bel_info.name = bel.name
bel_info.type = bel.type
for port in bel.ports:
bel_info.ports.append(port.port)
bel_info.types.append(port.type.value)
bel_info.wires.append(port.wire)
bel_info.site = bel.site_index
bel_info.site_variant = self.sites[bel.site_index].site_variant
bel_info.bel_category = bel.bel_category.value
site_type = self.sites[bel.site_index].site_type_name
bel_key = (site_type, bel.name)
bel_info.bel_bucket = cell_bel_mapper.bel_to_bel_bucket(*bel_key)
if bel.bel_category == BelCategory.LOGIC:
# Don't need pin_map for routing / site ports.
bel_info.pin_map = [-1 for _ in cell_bel_mapper.get_cells()]
for idx, cell in enumerate(cell_bel_mapper.get_cells()):
bel_info.pin_map[
idx] = cell_bel_mapper.get_cell_bel_map_index(
cell, tile_type.name, bel.site_index, site_type,
bel.name)
tile_type.bel_data.append(bel_info)
assert len(bels_used) == len(self.bel_output_map)
assert len(bels_used) == len(self.bel_index_remap)
for wire in self.wires:
wire_info = TileWireInfo()
wire_info.name = wire.name
wire_info.pips_uphill = wire.pips_uphill
wire_info.pips_downhill = wire.pips_downhill
for (bel_index, port) in wire.bel_pins:
bel_port = BelPort()
bel_port.bel_index = self.bel_index_remap[bel_index]
bel_port.port = port
wire_info.bel_pins.append(bel_port)
if wire.site_index is not None:
wire_info.site = wire.site_index
wire_info.site_variant = self.sites[wire.
site_index].site_variant
else:
wire_info.site = -1
wire_info.site_variant = -1
tile_type.wire_data.append(wire_info)
for pip in self.pips:
pip_info = PipInfo()
pip_info.src_index = pip.src_index
pip_info.dst_index = pip.dst_index
if pip.site_index is not None:
site = self.sites[pip.site_index]
site_type = site.site_type
pip_info.site = pip.site_index
pip_info.site_variant = site.site_variant
if pip.type == FlattenedPipType.SITE_PIP:
site_pip = site_type.sitePIPs[pip.pip_index]
bel_idx, pin_idx = site.bel_pin_index_to_bel_index[
site_pip.inpin]
orig_bel_index = site.bel_to_bel_index[bel_idx]
expected_category = self.bels[orig_bel_index].bel_category
assert expected_category in [
BelCategory.ROUTING, BelCategory.LOGIC
]
pip_info.bel = self.bel_index_remap[orig_bel_index]
assert tile_type.bel_data[
pip_info.bel].bel_category == expected_category.value
pip_info.extra_data = pin_idx
else:
assert pip.type == FlattenedPipType.SITE_PIN
site_pin = site_type.pins[pip.pip_index]
bel_idx, pin_idx = site.bel_pin_index_to_bel_index[
site_pin.belpin]
pip_info.bel = self.bel_index_remap[
site.bel_to_bel_index[bel_idx]]
pip_info.extra_data = pin_idx
assert tile_type.bel_data[
pip_info.
bel].bel_category == BelCategory.SITE_PORT.value
else:
assert pip.type == FlattenedPipType.TILE_PIP
pip_info.site = -1
pip_info.site_variant = -1
tile_type.pip_data.append(pip_info)
emit_constraints(tile_type, self.tile_constraints, cell_bel_mapper)
for site in self.sites:
tile_type.site_types.append(site.site_type_name)
return tile_type
class CellBelMapper():
def __init__(self, device, constids):
self.cells_in_order = []
self.cell_names = {}
self.bel_buckets = set()
self.cell_to_bel_buckets = {}
self.cell_to_bel_common_pins = {}
self.cell_to_bel_parameter_pins = {}
self.cell_site_bel_index = {}
self.cell_to_bel_constraints = {}
self.bel_to_bel_buckets = {}
for cell_bel_map in device.device_resource_capnp.cellBelMap:
cell_name = device.strs[cell_bel_map.cell]
self.cells_in_order.append(cell_name)
self.cell_names[cell_name] = constids.get_index(cell_name)
self.min_cell_index = min(self.cell_names.values())
self.max_cell_index = max(self.cell_names.values())
assert (self.max_cell_index - self.min_cell_index + 1) == len(
self.cell_names)
for cell_name in self.cell_names.keys():
cell_index = self.cell_names[cell_name] - self.min_cell_index
self.cell_names[cell_name] = cell_index
assert self.cells_in_order[cell_index] == cell_name
self.cell_to_bel_map = {}
for cell_bel_map in device.device_resource_capnp.cellBelMap:
cell_type = device.strs[cell_bel_map.cell]
assert cell_type in self.cell_names
bels = set()
for common_pin in cell_bel_map.commonPins:
pins = []
for pin in common_pin.pins:
pins.append((device.strs[pin.cellPin],
device.strs[pin.belPin]))
for site_types_and_bels in common_pin.siteTypes:
site_type = device.strs[site_types_and_bels.siteType]
for bel_str_id in site_types_and_bels.bels:
bel = device.strs[bel_str_id]
bels.add((site_type, bel))
key = (cell_type, site_type, bel)
assert key not in self.cell_to_bel_common_pins
self.cell_to_bel_common_pins[key] = pins
for parameter_pin in cell_bel_map.parameterPins:
pins = []
for pin in parameter_pin.pins:
pins.append((device.strs[pin.cellPin],
device.strs[pin.belPin]))
for parameter in parameter_pin.parametersSiteTypes:
param_key = device.strs[parameter.parameter.key]
which = parameter.parameter.which()
assert which == 'textValue'
param_value = device.strs[parameter.parameter.textValue]
bel = device.strs[parameter.bel]
site_type = device.strs[parameter.siteType]
bels.add((site_type, bel))
key = cell_type, site_type, bel
if key not in self.cell_to_bel_parameter_pins:
self.cell_to_bel_parameter_pins[key] = {}
assert (param_key, param_value
) not in self.cell_to_bel_parameter_pins[key]
self.cell_to_bel_parameter_pins[key][(param_key,
param_value)] = pins
self.cell_to_bel_map[cell_type] = bels
self.bels = set()
for site_type in device.device_resource_capnp.siteTypeList:
for bel in site_type.bels:
self.bels.add((device.strs[site_type.name],
device.strs[bel.name]))
def get_cell_bel_map_index(self, cell_type, tile_type, site_index,
site_type, bel):
if cell_type not in self.cell_to_bel_map:
return -1
if (site_type, bel) not in self.cell_to_bel_map[cell_type]:
return -1
key = cell_type, tile_type, site_index, site_type, bel
if key not in self.cell_site_bel_index:
index = len(self.cell_site_bel_index)
self.cell_site_bel_index[key] = index
return self.cell_site_bel_index[key]
def make_bel_bucket(self, bel_bucket_name, cell_names):
assert bel_bucket_name not in self.bel_buckets
bels_in_bucket = set()
cells_in_bucket = set(cell_names)
while True:
pre_loop_counts = (len(bels_in_bucket), len(cells_in_bucket))
for cell_name in cells_in_bucket:
bels_in_bucket |= self.cell_to_bel_map[cell_name]
for bel in bels_in_bucket:
for cell, bels in self.cell_to_bel_map.items():
if bel in bels:
cells_in_bucket.add(cell)
post_loop_counts = (len(bels_in_bucket), len(cells_in_bucket))
if pre_loop_counts == post_loop_counts:
break
assert bel_bucket_name not in self.bel_buckets
self.bel_buckets.add(bel_bucket_name)
for cell in cells_in_bucket:
assert cell not in self.cell_to_bel_buckets, (bel_bucket_name,
cell)
self.cell_to_bel_buckets[cell] = bel_bucket_name
for bel in bels_in_bucket:
self.bel_to_bel_buckets[bel] = bel_bucket_name
def handle_remaining(self):
remaining_cells = set(self.cell_names.keys()) - set(
self.cell_to_bel_buckets.keys())
for cell in sorted(remaining_cells):
self.make_bel_bucket(cell, [cell])
remaining_bels = set(self.bels)
for bels in self.cell_to_bel_map.values():
remaining_bels -= bels
bel_bucket_name = 'UNPLACABLE_BELS'
assert bel_bucket_name not in self.bel_buckets
self.bel_buckets.add(bel_bucket_name)
for site_type, bel in remaining_bels:
self.bel_to_bel_buckets[site_type, bel] = bel_bucket_name
bel_bucket_name = 'IOPORTS'
assert bel_bucket_name not in self.bel_buckets
self.bel_buckets.add(bel_bucket_name)
def get_cells(self):
return self.cells_in_order
def get_cell_constids(self):
return range(self.min_cell_index, self.max_cell_index + 1)
def get_cell_index(self, cell_name):
return self.cell_names[cell_name]
def get_bel_buckets(self):
return self.bel_buckets
def cell_to_bel_bucket(self, cell_name):
return self.cell_to_bel_buckets[cell_name]
def get_bels(self):
return self.bel_to_bel_buckets.keys()
def bel_to_bel_bucket(self, site_type, bel):
return self.bel_to_bel_buckets[(site_type, bel)]
def bels_for_cell(self, cell):
return self.cell_to_bel_map[cell]
DEBUG_BEL_BUCKETS = False
def print_bel_buckets(cell_bel_mapper):
print('BEL buckets:')
for bel_bucket in cell_bel_mapper.get_bel_buckets():
print(' - {}'.format(bel_bucket))
print('')
print('Cell -> BEL bucket:')
for cell in sorted(
cell_bel_mapper.get_cells(),
key=lambda cell: (cell_bel_mapper.cell_to_bel_bucket(cell), cell)):
print(' - {} => {}'.format(cell,
cell_bel_mapper.cell_to_bel_bucket(cell)))
print('')
print('BEL -> BEL bucket:')
for site_type, bel in sorted(
cell_bel_mapper.get_bels(),
key=lambda key: (cell_bel_mapper.bel_to_bel_bucket(*key), *key)):
print(' - {}/{} => {}'.format(
site_type, bel, cell_bel_mapper.bel_to_bel_bucket(site_type, bel)))
class ConstantNetworkGenerator():
def __init__(self, device, chip_info, cell_bel_mapper):
self.device = device
self.chip_info = chip_info
self.constants = chip_info.constants
self.cell_bel_mapper = cell_bel_mapper
self.site_type = '$CONSTANTS'
self.site_name = '$CONSTANTS_X0Y0'
self.tile_type_name = '$CONSTANTS'
self.tile_name = '$CONSTANTS_X0Y0'
self.tile_type, gnd_bel, vcc_bel = self.create_initial_bels()
self.gnd_node_wire, self.vcc_node_wire = self.initialize_constant_network(
self.tile_type, gnd_bel, vcc_bel)
def create_initial_bels(self):
consts = self.device.get_constants()
self.constants.gnd_cell_name = consts.GND_CELL_TYPE
self.constants.gnd_cell_port = consts.GND_PORT
self.constants.vcc_cell_name = consts.VCC_CELL_TYPE
self.constants.vcc_cell_port = consts.VCC_PORT
self.constants.gnd_bel_index = 0
self.constants.gnd_bel_pin = self.constants.gnd_cell_port
self.constants.vcc_bel_index = 1
self.constants.vcc_bel_pin = self.constants.vcc_cell_port
self.constants.gnd_net_name = consts.GND_NET
self.constants.vcc_net_name = consts.VCC_NET
tile_type = TileTypeInfo()
self.tile_type_index = len(self.chip_info.tile_types)
self.chip_info.tile_types.append(tile_type)
tile_type.site_types.append(self.site_type)
self.cell_bel_mapper.cell_to_bel_map[
self.constants.gnd_cell_name] = set(
((self.site_type, self.constants.gnd_cell_name), ))
self.cell_bel_mapper.cell_to_bel_map[
self.constants.vcc_cell_name] = set(
((self.site_type, self.constants.vcc_cell_name), ))
gnd_bel = BelInfo()
gnd_bel.name = self.constants.gnd_cell_name
gnd_bel.type = self.constants.gnd_cell_name
gnd_bel.bel_bucket = self.cell_bel_mapper.cell_to_bel_bucket(
self.constants.gnd_cell_name)
gnd_bel.ports.append(self.constants.gnd_cell_port)
gnd_bel.types.append(PortType.PORT_OUT)
gnd_bel.wires.append(0)
gnd_bel.site = 0
gnd_bel.site_variant = -1
gnd_bel.bel_category = BelCategory.LOGIC.value
gnd_bel.synthetic = 1
gnd_bel.pin_map = [-1 for _ in self.cell_bel_mapper.get_cells()]
gnd_cell_idx = self.cell_bel_mapper.get_cell_index(
self.constants.gnd_cell_name)
gnd_bel.pin_map[
gnd_cell_idx] = self.cell_bel_mapper.get_cell_bel_map_index(
cell_type=self.constants.gnd_cell_name,
tile_type=self.tile_type_name,
site_index=0,
site_type=self.site_type,
bel=gnd_bel.name)
assert gnd_bel.pin_map[gnd_cell_idx] != -1
assert len(tile_type.bel_data) == self.constants.gnd_bel_index
tile_type.bel_data.append(gnd_bel)
vcc_bel = BelInfo()
vcc_bel.name = self.constants.vcc_cell_name
vcc_bel.type = self.constants.vcc_cell_name
vcc_bel.bel_bucket = self.cell_bel_mapper.cell_to_bel_bucket(
self.constants.vcc_cell_name)
vcc_bel.ports.append(self.constants.vcc_cell_port)
vcc_bel.types.append(PortType.PORT_OUT)
vcc_bel.wires.append(1)
vcc_bel.site = 0
vcc_bel.site_variant = -1
vcc_bel.bel_category = BelCategory.LOGIC.value
vcc_bel.synthetic = 1
vcc_bel.pin_map = [-1 for _ in self.cell_bel_mapper.get_cells()]
vcc_cell_idx = self.cell_bel_mapper.get_cell_index(
self.constants.vcc_cell_name)
vcc_bel.pin_map[
vcc_cell_idx] = self.cell_bel_mapper.get_cell_bel_map_index(
cell_type=self.constants.vcc_cell_name,
tile_type=self.tile_type_name,
site_index=0,
site_type=self.site_type,
bel=vcc_bel.name)
assert vcc_bel.pin_map[vcc_cell_idx] != -1
assert len(tile_type.bel_data) == self.constants.vcc_bel_index
tile_type.bel_data.append(vcc_bel)
self.cell_bel_mapper.bels.add((self.site_name, gnd_bel.name))
self.cell_bel_mapper.bels.add((self.site_name, vcc_bel.name))
key = (self.constants.gnd_cell_name, self.site_type, gnd_bel.name)
self.cell_bel_mapper.cell_to_bel_common_pins[key] = ((
self.constants.gnd_cell_port, self.constants.gnd_cell_port), )
key = (self.constants.vcc_cell_name, self.site_type, vcc_bel.name)
self.cell_bel_mapper.cell_to_bel_common_pins[key] = ((
self.constants.vcc_cell_port, self.constants.vcc_cell_port), )
tile_type.name = self.tile_type_name
return tile_type, gnd_bel, vcc_bel
def initialize_constant_network(self, tile_type, gnd_bel, vcc_bel):
gnd_wire = TileWireInfo()
assert len(tile_type.wire_data) == gnd_bel.wires[0]
tile_type.wire_data.append(gnd_wire)
gnd_wire.name = '$GND_SOURCE'
gnd_wire.site = 0
gnd_wire.site_variant = -1
gnd_wire_bel_port = BelPort()
gnd_wire_bel_port.bel_index = self.constants.gnd_bel_index
gnd_wire_bel_port.port = gnd_bel.ports[0]
gnd_wire.bel_pins.append(gnd_wire_bel_port)
vcc_wire = TileWireInfo()
assert len(tile_type.wire_data) == vcc_bel.wires[0]
tile_type.wire_data.append(vcc_wire)
vcc_wire.name = '$VCC_SOURCE'
vcc_wire.site = 0
vcc_wire.site_variant = -1
vcc_wire_bel_port = BelPort()
vcc_wire_bel_port.bel_index = self.constants.vcc_bel_index
vcc_wire_bel_port.port = vcc_bel.ports[0]
vcc_wire.bel_pins.append(vcc_wire_bel_port)
gnd_site_port = PipInfo()
gnd_site_port_pip_idx = len(tile_type.pip_data)
tile_type.pip_data.append(gnd_site_port)
gnd_site_port.site = 0
gnd_site_port.site_variant = -1
gnd_site_port.extra_data = 0
gnd_site_port.src_index = gnd_bel.wires[0]
gnd_site_port.dst_index = len(tile_type.wire_data)
gnd_node_wire = TileWireInfo()
tile_type.wire_data.append(gnd_node_wire)
gnd_wire.pips_downhill.append(gnd_site_port_pip_idx)
gnd_node_wire.pips_uphill.append(gnd_site_port_pip_idx)
gnd_node_wire.name = '$GND_NODE'
gnd_node_wire.site = -1
gnd_site_port.bel = len(tile_type.bel_data)
gnd_site_port_bel = BelInfo()
tile_type.bel_data.append(gnd_site_port_bel)
gnd_site_port_bel.name = '$GND'
gnd_site_port_bel.type = 'NA'
gnd_site_port_bel.bel_bucket = 'UNPLACABLE_BELS'
gnd_site_port_bel.ports.append(gnd_site_port_bel.name)
gnd_site_port_bel.types.append(PortType.PORT_IN.value)
gnd_site_port_bel.wires.append(gnd_bel.wires[0])
gnd_site_port_bel.site = 0
gnd_site_port_bel.site_variant = -1
gnd_site_port_bel.bel_category = BelCategory.SITE_PORT.value
gnd_site_port_bel.synthetic = 1
gnd_site_port_bel_port = BelPort()
gnd_site_port_bel_port.bel_index = gnd_site_port.bel
gnd_site_port_bel_port.port = gnd_site_port_bel.name
gnd_wire.bel_pins.append(gnd_site_port_bel_port)
vcc_site_port = PipInfo()
vcc_site_port_pip_idx = len(tile_type.pip_data)
tile_type.pip_data.append(vcc_site_port)
vcc_site_port.site = 0
vcc_site_port.site_variant = -1
vcc_site_port.extra_data = 0
vcc_site_port.src_index = vcc_bel.wires[0]
vcc_site_port.dst_index = len(tile_type.wire_data)
vcc_node_wire = TileWireInfo()
tile_type.wire_data.append(vcc_node_wire)
vcc_wire.pips_downhill.append(vcc_site_port_pip_idx)
vcc_node_wire.pips_uphill.append(vcc_site_port_pip_idx)
vcc_node_wire.name = '$VCC_NODE'
vcc_node_wire.site = -1
vcc_site_port.bel = len(tile_type.bel_data)
vcc_site_port_bel = BelInfo()
tile_type.bel_data.append(vcc_site_port_bel)
vcc_site_port_bel.name = '$VCC'
vcc_site_port_bel.type = 'NA'
vcc_site_port_bel.bel_bucket = 'UNPLACABLE_BELS'
vcc_site_port_bel.ports.append(vcc_site_port_bel.name)
vcc_site_port_bel.types.append(PortType.PORT_IN.value)
vcc_site_port_bel.wires.append(vcc_bel.wires[0])
vcc_site_port_bel.site = 0
vcc_site_port_bel.site_variant = -1
vcc_site_port_bel.bel_category = BelCategory.SITE_PORT.value
vcc_site_port_bel.synthetic = 1
vcc_site_port_bel_port = BelPort()
vcc_site_port_bel_port.bel_index = vcc_site_port.bel
vcc_site_port_bel_port.port = vcc_site_port_bel.name
vcc_wire.bel_pins.append(vcc_site_port_bel_port)
return (gnd_site_port.dst_index, vcc_site_port.dst_index)
def populate_constant_network(self):
device = self.device
tile_idx = 0
tile_type_name = self.chip_info.tile_types[self.chip_info.
tiles[tile_idx].type].name
assert tile_type_name == 'NULL', tile_type_name
self.constants.gnd_bel_tile = tile_idx
self.constants.vcc_bel_tile = tile_idx
self.chip_info.tiles[tile_idx].name = self.tile_name
self.chip_info.tiles[tile_idx].type = self.tile_type_index
self.chip_info.tiles[tile_idx].sites = [len(self.chip_info.sites)]
site_inst = SiteInstInfo()
self.chip_info.sites.append(site_inst)
site_inst.name = '{}.{}'.format(self.site_name, self.site_type)
site_inst.site_name = self.site_name
site_inst.site_type = self.site_type
self.chip_info.tiles[tile_idx].tile_wire_to_node = [
-1 for _ in range(len(self.tile_type.wire_data))
]
gnd_node_idx = len(self.chip_info.nodes)
self.chip_info.tiles[tile_idx].tile_wire_to_node[
self.gnd_node_wire] = gnd_node_idx
gnd_node = NodeInfo()
self.chip_info.nodes.append(gnd_node)
gnd_node.name = 'gnd_node'
gnd_node_ref = TileWireRef()
gnd_node.tile_wires.append(gnd_node_ref)
gnd_node_ref.tile = tile_idx
gnd_node_ref.index = self.gnd_node_wire
vcc_node_idx = len(self.chip_info.nodes)
self.chip_info.tiles[tile_idx].tile_wire_to_node[
self.vcc_node_wire] = vcc_node_idx
vcc_node = NodeInfo()
self.chip_info.nodes.append(vcc_node)
vcc_node.name = 'vcc_node'
vcc_node_ref = TileWireRef()
vcc_node.tile_wires.append(vcc_node_ref)
vcc_node_ref.tile = tile_idx
vcc_node_ref.index = self.vcc_node_wire
bel_pins_connected_to_gnd = set()
bel_pins_connected_to_vcc = set()
site_types_with_gnd = set()
site_types_with_vcc = set()
for site_source in device.device_resource_capnp.constants.siteSources:
site_type = device.strs[site_source.siteType]
bel = device.strs[site_source.bel]
bel_pin = device.strs[site_source.belPin]
if site_source.constant == 'gnd':
site_types_with_gnd.add(site_type)
bel_pins_connected_to_gnd.add((site_type, bel, bel_pin))
elif site_source.constant == 'vcc':
site_types_with_vcc.add(site_type)
bel_pins_connected_to_vcc.add((site_type, bel, bel_pin))
else:
assert False, site_source.constant
tile_types_with_gnd = set()
tile_types_with_vcc = set()
for tile_type_idx, tile_type in enumerate(self.chip_info.tile_types):
if tile_type_idx == self.tile_type_index:
continue
tile_type_data = device.device_resource_capnp.tileTypeList[
tile_type_idx]
assert device.strs[tile_type_data.name] == tile_type.name
for wire_constant in tile_type_data.constants:
if wire_constant.constant == 'gnd':
tile_types_with_gnd.add(tile_type_idx)
elif wire_constant.constant == 'vcc':
tile_types_with_vcc.add(tile_type_idx)
else:
assert False, wire_constant.constant
for site_in_tile_type in tile_type_data.siteTypes:
site_type = device.device_resource_capnp.siteTypeList[
site_in_tile_type.primaryType]
site_type_name = device.strs[site_type.name]
if site_type_name in site_types_with_gnd:
tile_types_with_gnd.add(tile_type_idx)
if site_type_name in site_types_with_vcc:
tile_types_with_vcc.add(tile_type_idx)
for alt_site_type_idx in site_type.altSiteTypes:
alt_site_type = device.device_resource_capnp.siteTypeList[
alt_site_type_idx]
site_type_name = device.strs[alt_site_type.name]
if site_type_name in site_types_with_gnd:
tile_types_with_gnd.add(tile_type_idx)
if site_type_name in site_types_with_vcc:
tile_types_with_vcc.add(tile_type_idx)
tile_type_gnd_wires = {}
for tile_type_idx in tile_types_with_gnd:
tile_type = self.chip_info.tile_types[tile_type_idx]
gnd_wire_idx = len(tile_type.wire_data)
gnd_wire = TileWireInfo()
tile_type.wire_data.append(gnd_wire)
gnd_wire.name = '$GND_WIRE'
gnd_wire.site = -1
tile_type_gnd_wires[tile_type_idx] = gnd_wire_idx
for tile_idx, tile in enumerate(self.chip_info.tiles):
if tile.type not in tile_types_with_gnd:
continue
gnd_wire_idx = tile_type_gnd_wires[tile.type]
assert gnd_wire_idx >= len(
tile.tile_wire_to_node), (gnd_wire_idx,
len(tile.tile_wire_to_node),
len(tile_type.wire_data))
while gnd_wire_idx > len(tile.tile_wire_to_node):
tile.tile_wire_to_node.append(-1)
tile.tile_wire_to_node.append(gnd_node_idx)
wire_ref = TileWireRef()
wire_ref.tile = tile_idx
wire_ref.index = gnd_wire_idx
gnd_node.tile_wires.append(wire_ref)
tile_type_vcc_wires = {}
for tile_type_idx in tile_types_with_vcc:
tile_type = self.chip_info.tile_types[tile_type_idx]
vcc_wire_idx = len(tile_type.wire_data)
vcc_wire = TileWireInfo()
tile_type.wire_data.append(vcc_wire)
vcc_wire.name = '$VCC_WIRE'
vcc_wire.site = -1
tile_type_vcc_wires[tile_type_idx] = vcc_wire_idx
for tile_idx, tile in enumerate(self.chip_info.tiles):
if tile.type not in tile_types_with_vcc:
continue
vcc_wire_idx = tile_type_vcc_wires[tile.type]
assert vcc_wire_idx >= len(tile.tile_wire_to_node)
while vcc_wire_idx > len(tile.tile_wire_to_node):
tile.tile_wire_to_node.append(-1)
tile.tile_wire_to_node.append(vcc_node_idx)
wire_ref = TileWireRef()
wire_ref.tile = tile_idx
wire_ref.index = vcc_wire_idx
vcc_node.tile_wires.append(wire_ref)
for tile_type_idx in (tile_types_with_gnd | tile_types_with_vcc):
gnd_wire_idx = tile_type_gnd_wires.get(tile_type_idx, None)
vcc_wire_idx = tile_type_vcc_wires.get(tile_type_idx, None)
self.connect_tile_type(tile_type_idx, gnd_wire_idx, vcc_wire_idx,
bel_pins_connected_to_gnd,
bel_pins_connected_to_vcc)
# import them right now.
def connect_tile_type(self, tile_type_idx, gnd_wire_idx, vcc_wire_idx,
bel_pins_connected_to_gnd,
bel_pins_connected_to_vcc):
device = self.device
tile_type = self.chip_info.tile_types[tile_type_idx]
tile_type_data = self.device.device_resource_capnp.tileTypeList[
tile_type_idx]
assert device.strs[tile_type_data.name] == tile_type.name
gnd_site_wires = {}
vcc_site_wires = {}
for bel_info in tile_type.bel_data:
site_type = tile_type.site_types[bel_info.site]
for bel_pin_idx, bel_pin in enumerate(bel_info.ports):
wire_idx = bel_info.wires[bel_pin_idx]
if wire_idx == -1:
continue
key = (site_type, bel_info.name, bel_pin)
src_wire_idx = None
if key in bel_pins_connected_to_gnd:
assert key not in bel_pins_connected_to_vcc
gnd_site_wire_idx = gnd_site_wires.get(bel_info.site, None)
if gnd_site_wire_idx is None:
gnd_site_wire_idx = self.build_input_site_port(
tile_type_idx=tile_type_idx,
port_name='$GND',
site_wire_name='$GND_SITE_WIRE',
tile_wire_idx=gnd_wire_idx,
site=bel_info.site,
site_variant=bel_info.site_variant)
gnd_site_wires[bel_info.site] = gnd_site_wire_idx
src_wire_idx = gnd_site_wire_idx
elif key in bel_pins_connected_to_vcc:
assert key not in bel_pins_connected_to_gnd
vcc_site_wire_idx = vcc_site_wires.get(bel_info.site, None)
if vcc_site_wire_idx is None:
vcc_site_wire_idx = self.build_input_site_port(
tile_type_idx=tile_type_idx,
port_name='$VCC',
site_wire_name='$VCC_SITE_WIRE',
tile_wire_idx=vcc_wire_idx,
site=bel_info.site,
site_variant=bel_info.site_variant)
vcc_site_wires[bel_info.site] = vcc_site_wire_idx
src_wire_idx = vcc_site_wire_idx
else:
continue
# Create pip connecting constant network to site wire source.
edge = PipInfo()
edge.site = bel_info.site
edge.site_variant = bel_info.site_variant
edge_idx = len(tile_type.pip_data)
tile_type.pip_data.append(edge)
assert src_wire_idx is not None
edge.src_index = src_wire_idx
edge.dst_index = wire_idx
edge.bel = len(tile_type.bel_data)
# Create site PIP BEL for edge between constant network site
# wire and site wire source.
site_pip_bel = BelInfo()
tile_type.bel_data.append(site_pip_bel)
site_pip_bel.name = '{}_{}'.format(
bel_info.name, tile_type.wire_data[src_wire_idx].name)
site_pip_bel.type = 'NA'
site_pip_bel.ports.append(bel_info.name)
site_pip_bel.types.append(PortType.PORT_IN.value)
site_pip_bel.wires.append(src_wire_idx)
site_pip_bel.ports.append(
tile_type.wire_data[src_wire_idx].name)
site_pip_bel.types.append(PortType.PORT_OUT.value)
site_pip_bel.wires.append(wire_idx)
in_bel_port = BelPort()
in_bel_port.bel_index = edge.bel
in_bel_port.port = site_pip_bel.ports[0]
tile_type.wire_data[src_wire_idx].bel_pins.append(in_bel_port)
out_bel_port = BelPort()
out_bel_port.bel_index = edge.bel
out_bel_port.port = site_pip_bel.ports[1]
tile_type.wire_data[wire_idx].bel_pins.append(out_bel_port)
site_pip_bel.bel_bucket = 'UNPLACABLE_BELS'
site_pip_bel.site = bel_info.site
site_pip_bel.site_variant = bel_info.site_variant
site_pip_bel.bel_category = BelCategory.ROUTING.value
site_pip_bel.synthetic = 1
# Update wire data pointing to new pip.
tile_type.wire_data[src_wire_idx].pips_downhill.append(
edge_idx)
tile_type.wire_data[wire_idx].pips_uphill.append(edge_idx)
for wire_constant in tile_type_data.constants:
if wire_constant.constant == 'gnd':
src_wire_idx = gnd_wire_idx
elif wire_constant.constant == 'vcc':
src_wire_idx = vcc_wire_idx
else:
assert False, wire_constant.constant
assert src_wire_idx is not None
for wire_idx in wire_constant.wires:
wire_name = device.strs[tile_type_data.wires[wire_idx]]
assert tile_type.wire_data[wire_idx].name == wire_name, (
tile_type.wire_data[wire_idx].name, wire_name)
# Create pip connecting constant network to wire source.
edge = PipInfo()
edge.site = -1
edge_idx = len(tile_type.pip_data)
tile_type.pip_data.append(edge)
edge.src_index = src_wire_idx
edge.dst_index = wire_idx
edge.extra_data = -1
# Update wire data pointing to new pip.
tile_type.wire_data[src_wire_idx].pips_downhill.append(
edge_idx)
tile_type.wire_data[wire_idx].pips_uphill.append(edge_idx)
def build_input_site_port(self, tile_type_idx, port_name, site_wire_name,
tile_wire_idx, site, site_variant):
tile_type = self.chip_info.tile_types[tile_type_idx]
site_port_edge_idx = len(tile_type.pip_data)
site_port_edge = PipInfo()
tile_type.pip_data.append(site_port_edge)
site_port_bel_idx = len(tile_type.bel_data)
site_port_bel = BelInfo()
tile_type.bel_data.append(site_port_bel)
site_wire_idx = len(tile_type.wire_data)
site_wire = TileWireInfo()
tile_type.wire_data.append(site_wire)
site_port_edge.site = site
site_port_edge.site_variant = site_variant
site_port_edge.bel = site_port_bel_idx
site_port_edge.src_index = tile_wire_idx
tile_type.wire_data[tile_wire_idx].pips_downhill.append(
site_port_edge_idx)
site_port_edge.dst_index = site_wire_idx
site_wire.pips_uphill.append(site_port_edge_idx)
site_port_bel.name = port_name
site_port_bel.type = 'NA'
site_port_bel.bel_bucket = 'UNPLACABLE_BELS'
site_port_bel.ports.append(port_name)
site_port_bel.types.append(PortType.PORT_OUT.value)
site_port_bel.wires.append(site_wire_idx)
site_port_bel.site = site
site_port_bel.site_variant = site_variant
site_port_bel.bel_category = BelCategory.SITE_PORT.value
site_port_bel.synthetic = 1
site_wire.name = site_wire_name
site_wire_bel_port = BelPort()
site_wire.bel_pins.append(site_wire_bel_port)
site_wire.site = site
site_wire.site_variant = site_variant
site_wire_bel_port.bel_index = site_port_bel_idx
site_wire_bel_port.port = port_name
return site_wire_idx
def populate_chip_info(device, constids, bel_bucket_seeds):
assert len(constids.values) == 0
cell_bel_mapper = CellBelMapper(device, constids)
# Make the BEL buckets.
for bucket in bel_bucket_seeds:
bel_bucket = bucket['bucket']
cells = bucket['cells']
cell_bel_mapper.make_bel_bucket(bel_bucket, cells)
cell_bel_mapper.handle_remaining()
if DEBUG_BEL_BUCKETS:
print_bel_buckets(cell_bel_mapper)
chip_info = ChipInfo()
chip_info.name = device.device_resource_capnp.name
chip_info.generator = 'python-fpga-interchange v0.x'
chip_info.version = 1
# Emit cells in const ID order to build cell map.
for cell_name in cell_bel_mapper.get_cells():
chip_info.cell_map.add_cell(
cell_name, cell_bel_mapper.cell_to_bel_bucket(cell_name))
for bel_bucket in sorted(set(cell_bel_mapper.get_bel_buckets())):
chip_info.bel_buckets.append(bel_bucket)
tile_wire_to_wire_in_tile_index = []
num_tile_wires = []
constraints = device.get_constraints()
for tile_type_index, tile_type in enumerate(
device.device_resource_capnp.tileTypeList):
flattened_tile_type = FlattenedTileType(
device, tile_type_index, tile_type, cell_bel_mapper, constraints)
tile_type_info = flattened_tile_type.create_tile_type_info(
cell_bel_mapper)
chip_info.tile_types.append(tile_type_info)
# Create map of tile wires to wire in tile id.
per_tile_map = {}
for idx, wire in enumerate(tile_type_info.wire_data):
if wire.site != -1:
# Only care about tile wires!
break
assert wire.name not in per_tile_map
per_tile_map[wire.name] = idx
tile_wire_to_wire_in_tile_index.append(per_tile_map)
num_tile_wires.append(max(per_tile_map.values()) + 1)
constants = ConstantNetworkGenerator(device, chip_info, cell_bel_mapper)
# Emit cell bel pin map.
for key, idx in sorted(
cell_bel_mapper.cell_site_bel_index.items(),
key=lambda item: item[1]):
cell_type, tile_type, site_index, site_type, bel = key
cell_bel_map = CellBelMap(cell_type, tile_type, site_index, bel)
chip_info.cell_map.cell_bel_map.append(cell_bel_map)
pin_key = (cell_type, site_type, bel)
if pin_key in cell_bel_mapper.cell_to_bel_common_pins:
for (cell_pin,
bel_pin) in cell_bel_mapper.cell_to_bel_common_pins[pin_key]:
cell_bel_map.common_pins.append(CellBelPin(cell_pin, bel_pin))
if pin_key in cell_bel_mapper.cell_to_bel_parameter_pins:
for (param_key, param_value
), pins in cell_bel_mapper.cell_to_bel_parameter_pins[
pin_key].items():
parameter = ParameterPins()
parameter.key = param_key
parameter.value = param_value
for (cell_pin, bel_pin) in pins:
cell_bel_map.parameter_pins.append(
CellBelPin(cell_pin, bel_pin))
cell_bel_map.parameter_pins.append(parameter)
cell_bel_map = chip_info.cell_map.cell_bel_map[idx]
if idx in cell_bel_mapper.cell_to_bel_constraints:
cell_bel_map.constraints = cell_bel_mapper.cell_to_bel_constraints[
idx]
tiles = {}
tile_name_to_tile_index = {}
for tile_index, tile in enumerate(device.device_resource_capnp.tileList):
tile_info = TileInstInfo()
tile_info.name = device.strs[tile.name]
tile_info.type = tile.type
tile_info.tile_wire_to_node = list(
[-1 for _ in range(num_tile_wires[tile.type])])
tile_type = device.device_resource_capnp.tileTypeList[tile.type]
for site_type_in_tile_type, site in zip(tile_type.siteTypes,
tile.sites):
site_name = device.strs[site.name]
# Emit primary type
site_info = SiteInstInfo()
site_type = device.device_resource_capnp.siteTypeList[
site_type_in_tile_type.primaryType]
site_type_name = device.strs[site_type.name]
site_info.name = '{}.{}'.format(site_name, site_type_name)
site_info.site_name = site_name
site_info.site_type = site_type_name
tile_info.sites.append(len(chip_info.sites))
chip_info.sites.append(site_info)
for site_variant, (alt_site_type_index, _) in enumerate(
zip(site_type.altSiteTypes,
site_type_in_tile_type.altPinsToPrimaryPins)):
alt_site_info = SiteInstInfo()
alt_site_type = device.device_resource_capnp.siteTypeList[
alt_site_type_index]
alt_site_type_name = device.strs[alt_site_type.name]
alt_site_info.name = '{}.{}'.format(site_name,
alt_site_type_name)
alt_site_info.site_name = site_name
alt_site_info.site_type = alt_site_type_name
tile_info.sites.append(len(chip_info.sites))
chip_info.sites.append(alt_site_info)
assert len(tile_info.sites) == len(
chip_info.tile_types[tile.type].site_types), (
tile_info.name, len(tile_info.sites),
len(chip_info.tile_types[tile.type].site_types))
# (x, y) = (col, row)
tiles[(tile.col, tile.row)] = (tile_index, tile_info)
# Compute dimensions of grid
xs, ys = zip(*tiles.keys())
width = max(xs) + 1
height = max(ys) + 1
chip_info.width = width
chip_info.height = height
# Add tile instances to chip_info in row major order (per arch.h).
for y in range(height):
for x in range(width):
key = x, y
_, tile_info = tiles[key]
tile_name_to_tile_index[tile_info.name] = len(chip_info.tiles)
chip_info.tiles.append(tile_info)
# Output nodes
for idx, node in enumerate(device.device_resource_capnp.nodes):
# Skip nodes with only 1 wire!
if len(node.wires) == 1:
continue
node_info = NodeInfo()
node_index = len(chip_info.nodes)
chip_info.nodes.append(node_info)
# FIXME: Replace with actual node name?
node_info.name = 'node_{}'.format(node_index)
for wire_index in node.wires:
wire = device.device_resource_capnp.wires[wire_index]
tile_name = device.strs[wire.tile]
wire_name = device.strs[wire.wire]
tile_index = tile_name_to_tile_index[tile_name]
tile_info = chip_info.tiles[tile_index]
# Make reference from tile to node.
wire_in_tile_id = tile_wire_to_wire_in_tile_index[tile_info.
type][wire_name]
assert wire_in_tile_id < len(tile_info.tile_wire_to_node), (
wire_in_tile_id, len(tile_info.tile_wire_to_node),
tile_info.type, wire_name)
assert tile_info.tile_wire_to_node[wire_in_tile_id] == -1
tile_info.tile_wire_to_node[wire_in_tile_id] = node_index
# Make reference from node to tile.
tile_wire = TileWireRef()
tile_wire.tile = tile_index
tile_wire.index = wire_in_tile_id
node_info.tile_wires.append(tile_wire)
constants.populate_constant_network()
for package in device.device_resource_capnp.packages:
package_data = Package()
package_data.package = device.strs[package.name]
chip_info.packages.append(package_data)
for package_pin in package.packagePins:
if package_pin.site.which() == 'noSite':
continue
if package_pin.site.which() == 'noBel':
continue
package_pin_data = PackagePin()
package_pin_data.package_pin = device.strs[package_pin.packagePin]
package_pin_data.site = device.strs[package_pin.site.site]
package_pin_data.bel = device.strs[package_pin.bel.bel]
package_data.package_pins.append(package_pin_data)
return chip_info
| true | true |
f728195dd339d5267c7cae73f82a8afac42ab3cb | 951 | py | Python | src/transformers/data/__init__.py | coda-nsit/transformers | 372a9c6e633945b817f02de410923eec4dc18eed | [
"Apache-2.0"
] | null | null | null | src/transformers/data/__init__.py | coda-nsit/transformers | 372a9c6e633945b817f02de410923eec4dc18eed | [
"Apache-2.0"
] | null | null | null | src/transformers/data/__init__.py | coda-nsit/transformers | 372a9c6e633945b817f02de410923eec4dc18eed | [
"Apache-2.0"
] | null | null | null | # flake8: noqa
# There's no way to ignore "F401 '...' imported but unused" warnings in this
# module, but to preserve other warnings. So, don't check this module at all.
from .metrics import is_sklearn_available
from .processors import (
DataProcessor,
InputExample,
InputFeatures,
SingleSentenceClassificationProcessor,
SquadExample,
SquadFeatures,
SquadV1Processor,
SquadV2Processor,
glue_convert_examples_to_features,
glue_output_modes,
glue_processors,
glue_tasks_num_labels,
squad_convert_examples_to_features,
xnli_output_modes,
xnli_processors,
xnli_tasks_num_labels,
# opioid question answering imports
opioid_qa_convert_examples_to_features,
OpioidProcessor,
opioid_qa_processors,
opioid_qa_output_modes,
opioid_qa_num_labels
)
if is_sklearn_available():
from .metrics import glue_compute_metrics, xnli_compute_metrics, compute_accuracy_metrics
| 26.416667 | 93 | 0.769716 |
# module, but to preserve other warnings. So, don't check this module at all.
from .metrics import is_sklearn_available
from .processors import (
DataProcessor,
InputExample,
InputFeatures,
SingleSentenceClassificationProcessor,
SquadExample,
SquadFeatures,
SquadV1Processor,
SquadV2Processor,
glue_convert_examples_to_features,
glue_output_modes,
glue_processors,
glue_tasks_num_labels,
squad_convert_examples_to_features,
xnli_output_modes,
xnli_processors,
xnli_tasks_num_labels,
opioid_qa_convert_examples_to_features,
OpioidProcessor,
opioid_qa_processors,
opioid_qa_output_modes,
opioid_qa_num_labels
)
if is_sklearn_available():
from .metrics import glue_compute_metrics, xnli_compute_metrics, compute_accuracy_metrics
| true | true |
f72819c4e5b102864fd8cec7ae952001c8bfbdd6 | 189,788 | py | Python | source/gui/settingsDialogs.py | meunice/nvda | ba42885c0aaf7f695a088ab856fb350faf26a2dc | [
"bzip2-1.0.6"
] | null | null | null | source/gui/settingsDialogs.py | meunice/nvda | ba42885c0aaf7f695a088ab856fb350faf26a2dc | [
"bzip2-1.0.6"
] | null | null | null | source/gui/settingsDialogs.py | meunice/nvda | ba42885c0aaf7f695a088ab856fb350faf26a2dc | [
"bzip2-1.0.6"
] | null | null | null | # -*- coding: UTF-8 -*-
# A part of NonVisual Desktop Access (NVDA)
# Copyright (C) 2006-2020 NV Access Limited, Peter Vágner, Aleksey Sadovoy,
# Rui Batista, Joseph Lee, Heiko Folkerts, Zahari Yurukov, Leonard de Ruijter,
# Derek Riemer, Babbage B.V., Davy Kager, Ethan Holliger, Bill Dengler, Thomas Stivers
# This file is covered by the GNU General Public License.
# See the file COPYING for more details.
import logging
from abc import ABCMeta
import copy
import wx
from vision.providerBase import VisionEnhancementProviderSettings
from wx.lib import scrolledpanel
from wx.lib.expando import ExpandoTextCtrl
import wx.lib.newevent
import winUser
import logHandler
import installer
from synthDriverHandler import *
from synthDriverHandler import SynthDriver, getSynth
import config
import languageHandler
import speech
import gui
import globalVars
from logHandler import log
import nvwave
import audioDucking
import speechDictHandler
import queueHandler
import braille
import brailleTables
import brailleInput
import vision
import vision.providerInfo
import vision.providerBase
from typing import Callable, List, Optional, Any
import core
import keyboardHandler
import characterProcessing
from . import guiHelper
try:
import updateCheck
except RuntimeError:
updateCheck = None
from . import nvdaControls
from autoSettingsUtils.utils import UnsupportedConfigParameterError
from autoSettingsUtils.autoSettings import AutoSettings
from autoSettingsUtils.driverSetting import BooleanDriverSetting, NumericDriverSetting, DriverSetting
import touchHandler
import winVersion
import weakref
import time
import keyLabels
from .dpiScalingHelper import DpiScalingHelperMixinWithoutInit
class SettingsDialog(
DpiScalingHelperMixinWithoutInit,
gui.ContextHelpMixin,
wx.Dialog, # wxPython does not seem to call base class initializer, put last in MRO
metaclass=guiHelper.SIPABCMeta
):
"""A settings dialog.
A settings dialog consists of one or more settings controls and OK and Cancel buttons and an optional Apply button.
Action may be taken in response to the OK, Cancel or Apply buttons.
To use this dialog:
* Set L{title} to the title of the dialog.
* Override L{makeSettings} to populate a given sizer with the settings controls.
* Optionally, override L{postInit} to perform actions after the dialog is created, such as setting the focus. Be
aware that L{postInit} is also called by L{onApply}.
* Optionally, extend one or more of L{onOk}, L{onCancel} or L{onApply} to perform actions in response to the
OK, Cancel or Apply buttons, respectively.
@ivar title: The title of the dialog.
@type title: str
"""
class MultiInstanceError(RuntimeError): pass
_DIALOG_CREATED_STATE = 0
_DIALOG_DESTROYED_STATE = 1
# holds instances of SettingsDialogs as keys, and state as the value
_instances=weakref.WeakKeyDictionary()
title = ""
helpId = "NVDASettings"
shouldSuspendConfigProfileTriggers = True
def __new__(cls, *args, **kwargs):
# We are iterating over instanceItems only once, so it can safely be an iterator.
instanceItems = SettingsDialog._instances.items()
instancesOfSameClass = (
(dlg, state) for dlg, state in instanceItems if isinstance(dlg, cls)
)
firstMatchingInstance, state = next(instancesOfSameClass, (None, None))
multiInstanceAllowed = kwargs.get('multiInstanceAllowed', False)
if log.isEnabledFor(log.DEBUG):
instancesState = dict(SettingsDialog._instances)
log.debug(
"Creating new settings dialog (multiInstanceAllowed:{}). "
"State of _instances {!r}".format(multiInstanceAllowed, instancesState)
)
if state is cls._DIALOG_CREATED_STATE and not multiInstanceAllowed:
raise SettingsDialog.MultiInstanceError("Only one instance of SettingsDialog can exist at a time")
if state is cls._DIALOG_DESTROYED_STATE and not multiInstanceAllowed:
# the dialog has been destroyed by wx, but the instance is still available. This indicates there is something
# keeping it alive.
log.error("Opening new settings dialog while instance still exists: {!r}".format(firstMatchingInstance))
obj = super(SettingsDialog, cls).__new__(cls, *args, **kwargs)
SettingsDialog._instances[obj] = cls._DIALOG_CREATED_STATE
return obj
def _setInstanceDestroyedState(self):
if log.isEnabledFor(log.DEBUG):
instancesState = dict(SettingsDialog._instances)
log.debug(
"Setting state to destroyed for instance: {!r}\n"
"Current _instances {!r}".format(self, instancesState)
)
if self in SettingsDialog._instances:
SettingsDialog._instances[self] = self._DIALOG_DESTROYED_STATE
def __init__(
self, parent,
resizeable=False,
hasApplyButton=False,
settingsSizerOrientation=wx.VERTICAL,
multiInstanceAllowed=False
):
"""
@param parent: The parent for this dialog; C{None} for no parent.
@type parent: wx.Window
@param resizeable: True if the settings dialog should be resizable by the user, only set this if
you have tested that the components resize correctly.
@type resizeable: bool
@param hasApplyButton: C{True} to add an apply button to the dialog; defaults to C{False} for backwards compatibility.
@type hasApplyButton: bool
@param settingsSizerOrientation: Either wx.VERTICAL or wx.HORIZONTAL. This controls the orientation of the
sizer that is passed into L{makeSettings}. The default is wx.VERTICAL.
@type settingsSizerOrientation: wx.Orientation
@param multiInstanceAllowed: Whether multiple instances of SettingsDialog may exist.
Note that still only one instance of a particular SettingsDialog subclass may exist at one time.
@type multiInstanceAllowed: bool
"""
if gui._isDebug():
startTime = time.time()
windowStyle = wx.DEFAULT_DIALOG_STYLE
if resizeable:
windowStyle |= wx.RESIZE_BORDER | wx.MAXIMIZE_BOX
super().__init__(parent, title=self.title, style=windowStyle)
self.hasApply = hasApplyButton
self.mainSizer=wx.BoxSizer(wx.VERTICAL)
self.settingsSizer=wx.BoxSizer(settingsSizerOrientation)
self.makeSettings(self.settingsSizer)
self.mainSizer.Add(self.settingsSizer, border=guiHelper.BORDER_FOR_DIALOGS, flag=wx.ALL | wx.EXPAND, proportion=1)
buttons = wx.OK | wx.CANCEL
if hasApplyButton:
buttons |= wx.APPLY
self.mainSizer.Add(
self.CreateSeparatedButtonSizer(buttons),
border=guiHelper.BORDER_FOR_DIALOGS,
flag=wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
)
self.mainSizer.Fit(self)
self.SetSizer(self.mainSizer)
self.Bind(wx.EVT_BUTTON, self.onOk, id=wx.ID_OK)
self.Bind(wx.EVT_BUTTON, self.onCancel, id=wx.ID_CANCEL)
self.Bind(wx.EVT_BUTTON, self.onApply, id=wx.ID_APPLY)
self.Bind(wx.EVT_CHAR_HOOK, self._enterActivatesOk_ctrlSActivatesApply)
# Garbage collection normally handles removing the settings instance, however this may not happen immediately
# after a window is closed, or may be blocked by a circular reference. So instead, remove when the window is
# destroyed.
self.Bind(wx.EVT_WINDOW_DESTROY, self._onWindowDestroy)
self.postInit()
if resizeable:
self.SetMinSize(self.mainSizer.GetMinSize())
self.CentreOnScreen()
if gui._isDebug():
log.debug("Loading %s took %.2f seconds"%(self.__class__.__name__, time.time() - startTime))
def _enterActivatesOk_ctrlSActivatesApply(self, evt):
"""Listens for keyboard input and triggers ok button on enter and triggers apply button when control + S is
pressed. Cancel behavior is built into wx.
Pressing enter will also close the dialog when a list has focus
(e.g. the list of symbols in the symbol pronunciation dialog).
Without this custom handler, enter would propagate to the list control (wx ticket #3725).
"""
if evt.KeyCode in (wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER):
self.ProcessEvent(wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, wx.ID_OK))
elif self.hasApply and evt.UnicodeKey == ord(u'S') and evt.controlDown:
self.ProcessEvent(wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, wx.ID_APPLY))
else:
evt.Skip()
@abstractmethod
def makeSettings(self, sizer):
"""Populate the dialog with settings controls.
Subclasses must override this method.
@param sizer: The sizer to which to add the settings controls.
@type sizer: wx.Sizer
"""
raise NotImplementedError
def postInit(self):
"""Called after the dialog has been created.
For example, this might be used to set focus to the desired control.
Sub-classes may override this method.
"""
def onOk(self, evt):
"""Take action in response to the OK button being pressed.
Sub-classes may extend this method.
This base method should always be called to clean up the dialog.
"""
self.DestroyChildren()
self.Destroy()
self.SetReturnCode(wx.ID_OK)
def onCancel(self, evt):
"""Take action in response to the Cancel button being pressed.
Sub-classes may extend this method.
This base method should always be called to clean up the dialog.
"""
self.DestroyChildren()
self.Destroy()
self.SetReturnCode(wx.ID_CANCEL)
def onApply(self, evt):
"""Take action in response to the Apply button being pressed.
Sub-classes may extend or override this method.
This base method should be called to run the postInit method.
"""
self.postInit()
self.SetReturnCode(wx.ID_APPLY)
def _onWindowDestroy(self, evt):
evt.Skip()
self._setInstanceDestroyedState()
# An event and event binder that will notify the containers that they should
# redo the layout in whatever way makes sense for their particular content.
_RWLayoutNeededEvent, EVT_RW_LAYOUT_NEEDED = wx.lib.newevent.NewCommandEvent()
class SettingsPanel(
DpiScalingHelperMixinWithoutInit,
gui.ContextHelpMixin,
wx.Panel, # wxPython does not seem to call base class initializer, put last in MRO
metaclass=guiHelper.SIPABCMeta
):
"""A settings panel, to be used in a multi category settings dialog.
A settings panel consists of one or more settings controls.
Action may be taken in response to the parent dialog's OK or Cancel buttons.
To use this panel:
* Set L{title} to the title of the category.
* Override L{makeSettings} to populate a given sizer with the settings controls.
* Optionally, extend L{onPanelActivated} to perform actions after the category has been selected in the list of categories, such as synthesizer or braille display list population.
* Optionally, extend L{onPanelDeactivated} to perform actions after the category has been deselected (i.e. another category is selected) in the list of categories.
* Optionally, extend one or both of L{onSave} or L{onDiscard} to perform actions in response to the parent dialog's OK or Cancel buttons, respectively.
* Optionally, extend one or both of L{isValid} or L{postSave} to perform validation before or steps after saving, respectively.
@ivar title: The title of the settings panel, also listed in the list of settings categories.
@type title: str
"""
title=""
panelDescription=u""
def __init__(self, parent: wx.Window):
"""
@param parent: The parent for this panel; C{None} for no parent.
"""
if gui._isDebug():
startTime = time.time()
super().__init__(parent)
self._buildGui()
if gui._isDebug():
elapsedSeconds = time.time() - startTime
panelName = self.__class__.__qualname__
log.debug(f"Loading {panelName} took {elapsedSeconds:.2f} seconds")
def _buildGui(self):
self.mainSizer=wx.BoxSizer(wx.VERTICAL)
self.settingsSizer=wx.BoxSizer(wx.VERTICAL)
self.makeSettings(self.settingsSizer)
self.mainSizer.Add(self.settingsSizer, flag=wx.ALL | wx.EXPAND)
self.mainSizer.Fit(self)
self.SetSizer(self.mainSizer)
@abstractmethod
def makeSettings(self, sizer: wx.BoxSizer):
"""Populate the panel with settings controls.
Subclasses must override this method.
@param sizer: The sizer to which to add the settings controls.
"""
raise NotImplementedError
def onPanelActivated(self):
"""Called after the panel has been activated (i.e. de corresponding category is selected in the list of categories).
For example, this might be used for resource intensive tasks.
Sub-classes should extend this method.
"""
self.Show()
def onPanelDeactivated(self):
"""Called after the panel has been deactivated (i.e. another category has been selected in the list of categories).
Sub-classes should extendthis method.
"""
self.Hide()
@abstractmethod
def onSave(self):
"""Take action in response to the parent's dialog OK or apply button being pressed.
Sub-classes should override this method.
MultiCategorySettingsDialog is responsible for cleaning up the panel when OK is pressed.
"""
raise NotImplementedError
def isValid(self):
"""Evaluate whether the current circumstances of this panel are valid
and allow saving all the settings in a L{MultiCategorySettingsDialog}.
Sub-classes may extend this method.
@returns: C{True} if validation should continue,
C{False} otherwise.
@rtype: bool
"""
return True
def postSave(self):
"""Take action whenever saving settings for all panels in a L{MultiCategorySettingsDialog} succeeded.
Sub-classes may extend this method.
"""
def onDiscard(self):
"""Take action in response to the parent's dialog Cancel button being pressed.
Sub-classes may override this method.
MultiCategorySettingsDialog is responsible for cleaning up the panel when Cancel is pressed.
"""
def _sendLayoutUpdatedEvent(self):
"""Notify any wx parents that may be listening that they should redo their layout in whatever way
makes sense for them. It is expected that sub-classes call this method in response to changes in
the number of GUI items in their panel.
"""
event = _RWLayoutNeededEvent(self.GetId())
event.SetEventObject(self)
self.GetEventHandler().ProcessEvent(event)
class MultiCategorySettingsDialog(SettingsDialog):
"""A settings dialog with multiple settings categories.
A multi category settings dialog consists of a list view with settings categories on the left side,
and a settings panel on the right side of the dialog.
Furthermore, in addition to Ok and Cancel buttons, it has an Apply button by default,
which is different from the default behavior of L{SettingsDialog}.
To use this dialog: set title and populate L{categoryClasses} with subclasses of SettingsPanel.
Make sure that L{categoryClasses} only contains panels that are available on a particular system.
For example, if a certain category of settings is only supported on Windows 10 and higher,
that category should be left out of L{categoryClasses}
"""
title=""
categoryClasses=[]
class CategoryUnavailableError(RuntimeError): pass
def __init__(self, parent, initialCategory=None):
"""
@param parent: The parent for this dialog; C{None} for no parent.
@type parent: wx.Window
@param initialCategory: The initial category to select when opening this dialog
@type parent: SettingsPanel
"""
if initialCategory and not issubclass(initialCategory,SettingsPanel):
if gui._isDebug():
log.debug("Unable to open category: {}".format(initialCategory), stack_info=True)
raise TypeError("initialCategory should be an instance of SettingsPanel")
if initialCategory and initialCategory not in self.categoryClasses:
if gui._isDebug():
log.debug("Unable to open category: {}".format(initialCategory), stack_info=True)
raise MultiCategorySettingsDialog.CategoryUnavailableError(
"The provided initial category is not a part of this dialog"
)
self.initialCategory = initialCategory
self.currentCategory = None
self.setPostInitFocus = None
# dictionary key is index of category in self.catList, value is the instance. Partially filled, check for KeyError
self.catIdToInstanceMap = {}
super(MultiCategorySettingsDialog, self).__init__(
parent,
resizeable=True,
hasApplyButton=True,
settingsSizerOrientation=wx.HORIZONTAL
)
# setting the size must be done after the parent is constructed.
self.SetMinSize(self.scaleSize(self.MIN_SIZE))
self.SetSize(self.scaleSize(self.INITIAL_SIZE))
# the size has changed, so recenter on the screen
self.CentreOnScreen()
# Initial / min size for the dialog. This size was chosen as a medium fit, so the
# smaller settings panels are not surrounded by too much space but most of
# the panels fit. Vertical scrolling is acceptable. Horizontal scrolling less
# so, the width was chosen to eliminate horizontal scroll bars. If a panel
# exceeds the the initial width a debugWarning will be added to the log.
INITIAL_SIZE = (800, 480)
MIN_SIZE = (470, 240) # Min height required to show the OK, Cancel, Apply buttons
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: The label for the list of categories in a multi category settings dialog.
categoriesLabelText=_("&Categories:")
categoriesLabel = wx.StaticText(self, label=categoriesLabelText)
# since the categories list and the container both expand in height, the y
# portion is essentially a "min" height.
# These sizes are set manually so that the initial proportions within the dialog look correct. If these sizes are
# not given, then I believe the proportion arguments (as given to the gridBagSizer.AddGrowableColumn) are used
# to set their relative sizes. We want the proportion argument to be used for resizing, but not the initial size.
catListDim = (150, 10)
catListDim = self.scaleSize(catListDim)
initialScaledWidth = self.scaleSize(self.INITIAL_SIZE[0])
spaceForBorderWidth = self.scaleSize(20)
catListWidth = catListDim[0]
containerDim = (initialScaledWidth - catListWidth - spaceForBorderWidth, self.scaleSize(10))
self.catListCtrl = nvdaControls.AutoWidthColumnListCtrl(
self,
autoSizeColumn=1,
size=catListDim,
style=wx.LC_REPORT|wx.LC_SINGLE_SEL|wx.LC_NO_HEADER
)
# This list consists of only one column.
# The provided column header is just a placeholder, as it is hidden due to the wx.LC_NO_HEADER style flag.
self.catListCtrl.InsertColumn(0,categoriesLabelText)
self.container = scrolledpanel.ScrolledPanel(
parent = self,
style = wx.TAB_TRAVERSAL | wx.BORDER_THEME,
size=containerDim
)
# Th min size is reset so that they can be reduced to below their "size" constraint.
self.container.SetMinSize((1,1))
self.catListCtrl.SetMinSize((1,1))
self.containerSizer = wx.BoxSizer(wx.VERTICAL)
self.container.SetSizer(self.containerSizer)
for cls in self.categoryClasses:
if not issubclass(cls,SettingsPanel):
raise RuntimeError("Invalid category class %s provided in %s.categoryClasses"%(cls.__name__,self.__class__.__name__))
# It's important here that the listItems are added to catListCtrl in the same order that they exist in categoryClasses.
# the ListItem index / Id is used to index categoryClasses, and used as the key in catIdToInstanceMap
self.catListCtrl.Append((cls.title,))
# populate the GUI with the initial category
initialCatIndex = 0 if not self.initialCategory else self.categoryClasses.index(self.initialCategory)
self._doCategoryChange(initialCatIndex)
self.catListCtrl.Select(initialCatIndex)
# we must focus the initial category in the category list.
self.catListCtrl.Focus(initialCatIndex)
self.setPostInitFocus = self.container.SetFocus if self.initialCategory else self.catListCtrl.SetFocus
self.gridBagSizer=gridBagSizer=wx.GridBagSizer(
hgap=guiHelper.SPACE_BETWEEN_BUTTONS_HORIZONTAL,
vgap=guiHelper.SPACE_BETWEEN_BUTTONS_VERTICAL
)
# add the label, the categories list, and the settings panel to a 2 by 2 grid.
# The label should span two columns, so that the start of the categories list
# and the start of the settings panel are at the same vertical position.
gridBagSizer.Add(categoriesLabel, pos=(0,0), span=(1,2))
gridBagSizer.Add(self.catListCtrl, pos=(1,0), flag=wx.EXPAND)
gridBagSizer.Add(self.container, pos=(1,1), flag=wx.EXPAND)
# Make the row with the listCtrl and settings panel grow vertically.
gridBagSizer.AddGrowableRow(1)
# Make the columns with the listCtrl and settings panel grow horizontally if the dialog is resized.
# They should grow 1:3, since the settings panel is much more important, and already wider
# than the listCtrl.
gridBagSizer.AddGrowableCol(0, proportion=1)
gridBagSizer.AddGrowableCol(1, proportion=3)
sHelper.sizer.Add(gridBagSizer, flag=wx.EXPAND, proportion=1)
self.container.Layout()
self.catListCtrl.Bind(wx.EVT_LIST_ITEM_FOCUSED, self.onCategoryChange)
self.Bind(wx.EVT_CHAR_HOOK, self.onCharHook)
self.Bind(EVT_RW_LAYOUT_NEEDED, self._onPanelLayoutChanged)
def _getCategoryPanel(self, catId):
panel = self.catIdToInstanceMap.get(catId, None)
if not panel:
try:
cls = self.categoryClasses[catId]
except IndexError:
raise ValueError("Unable to create panel for unknown category ID: {}".format(catId))
panel = cls(parent=self.container)
panel.Hide()
self.containerSizer.Add(
panel, flag=wx.ALL | wx.EXPAND,
border=guiHelper.SPACE_BETWEEN_ASSOCIATED_CONTROL_HORIZONTAL
)
self.catIdToInstanceMap[catId] = panel
panelWidth = panel.Size[0]
availableWidth = self.containerSizer.GetSize()[0]
if panelWidth > availableWidth and gui._isDebug():
log.debugWarning(
("Panel width ({1}) too large for: {0} Try to reduce the width of this panel, or increase width of " +
"MultiCategorySettingsDialog.MIN_SIZE"
).format(cls, panel.Size[0])
)
panel.SetLabel(panel.title)
import oleacc
panel.server = nvdaControls.AccPropertyOverride(
panel,
propertyAnnotations={
oleacc.PROPID_ACC_ROLE: oleacc.ROLE_SYSTEM_PROPERTYPAGE, # change the role from pane to property page
oleacc.PROPID_ACC_DESCRIPTION: panel.panelDescription, # set a description
}
)
return panel
def postInit(self):
# By default after the dialog is created, focus lands on the button group for wx.Dialogs. However this is not where
# we want focus. We only want to modify focus after creation (makeSettings), but postInit is also called after
# onApply, so we reset the setPostInitFocus function.
if self.setPostInitFocus:
self.setPostInitFocus()
self.setPostInitFocus = None
else:
# when postInit is called without a setPostInitFocus ie because onApply was called
# then set the focus to the listCtrl. This is a good starting point for a "fresh state"
self.catListCtrl.SetFocus()
def onCharHook(self,evt):
"""Listens for keyboard input and switches panels for control+tab"""
if not self.catListCtrl:
# Dialog has not yet been constructed.
# Allow another handler to take the event, and return early.
evt.Skip()
return
key = evt.GetKeyCode()
listHadFocus = self.catListCtrl.HasFocus()
if evt.ControlDown() and key==wx.WXK_TAB:
# Focus the categories list. If we don't, the panel won't hide correctly
if not listHadFocus:
self.catListCtrl.SetFocus()
index = self.catListCtrl.GetFirstSelected()
newIndex=index-1 if evt.ShiftDown() else index+1
# Less than first wraps to the last index, greater than last wraps to first index.
newIndex=newIndex % self.catListCtrl.ItemCount
self.catListCtrl.Select(newIndex)
# we must focus the new selection in the category list to trigger the change of category.
self.catListCtrl.Focus(newIndex)
if not listHadFocus and self.currentCategory:
self.currentCategory.SetFocus()
else:
evt.Skip()
def _onPanelLayoutChanged(self,evt):
# call layout and SetupScrolling on the container so that the controls apear in their expected locations.
self.container.Layout()
self.container.SetupScrolling()
# when child elements get smaller the scrolledPanel does not
# erase the old contents and must be redrawn
self.container.Refresh()
def _doCategoryChange(self, newCatId):
oldCat = self.currentCategory
# Freeze and Thaw are called to stop visual artifact's while the GUI
# is being rebuilt. Without this, the controls can sometimes be seen being
# added.
self.container.Freeze()
try:
newCat = self._getCategoryPanel(newCatId)
except ValueError as e:
newCatTitle = self.catListCtrl.GetItemText(newCatId)
log.error("Unable to change to category: {}".format(newCatTitle), exc_info=e)
return
if oldCat:
oldCat.onPanelDeactivated()
self.currentCategory = newCat
newCat.onPanelActivated()
# call Layout and SetupScrolling on the container to make sure that the controls apear in their expected locations.
self.container.Layout()
self.container.SetupScrolling()
self.container.Thaw()
def onCategoryChange(self, evt):
currentCat = self.currentCategory
newIndex = evt.GetIndex()
if not currentCat or newIndex != self.categoryClasses.index(currentCat.__class__):
self._doCategoryChange(newIndex)
else:
evt.Skip()
def _doSave(self):
for panel in self.catIdToInstanceMap.values():
if panel.isValid() is False:
raise ValueError("Validation for %s blocked saving settings" % panel.__class__.__name__)
for panel in self.catIdToInstanceMap.values():
panel.onSave()
for panel in self.catIdToInstanceMap.values():
panel.postSave()
def onOk(self,evt):
try:
self._doSave()
except ValueError:
log.debugWarning("", exc_info=True)
return
for panel in self.catIdToInstanceMap.values():
panel.Destroy()
super(MultiCategorySettingsDialog,self).onOk(evt)
def onCancel(self,evt):
for panel in self.catIdToInstanceMap.values():
panel.onDiscard()
panel.Destroy()
super(MultiCategorySettingsDialog,self).onCancel(evt)
def onApply(self,evt):
try:
self._doSave()
except ValueError:
log.debugWarning("", exc_info=True)
return
super(MultiCategorySettingsDialog,self).onApply(evt)
class GeneralSettingsPanel(SettingsPanel):
# Translators: This is the label for the general settings panel.
title = _("General")
helpId = "GeneralSettingsLanguage"
LOG_LEVELS = (
# Translators: One of the log levels of NVDA (the disabled mode turns off logging completely).
(log.OFF, _("disabled")),
# Translators: One of the log levels of NVDA (the info mode shows info as NVDA runs).
(log.INFO, _("info")),
# Translators: One of the log levels of NVDA (the debug warning shows debugging messages and warnings as NVDA runs).
(log.DEBUGWARNING, _("debug warning")),
# Translators: One of the log levels of NVDA (the input/output shows keyboard commands and/or braille commands as well as speech and/or braille output of NVDA).
(log.IO, _("input/output")),
# Translators: One of the log levels of NVDA (the debug mode shows debug messages as NVDA runs).
(log.DEBUG, _("debug"))
)
def makeSettings(self, settingsSizer):
settingsSizerHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
self.languageNames = languageHandler.getAvailableLanguages(presentational=True)
languageChoices = [x[1] for x in self.languageNames]
# Translators: The label for a setting in general settings to select NVDA's interface language
# (once selected, NVDA must be restarted; the option user default means the user's Windows language
# will be used).
languageLabelText = _("NVDA &Language (requires restart):")
self.languageList=settingsSizerHelper.addLabeledControl(languageLabelText, wx.Choice, choices=languageChoices)
self.languageList.SetToolTip(wx.ToolTip("Choose the language NVDA's messages and user interface should be presented in."))
try:
self.oldLanguage=config.conf["general"]["language"]
index=[x[0] for x in self.languageNames].index(self.oldLanguage)
self.languageList.SetSelection(index)
except:
pass
if globalVars.appArgs.secure:
self.languageList.Disable()
# Translators: The label for a setting in general settings to save current configuration when NVDA
# exits (if it is not checked, user needs to save configuration before quitting NVDA).
self.saveOnExitCheckBox = wx.CheckBox(self, label=_("&Save configuration when exiting NVDA"))
self.saveOnExitCheckBox.SetValue(config.conf["general"]["saveConfigurationOnExit"])
if globalVars.appArgs.secure:
self.saveOnExitCheckBox.Disable()
settingsSizerHelper.addItem(self.saveOnExitCheckBox)
# Translators: The label for a setting in general settings to ask before quitting NVDA (if not checked, NVDA will exit without asking the user for action).
self.askToExitCheckBox=wx.CheckBox(self,label=_("Sho&w exit options when exiting NVDA"))
self.askToExitCheckBox.SetValue(config.conf["general"]["askToExit"])
settingsSizerHelper.addItem(self.askToExitCheckBox)
self.bindHelpEvent("GeneralSettingsShowExitOptions", self.askToExitCheckBox)
# Translators: The label for a setting in general settings to play sounds when NVDA starts or exits.
self.playStartAndExitSoundsCheckBox=wx.CheckBox(self,label=_("&Play sounds when starting or exiting NVDA"))
self.bindHelpEvent("GeneralSettingsPlaySounds", self.playStartAndExitSoundsCheckBox)
self.playStartAndExitSoundsCheckBox.SetValue(config.conf["general"]["playStartAndExitSounds"])
settingsSizerHelper.addItem(self.playStartAndExitSoundsCheckBox)
# Translators: The label for a setting in general settings to select logging level of NVDA as it runs
# (available options and what they are logging are found under comments for the logging level messages
# themselves).
logLevelLabelText=_("L&ogging level:")
logLevelChoices = [name for level, name in self.LOG_LEVELS]
self.logLevelList = settingsSizerHelper.addLabeledControl(logLevelLabelText, wx.Choice, choices=logLevelChoices)
curLevel = log.getEffectiveLevel()
if logHandler.isLogLevelForced():
self.logLevelList.Disable()
for index, (level, name) in enumerate(self.LOG_LEVELS):
if level == curLevel:
self.logLevelList.SetSelection(index)
break
else:
log.debugWarning("Could not set log level list to current log level")
# Translators: The label for a setting in general settings to allow NVDA to start after logging onto
# Windows (if checked, NVDA will start automatically after logging into Windows; if not, user must
# start NVDA by pressing the shortcut key (CTRL+Alt+N by default).
self.startAfterLogonCheckBox = wx.CheckBox(self, label=_("St&art NVDA after I sign in"))
self.startAfterLogonCheckBox.SetValue(config.getStartAfterLogon())
if globalVars.appArgs.secure or not config.isInstalledCopy():
self.startAfterLogonCheckBox.Disable()
settingsSizerHelper.addItem(self.startAfterLogonCheckBox)
self.bindHelpEvent("GeneralSettingsStartAfterLogOn", self.startAfterLogonCheckBox)
self.startOnLogonScreenCheckBox = wx.CheckBox(
self,
# Translators: The label for a setting in general settings to
# allow NVDA to come up in Windows login screen (useful if user
# needs to enter passwords or if multiple user accounts are present
# to allow user to choose the correct account).
label=_("Use NVDA during sign-in (requires administrator privileges)")
)
self.bindHelpEvent("GeneralSettingsStartOnLogOnScreen", self.startOnLogonScreenCheckBox)
self.startOnLogonScreenCheckBox.SetValue(config.getStartOnLogonScreen())
if globalVars.appArgs.secure or not config.canStartOnSecureScreens():
self.startOnLogonScreenCheckBox.Disable()
settingsSizerHelper.addItem(self.startOnLogonScreenCheckBox)
self.copySettingsButton = wx.Button(
self,
label=_(
# Translators: The label for a button in general settings to copy
# current user settings to system settings (to allow current
# settings to be used in secure screens such as User Account
# Control (UAC) dialog).
"Use currently saved settings during sign-in and on secure screens"
" (requires administrator privileges)"
)
)
self.bindHelpEvent("GeneralSettingsCopySettings", self.copySettingsButton)
self.copySettingsButton.Bind(wx.EVT_BUTTON,self.onCopySettings)
if globalVars.appArgs.secure or not config.canStartOnSecureScreens():
self.copySettingsButton.Disable()
settingsSizerHelper.addItem(self.copySettingsButton)
if updateCheck:
# Translators: The label of a checkbox in general settings to toggle automatic checking for updated versions of NVDA (if not checked, user must check for updates manually).
item=self.autoCheckForUpdatesCheckBox=wx.CheckBox(self,label=_("Automatically check for &updates to NVDA"))
self.bindHelpEvent("GeneralSettingsCheckForUpdates", self.autoCheckForUpdatesCheckBox)
item.Value=config.conf["update"]["autoCheck"]
if globalVars.appArgs.secure:
item.Disable()
settingsSizerHelper.addItem(item)
# Translators: The label of a checkbox in general settings to toggle startup notifications
# for a pending NVDA update.
item=self.notifyForPendingUpdateCheckBox=wx.CheckBox(self,label=_("Notify for &pending update on startup"))
item.Value=config.conf["update"]["startupNotification"]
if globalVars.appArgs.secure:
item.Disable()
settingsSizerHelper.addItem(item)
# Translators: The label of a checkbox in general settings to toggle allowing of usage stats gathering
item=self.allowUsageStatsCheckBox=wx.CheckBox(self,label=_("Allow the NVDA project to gather NVDA usage statistics"))
item.Value=config.conf["update"]["allowUsageStats"]
if globalVars.appArgs.secure:
item.Disable()
settingsSizerHelper.addItem(item)
def onCopySettings(self,evt):
addonsDirPath = os.path.join(globalVars.appArgs.configPath, 'addons')
if os.path.isdir(addonsDirPath) and 0 < len(os.listdir(addonsDirPath)):
message = _(
# Translators: A message to warn the user when attempting to copy current
# settings to system settings.
"Add-ons were detected in your user settings directory. "
"Copying these to the system profile could be a security risk. "
"Do you still wish to copy your settings?"
)
# Translators: The title of the warning dialog displayed when trying to
# copy settings for use in secure screens.
title = _("Warning")
style = wx.YES | wx.NO | wx.ICON_WARNING
if wx.NO == gui.messageBox(message, title, style, self):
return
progressDialog = gui.IndeterminateProgressDialog(
gui.mainFrame,
# Translators: The title of the dialog presented while settings are being copied
_("Copying Settings"),
# Translators: The message displayed while settings are being copied
# to the system configuration (for use on Windows logon etc)
_("Please wait while settings are copied to the system configuration.")
)
while True:
try:
gui.ExecAndPump(config.setSystemConfigToCurrentConfig)
res=True
break
except installer.RetriableFailure:
log.debugWarning("Error when copying settings to system config",exc_info=True)
# Translators: a message dialog asking to retry or cancel when copying settings fails
message=_("Unable to copy a file. Perhaps it is currently being used by another process or you have run out of disc space on the drive you are copying to.")
# Translators: the title of a retry cancel dialog when copying settings fails
title=_("Error Copying")
if winUser.MessageBox(None,message,title,winUser.MB_RETRYCANCEL)==winUser.IDRETRY:
continue
res=False
break
except:
log.debugWarning("Error when copying settings to system config",exc_info=True)
res=False
break
progressDialog.done()
del progressDialog
if not res:
# Translators: The message displayed when errors were found while trying to copy current configuration to system settings.
gui.messageBox(_("Error copying NVDA user settings"),_("Error"),wx.OK|wx.ICON_ERROR,self)
else:
# Translators: The message displayed when copying configuration to system settings was successful.
gui.messageBox(_("Successfully copied NVDA user settings"),_("Success"),wx.OK|wx.ICON_INFORMATION,self)
def onSave(self):
newLanguage=[x[0] for x in self.languageNames][self.languageList.GetSelection()]
config.conf["general"]["language"]=newLanguage
config.conf["general"]["saveConfigurationOnExit"]=self.saveOnExitCheckBox.IsChecked()
config.conf["general"]["askToExit"]=self.askToExitCheckBox.IsChecked()
config.conf["general"]["playStartAndExitSounds"]=self.playStartAndExitSoundsCheckBox.IsChecked()
logLevel=self.LOG_LEVELS[self.logLevelList.GetSelection()][0]
if not logHandler.isLogLevelForced():
config.conf["general"]["loggingLevel"] = logging.getLevelName(logLevel)
logHandler.setLogLevelFromConfig()
if self.startAfterLogonCheckBox.IsEnabled():
config.setStartAfterLogon(self.startAfterLogonCheckBox.GetValue())
if self.startOnLogonScreenCheckBox.IsEnabled():
try:
config.setStartOnLogonScreen(self.startOnLogonScreenCheckBox.GetValue())
except (WindowsError, RuntimeError):
gui.messageBox(_("This change requires administrator privileges."), _("Insufficient Privileges"), style=wx.OK | wx.ICON_ERROR, parent=self)
if updateCheck:
config.conf["update"]["autoCheck"]=self.autoCheckForUpdatesCheckBox.IsChecked()
config.conf["update"]["allowUsageStats"]=self.allowUsageStatsCheckBox.IsChecked()
config.conf["update"]["startupNotification"]=self.notifyForPendingUpdateCheckBox.IsChecked()
updateCheck.terminate()
updateCheck.initialize()
def postSave(self):
if self.oldLanguage != config.conf["general"]["language"]:
LanguageRestartDialog(self).ShowModal()
class LanguageRestartDialog(wx.Dialog):
def __init__(self, parent):
# Translators: The title of the dialog which appears when the user changed NVDA's interface language.
super(LanguageRestartDialog, self).__init__(parent, title=_("Language Configuration Change"))
mainSizer = wx.BoxSizer(wx.VERTICAL)
sHelper = guiHelper.BoxSizerHelper(self, orientation=wx.VERTICAL)
# Translators: The message displayed after NVDA interface language has been changed.
sHelper.addItem(wx.StaticText(self, label=_("NVDA must be restarted for the new language to take effect.")))
bHelper = sHelper.addDialogDismissButtons(guiHelper.ButtonHelper(wx.HORIZONTAL))
# Translators: The label for a button in the dialog which appears when the user changed NVDA's interface language.
restartNowButton = bHelper.addButton(self, label=_("Restart &now"))
restartNowButton.Bind(wx.EVT_BUTTON, self.onRestartNowButton)
restartNowButton.SetFocus()
# Translators: The label for a button in the dialog which appears when the user changed NVDA's interface language.
restartLaterButton = bHelper.addButton(self, wx.ID_CLOSE, label=_("Restart &later"))
restartLaterButton.Bind(wx.EVT_BUTTON, lambda evt: self.Close())
self.Bind(wx.EVT_CLOSE, lambda evt: self.Destroy())
self.EscapeId = wx.ID_CLOSE
mainSizer.Add(sHelper.sizer, border=guiHelper.BORDER_FOR_DIALOGS, flag=wx.ALL)
self.Sizer = mainSizer
mainSizer.Fit(self)
self.CentreOnScreen()
def onRestartNowButton(self, evt):
self.Destroy()
config.conf.save()
queueHandler.queueFunction(queueHandler.eventQueue,core.restart)
class SpeechSettingsPanel(SettingsPanel):
# Translators: This is the label for the speech panel
title = _("Speech")
helpId = "SpeechSettings"
def makeSettings(self, settingsSizer):
settingsSizerHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: A label for the synthesizer on the speech panel.
synthLabel = _("&Synthesizer")
synthBox = wx.StaticBox(self, label=synthLabel)
synthGroup = guiHelper.BoxSizerHelper(self, sizer=wx.StaticBoxSizer(synthBox, wx.HORIZONTAL))
settingsSizerHelper.addItem(synthGroup)
# Use a ExpandoTextCtrl because even when readonly it accepts focus from keyboard, which
# standard readonly TextCtrl does not. ExpandoTextCtrl is a TE_MULTILINE control, however
# by default it renders as a single line. Standard TextCtrl with TE_MULTILINE has two lines,
# and a vertical scroll bar. This is not neccessary for the single line of text we wish to
# display here.
synthDesc = getSynth().description
self.synthNameCtrl = ExpandoTextCtrl(self, size=(self.scaleSize(250), -1), value=synthDesc, style=wx.TE_READONLY)
self.synthNameCtrl.Bind(wx.EVT_CHAR_HOOK, self._enterTriggersOnChangeSynth)
# Translators: This is the label for the button used to change synthesizer,
# it appears in the context of a synthesizer group on the speech settings panel.
changeSynthBtn = wx.Button(self, label=_("C&hange..."))
self.bindHelpEvent("SpeechSettingsChange", self.synthNameCtrl)
self.bindHelpEvent("SpeechSettingsChange", changeSynthBtn)
synthGroup.addItem(
guiHelper.associateElements(
self.synthNameCtrl,
changeSynthBtn
)
)
changeSynthBtn.Bind(wx.EVT_BUTTON,self.onChangeSynth)
self.voicePanel = VoiceSettingsPanel(self)
settingsSizerHelper.addItem(self.voicePanel)
def _enterTriggersOnChangeSynth(self, evt):
if evt.KeyCode == wx.WXK_RETURN:
self.onChangeSynth(evt)
else:
evt.Skip()
def onChangeSynth(self, evt):
changeSynth = SynthesizerSelectionDialog(self, multiInstanceAllowed=True)
ret = changeSynth.ShowModal()
if ret == wx.ID_OK:
self.Freeze()
# trigger a refresh of the settings
self.onPanelActivated()
self._sendLayoutUpdatedEvent()
self.Thaw()
def updateCurrentSynth(self):
synthDesc = getSynth().description
self.synthNameCtrl.SetValue(synthDesc)
def onPanelActivated(self):
# call super after all panel updates have been completed, we dont want the panel to show until this is complete.
self.voicePanel.onPanelActivated()
super(SpeechSettingsPanel,self).onPanelActivated()
def onPanelDeactivated(self):
self.voicePanel.onPanelDeactivated()
super(SpeechSettingsPanel,self).onPanelDeactivated()
def onDiscard(self):
self.voicePanel.onDiscard()
def onSave(self):
self.voicePanel.onSave()
class SynthesizerSelectionDialog(SettingsDialog):
# Translators: This is the label for the synthesizer selection dialog
title = _("Select Synthesizer")
helpId = "SynthesizerSelection"
synthNames = []
def makeSettings(self, settingsSizer):
settingsSizerHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: This is a label for the select
# synthesizer combobox in the synthesizer dialog.
synthListLabelText=_("&Synthesizer:")
self.synthList = settingsSizerHelper.addLabeledControl(synthListLabelText, wx.Choice, choices=[])
self.bindHelpEvent("SelectSynthesizerSynthesizer", self.synthList)
self.updateSynthesizerList()
# Translators: This is the label for the select output
# device combo in the synthesizer dialog. Examples of
# of an output device are default soundcard, usb
# headphones, etc.
deviceListLabelText = _("Audio output &device:")
deviceNames=nvwave.getOutputDeviceNames()
# #11349: On Windows 10 20H1 and 20H2, Microsoft Sound Mapper returns an empty string.
if deviceNames[0] in ("", "Microsoft Sound Mapper"):
# Translators: name for default (Microsoft Sound Mapper) audio output device.
deviceNames[0] = _("Microsoft Sound Mapper")
self.deviceList = settingsSizerHelper.addLabeledControl(deviceListLabelText, wx.Choice, choices=deviceNames)
self.bindHelpEvent("SelectSynthesizerOutputDevice", self.deviceList)
try:
selection = deviceNames.index(config.conf["speech"]["outputDevice"])
except ValueError:
selection = 0
self.deviceList.SetSelection(selection)
# Translators: This is a label for the audio ducking combo box in the Synthesizer Settings dialog.
duckingListLabelText = _("Audio d&ucking mode:")
self.duckingList=settingsSizerHelper.addLabeledControl(duckingListLabelText, wx.Choice, choices=audioDucking.audioDuckingModes)
self.bindHelpEvent("SelectSynthesizerDuckingMode", self.duckingList)
index=config.conf['audio']['audioDuckingMode']
self.duckingList.SetSelection(index)
if not audioDucking.isAudioDuckingSupported():
self.duckingList.Disable()
def postInit(self):
# Finally, ensure that focus is on the synthlist
self.synthList.SetFocus()
def updateSynthesizerList(self):
driverList=getSynthList()
self.synthNames=[x[0] for x in driverList]
options=[x[1] for x in driverList]
self.synthList.Clear()
self.synthList.AppendItems(options)
try:
index=self.synthNames.index(getSynth().name)
self.synthList.SetSelection(index)
except:
pass
def onOk(self, evt):
if not self.synthNames:
# The list of synths has not been populated yet, so we didn't change anything in this panel
return
config.conf["speech"]["outputDevice"]=self.deviceList.GetStringSelection()
newSynth=self.synthNames[self.synthList.GetSelection()]
if not setSynth(newSynth):
# Translators: This message is presented when
# NVDA is unable to load the selected
# synthesizer.
gui.messageBox(_("Could not load the %s synthesizer.")%newSynth,_("Synthesizer Error"),wx.OK|wx.ICON_WARNING,self)
return
if audioDucking.isAudioDuckingSupported():
index=self.duckingList.GetSelection()
config.conf['audio']['audioDuckingMode']=index
audioDucking.setAudioDuckingMode(index)
# Reinitialize the tones module to update the audio device
import tones
tones.terminate()
tones.initialize()
if self.IsModal():
# Hack: we need to update the synth in our parent window before closing.
# Otherwise, NVDA will report the old synth even though the new synth is reflected visually.
self.Parent.updateCurrentSynth()
super(SynthesizerSelectionDialog, self).onOk(evt)
class DriverSettingChanger(object):
"""Functor which acts as callback for GUI events."""
def __init__(self,driver,setting):
self._driverRef=weakref.ref(driver)
self.setting=setting
@property
def driver(self):
return self._driverRef()
def __call__(self,evt):
evt.Skip() # allow other handlers to also process this event.
val=evt.GetSelection()
setattr(self.driver,self.setting.id,val)
class StringDriverSettingChanger(DriverSettingChanger):
"""Same as L{DriverSettingChanger} but handles combobox events."""
def __init__(self,driver,setting,container):
self.container=container
super(StringDriverSettingChanger,self).__init__(driver,setting)
def __call__(self,evt):
evt.Skip() # allow other handlers to also process this event.
# Quick workaround to deal with voice changes.
if self.setting.id == "voice":
# Cancel speech first so that the voice will change immediately instead of the change being queued.
speech.cancelSpeech()
changeVoice(
self.driver,
getattr(self.container,"_%ss"%self.setting.id)[evt.GetSelection()].id
)
self.container.updateDriverSettings(changedSetting=self.setting.id)
else:
setattr(
self.driver,
self.setting.id,
getattr(self.container,"_%ss"%self.setting.id)[evt.GetSelection()].id
)
class AutoSettingsMixin(metaclass=ABCMeta):
"""
Mixin class that provides support for driver/vision provider specific gui settings.
Derived classes should implement:
- L{getSettings}
- L{settingsSizer}
Derived classes likely need to inherit from L{SettingsPanel}, in particular
the following methods must be provided:
- makeSettings
- onPanelActivated
@note: This mixin uses self.lastControl and self.sizerDict to keep track of the
controls added / and maintain ordering.
If you plan to maintain other controls in the same panel care will need to be taken.
"""
def __init__(self, *args, **kwargs):
"""
Mixin init, forwards args to other base class.
The other base class is likely L{gui.SettingsPanel}.
@param args: Positional args to passed to other base class.
@param kwargs: Keyword args to passed to other base class.
"""
self.sizerDict = {}
self.lastControl = None
super(AutoSettingsMixin, self).__init__(*args, **kwargs)
# because settings instances can be of type L{Driver} as well, we have to handle
# showing settings for non-instances. Because of this, we must reacquire a reference
# to the settings class whenever we wish to use it (via L{getSettings}) in case the instance changes.
# We also use the weakref to refresh the gui when an instance dies.
self._currentSettingsRef = weakref.ref(
self.getSettings(),
lambda ref: wx.CallAfter(self.refreshGui)
)
settingsSizer: wx.BoxSizer
@abstractmethod
def getSettings(self) -> AutoSettings:
...
@abstractmethod
def makeSettings(self, sizer: wx.BoxSizer):
"""Populate the panel with settings controls.
@note: Normally classes also inherit from settingsDialogs.SettingsPanel.
@param sizer: The sizer to which to add the settings controls.
"""
...
def _getSettingsStorage(self) -> Any:
""" Override to change storage object for setting values."""
return self.getSettings()
@property
def hasOptions(self) -> bool:
return bool(self.getSettings().supportedSettings)
@classmethod
def _setSliderStepSizes(cls, slider, setting):
slider.SetLineSize(setting.minStep)
slider.SetPageSize(setting.largeStep)
def _makeSliderSettingControl(
self,
setting: NumericDriverSetting,
settingsStorage: Any
) -> wx.BoxSizer:
"""Constructs appropriate GUI controls for given L{DriverSetting} such as label and slider.
@param setting: Setting to construct controls for
@param settingsStorage: where to get initial values / set values.
This param must have an attribute with a name matching setting.id.
In most cases it will be of type L{AutoSettings}
@return: wx.BoxSizer containing newly created controls.
"""
labeledControl = guiHelper.LabeledControlHelper(
self,
f"{setting.displayNameWithAccelerator}:",
nvdaControls.EnhancedInputSlider,
minValue=setting.minVal,
maxValue=setting.maxVal
)
lSlider=labeledControl.control
setattr(self, f"{setting.id}Slider", lSlider)
lSlider.Bind(wx.EVT_SLIDER, DriverSettingChanger(
settingsStorage, setting
))
self._setSliderStepSizes(lSlider, setting)
lSlider.SetValue(getattr(settingsStorage, setting.id))
if self.lastControl:
lSlider.MoveAfterInTabOrder(self.lastControl)
self.lastControl=lSlider
return labeledControl.sizer
def _makeStringSettingControl(
self,
setting: DriverSetting,
settingsStorage: Any
):
"""
Same as L{_makeSliderSettingControl} but for string settings displayed in a wx.Choice control
Options for the choice control come from the availableXstringvalues property
(Dict[id, StringParameterInfo]) on the instance returned by self.getSettings()
The id of the value is stored on settingsStorage.
Returns sizer with label and combobox.
"""
labelText = f"{setting.displayNameWithAccelerator}:"
stringSettingAttribName = f"_{setting.id}s"
setattr(
self,
stringSettingAttribName,
# Settings are stored as an ordered dict.
# Therefore wrap this inside a list call.
list(getattr(
self.getSettings(),
f"available{setting.id.capitalize()}s"
).values())
)
stringSettings = getattr(self, stringSettingAttribName)
labeledControl = guiHelper.LabeledControlHelper(
self,
labelText,
wx.Choice,
choices=[x.displayName for x in stringSettings]
)
lCombo = labeledControl.control
setattr(self, f"{setting.id}List", lCombo)
self.bindHelpEvent(
f"SpeechSettings{setting.displayName.capitalize()}",
lCombo
)
try:
cur = getattr(settingsStorage, setting.id)
selectionIndex = [
x.id for x in stringSettings
].index(cur)
lCombo.SetSelection(selectionIndex)
except ValueError:
pass
lCombo.Bind(
wx.EVT_CHOICE,
StringDriverSettingChanger(settingsStorage, setting, self)
)
if self.lastControl:
lCombo.MoveAfterInTabOrder(self.lastControl)
self.lastControl = lCombo
return labeledControl.sizer
def _makeBooleanSettingControl(
self,
setting: BooleanDriverSetting,
settingsStorage: Any
):
"""
Same as L{_makeSliderSettingControl} but for boolean settings. Returns checkbox.
"""
checkbox = wx.CheckBox(self, label=setting.displayNameWithAccelerator)
setattr(self, f"{setting.id}Checkbox", checkbox)
settingsStorageProxy = weakref.proxy(settingsStorage)
self.bindHelpEvent(f"SpeechSettings{setting.displayName.capitalize()}", checkbox)
def _onCheckChanged(evt: wx.CommandEvent):
evt.Skip() # allow other handlers to also process this event.
setattr(settingsStorageProxy, setting.id, evt.IsChecked())
checkbox.Bind(wx.EVT_CHECKBOX, _onCheckChanged)
checkbox.SetValue(getattr(
settingsStorage,
setting.id
))
if self.lastControl:
checkbox.MoveAfterInTabOrder(self.lastControl)
self.lastControl=checkbox
return checkbox
def updateDriverSettings(self, changedSetting=None):
"""
Creates, hides or updates existing GUI controls for all of supported settings.
"""
settingsInst = self.getSettings()
settingsStorage = self._getSettingsStorage()
# firstly check already created options
for name, sizer in self.sizerDict.items():
if name == changedSetting:
# Changing a setting shouldn't cause that setting itself to disappear.
continue
if not settingsInst.isSupported(name):
self.settingsSizer.Hide(sizer)
# Create new controls, update already existing
if gui._isDebug():
log.debug(f"Current sizerDict: {self.sizerDict!r}")
log.debug(f"Current supportedSettings: {self.getSettings().supportedSettings!r}")
for setting in settingsInst.supportedSettings:
if setting.id == changedSetting:
# Changing a setting shouldn't cause that setting's own values to change.
continue
if setting.id in self.sizerDict: # update a value
self._updateValueForControl(setting, settingsStorage)
else: # create a new control
self._createNewControl(setting, settingsStorage)
# Update graphical layout of the dialog
self.settingsSizer.Layout()
def _createNewControl(self, setting, settingsStorage):
settingMaker = self._getSettingMaker(setting)
try:
s = settingMaker(setting, settingsStorage)
except UnsupportedConfigParameterError:
log.debugWarning(f"Unsupported setting {setting.id}; ignoring", exc_info=True)
else:
self.sizerDict[setting.id] = s
self.settingsSizer.Insert(
len(self.sizerDict) - 1,
s,
border=10,
flag=wx.BOTTOM
)
def _getSettingMaker(self, setting):
if isinstance(setting, NumericDriverSetting):
settingMaker = self._makeSliderSettingControl
elif isinstance(setting, BooleanDriverSetting):
settingMaker = self._makeBooleanSettingControl
else:
settingMaker = self._makeStringSettingControl
return settingMaker
def _updateValueForControl(self, setting, settingsStorage):
self.settingsSizer.Show(self.sizerDict[setting.id])
if isinstance(setting, NumericDriverSetting):
getattr(self, f"{setting.id}Slider").SetValue(
getattr(settingsStorage, setting.id)
)
elif isinstance(setting, BooleanDriverSetting):
getattr(self, f"{setting.id}Checkbox").SetValue(
getattr(settingsStorage, setting.id)
)
else:
options = getattr(self, f"_{setting.id}s")
lCombo = getattr(self, f"{setting.id}List")
try:
cur = getattr(settingsStorage, setting.id)
indexOfItem = [x.id for x in options].index(cur)
lCombo.SetSelection(indexOfItem)
except ValueError:
pass
def onDiscard(self):
# unbind change events for string settings as wx closes combo boxes on cancel
settingsInst = self.getSettings()
for setting in settingsInst.supportedSettings:
if isinstance(setting, (NumericDriverSetting, BooleanDriverSetting)):
continue
getattr(self, f"{setting.id}List").Unbind(wx.EVT_CHOICE)
# restore settings
settingsInst.loadSettings()
def onSave(self):
self.getSettings().saveSettings()
def refreshGui(self):
if not self._currentSettingsRef():
if gui._isDebug():
log.debug("refreshing panel")
self.sizerDict.clear()
self.settingsSizer.Clear(delete_windows=True)
self._currentSettingsRef = weakref.ref(
self.getSettings(),
lambda ref: wx.CallAfter(self.refreshGui)
)
self.makeSettings(self.settingsSizer)
def onPanelActivated(self):
"""Called after the panel has been activated
@note: Normally classes also inherit from settingsDialogs.SettingsPanel.
"""
self.refreshGui()
super().onPanelActivated()
#: DriverSettingsMixin name is provided or backwards compatibility.
# The name DriverSettingsMixin should be considered deprecated, use AutoSettingsMixin instead.
DriverSettingsMixin = AutoSettingsMixin
class VoiceSettingsPanel(AutoSettingsMixin, SettingsPanel):
# Translators: This is the label for the voice settings panel.
title = _("Voice")
helpId = "SpeechSettings"
@property
def driver(self):
synth: SynthDriver = getSynth()
return synth
def getSettings(self) -> AutoSettings:
return self.driver
def makeSettings(self, settingsSizer):
# Construct synthesizer settings
self.updateDriverSettings()
settingsSizerHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: This is the label for a checkbox in the
# voice settings panel (if checked, text will be read using the voice for the language of the text).
autoLanguageSwitchingText = _("Automatic language switching (when supported)")
self.autoLanguageSwitchingCheckbox = settingsSizerHelper.addItem(
wx.CheckBox(
self,
label=autoLanguageSwitchingText
))
self.bindHelpEvent("SpeechSettingsLanguageSwitching", self.autoLanguageSwitchingCheckbox)
self.autoLanguageSwitchingCheckbox.SetValue(
config.conf["speech"]["autoLanguageSwitching"]
)
# Translators: This is the label for a checkbox in the
# voice settings panel (if checked, different voices for dialects will be used to
# read text in that dialect).
autoDialectSwitchingText = _("Automatic dialect switching (when supported)")
self.autoDialectSwitchingCheckbox = settingsSizerHelper.addItem(
wx.CheckBox(self, label=autoDialectSwitchingText)
)
self.bindHelpEvent("SpeechSettingsDialectSwitching", self.autoDialectSwitchingCheckbox)
self.autoDialectSwitchingCheckbox.SetValue(
config.conf["speech"]["autoDialectSwitching"]
)
# Translators: This is the label for a combobox in the
# voice settings panel (possible choices are none, some, most and all).
punctuationLabelText = _("Punctuation/symbol &level:")
symbolLevelLabels = characterProcessing.SPEECH_SYMBOL_LEVEL_LABELS
symbolLevelChoices = [
symbolLevelLabels[level] for level in characterProcessing.CONFIGURABLE_SPEECH_SYMBOL_LEVELS
]
self.symbolLevelList = settingsSizerHelper.addLabeledControl(
punctuationLabelText, wx.Choice, choices=symbolLevelChoices
)
self.bindHelpEvent("SpeechSettingsSymbolLevel", self.symbolLevelList)
curLevel = config.conf["speech"]["symbolLevel"]
self.symbolLevelList.SetSelection(
characterProcessing.CONFIGURABLE_SPEECH_SYMBOL_LEVELS.index(curLevel)
)
# Translators: This is the label for a checkbox in the
# voice settings panel (if checked, text will be read using the voice for the language of the text).
trustVoiceLanguageText = _("Trust voice's language when processing characters and symbols")
self.trustVoiceLanguageCheckbox = settingsSizerHelper.addItem(
wx.CheckBox(self, label=trustVoiceLanguageText)
)
self.bindHelpEvent("SpeechSettingsTrust", self.trustVoiceLanguageCheckbox)
self.trustVoiceLanguageCheckbox.SetValue(config.conf["speech"]["trustVoiceLanguage"])
includeCLDRText = _(
# Translators: This is the label for a checkbox in the
# voice settings panel (if checked, data from the unicode CLDR will be used
# to speak emoji descriptions).
"Include Unicode Consortium data (including emoji) when processing characters and symbols"
)
self.includeCLDRCheckbox = settingsSizerHelper.addItem(
wx.CheckBox(self, label=includeCLDRText)
)
self.includeCLDRCheckbox.SetValue(config.conf["speech"]["includeCLDR"])
minPitchChange = int(config.conf.getConfigValidation(
("speech", self.driver.name, "capPitchChange")
).kwargs["min"])
maxPitchChange = int(config.conf.getConfigValidation(
("speech", self.driver.name, "capPitchChange")
).kwargs["max"])
# Translators: This is a label for a setting in voice settings (an edit box to change
# voice pitch for capital letters; the higher the value, the pitch will be higher).
capPitchChangeLabelText = _("Capital pitch change percentage")
self.capPitchChangeEdit = settingsSizerHelper.addLabeledControl(
capPitchChangeLabelText,
nvdaControls.SelectOnFocusSpinCtrl,
min=minPitchChange,
max=maxPitchChange,
initial=config.conf["speech"][self.driver.name]["capPitchChange"])
self.bindHelpEvent(
"SpeechSettingsCapPitchChange",
self.capPitchChangeEdit
)
# Translators: This is the label for a checkbox in the
# voice settings panel.
sayCapForCapsText = _("Say &cap before capitals")
self.sayCapForCapsCheckBox = settingsSizerHelper.addItem(
wx.CheckBox(self, label=sayCapForCapsText)
)
self.bindHelpEvent("SpeechSettingsSayCapBefore", self.sayCapForCapsCheckBox)
self.sayCapForCapsCheckBox.SetValue(
config.conf["speech"][self.driver.name]["sayCapForCapitals"]
)
# Translators: This is the label for a checkbox in the
# voice settings panel.
beepForCapsText =_("&Beep for capitals")
self.beepForCapsCheckBox = settingsSizerHelper.addItem(
wx.CheckBox(self, label=beepForCapsText)
)
self.bindHelpEvent(
"SpeechSettingsBeepForCaps",
self.beepForCapsCheckBox
)
self.beepForCapsCheckBox.SetValue(
config.conf["speech"][self.driver.name]["beepForCapitals"]
)
# Translators: This is the label for a checkbox in the
# voice settings panel.
useSpellingFunctionalityText = _("Use &spelling functionality if supported")
self.useSpellingFunctionalityCheckBox = settingsSizerHelper.addItem(
wx.CheckBox(self, label=useSpellingFunctionalityText)
)
self.bindHelpEvent("SpeechSettingsUseSpelling", self.useSpellingFunctionalityCheckBox)
self.useSpellingFunctionalityCheckBox.SetValue(
config.conf["speech"][self.driver.name]["useSpellingFunctionality"]
)
def onSave(self):
AutoSettingsMixin.onSave(self)
config.conf["speech"]["autoLanguageSwitching"] = self.autoLanguageSwitchingCheckbox.IsChecked()
config.conf["speech"]["autoDialectSwitching"] = self.autoDialectSwitchingCheckbox.IsChecked()
config.conf["speech"]["symbolLevel"]=characterProcessing.CONFIGURABLE_SPEECH_SYMBOL_LEVELS[self.symbolLevelList.GetSelection()]
config.conf["speech"]["trustVoiceLanguage"]=self.trustVoiceLanguageCheckbox.IsChecked()
currentIncludeCLDR = config.conf["speech"]["includeCLDR"]
config.conf["speech"]["includeCLDR"] = newIncludeCldr = self.includeCLDRCheckbox.IsChecked()
if currentIncludeCLDR is not newIncludeCldr:
# Either included or excluded CLDR data, so clear the cache.
characterProcessing.clearSpeechSymbols()
config.conf["speech"][self.driver.name]["capPitchChange"]=self.capPitchChangeEdit.Value
config.conf["speech"][self.driver.name]["sayCapForCapitals"]=self.sayCapForCapsCheckBox.IsChecked()
config.conf["speech"][self.driver.name]["beepForCapitals"]=self.beepForCapsCheckBox.IsChecked()
config.conf["speech"][self.driver.name]["useSpellingFunctionality"]=self.useSpellingFunctionalityCheckBox.IsChecked()
class KeyboardSettingsPanel(SettingsPanel):
# Translators: This is the label for the keyboard settings panel.
title = _("Keyboard")
helpId = "KeyboardSettings"
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: This is the label for a combobox in the
# keyboard settings panel.
kbdLabelText = _("&Keyboard layout:")
layouts=keyboardHandler.KeyboardInputGesture.LAYOUTS
self.kbdNames=sorted(layouts)
kbdChoices = [layouts[layout] for layout in self.kbdNames]
self.kbdList=sHelper.addLabeledControl(kbdLabelText, wx.Choice, choices=kbdChoices)
self.bindHelpEvent("KeyboardSettingsLayout", self.kbdList)
try:
index=self.kbdNames.index(config.conf['keyboard']['keyboardLayout'])
self.kbdList.SetSelection(index)
except:
log.debugWarning("Could not set Keyboard layout list to current layout",exc_info=True)
#Translators: This is the label for a list of checkboxes
# controlling which keys are NVDA modifier keys.
modifierBoxLabel = _("&Select NVDA Modifier Keys")
self.modifierChoices = [keyLabels.localizedKeyLabels[key] for key in keyboardHandler.SUPPORTED_NVDA_MODIFIER_KEYS]
self.modifierList=sHelper.addLabeledControl(modifierBoxLabel, nvdaControls.CustomCheckListBox, choices=self.modifierChoices)
checkedItems = []
if config.conf["keyboard"]["useNumpadInsertAsNVDAModifierKey"]:
checkedItems.append(keyboardHandler.SUPPORTED_NVDA_MODIFIER_KEYS.index("numpadinsert"))
if config.conf["keyboard"]["useExtendedInsertAsNVDAModifierKey"]:
checkedItems.append(keyboardHandler.SUPPORTED_NVDA_MODIFIER_KEYS.index("insert"))
if config.conf["keyboard"]["useCapsLockAsNVDAModifierKey"]:
checkedItems.append(keyboardHandler.SUPPORTED_NVDA_MODIFIER_KEYS.index("capslock"))
self.modifierList.CheckedItems = checkedItems
self.modifierList.Select(0)
self.bindHelpEvent("KeyboardSettingsModifiers", self.modifierList)
# Translators: This is the label for a checkbox in the
# keyboard settings panel.
charsText = _("Speak typed &characters")
self.charsCheckBox=sHelper.addItem(wx.CheckBox(self,label=charsText))
self.bindHelpEvent(
"KeyboardSettingsSpeakTypedCharacters",
self.charsCheckBox
)
self.charsCheckBox.SetValue(config.conf["keyboard"]["speakTypedCharacters"])
# Translators: This is the label for a checkbox in the
# keyboard settings panel.
speakTypedWordsText = _("Speak typed &words")
self.wordsCheckBox=sHelper.addItem(wx.CheckBox(self,label=speakTypedWordsText))
self.bindHelpEvent("KeyboardSettingsSpeakTypedWords", self.wordsCheckBox)
self.wordsCheckBox.SetValue(config.conf["keyboard"]["speakTypedWords"])
# Translators: This is the label for a checkbox in the
# keyboard settings panel.
speechInterruptForCharText = _("Speech &interrupt for typed characters")
self.speechInterruptForCharsCheckBox=sHelper.addItem(wx.CheckBox(self,label=speechInterruptForCharText))
self.bindHelpEvent("KeyboardSettingsSpeechInteruptForCharacters", self.speechInterruptForCharsCheckBox)
self.speechInterruptForCharsCheckBox.SetValue(config.conf["keyboard"]["speechInterruptForCharacters"])
# Translators: This is the label for a checkbox in the
# keyboard settings panel.
speechInterruptForEnterText = _("Speech i&nterrupt for Enter key")
self.speechInterruptForEnterCheckBox=sHelper.addItem(wx.CheckBox(self,label=speechInterruptForEnterText))
self.speechInterruptForEnterCheckBox.SetValue(config.conf["keyboard"]["speechInterruptForEnter"])
self.bindHelpEvent("KeyboardSettingsSpeechInteruptForEnter", self.speechInterruptForEnterCheckBox)
# Translators: This is the label for a checkbox in the
# keyboard settings panel.
allowSkimReadingInSayAllText = _("Allow skim &reading in Say All")
self.skimReadingInSayAllCheckBox=sHelper.addItem(wx.CheckBox(self,label=allowSkimReadingInSayAllText))
self.bindHelpEvent("KeyboardSettingsSkimReading", self.skimReadingInSayAllCheckBox)
self.skimReadingInSayAllCheckBox.SetValue(config.conf["keyboard"]["allowSkimReadingInSayAll"])
# Translators: This is the label for a checkbox in the
# keyboard settings panel.
beepForLowercaseWithCapsLockText = _("&Beep if typing lowercase letters when caps lock is on")
self.beepLowercaseCheckBox=sHelper.addItem(wx.CheckBox(self,label=beepForLowercaseWithCapsLockText))
self.bindHelpEvent("SpeechSettingsBeepLowercase", self.beepLowercaseCheckBox)
self.beepLowercaseCheckBox.SetValue(config.conf["keyboard"]["beepForLowercaseWithCapslock"])
# Translators: This is the label for a checkbox in the
# keyboard settings panel.
commandKeysText = _("Speak c&ommand keys")
self.commandKeysCheckBox=sHelper.addItem(wx.CheckBox(self,label=commandKeysText))
self.bindHelpEvent("SpeechSettingsSpeakCommandKeys", self.commandKeysCheckBox)
self.commandKeysCheckBox.SetValue(config.conf["keyboard"]["speakCommandKeys"])
# Translators: This is the label for a checkbox in the
# keyboard settings panel.
alertForSpellingErrorsText = _("Play sound for &spelling errors while typing")
self.alertForSpellingErrorsCheckBox=sHelper.addItem(wx.CheckBox(self,label=alertForSpellingErrorsText))
self.bindHelpEvent("KeyboardSettingsAlertForSpellingErrors", self.alertForSpellingErrorsCheckBox)
self.alertForSpellingErrorsCheckBox.SetValue(config.conf["keyboard"]["alertForSpellingErrors"])
if not config.conf["documentFormatting"]["reportSpellingErrors"]:
self.alertForSpellingErrorsCheckBox.Disable()
# Translators: This is the label for a checkbox in the
# keyboard settings panel.
handleInjectedKeysText = _("Handle keys from other &applications")
self.handleInjectedKeysCheckBox=sHelper.addItem(wx.CheckBox(self,label=handleInjectedKeysText))
self.bindHelpEvent("KeyboardSettingsHandleKeys", self.handleInjectedKeysCheckBox)
self.handleInjectedKeysCheckBox.SetValue(config.conf["keyboard"]["handleInjectedKeys"])
def isValid(self):
# #2871: check whether at least one key is the nvda key.
if not self.modifierList.CheckedItems:
log.debugWarning("No NVDA key set")
gui.messageBox(
# Translators: Message to report wrong configuration of the NVDA key
_("At least one key must be used as the NVDA key."),
# Translators: The title of the message box
_("Error"), wx.OK|wx.ICON_ERROR,self)
return False
return super(KeyboardSettingsPanel, self).isValid()
def onSave(self):
layout=self.kbdNames[self.kbdList.GetSelection()]
config.conf['keyboard']['keyboardLayout']=layout
config.conf["keyboard"]["useNumpadInsertAsNVDAModifierKey"]= self.modifierList.IsChecked(keyboardHandler.SUPPORTED_NVDA_MODIFIER_KEYS.index("numpadinsert"))
config.conf["keyboard"]["useExtendedInsertAsNVDAModifierKey"] = self.modifierList.IsChecked(keyboardHandler.SUPPORTED_NVDA_MODIFIER_KEYS.index("insert"))
config.conf["keyboard"]["useCapsLockAsNVDAModifierKey"] = self.modifierList.IsChecked(keyboardHandler.SUPPORTED_NVDA_MODIFIER_KEYS.index("capslock"))
config.conf["keyboard"]["speakTypedCharacters"]=self.charsCheckBox.IsChecked()
config.conf["keyboard"]["speakTypedWords"]=self.wordsCheckBox.IsChecked()
config.conf["keyboard"]["speechInterruptForCharacters"]=self.speechInterruptForCharsCheckBox.IsChecked()
config.conf["keyboard"]["speechInterruptForEnter"]=self.speechInterruptForEnterCheckBox.IsChecked()
config.conf["keyboard"]["allowSkimReadingInSayAll"]=self.skimReadingInSayAllCheckBox.IsChecked()
config.conf["keyboard"]["beepForLowercaseWithCapslock"]=self.beepLowercaseCheckBox.IsChecked()
config.conf["keyboard"]["speakCommandKeys"]=self.commandKeysCheckBox.IsChecked()
config.conf["keyboard"]["alertForSpellingErrors"]=self.alertForSpellingErrorsCheckBox.IsChecked()
config.conf["keyboard"]["handleInjectedKeys"]=self.handleInjectedKeysCheckBox.IsChecked()
class MouseSettingsPanel(SettingsPanel):
# Translators: This is the label for the mouse settings panel.
title = _("Mouse")
helpId = "MouseSettings"
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: This is the label for a checkbox in the
# mouse settings panel.
shapeChangesText = _("Report mouse &shape changes")
self.shapeCheckBox=sHelper.addItem(wx.CheckBox(self,label=shapeChangesText))
self.bindHelpEvent("MouseSettingsShape", self.shapeCheckBox)
self.shapeCheckBox.SetValue(config.conf["mouse"]["reportMouseShapeChanges"])
# Translators: This is the label for a checkbox in the
# mouse settings panel.
mouseTrackingText=_("Enable mouse &tracking")
self.mouseTrackingCheckBox=sHelper.addItem(wx.CheckBox(self,label=mouseTrackingText))
self.bindHelpEvent("MouseSettingsTracking", self.mouseTrackingCheckBox)
self.mouseTrackingCheckBox.SetValue(config.conf["mouse"]["enableMouseTracking"])
# Translators: This is the label for a combobox in the
# mouse settings panel.
textUnitLabelText=_("Text &unit resolution:")
import textInfos
self.textUnits=textInfos.MOUSE_TEXT_RESOLUTION_UNITS
textUnitsChoices = [textInfos.unitLabels[x] for x in self.textUnits]
self.textUnitComboBox=sHelper.addLabeledControl(textUnitLabelText, wx.Choice, choices=textUnitsChoices)
self.bindHelpEvent("MouseSettingsTextUnit", self.textUnitComboBox)
try:
index=self.textUnits.index(config.conf["mouse"]["mouseTextUnit"])
except:
index=0
self.textUnitComboBox.SetSelection(index)
# Translators: This is the label for a checkbox in the
# mouse settings panel.
reportObjectRoleText = _("Report &role when mouse enters object")
self.reportObjectRoleCheckBox=sHelper.addItem(wx.CheckBox(self,label=reportObjectRoleText))
self.bindHelpEvent("MouseSettingsRole", self.reportObjectRoleCheckBox)
self.reportObjectRoleCheckBox.SetValue(config.conf["mouse"]["reportObjectRoleOnMouseEnter"])
# Translators: This is the label for a checkbox in the
# mouse settings panel.
audioText = _("&Play audio coordinates when mouse moves")
self.audioCheckBox=sHelper.addItem(wx.CheckBox(self,label=audioText))
self.bindHelpEvent("MouseSettingsAudio", self.audioCheckBox)
self.audioCheckBox.SetValue(config.conf["mouse"]["audioCoordinatesOnMouseMove"])
# Translators: This is the label for a checkbox in the
# mouse settings panel.
audioDetectBrightnessText = _("&Brightness controls audio coordinates volume")
self.audioDetectBrightnessCheckBox=sHelper.addItem(wx.CheckBox(self,label=audioDetectBrightnessText))
self.bindHelpEvent("MouseSettingsBrightness", self.audioDetectBrightnessCheckBox)
self.audioDetectBrightnessCheckBox.SetValue(config.conf["mouse"]["audioCoordinates_detectBrightness"])
# Translators: This is the label for a checkbox in the
# mouse settings panel.
ignoreInjectedMouseInputText = _("Ignore mouse input from other &applications")
self.ignoreInjectedMouseInputCheckBox=sHelper.addItem(wx.CheckBox(self,label=ignoreInjectedMouseInputText))
self.ignoreInjectedMouseInputCheckBox.SetValue(config.conf["mouse"]["ignoreInjectedMouseInput"])
def onSave(self):
config.conf["mouse"]["reportMouseShapeChanges"]=self.shapeCheckBox.IsChecked()
config.conf["mouse"]["enableMouseTracking"]=self.mouseTrackingCheckBox.IsChecked()
config.conf["mouse"]["mouseTextUnit"]=self.textUnits[self.textUnitComboBox.GetSelection()]
config.conf["mouse"]["reportObjectRoleOnMouseEnter"]=self.reportObjectRoleCheckBox.IsChecked()
config.conf["mouse"]["audioCoordinatesOnMouseMove"]=self.audioCheckBox.IsChecked()
config.conf["mouse"]["audioCoordinates_detectBrightness"]=self.audioDetectBrightnessCheckBox.IsChecked()
config.conf["mouse"]["ignoreInjectedMouseInput"]=self.ignoreInjectedMouseInputCheckBox.IsChecked()
class ReviewCursorPanel(SettingsPanel):
# Translators: This is the label for the review cursor settings panel.
title = _("Review Cursor")
helpId = "ReviewCursorSettings"
def makeSettings(self, settingsSizer):
# Translators: This is the label for a checkbox in the
# review cursor settings panel.
self.followFocusCheckBox = wx.CheckBox(self, label=_("Follow system &focus"))
self.bindHelpEvent("ReviewCursorFollowFocus", self.followFocusCheckBox)
self.followFocusCheckBox.SetValue(config.conf["reviewCursor"]["followFocus"])
settingsSizer.Add(self.followFocusCheckBox,border=10,flag=wx.BOTTOM)
# Translators: This is the label for a checkbox in the
# review cursor settings panel.
self.followCaretCheckBox = wx.CheckBox(self, label=_("Follow System &Caret"))
self.bindHelpEvent("ReviewCursorFollowCaret", self.followCaretCheckBox)
self.followCaretCheckBox.SetValue(config.conf["reviewCursor"]["followCaret"])
settingsSizer.Add(self.followCaretCheckBox,border=10,flag=wx.BOTTOM)
# Translators: This is the label for a checkbox in the
# review cursor settings panel.
self.followMouseCheckBox = wx.CheckBox(self, label=_("Follow &mouse cursor"))
self.bindHelpEvent("ReviewCursorFollowMouse", self.followMouseCheckBox)
self.followMouseCheckBox.SetValue(config.conf["reviewCursor"]["followMouse"])
settingsSizer.Add(self.followMouseCheckBox,border=10,flag=wx.BOTTOM)
# Translators: This is the label for a checkbox in the
# review cursor settings panel.
self.simpleReviewModeCheckBox = wx.CheckBox(self, label=_("&Simple review mode"))
self.bindHelpEvent("ReviewCursorSimple", self.simpleReviewModeCheckBox)
self.simpleReviewModeCheckBox.SetValue(config.conf["reviewCursor"]["simpleReviewMode"])
settingsSizer.Add(self.simpleReviewModeCheckBox,border=10,flag=wx.BOTTOM)
def onSave(self):
config.conf["reviewCursor"]["followFocus"]=self.followFocusCheckBox.IsChecked()
config.conf["reviewCursor"]["followCaret"]=self.followCaretCheckBox.IsChecked()
config.conf["reviewCursor"]["followMouse"]=self.followMouseCheckBox.IsChecked()
config.conf["reviewCursor"]["simpleReviewMode"]=self.simpleReviewModeCheckBox.IsChecked()
class InputCompositionPanel(SettingsPanel):
# Translators: This is the label for the Input Composition settings panel.
title = _("Input Composition")
helpId = "InputCompositionSettings"
def makeSettings(self, settingsSizer):
# Translators: This is the label for a checkbox in the
# Input composition settings panel.
self.autoReportAllCandidatesCheckBox=wx.CheckBox(self,wx.ID_ANY,label=_("Automatically report all available &candidates"))
self.bindHelpEvent("InputCompositionReportAllCandidates", self.autoReportAllCandidatesCheckBox)
self.autoReportAllCandidatesCheckBox.SetValue(config.conf["inputComposition"]["autoReportAllCandidates"])
settingsSizer.Add(self.autoReportAllCandidatesCheckBox,border=10,flag=wx.BOTTOM)
# Translators: This is the label for a checkbox in the
# Input composition settings panel.
self.announceSelectedCandidateCheckBox=wx.CheckBox(self,wx.ID_ANY,label=_("Announce &selected candidate"))
self.bindHelpEvent("InputCompositionAnnounceSelectedCandidate", self.announceSelectedCandidateCheckBox)
self.announceSelectedCandidateCheckBox.SetValue(config.conf["inputComposition"]["announceSelectedCandidate"])
settingsSizer.Add(self.announceSelectedCandidateCheckBox,border=10,flag=wx.BOTTOM)
# Translators: This is the label for a checkbox in the
# Input composition settings panel.
self.candidateIncludesShortCharacterDescriptionCheckBox=wx.CheckBox(self,wx.ID_ANY,label=_("Always include short character &description when announcing candidates"))
self.bindHelpEvent(
"InputCompositionCandidateIncludesShortCharacterDescription",
self.candidateIncludesShortCharacterDescriptionCheckBox
)
self.candidateIncludesShortCharacterDescriptionCheckBox.SetValue(config.conf["inputComposition"]["alwaysIncludeShortCharacterDescriptionInCandidateName"])
settingsSizer.Add(self.candidateIncludesShortCharacterDescriptionCheckBox,border=10,flag=wx.BOTTOM)
# Translators: This is the label for a checkbox in the
# Input composition settings panel.
self.reportReadingStringChangesCheckBox=wx.CheckBox(self,wx.ID_ANY,label=_("Report changes to the &reading string"))
self.bindHelpEvent(
"InputCompositionReadingStringChanges",
self.reportReadingStringChangesCheckBox
)
self.reportReadingStringChangesCheckBox.SetValue(config.conf["inputComposition"]["reportReadingStringChanges"])
settingsSizer.Add(self.reportReadingStringChangesCheckBox,border=10,flag=wx.BOTTOM)
# Translators: This is the label for a checkbox in the
# Input composition settings panel.
self.reportCompositionStringChangesCheckBox=wx.CheckBox(self,wx.ID_ANY,label=_("Report changes to the &composition string"))
self.bindHelpEvent(
"InputCompositionCompositionStringChanges",
self.reportCompositionStringChangesCheckBox
)
self.reportCompositionStringChangesCheckBox.SetValue(config.conf["inputComposition"]["reportCompositionStringChanges"])
settingsSizer.Add(self.reportCompositionStringChangesCheckBox,border=10,flag=wx.BOTTOM)
def onSave(self):
config.conf["inputComposition"]["autoReportAllCandidates"]=self.autoReportAllCandidatesCheckBox.IsChecked()
config.conf["inputComposition"]["announceSelectedCandidate"]=self.announceSelectedCandidateCheckBox.IsChecked()
config.conf["inputComposition"]["alwaysIncludeShortCharacterDescriptionInCandidateName"]=self.candidateIncludesShortCharacterDescriptionCheckBox.IsChecked()
config.conf["inputComposition"]["reportReadingStringChanges"]=self.reportReadingStringChangesCheckBox.IsChecked()
config.conf["inputComposition"]["reportCompositionStringChanges"]=self.reportCompositionStringChangesCheckBox.IsChecked()
class ObjectPresentationPanel(SettingsPanel):
# Translators: This is the label for the object presentation panel.
title = _("Object Presentation")
helpId = "ObjectPresentationSettings"
progressLabels = (
# Translators: An option for progress bar output in the Object Presentation dialog
# which disables reporting of progress bars.
# See Progress bar output in the Object Presentation Settings section of the User Guide.
("off", _("off")),
# Translators: An option for progress bar output in the Object Presentation dialog
# which reports progress bar updates by speaking.
# See Progress bar output in the Object Presentation Settings section of the User Guide.
("speak", _("Speak")),
# Translators: An option for progress bar output in the Object Presentation dialog
# which reports progress bar updates by beeping.
# See Progress bar output in the Object Presentation Settings section of the User Guide.
("beep", _("Beep")),
# Translators: An option for progress bar output in the Object Presentation dialog
# which reports progress bar updates by both speaking and beeping.
# See Progress bar output in the Object Presentation Settings section of the User Guide.
("both", _("Speak and beep")),
)
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: This is the label for a checkbox in the
# object presentation settings panel.
reportToolTipsText = _("Report &tooltips")
self.tooltipCheckBox=sHelper.addItem(wx.CheckBox(self,label=reportToolTipsText))
self.bindHelpEvent("ObjectPresentationReportToolTips", self.tooltipCheckBox)
self.tooltipCheckBox.SetValue(config.conf["presentation"]["reportTooltips"])
# Translators: This is the label for a checkbox in the
# object presentation settings panel.
balloonText = _("Report ¬ifications")
self.balloonCheckBox=sHelper.addItem(wx.CheckBox(self,label=balloonText))
self.bindHelpEvent("ObjectPresentationReportBalloons", self.balloonCheckBox)
self.balloonCheckBox.SetValue(config.conf["presentation"]["reportHelpBalloons"])
# Translators: This is the label for a checkbox in the
# object presentation settings panel.
shortcutText = _("Report object shortcut &keys")
self.shortcutCheckBox=sHelper.addItem(wx.CheckBox(self,label=shortcutText))
self.bindHelpEvent("ObjectPresentationShortcutKeys", self.shortcutCheckBox)
self.shortcutCheckBox.SetValue(config.conf["presentation"]["reportKeyboardShortcuts"])
# Translators: This is the label for a checkbox in the
# object presentation settings panel.
positionInfoText = _("Report object &position information")
self.positionInfoCheckBox=sHelper.addItem(wx.CheckBox(self,label=positionInfoText))
self.bindHelpEvent("ObjectPresentationPositionInfo", self.positionInfoCheckBox)
self.positionInfoCheckBox.SetValue(config.conf["presentation"]["reportObjectPositionInformation"])
# Translators: This is the label for a checkbox in the
# object presentation settings panel.
guessPositionInfoText = _("&Guess object position information when unavailable")
self.guessPositionInfoCheckBox=sHelper.addItem(wx.CheckBox(self,label=guessPositionInfoText))
self.bindHelpEvent("ObjectPresentationGuessPositionInfo", self.guessPositionInfoCheckBox)
self.guessPositionInfoCheckBox.SetValue(config.conf["presentation"]["guessObjectPositionInformationWhenUnavailable"])
# Translators: This is the label for a checkbox in the
# object presentation settings panel.
descriptionText = _("Report object &descriptions")
self.descriptionCheckBox=sHelper.addItem(wx.CheckBox(self,label=descriptionText))
self.bindHelpEvent("ObjectPresentationReportDescriptions", self.descriptionCheckBox)
self.descriptionCheckBox.SetValue(config.conf["presentation"]["reportObjectDescriptions"])
# Translators: This is the label for a combobox in the
# object presentation settings panel.
progressLabelText = _("Progress &bar output:")
progressChoices = [name for setting, name in self.progressLabels]
self.progressList=sHelper.addLabeledControl(progressLabelText, wx.Choice, choices=progressChoices)
self.bindHelpEvent("ObjectPresentationProgressBarOutput", self.progressList)
for index, (setting, name) in enumerate(self.progressLabels):
if setting == config.conf["presentation"]["progressBarUpdates"]["progressBarOutputMode"]:
self.progressList.SetSelection(index)
break
else:
log.debugWarning("Could not set progress list to current report progress bar updates setting")
# Translators: This is the label for a checkbox in the
# object presentation settings panel.
reportBackgroundProgressBarsText = _("Report backg&round progress bars")
self.reportBackgroundProgressBarsCheckBox=sHelper.addItem(wx.CheckBox(self,label=reportBackgroundProgressBarsText))
self.bindHelpEvent(
"ObjectPresentationReportBackgroundProgressBars",
self.reportBackgroundProgressBarsCheckBox
)
self.reportBackgroundProgressBarsCheckBox.SetValue(config.conf["presentation"]["progressBarUpdates"]["reportBackgroundProgressBars"])
# Translators: This is the label for a checkbox in the
# object presentation settings panel.
dynamicContentText = _("Report dynamic &content changes")
self.dynamicContentCheckBox=sHelper.addItem(wx.CheckBox(self,label=dynamicContentText))
self.bindHelpEvent(
"ObjectPresentationReportDynamicContent",
self.dynamicContentCheckBox
)
self.dynamicContentCheckBox.SetValue(config.conf["presentation"]["reportDynamicContentChanges"])
# Translators: This is the label for a checkbox in the
# object presentation settings panel.
autoSuggestionsLabelText = _("Play a sound when &auto-suggestions appear")
self.autoSuggestionSoundsCheckBox=sHelper.addItem(wx.CheckBox(self,label=autoSuggestionsLabelText))
self.bindHelpEvent(
"ObjectPresentationSuggestionSounds",
self.autoSuggestionSoundsCheckBox
)
self.autoSuggestionSoundsCheckBox.SetValue(config.conf["presentation"]["reportAutoSuggestionsWithSound"])
def onSave(self):
config.conf["presentation"]["reportTooltips"]=self.tooltipCheckBox.IsChecked()
config.conf["presentation"]["reportHelpBalloons"]=self.balloonCheckBox.IsChecked()
config.conf["presentation"]["reportKeyboardShortcuts"]=self.shortcutCheckBox.IsChecked()
config.conf["presentation"]["reportObjectPositionInformation"]=self.positionInfoCheckBox.IsChecked()
config.conf["presentation"]["guessObjectPositionInformationWhenUnavailable"]=self.guessPositionInfoCheckBox.IsChecked()
config.conf["presentation"]["reportObjectDescriptions"]=self.descriptionCheckBox.IsChecked()
config.conf["presentation"]["progressBarUpdates"]["progressBarOutputMode"]=self.progressLabels[self.progressList.GetSelection()][0]
config.conf["presentation"]["progressBarUpdates"]["reportBackgroundProgressBars"]=self.reportBackgroundProgressBarsCheckBox.IsChecked()
config.conf["presentation"]["reportDynamicContentChanges"]=self.dynamicContentCheckBox.IsChecked()
config.conf["presentation"]["reportAutoSuggestionsWithSound"]=self.autoSuggestionSoundsCheckBox.IsChecked()
class BrowseModePanel(SettingsPanel):
# Translators: This is the label for the browse mode settings panel.
title = _("Browse Mode")
helpId = "BrowseModeSettings"
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: This is the label for a textfield in the
# browse mode settings panel.
maxLengthLabelText = _("&Maximum number of characters on one line")
self.maxLengthEdit = sHelper.addLabeledControl(maxLengthLabelText, nvdaControls.SelectOnFocusSpinCtrl,
# min and max are not enforced in the config for virtualBuffers.maxLineLength
min=10, max=250,
initial=config.conf["virtualBuffers"]["maxLineLength"])
self.bindHelpEvent("BrowseModeSettingsMaxLength", self.maxLengthEdit)
# Translators: This is the label for a textfield in the
# browse mode settings panel.
pageLinesLabelText = _("&Number of lines per page")
self.pageLinesEdit = sHelper.addLabeledControl(pageLinesLabelText, nvdaControls.SelectOnFocusSpinCtrl,
# min and max are not enforced in the config for virtualBuffers.linesPerPage
min=5, max=150,
initial=config.conf["virtualBuffers"]["linesPerPage"])
self.bindHelpEvent("BrowseModeSettingsPageLines", self.pageLinesEdit)
# Translators: This is the label for a checkbox in the
# browse mode settings panel.
useScreenLayoutText = _("Use &screen layout (when supported)")
self.useScreenLayoutCheckBox = sHelper.addItem(wx.CheckBox(self, label=useScreenLayoutText))
self.bindHelpEvent("BrowseModeSettingsScreenLayout", self.useScreenLayoutCheckBox)
self.useScreenLayoutCheckBox.SetValue(config.conf["virtualBuffers"]["useScreenLayout"])
# Translators: The label for a checkbox in browse mode settings to
# enable browse mode on page load.
enableOnPageLoadText = _("&Enable browse mode on page load")
self.enableOnPageLoadCheckBox = sHelper.addItem(wx.CheckBox(self, label=enableOnPageLoadText))
self.enableOnPageLoadCheckBox.SetValue(config.conf["virtualBuffers"]["enableOnPageLoad"])
# Translators: This is the label for a checkbox in the
# browse mode settings panel.
autoSayAllText = _("Automatic &Say All on page load")
self.autoSayAllCheckBox = sHelper.addItem(wx.CheckBox(self, label=autoSayAllText))
self.bindHelpEvent("BrowseModeSettingsAutoSayAll", self.autoSayAllCheckBox)
self.autoSayAllCheckBox.SetValue(config.conf["virtualBuffers"]["autoSayAllOnPageLoad"])
# Translators: This is the label for a checkbox in the
# browse mode settings panel.
layoutTablesText = _("Include l&ayout tables")
self.layoutTablesCheckBox = sHelper.addItem(wx.CheckBox(self, label =layoutTablesText))
self.bindHelpEvent("BrowseModeSettingsIncludeLayoutTables", self.layoutTablesCheckBox)
self.layoutTablesCheckBox.SetValue(config.conf["documentFormatting"]["includeLayoutTables"])
# Translators: This is the label for a checkbox in the
# browse mode settings panel.
autoPassThroughOnFocusChangeText = _("Automatic focus mode for focus changes")
self.autoPassThroughOnFocusChangeCheckBox = sHelper.addItem(wx.CheckBox(self, label=autoPassThroughOnFocusChangeText))
self.bindHelpEvent(
"BrowseModeSettingsAutoPassThroughOnFocusChange",
self.autoPassThroughOnFocusChangeCheckBox
)
self.autoPassThroughOnFocusChangeCheckBox.SetValue(config.conf["virtualBuffers"]["autoPassThroughOnFocusChange"])
# Translators: This is the label for a checkbox in the
# browse mode settings panel.
autoPassThroughOnCaretMoveText = _("Automatic focus mode for caret movement")
self.autoPassThroughOnCaretMoveCheckBox = sHelper.addItem(wx.CheckBox(self, label=autoPassThroughOnCaretMoveText))
self.bindHelpEvent(
"BrowseModeSettingsAutoPassThroughOnCaretMove",
self.autoPassThroughOnCaretMoveCheckBox
)
self.autoPassThroughOnCaretMoveCheckBox.SetValue(config.conf["virtualBuffers"]["autoPassThroughOnCaretMove"])
# Translators: This is the label for a checkbox in the
# browse mode settings panel.
passThroughAudioIndicationText = _("Audio indication of focus and browse modes")
self.passThroughAudioIndicationCheckBox = sHelper.addItem(wx.CheckBox(self, label=passThroughAudioIndicationText))
self.bindHelpEvent(
"BrowseModeSettingsPassThroughAudioIndication",
self.passThroughAudioIndicationCheckBox
)
self.passThroughAudioIndicationCheckBox.SetValue(config.conf["virtualBuffers"]["passThroughAudioIndication"])
# Translators: This is the label for a checkbox in the
# browse mode settings panel.
trapNonCommandGesturesText = _("&Trap all non-command gestures from reaching the document")
self.trapNonCommandGesturesCheckBox = sHelper.addItem(wx.CheckBox(self, label=trapNonCommandGesturesText))
self.bindHelpEvent(
"BrowseModeSettingsTrapNonCommandGestures",
self.trapNonCommandGesturesCheckBox
)
self.trapNonCommandGesturesCheckBox.SetValue(config.conf["virtualBuffers"]["trapNonCommandGestures"])
# Translators: This is the label for a checkbox in the
# browse mode settings panel.
autoFocusFocusableElementsText = _("Automatically set system &focus to focusable elements")
self.autoFocusFocusableElementsCheckBox = sHelper.addItem(
wx.CheckBox(self, label=autoFocusFocusableElementsText)
)
self.autoFocusFocusableElementsCheckBox.SetValue(
config.conf["virtualBuffers"]["autoFocusFocusableElements"]
)
def onSave(self):
config.conf["virtualBuffers"]["maxLineLength"]=self.maxLengthEdit.GetValue()
config.conf["virtualBuffers"]["linesPerPage"]=self.pageLinesEdit.GetValue()
config.conf["virtualBuffers"]["useScreenLayout"]=self.useScreenLayoutCheckBox.IsChecked()
config.conf["virtualBuffers"]["enableOnPageLoad"] = self.enableOnPageLoadCheckBox.IsChecked()
config.conf["virtualBuffers"]["autoSayAllOnPageLoad"]=self.autoSayAllCheckBox.IsChecked()
config.conf["documentFormatting"]["includeLayoutTables"]=self.layoutTablesCheckBox.IsChecked()
config.conf["virtualBuffers"]["autoPassThroughOnFocusChange"]=self.autoPassThroughOnFocusChangeCheckBox.IsChecked()
config.conf["virtualBuffers"]["autoPassThroughOnCaretMove"]=self.autoPassThroughOnCaretMoveCheckBox.IsChecked()
config.conf["virtualBuffers"]["passThroughAudioIndication"]=self.passThroughAudioIndicationCheckBox.IsChecked()
config.conf["virtualBuffers"]["trapNonCommandGestures"]=self.trapNonCommandGesturesCheckBox.IsChecked()
config.conf["virtualBuffers"]["autoFocusFocusableElements"] = (
self.autoFocusFocusableElementsCheckBox.IsChecked()
)
class DocumentFormattingPanel(SettingsPanel):
# Translators: This is the label for the document formatting panel.
title = _("Document Formatting")
helpId = "DocumentFormattingSettings"
# Translators: This is a label appearing on the document formatting settings panel.
panelDescription = _("The following options control the types of document formatting reported by NVDA.")
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
sHelper.addItem(wx.StaticText(self, label=self.panelDescription))
# Translators: This is the label for a group of document formatting options in the
# document formatting settings panel
fontGroupText = _("Font")
fontGroup = guiHelper.BoxSizerHelper(self, sizer=wx.StaticBoxSizer(wx.StaticBox(self, label=fontGroupText), wx.VERTICAL))
sHelper.addItem(fontGroup)
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
fontNameText = _("&Font name")
self.fontNameCheckBox=fontGroup.addItem(wx.CheckBox(self, label=fontNameText))
self.fontNameCheckBox.SetValue(config.conf["documentFormatting"]["reportFontName"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
fontSizeText = _("Font &size")
self.fontSizeCheckBox=fontGroup.addItem(wx.CheckBox(self,label=fontSizeText))
self.fontSizeCheckBox.SetValue(config.conf["documentFormatting"]["reportFontSize"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
fontAttributesText = _("Font attrib&utes")
self.fontAttrsCheckBox=fontGroup.addItem(wx.CheckBox(self,label=fontAttributesText))
self.fontAttrsCheckBox.SetValue(config.conf["documentFormatting"]["reportFontAttributes"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
superscriptsAndSubscriptsText = _("Su&perscripts and subscripts")
self.superscriptsAndSubscriptsCheckBox = fontGroup.addItem(
wx.CheckBox(self, label=superscriptsAndSubscriptsText)
)
self.superscriptsAndSubscriptsCheckBox.SetValue(
config.conf["documentFormatting"]["reportSuperscriptsAndSubscripts"]
)
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
emphasisText=_("E&mphasis")
self.emphasisCheckBox=fontGroup.addItem(wx.CheckBox(self,label=emphasisText))
self.emphasisCheckBox.SetValue(config.conf["documentFormatting"]["reportEmphasis"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
highlightText = _("Marked (highlighted text)")
self.highlightCheckBox = fontGroup.addItem(
wx.CheckBox(self, label=highlightText)
)
self.highlightCheckBox.SetValue(
config.conf["documentFormatting"]["reportHighlight"]
)
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
styleText =_("St&yle")
self.styleCheckBox=fontGroup.addItem(wx.CheckBox(self,label=styleText))
self.styleCheckBox.SetValue(config.conf["documentFormatting"]["reportStyle"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
colorsText = _("&Colors")
self.colorCheckBox=fontGroup.addItem(wx.CheckBox(self,label=colorsText))
self.colorCheckBox.SetValue(config.conf["documentFormatting"]["reportColor"])
# Translators: This is the label for a group of document formatting options in the
# document formatting settings panel
documentInfoGroupText = _("Document information")
docInfoGroup = guiHelper.BoxSizerHelper(self, sizer=wx.StaticBoxSizer(wx.StaticBox(self, label=documentInfoGroupText), wx.VERTICAL))
sHelper.addItem(docInfoGroup)
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
commentsText = _("No&tes and comments")
self.commentsCheckBox=docInfoGroup.addItem(wx.CheckBox(self,label=commentsText))
self.commentsCheckBox.SetValue(config.conf["documentFormatting"]["reportComments"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
revisionsText = _("&Editor revisions")
self.revisionsCheckBox=docInfoGroup.addItem(wx.CheckBox(self,label=revisionsText))
self.revisionsCheckBox.SetValue(config.conf["documentFormatting"]["reportRevisions"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
spellingErrorText = _("Spelling e&rrors")
self.spellingErrorsCheckBox=docInfoGroup.addItem(wx.CheckBox(self,label=spellingErrorText))
self.spellingErrorsCheckBox.SetValue(config.conf["documentFormatting"]["reportSpellingErrors"])
# Translators: This is the label for a group of document formatting options in the
# document formatting settings panel
pageAndSpaceGroupText = _("Pages and spacing")
pageAndSpaceGroup = guiHelper.BoxSizerHelper(self, sizer=wx.StaticBoxSizer(wx.StaticBox(self, label=pageAndSpaceGroupText), wx.VERTICAL))
sHelper.addItem(pageAndSpaceGroup)
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
pageText = _("&Pages")
self.pageCheckBox=pageAndSpaceGroup.addItem(wx.CheckBox(self,label=pageText))
self.pageCheckBox.SetValue(config.conf["documentFormatting"]["reportPage"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
lineText = _("Line &numbers")
self.lineNumberCheckBox=pageAndSpaceGroup.addItem(wx.CheckBox(self,label=lineText))
self.lineNumberCheckBox.SetValue(config.conf["documentFormatting"]["reportLineNumber"])
# Translators: This is the label for a combobox controlling the reporting of line indentation in the
# Document Formatting dialog (possible choices are Off, Speech, Tones, or Both.
lineIndentationText = _("Line &indentation reporting:")
indentChoices=[
#Translators: A choice in a combo box in the document formatting dialog to report No line Indentation.
_("Off"),
#Translators: A choice in a combo box in the document formatting dialog to report indentation with Speech.
pgettext('line indentation setting', "Speech"),
#Translators: A choice in a combo box in the document formatting dialog to report indentation with tones.
_("Tones"),
#Translators: A choice in a combo box in the document formatting dialog to report indentation with both Speech and tones.
_("Both Speech and Tones")
]
self.lineIndentationCombo = pageAndSpaceGroup.addLabeledControl(lineIndentationText, wx.Choice, choices=indentChoices)
self.bindHelpEvent(
"DocumentFormattingSettingsLineIndentation",
self.lineIndentationCombo
)
#We use bitwise operations because it saves us a four way if statement.
curChoice = config.conf["documentFormatting"]["reportLineIndentationWithTones"] << 1 | config.conf["documentFormatting"]["reportLineIndentation"]
self.lineIndentationCombo.SetSelection(curChoice)
# Translators: This message is presented in the document formatting settings panelue
# If this option is selected, NVDA will report paragraph indentation if available.
paragraphIndentationText = _("&Paragraph indentation")
self.paragraphIndentationCheckBox=pageAndSpaceGroup.addItem(wx.CheckBox(self,label=paragraphIndentationText))
self.paragraphIndentationCheckBox.SetValue(config.conf["documentFormatting"]["reportParagraphIndentation"])
# Translators: This message is presented in the document formatting settings panelue
# If this option is selected, NVDA will report line spacing if available.
lineSpacingText=_("&Line spacing")
self.lineSpacingCheckBox=pageAndSpaceGroup.addItem(wx.CheckBox(self,label=lineSpacingText))
self.lineSpacingCheckBox.SetValue(config.conf["documentFormatting"]["reportLineSpacing"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
alignmentText = _("&Alignment")
self.alignmentCheckBox=pageAndSpaceGroup.addItem(wx.CheckBox(self,label=alignmentText))
self.alignmentCheckBox.SetValue(config.conf["documentFormatting"]["reportAlignment"])
# Translators: This is the label for a group of document formatting options in the
# document formatting settings panel
tablesGroupText = _("Table information")
tablesGroup = guiHelper.BoxSizerHelper(self, sizer=wx.StaticBoxSizer(wx.StaticBox(self, label=tablesGroupText), wx.VERTICAL))
sHelper.addItem(tablesGroup)
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.tablesCheckBox=tablesGroup.addItem(wx.CheckBox(self,label=_("&Tables")))
self.tablesCheckBox.SetValue(config.conf["documentFormatting"]["reportTables"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.tableHeadersCheckBox=tablesGroup.addItem(wx.CheckBox(self,label=_("Row/column h&eaders")))
self.tableHeadersCheckBox.SetValue(config.conf["documentFormatting"]["reportTableHeaders"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.tableCellCoordsCheckBox=tablesGroup.addItem(wx.CheckBox(self,label=_("Cell c&oordinates")))
self.tableCellCoordsCheckBox.SetValue(config.conf["documentFormatting"]["reportTableCellCoords"])
borderChoices=[
# Translators: This is the label for a combobox in the
# document formatting settings panel.
_("Off"),
# Translators: This is the label for a combobox in the
# document formatting settings panel.
_("Styles"),
# Translators: This is the label for a combobox in the
# document formatting settings panel.
_("Both Colors and Styles"),
]
self.borderComboBox = tablesGroup.addLabeledControl(
# Translators: This is the label for a combobox in the
# document formatting settings panel.
_("Cell &borders:"),
wx.Choice,
choices=borderChoices
)
curChoice = 0
if config.conf["documentFormatting"]["reportBorderStyle"]:
if config.conf["documentFormatting"]["reportBorderColor"]:
curChoice = 2
else:
curChoice = 1
self.borderComboBox.SetSelection(curChoice)
# Translators: This is the label for a group of document formatting options in the
# document formatting settings panel
elementsGroupText = _("Elements")
elementsGroup = guiHelper.BoxSizerHelper(self, sizer=wx.StaticBoxSizer(wx.StaticBox(self, label=elementsGroupText), wx.VERTICAL))
sHelper.addItem(elementsGroup, flag=wx.EXPAND, proportion=1)
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.headingsCheckBox=elementsGroup.addItem(wx.CheckBox(self,label=_("&Headings")))
self.headingsCheckBox.SetValue(config.conf["documentFormatting"]["reportHeadings"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.linksCheckBox=elementsGroup.addItem(wx.CheckBox(self,label=_("Lin&ks")))
self.linksCheckBox.SetValue(config.conf["documentFormatting"]["reportLinks"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.graphicsCheckBox = elementsGroup.addItem(wx.CheckBox(self, label=_("&Graphics")))
self.graphicsCheckBox.SetValue(config.conf["documentFormatting"]["reportGraphics"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.listsCheckBox=elementsGroup.addItem(wx.CheckBox(self,label=_("&Lists")))
self.listsCheckBox.SetValue(config.conf["documentFormatting"]["reportLists"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.blockQuotesCheckBox=elementsGroup.addItem(wx.CheckBox(self,label=_("Block "es")))
self.blockQuotesCheckBox.SetValue(config.conf["documentFormatting"]["reportBlockQuotes"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
groupingsText = _("&Groupings")
self.groupingsCheckBox = elementsGroup.addItem(wx.CheckBox(self, label=groupingsText))
self.groupingsCheckBox.SetValue(config.conf["documentFormatting"]["reportGroupings"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
landmarksText = _("Lan&dmarks and regions")
self.landmarksCheckBox = elementsGroup.addItem(wx.CheckBox(self, label=landmarksText))
self.landmarksCheckBox.SetValue(config.conf["documentFormatting"]["reportLandmarks"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.articlesCheckBox = elementsGroup.addItem(wx.CheckBox(self, label=_("Arti&cles")))
self.articlesCheckBox.SetValue(config.conf["documentFormatting"]["reportArticles"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.framesCheckBox=elementsGroup.addItem(wx.CheckBox(self,label=_("Fra&mes")))
self.framesCheckBox.Value=config.conf["documentFormatting"]["reportFrames"]
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.clickableCheckBox=elementsGroup.addItem(wx.CheckBox(self,label=_("&Clickable")))
self.clickableCheckBox.Value=config.conf["documentFormatting"]["reportClickable"]
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
detectFormatAfterCursorText = _("Report formatting chan&ges after the cursor (can cause a lag)")
self.detectFormatAfterCursorCheckBox=wx.CheckBox(self, label=detectFormatAfterCursorText)
self.bindHelpEvent(
"DocumentFormattingDetectFormatAfterCursor",
self.detectFormatAfterCursorCheckBox
)
self.detectFormatAfterCursorCheckBox.SetValue(config.conf["documentFormatting"]["detectFormatAfterCursor"])
sHelper.addItem(self.detectFormatAfterCursorCheckBox)
def onSave(self):
config.conf["documentFormatting"]["detectFormatAfterCursor"]=self.detectFormatAfterCursorCheckBox.IsChecked()
config.conf["documentFormatting"]["reportFontName"]=self.fontNameCheckBox.IsChecked()
config.conf["documentFormatting"]["reportFontSize"]=self.fontSizeCheckBox.IsChecked()
config.conf["documentFormatting"]["reportFontAttributes"]=self.fontAttrsCheckBox.IsChecked()
config.conf["documentFormatting"]["reportSuperscriptsAndSubscripts"] = (
self.superscriptsAndSubscriptsCheckBox.IsChecked()
)
config.conf["documentFormatting"]["reportColor"]=self.colorCheckBox.IsChecked()
config.conf["documentFormatting"]["reportComments"]=self.commentsCheckBox.IsChecked()
config.conf["documentFormatting"]["reportRevisions"]=self.revisionsCheckBox.IsChecked()
config.conf["documentFormatting"]["reportEmphasis"]=self.emphasisCheckBox.IsChecked()
config.conf["documentFormatting"]["reportHighlight"] = self.highlightCheckBox.IsChecked()
config.conf["documentFormatting"]["reportAlignment"]=self.alignmentCheckBox.IsChecked()
config.conf["documentFormatting"]["reportStyle"]=self.styleCheckBox.IsChecked()
config.conf["documentFormatting"]["reportSpellingErrors"]=self.spellingErrorsCheckBox.IsChecked()
config.conf["documentFormatting"]["reportPage"]=self.pageCheckBox.IsChecked()
config.conf["documentFormatting"]["reportLineNumber"]=self.lineNumberCheckBox.IsChecked()
choice = self.lineIndentationCombo.GetSelection()
config.conf["documentFormatting"]["reportLineIndentation"] = choice in (1, 3)
config.conf["documentFormatting"]["reportLineIndentationWithTones"] = choice in (2, 3)
config.conf["documentFormatting"]["reportParagraphIndentation"]=self.paragraphIndentationCheckBox.IsChecked()
config.conf["documentFormatting"]["reportLineSpacing"]=self.lineSpacingCheckBox.IsChecked()
config.conf["documentFormatting"]["reportTables"]=self.tablesCheckBox.IsChecked()
config.conf["documentFormatting"]["reportTableHeaders"]=self.tableHeadersCheckBox.IsChecked()
config.conf["documentFormatting"]["reportTableCellCoords"]=self.tableCellCoordsCheckBox.IsChecked()
choice = self.borderComboBox.GetSelection()
config.conf["documentFormatting"]["reportBorderStyle"] = choice in (1,2)
config.conf["documentFormatting"]["reportBorderColor"] = (choice == 2)
config.conf["documentFormatting"]["reportLinks"]=self.linksCheckBox.IsChecked()
config.conf["documentFormatting"]["reportGraphics"] = self.graphicsCheckBox.IsChecked()
config.conf["documentFormatting"]["reportHeadings"]=self.headingsCheckBox.IsChecked()
config.conf["documentFormatting"]["reportLists"]=self.listsCheckBox.IsChecked()
config.conf["documentFormatting"]["reportBlockQuotes"]=self.blockQuotesCheckBox.IsChecked()
config.conf["documentFormatting"]["reportGroupings"] = self.groupingsCheckBox.IsChecked()
config.conf["documentFormatting"]["reportLandmarks"]=self.landmarksCheckBox.IsChecked()
config.conf["documentFormatting"]["reportArticles"] = self.articlesCheckBox.IsChecked()
config.conf["documentFormatting"]["reportFrames"]=self.framesCheckBox.Value
config.conf["documentFormatting"]["reportClickable"]=self.clickableCheckBox.Value
class TouchInteractionPanel(SettingsPanel):
# Translators: This is the label for the touch interaction settings panel.
title = _("Touch Interaction")
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: This is the label for a checkbox in the
# touch interaction settings panel.
touchSupportEnableLabel = _("Enable touch interaction support")
self.enableTouchSupportCheckBox = sHelper.addItem(wx.CheckBox(self, label=touchSupportEnableLabel))
self.enableTouchSupportCheckBox.SetValue(config.conf["touch"]["enabled"])
# Translators: This is the label for a checkbox in the
# touch interaction settings panel.
self.touchTypingCheckBox = sHelper.addItem(wx.CheckBox(self, label=_("&Touch typing mode")))
self.touchTypingCheckBox.SetValue(config.conf["touch"]["touchTyping"])
def onSave(self):
config.conf["touch"]["enabled"] = self.enableTouchSupportCheckBox.IsChecked()
config.conf["touch"]["touchTyping"] = self.touchTypingCheckBox.IsChecked()
touchHandler.setTouchSupport(config.conf["touch"]["enabled"])
class UwpOcrPanel(SettingsPanel):
# Translators: The title of the Windows 10 OCR panel.
title = _("Windows 10 OCR")
helpId = "Win10OcrSettings"
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Lazily import this.
from contentRecog import uwpOcr
self.languageCodes = uwpOcr.getLanguages()
languageChoices = [
languageHandler.getLanguageDescription(languageHandler.normalizeLanguage(lang))
for lang in self.languageCodes]
# Translators: Label for an option in the Windows 10 OCR dialog.
languageLabel = _("Recognition &language:")
self.languageChoice = sHelper.addLabeledControl(languageLabel, wx.Choice, choices=languageChoices)
self.bindHelpEvent("Win10OcrSettingsRecognitionLanguage", self.languageChoice)
try:
langIndex = self.languageCodes.index(config.conf["uwpOcr"]["language"])
self.languageChoice.Selection = langIndex
except ValueError:
self.languageChoice.Selection = 0
def onSave(self):
lang = self.languageCodes[self.languageChoice.Selection]
config.conf["uwpOcr"]["language"] = lang
class AdvancedPanelControls(wx.Panel):
"""Holds the actual controls for the Advanced Settings panel, this allows the state of the controls to
be more easily managed.
"""
def __init__(self, parent):
super(AdvancedPanelControls, self).__init__(parent)
self._defaultsRestored = False
sHelper = guiHelper.BoxSizerHelper(self, orientation=wx.VERTICAL)
self.SetSizer(sHelper.sizer)
# Translators: This is the label for a group of advanced options in the
# Advanced settings panel
groupText = _("NVDA Development")
devGroup = guiHelper.BoxSizerHelper(
parent=self,
sizer=wx.StaticBoxSizer(parent=self, label=groupText, orient=wx.VERTICAL)
)
sHelper.addItem(devGroup)
# Translators: This is the label for a checkbox in the
# Advanced settings panel.
label = _("Enable loading custom code from Developer Scratchpad directory")
self.scratchpadCheckBox=devGroup.addItem(wx.CheckBox(self, label=label))
self.scratchpadCheckBox.SetValue(config.conf["development"]["enableScratchpadDir"])
self.scratchpadCheckBox.defaultValue = self._getDefaultValue(["development", "enableScratchpadDir"])
self.scratchpadCheckBox.Bind(
wx.EVT_CHECKBOX,
lambda evt: self.openScratchpadButton.Enable(evt.IsChecked())
)
if config.isAppX:
self.scratchpadCheckBox.Disable()
# Translators: the label for a button in the Advanced settings category
label=_("Open developer scratchpad directory")
self.openScratchpadButton=devGroup.addItem(wx.Button(self, label=label))
self.openScratchpadButton.Enable(config.conf["development"]["enableScratchpadDir"])
self.openScratchpadButton.Bind(wx.EVT_BUTTON,self.onOpenScratchpadDir)
if config.isAppX:
self.openScratchpadButton.Disable()
# Translators: This is the label for a group of advanced options in the
# Advanced settings panel
label = _("Microsoft UI Automation")
UIAGroup = guiHelper.BoxSizerHelper(
parent=self,
sizer=wx.StaticBoxSizer(parent=self, label=label, orient=wx.VERTICAL)
)
sHelper.addItem(UIAGroup)
# Translators: This is the label for a checkbox in the
# Advanced settings panel.
label = _("Enable &selective registration for UI Automation events and property changes")
self.selectiveUIAEventRegistrationCheckBox = UIAGroup.addItem(wx.CheckBox(self, label=label))
self.selectiveUIAEventRegistrationCheckBox.SetValue(config.conf["UIA"]["selectiveEventRegistration"])
self.selectiveUIAEventRegistrationCheckBox.defaultValue = (
self._getDefaultValue(["UIA", "selectiveEventRegistration"])
)
# Translators: This is the label for a checkbox in the
# Advanced settings panel.
label = _("Use UI Automation to access Microsoft &Word document controls when available")
self.UIAInMSWordCheckBox=UIAGroup.addItem(wx.CheckBox(self, label=label))
self.UIAInMSWordCheckBox.SetValue(config.conf["UIA"]["useInMSWordWhenAvailable"])
self.UIAInMSWordCheckBox.defaultValue = self._getDefaultValue(["UIA", "useInMSWordWhenAvailable"])
# Translators: This is the label for a checkbox in the
# Advanced settings panel.
label = _("Use UI Automation to access the Windows C&onsole when available")
consoleUIADevMap = True if config.conf['UIA']['winConsoleImplementation'] == 'UIA' else False
self.ConsoleUIACheckBox = UIAGroup.addItem(wx.CheckBox(self, label=label))
self.ConsoleUIACheckBox.SetValue(consoleUIADevMap)
self.ConsoleUIACheckBox.defaultValue = self._getDefaultValue(["UIA", "winConsoleImplementation"])
# Translators: This is the label for a checkbox in the
# Advanced settings panel.
label = _("Speak &passwords in UIA consoles (may improve performance)")
self.winConsoleSpeakPasswordsCheckBox = UIAGroup.addItem(wx.CheckBox(self, label=label))
self.winConsoleSpeakPasswordsCheckBox.SetValue(config.conf["terminals"]["speakPasswords"])
self.winConsoleSpeakPasswordsCheckBox.defaultValue = self._getDefaultValue(["terminals", "speakPasswords"])
# Translators: This is the label for a group of advanced options in the
# Advanced settings panel
label = _("Terminal programs")
terminalsGroup = guiHelper.BoxSizerHelper(
parent=self,
sizer=wx.StaticBoxSizer(parent=self, label=label, orient=wx.VERTICAL)
)
sHelper.addItem(terminalsGroup)
# Translators: This is the label for a checkbox in the
# Advanced settings panel.
label = _("Use the new t&yped character support in Windows Console when available")
self.keyboardSupportInLegacyCheckBox=terminalsGroup.addItem(wx.CheckBox(self, label=label))
self.keyboardSupportInLegacyCheckBox.SetValue(config.conf["terminals"]["keyboardSupportInLegacy"])
self.keyboardSupportInLegacyCheckBox.defaultValue = self._getDefaultValue(["terminals", "keyboardSupportInLegacy"])
self.keyboardSupportInLegacyCheckBox.Enable(winVersion.isWin10(1607))
# Translators: This is the label for a group of advanced options in the
# Advanced settings panel
label = _("Speech")
speechGroup = guiHelper.BoxSizerHelper(
parent=self,
sizer=wx.StaticBoxSizer(parent=self, label=label, orient=wx.VERTICAL)
)
sHelper.addItem(speechGroup)
expiredFocusSpeechChoices = [
# Translators: Label for the 'Cancel speech for expired &focus events' combobox
# in the Advanced settings panel.
_("Default (No)"),
# Translators: Label for the 'Cancel speech for expired &focus events' combobox
# in the Advanced settings panel.
_("Yes"),
# Translators: Label for the 'Cancel speech for expired &focus events' combobox
# in the Advanced settings panel.
_("No"),
]
# Translators: This is the label for combobox in the Advanced settings panel.
cancelExpiredFocusSpeechText = _("Attempt to cancel speech for expired focus events:")
self.cancelExpiredFocusSpeechCombo: wx.Choice = speechGroup.addLabeledControl(
cancelExpiredFocusSpeechText,
wx.Choice,
choices=expiredFocusSpeechChoices
)
self.cancelExpiredFocusSpeechCombo.SetSelection(
config.conf["featureFlag"]["cancelExpiredFocusSpeech"]
)
self.cancelExpiredFocusSpeechCombo.defaultValue = self._getDefaultValue(
["featureFlag", "cancelExpiredFocusSpeech"]
)
# Translators: This is the label for a group of advanced options in the
# Advanced settings panel
label = _("Editable Text")
editableTextGroup = guiHelper.BoxSizerHelper(
self,
sizer=wx.StaticBoxSizer(parent=self, label=label, orient=wx.VERTICAL)
)
sHelper.addItem(editableTextGroup)
# Translators: This is the label for a numeric control in the
# Advanced settings panel.
label = _("Caret movement timeout (in ms)")
self.caretMoveTimeoutSpinControl=editableTextGroup.addLabeledControl(
label,
nvdaControls.SelectOnFocusSpinCtrl,
min=0,
max=2000,
initial=config.conf["editableText"]["caretMoveTimeoutMs"]
)
self.caretMoveTimeoutSpinControl.defaultValue = self._getDefaultValue(["editableText", "caretMoveTimeoutMs"])
# Translators: This is the label for a group of advanced options in the
# Advanced settings panel
label = _("Debug logging")
debugLogGroup = guiHelper.BoxSizerHelper(
self,
sizer=wx.StaticBoxSizer(parent=self, label=label, orient=wx.VERTICAL)
)
sHelper.addItem(debugLogGroup)
self.logCategories=[
"hwIo",
"MSAA",
"UIA",
"audioDucking",
"gui",
"louis",
"timeSinceInput",
"vision",
"speech",
"speechManager",
"nvwave",
]
# Translators: This is the label for a list in the
# Advanced settings panel
logCategoriesLabel=_("Enabled logging categories")
self.logCategoriesList=debugLogGroup.addLabeledControl(
logCategoriesLabel,
nvdaControls.CustomCheckListBox,
choices=self.logCategories
)
self.logCategoriesList.CheckedItems = [
index for index, x in enumerate(self.logCategories) if config.conf['debugLog'][x]
]
self.logCategoriesList.Select(0)
self.logCategoriesList.defaultCheckedItems = [
index for index, x in enumerate(self.logCategories) if bool(
self._getDefaultValue(['debugLog', x])
)
]
self.Layout()
def onOpenScratchpadDir(self,evt):
path=config.getScratchpadDir(ensureExists=True)
os.startfile(path)
def _getDefaultValue(self, configPath):
return config.conf.getConfigValidation(configPath).default
def haveConfigDefaultsBeenRestored(self):
return (
self._defaultsRestored
and self.scratchpadCheckBox.IsChecked() == self.scratchpadCheckBox.defaultValue
and (
self.selectiveUIAEventRegistrationCheckBox.IsChecked()
== self.selectiveUIAEventRegistrationCheckBox.defaultValue
)
and self.UIAInMSWordCheckBox.IsChecked() == self.UIAInMSWordCheckBox.defaultValue
and self.ConsoleUIACheckBox.IsChecked() == (self.ConsoleUIACheckBox.defaultValue == 'UIA')
and self.winConsoleSpeakPasswordsCheckBox.IsChecked() == self.winConsoleSpeakPasswordsCheckBox.defaultValue
and self.cancelExpiredFocusSpeechCombo.GetSelection() == self.cancelExpiredFocusSpeechCombo.defaultValue
and self.keyboardSupportInLegacyCheckBox.IsChecked() == self.keyboardSupportInLegacyCheckBox.defaultValue
and self.caretMoveTimeoutSpinControl.GetValue() == self.caretMoveTimeoutSpinControl.defaultValue
and set(self.logCategoriesList.CheckedItems) == set(self.logCategoriesList.defaultCheckedItems)
and True # reduce noise in diff when the list is extended.
)
def restoreToDefaults(self):
self.scratchpadCheckBox.SetValue(self.scratchpadCheckBox.defaultValue)
self.selectiveUIAEventRegistrationCheckBox.SetValue(self.selectiveUIAEventRegistrationCheckBox.defaultValue)
self.UIAInMSWordCheckBox.SetValue(self.UIAInMSWordCheckBox.defaultValue)
self.ConsoleUIACheckBox.SetValue(self.ConsoleUIACheckBox.defaultValue == 'UIA')
self.winConsoleSpeakPasswordsCheckBox.SetValue(self.winConsoleSpeakPasswordsCheckBox.defaultValue)
self.cancelExpiredFocusSpeechCombo.SetSelection(self.cancelExpiredFocusSpeechCombo.defaultValue)
self.keyboardSupportInLegacyCheckBox.SetValue(self.keyboardSupportInLegacyCheckBox.defaultValue)
self.caretMoveTimeoutSpinControl.SetValue(self.caretMoveTimeoutSpinControl.defaultValue)
self.logCategoriesList.CheckedItems = self.logCategoriesList.defaultCheckedItems
self._defaultsRestored = True
def onSave(self):
log.debug("Saving advanced config")
config.conf["development"]["enableScratchpadDir"]=self.scratchpadCheckBox.IsChecked()
config.conf["UIA"]["selectiveEventRegistration"] = self.selectiveUIAEventRegistrationCheckBox.IsChecked()
config.conf["UIA"]["useInMSWordWhenAvailable"]=self.UIAInMSWordCheckBox.IsChecked()
if self.ConsoleUIACheckBox.IsChecked():
config.conf['UIA']['winConsoleImplementation'] = "UIA"
else:
config.conf['UIA']['winConsoleImplementation'] = "auto"
config.conf["terminals"]["speakPasswords"] = self.winConsoleSpeakPasswordsCheckBox.IsChecked()
config.conf["featureFlag"]["cancelExpiredFocusSpeech"] = self.cancelExpiredFocusSpeechCombo.GetSelection()
config.conf["terminals"]["keyboardSupportInLegacy"]=self.keyboardSupportInLegacyCheckBox.IsChecked()
config.conf["editableText"]["caretMoveTimeoutMs"]=self.caretMoveTimeoutSpinControl.GetValue()
for index,key in enumerate(self.logCategories):
config.conf['debugLog'][key]=self.logCategoriesList.IsChecked(index)
class AdvancedPanel(SettingsPanel):
enableControlsCheckBox = None # type: wx.CheckBox
# Translators: This is the label for the Advanced settings panel.
title = _("Advanced")
# Translators: This is the label to warn users about the Advanced options in the
# Advanced settings panel
warningHeader = _("Warning!")
warningExplanation = _(
# Translators: This is a label appearing on the Advanced settings panel.
"The following settings are for advanced users. "
"Changing them may cause NVDA to function incorrectly. "
"Please only change these if you know what you are doing or "
"have been specifically instructed by NVDA developers."
)
panelDescription = u"{}\n{}".format(warningHeader, warningExplanation)
def makeSettings(self, settingsSizer):
"""
:type settingsSizer: wx.BoxSizer
"""
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
warningGroup = guiHelper.BoxSizerHelper(
self,
sizer=wx.StaticBoxSizer(wx.StaticBox(self), wx.VERTICAL)
)
sHelper.addItem(warningGroup)
warningBox = warningGroup.sizer.GetStaticBox() # type: wx.StaticBox
warningText = wx.StaticText(warningBox, label=self.warningHeader)
warningText.SetFont(wx.Font(18, wx.FONTFAMILY_DEFAULT, wx.NORMAL, wx.BOLD))
warningGroup.addItem(warningText)
self.windowText = warningGroup.addItem(wx.StaticText(warningBox, label=self.warningExplanation))
self.windowText.Wrap(self.scaleSize(544))
enableAdvancedControlslabel = _(
# Translators: This is the label for a checkbox in the Advanced settings panel.
"I understand that changing these settings may cause NVDA to function incorrectly."
)
self.enableControlsCheckBox = warningGroup.addItem(
wx.CheckBox(parent=warningBox, label=enableAdvancedControlslabel, id=wx.NewIdRef())
)
boldedFont = self.enableControlsCheckBox.GetFont().Bold()
self.enableControlsCheckBox.SetFont(boldedFont)
restoreDefaultsButton = warningGroup.addItem(
# Translators: This is the label for a button in the Advanced settings panel
wx.Button(self, label=_("Restore defaults"))
)
restoreDefaultsButton.Bind(wx.EVT_BUTTON, lambda evt: self.advancedControls.restoreToDefaults())
self.advancedControls = AdvancedPanelControls(self)
sHelper.sizer.Add(self.advancedControls, flag=wx.EXPAND)
self.enableControlsCheckBox.Bind(
wx.EVT_CHECKBOX,
self.onEnableControlsCheckBox
)
self.advancedControls.Enable(self.enableControlsCheckBox.IsChecked())
def onSave(self):
if (
self.enableControlsCheckBox.IsChecked() or
self.advancedControls.haveConfigDefaultsBeenRestored()
):
self.advancedControls.onSave()
def onEnableControlsCheckBox(self, evt):
# due to some not very well understood mis ordering of event processing, we force NVDA to
# process pending events. This fixes an issue where the checkbox state was being reported
# incorrectly. This checkbox is slightly different from most, in that its behaviour is to
# enable more controls than is typical. This might be causing enough of a delay, that there
# is a mismatch in the state of the checkbox and when the events are processed by NVDA.
from api import processPendingEvents
processPendingEvents()
self.advancedControls.Enable(evt.IsChecked())
class DictionaryEntryDialog(wx.Dialog):
TYPE_LABELS = {
# Translators: This is a label for an Entry Type radio button in add dictionary entry dialog.
speechDictHandler.ENTRY_TYPE_ANYWHERE: _("&Anywhere"),
# Translators: This is a label for an Entry Type radio button in add dictionary entry dialog.
speechDictHandler.ENTRY_TYPE_WORD: _("Whole &word"),
# Translators: This is a label for an Entry Type radio button in add dictionary entry dialog.
speechDictHandler.ENTRY_TYPE_REGEXP: _("Regular &expression")
}
TYPE_LABELS_ORDERING = (speechDictHandler.ENTRY_TYPE_ANYWHERE, speechDictHandler.ENTRY_TYPE_WORD, speechDictHandler.ENTRY_TYPE_REGEXP)
# Translators: This is the label for the edit dictionary entry dialog.
def __init__(self, parent, title=_("Edit Dictionary Entry")):
super(DictionaryEntryDialog,self).__init__(parent,title=title)
mainSizer=wx.BoxSizer(wx.VERTICAL)
sHelper = guiHelper.BoxSizerHelper(self, orientation=wx.VERTICAL)
# Translators: This is a label for an edit field in add dictionary entry dialog.
patternLabelText = _("&Pattern")
self.patternTextCtrl=sHelper.addLabeledControl(patternLabelText, wx.TextCtrl)
# Translators: This is a label for an edit field in add dictionary entry dialog and in punctuation/symbol pronunciation dialog.
replacementLabelText = _("&Replacement")
self.replacementTextCtrl=sHelper.addLabeledControl(replacementLabelText, wx.TextCtrl)
# Translators: This is a label for an edit field in add dictionary entry dialog.
commentLabelText = _("&Comment")
self.commentTextCtrl=sHelper.addLabeledControl(commentLabelText, wx.TextCtrl)
# Translators: This is a label for a checkbox in add dictionary entry dialog.
caseSensitiveText = _("Case &sensitive")
self.caseSensitiveCheckBox=sHelper.addItem(wx.CheckBox(self,label=caseSensitiveText))
# Translators: This is a label for a set of radio buttons in add dictionary entry dialog.
typeText = _("&Type")
typeChoices = [DictionaryEntryDialog.TYPE_LABELS[i] for i in DictionaryEntryDialog.TYPE_LABELS_ORDERING]
self.typeRadioBox=sHelper.addItem(wx.RadioBox(self,label=typeText, choices=typeChoices))
sHelper.addDialogDismissButtons(wx.OK | wx.CANCEL, separated=True)
mainSizer.Add(sHelper.sizer, border=guiHelper.BORDER_FOR_DIALOGS, flag=wx.ALL)
mainSizer.Fit(self)
self.SetSizer(mainSizer)
self.setType(speechDictHandler.ENTRY_TYPE_ANYWHERE)
self.patternTextCtrl.SetFocus()
self.Bind(wx.EVT_BUTTON,self.onOk,id=wx.ID_OK)
def getType(self):
typeRadioValue = self.typeRadioBox.GetSelection()
if typeRadioValue == wx.NOT_FOUND:
return speechDictHandler.ENTRY_TYPE_ANYWHERE
return DictionaryEntryDialog.TYPE_LABELS_ORDERING[typeRadioValue]
def onOk(self,evt):
if not self.patternTextCtrl.GetValue():
# Translators: This is an error message to let the user know that the pattern field in the dictionary entry is not valid.
gui.messageBox(_("A pattern is required."), _("Dictionary Entry Error"), wx.OK|wx.ICON_WARNING, self)
self.patternTextCtrl.SetFocus()
return
try:
dictEntry = self.dictEntry = speechDictHandler.SpeechDictEntry(
self.patternTextCtrl.GetValue(),
self.replacementTextCtrl.GetValue(),
self.commentTextCtrl.GetValue(),
bool(self.caseSensitiveCheckBox.GetValue()),
self.getType()
)
dictEntry.sub("test") # Ensure there are no grouping error (#11407)
except Exception as e:
log.debugWarning("Could not add dictionary entry due to (regex error) : %s" % e)
# Translators: This is an error message to let the user know that the dictionary entry is not valid.
gui.messageBox(_("Regular Expression error: \"%s\".")%e, _("Dictionary Entry Error"), wx.OK|wx.ICON_WARNING, self)
return
evt.Skip()
def setType(self, type):
self.typeRadioBox.SetSelection(DictionaryEntryDialog.TYPE_LABELS_ORDERING.index(type))
class DictionaryDialog(SettingsDialog):
TYPE_LABELS = {t: l.replace("&", "") for t, l in DictionaryEntryDialog.TYPE_LABELS.items()}
helpId = "SpeechDictionaries"
def __init__(self,parent,title,speechDict):
self.title = title
self.speechDict = speechDict
self.tempSpeechDict=speechDictHandler.SpeechDict()
self.tempSpeechDict.extend(self.speechDict)
globalVars.speechDictionaryProcessing=False
super().__init__(parent, resizeable=True)
# Historical initial size, result of L{self.dictList} being (550,350) as of #6287.
# Setting an initial size on L{self.dictList} by passing a L{size} argument when
# creating the control would also set its minimum size and thus block the dialog from being shrunk.
self.SetSize(576, 502)
self.CentreOnScreen()
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: The label for the list box of dictionary entries in speech dictionary dialog.
entriesLabelText=_("&Dictionary entries")
self.dictList = sHelper.addLabeledControl(
entriesLabelText,
wx.ListCtrl, style=wx.LC_REPORT | wx.LC_SINGLE_SEL
)
# Translators: The label for a column in dictionary entries list used to identify comments for the entry.
self.dictList.InsertColumn(0,_("Comment"),width=150)
# Translators: The label for a column in dictionary entries list used to identify pattern (original word or a pattern).
self.dictList.InsertColumn(1,_("Pattern"),width=150)
# Translators: The label for a column in dictionary entries list and in a list of symbols from symbol pronunciation dialog used to identify replacement for a pattern or a symbol
self.dictList.InsertColumn(2,_("Replacement"),width=150)
# Translators: The label for a column in dictionary entries list used to identify whether the entry is case sensitive or not.
self.dictList.InsertColumn(3,_("case"),width=50)
# Translators: The label for a column in dictionary entries list used to identify whether the entry is a regular expression, matches whole words, or matches anywhere.
self.dictList.InsertColumn(4,_("Type"),width=50)
self.offOn = (_("off"),_("on"))
for entry in self.tempSpeechDict:
self.dictList.Append((entry.comment,entry.pattern,entry.replacement,self.offOn[int(entry.caseSensitive)],DictionaryDialog.TYPE_LABELS[entry.type]))
self.editingIndex=-1
bHelper = guiHelper.ButtonHelper(orientation=wx.HORIZONTAL)
bHelper.addButton(
parent=self,
# Translators: The label for a button in speech dictionaries dialog to add new entries.
label=_("&Add")
).Bind(wx.EVT_BUTTON, self.OnAddClick)
bHelper.addButton(
parent=self,
# Translators: The label for a button in speech dictionaries dialog to edit existing entries.
label=_("&Edit")
).Bind(wx.EVT_BUTTON, self.OnEditClick)
bHelper.addButton(
parent=self,
# Translators: The label for a button in speech dictionaries dialog to remove existing entries.
label=_("&Remove")
).Bind(wx.EVT_BUTTON, self.OnRemoveClick)
sHelper.addItem(bHelper)
def postInit(self):
self.dictList.SetFocus()
def onCancel(self,evt):
globalVars.speechDictionaryProcessing=True
super(DictionaryDialog, self).onCancel(evt)
def onOk(self,evt):
globalVars.speechDictionaryProcessing=True
if self.tempSpeechDict!=self.speechDict:
del self.speechDict[:]
self.speechDict.extend(self.tempSpeechDict)
self.speechDict.save()
super(DictionaryDialog, self).onOk(evt)
def OnAddClick(self,evt):
# Translators: This is the label for the add dictionary entry dialog.
entryDialog=DictionaryEntryDialog(self,title=_("Add Dictionary Entry"))
if entryDialog.ShowModal()==wx.ID_OK:
self.tempSpeechDict.append(entryDialog.dictEntry)
self.dictList.Append((entryDialog.commentTextCtrl.GetValue(),entryDialog.patternTextCtrl.GetValue(),entryDialog.replacementTextCtrl.GetValue(),self.offOn[int(entryDialog.caseSensitiveCheckBox.GetValue())],DictionaryDialog.TYPE_LABELS[entryDialog.getType()]))
index=self.dictList.GetFirstSelected()
while index>=0:
self.dictList.Select(index,on=0)
index=self.dictList.GetNextSelected(index)
addedIndex=self.dictList.GetItemCount()-1
self.dictList.Select(addedIndex)
self.dictList.Focus(addedIndex)
self.dictList.SetFocus()
entryDialog.Destroy()
def OnEditClick(self,evt):
if self.dictList.GetSelectedItemCount()!=1:
return
editIndex=self.dictList.GetFirstSelected()
if editIndex<0:
return
entryDialog=DictionaryEntryDialog(self)
entryDialog.patternTextCtrl.SetValue(self.tempSpeechDict[editIndex].pattern)
entryDialog.replacementTextCtrl.SetValue(self.tempSpeechDict[editIndex].replacement)
entryDialog.commentTextCtrl.SetValue(self.tempSpeechDict[editIndex].comment)
entryDialog.caseSensitiveCheckBox.SetValue(self.tempSpeechDict[editIndex].caseSensitive)
entryDialog.setType(self.tempSpeechDict[editIndex].type)
if entryDialog.ShowModal()==wx.ID_OK:
self.tempSpeechDict[editIndex]=entryDialog.dictEntry
self.dictList.SetItem(editIndex,0,entryDialog.commentTextCtrl.GetValue())
self.dictList.SetItem(editIndex,1,entryDialog.patternTextCtrl.GetValue())
self.dictList.SetItem(editIndex,2,entryDialog.replacementTextCtrl.GetValue())
self.dictList.SetItem(editIndex,3,self.offOn[int(entryDialog.caseSensitiveCheckBox.GetValue())])
self.dictList.SetItem(editIndex,4,DictionaryDialog.TYPE_LABELS[entryDialog.getType()])
self.dictList.SetFocus()
entryDialog.Destroy()
def OnRemoveClick(self,evt):
index=self.dictList.GetFirstSelected()
while index>=0:
self.dictList.DeleteItem(index)
del self.tempSpeechDict[index]
index=self.dictList.GetNextSelected(index)
self.dictList.SetFocus()
class BrailleSettingsPanel(SettingsPanel):
# Translators: This is the label for the braille panel
title = _("Braille")
helpId = "BrailleSettings"
def makeSettings(self, settingsSizer):
settingsSizerHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: A label for the braille display on the braille panel.
displayLabel = _("Braille &display")
displayBox = wx.StaticBox(self, label=displayLabel)
displayGroup = guiHelper.BoxSizerHelper(self, sizer=wx.StaticBoxSizer(displayBox, wx.HORIZONTAL))
settingsSizerHelper.addItem(displayGroup)
self.displayNameCtrl = ExpandoTextCtrl(self, size=(self.scaleSize(250), -1), style=wx.TE_READONLY)
self.updateCurrentDisplay()
# Translators: This is the label for the button used to change braille display,
# it appears in the context of a braille display group on the braille settings panel.
changeDisplayBtn = wx.Button(self, label=_("C&hange..."))
displayGroup.addItem(
guiHelper.associateElements(
self.displayNameCtrl,
changeDisplayBtn
)
)
self.displayNameCtrl.Bind(wx.EVT_CHAR_HOOK, self._enterTriggersOnChangeDisplay)
changeDisplayBtn.Bind(wx.EVT_BUTTON,self.onChangeDisplay)
self.brailleSubPanel = BrailleSettingsSubPanel(self)
settingsSizerHelper.addItem(self.brailleSubPanel)
def _enterTriggersOnChangeDisplay(self, evt):
if evt.KeyCode == wx.WXK_RETURN:
self.onChangeDisplay(evt)
else:
evt.Skip()
def onChangeDisplay(self, evt):
changeDisplay = BrailleDisplaySelectionDialog(self, multiInstanceAllowed=True)
ret = changeDisplay.ShowModal()
if ret == wx.ID_OK:
self.Freeze()
# trigger a refresh of the settings
self.onPanelActivated()
self._sendLayoutUpdatedEvent()
self.Thaw()
def updateCurrentDisplay(self):
if config.conf["braille"]["display"] == braille.AUTO_DISPLAY_NAME:
displayDesc = BrailleDisplaySelectionDialog.getCurrentAutoDisplayDescription()
else:
displayDesc = braille.handler.display.description
self.displayNameCtrl.SetValue(displayDesc)
def onPanelActivated(self):
self.brailleSubPanel.onPanelActivated()
super(BrailleSettingsPanel,self).onPanelActivated()
def onPanelDeactivated(self):
self.brailleSubPanel.onPanelDeactivated()
super(BrailleSettingsPanel,self).onPanelDeactivated()
def onDiscard(self):
self.brailleSubPanel.onDiscard()
def onSave(self):
self.brailleSubPanel.onSave()
class BrailleDisplaySelectionDialog(SettingsDialog):
# Translators: This is the label for the braille display selection dialog.
title = _("Select Braille Display")
helpId = "BrailleSettings"
displayNames = []
possiblePorts = []
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: The label for a setting in braille settings to choose a braille display.
displayLabelText = _("Braille &display:")
self.displayList = sHelper.addLabeledControl(displayLabelText, wx.Choice, choices=[])
self.Bind(wx.EVT_CHOICE, self.onDisplayNameChanged, self.displayList)
# Translators: The label for a setting in braille settings to choose the connection port (if the selected braille display supports port selection).
portsLabelText = _("&Port:")
self.portsList = sHelper.addLabeledControl(portsLabelText, wx.Choice, choices=[])
self.bindHelpEvent("BrailleSettingsPort", self.portsList)
self.updateBrailleDisplayLists()
def postInit(self):
# Finally, ensure that focus is on the list of displays.
self.displayList.SetFocus()
@staticmethod
def getCurrentAutoDisplayDescription():
description = braille.AUTOMATIC_PORT[1]
if (
config.conf["braille"]["display"] == braille.AUTO_DISPLAY_NAME
and braille.handler.display.name != "noBraille"
):
description = "%s (%s)" % (description, braille.handler.display.description)
return description
def updateBrailleDisplayLists(self):
driverList = [(braille.AUTO_DISPLAY_NAME, self.getCurrentAutoDisplayDescription())]
driverList.extend(braille.getDisplayList())
self.displayNames = [driver[0] for driver in driverList]
displayChoices = [driver[1] for driver in driverList]
self.displayList.Clear()
self.displayList.AppendItems(displayChoices)
self.bindHelpEvent("BrailleSettingsDisplay", self.displayList)
try:
if config.conf["braille"]["display"] == braille.AUTO_DISPLAY_NAME:
selection = 0
else:
selection = self.displayNames.index(braille.handler.display.name)
self.displayList.SetSelection(selection)
except:
pass
self.updatePossiblePorts()
def updatePossiblePorts(self):
displayName = self.displayNames[self.displayList.GetSelection()]
self.possiblePorts = []
if displayName != "auto":
displayCls = braille._getDisplayDriver(displayName)
try:
self.possiblePorts.extend(displayCls.getPossiblePorts().items())
except NotImplementedError:
pass
if self.possiblePorts:
self.portsList.SetItems([p[1] for p in self.possiblePorts])
try:
selectedPort = config.conf["braille"][displayName].get("port")
portNames = [p[0] for p in self.possiblePorts]
selection = portNames.index(selectedPort)
except (KeyError, ValueError):
# Display name not in config or port not valid
selection = 0
self.portsList.SetSelection(selection)
# If no port selection is possible or only automatic selection is available, disable the port selection control
enable = len(self.possiblePorts) > 0 and not (len(self.possiblePorts) == 1 and self.possiblePorts[0][0] == "auto")
self.portsList.Enable(enable)
def onDisplayNameChanged(self, evt):
self.updatePossiblePorts()
def onOk(self, evt):
if not self.displayNames:
# The list of displays has not been populated yet, so we didn't change anything in this panel
return
display = self.displayNames[self.displayList.GetSelection()]
if display not in config.conf["braille"]:
config.conf["braille"][display] = {}
if self.possiblePorts:
port = self.possiblePorts[self.portsList.GetSelection()][0]
config.conf["braille"][display]["port"] = port
if not braille.handler.setDisplayByName(display):
gui.messageBox(
# Translators: The message in a dialog presented when NVDA is unable to load the selected
# braille display.
message=_("Could not load the {display} display.").format(display=display),
# Translators: The title in a dialog presented when NVDA is unable to load the selected
# braille display.
caption=_("Braille Display Error"),
style=wx.OK | wx.ICON_WARNING,
parent=self
)
return
if self.IsModal():
# Hack: we need to update the display in our parent window before closing.
# Otherwise, NVDA will report the old display even though the new display is reflected visually.
self.Parent.updateCurrentDisplay()
super(BrailleDisplaySelectionDialog, self).onOk(evt)
class BrailleSettingsSubPanel(AutoSettingsMixin, SettingsPanel):
@property
def driver(self):
return braille.handler.display
def getSettings(self) -> AutoSettings:
return self.driver
def makeSettings(self, settingsSizer):
shouldDebugGui = gui._isDebug()
startTime = 0 if not shouldDebugGui else time.time()
# Construct braille display specific settings
self.updateDriverSettings()
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
tables = brailleTables.listTables()
# Translators: The label for a setting in braille settings to select the output table (the braille table used to read braille text on the braille display).
outputsLabelText = _("&Output table:")
outTables = [table for table in tables if table.output]
self.outTableNames = [table.fileName for table in outTables]
outTableChoices = [table.displayName for table in outTables]
self.outTableList = sHelper.addLabeledControl(outputsLabelText, wx.Choice, choices=outTableChoices)
self.bindHelpEvent("BrailleSettingsOutputTable", self.outTableList)
try:
selection = self.outTableNames.index(config.conf["braille"]["translationTable"])
self.outTableList.SetSelection(selection)
except:
pass
if shouldDebugGui:
timePassed = time.time() - startTime
log.debug(
f"Loading output tables completed, now at {timePassed:.2f} seconds from start"
)
# Translators: The label for a setting in braille settings to select the input table (the braille table used to type braille characters on a braille keyboard).
inputLabelText = _("&Input table:")
self.inTables = [table for table in tables if table.input]
inTableChoices = [table.displayName for table in self.inTables]
self.inTableList = sHelper.addLabeledControl(inputLabelText, wx.Choice, choices=inTableChoices)
self.bindHelpEvent("BrailleSettingsInputTable", self.inTableList)
try:
selection = self.inTables.index(brailleInput.handler.table)
self.inTableList.SetSelection(selection)
except:
pass
if shouldDebugGui:
timePassed = time.time() - startTime
log.debug(
f"Loading input tables completed, now at {timePassed:.2f} seconds from start"
)
# Translators: The label for a setting in braille settings to expand the current word under cursor to computer braille.
expandAtCursorText = _("E&xpand to computer braille for the word at the cursor")
self.expandAtCursorCheckBox = sHelper.addItem(
wx.CheckBox(self, wx.ID_ANY, label=expandAtCursorText)
)
self.bindHelpEvent("BrailleSettingsExpandToComputerBraille", self.expandAtCursorCheckBox)
self.expandAtCursorCheckBox.SetValue(config.conf["braille"]["expandAtCursor"])
# Translators: The label for a setting in braille settings to show the cursor.
showCursorLabelText = _("&Show cursor")
self.showCursorCheckBox = sHelper.addItem(wx.CheckBox(self, label=showCursorLabelText))
self.bindHelpEvent("BrailleSettingsShowCursor", self.showCursorCheckBox)
self.showCursorCheckBox.Bind(wx.EVT_CHECKBOX, self.onShowCursorChange)
self.showCursorCheckBox.SetValue(config.conf["braille"]["showCursor"])
# Translators: The label for a setting in braille settings to enable cursor blinking.
cursorBlinkLabelText = _("Blink cursor")
self.cursorBlinkCheckBox = sHelper.addItem(
wx.CheckBox(self, label=cursorBlinkLabelText)
)
self.bindHelpEvent("BrailleSettingsBlinkCursor", self.cursorBlinkCheckBox)
self.cursorBlinkCheckBox.Bind(wx.EVT_CHECKBOX, self.onBlinkCursorChange)
self.cursorBlinkCheckBox.SetValue(config.conf["braille"]["cursorBlink"])
if not self.showCursorCheckBox.GetValue():
self.cursorBlinkCheckBox.Disable()
# Translators: The label for a setting in braille settings to change cursor blink rate in milliseconds (1 second is 1000 milliseconds).
cursorBlinkRateLabelText = _("Cursor blink rate (ms)")
minBlinkRate = int(config.conf.getConfigValidation(
("braille", "cursorBlinkRate")
).kwargs["min"])
maxBlinkRate = int(config.conf.getConfigValidation(("braille", "cursorBlinkRate")).kwargs["max"])
self.cursorBlinkRateEdit = sHelper.addLabeledControl(
cursorBlinkRateLabelText,
nvdaControls.SelectOnFocusSpinCtrl,
min=minBlinkRate,
max=maxBlinkRate,
initial=config.conf["braille"]["cursorBlinkRate"]
)
self.bindHelpEvent("BrailleSettingsBlinkRate", self.cursorBlinkRateEdit)
if not self.showCursorCheckBox.GetValue() or not self.cursorBlinkCheckBox.GetValue() :
self.cursorBlinkRateEdit.Disable()
self.cursorShapes = [s[0] for s in braille.CURSOR_SHAPES]
cursorShapeChoices = [s[1] for s in braille.CURSOR_SHAPES]
# Translators: The label for a setting in braille settings to select the cursor shape when tethered to focus.
cursorShapeFocusLabelText = _("Cursor shape for &focus:")
self.cursorShapeFocusList = sHelper.addLabeledControl(cursorShapeFocusLabelText, wx.Choice, choices=cursorShapeChoices)
self.bindHelpEvent("BrailleSettingsCursorShapeForFocus", self.cursorShapeFocusList)
try:
selection = self.cursorShapes.index(config.conf["braille"]["cursorShapeFocus"])
self.cursorShapeFocusList.SetSelection(selection)
except:
pass
if not self.showCursorCheckBox.GetValue():
self.cursorShapeFocusList.Disable()
# Translators: The label for a setting in braille settings to select the cursor shape when tethered to review.
cursorShapeReviewLabelText = _("Cursor shape for &review:")
self.cursorShapeReviewList = sHelper.addLabeledControl(cursorShapeReviewLabelText, wx.Choice, choices=cursorShapeChoices)
self.bindHelpEvent("BrailleSettingsCursorShapeForReview", self.cursorShapeReviewList)
try:
selection = self.cursorShapes.index(config.conf["braille"]["cursorShapeReview"])
self.cursorShapeReviewList.SetSelection(selection)
except:
pass
if not self.showCursorCheckBox.GetValue():
self.cursorShapeReviewList.Disable()
if gui._isDebug():
log.debug("Loading cursor settings completed, now at %.2f seconds from start"%(time.time() - startTime))
minTimeout = int(config.conf.getConfigValidation(
("braille", "messageTimeout")
).kwargs["min"])
maxTimeOut = int(config.conf.getConfigValidation(
("braille", "messageTimeout")
).kwargs["max"])
# Translators: The label for a setting in braille settings to change how long a message stays on the braille display (in seconds).
messageTimeoutText = _("Message &timeout (sec)")
self.messageTimeoutEdit = sHelper.addLabeledControl(
messageTimeoutText,
nvdaControls.SelectOnFocusSpinCtrl,
min=minTimeout,
max=maxTimeOut,
initial=config.conf["braille"]["messageTimeout"]
)
self.bindHelpEvent("BrailleSettingsMessageTimeout", self.messageTimeoutEdit)
# Translators: The label for a setting in braille settings to display a message on the braille display indefinitely.
noMessageTimeoutLabelText = _("Show &messages indefinitely")
self.noMessageTimeoutCheckBox = sHelper.addItem(wx.CheckBox(self, label=noMessageTimeoutLabelText))
self.bindHelpEvent("BrailleSettingsNoMessageTimeout", self.noMessageTimeoutCheckBox)
self.noMessageTimeoutCheckBox.Bind(wx.EVT_CHECKBOX, self.onNoMessageTimeoutChange)
self.noMessageTimeoutCheckBox.SetValue(config.conf["braille"]["noMessageTimeout"])
if self.noMessageTimeoutCheckBox.GetValue():
self.messageTimeoutEdit.Disable()
if gui._isDebug():
log.debug("Loading timeout settings completed, now at %.2f seconds from start"%(time.time() - startTime))
# Translators: The label for a setting in braille settings to set whether braille should be tethered to focus or review cursor.
tetherListText = _("Tether B&raille:")
# Translators: The value for a setting in the braille settings, to set whether braille should be tethered to focus or review cursor.
tetherChoices = [x[1] for x in braille.handler.tetherValues]
self.tetherList = sHelper.addLabeledControl(tetherListText, wx.Choice, choices=tetherChoices)
self.bindHelpEvent("BrailleTether", self.tetherList)
tetherChoice=braille.handler.TETHER_AUTO if config.conf["braille"]["autoTether"] else config.conf["braille"]["tetherTo"]
selection = next((x for x,y in enumerate(braille.handler.tetherValues) if y[0]==tetherChoice))
try:
self.tetherList.SetSelection(selection)
except:
pass
if gui._isDebug():
log.debug("Loading tether settings completed, now at %.2f seconds from start"%(time.time() - startTime))
# Translators: The label for a setting in braille settings to read by paragraph (if it is checked, the commands to move the display by lines moves the display by paragraphs instead).
readByParagraphText = _("Read by ¶graph")
self.readByParagraphCheckBox = sHelper.addItem(wx.CheckBox(self, label=readByParagraphText))
self.bindHelpEvent("BrailleSettingsReadByParagraph", self.readByParagraphCheckBox)
self.readByParagraphCheckBox.Value = config.conf["braille"]["readByParagraph"]
# Translators: The label for a setting in braille settings to enable word wrap (try to avoid spliting words at the end of the braille display).
wordWrapText = _("Avoid splitting &words when possible")
self.wordWrapCheckBox = sHelper.addItem(wx.CheckBox(self, label=wordWrapText))
self.bindHelpEvent("BrailleSettingsWordWrap", self.wordWrapCheckBox)
self.wordWrapCheckBox.Value = config.conf["braille"]["wordWrap"]
# Translators: The label for a setting in braille settings to select how the context for the focus object should be presented on a braille display.
focusContextPresentationLabelText = _("Focus context presentation:")
self.focusContextPresentationValues = [x[0] for x in braille.focusContextPresentations]
focusContextPresentationChoices = [x[1] for x in braille.focusContextPresentations]
self.focusContextPresentationList = sHelper.addLabeledControl(focusContextPresentationLabelText, wx.Choice, choices=focusContextPresentationChoices)
self.bindHelpEvent("BrailleSettingsFocusContextPresentation", self.focusContextPresentationList)
try:
index=self.focusContextPresentationValues.index(config.conf["braille"]["focusContextPresentation"])
except:
index=0
self.focusContextPresentationList.SetSelection(index)
if gui._isDebug():
log.debug("Finished making settings, now at %.2f seconds from start"%(time.time() - startTime))
def onSave(self):
AutoSettingsMixin.onSave(self)
config.conf["braille"]["translationTable"] = self.outTableNames[self.outTableList.GetSelection()]
brailleInput.handler.table = self.inTables[self.inTableList.GetSelection()]
config.conf["braille"]["expandAtCursor"] = self.expandAtCursorCheckBox.GetValue()
config.conf["braille"]["showCursor"] = self.showCursorCheckBox.GetValue()
config.conf["braille"]["cursorBlink"] = self.cursorBlinkCheckBox.GetValue()
config.conf["braille"]["cursorBlinkRate"] = self.cursorBlinkRateEdit.GetValue()
config.conf["braille"]["cursorShapeFocus"] = self.cursorShapes[self.cursorShapeFocusList.GetSelection()]
config.conf["braille"]["cursorShapeReview"] = self.cursorShapes[self.cursorShapeReviewList.GetSelection()]
config.conf["braille"]["noMessageTimeout"] = self.noMessageTimeoutCheckBox.GetValue()
config.conf["braille"]["messageTimeout"] = self.messageTimeoutEdit.GetValue()
tetherChoice = braille.handler.tetherValues[self.tetherList.GetSelection()][0]
if tetherChoice==braille.handler.TETHER_AUTO:
config.conf["braille"]["autoTether"] = True
config.conf["braille"]["tetherTo"] = braille.handler.TETHER_FOCUS
else:
config.conf["braille"]["autoTether"] = False
braille.handler.setTether(tetherChoice, auto=False)
config.conf["braille"]["readByParagraph"] = self.readByParagraphCheckBox.Value
config.conf["braille"]["wordWrap"] = self.wordWrapCheckBox.Value
config.conf["braille"]["focusContextPresentation"] = self.focusContextPresentationValues[self.focusContextPresentationList.GetSelection()]
def onShowCursorChange(self, evt):
self.cursorBlinkCheckBox.Enable(evt.IsChecked())
self.cursorBlinkRateEdit.Enable(evt.IsChecked() and self.cursorBlinkCheckBox.GetValue())
self.cursorShapeFocusList.Enable(evt.IsChecked())
self.cursorShapeReviewList.Enable(evt.IsChecked())
def onBlinkCursorChange(self, evt):
self.cursorBlinkRateEdit.Enable(evt.IsChecked())
def onNoMessageTimeoutChange(self, evt):
self.messageTimeoutEdit.Enable(not evt.IsChecked())
def showStartErrorForProviders(
parent: wx.Window,
providers: List[vision.providerInfo.ProviderInfo],
) -> None:
if not providers:
return
if len(providers) == 1:
providerName = providers[0].displayName
# Translators: This message is presented when
# NVDA is unable to load a single vision enhancement provider.
message = _("Could not load the {providerName} vision enhancement provider").format(
providerName=providerName
)
else:
providerNames = ", ".join(provider.displayName for provider in providers)
# Translators: This message is presented when NVDA is unable to
# load multiple vision enhancement providers.
message = _("Could not load the following vision enhancement providers:\n{providerNames}").format(
providerNames=providerNames
)
gui.messageBox(
message,
# Translators: The title of the vision enhancement provider error message box.
_("Vision Enhancement Provider Error"),
wx.OK | wx.ICON_WARNING,
parent,
)
def showTerminationErrorForProviders(
parent: wx.Window,
providers: List[vision.providerInfo.ProviderInfo],
) -> None:
if not providers:
return
if len(providers) == 1:
providerName = providers[0].displayName
# Translators: This message is presented when
# NVDA is unable to gracefully terminate a single vision enhancement provider.
message = _("Could not gracefully terminate the {providerName} vision enhancement provider").format(
providerName=providerName
)
else:
providerNames = ", ".join(provider.displayName for provider in providers)
message = _(
# Translators: This message is presented when
# NVDA is unable to terminate multiple vision enhancement providers.
"Could not gracefully terminate the following vision enhancement providers:\n"
"{providerNames}"
).format(providerNames=providerNames)
gui.messageBox(
message,
# Translators: The title of the vision enhancement provider error message box.
_("Vision Enhancement Provider Error"),
wx.OK | wx.ICON_WARNING,
parent,
)
class VisionProviderStateControl(vision.providerBase.VisionProviderStateControl):
"""
Gives settings panels for vision enhancement providers a way to control a
single vision enhancement provider, handling any error conditions in
a UX friendly way.
"""
def __init__(
self,
parent: wx.Window,
providerInfo: vision.providerInfo.ProviderInfo
):
self._providerInfo = providerInfo
self._parent = weakref.ref(parent) # don't keep parent dialog alive with a circular reference.
def getProviderInfo(self) -> vision.providerInfo.ProviderInfo:
return self._providerInfo
def getProviderInstance(self) -> Optional[vision.providerBase.VisionEnhancementProvider]:
return vision.handler.getProviderInstance(self._providerInfo)
def startProvider(
self,
shouldPromptOnError: bool = True
) -> bool:
"""Initializes the provider, prompting user with the error if necessary.
@param shouldPromptOnError: True if the user should be presented with any errors that may occur.
@return: True on success
"""
success = self._doStartProvider()
if not success and shouldPromptOnError:
showStartErrorForProviders(self._parent(), [self._providerInfo, ])
return success
def terminateProvider(
self,
shouldPromptOnError: bool = True
) -> bool:
"""Terminate the provider, prompting user with the error if necessary.
@param shouldPromptOnError: True if the user should be presented with any errors that may occur.
@return: True on success
"""
success = self._doTerminate()
if not success and shouldPromptOnError:
showTerminationErrorForProviders(self._parent(), [self._providerInfo, ])
return success
def _doStartProvider(self) -> bool:
"""Attempt to start the provider, catching any errors.
@return True on successful termination.
"""
try:
vision.handler.initializeProvider(self._providerInfo)
return True
except Exception:
log.error(
f"Could not initialize the {self._providerInfo.providerId} vision enhancement provider",
exc_info=True
)
return False
def _doTerminate(self) -> bool:
"""Attempt to terminate the provider, catching any errors.
@return True on successful termination.
"""
try:
# Terminating a provider from the gui should never save the settings.
# This is because termination happens on the fly when unchecking check boxes.
# Saving settings would be harmful if a user opens the vision panel,
# then changes some settings and disables the provider.
vision.handler.terminateProvider(self._providerInfo, saveSettings=False)
return True
except Exception:
log.error(
f"Could not terminate the {self._providerInfo.providerId} vision enhancement provider",
exc_info=True
)
return False
class VisionSettingsPanel(SettingsPanel):
settingsSizerHelper: guiHelper.BoxSizerHelper
providerPanelInstances: List[SettingsPanel]
initialProviders: List[vision.providerInfo.ProviderInfo]
# Translators: This is the label for the vision panel
title = _("Vision")
# Translators: This is a label appearing on the vision settings panel.
panelDescription = _("Configure visual aids.")
def _createProviderSettingsPanel(
self,
providerInfo: vision.providerInfo.ProviderInfo
) -> Optional[SettingsPanel]:
settingsPanelCls = providerInfo.providerClass.getSettingsPanelClass()
if not settingsPanelCls:
if gui._isDebug():
log.debug(f"Using default panel for providerId: {providerInfo.providerId}")
settingsPanelCls = VisionProviderSubPanel_Wrapper
else:
if gui._isDebug():
log.debug(f"Using custom panel for providerId: {providerInfo.providerId}")
providerControl = VisionProviderStateControl(parent=self, providerInfo=providerInfo)
try:
return settingsPanelCls(
parent=self,
providerControl=providerControl
)
# Broad except used since we can not know what exceptions a provider might throw.
# We should be able to continue despite a buggy provider.
except Exception:
log.debug(f"Error creating providerPanel: {settingsPanelCls!r}", exc_info=True)
return None
def makeSettings(self, settingsSizer: wx.BoxSizer):
self.initialProviders = vision.handler.getActiveProviderInfos()
self.providerPanelInstances = []
self.settingsSizerHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
self.settingsSizerHelper.addItem(wx.StaticText(self, label=self.panelDescription))
for providerInfo in vision.handler.getProviderList(reloadFromSystem=True):
providerSizer = self.settingsSizerHelper.addItem(
wx.StaticBoxSizer(wx.StaticBox(self, label=providerInfo.displayName), wx.VERTICAL),
flag=wx.EXPAND
)
if len(self.providerPanelInstances) > 0:
settingsSizer.AddSpacer(guiHelper.SPACE_BETWEEN_VERTICAL_DIALOG_ITEMS)
settingsPanel = self._createProviderSettingsPanel(providerInfo)
if not settingsPanel:
continue
providerSizer.Add(settingsPanel, flag=wx.EXPAND)
self.providerPanelInstances.append(settingsPanel)
def safeInitProviders(
self,
providers: List[vision.providerInfo.ProviderInfo]
) -> None:
"""Initializes one or more providers in a way that is gui friendly,
showing an error if appropriate.
"""
errorProviders: List[vision.providerInfo.ProviderInfo] = []
for provider in providers:
success = VisionProviderStateControl(self, provider).startProvider(shouldPromptOnError=False)
if not success:
errorProviders.append(provider)
showStartErrorForProviders(self, errorProviders)
def safeTerminateProviders(
self,
providers: List[vision.providerInfo.ProviderInfo],
verbose: bool = False
) -> None:
"""Terminates one or more providers in a way that is gui friendly,
@verbose: Whether to show a termination error.
@returns: Whether termination succeeded for all providers.
"""
errorProviders: List[vision.providerInfo.ProviderInfo] = []
for provider in providers:
success = VisionProviderStateControl(self, provider).terminateProvider(shouldPromptOnError=False)
if not success:
errorProviders.append(provider)
if verbose:
showTerminationErrorForProviders(self, errorProviders)
def refreshPanel(self):
self.Freeze()
# trigger a refresh of the settings
self.onPanelActivated()
self._sendLayoutUpdatedEvent()
self.Thaw()
def onPanelActivated(self):
super().onPanelActivated()
def onDiscard(self):
for panel in self.providerPanelInstances:
try:
panel.onDiscard()
# Broad except used since we can not know what exceptions a provider might throw.
# We should be able to continue despite a buggy provider.
except Exception:
log.debug(f"Error discarding providerPanel: {panel.__class__!r}", exc_info=True)
providersToInitialize = [
provider for provider in self.initialProviders
if not bool(vision.handler.getProviderInstance(provider))
]
self.safeInitProviders(providersToInitialize)
initialProviderIds = [
providerInfo.providerId for providerInfo in self.initialProviders
]
providersToTerminate = [
provider for provider in vision.handler.getActiveProviderInfos()
if provider.providerId not in initialProviderIds
]
self.safeTerminateProviders(providersToTerminate)
def onSave(self):
for panel in self.providerPanelInstances:
try:
panel.onSave()
# Broad except used since we can not know what exceptions a provider might throw.
# We should be able to continue despite a buggy provider.
except Exception:
log.debug(f"Error saving providerPanel: {panel.__class__!r}", exc_info=True)
self.initialProviders = vision.handler.getActiveProviderInfos()
class VisionProviderSubPanel_Settings(
AutoSettingsMixin,
SettingsPanel
):
_settingsCallable: Callable[[], VisionEnhancementProviderSettings]
def __init__(
self,
parent: wx.Window,
*, # Make next argument keyword only
settingsCallable: Callable[[], vision.providerBase.VisionEnhancementProviderSettings]
):
"""
@param settingsCallable: A callable that returns an instance to a VisionEnhancementProviderSettings.
This will usually be a weakref, but could be any callable taking no arguments.
"""
self._settingsCallable = settingsCallable
super().__init__(parent=parent)
def getSettings(self) -> AutoSettings:
settings = self._settingsCallable()
return settings
def makeSettings(self, settingsSizer):
# Construct vision enhancement provider settings
self.updateDriverSettings()
class VisionProviderSubPanel_Wrapper(
SettingsPanel
):
_checkBox: wx.CheckBox
def __init__(
self,
parent: wx.Window,
providerControl: VisionProviderStateControl
):
self._providerControl = providerControl
self._providerSettings: Optional[VisionProviderSubPanel_Settings] = None
self._providerSettingsSizer = wx.BoxSizer(orient=wx.VERTICAL)
super().__init__(parent=parent)
def makeSettings(self, settingsSizer):
self._checkBox = wx.CheckBox(
self,
# Translators: Enable checkbox on a vision enhancement provider on the vision settings category panel
label=_("Enable")
)
settingsSizer.Add(self._checkBox)
self._optionsSizer = wx.BoxSizer(orient=wx.VERTICAL)
self._optionsSizer.AddSpacer(size=self.scaleSize(10))
# Translators: Options label on a vision enhancement provider on the vision settings category panel
self._optionsText = wx.StaticText(self, label=_("Options:"))
self._optionsSizer.Add(self._optionsText)
self._optionsSizer.Add(
self._providerSettingsSizer,
border=self.scaleSize(15),
flag=wx.LEFT | wx.EXPAND,
proportion=1.0
)
settingsSizer.Add(
self._optionsSizer,
flag=wx.EXPAND,
proportion=1.0
)
self._checkBox.SetValue(bool(self._providerControl.getProviderInstance()))
if self._createProviderSettings():
self._checkBox.Bind(wx.EVT_CHECKBOX, self._enableToggle)
else:
self._checkBox.Bind(wx.EVT_CHECKBOX, self._nonEnableableGUI)
self._updateOptionsVisibility()
def _updateOptionsVisibility(self):
hasProviderOptions = bool(self._providerSettings) and self._providerSettings.hasOptions
if hasProviderOptions:
self.settingsSizer.Show(self._optionsSizer, recursive=True)
else:
self.settingsSizer.Hide(self._optionsSizer, recursive=True)
self._sendLayoutUpdatedEvent()
def _createProviderSettings(self):
try:
getSettingsCallable = self._providerControl.getProviderInfo().providerClass.getSettings
self._providerSettings = VisionProviderSubPanel_Settings(
self,
settingsCallable=getSettingsCallable
)
self._providerSettingsSizer.Add(self._providerSettings, flag=wx.EXPAND, proportion=1.0)
# Broad except used since we can not know what exceptions a provider might throw.
# We should be able to continue despite a buggy provider.
except Exception:
log.error("unable to create provider settings", exc_info=True)
return False
return True
def _nonEnableableGUI(self, evt):
gui.messageBox(
# Translators: Shown when there is an error showing the GUI for a vision enhancement provider
_("Unable to configure user interface for Vision Enhancement Provider, it can not be enabled."),
# Translators: The title of the error dialog displayed when there is an error showing the GUI
# for a vision enhancement provider
_("Error"),
parent=self,
)
self._checkBox.SetValue(False)
def _enableToggle(self, evt):
shouldBeRunning = evt.IsChecked()
if shouldBeRunning and not self._providerControl.startProvider():
self._checkBox.SetValue(False)
self._updateOptionsVisibility()
return
elif not shouldBeRunning and not self._providerControl.terminateProvider():
# When there is an error on termination, don't leave the checkbox checked.
# The provider should not be left configured to startup.
self._checkBox.SetValue(False)
self._updateOptionsVisibility()
return
# Able to successfully start / terminate:
self._providerSettings.updateDriverSettings()
self._providerSettings.refreshGui()
self._updateOptionsVisibility()
def onDiscard(self):
if self._providerSettings:
self._providerSettings.onDiscard()
def onSave(self):
log.debug(f"calling VisionProviderSubPanel_Wrapper")
if self._providerSettings:
self._providerSettings.onSave()
""" The name of the config profile currently being edited, if any.
This is set when the currently edited configuration profile is determined and returned to None when the dialog is destroyed.
This can be used by an AppModule for NVDA to identify and announce
changes in the name of the edited configuration profile when categories are changed"""
NvdaSettingsDialogActiveConfigProfile = None
NvdaSettingsDialogWindowHandle = None
class NVDASettingsDialog(MultiCategorySettingsDialog):
# Translators: This is the label for the NVDA settings dialog.
title = _("NVDA Settings")
categoryClasses=[
GeneralSettingsPanel,
SpeechSettingsPanel,
BrailleSettingsPanel,
VisionSettingsPanel,
KeyboardSettingsPanel,
MouseSettingsPanel,
ReviewCursorPanel,
InputCompositionPanel,
ObjectPresentationPanel,
BrowseModePanel,
DocumentFormattingPanel,
]
if touchHandler.touchSupported():
categoryClasses.append(TouchInteractionPanel)
if winVersion.isUwpOcrAvailable():
categoryClasses.append(UwpOcrPanel)
# And finally the Advanced panel which should always be last.
if not globalVars.appArgs.secure:
categoryClasses.append(AdvancedPanel)
def makeSettings(self, settingsSizer):
# Ensure that after the settings dialog is created the name is set correctly
super(NVDASettingsDialog, self).makeSettings(settingsSizer)
self._doOnCategoryChange()
global NvdaSettingsDialogWindowHandle
NvdaSettingsDialogWindowHandle = self.GetHandle()
def _doOnCategoryChange(self):
global NvdaSettingsDialogActiveConfigProfile
NvdaSettingsDialogActiveConfigProfile = config.conf.profiles[-1].name
if not NvdaSettingsDialogActiveConfigProfile or isinstance(self.currentCategory, GeneralSettingsPanel):
# Translators: The profile name for normal configuration
NvdaSettingsDialogActiveConfigProfile = _("normal configuration")
self.SetTitle(self._getDialogTitle())
self.bindHelpEvent(
self.currentCategory.helpId,
self.catListCtrl
)
def _getDialogTitle(self):
return u"{dialogTitle}: {panelTitle} ({configProfile})".format(
dialogTitle=self.title,
panelTitle=self.currentCategory.title,
configProfile=NvdaSettingsDialogActiveConfigProfile
)
def onCategoryChange(self,evt):
super(NVDASettingsDialog,self).onCategoryChange(evt)
if evt.Skipped:
return
self._doOnCategoryChange()
def Destroy(self):
global NvdaSettingsDialogActiveConfigProfile, NvdaSettingsDialogWindowHandle
NvdaSettingsDialogActiveConfigProfile = None
NvdaSettingsDialogWindowHandle = None
super(NVDASettingsDialog, self).Destroy()
class AddSymbolDialog(
gui.ContextHelpMixin,
wx.Dialog # wxPython does not seem to call base class initializer, put last in MRO
):
helpId = "SymbolPronunciation"
def __init__(self, parent):
# Translators: This is the label for the add symbol dialog.
super().__init__(parent, title=_("Add Symbol"))
mainSizer=wx.BoxSizer(wx.VERTICAL)
sHelper = guiHelper.BoxSizerHelper(self, orientation=wx.VERTICAL)
# Translators: This is the label for the edit field in the add symbol dialog.
symbolText = _("&Symbol:")
self.identifierTextCtrl = sHelper.addLabeledControl(symbolText, wx.TextCtrl)
sHelper.addDialogDismissButtons(self.CreateButtonSizer(wx.OK | wx.CANCEL))
mainSizer.Add(sHelper.sizer, border=guiHelper.BORDER_FOR_DIALOGS, flag=wx.ALL)
mainSizer.Fit(self)
self.SetSizer(mainSizer)
self.identifierTextCtrl.SetFocus()
self.CentreOnScreen()
class SpeechSymbolsDialog(SettingsDialog):
helpId = "SymbolPronunciation"
def __init__(self,parent):
try:
symbolProcessor = characterProcessing._localeSpeechSymbolProcessors.fetchLocaleData(speech.getCurrentLanguage())
except LookupError:
symbolProcessor = characterProcessing._localeSpeechSymbolProcessors.fetchLocaleData("en")
self.symbolProcessor = symbolProcessor
# Translators: This is the label for the symbol pronunciation dialog.
# %s is replaced by the language for which symbol pronunciation is being edited.
self.title = _("Symbol Pronunciation (%s)")%languageHandler.getLanguageDescription(self.symbolProcessor.locale)
super(SpeechSymbolsDialog, self).__init__(
parent,
resizeable=True,
)
def makeSettings(self, settingsSizer):
self.filteredSymbols = self.symbols = [
copy.copy(symbol) for symbol in self.symbolProcessor.computedSymbols.values()
]
self.pendingRemovals = {}
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: The label of a text field to search for symbols in the speech symbols dialog.
filterText = pgettext("speechSymbols", "&Filter by:")
self.filterEdit = sHelper.addLabeledControl(
labelText = filterText,
wxCtrlClass=wx.TextCtrl,
size=(self.scaleSize(310), -1),
)
self.filterEdit.Bind(wx.EVT_TEXT, self.onFilterEditTextChange)
# Translators: The label for symbols list in symbol pronunciation dialog.
symbolsText = _("&Symbols")
self.symbolsList = sHelper.addLabeledControl(
symbolsText,
nvdaControls.AutoWidthColumnListCtrl,
autoSizeColumn=2, # The replacement column is likely to need the most space
itemTextCallable=self.getItemTextForList,
style=wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_VIRTUAL
)
# Translators: The label for a column in symbols list used to identify a symbol.
self.symbolsList.InsertColumn(0, _("Symbol"), width=self.scaleSize(150))
# Translators: The label for a column in symbols list used to identify a replacement.
self.symbolsList.InsertColumn(1, _("Replacement"))
# Translators: The label for a column in symbols list used to identify a symbol's speech level (either none, some, most, all or character).
self.symbolsList.InsertColumn(2, _("Level"))
# Translators: The label for a column in symbols list which specifies when the actual symbol will be sent to the synthesizer (preserved).
# See the "Punctuation/Symbol Pronunciation" section of the User Guide for details.
self.symbolsList.InsertColumn(3, _("Preserve"))
self.symbolsList.Bind(wx.EVT_LIST_ITEM_FOCUSED, self.onListItemFocused)
# Translators: The label for the group of controls in symbol pronunciation dialog to change the pronunciation of a symbol.
changeSymbolText = _("Change selected symbol")
changeSymbolHelper = sHelper.addItem(guiHelper.BoxSizerHelper(
parent=self,
sizer=wx.StaticBoxSizer(
parent=self,
label=changeSymbolText,
orient=wx.VERTICAL,
)
))
# Used to ensure that event handlers call Skip(). Not calling skip can cause focus problems for controls. More
# generally the advice on the wx documentation is: "In general, it is recommended to skip all non-command events
# to allow the default handling to take place. The command events are, however, normally not skipped as usually
# a single command such as a button click or menu item selection must only be processed by one handler."
def skipEventAndCall(handler):
def wrapWithEventSkip(event):
if event:
event.Skip()
return handler()
return wrapWithEventSkip
# Translators: The label for the edit field in symbol pronunciation dialog to change the replacement text of a symbol.
replacementText = _("&Replacement")
self.replacementEdit = changeSymbolHelper.addLabeledControl(
labelText=replacementText,
wxCtrlClass=wx.TextCtrl,
size=(self.scaleSize(300), -1),
)
self.replacementEdit.Bind(wx.EVT_TEXT, skipEventAndCall(self.onSymbolEdited))
# Translators: The label for the combo box in symbol pronunciation dialog to change the speech level of a symbol.
levelText = _("&Level")
symbolLevelLabels = characterProcessing.SPEECH_SYMBOL_LEVEL_LABELS
levelChoices = [symbolLevelLabels[level] for level in characterProcessing.SPEECH_SYMBOL_LEVELS]
self.levelList = changeSymbolHelper.addLabeledControl(levelText, wx.Choice, choices=levelChoices)
self.levelList.Bind(wx.EVT_CHOICE, skipEventAndCall(self.onSymbolEdited))
# Translators: The label for the combo box in symbol pronunciation dialog to change when a symbol is sent to the synthesizer.
preserveText = _("&Send actual symbol to synthesizer")
symbolPreserveLabels = characterProcessing.SPEECH_SYMBOL_PRESERVE_LABELS
preserveChoices = [symbolPreserveLabels[mode] for mode in characterProcessing.SPEECH_SYMBOL_PRESERVES]
self.preserveList = changeSymbolHelper.addLabeledControl(preserveText, wx.Choice, choices=preserveChoices)
self.preserveList.Bind(wx.EVT_CHOICE, skipEventAndCall(self.onSymbolEdited))
bHelper = sHelper.addItem(guiHelper.ButtonHelper(orientation=wx.HORIZONTAL))
# Translators: The label for a button in the Symbol Pronunciation dialog to add a new symbol.
addButton = bHelper.addButton(self, label=_("&Add"))
# Translators: The label for a button in the Symbol Pronunciation dialog to remove a symbol.
self.removeButton = bHelper.addButton(self, label=_("Re&move"))
self.removeButton.Disable()
addButton.Bind(wx.EVT_BUTTON, self.OnAddClick)
self.removeButton.Bind(wx.EVT_BUTTON, self.OnRemoveClick)
# Populate the unfiltered list with symbols.
self.filter()
def postInit(self):
self.symbolsList.SetFocus()
def filter(self, filterText=''):
NONE_SELECTED = -1
previousSelectionValue = None
previousIndex = self.symbolsList.GetFirstSelected() # may return NONE_SELECTED
if previousIndex != NONE_SELECTED:
previousSelectionValue = self.filteredSymbols[previousIndex]
if not filterText:
self.filteredSymbols = self.symbols
else:
# Do case-insensitive matching by lowering both filterText and each symbols's text.
filterText = filterText.lower()
self.filteredSymbols = [
symbol for symbol in self.symbols
if filterText in symbol.displayName.lower()
or filterText in symbol.replacement.lower()
]
self.symbolsList.ItemCount = len(self.filteredSymbols)
# sometimes filtering may result in an empty list.
if not self.symbolsList.ItemCount:
self.editingItem = None
# disable the "change symbol" controls, since there are no items in the list.
self.replacementEdit.Disable()
self.levelList.Disable()
self.preserveList.Disable()
self.removeButton.Disable()
return # exit early, no need to select an item.
# If there was a selection before filtering, try to preserve it
newIndex = 0 # select first item by default.
if previousSelectionValue:
try:
newIndex = self.filteredSymbols.index(previousSelectionValue)
except ValueError:
pass
# Change the selection
self.symbolsList.Select(newIndex)
self.symbolsList.Focus(newIndex)
# We don't get a new focus event with the new index.
self.symbolsList.sendListItemFocusedEvent(newIndex)
def getItemTextForList(self, item, column):
symbol = self.filteredSymbols[item]
if column == 0:
return symbol.displayName
elif column == 1:
return symbol.replacement
elif column == 2:
return characterProcessing.SPEECH_SYMBOL_LEVEL_LABELS[symbol.level]
elif column == 3:
return characterProcessing.SPEECH_SYMBOL_PRESERVE_LABELS[symbol.preserve]
else:
raise ValueError("Unknown column: %d" % column)
def onSymbolEdited(self):
if self.editingItem is not None:
# Update the symbol the user was just editing.
item = self.editingItem
symbol = self.filteredSymbols[item]
symbol.replacement = self.replacementEdit.Value
symbol.level = characterProcessing.SPEECH_SYMBOL_LEVELS[self.levelList.Selection]
symbol.preserve = characterProcessing.SPEECH_SYMBOL_PRESERVES[self.preserveList.Selection]
def onListItemFocused(self, evt):
# Update the editing controls to reflect the newly selected symbol.
item = evt.GetIndex()
symbol = self.filteredSymbols[item]
self.editingItem = item
# ChangeValue and Selection property used because they do not cause EVNT_CHANGED to be fired.
self.replacementEdit.ChangeValue(symbol.replacement)
self.levelList.Selection = characterProcessing.SPEECH_SYMBOL_LEVELS.index(symbol.level)
self.preserveList.Selection = characterProcessing.SPEECH_SYMBOL_PRESERVES.index(symbol.preserve)
self.removeButton.Enabled = not self.symbolProcessor.isBuiltin(symbol.identifier)
self.replacementEdit.Enable()
self.levelList.Enable()
self.preserveList.Enable()
evt.Skip()
def OnAddClick(self, evt):
with AddSymbolDialog(self) as entryDialog:
if entryDialog.ShowModal() != wx.ID_OK:
return
identifier = entryDialog.identifierTextCtrl.GetValue()
if not identifier:
return
# Clean the filter, so we can select the new entry.
self.filterEdit.Value=""
self.filter()
for index, symbol in enumerate(self.symbols):
if identifier == symbol.identifier:
# Translators: An error reported in the Symbol Pronunciation dialog when adding a symbol that is already present.
gui.messageBox(_('Symbol "%s" is already present.') % identifier,
_("Error"), wx.OK | wx.ICON_ERROR)
self.symbolsList.Select(index)
self.symbolsList.Focus(index)
self.symbolsList.SetFocus()
return
addedSymbol = characterProcessing.SpeechSymbol(identifier)
try:
del self.pendingRemovals[identifier]
except KeyError:
pass
addedSymbol.displayName = identifier
addedSymbol.replacement = ""
addedSymbol.level = characterProcessing.SYMLVL_ALL
addedSymbol.preserve = characterProcessing.SYMPRES_NEVER
self.symbols.append(addedSymbol)
self.symbolsList.ItemCount = len(self.symbols)
index = self.symbolsList.ItemCount - 1
self.symbolsList.Select(index)
self.symbolsList.Focus(index)
# We don't get a new focus event with the new index.
self.symbolsList.sendListItemFocusedEvent(index)
self.symbolsList.SetFocus()
def OnRemoveClick(self, evt):
index = self.symbolsList.GetFirstSelected()
symbol = self.filteredSymbols[index]
self.pendingRemovals[symbol.identifier] = symbol
del self.filteredSymbols[index]
if self.filteredSymbols is not self.symbols:
self.symbols.remove(symbol)
self.symbolsList.ItemCount = len(self.filteredSymbols)
# sometimes removing may result in an empty list.
if not self.symbolsList.ItemCount:
self.editingItem = None
# disable the "change symbol" controls, since there are no items in the list.
self.replacementEdit.Disable()
self.levelList.Disable()
self.preserveList.Disable()
self.removeButton.Disable()
else:
index = min(index, self.symbolsList.ItemCount - 1)
self.symbolsList.Select(index)
self.symbolsList.Focus(index)
# We don't get a new focus event with the new index.
self.symbolsList.sendListItemFocusedEvent(index)
self.symbolsList.SetFocus()
def onOk(self, evt):
self.onSymbolEdited()
self.editingItem = None
for symbol in self.pendingRemovals.values():
self.symbolProcessor.deleteSymbol(symbol)
for symbol in self.symbols:
if not symbol.replacement:
continue
self.symbolProcessor.updateSymbol(symbol)
try:
self.symbolProcessor.userSymbols.save()
except IOError as e:
log.error("Error saving user symbols info: %s" % e)
characterProcessing._localeSpeechSymbolProcessors.invalidateLocaleData(self.symbolProcessor.locale)
super(SpeechSymbolsDialog, self).onOk(evt)
def _refreshVisibleItems(self):
count = self.symbolsList.GetCountPerPage()
first = self.symbolsList.GetTopItem()
self.symbolsList.RefreshItems(first, first+count)
def onFilterEditTextChange(self, evt):
self.filter(self.filterEdit.Value)
self._refreshVisibleItems()
evt.Skip()
| 45.64406 | 262 | 0.76116 |
import logging
from abc import ABCMeta
import copy
import wx
from vision.providerBase import VisionEnhancementProviderSettings
from wx.lib import scrolledpanel
from wx.lib.expando import ExpandoTextCtrl
import wx.lib.newevent
import winUser
import logHandler
import installer
from synthDriverHandler import *
from synthDriverHandler import SynthDriver, getSynth
import config
import languageHandler
import speech
import gui
import globalVars
from logHandler import log
import nvwave
import audioDucking
import speechDictHandler
import queueHandler
import braille
import brailleTables
import brailleInput
import vision
import vision.providerInfo
import vision.providerBase
from typing import Callable, List, Optional, Any
import core
import keyboardHandler
import characterProcessing
from . import guiHelper
try:
import updateCheck
except RuntimeError:
updateCheck = None
from . import nvdaControls
from autoSettingsUtils.utils import UnsupportedConfigParameterError
from autoSettingsUtils.autoSettings import AutoSettings
from autoSettingsUtils.driverSetting import BooleanDriverSetting, NumericDriverSetting, DriverSetting
import touchHandler
import winVersion
import weakref
import time
import keyLabels
from .dpiScalingHelper import DpiScalingHelperMixinWithoutInit
class SettingsDialog(
DpiScalingHelperMixinWithoutInit,
gui.ContextHelpMixin,
wx.Dialog,
metaclass=guiHelper.SIPABCMeta
):
class MultiInstanceError(RuntimeError): pass
_DIALOG_CREATED_STATE = 0
_DIALOG_DESTROYED_STATE = 1
_instances=weakref.WeakKeyDictionary()
title = ""
helpId = "NVDASettings"
shouldSuspendConfigProfileTriggers = True
def __new__(cls, *args, **kwargs):
instanceItems = SettingsDialog._instances.items()
instancesOfSameClass = (
(dlg, state) for dlg, state in instanceItems if isinstance(dlg, cls)
)
firstMatchingInstance, state = next(instancesOfSameClass, (None, None))
multiInstanceAllowed = kwargs.get('multiInstanceAllowed', False)
if log.isEnabledFor(log.DEBUG):
instancesState = dict(SettingsDialog._instances)
log.debug(
"Creating new settings dialog (multiInstanceAllowed:{}). "
"State of _instances {!r}".format(multiInstanceAllowed, instancesState)
)
if state is cls._DIALOG_CREATED_STATE and not multiInstanceAllowed:
raise SettingsDialog.MultiInstanceError("Only one instance of SettingsDialog can exist at a time")
if state is cls._DIALOG_DESTROYED_STATE and not multiInstanceAllowed:
log.error("Opening new settings dialog while instance still exists: {!r}".format(firstMatchingInstance))
obj = super(SettingsDialog, cls).__new__(cls, *args, **kwargs)
SettingsDialog._instances[obj] = cls._DIALOG_CREATED_STATE
return obj
def _setInstanceDestroyedState(self):
if log.isEnabledFor(log.DEBUG):
instancesState = dict(SettingsDialog._instances)
log.debug(
"Setting state to destroyed for instance: {!r}\n"
"Current _instances {!r}".format(self, instancesState)
)
if self in SettingsDialog._instances:
SettingsDialog._instances[self] = self._DIALOG_DESTROYED_STATE
def __init__(
self, parent,
resizeable=False,
hasApplyButton=False,
settingsSizerOrientation=wx.VERTICAL,
multiInstanceAllowed=False
):
if gui._isDebug():
startTime = time.time()
windowStyle = wx.DEFAULT_DIALOG_STYLE
if resizeable:
windowStyle |= wx.RESIZE_BORDER | wx.MAXIMIZE_BOX
super().__init__(parent, title=self.title, style=windowStyle)
self.hasApply = hasApplyButton
self.mainSizer=wx.BoxSizer(wx.VERTICAL)
self.settingsSizer=wx.BoxSizer(settingsSizerOrientation)
self.makeSettings(self.settingsSizer)
self.mainSizer.Add(self.settingsSizer, border=guiHelper.BORDER_FOR_DIALOGS, flag=wx.ALL | wx.EXPAND, proportion=1)
buttons = wx.OK | wx.CANCEL
if hasApplyButton:
buttons |= wx.APPLY
self.mainSizer.Add(
self.CreateSeparatedButtonSizer(buttons),
border=guiHelper.BORDER_FOR_DIALOGS,
flag=wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
)
self.mainSizer.Fit(self)
self.SetSizer(self.mainSizer)
self.Bind(wx.EVT_BUTTON, self.onOk, id=wx.ID_OK)
self.Bind(wx.EVT_BUTTON, self.onCancel, id=wx.ID_CANCEL)
self.Bind(wx.EVT_BUTTON, self.onApply, id=wx.ID_APPLY)
self.Bind(wx.EVT_CHAR_HOOK, self._enterActivatesOk_ctrlSActivatesApply)
self.Bind(wx.EVT_WINDOW_DESTROY, self._onWindowDestroy)
self.postInit()
if resizeable:
self.SetMinSize(self.mainSizer.GetMinSize())
self.CentreOnScreen()
if gui._isDebug():
log.debug("Loading %s took %.2f seconds"%(self.__class__.__name__, time.time() - startTime))
def _enterActivatesOk_ctrlSActivatesApply(self, evt):
if evt.KeyCode in (wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER):
self.ProcessEvent(wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, wx.ID_OK))
elif self.hasApply and evt.UnicodeKey == ord(u'S') and evt.controlDown:
self.ProcessEvent(wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, wx.ID_APPLY))
else:
evt.Skip()
@abstractmethod
def makeSettings(self, sizer):
raise NotImplementedError
def postInit(self):
def onOk(self, evt):
self.DestroyChildren()
self.Destroy()
self.SetReturnCode(wx.ID_OK)
def onCancel(self, evt):
self.DestroyChildren()
self.Destroy()
self.SetReturnCode(wx.ID_CANCEL)
def onApply(self, evt):
self.postInit()
self.SetReturnCode(wx.ID_APPLY)
def _onWindowDestroy(self, evt):
evt.Skip()
self._setInstanceDestroyedState()
_RWLayoutNeededEvent, EVT_RW_LAYOUT_NEEDED = wx.lib.newevent.NewCommandEvent()
class SettingsPanel(
DpiScalingHelperMixinWithoutInit,
gui.ContextHelpMixin,
wx.Panel,
metaclass=guiHelper.SIPABCMeta
):
title=""
panelDescription=u""
def __init__(self, parent: wx.Window):
if gui._isDebug():
startTime = time.time()
super().__init__(parent)
self._buildGui()
if gui._isDebug():
elapsedSeconds = time.time() - startTime
panelName = self.__class__.__qualname__
log.debug(f"Loading {panelName} took {elapsedSeconds:.2f} seconds")
def _buildGui(self):
self.mainSizer=wx.BoxSizer(wx.VERTICAL)
self.settingsSizer=wx.BoxSizer(wx.VERTICAL)
self.makeSettings(self.settingsSizer)
self.mainSizer.Add(self.settingsSizer, flag=wx.ALL | wx.EXPAND)
self.mainSizer.Fit(self)
self.SetSizer(self.mainSizer)
@abstractmethod
def makeSettings(self, sizer: wx.BoxSizer):
raise NotImplementedError
def onPanelActivated(self):
self.Show()
def onPanelDeactivated(self):
self.Hide()
@abstractmethod
def onSave(self):
raise NotImplementedError
def isValid(self):
return True
def postSave(self):
def onDiscard(self):
def _sendLayoutUpdatedEvent(self):
event = _RWLayoutNeededEvent(self.GetId())
event.SetEventObject(self)
self.GetEventHandler().ProcessEvent(event)
class MultiCategorySettingsDialog(SettingsDialog):
title=""
categoryClasses=[]
class CategoryUnavailableError(RuntimeError): pass
def __init__(self, parent, initialCategory=None):
if initialCategory and not issubclass(initialCategory,SettingsPanel):
if gui._isDebug():
log.debug("Unable to open category: {}".format(initialCategory), stack_info=True)
raise TypeError("initialCategory should be an instance of SettingsPanel")
if initialCategory and initialCategory not in self.categoryClasses:
if gui._isDebug():
log.debug("Unable to open category: {}".format(initialCategory), stack_info=True)
raise MultiCategorySettingsDialog.CategoryUnavailableError(
"The provided initial category is not a part of this dialog"
)
self.initialCategory = initialCategory
self.currentCategory = None
self.setPostInitFocus = None
self.catIdToInstanceMap = {}
super(MultiCategorySettingsDialog, self).__init__(
parent,
resizeable=True,
hasApplyButton=True,
settingsSizerOrientation=wx.HORIZONTAL
)
self.SetMinSize(self.scaleSize(self.MIN_SIZE))
self.SetSize(self.scaleSize(self.INITIAL_SIZE))
self.CentreOnScreen()
INITIAL_SIZE = (800, 480)
MIN_SIZE = (470, 240)
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
categoriesLabelText=_("&Categories:")
categoriesLabel = wx.StaticText(self, label=categoriesLabelText)
catListDim = (150, 10)
catListDim = self.scaleSize(catListDim)
initialScaledWidth = self.scaleSize(self.INITIAL_SIZE[0])
spaceForBorderWidth = self.scaleSize(20)
catListWidth = catListDim[0]
containerDim = (initialScaledWidth - catListWidth - spaceForBorderWidth, self.scaleSize(10))
self.catListCtrl = nvdaControls.AutoWidthColumnListCtrl(
self,
autoSizeColumn=1,
size=catListDim,
style=wx.LC_REPORT|wx.LC_SINGLE_SEL|wx.LC_NO_HEADER
)
self.catListCtrl.InsertColumn(0,categoriesLabelText)
self.container = scrolledpanel.ScrolledPanel(
parent = self,
style = wx.TAB_TRAVERSAL | wx.BORDER_THEME,
size=containerDim
)
self.container.SetMinSize((1,1))
self.catListCtrl.SetMinSize((1,1))
self.containerSizer = wx.BoxSizer(wx.VERTICAL)
self.container.SetSizer(self.containerSizer)
for cls in self.categoryClasses:
if not issubclass(cls,SettingsPanel):
raise RuntimeError("Invalid category class %s provided in %s.categoryClasses"%(cls.__name__,self.__class__.__name__))
# the ListItem index / Id is used to index categoryClasses, and used as the key in catIdToInstanceMap
self.catListCtrl.Append((cls.title,))
# populate the GUI with the initial category
initialCatIndex = 0 if not self.initialCategory else self.categoryClasses.index(self.initialCategory)
self._doCategoryChange(initialCatIndex)
self.catListCtrl.Select(initialCatIndex)
# we must focus the initial category in the category list.
self.catListCtrl.Focus(initialCatIndex)
self.setPostInitFocus = self.container.SetFocus if self.initialCategory else self.catListCtrl.SetFocus
self.gridBagSizer=gridBagSizer=wx.GridBagSizer(
hgap=guiHelper.SPACE_BETWEEN_BUTTONS_HORIZONTAL,
vgap=guiHelper.SPACE_BETWEEN_BUTTONS_VERTICAL
)
# add the label, the categories list, and the settings panel to a 2 by 2 grid.
# The label should span two columns, so that the start of the categories list
# and the start of the settings panel are at the same vertical position.
gridBagSizer.Add(categoriesLabel, pos=(0,0), span=(1,2))
gridBagSizer.Add(self.catListCtrl, pos=(1,0), flag=wx.EXPAND)
gridBagSizer.Add(self.container, pos=(1,1), flag=wx.EXPAND)
# Make the row with the listCtrl and settings panel grow vertically.
gridBagSizer.AddGrowableRow(1)
# Make the columns with the listCtrl and settings panel grow horizontally if the dialog is resized.
# They should grow 1:3, since the settings panel is much more important, and already wider
# than the listCtrl.
gridBagSizer.AddGrowableCol(0, proportion=1)
gridBagSizer.AddGrowableCol(1, proportion=3)
sHelper.sizer.Add(gridBagSizer, flag=wx.EXPAND, proportion=1)
self.container.Layout()
self.catListCtrl.Bind(wx.EVT_LIST_ITEM_FOCUSED, self.onCategoryChange)
self.Bind(wx.EVT_CHAR_HOOK, self.onCharHook)
self.Bind(EVT_RW_LAYOUT_NEEDED, self._onPanelLayoutChanged)
def _getCategoryPanel(self, catId):
panel = self.catIdToInstanceMap.get(catId, None)
if not panel:
try:
cls = self.categoryClasses[catId]
except IndexError:
raise ValueError("Unable to create panel for unknown category ID: {}".format(catId))
panel = cls(parent=self.container)
panel.Hide()
self.containerSizer.Add(
panel, flag=wx.ALL | wx.EXPAND,
border=guiHelper.SPACE_BETWEEN_ASSOCIATED_CONTROL_HORIZONTAL
)
self.catIdToInstanceMap[catId] = panel
panelWidth = panel.Size[0]
availableWidth = self.containerSizer.GetSize()[0]
if panelWidth > availableWidth and gui._isDebug():
log.debugWarning(
("Panel width ({1}) too large for: {0} Try to reduce the width of this panel, or increase width of " +
"MultiCategorySettingsDialog.MIN_SIZE"
).format(cls, panel.Size[0])
)
panel.SetLabel(panel.title)
import oleacc
panel.server = nvdaControls.AccPropertyOverride(
panel,
propertyAnnotations={
oleacc.PROPID_ACC_ROLE: oleacc.ROLE_SYSTEM_PROPERTYPAGE, # change the role from pane to property page
oleacc.PROPID_ACC_DESCRIPTION: panel.panelDescription, # set a description
}
)
return panel
def postInit(self):
# By default after the dialog is created, focus lands on the button group for wx.Dialogs. However this is not where
# we want focus. We only want to modify focus after creation (makeSettings), but postInit is also called after
# onApply, so we reset the setPostInitFocus function.
if self.setPostInitFocus:
self.setPostInitFocus()
self.setPostInitFocus = None
else:
# when postInit is called without a setPostInitFocus ie because onApply was called
# then set the focus to the listCtrl. This is a good starting point for a "fresh state"
self.catListCtrl.SetFocus()
def onCharHook(self,evt):
if not self.catListCtrl:
# Dialog has not yet been constructed.
# Allow another handler to take the event, and return early.
evt.Skip()
return
key = evt.GetKeyCode()
listHadFocus = self.catListCtrl.HasFocus()
if evt.ControlDown() and key==wx.WXK_TAB:
# Focus the categories list. If we don't, the panel won't hide correctly
if not listHadFocus:
self.catListCtrl.SetFocus()
index = self.catListCtrl.GetFirstSelected()
newIndex=index-1 if evt.ShiftDown() else index+1
# Less than first wraps to the last index, greater than last wraps to first index.
newIndex=newIndex % self.catListCtrl.ItemCount
self.catListCtrl.Select(newIndex)
# we must focus the new selection in the category list to trigger the change of category.
self.catListCtrl.Focus(newIndex)
if not listHadFocus and self.currentCategory:
self.currentCategory.SetFocus()
else:
evt.Skip()
def _onPanelLayoutChanged(self,evt):
# call layout and SetupScrolling on the container so that the controls apear in their expected locations.
self.container.Layout()
self.container.SetupScrolling()
# when child elements get smaller the scrolledPanel does not
# erase the old contents and must be redrawn
self.container.Refresh()
def _doCategoryChange(self, newCatId):
oldCat = self.currentCategory
# Freeze and Thaw are called to stop visual artifact's while the GUI
self.container.Freeze()
try:
newCat = self._getCategoryPanel(newCatId)
except ValueError as e:
newCatTitle = self.catListCtrl.GetItemText(newCatId)
log.error("Unable to change to category: {}".format(newCatTitle), exc_info=e)
return
if oldCat:
oldCat.onPanelDeactivated()
self.currentCategory = newCat
newCat.onPanelActivated()
self.container.Layout()
self.container.SetupScrolling()
self.container.Thaw()
def onCategoryChange(self, evt):
currentCat = self.currentCategory
newIndex = evt.GetIndex()
if not currentCat or newIndex != self.categoryClasses.index(currentCat.__class__):
self._doCategoryChange(newIndex)
else:
evt.Skip()
def _doSave(self):
for panel in self.catIdToInstanceMap.values():
if panel.isValid() is False:
raise ValueError("Validation for %s blocked saving settings" % panel.__class__.__name__)
for panel in self.catIdToInstanceMap.values():
panel.onSave()
for panel in self.catIdToInstanceMap.values():
panel.postSave()
def onOk(self,evt):
try:
self._doSave()
except ValueError:
log.debugWarning("", exc_info=True)
return
for panel in self.catIdToInstanceMap.values():
panel.Destroy()
super(MultiCategorySettingsDialog,self).onOk(evt)
def onCancel(self,evt):
for panel in self.catIdToInstanceMap.values():
panel.onDiscard()
panel.Destroy()
super(MultiCategorySettingsDialog,self).onCancel(evt)
def onApply(self,evt):
try:
self._doSave()
except ValueError:
log.debugWarning("", exc_info=True)
return
super(MultiCategorySettingsDialog,self).onApply(evt)
class GeneralSettingsPanel(SettingsPanel):
title = _("General")
helpId = "GeneralSettingsLanguage"
LOG_LEVELS = (
(log.OFF, _("disabled")),
(log.INFO, _("info")),
(log.DEBUGWARNING, _("debug warning")),
(log.IO, _("input/output")),
(log.DEBUG, _("debug"))
)
def makeSettings(self, settingsSizer):
settingsSizerHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
self.languageNames = languageHandler.getAvailableLanguages(presentational=True)
languageChoices = [x[1] for x in self.languageNames]
# (once selected, NVDA must be restarted; the option user default means the user's Windows language
languageLabelText = _("NVDA &Language (requires restart):")
self.languageList=settingsSizerHelper.addLabeledControl(languageLabelText, wx.Choice, choices=languageChoices)
self.languageList.SetToolTip(wx.ToolTip("Choose the language NVDA's messages and user interface should be presented in."))
try:
self.oldLanguage=config.conf["general"]["language"]
index=[x[0] for x in self.languageNames].index(self.oldLanguage)
self.languageList.SetSelection(index)
except:
pass
if globalVars.appArgs.secure:
self.languageList.Disable()
# Translators: The label for a setting in general settings to save current configuration when NVDA
# exits (if it is not checked, user needs to save configuration before quitting NVDA).
self.saveOnExitCheckBox = wx.CheckBox(self, label=_("&Save configuration when exiting NVDA"))
self.saveOnExitCheckBox.SetValue(config.conf["general"]["saveConfigurationOnExit"])
if globalVars.appArgs.secure:
self.saveOnExitCheckBox.Disable()
settingsSizerHelper.addItem(self.saveOnExitCheckBox)
# Translators: The label for a setting in general settings to ask before quitting NVDA (if not checked, NVDA will exit without asking the user for action).
self.askToExitCheckBox=wx.CheckBox(self,label=_("Sho&w exit options when exiting NVDA"))
self.askToExitCheckBox.SetValue(config.conf["general"]["askToExit"])
settingsSizerHelper.addItem(self.askToExitCheckBox)
self.bindHelpEvent("GeneralSettingsShowExitOptions", self.askToExitCheckBox)
# Translators: The label for a setting in general settings to play sounds when NVDA starts or exits.
self.playStartAndExitSoundsCheckBox=wx.CheckBox(self,label=_("&Play sounds when starting or exiting NVDA"))
self.bindHelpEvent("GeneralSettingsPlaySounds", self.playStartAndExitSoundsCheckBox)
self.playStartAndExitSoundsCheckBox.SetValue(config.conf["general"]["playStartAndExitSounds"])
settingsSizerHelper.addItem(self.playStartAndExitSoundsCheckBox)
# Translators: The label for a setting in general settings to select logging level of NVDA as it runs
# (available options and what they are logging are found under comments for the logging level messages
# themselves).
logLevelLabelText=_("L&ogging level:")
logLevelChoices = [name for level, name in self.LOG_LEVELS]
self.logLevelList = settingsSizerHelper.addLabeledControl(logLevelLabelText, wx.Choice, choices=logLevelChoices)
curLevel = log.getEffectiveLevel()
if logHandler.isLogLevelForced():
self.logLevelList.Disable()
for index, (level, name) in enumerate(self.LOG_LEVELS):
if level == curLevel:
self.logLevelList.SetSelection(index)
break
else:
log.debugWarning("Could not set log level list to current log level")
# Translators: The label for a setting in general settings to allow NVDA to start after logging onto
# Windows (if checked, NVDA will start automatically after logging into Windows; if not, user must
# start NVDA by pressing the shortcut key (CTRL+Alt+N by default).
self.startAfterLogonCheckBox = wx.CheckBox(self, label=_("St&art NVDA after I sign in"))
self.startAfterLogonCheckBox.SetValue(config.getStartAfterLogon())
if globalVars.appArgs.secure or not config.isInstalledCopy():
self.startAfterLogonCheckBox.Disable()
settingsSizerHelper.addItem(self.startAfterLogonCheckBox)
self.bindHelpEvent("GeneralSettingsStartAfterLogOn", self.startAfterLogonCheckBox)
self.startOnLogonScreenCheckBox = wx.CheckBox(
self,
# Translators: The label for a setting in general settings to
# allow NVDA to come up in Windows login screen (useful if user
# needs to enter passwords or if multiple user accounts are present
# to allow user to choose the correct account).
label=_("Use NVDA during sign-in (requires administrator privileges)")
)
self.bindHelpEvent("GeneralSettingsStartOnLogOnScreen", self.startOnLogonScreenCheckBox)
self.startOnLogonScreenCheckBox.SetValue(config.getStartOnLogonScreen())
if globalVars.appArgs.secure or not config.canStartOnSecureScreens():
self.startOnLogonScreenCheckBox.Disable()
settingsSizerHelper.addItem(self.startOnLogonScreenCheckBox)
self.copySettingsButton = wx.Button(
self,
label=_(
# Translators: The label for a button in general settings to copy
# current user settings to system settings (to allow current
# settings to be used in secure screens such as User Account
# Control (UAC) dialog).
"Use currently saved settings during sign-in and on secure screens"
" (requires administrator privileges)"
)
)
self.bindHelpEvent("GeneralSettingsCopySettings", self.copySettingsButton)
self.copySettingsButton.Bind(wx.EVT_BUTTON,self.onCopySettings)
if globalVars.appArgs.secure or not config.canStartOnSecureScreens():
self.copySettingsButton.Disable()
settingsSizerHelper.addItem(self.copySettingsButton)
if updateCheck:
# Translators: The label of a checkbox in general settings to toggle automatic checking for updated versions of NVDA (if not checked, user must check for updates manually).
item=self.autoCheckForUpdatesCheckBox=wx.CheckBox(self,label=_("Automatically check for &updates to NVDA"))
self.bindHelpEvent("GeneralSettingsCheckForUpdates", self.autoCheckForUpdatesCheckBox)
item.Value=config.conf["update"]["autoCheck"]
if globalVars.appArgs.secure:
item.Disable()
settingsSizerHelper.addItem(item)
# Translators: The label of a checkbox in general settings to toggle startup notifications
# for a pending NVDA update.
item=self.notifyForPendingUpdateCheckBox=wx.CheckBox(self,label=_("Notify for &pending update on startup"))
item.Value=config.conf["update"]["startupNotification"]
if globalVars.appArgs.secure:
item.Disable()
settingsSizerHelper.addItem(item)
# Translators: The label of a checkbox in general settings to toggle allowing of usage stats gathering
item=self.allowUsageStatsCheckBox=wx.CheckBox(self,label=_("Allow the NVDA project to gather NVDA usage statistics"))
item.Value=config.conf["update"]["allowUsageStats"]
if globalVars.appArgs.secure:
item.Disable()
settingsSizerHelper.addItem(item)
def onCopySettings(self,evt):
addonsDirPath = os.path.join(globalVars.appArgs.configPath, 'addons')
if os.path.isdir(addonsDirPath) and 0 < len(os.listdir(addonsDirPath)):
message = _(
# Translators: A message to warn the user when attempting to copy current
# settings to system settings.
"Add-ons were detected in your user settings directory. "
"Copying these to the system profile could be a security risk. "
"Do you still wish to copy your settings?"
)
# Translators: The title of the warning dialog displayed when trying to
# copy settings for use in secure screens.
title = _("Warning")
style = wx.YES | wx.NO | wx.ICON_WARNING
if wx.NO == gui.messageBox(message, title, style, self):
return
progressDialog = gui.IndeterminateProgressDialog(
gui.mainFrame,
# Translators: The title of the dialog presented while settings are being copied
_("Copying Settings"),
# Translators: The message displayed while settings are being copied
# to the system configuration (for use on Windows logon etc)
_("Please wait while settings are copied to the system configuration.")
)
while True:
try:
gui.ExecAndPump(config.setSystemConfigToCurrentConfig)
res=True
break
except installer.RetriableFailure:
log.debugWarning("Error when copying settings to system config",exc_info=True)
# Translators: a message dialog asking to retry or cancel when copying settings fails
message=_("Unable to copy a file. Perhaps it is currently being used by another process or you have run out of disc space on the drive you are copying to.")
# Translators: the title of a retry cancel dialog when copying settings fails
title=_("Error Copying")
if winUser.MessageBox(None,message,title,winUser.MB_RETRYCANCEL)==winUser.IDRETRY:
continue
res=False
break
except:
log.debugWarning("Error when copying settings to system config",exc_info=True)
res=False
break
progressDialog.done()
del progressDialog
if not res:
# Translators: The message displayed when errors were found while trying to copy current configuration to system settings.
gui.messageBox(_("Error copying NVDA user settings"),_("Error"),wx.OK|wx.ICON_ERROR,self)
else:
# Translators: The message displayed when copying configuration to system settings was successful.
gui.messageBox(_("Successfully copied NVDA user settings"),_("Success"),wx.OK|wx.ICON_INFORMATION,self)
def onSave(self):
newLanguage=[x[0] for x in self.languageNames][self.languageList.GetSelection()]
config.conf["general"]["language"]=newLanguage
config.conf["general"]["saveConfigurationOnExit"]=self.saveOnExitCheckBox.IsChecked()
config.conf["general"]["askToExit"]=self.askToExitCheckBox.IsChecked()
config.conf["general"]["playStartAndExitSounds"]=self.playStartAndExitSoundsCheckBox.IsChecked()
logLevel=self.LOG_LEVELS[self.logLevelList.GetSelection()][0]
if not logHandler.isLogLevelForced():
config.conf["general"]["loggingLevel"] = logging.getLevelName(logLevel)
logHandler.setLogLevelFromConfig()
if self.startAfterLogonCheckBox.IsEnabled():
config.setStartAfterLogon(self.startAfterLogonCheckBox.GetValue())
if self.startOnLogonScreenCheckBox.IsEnabled():
try:
config.setStartOnLogonScreen(self.startOnLogonScreenCheckBox.GetValue())
except (WindowsError, RuntimeError):
gui.messageBox(_("This change requires administrator privileges."), _("Insufficient Privileges"), style=wx.OK | wx.ICON_ERROR, parent=self)
if updateCheck:
config.conf["update"]["autoCheck"]=self.autoCheckForUpdatesCheckBox.IsChecked()
config.conf["update"]["allowUsageStats"]=self.allowUsageStatsCheckBox.IsChecked()
config.conf["update"]["startupNotification"]=self.notifyForPendingUpdateCheckBox.IsChecked()
updateCheck.terminate()
updateCheck.initialize()
def postSave(self):
if self.oldLanguage != config.conf["general"]["language"]:
LanguageRestartDialog(self).ShowModal()
class LanguageRestartDialog(wx.Dialog):
def __init__(self, parent):
# Translators: The title of the dialog which appears when the user changed NVDA's interface language.
super(LanguageRestartDialog, self).__init__(parent, title=_("Language Configuration Change"))
mainSizer = wx.BoxSizer(wx.VERTICAL)
sHelper = guiHelper.BoxSizerHelper(self, orientation=wx.VERTICAL)
sHelper.addItem(wx.StaticText(self, label=_("NVDA must be restarted for the new language to take effect.")))
bHelper = sHelper.addDialogDismissButtons(guiHelper.ButtonHelper(wx.HORIZONTAL))
restartNowButton = bHelper.addButton(self, label=_("Restart &now"))
restartNowButton.Bind(wx.EVT_BUTTON, self.onRestartNowButton)
restartNowButton.SetFocus()
# Translators: The label for a button in the dialog which appears when the user changed NVDA's interface language.
restartLaterButton = bHelper.addButton(self, wx.ID_CLOSE, label=_("Restart &later"))
restartLaterButton.Bind(wx.EVT_BUTTON, lambda evt: self.Close())
self.Bind(wx.EVT_CLOSE, lambda evt: self.Destroy())
self.EscapeId = wx.ID_CLOSE
mainSizer.Add(sHelper.sizer, border=guiHelper.BORDER_FOR_DIALOGS, flag=wx.ALL)
self.Sizer = mainSizer
mainSizer.Fit(self)
self.CentreOnScreen()
def onRestartNowButton(self, evt):
self.Destroy()
config.conf.save()
queueHandler.queueFunction(queueHandler.eventQueue,core.restart)
class SpeechSettingsPanel(SettingsPanel):
title = _("Speech")
helpId = "SpeechSettings"
def makeSettings(self, settingsSizer):
settingsSizerHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
synthLabel = _("&Synthesizer")
synthBox = wx.StaticBox(self, label=synthLabel)
synthGroup = guiHelper.BoxSizerHelper(self, sizer=wx.StaticBoxSizer(synthBox, wx.HORIZONTAL))
settingsSizerHelper.addItem(synthGroup)
synthDesc = getSynth().description
self.synthNameCtrl = ExpandoTextCtrl(self, size=(self.scaleSize(250), -1), value=synthDesc, style=wx.TE_READONLY)
self.synthNameCtrl.Bind(wx.EVT_CHAR_HOOK, self._enterTriggersOnChangeSynth)
changeSynthBtn = wx.Button(self, label=_("C&hange..."))
self.bindHelpEvent("SpeechSettingsChange", self.synthNameCtrl)
self.bindHelpEvent("SpeechSettingsChange", changeSynthBtn)
synthGroup.addItem(
guiHelper.associateElements(
self.synthNameCtrl,
changeSynthBtn
)
)
changeSynthBtn.Bind(wx.EVT_BUTTON,self.onChangeSynth)
self.voicePanel = VoiceSettingsPanel(self)
settingsSizerHelper.addItem(self.voicePanel)
def _enterTriggersOnChangeSynth(self, evt):
if evt.KeyCode == wx.WXK_RETURN:
self.onChangeSynth(evt)
else:
evt.Skip()
def onChangeSynth(self, evt):
changeSynth = SynthesizerSelectionDialog(self, multiInstanceAllowed=True)
ret = changeSynth.ShowModal()
if ret == wx.ID_OK:
self.Freeze()
self.onPanelActivated()
self._sendLayoutUpdatedEvent()
self.Thaw()
def updateCurrentSynth(self):
synthDesc = getSynth().description
self.synthNameCtrl.SetValue(synthDesc)
def onPanelActivated(self):
self.voicePanel.onPanelActivated()
super(SpeechSettingsPanel,self).onPanelActivated()
def onPanelDeactivated(self):
self.voicePanel.onPanelDeactivated()
super(SpeechSettingsPanel,self).onPanelDeactivated()
def onDiscard(self):
self.voicePanel.onDiscard()
def onSave(self):
self.voicePanel.onSave()
class SynthesizerSelectionDialog(SettingsDialog):
title = _("Select Synthesizer")
helpId = "SynthesizerSelection"
synthNames = []
def makeSettings(self, settingsSizer):
settingsSizerHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
synthListLabelText=_("&Synthesizer:")
self.synthList = settingsSizerHelper.addLabeledControl(synthListLabelText, wx.Choice, choices=[])
self.bindHelpEvent("SelectSynthesizerSynthesizer", self.synthList)
self.updateSynthesizerList()
deviceListLabelText = _("Audio output &device:")
deviceNames=nvwave.getOutputDeviceNames()
icrosoft Sound Mapper")
self.deviceList = settingsSizerHelper.addLabeledControl(deviceListLabelText, wx.Choice, choices=deviceNames)
self.bindHelpEvent("SelectSynthesizerOutputDevice", self.deviceList)
try:
selection = deviceNames.index(config.conf["speech"]["outputDevice"])
except ValueError:
selection = 0
self.deviceList.SetSelection(selection)
duckingListLabelText = _("Audio d&ucking mode:")
self.duckingList=settingsSizerHelper.addLabeledControl(duckingListLabelText, wx.Choice, choices=audioDucking.audioDuckingModes)
self.bindHelpEvent("SelectSynthesizerDuckingMode", self.duckingList)
index=config.conf['audio']['audioDuckingMode']
self.duckingList.SetSelection(index)
if not audioDucking.isAudioDuckingSupported():
self.duckingList.Disable()
def postInit(self):
self.synthList.SetFocus()
def updateSynthesizerList(self):
driverList=getSynthList()
self.synthNames=[x[0] for x in driverList]
options=[x[1] for x in driverList]
self.synthList.Clear()
self.synthList.AppendItems(options)
try:
index=self.synthNames.index(getSynth().name)
self.synthList.SetSelection(index)
except:
pass
def onOk(self, evt):
if not self.synthNames:
return
config.conf["speech"]["outputDevice"]=self.deviceList.GetStringSelection()
newSynth=self.synthNames[self.synthList.GetSelection()]
if not setSynth(newSynth):
# Translators: This message is presented when
# NVDA is unable to load the selected
# synthesizer.
gui.messageBox(_("Could not load the %s synthesizer.")%newSynth,_("Synthesizer Error"),wx.OK|wx.ICON_WARNING,self)
return
if audioDucking.isAudioDuckingSupported():
index=self.duckingList.GetSelection()
config.conf['audio']['audioDuckingMode']=index
audioDucking.setAudioDuckingMode(index)
# Reinitialize the tones module to update the audio device
import tones
tones.terminate()
tones.initialize()
if self.IsModal():
# Hack: we need to update the synth in our parent window before closing.
# Otherwise, NVDA will report the old synth even though the new synth is reflected visually.
self.Parent.updateCurrentSynth()
super(SynthesizerSelectionDialog, self).onOk(evt)
class DriverSettingChanger(object):
def __init__(self,driver,setting):
self._driverRef=weakref.ref(driver)
self.setting=setting
@property
def driver(self):
return self._driverRef()
def __call__(self,evt):
evt.Skip() # allow other handlers to also process this event.
val=evt.GetSelection()
setattr(self.driver,self.setting.id,val)
class StringDriverSettingChanger(DriverSettingChanger):
def __init__(self,driver,setting,container):
self.container=container
super(StringDriverSettingChanger,self).__init__(driver,setting)
def __call__(self,evt):
evt.Skip() # allow other handlers to also process this event.
# Quick workaround to deal with voice changes.
if self.setting.id == "voice":
# Cancel speech first so that the voice will change immediately instead of the change being queued.
speech.cancelSpeech()
changeVoice(
self.driver,
getattr(self.container,"_%ss"%self.setting.id)[evt.GetSelection()].id
)
self.container.updateDriverSettings(changedSetting=self.setting.id)
else:
setattr(
self.driver,
self.setting.id,
getattr(self.container,"_%ss"%self.setting.id)[evt.GetSelection()].id
)
class AutoSettingsMixin(metaclass=ABCMeta):
def __init__(self, *args, **kwargs):
self.sizerDict = {}
self.lastControl = None
super(AutoSettingsMixin, self).__init__(*args, **kwargs)
# because settings instances can be of type L{Driver} as well, we have to handle
# showing settings for non-instances. Because of this, we must reacquire a reference
# to the settings class whenever we wish to use it (via L{getSettings}) in case the instance changes.
# We also use the weakref to refresh the gui when an instance dies.
self._currentSettingsRef = weakref.ref(
self.getSettings(),
lambda ref: wx.CallAfter(self.refreshGui)
)
settingsSizer: wx.BoxSizer
@abstractmethod
def getSettings(self) -> AutoSettings:
...
@abstractmethod
def makeSettings(self, sizer: wx.BoxSizer):
...
def _getSettingsStorage(self) -> Any:
return self.getSettings()
@property
def hasOptions(self) -> bool:
return bool(self.getSettings().supportedSettings)
@classmethod
def _setSliderStepSizes(cls, slider, setting):
slider.SetLineSize(setting.minStep)
slider.SetPageSize(setting.largeStep)
def _makeSliderSettingControl(
self,
setting: NumericDriverSetting,
settingsStorage: Any
) -> wx.BoxSizer:
labeledControl = guiHelper.LabeledControlHelper(
self,
f"{setting.displayNameWithAccelerator}:",
nvdaControls.EnhancedInputSlider,
minValue=setting.minVal,
maxValue=setting.maxVal
)
lSlider=labeledControl.control
setattr(self, f"{setting.id}Slider", lSlider)
lSlider.Bind(wx.EVT_SLIDER, DriverSettingChanger(
settingsStorage, setting
))
self._setSliderStepSizes(lSlider, setting)
lSlider.SetValue(getattr(settingsStorage, setting.id))
if self.lastControl:
lSlider.MoveAfterInTabOrder(self.lastControl)
self.lastControl=lSlider
return labeledControl.sizer
def _makeStringSettingControl(
self,
setting: DriverSetting,
settingsStorage: Any
):
labelText = f"{setting.displayNameWithAccelerator}:"
stringSettingAttribName = f"_{setting.id}s"
setattr(
self,
stringSettingAttribName,
# Settings are stored as an ordered dict.
# Therefore wrap this inside a list call.
list(getattr(
self.getSettings(),
f"available{setting.id.capitalize()}s"
).values())
)
stringSettings = getattr(self, stringSettingAttribName)
labeledControl = guiHelper.LabeledControlHelper(
self,
labelText,
wx.Choice,
choices=[x.displayName for x in stringSettings]
)
lCombo = labeledControl.control
setattr(self, f"{setting.id}List", lCombo)
self.bindHelpEvent(
f"SpeechSettings{setting.displayName.capitalize()}",
lCombo
)
try:
cur = getattr(settingsStorage, setting.id)
selectionIndex = [
x.id for x in stringSettings
].index(cur)
lCombo.SetSelection(selectionIndex)
except ValueError:
pass
lCombo.Bind(
wx.EVT_CHOICE,
StringDriverSettingChanger(settingsStorage, setting, self)
)
if self.lastControl:
lCombo.MoveAfterInTabOrder(self.lastControl)
self.lastControl = lCombo
return labeledControl.sizer
def _makeBooleanSettingControl(
self,
setting: BooleanDriverSetting,
settingsStorage: Any
):
checkbox = wx.CheckBox(self, label=setting.displayNameWithAccelerator)
setattr(self, f"{setting.id}Checkbox", checkbox)
settingsStorageProxy = weakref.proxy(settingsStorage)
self.bindHelpEvent(f"SpeechSettings{setting.displayName.capitalize()}", checkbox)
def _onCheckChanged(evt: wx.CommandEvent):
evt.Skip() # allow other handlers to also process this event.
setattr(settingsStorageProxy, setting.id, evt.IsChecked())
checkbox.Bind(wx.EVT_CHECKBOX, _onCheckChanged)
checkbox.SetValue(getattr(
settingsStorage,
setting.id
))
if self.lastControl:
checkbox.MoveAfterInTabOrder(self.lastControl)
self.lastControl=checkbox
return checkbox
def updateDriverSettings(self, changedSetting=None):
settingsInst = self.getSettings()
settingsStorage = self._getSettingsStorage()
# firstly check already created options
for name, sizer in self.sizerDict.items():
if name == changedSetting:
# Changing a setting shouldn't cause that setting itself to disappear.
continue
if not settingsInst.isSupported(name):
self.settingsSizer.Hide(sizer)
if gui._isDebug():
log.debug(f"Current sizerDict: {self.sizerDict!r}")
log.debug(f"Current supportedSettings: {self.getSettings().supportedSettings!r}")
for setting in settingsInst.supportedSettings:
if setting.id == changedSetting:
continue
if setting.id in self.sizerDict:
self._updateValueForControl(setting, settingsStorage)
else:
self._createNewControl(setting, settingsStorage)
self.settingsSizer.Layout()
def _createNewControl(self, setting, settingsStorage):
settingMaker = self._getSettingMaker(setting)
try:
s = settingMaker(setting, settingsStorage)
except UnsupportedConfigParameterError:
log.debugWarning(f"Unsupported setting {setting.id}; ignoring", exc_info=True)
else:
self.sizerDict[setting.id] = s
self.settingsSizer.Insert(
len(self.sizerDict) - 1,
s,
border=10,
flag=wx.BOTTOM
)
def _getSettingMaker(self, setting):
if isinstance(setting, NumericDriverSetting):
settingMaker = self._makeSliderSettingControl
elif isinstance(setting, BooleanDriverSetting):
settingMaker = self._makeBooleanSettingControl
else:
settingMaker = self._makeStringSettingControl
return settingMaker
def _updateValueForControl(self, setting, settingsStorage):
self.settingsSizer.Show(self.sizerDict[setting.id])
if isinstance(setting, NumericDriverSetting):
getattr(self, f"{setting.id}Slider").SetValue(
getattr(settingsStorage, setting.id)
)
elif isinstance(setting, BooleanDriverSetting):
getattr(self, f"{setting.id}Checkbox").SetValue(
getattr(settingsStorage, setting.id)
)
else:
options = getattr(self, f"_{setting.id}s")
lCombo = getattr(self, f"{setting.id}List")
try:
cur = getattr(settingsStorage, setting.id)
indexOfItem = [x.id for x in options].index(cur)
lCombo.SetSelection(indexOfItem)
except ValueError:
pass
def onDiscard(self):
settingsInst = self.getSettings()
for setting in settingsInst.supportedSettings:
if isinstance(setting, (NumericDriverSetting, BooleanDriverSetting)):
continue
getattr(self, f"{setting.id}List").Unbind(wx.EVT_CHOICE)
settingsInst.loadSettings()
def onSave(self):
self.getSettings().saveSettings()
def refreshGui(self):
if not self._currentSettingsRef():
if gui._isDebug():
log.debug("refreshing panel")
self.sizerDict.clear()
self.settingsSizer.Clear(delete_windows=True)
self._currentSettingsRef = weakref.ref(
self.getSettings(),
lambda ref: wx.CallAfter(self.refreshGui)
)
self.makeSettings(self.settingsSizer)
def onPanelActivated(self):
self.refreshGui()
super().onPanelActivated()
DriverSettingsMixin = AutoSettingsMixin
class VoiceSettingsPanel(AutoSettingsMixin, SettingsPanel):
title = _("Voice")
helpId = "SpeechSettings"
@property
def driver(self):
synth: SynthDriver = getSynth()
return synth
def getSettings(self) -> AutoSettings:
return self.driver
def makeSettings(self, settingsSizer):
self.updateDriverSettings()
settingsSizerHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
autoLanguageSwitchingText = _("Automatic language switching (when supported)")
self.autoLanguageSwitchingCheckbox = settingsSizerHelper.addItem(
wx.CheckBox(
self,
label=autoLanguageSwitchingText
))
self.bindHelpEvent("SpeechSettingsLanguageSwitching", self.autoLanguageSwitchingCheckbox)
self.autoLanguageSwitchingCheckbox.SetValue(
config.conf["speech"]["autoLanguageSwitching"]
)
autoDialectSwitchingText = _("Automatic dialect switching (when supported)")
self.autoDialectSwitchingCheckbox = settingsSizerHelper.addItem(
wx.CheckBox(self, label=autoDialectSwitchingText)
)
self.bindHelpEvent("SpeechSettingsDialectSwitching", self.autoDialectSwitchingCheckbox)
self.autoDialectSwitchingCheckbox.SetValue(
config.conf["speech"]["autoDialectSwitching"]
)
punctuationLabelText = _("Punctuation/symbol &level:")
symbolLevelLabels = characterProcessing.SPEECH_SYMBOL_LEVEL_LABELS
symbolLevelChoices = [
symbolLevelLabels[level] for level in characterProcessing.CONFIGURABLE_SPEECH_SYMBOL_LEVELS
]
self.symbolLevelList = settingsSizerHelper.addLabeledControl(
punctuationLabelText, wx.Choice, choices=symbolLevelChoices
)
self.bindHelpEvent("SpeechSettingsSymbolLevel", self.symbolLevelList)
curLevel = config.conf["speech"]["symbolLevel"]
self.symbolLevelList.SetSelection(
characterProcessing.CONFIGURABLE_SPEECH_SYMBOL_LEVELS.index(curLevel)
)
trustVoiceLanguageText = _("Trust voice's language when processing characters and symbols")
self.trustVoiceLanguageCheckbox = settingsSizerHelper.addItem(
wx.CheckBox(self, label=trustVoiceLanguageText)
)
self.bindHelpEvent("SpeechSettingsTrust", self.trustVoiceLanguageCheckbox)
self.trustVoiceLanguageCheckbox.SetValue(config.conf["speech"]["trustVoiceLanguage"])
includeCLDRText = _(
# Translators: This is the label for a checkbox in the
# voice settings panel (if checked, data from the unicode CLDR will be used
# to speak emoji descriptions).
"Include Unicode Consortium data (including emoji) when processing characters and symbols"
)
self.includeCLDRCheckbox = settingsSizerHelper.addItem(
wx.CheckBox(self, label=includeCLDRText)
)
self.includeCLDRCheckbox.SetValue(config.conf["speech"]["includeCLDR"])
minPitchChange = int(config.conf.getConfigValidation(
("speech", self.driver.name, "capPitchChange")
).kwargs["min"])
maxPitchChange = int(config.conf.getConfigValidation(
("speech", self.driver.name, "capPitchChange")
).kwargs["max"])
# Translators: This is a label for a setting in voice settings (an edit box to change
# voice pitch for capital letters; the higher the value, the pitch will be higher).
capPitchChangeLabelText = _("Capital pitch change percentage")
self.capPitchChangeEdit = settingsSizerHelper.addLabeledControl(
capPitchChangeLabelText,
nvdaControls.SelectOnFocusSpinCtrl,
min=minPitchChange,
max=maxPitchChange,
initial=config.conf["speech"][self.driver.name]["capPitchChange"])
self.bindHelpEvent(
"SpeechSettingsCapPitchChange",
self.capPitchChangeEdit
)
# Translators: This is the label for a checkbox in the
# voice settings panel.
sayCapForCapsText = _("Say &cap before capitals")
self.sayCapForCapsCheckBox = settingsSizerHelper.addItem(
wx.CheckBox(self, label=sayCapForCapsText)
)
self.bindHelpEvent("SpeechSettingsSayCapBefore", self.sayCapForCapsCheckBox)
self.sayCapForCapsCheckBox.SetValue(
config.conf["speech"][self.driver.name]["sayCapForCapitals"]
)
# Translators: This is the label for a checkbox in the
# voice settings panel.
beepForCapsText =_("&Beep for capitals")
self.beepForCapsCheckBox = settingsSizerHelper.addItem(
wx.CheckBox(self, label=beepForCapsText)
)
self.bindHelpEvent(
"SpeechSettingsBeepForCaps",
self.beepForCapsCheckBox
)
self.beepForCapsCheckBox.SetValue(
config.conf["speech"][self.driver.name]["beepForCapitals"]
)
# Translators: This is the label for a checkbox in the
# voice settings panel.
useSpellingFunctionalityText = _("Use &spelling functionality if supported")
self.useSpellingFunctionalityCheckBox = settingsSizerHelper.addItem(
wx.CheckBox(self, label=useSpellingFunctionalityText)
)
self.bindHelpEvent("SpeechSettingsUseSpelling", self.useSpellingFunctionalityCheckBox)
self.useSpellingFunctionalityCheckBox.SetValue(
config.conf["speech"][self.driver.name]["useSpellingFunctionality"]
)
def onSave(self):
AutoSettingsMixin.onSave(self)
config.conf["speech"]["autoLanguageSwitching"] = self.autoLanguageSwitchingCheckbox.IsChecked()
config.conf["speech"]["autoDialectSwitching"] = self.autoDialectSwitchingCheckbox.IsChecked()
config.conf["speech"]["symbolLevel"]=characterProcessing.CONFIGURABLE_SPEECH_SYMBOL_LEVELS[self.symbolLevelList.GetSelection()]
config.conf["speech"]["trustVoiceLanguage"]=self.trustVoiceLanguageCheckbox.IsChecked()
currentIncludeCLDR = config.conf["speech"]["includeCLDR"]
config.conf["speech"]["includeCLDR"] = newIncludeCldr = self.includeCLDRCheckbox.IsChecked()
if currentIncludeCLDR is not newIncludeCldr:
# Either included or excluded CLDR data, so clear the cache.
characterProcessing.clearSpeechSymbols()
config.conf["speech"][self.driver.name]["capPitchChange"]=self.capPitchChangeEdit.Value
config.conf["speech"][self.driver.name]["sayCapForCapitals"]=self.sayCapForCapsCheckBox.IsChecked()
config.conf["speech"][self.driver.name]["beepForCapitals"]=self.beepForCapsCheckBox.IsChecked()
config.conf["speech"][self.driver.name]["useSpellingFunctionality"]=self.useSpellingFunctionalityCheckBox.IsChecked()
class KeyboardSettingsPanel(SettingsPanel):
# Translators: This is the label for the keyboard settings panel.
title = _("Keyboard")
helpId = "KeyboardSettings"
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: This is the label for a combobox in the
# keyboard settings panel.
kbdLabelText = _("&Keyboard layout:")
layouts=keyboardHandler.KeyboardInputGesture.LAYOUTS
self.kbdNames=sorted(layouts)
kbdChoices = [layouts[layout] for layout in self.kbdNames]
self.kbdList=sHelper.addLabeledControl(kbdLabelText, wx.Choice, choices=kbdChoices)
self.bindHelpEvent("KeyboardSettingsLayout", self.kbdList)
try:
index=self.kbdNames.index(config.conf['keyboard']['keyboardLayout'])
self.kbdList.SetSelection(index)
except:
log.debugWarning("Could not set Keyboard layout list to current layout",exc_info=True)
#Translators: This is the label for a list of checkboxes
# controlling which keys are NVDA modifier keys.
modifierBoxLabel = _("&Select NVDA Modifier Keys")
self.modifierChoices = [keyLabels.localizedKeyLabels[key] for key in keyboardHandler.SUPPORTED_NVDA_MODIFIER_KEYS]
self.modifierList=sHelper.addLabeledControl(modifierBoxLabel, nvdaControls.CustomCheckListBox, choices=self.modifierChoices)
checkedItems = []
if config.conf["keyboard"]["useNumpadInsertAsNVDAModifierKey"]:
checkedItems.append(keyboardHandler.SUPPORTED_NVDA_MODIFIER_KEYS.index("numpadinsert"))
if config.conf["keyboard"]["useExtendedInsertAsNVDAModifierKey"]:
checkedItems.append(keyboardHandler.SUPPORTED_NVDA_MODIFIER_KEYS.index("insert"))
if config.conf["keyboard"]["useCapsLockAsNVDAModifierKey"]:
checkedItems.append(keyboardHandler.SUPPORTED_NVDA_MODIFIER_KEYS.index("capslock"))
self.modifierList.CheckedItems = checkedItems
self.modifierList.Select(0)
self.bindHelpEvent("KeyboardSettingsModifiers", self.modifierList)
# Translators: This is the label for a checkbox in the
# keyboard settings panel.
charsText = _("Speak typed &characters")
self.charsCheckBox=sHelper.addItem(wx.CheckBox(self,label=charsText))
self.bindHelpEvent(
"KeyboardSettingsSpeakTypedCharacters",
self.charsCheckBox
)
self.charsCheckBox.SetValue(config.conf["keyboard"]["speakTypedCharacters"])
# Translators: This is the label for a checkbox in the
# keyboard settings panel.
speakTypedWordsText = _("Speak typed &words")
self.wordsCheckBox=sHelper.addItem(wx.CheckBox(self,label=speakTypedWordsText))
self.bindHelpEvent("KeyboardSettingsSpeakTypedWords", self.wordsCheckBox)
self.wordsCheckBox.SetValue(config.conf["keyboard"]["speakTypedWords"])
# Translators: This is the label for a checkbox in the
# keyboard settings panel.
speechInterruptForCharText = _("Speech &interrupt for typed characters")
self.speechInterruptForCharsCheckBox=sHelper.addItem(wx.CheckBox(self,label=speechInterruptForCharText))
self.bindHelpEvent("KeyboardSettingsSpeechInteruptForCharacters", self.speechInterruptForCharsCheckBox)
self.speechInterruptForCharsCheckBox.SetValue(config.conf["keyboard"]["speechInterruptForCharacters"])
# Translators: This is the label for a checkbox in the
# keyboard settings panel.
speechInterruptForEnterText = _("Speech i&nterrupt for Enter key")
self.speechInterruptForEnterCheckBox=sHelper.addItem(wx.CheckBox(self,label=speechInterruptForEnterText))
self.speechInterruptForEnterCheckBox.SetValue(config.conf["keyboard"]["speechInterruptForEnter"])
self.bindHelpEvent("KeyboardSettingsSpeechInteruptForEnter", self.speechInterruptForEnterCheckBox)
# Translators: This is the label for a checkbox in the
# keyboard settings panel.
allowSkimReadingInSayAllText = _("Allow skim &reading in Say All")
self.skimReadingInSayAllCheckBox=sHelper.addItem(wx.CheckBox(self,label=allowSkimReadingInSayAllText))
self.bindHelpEvent("KeyboardSettingsSkimReading", self.skimReadingInSayAllCheckBox)
self.skimReadingInSayAllCheckBox.SetValue(config.conf["keyboard"]["allowSkimReadingInSayAll"])
# Translators: This is the label for a checkbox in the
# keyboard settings panel.
beepForLowercaseWithCapsLockText = _("&Beep if typing lowercase letters when caps lock is on")
self.beepLowercaseCheckBox=sHelper.addItem(wx.CheckBox(self,label=beepForLowercaseWithCapsLockText))
self.bindHelpEvent("SpeechSettingsBeepLowercase", self.beepLowercaseCheckBox)
self.beepLowercaseCheckBox.SetValue(config.conf["keyboard"]["beepForLowercaseWithCapslock"])
# Translators: This is the label for a checkbox in the
# keyboard settings panel.
commandKeysText = _("Speak c&ommand keys")
self.commandKeysCheckBox=sHelper.addItem(wx.CheckBox(self,label=commandKeysText))
self.bindHelpEvent("SpeechSettingsSpeakCommandKeys", self.commandKeysCheckBox)
self.commandKeysCheckBox.SetValue(config.conf["keyboard"]["speakCommandKeys"])
# Translators: This is the label for a checkbox in the
# keyboard settings panel.
alertForSpellingErrorsText = _("Play sound for &spelling errors while typing")
self.alertForSpellingErrorsCheckBox=sHelper.addItem(wx.CheckBox(self,label=alertForSpellingErrorsText))
self.bindHelpEvent("KeyboardSettingsAlertForSpellingErrors", self.alertForSpellingErrorsCheckBox)
self.alertForSpellingErrorsCheckBox.SetValue(config.conf["keyboard"]["alertForSpellingErrors"])
if not config.conf["documentFormatting"]["reportSpellingErrors"]:
self.alertForSpellingErrorsCheckBox.Disable()
# Translators: This is the label for a checkbox in the
# keyboard settings panel.
handleInjectedKeysText = _("Handle keys from other &applications")
self.handleInjectedKeysCheckBox=sHelper.addItem(wx.CheckBox(self,label=handleInjectedKeysText))
self.bindHelpEvent("KeyboardSettingsHandleKeys", self.handleInjectedKeysCheckBox)
self.handleInjectedKeysCheckBox.SetValue(config.conf["keyboard"]["handleInjectedKeys"])
def isValid(self):
# #2871: check whether at least one key is the nvda key.
if not self.modifierList.CheckedItems:
log.debugWarning("No NVDA key set")
gui.messageBox(
# Translators: Message to report wrong configuration of the NVDA key
_("At least one key must be used as the NVDA key."),
# Translators: The title of the message box
_("Error"), wx.OK|wx.ICON_ERROR,self)
return False
return super(KeyboardSettingsPanel, self).isValid()
def onSave(self):
layout=self.kbdNames[self.kbdList.GetSelection()]
config.conf['keyboard']['keyboardLayout']=layout
config.conf["keyboard"]["useNumpadInsertAsNVDAModifierKey"]= self.modifierList.IsChecked(keyboardHandler.SUPPORTED_NVDA_MODIFIER_KEYS.index("numpadinsert"))
config.conf["keyboard"]["useExtendedInsertAsNVDAModifierKey"] = self.modifierList.IsChecked(keyboardHandler.SUPPORTED_NVDA_MODIFIER_KEYS.index("insert"))
config.conf["keyboard"]["useCapsLockAsNVDAModifierKey"] = self.modifierList.IsChecked(keyboardHandler.SUPPORTED_NVDA_MODIFIER_KEYS.index("capslock"))
config.conf["keyboard"]["speakTypedCharacters"]=self.charsCheckBox.IsChecked()
config.conf["keyboard"]["speakTypedWords"]=self.wordsCheckBox.IsChecked()
config.conf["keyboard"]["speechInterruptForCharacters"]=self.speechInterruptForCharsCheckBox.IsChecked()
config.conf["keyboard"]["speechInterruptForEnter"]=self.speechInterruptForEnterCheckBox.IsChecked()
config.conf["keyboard"]["allowSkimReadingInSayAll"]=self.skimReadingInSayAllCheckBox.IsChecked()
config.conf["keyboard"]["beepForLowercaseWithCapslock"]=self.beepLowercaseCheckBox.IsChecked()
config.conf["keyboard"]["speakCommandKeys"]=self.commandKeysCheckBox.IsChecked()
config.conf["keyboard"]["alertForSpellingErrors"]=self.alertForSpellingErrorsCheckBox.IsChecked()
config.conf["keyboard"]["handleInjectedKeys"]=self.handleInjectedKeysCheckBox.IsChecked()
class MouseSettingsPanel(SettingsPanel):
# Translators: This is the label for the mouse settings panel.
title = _("Mouse")
helpId = "MouseSettings"
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: This is the label for a checkbox in the
# mouse settings panel.
shapeChangesText = _("Report mouse &shape changes")
self.shapeCheckBox=sHelper.addItem(wx.CheckBox(self,label=shapeChangesText))
self.bindHelpEvent("MouseSettingsShape", self.shapeCheckBox)
self.shapeCheckBox.SetValue(config.conf["mouse"]["reportMouseShapeChanges"])
# Translators: This is the label for a checkbox in the
# mouse settings panel.
mouseTrackingText=_("Enable mouse &tracking")
self.mouseTrackingCheckBox=sHelper.addItem(wx.CheckBox(self,label=mouseTrackingText))
self.bindHelpEvent("MouseSettingsTracking", self.mouseTrackingCheckBox)
self.mouseTrackingCheckBox.SetValue(config.conf["mouse"]["enableMouseTracking"])
# Translators: This is the label for a combobox in the
# mouse settings panel.
textUnitLabelText=_("Text &unit resolution:")
import textInfos
self.textUnits=textInfos.MOUSE_TEXT_RESOLUTION_UNITS
textUnitsChoices = [textInfos.unitLabels[x] for x in self.textUnits]
self.textUnitComboBox=sHelper.addLabeledControl(textUnitLabelText, wx.Choice, choices=textUnitsChoices)
self.bindHelpEvent("MouseSettingsTextUnit", self.textUnitComboBox)
try:
index=self.textUnits.index(config.conf["mouse"]["mouseTextUnit"])
except:
index=0
self.textUnitComboBox.SetSelection(index)
# Translators: This is the label for a checkbox in the
# mouse settings panel.
reportObjectRoleText = _("Report &role when mouse enters object")
self.reportObjectRoleCheckBox=sHelper.addItem(wx.CheckBox(self,label=reportObjectRoleText))
self.bindHelpEvent("MouseSettingsRole", self.reportObjectRoleCheckBox)
self.reportObjectRoleCheckBox.SetValue(config.conf["mouse"]["reportObjectRoleOnMouseEnter"])
# Translators: This is the label for a checkbox in the
# mouse settings panel.
audioText = _("&Play audio coordinates when mouse moves")
self.audioCheckBox=sHelper.addItem(wx.CheckBox(self,label=audioText))
self.bindHelpEvent("MouseSettingsAudio", self.audioCheckBox)
self.audioCheckBox.SetValue(config.conf["mouse"]["audioCoordinatesOnMouseMove"])
# Translators: This is the label for a checkbox in the
# mouse settings panel.
audioDetectBrightnessText = _("&Brightness controls audio coordinates volume")
self.audioDetectBrightnessCheckBox=sHelper.addItem(wx.CheckBox(self,label=audioDetectBrightnessText))
self.bindHelpEvent("MouseSettingsBrightness", self.audioDetectBrightnessCheckBox)
self.audioDetectBrightnessCheckBox.SetValue(config.conf["mouse"]["audioCoordinates_detectBrightness"])
# Translators: This is the label for a checkbox in the
# mouse settings panel.
ignoreInjectedMouseInputText = _("Ignore mouse input from other &applications")
self.ignoreInjectedMouseInputCheckBox=sHelper.addItem(wx.CheckBox(self,label=ignoreInjectedMouseInputText))
self.ignoreInjectedMouseInputCheckBox.SetValue(config.conf["mouse"]["ignoreInjectedMouseInput"])
def onSave(self):
config.conf["mouse"]["reportMouseShapeChanges"]=self.shapeCheckBox.IsChecked()
config.conf["mouse"]["enableMouseTracking"]=self.mouseTrackingCheckBox.IsChecked()
config.conf["mouse"]["mouseTextUnit"]=self.textUnits[self.textUnitComboBox.GetSelection()]
config.conf["mouse"]["reportObjectRoleOnMouseEnter"]=self.reportObjectRoleCheckBox.IsChecked()
config.conf["mouse"]["audioCoordinatesOnMouseMove"]=self.audioCheckBox.IsChecked()
config.conf["mouse"]["audioCoordinates_detectBrightness"]=self.audioDetectBrightnessCheckBox.IsChecked()
config.conf["mouse"]["ignoreInjectedMouseInput"]=self.ignoreInjectedMouseInputCheckBox.IsChecked()
class ReviewCursorPanel(SettingsPanel):
# Translators: This is the label for the review cursor settings panel.
title = _("Review Cursor")
helpId = "ReviewCursorSettings"
def makeSettings(self, settingsSizer):
# Translators: This is the label for a checkbox in the
# review cursor settings panel.
self.followFocusCheckBox = wx.CheckBox(self, label=_("Follow system &focus"))
self.bindHelpEvent("ReviewCursorFollowFocus", self.followFocusCheckBox)
self.followFocusCheckBox.SetValue(config.conf["reviewCursor"]["followFocus"])
settingsSizer.Add(self.followFocusCheckBox,border=10,flag=wx.BOTTOM)
# Translators: This is the label for a checkbox in the
# review cursor settings panel.
self.followCaretCheckBox = wx.CheckBox(self, label=_("Follow System &Caret"))
self.bindHelpEvent("ReviewCursorFollowCaret", self.followCaretCheckBox)
self.followCaretCheckBox.SetValue(config.conf["reviewCursor"]["followCaret"])
settingsSizer.Add(self.followCaretCheckBox,border=10,flag=wx.BOTTOM)
# Translators: This is the label for a checkbox in the
# review cursor settings panel.
self.followMouseCheckBox = wx.CheckBox(self, label=_("Follow &mouse cursor"))
self.bindHelpEvent("ReviewCursorFollowMouse", self.followMouseCheckBox)
self.followMouseCheckBox.SetValue(config.conf["reviewCursor"]["followMouse"])
settingsSizer.Add(self.followMouseCheckBox,border=10,flag=wx.BOTTOM)
# Translators: This is the label for a checkbox in the
# review cursor settings panel.
self.simpleReviewModeCheckBox = wx.CheckBox(self, label=_("&Simple review mode"))
self.bindHelpEvent("ReviewCursorSimple", self.simpleReviewModeCheckBox)
self.simpleReviewModeCheckBox.SetValue(config.conf["reviewCursor"]["simpleReviewMode"])
settingsSizer.Add(self.simpleReviewModeCheckBox,border=10,flag=wx.BOTTOM)
def onSave(self):
config.conf["reviewCursor"]["followFocus"]=self.followFocusCheckBox.IsChecked()
config.conf["reviewCursor"]["followCaret"]=self.followCaretCheckBox.IsChecked()
config.conf["reviewCursor"]["followMouse"]=self.followMouseCheckBox.IsChecked()
config.conf["reviewCursor"]["simpleReviewMode"]=self.simpleReviewModeCheckBox.IsChecked()
class InputCompositionPanel(SettingsPanel):
# Translators: This is the label for the Input Composition settings panel.
title = _("Input Composition")
helpId = "InputCompositionSettings"
def makeSettings(self, settingsSizer):
# Translators: This is the label for a checkbox in the
# Input composition settings panel.
self.autoReportAllCandidatesCheckBox=wx.CheckBox(self,wx.ID_ANY,label=_("Automatically report all available &candidates"))
self.bindHelpEvent("InputCompositionReportAllCandidates", self.autoReportAllCandidatesCheckBox)
self.autoReportAllCandidatesCheckBox.SetValue(config.conf["inputComposition"]["autoReportAllCandidates"])
settingsSizer.Add(self.autoReportAllCandidatesCheckBox,border=10,flag=wx.BOTTOM)
# Translators: This is the label for a checkbox in the
# Input composition settings panel.
self.announceSelectedCandidateCheckBox=wx.CheckBox(self,wx.ID_ANY,label=_("Announce &selected candidate"))
self.bindHelpEvent("InputCompositionAnnounceSelectedCandidate", self.announceSelectedCandidateCheckBox)
self.announceSelectedCandidateCheckBox.SetValue(config.conf["inputComposition"]["announceSelectedCandidate"])
settingsSizer.Add(self.announceSelectedCandidateCheckBox,border=10,flag=wx.BOTTOM)
# Translators: This is the label for a checkbox in the
# Input composition settings panel.
self.candidateIncludesShortCharacterDescriptionCheckBox=wx.CheckBox(self,wx.ID_ANY,label=_("Always include short character &description when announcing candidates"))
self.bindHelpEvent(
"InputCompositionCandidateIncludesShortCharacterDescription",
self.candidateIncludesShortCharacterDescriptionCheckBox
)
self.candidateIncludesShortCharacterDescriptionCheckBox.SetValue(config.conf["inputComposition"]["alwaysIncludeShortCharacterDescriptionInCandidateName"])
settingsSizer.Add(self.candidateIncludesShortCharacterDescriptionCheckBox,border=10,flag=wx.BOTTOM)
# Translators: This is the label for a checkbox in the
# Input composition settings panel.
self.reportReadingStringChangesCheckBox=wx.CheckBox(self,wx.ID_ANY,label=_("Report changes to the &reading string"))
self.bindHelpEvent(
"InputCompositionReadingStringChanges",
self.reportReadingStringChangesCheckBox
)
self.reportReadingStringChangesCheckBox.SetValue(config.conf["inputComposition"]["reportReadingStringChanges"])
settingsSizer.Add(self.reportReadingStringChangesCheckBox,border=10,flag=wx.BOTTOM)
# Translators: This is the label for a checkbox in the
# Input composition settings panel.
self.reportCompositionStringChangesCheckBox=wx.CheckBox(self,wx.ID_ANY,label=_("Report changes to the &composition string"))
self.bindHelpEvent(
"InputCompositionCompositionStringChanges",
self.reportCompositionStringChangesCheckBox
)
self.reportCompositionStringChangesCheckBox.SetValue(config.conf["inputComposition"]["reportCompositionStringChanges"])
settingsSizer.Add(self.reportCompositionStringChangesCheckBox,border=10,flag=wx.BOTTOM)
def onSave(self):
config.conf["inputComposition"]["autoReportAllCandidates"]=self.autoReportAllCandidatesCheckBox.IsChecked()
config.conf["inputComposition"]["announceSelectedCandidate"]=self.announceSelectedCandidateCheckBox.IsChecked()
config.conf["inputComposition"]["alwaysIncludeShortCharacterDescriptionInCandidateName"]=self.candidateIncludesShortCharacterDescriptionCheckBox.IsChecked()
config.conf["inputComposition"]["reportReadingStringChanges"]=self.reportReadingStringChangesCheckBox.IsChecked()
config.conf["inputComposition"]["reportCompositionStringChanges"]=self.reportCompositionStringChangesCheckBox.IsChecked()
class ObjectPresentationPanel(SettingsPanel):
# Translators: This is the label for the object presentation panel.
title = _("Object Presentation")
helpId = "ObjectPresentationSettings"
progressLabels = (
# Translators: An option for progress bar output in the Object Presentation dialog
# which disables reporting of progress bars.
# See Progress bar output in the Object Presentation Settings section of the User Guide.
("off", _("off")),
# Translators: An option for progress bar output in the Object Presentation dialog
# which reports progress bar updates by speaking.
# See Progress bar output in the Object Presentation Settings section of the User Guide.
("speak", _("Speak")),
# Translators: An option for progress bar output in the Object Presentation dialog
# which reports progress bar updates by beeping.
# See Progress bar output in the Object Presentation Settings section of the User Guide.
("beep", _("Beep")),
# Translators: An option for progress bar output in the Object Presentation dialog
# which reports progress bar updates by both speaking and beeping.
# See Progress bar output in the Object Presentation Settings section of the User Guide.
("both", _("Speak and beep")),
)
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: This is the label for a checkbox in the
# object presentation settings panel.
reportToolTipsText = _("Report &tooltips")
self.tooltipCheckBox=sHelper.addItem(wx.CheckBox(self,label=reportToolTipsText))
self.bindHelpEvent("ObjectPresentationReportToolTips", self.tooltipCheckBox)
self.tooltipCheckBox.SetValue(config.conf["presentation"]["reportTooltips"])
# Translators: This is the label for a checkbox in the
# object presentation settings panel.
balloonText = _("Report ¬ifications")
self.balloonCheckBox=sHelper.addItem(wx.CheckBox(self,label=balloonText))
self.bindHelpEvent("ObjectPresentationReportBalloons", self.balloonCheckBox)
self.balloonCheckBox.SetValue(config.conf["presentation"]["reportHelpBalloons"])
# Translators: This is the label for a checkbox in the
# object presentation settings panel.
shortcutText = _("Report object shortcut &keys")
self.shortcutCheckBox=sHelper.addItem(wx.CheckBox(self,label=shortcutText))
self.bindHelpEvent("ObjectPresentationShortcutKeys", self.shortcutCheckBox)
self.shortcutCheckBox.SetValue(config.conf["presentation"]["reportKeyboardShortcuts"])
# Translators: This is the label for a checkbox in the
# object presentation settings panel.
positionInfoText = _("Report object &position information")
self.positionInfoCheckBox=sHelper.addItem(wx.CheckBox(self,label=positionInfoText))
self.bindHelpEvent("ObjectPresentationPositionInfo", self.positionInfoCheckBox)
self.positionInfoCheckBox.SetValue(config.conf["presentation"]["reportObjectPositionInformation"])
# Translators: This is the label for a checkbox in the
# object presentation settings panel.
guessPositionInfoText = _("&Guess object position information when unavailable")
self.guessPositionInfoCheckBox=sHelper.addItem(wx.CheckBox(self,label=guessPositionInfoText))
self.bindHelpEvent("ObjectPresentationGuessPositionInfo", self.guessPositionInfoCheckBox)
self.guessPositionInfoCheckBox.SetValue(config.conf["presentation"]["guessObjectPositionInformationWhenUnavailable"])
# Translators: This is the label for a checkbox in the
# object presentation settings panel.
descriptionText = _("Report object &descriptions")
self.descriptionCheckBox=sHelper.addItem(wx.CheckBox(self,label=descriptionText))
self.bindHelpEvent("ObjectPresentationReportDescriptions", self.descriptionCheckBox)
self.descriptionCheckBox.SetValue(config.conf["presentation"]["reportObjectDescriptions"])
# Translators: This is the label for a combobox in the
# object presentation settings panel.
progressLabelText = _("Progress &bar output:")
progressChoices = [name for setting, name in self.progressLabels]
self.progressList=sHelper.addLabeledControl(progressLabelText, wx.Choice, choices=progressChoices)
self.bindHelpEvent("ObjectPresentationProgressBarOutput", self.progressList)
for index, (setting, name) in enumerate(self.progressLabels):
if setting == config.conf["presentation"]["progressBarUpdates"]["progressBarOutputMode"]:
self.progressList.SetSelection(index)
break
else:
log.debugWarning("Could not set progress list to current report progress bar updates setting")
# Translators: This is the label for a checkbox in the
# object presentation settings panel.
reportBackgroundProgressBarsText = _("Report backg&round progress bars")
self.reportBackgroundProgressBarsCheckBox=sHelper.addItem(wx.CheckBox(self,label=reportBackgroundProgressBarsText))
self.bindHelpEvent(
"ObjectPresentationReportBackgroundProgressBars",
self.reportBackgroundProgressBarsCheckBox
)
self.reportBackgroundProgressBarsCheckBox.SetValue(config.conf["presentation"]["progressBarUpdates"]["reportBackgroundProgressBars"])
# Translators: This is the label for a checkbox in the
# object presentation settings panel.
dynamicContentText = _("Report dynamic &content changes")
self.dynamicContentCheckBox=sHelper.addItem(wx.CheckBox(self,label=dynamicContentText))
self.bindHelpEvent(
"ObjectPresentationReportDynamicContent",
self.dynamicContentCheckBox
)
self.dynamicContentCheckBox.SetValue(config.conf["presentation"]["reportDynamicContentChanges"])
# Translators: This is the label for a checkbox in the
# object presentation settings panel.
autoSuggestionsLabelText = _("Play a sound when &auto-suggestions appear")
self.autoSuggestionSoundsCheckBox=sHelper.addItem(wx.CheckBox(self,label=autoSuggestionsLabelText))
self.bindHelpEvent(
"ObjectPresentationSuggestionSounds",
self.autoSuggestionSoundsCheckBox
)
self.autoSuggestionSoundsCheckBox.SetValue(config.conf["presentation"]["reportAutoSuggestionsWithSound"])
def onSave(self):
config.conf["presentation"]["reportTooltips"]=self.tooltipCheckBox.IsChecked()
config.conf["presentation"]["reportHelpBalloons"]=self.balloonCheckBox.IsChecked()
config.conf["presentation"]["reportKeyboardShortcuts"]=self.shortcutCheckBox.IsChecked()
config.conf["presentation"]["reportObjectPositionInformation"]=self.positionInfoCheckBox.IsChecked()
config.conf["presentation"]["guessObjectPositionInformationWhenUnavailable"]=self.guessPositionInfoCheckBox.IsChecked()
config.conf["presentation"]["reportObjectDescriptions"]=self.descriptionCheckBox.IsChecked()
config.conf["presentation"]["progressBarUpdates"]["progressBarOutputMode"]=self.progressLabels[self.progressList.GetSelection()][0]
config.conf["presentation"]["progressBarUpdates"]["reportBackgroundProgressBars"]=self.reportBackgroundProgressBarsCheckBox.IsChecked()
config.conf["presentation"]["reportDynamicContentChanges"]=self.dynamicContentCheckBox.IsChecked()
config.conf["presentation"]["reportAutoSuggestionsWithSound"]=self.autoSuggestionSoundsCheckBox.IsChecked()
class BrowseModePanel(SettingsPanel):
# Translators: This is the label for the browse mode settings panel.
title = _("Browse Mode")
helpId = "BrowseModeSettings"
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: This is the label for a textfield in the
# browse mode settings panel.
maxLengthLabelText = _("&Maximum number of characters on one line")
self.maxLengthEdit = sHelper.addLabeledControl(maxLengthLabelText, nvdaControls.SelectOnFocusSpinCtrl,
# min and max are not enforced in the config for virtualBuffers.maxLineLength
min=10, max=250,
initial=config.conf["virtualBuffers"]["maxLineLength"])
self.bindHelpEvent("BrowseModeSettingsMaxLength", self.maxLengthEdit)
# Translators: This is the label for a textfield in the
# browse mode settings panel.
pageLinesLabelText = _("&Number of lines per page")
self.pageLinesEdit = sHelper.addLabeledControl(pageLinesLabelText, nvdaControls.SelectOnFocusSpinCtrl,
# min and max are not enforced in the config for virtualBuffers.linesPerPage
min=5, max=150,
initial=config.conf["virtualBuffers"]["linesPerPage"])
self.bindHelpEvent("BrowseModeSettingsPageLines", self.pageLinesEdit)
# Translators: This is the label for a checkbox in the
# browse mode settings panel.
useScreenLayoutText = _("Use &screen layout (when supported)")
self.useScreenLayoutCheckBox = sHelper.addItem(wx.CheckBox(self, label=useScreenLayoutText))
self.bindHelpEvent("BrowseModeSettingsScreenLayout", self.useScreenLayoutCheckBox)
self.useScreenLayoutCheckBox.SetValue(config.conf["virtualBuffers"]["useScreenLayout"])
# Translators: The label for a checkbox in browse mode settings to
# enable browse mode on page load.
enableOnPageLoadText = _("&Enable browse mode on page load")
self.enableOnPageLoadCheckBox = sHelper.addItem(wx.CheckBox(self, label=enableOnPageLoadText))
self.enableOnPageLoadCheckBox.SetValue(config.conf["virtualBuffers"]["enableOnPageLoad"])
# Translators: This is the label for a checkbox in the
# browse mode settings panel.
autoSayAllText = _("Automatic &Say All on page load")
self.autoSayAllCheckBox = sHelper.addItem(wx.CheckBox(self, label=autoSayAllText))
self.bindHelpEvent("BrowseModeSettingsAutoSayAll", self.autoSayAllCheckBox)
self.autoSayAllCheckBox.SetValue(config.conf["virtualBuffers"]["autoSayAllOnPageLoad"])
# Translators: This is the label for a checkbox in the
# browse mode settings panel.
layoutTablesText = _("Include l&ayout tables")
self.layoutTablesCheckBox = sHelper.addItem(wx.CheckBox(self, label =layoutTablesText))
self.bindHelpEvent("BrowseModeSettingsIncludeLayoutTables", self.layoutTablesCheckBox)
self.layoutTablesCheckBox.SetValue(config.conf["documentFormatting"]["includeLayoutTables"])
# Translators: This is the label for a checkbox in the
# browse mode settings panel.
autoPassThroughOnFocusChangeText = _("Automatic focus mode for focus changes")
self.autoPassThroughOnFocusChangeCheckBox = sHelper.addItem(wx.CheckBox(self, label=autoPassThroughOnFocusChangeText))
self.bindHelpEvent(
"BrowseModeSettingsAutoPassThroughOnFocusChange",
self.autoPassThroughOnFocusChangeCheckBox
)
self.autoPassThroughOnFocusChangeCheckBox.SetValue(config.conf["virtualBuffers"]["autoPassThroughOnFocusChange"])
# Translators: This is the label for a checkbox in the
# browse mode settings panel.
autoPassThroughOnCaretMoveText = _("Automatic focus mode for caret movement")
self.autoPassThroughOnCaretMoveCheckBox = sHelper.addItem(wx.CheckBox(self, label=autoPassThroughOnCaretMoveText))
self.bindHelpEvent(
"BrowseModeSettingsAutoPassThroughOnCaretMove",
self.autoPassThroughOnCaretMoveCheckBox
)
self.autoPassThroughOnCaretMoveCheckBox.SetValue(config.conf["virtualBuffers"]["autoPassThroughOnCaretMove"])
# Translators: This is the label for a checkbox in the
# browse mode settings panel.
passThroughAudioIndicationText = _("Audio indication of focus and browse modes")
self.passThroughAudioIndicationCheckBox = sHelper.addItem(wx.CheckBox(self, label=passThroughAudioIndicationText))
self.bindHelpEvent(
"BrowseModeSettingsPassThroughAudioIndication",
self.passThroughAudioIndicationCheckBox
)
self.passThroughAudioIndicationCheckBox.SetValue(config.conf["virtualBuffers"]["passThroughAudioIndication"])
# Translators: This is the label for a checkbox in the
# browse mode settings panel.
trapNonCommandGesturesText = _("&Trap all non-command gestures from reaching the document")
self.trapNonCommandGesturesCheckBox = sHelper.addItem(wx.CheckBox(self, label=trapNonCommandGesturesText))
self.bindHelpEvent(
"BrowseModeSettingsTrapNonCommandGestures",
self.trapNonCommandGesturesCheckBox
)
self.trapNonCommandGesturesCheckBox.SetValue(config.conf["virtualBuffers"]["trapNonCommandGestures"])
# Translators: This is the label for a checkbox in the
# browse mode settings panel.
autoFocusFocusableElementsText = _("Automatically set system &focus to focusable elements")
self.autoFocusFocusableElementsCheckBox = sHelper.addItem(
wx.CheckBox(self, label=autoFocusFocusableElementsText)
)
self.autoFocusFocusableElementsCheckBox.SetValue(
config.conf["virtualBuffers"]["autoFocusFocusableElements"]
)
def onSave(self):
config.conf["virtualBuffers"]["maxLineLength"]=self.maxLengthEdit.GetValue()
config.conf["virtualBuffers"]["linesPerPage"]=self.pageLinesEdit.GetValue()
config.conf["virtualBuffers"]["useScreenLayout"]=self.useScreenLayoutCheckBox.IsChecked()
config.conf["virtualBuffers"]["enableOnPageLoad"] = self.enableOnPageLoadCheckBox.IsChecked()
config.conf["virtualBuffers"]["autoSayAllOnPageLoad"]=self.autoSayAllCheckBox.IsChecked()
config.conf["documentFormatting"]["includeLayoutTables"]=self.layoutTablesCheckBox.IsChecked()
config.conf["virtualBuffers"]["autoPassThroughOnFocusChange"]=self.autoPassThroughOnFocusChangeCheckBox.IsChecked()
config.conf["virtualBuffers"]["autoPassThroughOnCaretMove"]=self.autoPassThroughOnCaretMoveCheckBox.IsChecked()
config.conf["virtualBuffers"]["passThroughAudioIndication"]=self.passThroughAudioIndicationCheckBox.IsChecked()
config.conf["virtualBuffers"]["trapNonCommandGestures"]=self.trapNonCommandGesturesCheckBox.IsChecked()
config.conf["virtualBuffers"]["autoFocusFocusableElements"] = (
self.autoFocusFocusableElementsCheckBox.IsChecked()
)
class DocumentFormattingPanel(SettingsPanel):
# Translators: This is the label for the document formatting panel.
title = _("Document Formatting")
helpId = "DocumentFormattingSettings"
# Translators: This is a label appearing on the document formatting settings panel.
panelDescription = _("The following options control the types of document formatting reported by NVDA.")
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
sHelper.addItem(wx.StaticText(self, label=self.panelDescription))
# Translators: This is the label for a group of document formatting options in the
# document formatting settings panel
fontGroupText = _("Font")
fontGroup = guiHelper.BoxSizerHelper(self, sizer=wx.StaticBoxSizer(wx.StaticBox(self, label=fontGroupText), wx.VERTICAL))
sHelper.addItem(fontGroup)
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
fontNameText = _("&Font name")
self.fontNameCheckBox=fontGroup.addItem(wx.CheckBox(self, label=fontNameText))
self.fontNameCheckBox.SetValue(config.conf["documentFormatting"]["reportFontName"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
fontSizeText = _("Font &size")
self.fontSizeCheckBox=fontGroup.addItem(wx.CheckBox(self,label=fontSizeText))
self.fontSizeCheckBox.SetValue(config.conf["documentFormatting"]["reportFontSize"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
fontAttributesText = _("Font attrib&utes")
self.fontAttrsCheckBox=fontGroup.addItem(wx.CheckBox(self,label=fontAttributesText))
self.fontAttrsCheckBox.SetValue(config.conf["documentFormatting"]["reportFontAttributes"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
superscriptsAndSubscriptsText = _("Su&perscripts and subscripts")
self.superscriptsAndSubscriptsCheckBox = fontGroup.addItem(
wx.CheckBox(self, label=superscriptsAndSubscriptsText)
)
self.superscriptsAndSubscriptsCheckBox.SetValue(
config.conf["documentFormatting"]["reportSuperscriptsAndSubscripts"]
)
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
emphasisText=_("E&mphasis")
self.emphasisCheckBox=fontGroup.addItem(wx.CheckBox(self,label=emphasisText))
self.emphasisCheckBox.SetValue(config.conf["documentFormatting"]["reportEmphasis"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
highlightText = _("Marked (highlighted text)")
self.highlightCheckBox = fontGroup.addItem(
wx.CheckBox(self, label=highlightText)
)
self.highlightCheckBox.SetValue(
config.conf["documentFormatting"]["reportHighlight"]
)
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
styleText =_("St&yle")
self.styleCheckBox=fontGroup.addItem(wx.CheckBox(self,label=styleText))
self.styleCheckBox.SetValue(config.conf["documentFormatting"]["reportStyle"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
colorsText = _("&Colors")
self.colorCheckBox=fontGroup.addItem(wx.CheckBox(self,label=colorsText))
self.colorCheckBox.SetValue(config.conf["documentFormatting"]["reportColor"])
# Translators: This is the label for a group of document formatting options in the
# document formatting settings panel
documentInfoGroupText = _("Document information")
docInfoGroup = guiHelper.BoxSizerHelper(self, sizer=wx.StaticBoxSizer(wx.StaticBox(self, label=documentInfoGroupText), wx.VERTICAL))
sHelper.addItem(docInfoGroup)
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
commentsText = _("No&tes and comments")
self.commentsCheckBox=docInfoGroup.addItem(wx.CheckBox(self,label=commentsText))
self.commentsCheckBox.SetValue(config.conf["documentFormatting"]["reportComments"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
revisionsText = _("&Editor revisions")
self.revisionsCheckBox=docInfoGroup.addItem(wx.CheckBox(self,label=revisionsText))
self.revisionsCheckBox.SetValue(config.conf["documentFormatting"]["reportRevisions"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
spellingErrorText = _("Spelling e&rrors")
self.spellingErrorsCheckBox=docInfoGroup.addItem(wx.CheckBox(self,label=spellingErrorText))
self.spellingErrorsCheckBox.SetValue(config.conf["documentFormatting"]["reportSpellingErrors"])
# Translators: This is the label for a group of document formatting options in the
# document formatting settings panel
pageAndSpaceGroupText = _("Pages and spacing")
pageAndSpaceGroup = guiHelper.BoxSizerHelper(self, sizer=wx.StaticBoxSizer(wx.StaticBox(self, label=pageAndSpaceGroupText), wx.VERTICAL))
sHelper.addItem(pageAndSpaceGroup)
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
pageText = _("&Pages")
self.pageCheckBox=pageAndSpaceGroup.addItem(wx.CheckBox(self,label=pageText))
self.pageCheckBox.SetValue(config.conf["documentFormatting"]["reportPage"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
lineText = _("Line &numbers")
self.lineNumberCheckBox=pageAndSpaceGroup.addItem(wx.CheckBox(self,label=lineText))
self.lineNumberCheckBox.SetValue(config.conf["documentFormatting"]["reportLineNumber"])
# Translators: This is the label for a combobox controlling the reporting of line indentation in the
# Document Formatting dialog (possible choices are Off, Speech, Tones, or Both.
lineIndentationText = _("Line &indentation reporting:")
indentChoices=[
#Translators: A choice in a combo box in the document formatting dialog to report No line Indentation.
_("Off"),
#Translators: A choice in a combo box in the document formatting dialog to report indentation with Speech.
pgettext('line indentation setting', "Speech"),
#Translators: A choice in a combo box in the document formatting dialog to report indentation with tones.
_("Tones"),
#Translators: A choice in a combo box in the document formatting dialog to report indentation with both Speech and tones.
_("Both Speech and Tones")
]
self.lineIndentationCombo = pageAndSpaceGroup.addLabeledControl(lineIndentationText, wx.Choice, choices=indentChoices)
self.bindHelpEvent(
"DocumentFormattingSettingsLineIndentation",
self.lineIndentationCombo
)
#We use bitwise operations because it saves us a four way if statement.
curChoice = config.conf["documentFormatting"]["reportLineIndentationWithTones"] << 1 | config.conf["documentFormatting"]["reportLineIndentation"]
self.lineIndentationCombo.SetSelection(curChoice)
# Translators: This message is presented in the document formatting settings panelue
# If this option is selected, NVDA will report paragraph indentation if available.
paragraphIndentationText = _("&Paragraph indentation")
self.paragraphIndentationCheckBox=pageAndSpaceGroup.addItem(wx.CheckBox(self,label=paragraphIndentationText))
self.paragraphIndentationCheckBox.SetValue(config.conf["documentFormatting"]["reportParagraphIndentation"])
# Translators: This message is presented in the document formatting settings panelue
# If this option is selected, NVDA will report line spacing if available.
lineSpacingText=_("&Line spacing")
self.lineSpacingCheckBox=pageAndSpaceGroup.addItem(wx.CheckBox(self,label=lineSpacingText))
self.lineSpacingCheckBox.SetValue(config.conf["documentFormatting"]["reportLineSpacing"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
alignmentText = _("&Alignment")
self.alignmentCheckBox=pageAndSpaceGroup.addItem(wx.CheckBox(self,label=alignmentText))
self.alignmentCheckBox.SetValue(config.conf["documentFormatting"]["reportAlignment"])
# Translators: This is the label for a group of document formatting options in the
# document formatting settings panel
tablesGroupText = _("Table information")
tablesGroup = guiHelper.BoxSizerHelper(self, sizer=wx.StaticBoxSizer(wx.StaticBox(self, label=tablesGroupText), wx.VERTICAL))
sHelper.addItem(tablesGroup)
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.tablesCheckBox=tablesGroup.addItem(wx.CheckBox(self,label=_("&Tables")))
self.tablesCheckBox.SetValue(config.conf["documentFormatting"]["reportTables"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.tableHeadersCheckBox=tablesGroup.addItem(wx.CheckBox(self,label=_("Row/column h&eaders")))
self.tableHeadersCheckBox.SetValue(config.conf["documentFormatting"]["reportTableHeaders"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.tableCellCoordsCheckBox=tablesGroup.addItem(wx.CheckBox(self,label=_("Cell c&oordinates")))
self.tableCellCoordsCheckBox.SetValue(config.conf["documentFormatting"]["reportTableCellCoords"])
borderChoices=[
# Translators: This is the label for a combobox in the
# document formatting settings panel.
_("Off"),
# Translators: This is the label for a combobox in the
# document formatting settings panel.
_("Styles"),
# Translators: This is the label for a combobox in the
# document formatting settings panel.
_("Both Colors and Styles"),
]
self.borderComboBox = tablesGroup.addLabeledControl(
# Translators: This is the label for a combobox in the
# document formatting settings panel.
_("Cell &borders:"),
wx.Choice,
choices=borderChoices
)
curChoice = 0
if config.conf["documentFormatting"]["reportBorderStyle"]:
if config.conf["documentFormatting"]["reportBorderColor"]:
curChoice = 2
else:
curChoice = 1
self.borderComboBox.SetSelection(curChoice)
# Translators: This is the label for a group of document formatting options in the
# document formatting settings panel
elementsGroupText = _("Elements")
elementsGroup = guiHelper.BoxSizerHelper(self, sizer=wx.StaticBoxSizer(wx.StaticBox(self, label=elementsGroupText), wx.VERTICAL))
sHelper.addItem(elementsGroup, flag=wx.EXPAND, proportion=1)
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.headingsCheckBox=elementsGroup.addItem(wx.CheckBox(self,label=_("&Headings")))
self.headingsCheckBox.SetValue(config.conf["documentFormatting"]["reportHeadings"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.linksCheckBox=elementsGroup.addItem(wx.CheckBox(self,label=_("Lin&ks")))
self.linksCheckBox.SetValue(config.conf["documentFormatting"]["reportLinks"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.graphicsCheckBox = elementsGroup.addItem(wx.CheckBox(self, label=_("&Graphics")))
self.graphicsCheckBox.SetValue(config.conf["documentFormatting"]["reportGraphics"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.listsCheckBox=elementsGroup.addItem(wx.CheckBox(self,label=_("&Lists")))
self.listsCheckBox.SetValue(config.conf["documentFormatting"]["reportLists"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.blockQuotesCheckBox=elementsGroup.addItem(wx.CheckBox(self,label=_("Block "es")))
self.blockQuotesCheckBox.SetValue(config.conf["documentFormatting"]["reportBlockQuotes"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
groupingsText = _("&Groupings")
self.groupingsCheckBox = elementsGroup.addItem(wx.CheckBox(self, label=groupingsText))
self.groupingsCheckBox.SetValue(config.conf["documentFormatting"]["reportGroupings"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
landmarksText = _("Lan&dmarks and regions")
self.landmarksCheckBox = elementsGroup.addItem(wx.CheckBox(self, label=landmarksText))
self.landmarksCheckBox.SetValue(config.conf["documentFormatting"]["reportLandmarks"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.articlesCheckBox = elementsGroup.addItem(wx.CheckBox(self, label=_("Arti&cles")))
self.articlesCheckBox.SetValue(config.conf["documentFormatting"]["reportArticles"])
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.framesCheckBox=elementsGroup.addItem(wx.CheckBox(self,label=_("Fra&mes")))
self.framesCheckBox.Value=config.conf["documentFormatting"]["reportFrames"]
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
self.clickableCheckBox=elementsGroup.addItem(wx.CheckBox(self,label=_("&Clickable")))
self.clickableCheckBox.Value=config.conf["documentFormatting"]["reportClickable"]
# Translators: This is the label for a checkbox in the
# document formatting settings panel.
detectFormatAfterCursorText = _("Report formatting chan&ges after the cursor (can cause a lag)")
self.detectFormatAfterCursorCheckBox=wx.CheckBox(self, label=detectFormatAfterCursorText)
self.bindHelpEvent(
"DocumentFormattingDetectFormatAfterCursor",
self.detectFormatAfterCursorCheckBox
)
self.detectFormatAfterCursorCheckBox.SetValue(config.conf["documentFormatting"]["detectFormatAfterCursor"])
sHelper.addItem(self.detectFormatAfterCursorCheckBox)
def onSave(self):
config.conf["documentFormatting"]["detectFormatAfterCursor"]=self.detectFormatAfterCursorCheckBox.IsChecked()
config.conf["documentFormatting"]["reportFontName"]=self.fontNameCheckBox.IsChecked()
config.conf["documentFormatting"]["reportFontSize"]=self.fontSizeCheckBox.IsChecked()
config.conf["documentFormatting"]["reportFontAttributes"]=self.fontAttrsCheckBox.IsChecked()
config.conf["documentFormatting"]["reportSuperscriptsAndSubscripts"] = (
self.superscriptsAndSubscriptsCheckBox.IsChecked()
)
config.conf["documentFormatting"]["reportColor"]=self.colorCheckBox.IsChecked()
config.conf["documentFormatting"]["reportComments"]=self.commentsCheckBox.IsChecked()
config.conf["documentFormatting"]["reportRevisions"]=self.revisionsCheckBox.IsChecked()
config.conf["documentFormatting"]["reportEmphasis"]=self.emphasisCheckBox.IsChecked()
config.conf["documentFormatting"]["reportHighlight"] = self.highlightCheckBox.IsChecked()
config.conf["documentFormatting"]["reportAlignment"]=self.alignmentCheckBox.IsChecked()
config.conf["documentFormatting"]["reportStyle"]=self.styleCheckBox.IsChecked()
config.conf["documentFormatting"]["reportSpellingErrors"]=self.spellingErrorsCheckBox.IsChecked()
config.conf["documentFormatting"]["reportPage"]=self.pageCheckBox.IsChecked()
config.conf["documentFormatting"]["reportLineNumber"]=self.lineNumberCheckBox.IsChecked()
choice = self.lineIndentationCombo.GetSelection()
config.conf["documentFormatting"]["reportLineIndentation"] = choice in (1, 3)
config.conf["documentFormatting"]["reportLineIndentationWithTones"] = choice in (2, 3)
config.conf["documentFormatting"]["reportParagraphIndentation"]=self.paragraphIndentationCheckBox.IsChecked()
config.conf["documentFormatting"]["reportLineSpacing"]=self.lineSpacingCheckBox.IsChecked()
config.conf["documentFormatting"]["reportTables"]=self.tablesCheckBox.IsChecked()
config.conf["documentFormatting"]["reportTableHeaders"]=self.tableHeadersCheckBox.IsChecked()
config.conf["documentFormatting"]["reportTableCellCoords"]=self.tableCellCoordsCheckBox.IsChecked()
choice = self.borderComboBox.GetSelection()
config.conf["documentFormatting"]["reportBorderStyle"] = choice in (1,2)
config.conf["documentFormatting"]["reportBorderColor"] = (choice == 2)
config.conf["documentFormatting"]["reportLinks"]=self.linksCheckBox.IsChecked()
config.conf["documentFormatting"]["reportGraphics"] = self.graphicsCheckBox.IsChecked()
config.conf["documentFormatting"]["reportHeadings"]=self.headingsCheckBox.IsChecked()
config.conf["documentFormatting"]["reportLists"]=self.listsCheckBox.IsChecked()
config.conf["documentFormatting"]["reportBlockQuotes"]=self.blockQuotesCheckBox.IsChecked()
config.conf["documentFormatting"]["reportGroupings"] = self.groupingsCheckBox.IsChecked()
config.conf["documentFormatting"]["reportLandmarks"]=self.landmarksCheckBox.IsChecked()
config.conf["documentFormatting"]["reportArticles"] = self.articlesCheckBox.IsChecked()
config.conf["documentFormatting"]["reportFrames"]=self.framesCheckBox.Value
config.conf["documentFormatting"]["reportClickable"]=self.clickableCheckBox.Value
class TouchInteractionPanel(SettingsPanel):
# Translators: This is the label for the touch interaction settings panel.
title = _("Touch Interaction")
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: This is the label for a checkbox in the
# touch interaction settings panel.
touchSupportEnableLabel = _("Enable touch interaction support")
self.enableTouchSupportCheckBox = sHelper.addItem(wx.CheckBox(self, label=touchSupportEnableLabel))
self.enableTouchSupportCheckBox.SetValue(config.conf["touch"]["enabled"])
# Translators: This is the label for a checkbox in the
# touch interaction settings panel.
self.touchTypingCheckBox = sHelper.addItem(wx.CheckBox(self, label=_("&Touch typing mode")))
self.touchTypingCheckBox.SetValue(config.conf["touch"]["touchTyping"])
def onSave(self):
config.conf["touch"]["enabled"] = self.enableTouchSupportCheckBox.IsChecked()
config.conf["touch"]["touchTyping"] = self.touchTypingCheckBox.IsChecked()
touchHandler.setTouchSupport(config.conf["touch"]["enabled"])
class UwpOcrPanel(SettingsPanel):
# Translators: The title of the Windows 10 OCR panel.
title = _("Windows 10 OCR")
helpId = "Win10OcrSettings"
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Lazily import this.
from contentRecog import uwpOcr
self.languageCodes = uwpOcr.getLanguages()
languageChoices = [
languageHandler.getLanguageDescription(languageHandler.normalizeLanguage(lang))
for lang in self.languageCodes]
# Translators: Label for an option in the Windows 10 OCR dialog.
languageLabel = _("Recognition &language:")
self.languageChoice = sHelper.addLabeledControl(languageLabel, wx.Choice, choices=languageChoices)
self.bindHelpEvent("Win10OcrSettingsRecognitionLanguage", self.languageChoice)
try:
langIndex = self.languageCodes.index(config.conf["uwpOcr"]["language"])
self.languageChoice.Selection = langIndex
except ValueError:
self.languageChoice.Selection = 0
def onSave(self):
lang = self.languageCodes[self.languageChoice.Selection]
config.conf["uwpOcr"]["language"] = lang
class AdvancedPanelControls(wx.Panel):
def __init__(self, parent):
super(AdvancedPanelControls, self).__init__(parent)
self._defaultsRestored = False
sHelper = guiHelper.BoxSizerHelper(self, orientation=wx.VERTICAL)
self.SetSizer(sHelper.sizer)
# Translators: This is the label for a group of advanced options in the
# Advanced settings panel
groupText = _("NVDA Development")
devGroup = guiHelper.BoxSizerHelper(
parent=self,
sizer=wx.StaticBoxSizer(parent=self, label=groupText, orient=wx.VERTICAL)
)
sHelper.addItem(devGroup)
# Translators: This is the label for a checkbox in the
# Advanced settings panel.
label = _("Enable loading custom code from Developer Scratchpad directory")
self.scratchpadCheckBox=devGroup.addItem(wx.CheckBox(self, label=label))
self.scratchpadCheckBox.SetValue(config.conf["development"]["enableScratchpadDir"])
self.scratchpadCheckBox.defaultValue = self._getDefaultValue(["development", "enableScratchpadDir"])
self.scratchpadCheckBox.Bind(
wx.EVT_CHECKBOX,
lambda evt: self.openScratchpadButton.Enable(evt.IsChecked())
)
if config.isAppX:
self.scratchpadCheckBox.Disable()
# Translators: the label for a button in the Advanced settings category
label=_("Open developer scratchpad directory")
self.openScratchpadButton=devGroup.addItem(wx.Button(self, label=label))
self.openScratchpadButton.Enable(config.conf["development"]["enableScratchpadDir"])
self.openScratchpadButton.Bind(wx.EVT_BUTTON,self.onOpenScratchpadDir)
if config.isAppX:
self.openScratchpadButton.Disable()
# Translators: This is the label for a group of advanced options in the
# Advanced settings panel
label = _("Microsoft UI Automation")
UIAGroup = guiHelper.BoxSizerHelper(
parent=self,
sizer=wx.StaticBoxSizer(parent=self, label=label, orient=wx.VERTICAL)
)
sHelper.addItem(UIAGroup)
# Translators: This is the label for a checkbox in the
# Advanced settings panel.
label = _("Enable &selective registration for UI Automation events and property changes")
self.selectiveUIAEventRegistrationCheckBox = UIAGroup.addItem(wx.CheckBox(self, label=label))
self.selectiveUIAEventRegistrationCheckBox.SetValue(config.conf["UIA"]["selectiveEventRegistration"])
self.selectiveUIAEventRegistrationCheckBox.defaultValue = (
self._getDefaultValue(["UIA", "selectiveEventRegistration"])
)
# Translators: This is the label for a checkbox in the
# Advanced settings panel.
label = _("Use UI Automation to access Microsoft &Word document controls when available")
self.UIAInMSWordCheckBox=UIAGroup.addItem(wx.CheckBox(self, label=label))
self.UIAInMSWordCheckBox.SetValue(config.conf["UIA"]["useInMSWordWhenAvailable"])
self.UIAInMSWordCheckBox.defaultValue = self._getDefaultValue(["UIA", "useInMSWordWhenAvailable"])
# Translators: This is the label for a checkbox in the
# Advanced settings panel.
label = _("Use UI Automation to access the Windows C&onsole when available")
consoleUIADevMap = True if config.conf['UIA']['winConsoleImplementation'] == 'UIA' else False
self.ConsoleUIACheckBox = UIAGroup.addItem(wx.CheckBox(self, label=label))
self.ConsoleUIACheckBox.SetValue(consoleUIADevMap)
self.ConsoleUIACheckBox.defaultValue = self._getDefaultValue(["UIA", "winConsoleImplementation"])
# Translators: This is the label for a checkbox in the
# Advanced settings panel.
label = _("Speak &passwords in UIA consoles (may improve performance)")
self.winConsoleSpeakPasswordsCheckBox = UIAGroup.addItem(wx.CheckBox(self, label=label))
self.winConsoleSpeakPasswordsCheckBox.SetValue(config.conf["terminals"]["speakPasswords"])
self.winConsoleSpeakPasswordsCheckBox.defaultValue = self._getDefaultValue(["terminals", "speakPasswords"])
# Translators: This is the label for a group of advanced options in the
# Advanced settings panel
label = _("Terminal programs")
terminalsGroup = guiHelper.BoxSizerHelper(
parent=self,
sizer=wx.StaticBoxSizer(parent=self, label=label, orient=wx.VERTICAL)
)
sHelper.addItem(terminalsGroup)
# Translators: This is the label for a checkbox in the
# Advanced settings panel.
label = _("Use the new t&yped character support in Windows Console when available")
self.keyboardSupportInLegacyCheckBox=terminalsGroup.addItem(wx.CheckBox(self, label=label))
self.keyboardSupportInLegacyCheckBox.SetValue(config.conf["terminals"]["keyboardSupportInLegacy"])
self.keyboardSupportInLegacyCheckBox.defaultValue = self._getDefaultValue(["terminals", "keyboardSupportInLegacy"])
self.keyboardSupportInLegacyCheckBox.Enable(winVersion.isWin10(1607))
# Translators: This is the label for a group of advanced options in the
# Advanced settings panel
label = _("Speech")
speechGroup = guiHelper.BoxSizerHelper(
parent=self,
sizer=wx.StaticBoxSizer(parent=self, label=label, orient=wx.VERTICAL)
)
sHelper.addItem(speechGroup)
expiredFocusSpeechChoices = [
# Translators: Label for the 'Cancel speech for expired &focus events' combobox
# in the Advanced settings panel.
_("Default (No)"),
# Translators: Label for the 'Cancel speech for expired &focus events' combobox
# in the Advanced settings panel.
_("Yes"),
# Translators: Label for the 'Cancel speech for expired &focus events' combobox
# in the Advanced settings panel.
_("No"),
]
# Translators: This is the label for combobox in the Advanced settings panel.
cancelExpiredFocusSpeechText = _("Attempt to cancel speech for expired focus events:")
self.cancelExpiredFocusSpeechCombo: wx.Choice = speechGroup.addLabeledControl(
cancelExpiredFocusSpeechText,
wx.Choice,
choices=expiredFocusSpeechChoices
)
self.cancelExpiredFocusSpeechCombo.SetSelection(
config.conf["featureFlag"]["cancelExpiredFocusSpeech"]
)
self.cancelExpiredFocusSpeechCombo.defaultValue = self._getDefaultValue(
["featureFlag", "cancelExpiredFocusSpeech"]
)
# Translators: This is the label for a group of advanced options in the
# Advanced settings panel
label = _("Editable Text")
editableTextGroup = guiHelper.BoxSizerHelper(
self,
sizer=wx.StaticBoxSizer(parent=self, label=label, orient=wx.VERTICAL)
)
sHelper.addItem(editableTextGroup)
# Translators: This is the label for a numeric control in the
# Advanced settings panel.
label = _("Caret movement timeout (in ms)")
self.caretMoveTimeoutSpinControl=editableTextGroup.addLabeledControl(
label,
nvdaControls.SelectOnFocusSpinCtrl,
min=0,
max=2000,
initial=config.conf["editableText"]["caretMoveTimeoutMs"]
)
self.caretMoveTimeoutSpinControl.defaultValue = self._getDefaultValue(["editableText", "caretMoveTimeoutMs"])
# Translators: This is the label for a group of advanced options in the
# Advanced settings panel
label = _("Debug logging")
debugLogGroup = guiHelper.BoxSizerHelper(
self,
sizer=wx.StaticBoxSizer(parent=self, label=label, orient=wx.VERTICAL)
)
sHelper.addItem(debugLogGroup)
self.logCategories=[
"hwIo",
"MSAA",
"UIA",
"audioDucking",
"gui",
"louis",
"timeSinceInput",
"vision",
"speech",
"speechManager",
"nvwave",
]
# Translators: This is the label for a list in the
# Advanced settings panel
logCategoriesLabel=_("Enabled logging categories")
self.logCategoriesList=debugLogGroup.addLabeledControl(
logCategoriesLabel,
nvdaControls.CustomCheckListBox,
choices=self.logCategories
)
self.logCategoriesList.CheckedItems = [
index for index, x in enumerate(self.logCategories) if config.conf['debugLog'][x]
]
self.logCategoriesList.Select(0)
self.logCategoriesList.defaultCheckedItems = [
index for index, x in enumerate(self.logCategories) if bool(
self._getDefaultValue(['debugLog', x])
)
]
self.Layout()
def onOpenScratchpadDir(self,evt):
path=config.getScratchpadDir(ensureExists=True)
os.startfile(path)
def _getDefaultValue(self, configPath):
return config.conf.getConfigValidation(configPath).default
def haveConfigDefaultsBeenRestored(self):
return (
self._defaultsRestored
and self.scratchpadCheckBox.IsChecked() == self.scratchpadCheckBox.defaultValue
and (
self.selectiveUIAEventRegistrationCheckBox.IsChecked()
== self.selectiveUIAEventRegistrationCheckBox.defaultValue
)
and self.UIAInMSWordCheckBox.IsChecked() == self.UIAInMSWordCheckBox.defaultValue
and self.ConsoleUIACheckBox.IsChecked() == (self.ConsoleUIACheckBox.defaultValue == 'UIA')
and self.winConsoleSpeakPasswordsCheckBox.IsChecked() == self.winConsoleSpeakPasswordsCheckBox.defaultValue
and self.cancelExpiredFocusSpeechCombo.GetSelection() == self.cancelExpiredFocusSpeechCombo.defaultValue
and self.keyboardSupportInLegacyCheckBox.IsChecked() == self.keyboardSupportInLegacyCheckBox.defaultValue
and self.caretMoveTimeoutSpinControl.GetValue() == self.caretMoveTimeoutSpinControl.defaultValue
and set(self.logCategoriesList.CheckedItems) == set(self.logCategoriesList.defaultCheckedItems)
and True # reduce noise in diff when the list is extended.
)
def restoreToDefaults(self):
self.scratchpadCheckBox.SetValue(self.scratchpadCheckBox.defaultValue)
self.selectiveUIAEventRegistrationCheckBox.SetValue(self.selectiveUIAEventRegistrationCheckBox.defaultValue)
self.UIAInMSWordCheckBox.SetValue(self.UIAInMSWordCheckBox.defaultValue)
self.ConsoleUIACheckBox.SetValue(self.ConsoleUIACheckBox.defaultValue == 'UIA')
self.winConsoleSpeakPasswordsCheckBox.SetValue(self.winConsoleSpeakPasswordsCheckBox.defaultValue)
self.cancelExpiredFocusSpeechCombo.SetSelection(self.cancelExpiredFocusSpeechCombo.defaultValue)
self.keyboardSupportInLegacyCheckBox.SetValue(self.keyboardSupportInLegacyCheckBox.defaultValue)
self.caretMoveTimeoutSpinControl.SetValue(self.caretMoveTimeoutSpinControl.defaultValue)
self.logCategoriesList.CheckedItems = self.logCategoriesList.defaultCheckedItems
self._defaultsRestored = True
def onSave(self):
log.debug("Saving advanced config")
config.conf["development"]["enableScratchpadDir"]=self.scratchpadCheckBox.IsChecked()
config.conf["UIA"]["selectiveEventRegistration"] = self.selectiveUIAEventRegistrationCheckBox.IsChecked()
config.conf["UIA"]["useInMSWordWhenAvailable"]=self.UIAInMSWordCheckBox.IsChecked()
if self.ConsoleUIACheckBox.IsChecked():
config.conf['UIA']['winConsoleImplementation'] = "UIA"
else:
config.conf['UIA']['winConsoleImplementation'] = "auto"
config.conf["terminals"]["speakPasswords"] = self.winConsoleSpeakPasswordsCheckBox.IsChecked()
config.conf["featureFlag"]["cancelExpiredFocusSpeech"] = self.cancelExpiredFocusSpeechCombo.GetSelection()
config.conf["terminals"]["keyboardSupportInLegacy"]=self.keyboardSupportInLegacyCheckBox.IsChecked()
config.conf["editableText"]["caretMoveTimeoutMs"]=self.caretMoveTimeoutSpinControl.GetValue()
for index,key in enumerate(self.logCategories):
config.conf['debugLog'][key]=self.logCategoriesList.IsChecked(index)
class AdvancedPanel(SettingsPanel):
enableControlsCheckBox = None # type: wx.CheckBox
# Translators: This is the label for the Advanced settings panel.
title = _("Advanced")
# Translators: This is the label to warn users about the Advanced options in the
# Advanced settings panel
warningHeader = _("Warning!")
warningExplanation = _(
# Translators: This is a label appearing on the Advanced settings panel.
"The following settings are for advanced users. "
"Changing them may cause NVDA to function incorrectly. "
"Please only change these if you know what you are doing or "
"have been specifically instructed by NVDA developers."
)
panelDescription = u"{}\n{}".format(warningHeader, warningExplanation)
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
warningGroup = guiHelper.BoxSizerHelper(
self,
sizer=wx.StaticBoxSizer(wx.StaticBox(self), wx.VERTICAL)
)
sHelper.addItem(warningGroup)
warningBox = warningGroup.sizer.GetStaticBox() # type: wx.StaticBox
warningText = wx.StaticText(warningBox, label=self.warningHeader)
warningText.SetFont(wx.Font(18, wx.FONTFAMILY_DEFAULT, wx.NORMAL, wx.BOLD))
warningGroup.addItem(warningText)
self.windowText = warningGroup.addItem(wx.StaticText(warningBox, label=self.warningExplanation))
self.windowText.Wrap(self.scaleSize(544))
enableAdvancedControlslabel = _(
# Translators: This is the label for a checkbox in the Advanced settings panel.
"I understand that changing these settings may cause NVDA to function incorrectly."
)
self.enableControlsCheckBox = warningGroup.addItem(
wx.CheckBox(parent=warningBox, label=enableAdvancedControlslabel, id=wx.NewIdRef())
)
boldedFont = self.enableControlsCheckBox.GetFont().Bold()
self.enableControlsCheckBox.SetFont(boldedFont)
restoreDefaultsButton = warningGroup.addItem(
# Translators: This is the label for a button in the Advanced settings panel
wx.Button(self, label=_("Restore defaults"))
)
restoreDefaultsButton.Bind(wx.EVT_BUTTON, lambda evt: self.advancedControls.restoreToDefaults())
self.advancedControls = AdvancedPanelControls(self)
sHelper.sizer.Add(self.advancedControls, flag=wx.EXPAND)
self.enableControlsCheckBox.Bind(
wx.EVT_CHECKBOX,
self.onEnableControlsCheckBox
)
self.advancedControls.Enable(self.enableControlsCheckBox.IsChecked())
def onSave(self):
if (
self.enableControlsCheckBox.IsChecked() or
self.advancedControls.haveConfigDefaultsBeenRestored()
):
self.advancedControls.onSave()
def onEnableControlsCheckBox(self, evt):
# due to some not very well understood mis ordering of event processing, we force NVDA to
# process pending events. This fixes an issue where the checkbox state was being reported
# incorrectly. This checkbox is slightly different from most, in that its behaviour is to
# enable more controls than is typical. This might be causing enough of a delay, that there
# is a mismatch in the state of the checkbox and when the events are processed by NVDA.
from api import processPendingEvents
processPendingEvents()
self.advancedControls.Enable(evt.IsChecked())
class DictionaryEntryDialog(wx.Dialog):
TYPE_LABELS = {
# Translators: This is a label for an Entry Type radio button in add dictionary entry dialog.
speechDictHandler.ENTRY_TYPE_ANYWHERE: _("&Anywhere"),
# Translators: This is a label for an Entry Type radio button in add dictionary entry dialog.
speechDictHandler.ENTRY_TYPE_WORD: _("Whole &word"),
# Translators: This is a label for an Entry Type radio button in add dictionary entry dialog.
speechDictHandler.ENTRY_TYPE_REGEXP: _("Regular &expression")
}
TYPE_LABELS_ORDERING = (speechDictHandler.ENTRY_TYPE_ANYWHERE, speechDictHandler.ENTRY_TYPE_WORD, speechDictHandler.ENTRY_TYPE_REGEXP)
# Translators: This is the label for the edit dictionary entry dialog.
def __init__(self, parent, title=_("Edit Dictionary Entry")):
super(DictionaryEntryDialog,self).__init__(parent,title=title)
mainSizer=wx.BoxSizer(wx.VERTICAL)
sHelper = guiHelper.BoxSizerHelper(self, orientation=wx.VERTICAL)
# Translators: This is a label for an edit field in add dictionary entry dialog.
patternLabelText = _("&Pattern")
self.patternTextCtrl=sHelper.addLabeledControl(patternLabelText, wx.TextCtrl)
# Translators: This is a label for an edit field in add dictionary entry dialog and in punctuation/symbol pronunciation dialog.
replacementLabelText = _("&Replacement")
self.replacementTextCtrl=sHelper.addLabeledControl(replacementLabelText, wx.TextCtrl)
# Translators: This is a label for an edit field in add dictionary entry dialog.
commentLabelText = _("&Comment")
self.commentTextCtrl=sHelper.addLabeledControl(commentLabelText, wx.TextCtrl)
# Translators: This is a label for a checkbox in add dictionary entry dialog.
caseSensitiveText = _("Case &sensitive")
self.caseSensitiveCheckBox=sHelper.addItem(wx.CheckBox(self,label=caseSensitiveText))
# Translators: This is a label for a set of radio buttons in add dictionary entry dialog.
typeText = _("&Type")
typeChoices = [DictionaryEntryDialog.TYPE_LABELS[i] for i in DictionaryEntryDialog.TYPE_LABELS_ORDERING]
self.typeRadioBox=sHelper.addItem(wx.RadioBox(self,label=typeText, choices=typeChoices))
sHelper.addDialogDismissButtons(wx.OK | wx.CANCEL, separated=True)
mainSizer.Add(sHelper.sizer, border=guiHelper.BORDER_FOR_DIALOGS, flag=wx.ALL)
mainSizer.Fit(self)
self.SetSizer(mainSizer)
self.setType(speechDictHandler.ENTRY_TYPE_ANYWHERE)
self.patternTextCtrl.SetFocus()
self.Bind(wx.EVT_BUTTON,self.onOk,id=wx.ID_OK)
def getType(self):
typeRadioValue = self.typeRadioBox.GetSelection()
if typeRadioValue == wx.NOT_FOUND:
return speechDictHandler.ENTRY_TYPE_ANYWHERE
return DictionaryEntryDialog.TYPE_LABELS_ORDERING[typeRadioValue]
def onOk(self,evt):
if not self.patternTextCtrl.GetValue():
# Translators: This is an error message to let the user know that the pattern field in the dictionary entry is not valid.
gui.messageBox(_("A pattern is required."), _("Dictionary Entry Error"), wx.OK|wx.ICON_WARNING, self)
self.patternTextCtrl.SetFocus()
return
try:
dictEntry = self.dictEntry = speechDictHandler.SpeechDictEntry(
self.patternTextCtrl.GetValue(),
self.replacementTextCtrl.GetValue(),
self.commentTextCtrl.GetValue(),
bool(self.caseSensitiveCheckBox.GetValue()),
self.getType()
)
dictEntry.sub("test") # Ensure there are no grouping error (#11407)
except Exception as e:
log.debugWarning("Could not add dictionary entry due to (regex error) : %s" % e)
# Translators: This is an error message to let the user know that the dictionary entry is not valid.
gui.messageBox(_("Regular Expression error: \"%s\".")%e, _("Dictionary Entry Error"), wx.OK|wx.ICON_WARNING, self)
return
evt.Skip()
def setType(self, type):
self.typeRadioBox.SetSelection(DictionaryEntryDialog.TYPE_LABELS_ORDERING.index(type))
class DictionaryDialog(SettingsDialog):
TYPE_LABELS = {t: l.replace("&", "") for t, l in DictionaryEntryDialog.TYPE_LABELS.items()}
helpId = "SpeechDictionaries"
def __init__(self,parent,title,speechDict):
self.title = title
self.speechDict = speechDict
self.tempSpeechDict=speechDictHandler.SpeechDict()
self.tempSpeechDict.extend(self.speechDict)
globalVars.speechDictionaryProcessing=False
super().__init__(parent, resizeable=True)
# Historical initial size, result of L{self.dictList} being (550,350) as of #6287.
# Setting an initial size on L{self.dictList} by passing a L{size} argument when
# creating the control would also set its minimum size and thus block the dialog from being shrunk.
self.SetSize(576, 502)
self.CentreOnScreen()
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: The label for the list box of dictionary entries in speech dictionary dialog.
entriesLabelText=_("&Dictionary entries")
self.dictList = sHelper.addLabeledControl(
entriesLabelText,
wx.ListCtrl, style=wx.LC_REPORT | wx.LC_SINGLE_SEL
)
# Translators: The label for a column in dictionary entries list used to identify comments for the entry.
self.dictList.InsertColumn(0,_("Comment"),width=150)
# Translators: The label for a column in dictionary entries list used to identify pattern (original word or a pattern).
self.dictList.InsertColumn(1,_("Pattern"),width=150)
# Translators: The label for a column in dictionary entries list and in a list of symbols from symbol pronunciation dialog used to identify replacement for a pattern or a symbol
self.dictList.InsertColumn(2,_("Replacement"),width=150)
# Translators: The label for a column in dictionary entries list used to identify whether the entry is case sensitive or not.
self.dictList.InsertColumn(3,_("case"),width=50)
# Translators: The label for a column in dictionary entries list used to identify whether the entry is a regular expression, matches whole words, or matches anywhere.
self.dictList.InsertColumn(4,_("Type"),width=50)
self.offOn = (_("off"),_("on"))
for entry in self.tempSpeechDict:
self.dictList.Append((entry.comment,entry.pattern,entry.replacement,self.offOn[int(entry.caseSensitive)],DictionaryDialog.TYPE_LABELS[entry.type]))
self.editingIndex=-1
bHelper = guiHelper.ButtonHelper(orientation=wx.HORIZONTAL)
bHelper.addButton(
parent=self,
# Translators: The label for a button in speech dictionaries dialog to add new entries.
label=_("&Add")
).Bind(wx.EVT_BUTTON, self.OnAddClick)
bHelper.addButton(
parent=self,
# Translators: The label for a button in speech dictionaries dialog to edit existing entries.
label=_("&Edit")
).Bind(wx.EVT_BUTTON, self.OnEditClick)
bHelper.addButton(
parent=self,
# Translators: The label for a button in speech dictionaries dialog to remove existing entries.
label=_("&Remove")
).Bind(wx.EVT_BUTTON, self.OnRemoveClick)
sHelper.addItem(bHelper)
def postInit(self):
self.dictList.SetFocus()
def onCancel(self,evt):
globalVars.speechDictionaryProcessing=True
super(DictionaryDialog, self).onCancel(evt)
def onOk(self,evt):
globalVars.speechDictionaryProcessing=True
if self.tempSpeechDict!=self.speechDict:
del self.speechDict[:]
self.speechDict.extend(self.tempSpeechDict)
self.speechDict.save()
super(DictionaryDialog, self).onOk(evt)
def OnAddClick(self,evt):
# Translators: This is the label for the add dictionary entry dialog.
entryDialog=DictionaryEntryDialog(self,title=_("Add Dictionary Entry"))
if entryDialog.ShowModal()==wx.ID_OK:
self.tempSpeechDict.append(entryDialog.dictEntry)
self.dictList.Append((entryDialog.commentTextCtrl.GetValue(),entryDialog.patternTextCtrl.GetValue(),entryDialog.replacementTextCtrl.GetValue(),self.offOn[int(entryDialog.caseSensitiveCheckBox.GetValue())],DictionaryDialog.TYPE_LABELS[entryDialog.getType()]))
index=self.dictList.GetFirstSelected()
while index>=0:
self.dictList.Select(index,on=0)
index=self.dictList.GetNextSelected(index)
addedIndex=self.dictList.GetItemCount()-1
self.dictList.Select(addedIndex)
self.dictList.Focus(addedIndex)
self.dictList.SetFocus()
entryDialog.Destroy()
def OnEditClick(self,evt):
if self.dictList.GetSelectedItemCount()!=1:
return
editIndex=self.dictList.GetFirstSelected()
if editIndex<0:
return
entryDialog=DictionaryEntryDialog(self)
entryDialog.patternTextCtrl.SetValue(self.tempSpeechDict[editIndex].pattern)
entryDialog.replacementTextCtrl.SetValue(self.tempSpeechDict[editIndex].replacement)
entryDialog.commentTextCtrl.SetValue(self.tempSpeechDict[editIndex].comment)
entryDialog.caseSensitiveCheckBox.SetValue(self.tempSpeechDict[editIndex].caseSensitive)
entryDialog.setType(self.tempSpeechDict[editIndex].type)
if entryDialog.ShowModal()==wx.ID_OK:
self.tempSpeechDict[editIndex]=entryDialog.dictEntry
self.dictList.SetItem(editIndex,0,entryDialog.commentTextCtrl.GetValue())
self.dictList.SetItem(editIndex,1,entryDialog.patternTextCtrl.GetValue())
self.dictList.SetItem(editIndex,2,entryDialog.replacementTextCtrl.GetValue())
self.dictList.SetItem(editIndex,3,self.offOn[int(entryDialog.caseSensitiveCheckBox.GetValue())])
self.dictList.SetItem(editIndex,4,DictionaryDialog.TYPE_LABELS[entryDialog.getType()])
self.dictList.SetFocus()
entryDialog.Destroy()
def OnRemoveClick(self,evt):
index=self.dictList.GetFirstSelected()
while index>=0:
self.dictList.DeleteItem(index)
del self.tempSpeechDict[index]
index=self.dictList.GetNextSelected(index)
self.dictList.SetFocus()
class BrailleSettingsPanel(SettingsPanel):
# Translators: This is the label for the braille panel
title = _("Braille")
helpId = "BrailleSettings"
def makeSettings(self, settingsSizer):
settingsSizerHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: A label for the braille display on the braille panel.
displayLabel = _("Braille &display")
displayBox = wx.StaticBox(self, label=displayLabel)
displayGroup = guiHelper.BoxSizerHelper(self, sizer=wx.StaticBoxSizer(displayBox, wx.HORIZONTAL))
settingsSizerHelper.addItem(displayGroup)
self.displayNameCtrl = ExpandoTextCtrl(self, size=(self.scaleSize(250), -1), style=wx.TE_READONLY)
self.updateCurrentDisplay()
# Translators: This is the label for the button used to change braille display,
# it appears in the context of a braille display group on the braille settings panel.
changeDisplayBtn = wx.Button(self, label=_("C&hange..."))
displayGroup.addItem(
guiHelper.associateElements(
self.displayNameCtrl,
changeDisplayBtn
)
)
self.displayNameCtrl.Bind(wx.EVT_CHAR_HOOK, self._enterTriggersOnChangeDisplay)
changeDisplayBtn.Bind(wx.EVT_BUTTON,self.onChangeDisplay)
self.brailleSubPanel = BrailleSettingsSubPanel(self)
settingsSizerHelper.addItem(self.brailleSubPanel)
def _enterTriggersOnChangeDisplay(self, evt):
if evt.KeyCode == wx.WXK_RETURN:
self.onChangeDisplay(evt)
else:
evt.Skip()
def onChangeDisplay(self, evt):
changeDisplay = BrailleDisplaySelectionDialog(self, multiInstanceAllowed=True)
ret = changeDisplay.ShowModal()
if ret == wx.ID_OK:
self.Freeze()
# trigger a refresh of the settings
self.onPanelActivated()
self._sendLayoutUpdatedEvent()
self.Thaw()
def updateCurrentDisplay(self):
if config.conf["braille"]["display"] == braille.AUTO_DISPLAY_NAME:
displayDesc = BrailleDisplaySelectionDialog.getCurrentAutoDisplayDescription()
else:
displayDesc = braille.handler.display.description
self.displayNameCtrl.SetValue(displayDesc)
def onPanelActivated(self):
self.brailleSubPanel.onPanelActivated()
super(BrailleSettingsPanel,self).onPanelActivated()
def onPanelDeactivated(self):
self.brailleSubPanel.onPanelDeactivated()
super(BrailleSettingsPanel,self).onPanelDeactivated()
def onDiscard(self):
self.brailleSubPanel.onDiscard()
def onSave(self):
self.brailleSubPanel.onSave()
class BrailleDisplaySelectionDialog(SettingsDialog):
# Translators: This is the label for the braille display selection dialog.
title = _("Select Braille Display")
helpId = "BrailleSettings"
displayNames = []
possiblePorts = []
def makeSettings(self, settingsSizer):
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# Translators: The label for a setting in braille settings to choose a braille display.
displayLabelText = _("Braille &display:")
self.displayList = sHelper.addLabeledControl(displayLabelText, wx.Choice, choices=[])
self.Bind(wx.EVT_CHOICE, self.onDisplayNameChanged, self.displayList)
# Translators: The label for a setting in braille settings to choose the connection port (if the selected braille display supports port selection).
portsLabelText = _("&Port:")
self.portsList = sHelper.addLabeledControl(portsLabelText, wx.Choice, choices=[])
self.bindHelpEvent("BrailleSettingsPort", self.portsList)
self.updateBrailleDisplayLists()
def postInit(self):
# Finally, ensure that focus is on the list of displays.
self.displayList.SetFocus()
@staticmethod
def getCurrentAutoDisplayDescription():
description = braille.AUTOMATIC_PORT[1]
if (
config.conf["braille"]["display"] == braille.AUTO_DISPLAY_NAME
and braille.handler.display.name != "noBraille"
):
description = "%s (%s)" % (description, braille.handler.display.description)
return description
def updateBrailleDisplayLists(self):
driverList = [(braille.AUTO_DISPLAY_NAME, self.getCurrentAutoDisplayDescription())]
driverList.extend(braille.getDisplayList())
self.displayNames = [driver[0] for driver in driverList]
displayChoices = [driver[1] for driver in driverList]
self.displayList.Clear()
self.displayList.AppendItems(displayChoices)
self.bindHelpEvent("BrailleSettingsDisplay", self.displayList)
try:
if config.conf["braille"]["display"] == braille.AUTO_DISPLAY_NAME:
selection = 0
else:
selection = self.displayNames.index(braille.handler.display.name)
self.displayList.SetSelection(selection)
except:
pass
self.updatePossiblePorts()
def updatePossiblePorts(self):
displayName = self.displayNames[self.displayList.GetSelection()]
self.possiblePorts = []
if displayName != "auto":
displayCls = braille._getDisplayDriver(displayName)
try:
self.possiblePorts.extend(displayCls.getPossiblePorts().items())
except NotImplementedError:
pass
if self.possiblePorts:
self.portsList.SetItems([p[1] for p in self.possiblePorts])
try:
selectedPort = config.conf["braille"][displayName].get("port")
portNames = [p[0] for p in self.possiblePorts]
selection = portNames.index(selectedPort)
except (KeyError, ValueError):
# Display name not in config or port not valid
selection = 0
self.portsList.SetSelection(selection)
# If no port selection is possible or only automatic selection is available, disable the port selection control
enable = len(self.possiblePorts) > 0 and not (len(self.possiblePorts) == 1 and self.possiblePorts[0][0] == "auto")
self.portsList.Enable(enable)
def onDisplayNameChanged(self, evt):
self.updatePossiblePorts()
def onOk(self, evt):
if not self.displayNames:
# The list of displays has not been populated yet, so we didn't change anything in this panel
return
display = self.displayNames[self.displayList.GetSelection()]
if display not in config.conf["braille"]:
config.conf["braille"][display] = {}
if self.possiblePorts:
port = self.possiblePorts[self.portsList.GetSelection()][0]
config.conf["braille"][display]["port"] = port
if not braille.handler.setDisplayByName(display):
gui.messageBox(
message=_("Could not load the {display} display.").format(display=display),
caption=_("Braille Display Error"),
style=wx.OK | wx.ICON_WARNING,
parent=self
)
return
if self.IsModal():
self.Parent.updateCurrentDisplay()
super(BrailleDisplaySelectionDialog, self).onOk(evt)
class BrailleSettingsSubPanel(AutoSettingsMixin, SettingsPanel):
@property
def driver(self):
return braille.handler.display
def getSettings(self) -> AutoSettings:
return self.driver
def makeSettings(self, settingsSizer):
shouldDebugGui = gui._isDebug()
startTime = 0 if not shouldDebugGui else time.time()
self.updateDriverSettings()
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
tables = brailleTables.listTables()
outputsLabelText = _("&Output table:")
outTables = [table for table in tables if table.output]
self.outTableNames = [table.fileName for table in outTables]
outTableChoices = [table.displayName for table in outTables]
self.outTableList = sHelper.addLabeledControl(outputsLabelText, wx.Choice, choices=outTableChoices)
self.bindHelpEvent("BrailleSettingsOutputTable", self.outTableList)
try:
selection = self.outTableNames.index(config.conf["braille"]["translationTable"])
self.outTableList.SetSelection(selection)
except:
pass
if shouldDebugGui:
timePassed = time.time() - startTime
log.debug(
f"Loading output tables completed, now at {timePassed:.2f} seconds from start"
)
inputLabelText = _("&Input table:")
self.inTables = [table for table in tables if table.input]
inTableChoices = [table.displayName for table in self.inTables]
self.inTableList = sHelper.addLabeledControl(inputLabelText, wx.Choice, choices=inTableChoices)
self.bindHelpEvent("BrailleSettingsInputTable", self.inTableList)
try:
selection = self.inTables.index(brailleInput.handler.table)
self.inTableList.SetSelection(selection)
except:
pass
if shouldDebugGui:
timePassed = time.time() - startTime
log.debug(
f"Loading input tables completed, now at {timePassed:.2f} seconds from start"
)
expandAtCursorText = _("E&xpand to computer braille for the word at the cursor")
self.expandAtCursorCheckBox = sHelper.addItem(
wx.CheckBox(self, wx.ID_ANY, label=expandAtCursorText)
)
self.bindHelpEvent("BrailleSettingsExpandToComputerBraille", self.expandAtCursorCheckBox)
self.expandAtCursorCheckBox.SetValue(config.conf["braille"]["expandAtCursor"])
showCursorLabelText = _("&Show cursor")
self.showCursorCheckBox = sHelper.addItem(wx.CheckBox(self, label=showCursorLabelText))
self.bindHelpEvent("BrailleSettingsShowCursor", self.showCursorCheckBox)
self.showCursorCheckBox.Bind(wx.EVT_CHECKBOX, self.onShowCursorChange)
self.showCursorCheckBox.SetValue(config.conf["braille"]["showCursor"])
cursorBlinkLabelText = _("Blink cursor")
self.cursorBlinkCheckBox = sHelper.addItem(
wx.CheckBox(self, label=cursorBlinkLabelText)
)
self.bindHelpEvent("BrailleSettingsBlinkCursor", self.cursorBlinkCheckBox)
self.cursorBlinkCheckBox.Bind(wx.EVT_CHECKBOX, self.onBlinkCursorChange)
self.cursorBlinkCheckBox.SetValue(config.conf["braille"]["cursorBlink"])
if not self.showCursorCheckBox.GetValue():
self.cursorBlinkCheckBox.Disable()
cursorBlinkRateLabelText = _("Cursor blink rate (ms)")
minBlinkRate = int(config.conf.getConfigValidation(
("braille", "cursorBlinkRate")
).kwargs["min"])
maxBlinkRate = int(config.conf.getConfigValidation(("braille", "cursorBlinkRate")).kwargs["max"])
self.cursorBlinkRateEdit = sHelper.addLabeledControl(
cursorBlinkRateLabelText,
nvdaControls.SelectOnFocusSpinCtrl,
min=minBlinkRate,
max=maxBlinkRate,
initial=config.conf["braille"]["cursorBlinkRate"]
)
self.bindHelpEvent("BrailleSettingsBlinkRate", self.cursorBlinkRateEdit)
if not self.showCursorCheckBox.GetValue() or not self.cursorBlinkCheckBox.GetValue() :
self.cursorBlinkRateEdit.Disable()
self.cursorShapes = [s[0] for s in braille.CURSOR_SHAPES]
cursorShapeChoices = [s[1] for s in braille.CURSOR_SHAPES]
cursorShapeFocusLabelText = _("Cursor shape for &focus:")
self.cursorShapeFocusList = sHelper.addLabeledControl(cursorShapeFocusLabelText, wx.Choice, choices=cursorShapeChoices)
self.bindHelpEvent("BrailleSettingsCursorShapeForFocus", self.cursorShapeFocusList)
try:
selection = self.cursorShapes.index(config.conf["braille"]["cursorShapeFocus"])
self.cursorShapeFocusList.SetSelection(selection)
except:
pass
if not self.showCursorCheckBox.GetValue():
self.cursorShapeFocusList.Disable()
cursorShapeReviewLabelText = _("Cursor shape for &review:")
self.cursorShapeReviewList = sHelper.addLabeledControl(cursorShapeReviewLabelText, wx.Choice, choices=cursorShapeChoices)
self.bindHelpEvent("BrailleSettingsCursorShapeForReview", self.cursorShapeReviewList)
try:
selection = self.cursorShapes.index(config.conf["braille"]["cursorShapeReview"])
self.cursorShapeReviewList.SetSelection(selection)
except:
pass
if not self.showCursorCheckBox.GetValue():
self.cursorShapeReviewList.Disable()
if gui._isDebug():
log.debug("Loading cursor settings completed, now at %.2f seconds from start"%(time.time() - startTime))
minTimeout = int(config.conf.getConfigValidation(
("braille", "messageTimeout")
).kwargs["min"])
maxTimeOut = int(config.conf.getConfigValidation(
("braille", "messageTimeout")
).kwargs["max"])
messageTimeoutText = _("Message &timeout (sec)")
self.messageTimeoutEdit = sHelper.addLabeledControl(
messageTimeoutText,
nvdaControls.SelectOnFocusSpinCtrl,
min=minTimeout,
max=maxTimeOut,
initial=config.conf["braille"]["messageTimeout"]
)
self.bindHelpEvent("BrailleSettingsMessageTimeout", self.messageTimeoutEdit)
noMessageTimeoutLabelText = _("Show &messages indefinitely")
self.noMessageTimeoutCheckBox = sHelper.addItem(wx.CheckBox(self, label=noMessageTimeoutLabelText))
self.bindHelpEvent("BrailleSettingsNoMessageTimeout", self.noMessageTimeoutCheckBox)
self.noMessageTimeoutCheckBox.Bind(wx.EVT_CHECKBOX, self.onNoMessageTimeoutChange)
self.noMessageTimeoutCheckBox.SetValue(config.conf["braille"]["noMessageTimeout"])
if self.noMessageTimeoutCheckBox.GetValue():
self.messageTimeoutEdit.Disable()
if gui._isDebug():
log.debug("Loading timeout settings completed, now at %.2f seconds from start"%(time.time() - startTime))
tetherListText = _("Tether B&raille:")
tetherChoices = [x[1] for x in braille.handler.tetherValues]
self.tetherList = sHelper.addLabeledControl(tetherListText, wx.Choice, choices=tetherChoices)
self.bindHelpEvent("BrailleTether", self.tetherList)
tetherChoice=braille.handler.TETHER_AUTO if config.conf["braille"]["autoTether"] else config.conf["braille"]["tetherTo"]
selection = next((x for x,y in enumerate(braille.handler.tetherValues) if y[0]==tetherChoice))
try:
self.tetherList.SetSelection(selection)
except:
pass
if gui._isDebug():
log.debug("Loading tether settings completed, now at %.2f seconds from start"%(time.time() - startTime))
readByParagraphText = _("Read by ¶graph")
self.readByParagraphCheckBox = sHelper.addItem(wx.CheckBox(self, label=readByParagraphText))
self.bindHelpEvent("BrailleSettingsReadByParagraph", self.readByParagraphCheckBox)
self.readByParagraphCheckBox.Value = config.conf["braille"]["readByParagraph"]
wordWrapText = _("Avoid splitting &words when possible")
self.wordWrapCheckBox = sHelper.addItem(wx.CheckBox(self, label=wordWrapText))
self.bindHelpEvent("BrailleSettingsWordWrap", self.wordWrapCheckBox)
self.wordWrapCheckBox.Value = config.conf["braille"]["wordWrap"]
focusContextPresentationLabelText = _("Focus context presentation:")
self.focusContextPresentationValues = [x[0] for x in braille.focusContextPresentations]
focusContextPresentationChoices = [x[1] for x in braille.focusContextPresentations]
self.focusContextPresentationList = sHelper.addLabeledControl(focusContextPresentationLabelText, wx.Choice, choices=focusContextPresentationChoices)
self.bindHelpEvent("BrailleSettingsFocusContextPresentation", self.focusContextPresentationList)
try:
index=self.focusContextPresentationValues.index(config.conf["braille"]["focusContextPresentation"])
except:
index=0
self.focusContextPresentationList.SetSelection(index)
if gui._isDebug():
log.debug("Finished making settings, now at %.2f seconds from start"%(time.time() - startTime))
def onSave(self):
AutoSettingsMixin.onSave(self)
config.conf["braille"]["translationTable"] = self.outTableNames[self.outTableList.GetSelection()]
brailleInput.handler.table = self.inTables[self.inTableList.GetSelection()]
config.conf["braille"]["expandAtCursor"] = self.expandAtCursorCheckBox.GetValue()
config.conf["braille"]["showCursor"] = self.showCursorCheckBox.GetValue()
config.conf["braille"]["cursorBlink"] = self.cursorBlinkCheckBox.GetValue()
config.conf["braille"]["cursorBlinkRate"] = self.cursorBlinkRateEdit.GetValue()
config.conf["braille"]["cursorShapeFocus"] = self.cursorShapes[self.cursorShapeFocusList.GetSelection()]
config.conf["braille"]["cursorShapeReview"] = self.cursorShapes[self.cursorShapeReviewList.GetSelection()]
config.conf["braille"]["noMessageTimeout"] = self.noMessageTimeoutCheckBox.GetValue()
config.conf["braille"]["messageTimeout"] = self.messageTimeoutEdit.GetValue()
tetherChoice = braille.handler.tetherValues[self.tetherList.GetSelection()][0]
if tetherChoice==braille.handler.TETHER_AUTO:
config.conf["braille"]["autoTether"] = True
config.conf["braille"]["tetherTo"] = braille.handler.TETHER_FOCUS
else:
config.conf["braille"]["autoTether"] = False
braille.handler.setTether(tetherChoice, auto=False)
config.conf["braille"]["readByParagraph"] = self.readByParagraphCheckBox.Value
config.conf["braille"]["wordWrap"] = self.wordWrapCheckBox.Value
config.conf["braille"]["focusContextPresentation"] = self.focusContextPresentationValues[self.focusContextPresentationList.GetSelection()]
def onShowCursorChange(self, evt):
self.cursorBlinkCheckBox.Enable(evt.IsChecked())
self.cursorBlinkRateEdit.Enable(evt.IsChecked() and self.cursorBlinkCheckBox.GetValue())
self.cursorShapeFocusList.Enable(evt.IsChecked())
self.cursorShapeReviewList.Enable(evt.IsChecked())
def onBlinkCursorChange(self, evt):
self.cursorBlinkRateEdit.Enable(evt.IsChecked())
def onNoMessageTimeoutChange(self, evt):
self.messageTimeoutEdit.Enable(not evt.IsChecked())
def showStartErrorForProviders(
parent: wx.Window,
providers: List[vision.providerInfo.ProviderInfo],
) -> None:
if not providers:
return
if len(providers) == 1:
providerName = providers[0].displayName
message = _("Could not load the {providerName} vision enhancement provider").format(
providerName=providerName
)
else:
providerNames = ", ".join(provider.displayName for provider in providers)
message = _("Could not load the following vision enhancement providers:\n{providerNames}").format(
providerNames=providerNames
)
gui.messageBox(
message,
_("Vision Enhancement Provider Error"),
wx.OK | wx.ICON_WARNING,
parent,
)
def showTerminationErrorForProviders(
parent: wx.Window,
providers: List[vision.providerInfo.ProviderInfo],
) -> None:
if not providers:
return
if len(providers) == 1:
providerName = providers[0].displayName
message = _("Could not gracefully terminate the {providerName} vision enhancement provider").format(
providerName=providerName
)
else:
providerNames = ", ".join(provider.displayName for provider in providers)
message = _(
"Could not gracefully terminate the following vision enhancement providers:\n"
"{providerNames}"
).format(providerNames=providerNames)
gui.messageBox(
message,
_("Vision Enhancement Provider Error"),
wx.OK | wx.ICON_WARNING,
parent,
)
class VisionProviderStateControl(vision.providerBase.VisionProviderStateControl):
def __init__(
self,
parent: wx.Window,
providerInfo: vision.providerInfo.ProviderInfo
):
self._providerInfo = providerInfo
self._parent = weakref.ref(parent)
def getProviderInfo(self) -> vision.providerInfo.ProviderInfo:
return self._providerInfo
def getProviderInstance(self) -> Optional[vision.providerBase.VisionEnhancementProvider]:
return vision.handler.getProviderInstance(self._providerInfo)
def startProvider(
self,
shouldPromptOnError: bool = True
) -> bool:
success = self._doStartProvider()
if not success and shouldPromptOnError:
showStartErrorForProviders(self._parent(), [self._providerInfo, ])
return success
def terminateProvider(
self,
shouldPromptOnError: bool = True
) -> bool:
success = self._doTerminate()
if not success and shouldPromptOnError:
showTerminationErrorForProviders(self._parent(), [self._providerInfo, ])
return success
def _doStartProvider(self) -> bool:
try:
vision.handler.initializeProvider(self._providerInfo)
return True
except Exception:
log.error(
f"Could not initialize the {self._providerInfo.providerId} vision enhancement provider",
exc_info=True
)
return False
def _doTerminate(self) -> bool:
try:
# Terminating a provider from the gui should never save the settings.
# This is because termination happens on the fly when unchecking check boxes.
# Saving settings would be harmful if a user opens the vision panel,
# then changes some settings and disables the provider.
vision.handler.terminateProvider(self._providerInfo, saveSettings=False)
return True
except Exception:
log.error(
f"Could not terminate the {self._providerInfo.providerId} vision enhancement provider",
exc_info=True
)
return False
class VisionSettingsPanel(SettingsPanel):
settingsSizerHelper: guiHelper.BoxSizerHelper
providerPanelInstances: List[SettingsPanel]
initialProviders: List[vision.providerInfo.ProviderInfo]
# Translators: This is the label for the vision panel
title = _("Vision")
# Translators: This is a label appearing on the vision settings panel.
panelDescription = _("Configure visual aids.")
def _createProviderSettingsPanel(
self,
providerInfo: vision.providerInfo.ProviderInfo
) -> Optional[SettingsPanel]:
settingsPanelCls = providerInfo.providerClass.getSettingsPanelClass()
if not settingsPanelCls:
if gui._isDebug():
log.debug(f"Using default panel for providerId: {providerInfo.providerId}")
settingsPanelCls = VisionProviderSubPanel_Wrapper
else:
if gui._isDebug():
log.debug(f"Using custom panel for providerId: {providerInfo.providerId}")
providerControl = VisionProviderStateControl(parent=self, providerInfo=providerInfo)
try:
return settingsPanelCls(
parent=self,
providerControl=providerControl
)
# Broad except used since we can not know what exceptions a provider might throw.
# We should be able to continue despite a buggy provider.
except Exception:
log.debug(f"Error creating providerPanel: {settingsPanelCls!r}", exc_info=True)
return None
def makeSettings(self, settingsSizer: wx.BoxSizer):
self.initialProviders = vision.handler.getActiveProviderInfos()
self.providerPanelInstances = []
self.settingsSizerHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
self.settingsSizerHelper.addItem(wx.StaticText(self, label=self.panelDescription))
for providerInfo in vision.handler.getProviderList(reloadFromSystem=True):
providerSizer = self.settingsSizerHelper.addItem(
wx.StaticBoxSizer(wx.StaticBox(self, label=providerInfo.displayName), wx.VERTICAL),
flag=wx.EXPAND
)
if len(self.providerPanelInstances) > 0:
settingsSizer.AddSpacer(guiHelper.SPACE_BETWEEN_VERTICAL_DIALOG_ITEMS)
settingsPanel = self._createProviderSettingsPanel(providerInfo)
if not settingsPanel:
continue
providerSizer.Add(settingsPanel, flag=wx.EXPAND)
self.providerPanelInstances.append(settingsPanel)
def safeInitProviders(
self,
providers: List[vision.providerInfo.ProviderInfo]
) -> None:
errorProviders: List[vision.providerInfo.ProviderInfo] = []
for provider in providers:
success = VisionProviderStateControl(self, provider).startProvider(shouldPromptOnError=False)
if not success:
errorProviders.append(provider)
showStartErrorForProviders(self, errorProviders)
def safeTerminateProviders(
self,
providers: List[vision.providerInfo.ProviderInfo],
verbose: bool = False
) -> None:
errorProviders: List[vision.providerInfo.ProviderInfo] = []
for provider in providers:
success = VisionProviderStateControl(self, provider).terminateProvider(shouldPromptOnError=False)
if not success:
errorProviders.append(provider)
if verbose:
showTerminationErrorForProviders(self, errorProviders)
def refreshPanel(self):
self.Freeze()
# trigger a refresh of the settings
self.onPanelActivated()
self._sendLayoutUpdatedEvent()
self.Thaw()
def onPanelActivated(self):
super().onPanelActivated()
def onDiscard(self):
for panel in self.providerPanelInstances:
try:
panel.onDiscard()
# Broad except used since we can not know what exceptions a provider might throw.
# We should be able to continue despite a buggy provider.
except Exception:
log.debug(f"Error discarding providerPanel: {panel.__class__!r}", exc_info=True)
providersToInitialize = [
provider for provider in self.initialProviders
if not bool(vision.handler.getProviderInstance(provider))
]
self.safeInitProviders(providersToInitialize)
initialProviderIds = [
providerInfo.providerId for providerInfo in self.initialProviders
]
providersToTerminate = [
provider for provider in vision.handler.getActiveProviderInfos()
if provider.providerId not in initialProviderIds
]
self.safeTerminateProviders(providersToTerminate)
def onSave(self):
for panel in self.providerPanelInstances:
try:
panel.onSave()
# Broad except used since we can not know what exceptions a provider might throw.
# We should be able to continue despite a buggy provider.
except Exception:
log.debug(f"Error saving providerPanel: {panel.__class__!r}", exc_info=True)
self.initialProviders = vision.handler.getActiveProviderInfos()
class VisionProviderSubPanel_Settings(
AutoSettingsMixin,
SettingsPanel
):
_settingsCallable: Callable[[], VisionEnhancementProviderSettings]
def __init__(
self,
parent: wx.Window,
*, # Make next argument keyword only
settingsCallable: Callable[[], vision.providerBase.VisionEnhancementProviderSettings]
):
self._settingsCallable = settingsCallable
super().__init__(parent=parent)
def getSettings(self) -> AutoSettings:
settings = self._settingsCallable()
return settings
def makeSettings(self, settingsSizer):
# Construct vision enhancement provider settings
self.updateDriverSettings()
class VisionProviderSubPanel_Wrapper(
SettingsPanel
):
_checkBox: wx.CheckBox
def __init__(
self,
parent: wx.Window,
providerControl: VisionProviderStateControl
):
self._providerControl = providerControl
self._providerSettings: Optional[VisionProviderSubPanel_Settings] = None
self._providerSettingsSizer = wx.BoxSizer(orient=wx.VERTICAL)
super().__init__(parent=parent)
def makeSettings(self, settingsSizer):
self._checkBox = wx.CheckBox(
self,
# Translators: Enable checkbox on a vision enhancement provider on the vision settings category panel
label=_("Enable")
)
settingsSizer.Add(self._checkBox)
self._optionsSizer = wx.BoxSizer(orient=wx.VERTICAL)
self._optionsSizer.AddSpacer(size=self.scaleSize(10))
# Translators: Options label on a vision enhancement provider on the vision settings category panel
self._optionsText = wx.StaticText(self, label=_("Options:"))
self._optionsSizer.Add(self._optionsText)
self._optionsSizer.Add(
self._providerSettingsSizer,
border=self.scaleSize(15),
flag=wx.LEFT | wx.EXPAND,
proportion=1.0
)
settingsSizer.Add(
self._optionsSizer,
flag=wx.EXPAND,
proportion=1.0
)
self._checkBox.SetValue(bool(self._providerControl.getProviderInstance()))
if self._createProviderSettings():
self._checkBox.Bind(wx.EVT_CHECKBOX, self._enableToggle)
else:
self._checkBox.Bind(wx.EVT_CHECKBOX, self._nonEnableableGUI)
self._updateOptionsVisibility()
def _updateOptionsVisibility(self):
hasProviderOptions = bool(self._providerSettings) and self._providerSettings.hasOptions
if hasProviderOptions:
self.settingsSizer.Show(self._optionsSizer, recursive=True)
else:
self.settingsSizer.Hide(self._optionsSizer, recursive=True)
self._sendLayoutUpdatedEvent()
def _createProviderSettings(self):
try:
getSettingsCallable = self._providerControl.getProviderInfo().providerClass.getSettings
self._providerSettings = VisionProviderSubPanel_Settings(
self,
settingsCallable=getSettingsCallable
)
self._providerSettingsSizer.Add(self._providerSettings, flag=wx.EXPAND, proportion=1.0)
# Broad except used since we can not know what exceptions a provider might throw.
# We should be able to continue despite a buggy provider.
except Exception:
log.error("unable to create provider settings", exc_info=True)
return False
return True
def _nonEnableableGUI(self, evt):
gui.messageBox(
# Translators: Shown when there is an error showing the GUI for a vision enhancement provider
_("Unable to configure user interface for Vision Enhancement Provider, it can not be enabled."),
# Translators: The title of the error dialog displayed when there is an error showing the GUI
# for a vision enhancement provider
_("Error"),
parent=self,
)
self._checkBox.SetValue(False)
def _enableToggle(self, evt):
shouldBeRunning = evt.IsChecked()
if shouldBeRunning and not self._providerControl.startProvider():
self._checkBox.SetValue(False)
self._updateOptionsVisibility()
return
elif not shouldBeRunning and not self._providerControl.terminateProvider():
# When there is an error on termination, don't leave the checkbox checked.
self._checkBox.SetValue(False)
self._updateOptionsVisibility()
return
self._providerSettings.updateDriverSettings()
self._providerSettings.refreshGui()
self._updateOptionsVisibility()
def onDiscard(self):
if self._providerSettings:
self._providerSettings.onDiscard()
def onSave(self):
log.debug(f"calling VisionProviderSubPanel_Wrapper")
if self._providerSettings:
self._providerSettings.onSave()
NvdaSettingsDialogActiveConfigProfile = None
NvdaSettingsDialogWindowHandle = None
class NVDASettingsDialog(MultiCategorySettingsDialog):
title = _("NVDA Settings")
categoryClasses=[
GeneralSettingsPanel,
SpeechSettingsPanel,
BrailleSettingsPanel,
VisionSettingsPanel,
KeyboardSettingsPanel,
MouseSettingsPanel,
ReviewCursorPanel,
InputCompositionPanel,
ObjectPresentationPanel,
BrowseModePanel,
DocumentFormattingPanel,
]
if touchHandler.touchSupported():
categoryClasses.append(TouchInteractionPanel)
if winVersion.isUwpOcrAvailable():
categoryClasses.append(UwpOcrPanel)
if not globalVars.appArgs.secure:
categoryClasses.append(AdvancedPanel)
def makeSettings(self, settingsSizer):
super(NVDASettingsDialog, self).makeSettings(settingsSizer)
self._doOnCategoryChange()
global NvdaSettingsDialogWindowHandle
NvdaSettingsDialogWindowHandle = self.GetHandle()
def _doOnCategoryChange(self):
global NvdaSettingsDialogActiveConfigProfile
NvdaSettingsDialogActiveConfigProfile = config.conf.profiles[-1].name
if not NvdaSettingsDialogActiveConfigProfile or isinstance(self.currentCategory, GeneralSettingsPanel):
NvdaSettingsDialogActiveConfigProfile = _("normal configuration")
self.SetTitle(self._getDialogTitle())
self.bindHelpEvent(
self.currentCategory.helpId,
self.catListCtrl
)
def _getDialogTitle(self):
return u"{dialogTitle}: {panelTitle} ({configProfile})".format(
dialogTitle=self.title,
panelTitle=self.currentCategory.title,
configProfile=NvdaSettingsDialogActiveConfigProfile
)
def onCategoryChange(self,evt):
super(NVDASettingsDialog,self).onCategoryChange(evt)
if evt.Skipped:
return
self._doOnCategoryChange()
def Destroy(self):
global NvdaSettingsDialogActiveConfigProfile, NvdaSettingsDialogWindowHandle
NvdaSettingsDialogActiveConfigProfile = None
NvdaSettingsDialogWindowHandle = None
super(NVDASettingsDialog, self).Destroy()
class AddSymbolDialog(
gui.ContextHelpMixin,
wx.Dialog
):
helpId = "SymbolPronunciation"
def __init__(self, parent):
super().__init__(parent, title=_("Add Symbol"))
mainSizer=wx.BoxSizer(wx.VERTICAL)
sHelper = guiHelper.BoxSizerHelper(self, orientation=wx.VERTICAL)
symbolText = _("&Symbol:")
self.identifierTextCtrl = sHelper.addLabeledControl(symbolText, wx.TextCtrl)
sHelper.addDialogDismissButtons(self.CreateButtonSizer(wx.OK | wx.CANCEL))
mainSizer.Add(sHelper.sizer, border=guiHelper.BORDER_FOR_DIALOGS, flag=wx.ALL)
mainSizer.Fit(self)
self.SetSizer(mainSizer)
self.identifierTextCtrl.SetFocus()
self.CentreOnScreen()
class SpeechSymbolsDialog(SettingsDialog):
helpId = "SymbolPronunciation"
def __init__(self,parent):
try:
symbolProcessor = characterProcessing._localeSpeechSymbolProcessors.fetchLocaleData(speech.getCurrentLanguage())
except LookupError:
symbolProcessor = characterProcessing._localeSpeechSymbolProcessors.fetchLocaleData("en")
self.symbolProcessor = symbolProcessor
self.title = _("Symbol Pronunciation (%s)")%languageHandler.getLanguageDescription(self.symbolProcessor.locale)
super(SpeechSymbolsDialog, self).__init__(
parent,
resizeable=True,
)
def makeSettings(self, settingsSizer):
self.filteredSymbols = self.symbols = [
copy.copy(symbol) for symbol in self.symbolProcessor.computedSymbols.values()
]
self.pendingRemovals = {}
sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
filterText = pgettext("speechSymbols", "&Filter by:")
self.filterEdit = sHelper.addLabeledControl(
labelText = filterText,
wxCtrlClass=wx.TextCtrl,
size=(self.scaleSize(310), -1),
)
self.filterEdit.Bind(wx.EVT_TEXT, self.onFilterEditTextChange)
symbolsText = _("&Symbols")
self.symbolsList = sHelper.addLabeledControl(
symbolsText,
nvdaControls.AutoWidthColumnListCtrl,
autoSizeColumn=2,
itemTextCallable=self.getItemTextForList,
style=wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_VIRTUAL
)
self.symbolsList.InsertColumn(0, _("Symbol"), width=self.scaleSize(150))
self.symbolsList.InsertColumn(1, _("Replacement"))
self.symbolsList.InsertColumn(2, _("Level"))
# Translators: The label for a column in symbols list which specifies when the actual symbol will be sent to the synthesizer (preserved).
# See the "Punctuation/Symbol Pronunciation" section of the User Guide for details.
self.symbolsList.InsertColumn(3, _("Preserve"))
self.symbolsList.Bind(wx.EVT_LIST_ITEM_FOCUSED, self.onListItemFocused)
# Translators: The label for the group of controls in symbol pronunciation dialog to change the pronunciation of a symbol.
changeSymbolText = _("Change selected symbol")
changeSymbolHelper = sHelper.addItem(guiHelper.BoxSizerHelper(
parent=self,
sizer=wx.StaticBoxSizer(
parent=self,
label=changeSymbolText,
orient=wx.VERTICAL,
)
))
# Used to ensure that event handlers call Skip(). Not calling skip can cause focus problems for controls. More
# generally the advice on the wx documentation is: "In general, it is recommended to skip all non-command events
# to allow the default handling to take place. The command events are, however, normally not skipped as usually
# a single command such as a button click or menu item selection must only be processed by one handler."
def skipEventAndCall(handler):
def wrapWithEventSkip(event):
if event:
event.Skip()
return handler()
return wrapWithEventSkip
# Translators: The label for the edit field in symbol pronunciation dialog to change the replacement text of a symbol.
replacementText = _("&Replacement")
self.replacementEdit = changeSymbolHelper.addLabeledControl(
labelText=replacementText,
wxCtrlClass=wx.TextCtrl,
size=(self.scaleSize(300), -1),
)
self.replacementEdit.Bind(wx.EVT_TEXT, skipEventAndCall(self.onSymbolEdited))
# Translators: The label for the combo box in symbol pronunciation dialog to change the speech level of a symbol.
levelText = _("&Level")
symbolLevelLabels = characterProcessing.SPEECH_SYMBOL_LEVEL_LABELS
levelChoices = [symbolLevelLabels[level] for level in characterProcessing.SPEECH_SYMBOL_LEVELS]
self.levelList = changeSymbolHelper.addLabeledControl(levelText, wx.Choice, choices=levelChoices)
self.levelList.Bind(wx.EVT_CHOICE, skipEventAndCall(self.onSymbolEdited))
# Translators: The label for the combo box in symbol pronunciation dialog to change when a symbol is sent to the synthesizer.
preserveText = _("&Send actual symbol to synthesizer")
symbolPreserveLabels = characterProcessing.SPEECH_SYMBOL_PRESERVE_LABELS
preserveChoices = [symbolPreserveLabels[mode] for mode in characterProcessing.SPEECH_SYMBOL_PRESERVES]
self.preserveList = changeSymbolHelper.addLabeledControl(preserveText, wx.Choice, choices=preserveChoices)
self.preserveList.Bind(wx.EVT_CHOICE, skipEventAndCall(self.onSymbolEdited))
bHelper = sHelper.addItem(guiHelper.ButtonHelper(orientation=wx.HORIZONTAL))
# Translators: The label for a button in the Symbol Pronunciation dialog to add a new symbol.
addButton = bHelper.addButton(self, label=_("&Add"))
# Translators: The label for a button in the Symbol Pronunciation dialog to remove a symbol.
self.removeButton = bHelper.addButton(self, label=_("Re&move"))
self.removeButton.Disable()
addButton.Bind(wx.EVT_BUTTON, self.OnAddClick)
self.removeButton.Bind(wx.EVT_BUTTON, self.OnRemoveClick)
# Populate the unfiltered list with symbols.
self.filter()
def postInit(self):
self.symbolsList.SetFocus()
def filter(self, filterText=''):
NONE_SELECTED = -1
previousSelectionValue = None
previousIndex = self.symbolsList.GetFirstSelected() # may return NONE_SELECTED
if previousIndex != NONE_SELECTED:
previousSelectionValue = self.filteredSymbols[previousIndex]
if not filterText:
self.filteredSymbols = self.symbols
else:
# Do case-insensitive matching by lowering both filterText and each symbols's text.
filterText = filterText.lower()
self.filteredSymbols = [
symbol for symbol in self.symbols
if filterText in symbol.displayName.lower()
or filterText in symbol.replacement.lower()
]
self.symbolsList.ItemCount = len(self.filteredSymbols)
if not self.symbolsList.ItemCount:
self.editingItem = None
self.replacementEdit.Disable()
self.levelList.Disable()
self.preserveList.Disable()
self.removeButton.Disable()
return
newIndex = 0
if previousSelectionValue:
try:
newIndex = self.filteredSymbols.index(previousSelectionValue)
except ValueError:
pass
self.symbolsList.Select(newIndex)
self.symbolsList.Focus(newIndex)
self.symbolsList.sendListItemFocusedEvent(newIndex)
def getItemTextForList(self, item, column):
symbol = self.filteredSymbols[item]
if column == 0:
return symbol.displayName
elif column == 1:
return symbol.replacement
elif column == 2:
return characterProcessing.SPEECH_SYMBOL_LEVEL_LABELS[symbol.level]
elif column == 3:
return characterProcessing.SPEECH_SYMBOL_PRESERVE_LABELS[symbol.preserve]
else:
raise ValueError("Unknown column: %d" % column)
def onSymbolEdited(self):
if self.editingItem is not None:
# Update the symbol the user was just editing.
item = self.editingItem
symbol = self.filteredSymbols[item]
symbol.replacement = self.replacementEdit.Value
symbol.level = characterProcessing.SPEECH_SYMBOL_LEVELS[self.levelList.Selection]
symbol.preserve = characterProcessing.SPEECH_SYMBOL_PRESERVES[self.preserveList.Selection]
def onListItemFocused(self, evt):
# Update the editing controls to reflect the newly selected symbol.
item = evt.GetIndex()
symbol = self.filteredSymbols[item]
self.editingItem = item
# ChangeValue and Selection property used because they do not cause EVNT_CHANGED to be fired.
self.replacementEdit.ChangeValue(symbol.replacement)
self.levelList.Selection = characterProcessing.SPEECH_SYMBOL_LEVELS.index(symbol.level)
self.preserveList.Selection = characterProcessing.SPEECH_SYMBOL_PRESERVES.index(symbol.preserve)
self.removeButton.Enabled = not self.symbolProcessor.isBuiltin(symbol.identifier)
self.replacementEdit.Enable()
self.levelList.Enable()
self.preserveList.Enable()
evt.Skip()
def OnAddClick(self, evt):
with AddSymbolDialog(self) as entryDialog:
if entryDialog.ShowModal() != wx.ID_OK:
return
identifier = entryDialog.identifierTextCtrl.GetValue()
if not identifier:
return
# Clean the filter, so we can select the new entry.
self.filterEdit.Value=""
self.filter()
for index, symbol in enumerate(self.symbols):
if identifier == symbol.identifier:
# Translators: An error reported in the Symbol Pronunciation dialog when adding a symbol that is already present.
gui.messageBox(_('Symbol "%s" is already present.') % identifier,
_("Error"), wx.OK | wx.ICON_ERROR)
self.symbolsList.Select(index)
self.symbolsList.Focus(index)
self.symbolsList.SetFocus()
return
addedSymbol = characterProcessing.SpeechSymbol(identifier)
try:
del self.pendingRemovals[identifier]
except KeyError:
pass
addedSymbol.displayName = identifier
addedSymbol.replacement = ""
addedSymbol.level = characterProcessing.SYMLVL_ALL
addedSymbol.preserve = characterProcessing.SYMPRES_NEVER
self.symbols.append(addedSymbol)
self.symbolsList.ItemCount = len(self.symbols)
index = self.symbolsList.ItemCount - 1
self.symbolsList.Select(index)
self.symbolsList.Focus(index)
# We don't get a new focus event with the new index.
self.symbolsList.sendListItemFocusedEvent(index)
self.symbolsList.SetFocus()
def OnRemoveClick(self, evt):
index = self.symbolsList.GetFirstSelected()
symbol = self.filteredSymbols[index]
self.pendingRemovals[symbol.identifier] = symbol
del self.filteredSymbols[index]
if self.filteredSymbols is not self.symbols:
self.symbols.remove(symbol)
self.symbolsList.ItemCount = len(self.filteredSymbols)
if not self.symbolsList.ItemCount:
self.editingItem = None
self.replacementEdit.Disable()
self.levelList.Disable()
self.preserveList.Disable()
self.removeButton.Disable()
else:
index = min(index, self.symbolsList.ItemCount - 1)
self.symbolsList.Select(index)
self.symbolsList.Focus(index)
self.symbolsList.sendListItemFocusedEvent(index)
self.symbolsList.SetFocus()
def onOk(self, evt):
self.onSymbolEdited()
self.editingItem = None
for symbol in self.pendingRemovals.values():
self.symbolProcessor.deleteSymbol(symbol)
for symbol in self.symbols:
if not symbol.replacement:
continue
self.symbolProcessor.updateSymbol(symbol)
try:
self.symbolProcessor.userSymbols.save()
except IOError as e:
log.error("Error saving user symbols info: %s" % e)
characterProcessing._localeSpeechSymbolProcessors.invalidateLocaleData(self.symbolProcessor.locale)
super(SpeechSymbolsDialog, self).onOk(evt)
def _refreshVisibleItems(self):
count = self.symbolsList.GetCountPerPage()
first = self.symbolsList.GetTopItem()
self.symbolsList.RefreshItems(first, first+count)
def onFilterEditTextChange(self, evt):
self.filter(self.filterEdit.Value)
self._refreshVisibleItems()
evt.Skip()
| true | true |
f72819ff76d7fcc07036a600247241e818622725 | 2,222 | py | Python | ckanext/harvest/logic/action/patch.py | alphagov-mirror/ckanext-harvest | be4d134cf2e4d4548c67dc2f61b200948f0f74e0 | [
"PostgreSQL"
] | 86 | 2015-01-09T19:21:20.000Z | 2022-03-23T07:17:27.000Z | ckanext/harvest/logic/action/patch.py | alphagov-mirror/ckanext-harvest | be4d134cf2e4d4548c67dc2f61b200948f0f74e0 | [
"PostgreSQL"
] | 319 | 2015-01-13T13:40:08.000Z | 2022-03-24T12:13:42.000Z | ckanext/harvest/logic/action/patch.py | alphagov-mirror/ckanext-harvest | be4d134cf2e4d4548c67dc2f61b200948f0f74e0 | [
"PostgreSQL"
] | 154 | 2015-01-13T21:06:03.000Z | 2022-03-15T12:10:57.000Z | '''API functions for partial updates of existing data in CKAN'''
import logging
from ckan.logic import get_action
from ckanext.harvest.utils import (
DATASET_TYPE_NAME
)
log = logging.getLogger(__name__)
def harvest_source_patch(context, data_dict):
'''
Patch an existing harvest source
This method just proxies the request to package_patch, which will update a
harvest_source dataset type and the HarvestSource object. All auth checks
and validation will be done there. We only make sure to set the dataset
type.
Note that the harvest source type (ckan, waf, csw, etc) is now set via the
source_type field.
All fields that are not provided, will be stay as they were before.
:param id: the name or id of the harvest source to update
:type id: string
:param url: the URL for the harvest source
:type url: string
:param name: the name of the new harvest source, must be between 2 and 100
characters long and contain only lowercase alphanumeric characters
:type name: string
:param title: the title of the dataset (optional, default: same as
``name``)
:type title: string
:param notes: a description of the harvest source (optional)
:type notes: string
:param source_type: the harvester type for this source. This must be one
of the registerd harvesters, eg 'ckan', 'csw', etc.
:type source_type: string
:param frequency: the frequency in wich this harvester should run. See
``ckanext.harvest.model`` source for possible values. Default is
'MANUAL'
:type frequency: string
:param config: extra configuration options for the particular harvester
type. Should be a serialized as JSON. (optional)
:type config: string
:returns: the updated harvest source
:rtype: dictionary
'''
log.info('Patch harvest source: %r', data_dict)
data_dict['type'] = DATASET_TYPE_NAME
context['extras_as_string'] = True
try:
source = get_action('package_patch')(context, data_dict)
except KeyError:
raise Exception('The harvest_source_patch action is not available on '
'this version of CKAN')
return source
| 34.71875 | 78 | 0.69982 |
import logging
from ckan.logic import get_action
from ckanext.harvest.utils import (
DATASET_TYPE_NAME
)
log = logging.getLogger(__name__)
def harvest_source_patch(context, data_dict):
log.info('Patch harvest source: %r', data_dict)
data_dict['type'] = DATASET_TYPE_NAME
context['extras_as_string'] = True
try:
source = get_action('package_patch')(context, data_dict)
except KeyError:
raise Exception('The harvest_source_patch action is not available on '
'this version of CKAN')
return source
| true | true |
f7281be3f98ed8313aadea4a83e9992b64fdadbd | 4,090 | py | Python | src/analysis.py | alexissavva/NLP | 100963e96ebd6aae26027c2f13f42675dbd5ed9f | [
"MIT"
] | 31 | 2019-07-28T07:56:29.000Z | 2022-03-24T17:54:11.000Z | src/analysis.py | alexissavva/NLP | 100963e96ebd6aae26027c2f13f42675dbd5ed9f | [
"MIT"
] | 10 | 2020-08-04T05:07:32.000Z | 2021-11-27T17:00:58.000Z | src/analysis.py | alexissavva/NLP | 100963e96ebd6aae26027c2f13f42675dbd5ed9f | [
"MIT"
] | 22 | 2019-06-11T14:56:55.000Z | 2021-11-04T13:01:33.000Z | """ Usage:
<file-name> --in=IN_FILE --out=OUT_FILE [--debug]
"""
# External imports
import logging
import pdb
from pprint import pprint
from pprint import pformat
from docopt import docopt
from collections import defaultdict
from operator import itemgetter
from tqdm import tqdm
# Local imports
#=-----
def get_predicted_gender(spanish_sent):
"""
Return the gender of the first entity in the spanish
translation.
"""
first_word = spanish_sent.split()[0].lower()
if first_word == "el":
return "male"
elif first_word == "la":
return "female"
else:
return "neutral"
def percentage(part, total):
"""
Calculate percentage.
"""
return (part / total) * 100
if __name__ == "__main__":
# Parse command line arguments
args = docopt(__doc__)
inp_fn = args["--in"]
out_fn = args["--out"]
debug = args["--debug"]
if debug:
logging.basicConfig(level = logging.DEBUG)
else:
logging.basicConfig(level = logging.INFO)
prof_dict = defaultdict(list)
conf_dict = defaultdict(lambda: defaultdict(lambda: 0))
total = defaultdict(lambda: 0)
pred_cnt = defaultdict(lambda: 0)
correct_cnt = defaultdict(lambda: 0)
lines = [line for line in open(inp_fn, encoding = "utf8")][1:]
with open(out_fn, "w", encoding = "utf8") as fout:
for line in lines:
logging.debug(line)
sent_id, en_sent, es_sent = line.strip().split("\t")
profession, _, _, gold_gender, _ = sent_id.split(".")
fout.write(f"{en_sent} ||| {es_sent}\n")
if ".0." not in line:
continue
total[gold_gender] += 1
pred_gender = get_predicted_gender(es_sent)
if pred_gender == gold_gender:
correct_cnt[gold_gender] += 1
pred_cnt[pred_gender] += 1
prof_dict[profession].append((pred_gender, gold_gender))
conf_dict[gold_gender][pred_gender] += 1
prof_dict = dict(prof_dict)
all_total = sum(total.values())
acc = round((sum(correct_cnt.values()) / all_total) * 100, 2)
acc_male = round((correct_cnt["male"] / total["male"]) * 100, 2)
acc_female = round((correct_cnt["female"] / total["female"]) * 100, 2)
print(f"#total = {all_total}; \n acc = {acc}%; acc_male = {acc_male}; acc_female = {acc_female}")
print("Gold distribution: male: {}, female: {}, neutral: {}".format(round(percentage(total["male"], all_total), 2),
round(percentage(total["female"], all_total),2),
round(percentage(total["neutral"], all_total)),2))
print("Predictions: male: {}, female: {}, neutral: {}".format(round((pred_cnt["male"] / all_total) * 100, 2),
round((pred_cnt["female"] / all_total) * 100, 2),
round((pred_cnt["neutral"] / all_total) * 100, 2)))
male_prof = [prof for prof, vals in prof_dict.items()
if all(pred_gender == "male"
for pred_gender
in map(itemgetter(0), vals))]
female_prof = [prof for prof, vals in prof_dict.items()
if all(pred_gender == "female"
for pred_gender
in map(itemgetter(0), vals))]
neutral_prof = [prof for prof, vals in prof_dict.items()
if all(pred_gender == "neutral"
for pred_gender
in map(itemgetter(0), vals))]
amb_prof = [prof for prof, vals in prof_dict.items()
if len(set(map(itemgetter(0), vals))) != 1]
print(f"male professions = {male_prof}")
print(f"female professions = {female_prof}")
print(f"neutral professions = {neutral_prof}")
print(f"ambiguous professions = {amb_prof}")
pprint(conf_dict)
logging.info("DONE")
| 34.083333 | 122 | 0.555746 |
import logging
import pdb
from pprint import pprint
from pprint import pformat
from docopt import docopt
from collections import defaultdict
from operator import itemgetter
from tqdm import tqdm
def get_predicted_gender(spanish_sent):
first_word = spanish_sent.split()[0].lower()
if first_word == "el":
return "male"
elif first_word == "la":
return "female"
else:
return "neutral"
def percentage(part, total):
return (part / total) * 100
if __name__ == "__main__":
args = docopt(__doc__)
inp_fn = args["--in"]
out_fn = args["--out"]
debug = args["--debug"]
if debug:
logging.basicConfig(level = logging.DEBUG)
else:
logging.basicConfig(level = logging.INFO)
prof_dict = defaultdict(list)
conf_dict = defaultdict(lambda: defaultdict(lambda: 0))
total = defaultdict(lambda: 0)
pred_cnt = defaultdict(lambda: 0)
correct_cnt = defaultdict(lambda: 0)
lines = [line for line in open(inp_fn, encoding = "utf8")][1:]
with open(out_fn, "w", encoding = "utf8") as fout:
for line in lines:
logging.debug(line)
sent_id, en_sent, es_sent = line.strip().split("\t")
profession, _, _, gold_gender, _ = sent_id.split(".")
fout.write(f"{en_sent} ||| {es_sent}\n")
if ".0." not in line:
continue
total[gold_gender] += 1
pred_gender = get_predicted_gender(es_sent)
if pred_gender == gold_gender:
correct_cnt[gold_gender] += 1
pred_cnt[pred_gender] += 1
prof_dict[profession].append((pred_gender, gold_gender))
conf_dict[gold_gender][pred_gender] += 1
prof_dict = dict(prof_dict)
all_total = sum(total.values())
acc = round((sum(correct_cnt.values()) / all_total) * 100, 2)
acc_male = round((correct_cnt["male"] / total["male"]) * 100, 2)
acc_female = round((correct_cnt["female"] / total["female"]) * 100, 2)
print(f"#total = {all_total}; \n acc = {acc}%; acc_male = {acc_male}; acc_female = {acc_female}")
print("Gold distribution: male: {}, female: {}, neutral: {}".format(round(percentage(total["male"], all_total), 2),
round(percentage(total["female"], all_total),2),
round(percentage(total["neutral"], all_total)),2))
print("Predictions: male: {}, female: {}, neutral: {}".format(round((pred_cnt["male"] / all_total) * 100, 2),
round((pred_cnt["female"] / all_total) * 100, 2),
round((pred_cnt["neutral"] / all_total) * 100, 2)))
male_prof = [prof for prof, vals in prof_dict.items()
if all(pred_gender == "male"
for pred_gender
in map(itemgetter(0), vals))]
female_prof = [prof for prof, vals in prof_dict.items()
if all(pred_gender == "female"
for pred_gender
in map(itemgetter(0), vals))]
neutral_prof = [prof for prof, vals in prof_dict.items()
if all(pred_gender == "neutral"
for pred_gender
in map(itemgetter(0), vals))]
amb_prof = [prof for prof, vals in prof_dict.items()
if len(set(map(itemgetter(0), vals))) != 1]
print(f"male professions = {male_prof}")
print(f"female professions = {female_prof}")
print(f"neutral professions = {neutral_prof}")
print(f"ambiguous professions = {amb_prof}")
pprint(conf_dict)
logging.info("DONE")
| true | true |
f7281ccc6ccc63337bc1c58b6dcc69dfa0697200 | 4,863 | py | Python | lex2/textio/_textio.py | DeltaRazero/liblexer2-python3 | 43a1a63ee005da8a6936665cb27f4ced8158ed6c | [
"Zlib"
] | 1 | 2020-10-31T13:14:45.000Z | 2020-10-31T13:14:45.000Z | lex2/textio/_textio.py | DeltaRazero/liblexer2-python3 | 43a1a63ee005da8a6936665cb27f4ced8158ed6c | [
"Zlib"
] | 4 | 2020-10-28T16:21:22.000Z | 2020-11-09T21:02:33.000Z | lex2/textio/_textio.py | DeltaRazero/liblexer2-python3 | 43a1a63ee005da8a6936665cb27f4ced8158ed6c | [
"Zlib"
] | null | null | null | """<internal>"""
'''
zlib License
(C) 2020-2022 DeltaRazero
All rights reserved.
'''
# ***************************************************************************************
class __:
'<imports>'
import abc
import pathlib as pl
import typing as t
from ._textstream_core import (
ITextstream,
)
from ._textstream_disk import TextstreamDisk
from ._textstream_memory import TextstreamMemory
# ***************************************************************************************
DEFAULT_BUFFER_SIZE = 512
# ***************************************************************************************
class ITextIO (metaclass=__.abc.ABCMeta):
"""Interface to a class implementing TextIO functionality.
"""
# :: INTERFACE METHODS :: #
@__.abc.abstractmethod
def open(self,
fp: __.t.Union[str, __.pl.Path],
buffer_size: int=DEFAULT_BUFFER_SIZE,
encoding: str="UTF-8",
convert_line_endings: bool=True
) -> None:
"""Opens a textfile.
Parameters
----------
fp : str | Path
String or Path object of a text file to open.
buffer_size : int, optional
Size of the buffer in kilobytes (kB). A size of zero (0) allocates the whole
file into memory.
Keep in mind that in order to completely capture a token, it must be smaller
or equal to the size allocated to the buffer by this argument. Note that the
buffer size will be floored to the nearest even number.
encoding : str, optional
Encoding of the text file.
convert_line_endings : bool, optional
Convert line-endings from Windows style to UNIX style.
"""
...
@__.abc.abstractmethod
def load(self, str_data: str, convert_line_endings: bool=False) -> None:
"""Load string data directly.
Parameters
----------
str_data : str
String data to directly load. Note that encoding depends on the system-wide
encoding.
convert_line_endings : bool, optional
Convert line-endings from Windows style to UNIX style.
"""
...
@__.abc.abstractmethod
def close(self) -> None:
"""Closes and deletes textstream resources.
"""
...
# ***************************************************************************************
class TextIO (ITextIO, metaclass=__.abc.ABCMeta):
"""Base class implementing ITextIO, providing TextIO functionality.
"""
# :: PROTECTED FIELDS :: #
_ts : __.ITextstream
# :: CONSTRUCTOR & DESTRUCTOR :: #
@__.abc.abstractmethod
def __init__(self) -> None:
"""TextIO object instance initializer.
"""
self._ts = None
return
def __del__(self) -> None:
self.close()
return
# :: INTERFACE METHODS :: #
def open(self,
fp: __.t.Union[str, __.pl.Path],
buffer_size: int=DEFAULT_BUFFER_SIZE,
encoding: str="UTF-8",
convert_line_endings: bool=True,
) -> None:
# Re-call method in case of string filepath
if (isinstance(fp, str)):
self.open(
fp=__.pl.Path(fp),
buffer_size=buffer_size,
encoding=encoding,
convert_line_endings=convert_line_endings,
)
return
self.close()
# Check if path exists and is file
if (not fp.is_file()):
raise FileNotFoundError(f'Not an existing file or is a directory: "{str(fp)}"')
# Buffersize is in units of kilobytes (kB)
buffer_size *= 1000
if (buffer_size < 0):
raise ValueError("buffer size cannot be a negative value")
if (buffer_size == 0):
with open(fp, "r", encoding=encoding) as f:
self._ts = __.TextstreamMemory(
str_data=f.read(),
convert_line_endings=convert_line_endings,
)
else:
self._ts = __.TextstreamDisk(
fp=fp,
buffer_size=buffer_size,
encoding=encoding,
convert_line_endings=convert_line_endings,
)
return
def load(self,
str_data: str,
convert_line_endings: bool=False
) -> None:
self.close()
self._ts = __.TextstreamMemory(
str_data=str_data,
convert_line_endings=convert_line_endings,
)
return
def close(self) -> None:
# Only close/cleanup if a textream is already instanced
if (self._ts):
self._ts.close()
del self._ts
self._ts = None
return
| 26.57377 | 91 | 0.518816 |
class __:
import abc
import pathlib as pl
import typing as t
from ._textstream_core import (
ITextstream,
)
from ._textstream_disk import TextstreamDisk
from ._textstream_memory import TextstreamMemory
DEFAULT_BUFFER_SIZE = 512
class ITextIO (metaclass=__.abc.ABCMeta):
@__.abc.abstractmethod
def open(self,
fp: __.t.Union[str, __.pl.Path],
buffer_size: int=DEFAULT_BUFFER_SIZE,
encoding: str="UTF-8",
convert_line_endings: bool=True
) -> None:
...
@__.abc.abstractmethod
def load(self, str_data: str, convert_line_endings: bool=False) -> None:
...
@__.abc.abstractmethod
def close(self) -> None:
...
class TextIO (ITextIO, metaclass=__.abc.ABCMeta):
_ts : __.ITextstream
@__.abc.abstractmethod
def __init__(self) -> None:
self._ts = None
return
def __del__(self) -> None:
self.close()
return
def open(self,
fp: __.t.Union[str, __.pl.Path],
buffer_size: int=DEFAULT_BUFFER_SIZE,
encoding: str="UTF-8",
convert_line_endings: bool=True,
) -> None:
if (isinstance(fp, str)):
self.open(
fp=__.pl.Path(fp),
buffer_size=buffer_size,
encoding=encoding,
convert_line_endings=convert_line_endings,
)
return
self.close()
if (not fp.is_file()):
raise FileNotFoundError(f'Not an existing file or is a directory: "{str(fp)}"')
buffer_size *= 1000
if (buffer_size < 0):
raise ValueError("buffer size cannot be a negative value")
if (buffer_size == 0):
with open(fp, "r", encoding=encoding) as f:
self._ts = __.TextstreamMemory(
str_data=f.read(),
convert_line_endings=convert_line_endings,
)
else:
self._ts = __.TextstreamDisk(
fp=fp,
buffer_size=buffer_size,
encoding=encoding,
convert_line_endings=convert_line_endings,
)
return
def load(self,
str_data: str,
convert_line_endings: bool=False
) -> None:
self.close()
self._ts = __.TextstreamMemory(
str_data=str_data,
convert_line_endings=convert_line_endings,
)
return
def close(self) -> None:
if (self._ts):
self._ts.close()
del self._ts
self._ts = None
return
| true | true |
f7281db02a76f0dac13b9c843ff0c6e71debf922 | 20,449 | py | Python | tools/run_tests/xds_k8s_test_driver/framework/xds_url_map_testcase.py | echo80313/grpc | 93cdc8b77e7b3fe4a3afec1c9c7e29b3f02ec3cf | [
"Apache-2.0"
] | null | null | null | tools/run_tests/xds_k8s_test_driver/framework/xds_url_map_testcase.py | echo80313/grpc | 93cdc8b77e7b3fe4a3afec1c9c7e29b3f02ec3cf | [
"Apache-2.0"
] | 4 | 2022-02-27T18:59:37.000Z | 2022-02-27T18:59:53.000Z | tools/run_tests/xds_k8s_test_driver/framework/xds_url_map_testcase.py | echo80313/grpc | 93cdc8b77e7b3fe4a3afec1c9c7e29b3f02ec3cf | [
"Apache-2.0"
] | null | null | null | # Copyright 2021 The gRPC Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A test framework built for urlMap related xDS test cases."""
import abc
from dataclasses import dataclass
import datetime
import json
import os
import re
import sys
import time
from typing import Any, Iterable, Mapping, Optional, Tuple
import unittest
from absl import flags
from absl import logging
from absl.testing import absltest
from google.protobuf import json_format
import grpc
from framework import xds_k8s_testcase
from framework import xds_url_map_test_resources
from framework.helpers import retryers
from framework.helpers import skips
from framework.test_app import client_app
# Load existing flags
flags.adopt_module_key_flags(xds_k8s_testcase)
flags.adopt_module_key_flags(xds_url_map_test_resources)
# Define urlMap specific flags
QPS = flags.DEFINE_integer('qps', default=25, help='The QPS client is sending')
# Test configs
_URL_MAP_PROPAGATE_TIMEOUT_SEC = 600
# With the per-run IAM change, the first xDS response has a several minutes
# delay. We want to increase the interval, reduce the log spam.
_URL_MAP_PROPAGATE_CHECK_INTERVAL_SEC = 15
URL_MAP_TESTCASE_FILE_SUFFIX = '_test.py'
_CLIENT_CONFIGURE_WAIT_SEC = 2
# Type aliases
XdsTestClient = client_app.XdsTestClient
GcpResourceManager = xds_url_map_test_resources.GcpResourceManager
HostRule = xds_url_map_test_resources.HostRule
PathMatcher = xds_url_map_test_resources.PathMatcher
JsonType = Any
# ProtoBuf translatable RpcType enums
RpcTypeUnaryCall = 'UNARY_CALL'
RpcTypeEmptyCall = 'EMPTY_CALL'
def _split_camel(s: str, delimiter: str = '-') -> str:
"""Turn camel case name to snake-case-like name."""
return ''.join(delimiter + c.lower() if c.isupper() else c
for c in s).lstrip(delimiter)
class DumpedXdsConfig(dict):
"""A convenience class to check xDS config.
Feel free to add more pre-compute fields.
"""
def __init__(self, xds_json: JsonType): # pylint: disable=too-many-branches
super().__init__(xds_json)
self.json_config = xds_json
self.lds = None
self.rds = None
self.rds_version = None
self.cds = []
self.eds = []
self.endpoints = []
for xds_config in self.get('xdsConfig', []):
try:
if 'listenerConfig' in xds_config:
self.lds = xds_config['listenerConfig']['dynamicListeners'][
0]['activeState']['listener']
elif 'routeConfig' in xds_config:
self.rds = xds_config['routeConfig']['dynamicRouteConfigs'][
0]['routeConfig']
self.rds_version = xds_config['routeConfig'][
'dynamicRouteConfigs'][0]['versionInfo']
elif 'clusterConfig' in xds_config:
for cluster in xds_config['clusterConfig'][
'dynamicActiveClusters']:
self.cds.append(cluster['cluster'])
elif 'endpointConfig' in xds_config:
for endpoint in xds_config['endpointConfig'][
'dynamicEndpointConfigs']:
self.eds.append(endpoint['endpointConfig'])
# TODO(lidiz) reduce the catch to LookupError
except Exception as e: # pylint: disable=broad-except
logging.debug('Parsing dumped xDS config failed with %s: %s',
type(e), e)
for generic_xds_config in self.get('genericXdsConfigs', []):
try:
if re.search(r'\.Listener$', generic_xds_config['typeUrl']):
self.lds = generic_xds_config["xdsConfig"]
elif re.search(r'\.RouteConfiguration$',
generic_xds_config['typeUrl']):
self.rds = generic_xds_config["xdsConfig"]
self.rds_version = generic_xds_config["versionInfo"]
elif re.search(r'\.Cluster$', generic_xds_config['typeUrl']):
self.cds.append(generic_xds_config["xdsConfig"])
elif re.search(r'\.ClusterLoadAssignment$',
generic_xds_config['typeUrl']):
self.eds.append(generic_xds_config["xdsConfig"])
# TODO(lidiz) reduce the catch to LookupError
except Exception as e: # pylint: disable=broad-except
logging.debug('Parsing dumped xDS config failed with %s: %s',
type(e), e)
for endpoint_config in self.eds:
for endpoint in endpoint_config.get('endpoints', {}):
for lb_endpoint in endpoint.get('lbEndpoints', {}):
try:
if lb_endpoint['healthStatus'] == 'HEALTHY':
self.endpoints.append(
'%s:%s' % (lb_endpoint['endpoint']['address']
['socketAddress']['address'],
lb_endpoint['endpoint']['address']
['socketAddress']['portValue']))
# TODO(lidiz) reduce the catch to LookupError
except Exception as e: # pylint: disable=broad-except
logging.debug('Parse endpoint failed with %s: %s',
type(e), e)
def __str__(self) -> str:
return json.dumps(self, indent=2)
class RpcDistributionStats:
"""A convenience class to check RPC distribution.
Feel free to add more pre-compute fields.
"""
num_failures: int
num_oks: int
default_service_rpc_count: int
alternative_service_rpc_count: int
unary_call_default_service_rpc_count: int
empty_call_default_service_rpc_count: int
unary_call_alternative_service_rpc_count: int
empty_call_alternative_service_rpc_count: int
def __init__(self, json_lb_stats: JsonType):
self.num_failures = json_lb_stats.get('numFailures', 0)
self.num_peers = 0
self.num_oks = 0
self.default_service_rpc_count = 0
self.alternative_service_rpc_count = 0
self.unary_call_default_service_rpc_count = 0
self.empty_call_default_service_rpc_count = 0
self.unary_call_alternative_service_rpc_count = 0
self.empty_call_alternative_service_rpc_count = 0
self.raw = json_lb_stats
if 'rpcsByPeer' in json_lb_stats:
self.num_peers = len(json_lb_stats['rpcsByPeer'])
if 'rpcsByMethod' in json_lb_stats:
for rpc_type in json_lb_stats['rpcsByMethod']:
for peer in json_lb_stats['rpcsByMethod'][rpc_type][
'rpcsByPeer']:
count = json_lb_stats['rpcsByMethod'][rpc_type][
'rpcsByPeer'][peer]
self.num_oks += count
if rpc_type == 'UnaryCall':
if 'alternative' in peer:
self.unary_call_alternative_service_rpc_count = count
self.alternative_service_rpc_count += count
else:
self.unary_call_default_service_rpc_count = count
self.default_service_rpc_count += count
else:
if 'alternative' in peer:
self.empty_call_alternative_service_rpc_count = count
self.alternative_service_rpc_count += count
else:
self.empty_call_default_service_rpc_count = count
self.default_service_rpc_count += count
@dataclass
class ExpectedResult:
"""Describes the expected result of assertRpcStatusCode method below."""
rpc_type: str = RpcTypeUnaryCall
status_code: grpc.StatusCode = grpc.StatusCode.OK
ratio: float = 1
class _MetaXdsUrlMapTestCase(type):
"""Tracking test case subclasses."""
# Automatic discover of all subclasses
_test_case_classes = []
_test_case_names = set()
# Keep track of started and finished test cases, so we know when to setup
# and tear down GCP resources.
_started_test_cases = set()
_finished_test_cases = set()
def __new__(cls, name: str, bases: Iterable[Any],
attrs: Mapping[str, Any]) -> Any:
# Hand over the tracking objects
attrs['test_case_classes'] = cls._test_case_classes
attrs['test_case_names'] = cls._test_case_names
attrs['started_test_cases'] = cls._started_test_cases
attrs['finished_test_cases'] = cls._finished_test_cases
# Handle the test name reflection
module_name = os.path.split(
sys.modules[attrs['__module__']].__file__)[-1]
if module_name.endswith(URL_MAP_TESTCASE_FILE_SUFFIX):
module_name = module_name.replace(URL_MAP_TESTCASE_FILE_SUFFIX, '')
attrs['short_module_name'] = module_name.replace('_', '-')
# Create the class and track
new_class = type.__new__(cls, name, bases, attrs)
if name.startswith('Test'):
cls._test_case_names.add(name)
cls._test_case_classes.append(new_class)
else:
logging.debug('Skipping test case class: %s', name)
return new_class
class XdsUrlMapTestCase(absltest.TestCase, metaclass=_MetaXdsUrlMapTestCase):
"""XdsUrlMapTestCase is the base class for urlMap related tests.
The subclass is expected to implement 3 methods:
- url_map_change: Updates the urlMap components for this test case
- xds_config_validate: Validates if the client received legit xDS configs
- rpc_distribution_validate: Validates if the routing behavior is correct
"""
@staticmethod
def is_supported(config: skips.TestConfig) -> bool:
"""Allow the test case to decide whether it supports the given config.
Returns:
A bool indicates if the given config is supported.
"""
del config
return True
@staticmethod
def client_init_config(rpc: str, metadata: str) -> Tuple[str, str]:
"""Updates the initial RPC configs for this test case.
Each test case will start a test client. The client takes RPC configs
and starts to send RPCs immediately. The config returned by this
function will be used to replace the default configs.
The default configs are passed in as arguments, so this method can
modify part of them.
Args:
rpc: The default rpc config, specifying RPCs to send, format
'UnaryCall,EmptyCall'
metadata: The metadata config, specifying metadata to send with each
RPC, format 'EmptyCall:key1:value1,UnaryCall:key2:value2'.
Returns:
A tuple contains the updated rpc and metadata config.
"""
return rpc, metadata
@staticmethod
@abc.abstractmethod
def url_map_change(
host_rule: HostRule,
path_matcher: PathMatcher) -> Tuple[HostRule, PathMatcher]:
"""Updates the dedicated urlMap components for this test case.
Each test case will have a dedicated HostRule, where the hostname is
generated from the test case name. The HostRule will be linked to a
PathMatcher, where stores the routing logic.
Args:
host_rule: A HostRule GCP resource as a JSON dict.
path_matcher: A PathMatcher GCP resource as a JSON dict.
Returns:
A tuple contains the updated version of given HostRule and
PathMatcher.
"""
@abc.abstractmethod
def xds_config_validate(self, xds_config: DumpedXdsConfig) -> None:
"""Validates received xDS config, if anything is wrong, raise.
This stage only ends when the control plane failed to send a valid
config within a given time range, like 600s.
Args:
xds_config: A DumpedXdsConfig instance can be used as a JSON dict,
but also provides helper fields for commonly checked xDS config.
"""
@abc.abstractmethod
def rpc_distribution_validate(self, test_client: XdsTestClient) -> None:
"""Validates the routing behavior, if any is wrong, raise.
Args:
test_client: A XdsTestClient instance for all sorts of end2end testing.
"""
@classmethod
def hostname(cls):
return "%s.%s:%s" % (cls.short_module_name, _split_camel(
cls.__name__), GcpResourceManager().server_xds_port)
@classmethod
def path_matcher_name(cls):
# Path matcher name must match r'(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?)'
return "%s-%s-pm" % (cls.short_module_name, _split_camel(cls.__name__))
@classmethod
def setUpClass(cls):
# Raises unittest.SkipTest if given client/server/version does not
# support current test case.
skips.evaluate_test_config(cls.is_supported)
if not cls.started_test_cases:
# Create the GCP resource once before the first test start
GcpResourceManager().setup(cls.test_case_classes)
cls.started_test_cases.add(cls.__name__)
# Create the test case's own client runner with it's own namespace,
# enables concurrent running with other test cases.
cls.test_client_runner = GcpResourceManager().create_test_client_runner(
)
# Start the client, and allow the test to override the initial RPC config.
rpc, metadata = cls.client_init_config(rpc="UnaryCall,EmptyCall",
metadata="")
cls.test_client = cls.test_client_runner.run(
server_target=f'xds:///{cls.hostname()}',
rpc=rpc,
metadata=metadata,
qps=QPS.value,
print_response=True)
@classmethod
def tearDownClass(cls):
cls.test_client_runner.cleanup(force=True, force_namespace=True)
cls.finished_test_cases.add(cls.__name__)
if cls.finished_test_cases == cls.test_case_names:
# Tear down the GCP resource after all tests finished
GcpResourceManager().cleanup()
def _fetch_and_check_xds_config(self):
# TODO(lidiz) find another way to store last seen xDS config
# Cleanup state for this attempt
self._xds_json_config = None # pylint: disable=attribute-defined-outside-init
# Fetch client config
config = self.test_client.csds.fetch_client_status(
log_level=logging.INFO)
self.assertIsNotNone(config)
# Found client config, test it.
self._xds_json_config = json_format.MessageToDict(config) # pylint: disable=attribute-defined-outside-init
# Execute the child class provided validation logic
self.xds_config_validate(DumpedXdsConfig(self._xds_json_config))
def run(self, result: unittest.TestResult = None) -> None:
"""Abort this test case if CSDS check is failed.
This prevents the test runner to waste time on RPC distribution test,
and yields clearer signal.
"""
if result.failures or result.errors:
logging.info('Aborting %s', self.__class__.__name__)
else:
super().run(result)
def test_client_config(self):
retryer = retryers.constant_retryer(
wait_fixed=datetime.timedelta(
seconds=_URL_MAP_PROPAGATE_CHECK_INTERVAL_SEC),
timeout=datetime.timedelta(seconds=_URL_MAP_PROPAGATE_TIMEOUT_SEC),
logger=logging,
log_level=logging.INFO)
try:
retryer(self._fetch_and_check_xds_config)
finally:
logging.info(
'latest xDS config:\n%s',
GcpResourceManager().td.compute.resource_pretty_format(
self._xds_json_config))
def test_rpc_distribution(self):
self.rpc_distribution_validate(self.test_client)
@staticmethod
def configure_and_send(test_client: XdsTestClient,
*,
rpc_types: Iterable[str],
metadata: Optional[Iterable[Tuple[str, str,
str]]] = None,
app_timeout: Optional[int] = None,
num_rpcs: int) -> RpcDistributionStats:
test_client.update_config.configure(rpc_types=rpc_types,
metadata=metadata,
app_timeout=app_timeout)
# Configure RPC might race with get stats RPC on slower machines.
time.sleep(_CLIENT_CONFIGURE_WAIT_SEC)
json_lb_stats = json_format.MessageToDict(
test_client.get_load_balancer_stats(num_rpcs=num_rpcs))
logging.info(
'Received LoadBalancerStatsResponse from test client %s:\n%s',
test_client.ip, json.dumps(json_lb_stats, indent=2))
return RpcDistributionStats(json_lb_stats)
def assertNumEndpoints(self, xds_config: DumpedXdsConfig, k: int) -> None:
self.assertLen(
xds_config.endpoints, k,
f'insufficient endpoints in EDS: want={k} seen={xds_config.endpoints}'
)
def assertRpcStatusCode( # pylint: disable=too-many-locals
self, test_client: XdsTestClient, *,
expected: Iterable[ExpectedResult], length: int,
tolerance: float) -> None:
"""Assert the distribution of RPC statuses over a period of time."""
# Sending with pre-set QPS for a period of time
before_stats = test_client.get_load_balancer_accumulated_stats()
logging.info(
'Received LoadBalancerAccumulatedStatsResponse from test client %s: before:\n%s',
test_client.ip, before_stats)
time.sleep(length)
after_stats = test_client.get_load_balancer_accumulated_stats()
logging.info(
'Received LoadBalancerAccumulatedStatsResponse from test client %s: after: \n%s',
test_client.ip, after_stats)
# Validate the diff
for expected_result in expected:
rpc = expected_result.rpc_type
status = expected_result.status_code.value[0]
# Compute observation
# ProtoBuf messages has special magic dictionary that we don't need
# to catch exceptions:
# https://developers.google.com/protocol-buffers/docs/reference/python-generated#undefined
seen_after = after_stats.stats_per_method[rpc].result[status]
seen_before = before_stats.stats_per_method[rpc].result[status]
seen = seen_after - seen_before
# Compute total number of RPC started
stats_per_method_after = after_stats.stats_per_method.get(
rpc, {}).result.items()
total_after = sum(
x[1] for x in stats_per_method_after) # (status_code, count)
stats_per_method_before = before_stats.stats_per_method.get(
rpc, {}).result.items()
total_before = sum(
x[1] for x in stats_per_method_before) # (status_code, count)
total = total_after - total_before
# Compute and validate the number
want = total * expected_result.ratio
diff_ratio = abs(seen - want) / total
self.assertLessEqual(
diff_ratio, tolerance,
(f'Expect rpc [{rpc}] to return '
f'[{expected_result.status_code}] at '
f'{expected_result.ratio:.2f} ratio: '
f'seen={seen} want={want} total={total} '
f'diff_ratio={diff_ratio:.4f} > {tolerance:.2f}'))
| 42.691023 | 115 | 0.627366 |
import abc
from dataclasses import dataclass
import datetime
import json
import os
import re
import sys
import time
from typing import Any, Iterable, Mapping, Optional, Tuple
import unittest
from absl import flags
from absl import logging
from absl.testing import absltest
from google.protobuf import json_format
import grpc
from framework import xds_k8s_testcase
from framework import xds_url_map_test_resources
from framework.helpers import retryers
from framework.helpers import skips
from framework.test_app import client_app
flags.adopt_module_key_flags(xds_k8s_testcase)
flags.adopt_module_key_flags(xds_url_map_test_resources)
QPS = flags.DEFINE_integer('qps', default=25, help='The QPS client is sending')
_URL_MAP_PROPAGATE_TIMEOUT_SEC = 600
_URL_MAP_PROPAGATE_CHECK_INTERVAL_SEC = 15
URL_MAP_TESTCASE_FILE_SUFFIX = '_test.py'
_CLIENT_CONFIGURE_WAIT_SEC = 2
XdsTestClient = client_app.XdsTestClient
GcpResourceManager = xds_url_map_test_resources.GcpResourceManager
HostRule = xds_url_map_test_resources.HostRule
PathMatcher = xds_url_map_test_resources.PathMatcher
JsonType = Any
RpcTypeUnaryCall = 'UNARY_CALL'
RpcTypeEmptyCall = 'EMPTY_CALL'
def _split_camel(s: str, delimiter: str = '-') -> str:
return ''.join(delimiter + c.lower() if c.isupper() else c
for c in s).lstrip(delimiter)
class DumpedXdsConfig(dict):
def __init__(self, xds_json: JsonType):
super().__init__(xds_json)
self.json_config = xds_json
self.lds = None
self.rds = None
self.rds_version = None
self.cds = []
self.eds = []
self.endpoints = []
for xds_config in self.get('xdsConfig', []):
try:
if 'listenerConfig' in xds_config:
self.lds = xds_config['listenerConfig']['dynamicListeners'][
0]['activeState']['listener']
elif 'routeConfig' in xds_config:
self.rds = xds_config['routeConfig']['dynamicRouteConfigs'][
0]['routeConfig']
self.rds_version = xds_config['routeConfig'][
'dynamicRouteConfigs'][0]['versionInfo']
elif 'clusterConfig' in xds_config:
for cluster in xds_config['clusterConfig'][
'dynamicActiveClusters']:
self.cds.append(cluster['cluster'])
elif 'endpointConfig' in xds_config:
for endpoint in xds_config['endpointConfig'][
'dynamicEndpointConfigs']:
self.eds.append(endpoint['endpointConfig'])
except Exception as e:
logging.debug('Parsing dumped xDS config failed with %s: %s',
type(e), e)
for generic_xds_config in self.get('genericXdsConfigs', []):
try:
if re.search(r'\.Listener$', generic_xds_config['typeUrl']):
self.lds = generic_xds_config["xdsConfig"]
elif re.search(r'\.RouteConfiguration$',
generic_xds_config['typeUrl']):
self.rds = generic_xds_config["xdsConfig"]
self.rds_version = generic_xds_config["versionInfo"]
elif re.search(r'\.Cluster$', generic_xds_config['typeUrl']):
self.cds.append(generic_xds_config["xdsConfig"])
elif re.search(r'\.ClusterLoadAssignment$',
generic_xds_config['typeUrl']):
self.eds.append(generic_xds_config["xdsConfig"])
except Exception as e:
logging.debug('Parsing dumped xDS config failed with %s: %s',
type(e), e)
for endpoint_config in self.eds:
for endpoint in endpoint_config.get('endpoints', {}):
for lb_endpoint in endpoint.get('lbEndpoints', {}):
try:
if lb_endpoint['healthStatus'] == 'HEALTHY':
self.endpoints.append(
'%s:%s' % (lb_endpoint['endpoint']['address']
['socketAddress']['address'],
lb_endpoint['endpoint']['address']
['socketAddress']['portValue']))
except Exception as e:
logging.debug('Parse endpoint failed with %s: %s',
type(e), e)
def __str__(self) -> str:
return json.dumps(self, indent=2)
class RpcDistributionStats:
num_failures: int
num_oks: int
default_service_rpc_count: int
alternative_service_rpc_count: int
unary_call_default_service_rpc_count: int
empty_call_default_service_rpc_count: int
unary_call_alternative_service_rpc_count: int
empty_call_alternative_service_rpc_count: int
def __init__(self, json_lb_stats: JsonType):
self.num_failures = json_lb_stats.get('numFailures', 0)
self.num_peers = 0
self.num_oks = 0
self.default_service_rpc_count = 0
self.alternative_service_rpc_count = 0
self.unary_call_default_service_rpc_count = 0
self.empty_call_default_service_rpc_count = 0
self.unary_call_alternative_service_rpc_count = 0
self.empty_call_alternative_service_rpc_count = 0
self.raw = json_lb_stats
if 'rpcsByPeer' in json_lb_stats:
self.num_peers = len(json_lb_stats['rpcsByPeer'])
if 'rpcsByMethod' in json_lb_stats:
for rpc_type in json_lb_stats['rpcsByMethod']:
for peer in json_lb_stats['rpcsByMethod'][rpc_type][
'rpcsByPeer']:
count = json_lb_stats['rpcsByMethod'][rpc_type][
'rpcsByPeer'][peer]
self.num_oks += count
if rpc_type == 'UnaryCall':
if 'alternative' in peer:
self.unary_call_alternative_service_rpc_count = count
self.alternative_service_rpc_count += count
else:
self.unary_call_default_service_rpc_count = count
self.default_service_rpc_count += count
else:
if 'alternative' in peer:
self.empty_call_alternative_service_rpc_count = count
self.alternative_service_rpc_count += count
else:
self.empty_call_default_service_rpc_count = count
self.default_service_rpc_count += count
@dataclass
class ExpectedResult:
rpc_type: str = RpcTypeUnaryCall
status_code: grpc.StatusCode = grpc.StatusCode.OK
ratio: float = 1
class _MetaXdsUrlMapTestCase(type):
_test_case_classes = []
_test_case_names = set()
_started_test_cases = set()
_finished_test_cases = set()
def __new__(cls, name: str, bases: Iterable[Any],
attrs: Mapping[str, Any]) -> Any:
attrs['test_case_classes'] = cls._test_case_classes
attrs['test_case_names'] = cls._test_case_names
attrs['started_test_cases'] = cls._started_test_cases
attrs['finished_test_cases'] = cls._finished_test_cases
module_name = os.path.split(
sys.modules[attrs['__module__']].__file__)[-1]
if module_name.endswith(URL_MAP_TESTCASE_FILE_SUFFIX):
module_name = module_name.replace(URL_MAP_TESTCASE_FILE_SUFFIX, '')
attrs['short_module_name'] = module_name.replace('_', '-')
new_class = type.__new__(cls, name, bases, attrs)
if name.startswith('Test'):
cls._test_case_names.add(name)
cls._test_case_classes.append(new_class)
else:
logging.debug('Skipping test case class: %s', name)
return new_class
class XdsUrlMapTestCase(absltest.TestCase, metaclass=_MetaXdsUrlMapTestCase):
@staticmethod
def is_supported(config: skips.TestConfig) -> bool:
del config
return True
@staticmethod
def client_init_config(rpc: str, metadata: str) -> Tuple[str, str]:
return rpc, metadata
@staticmethod
@abc.abstractmethod
def url_map_change(
host_rule: HostRule,
path_matcher: PathMatcher) -> Tuple[HostRule, PathMatcher]:
@abc.abstractmethod
def xds_config_validate(self, xds_config: DumpedXdsConfig) -> None:
@abc.abstractmethod
def rpc_distribution_validate(self, test_client: XdsTestClient) -> None:
@classmethod
def hostname(cls):
return "%s.%s:%s" % (cls.short_module_name, _split_camel(
cls.__name__), GcpResourceManager().server_xds_port)
@classmethod
def path_matcher_name(cls):
return "%s-%s-pm" % (cls.short_module_name, _split_camel(cls.__name__))
@classmethod
def setUpClass(cls):
skips.evaluate_test_config(cls.is_supported)
if not cls.started_test_cases:
GcpResourceManager().setup(cls.test_case_classes)
cls.started_test_cases.add(cls.__name__)
cls.test_client_runner = GcpResourceManager().create_test_client_runner(
)
rpc, metadata = cls.client_init_config(rpc="UnaryCall,EmptyCall",
metadata="")
cls.test_client = cls.test_client_runner.run(
server_target=f'xds:///{cls.hostname()}',
rpc=rpc,
metadata=metadata,
qps=QPS.value,
print_response=True)
@classmethod
def tearDownClass(cls):
cls.test_client_runner.cleanup(force=True, force_namespace=True)
cls.finished_test_cases.add(cls.__name__)
if cls.finished_test_cases == cls.test_case_names:
GcpResourceManager().cleanup()
def _fetch_and_check_xds_config(self):
self._xds_json_config = None
config = self.test_client.csds.fetch_client_status(
log_level=logging.INFO)
self.assertIsNotNone(config)
self._xds_json_config = json_format.MessageToDict(config)
self.xds_config_validate(DumpedXdsConfig(self._xds_json_config))
def run(self, result: unittest.TestResult = None) -> None:
if result.failures or result.errors:
logging.info('Aborting %s', self.__class__.__name__)
else:
super().run(result)
def test_client_config(self):
retryer = retryers.constant_retryer(
wait_fixed=datetime.timedelta(
seconds=_URL_MAP_PROPAGATE_CHECK_INTERVAL_SEC),
timeout=datetime.timedelta(seconds=_URL_MAP_PROPAGATE_TIMEOUT_SEC),
logger=logging,
log_level=logging.INFO)
try:
retryer(self._fetch_and_check_xds_config)
finally:
logging.info(
'latest xDS config:\n%s',
GcpResourceManager().td.compute.resource_pretty_format(
self._xds_json_config))
def test_rpc_distribution(self):
self.rpc_distribution_validate(self.test_client)
@staticmethod
def configure_and_send(test_client: XdsTestClient,
*,
rpc_types: Iterable[str],
metadata: Optional[Iterable[Tuple[str, str,
str]]] = None,
app_timeout: Optional[int] = None,
num_rpcs: int) -> RpcDistributionStats:
test_client.update_config.configure(rpc_types=rpc_types,
metadata=metadata,
app_timeout=app_timeout)
time.sleep(_CLIENT_CONFIGURE_WAIT_SEC)
json_lb_stats = json_format.MessageToDict(
test_client.get_load_balancer_stats(num_rpcs=num_rpcs))
logging.info(
'Received LoadBalancerStatsResponse from test client %s:\n%s',
test_client.ip, json.dumps(json_lb_stats, indent=2))
return RpcDistributionStats(json_lb_stats)
def assertNumEndpoints(self, xds_config: DumpedXdsConfig, k: int) -> None:
self.assertLen(
xds_config.endpoints, k,
f'insufficient endpoints in EDS: want={k} seen={xds_config.endpoints}'
)
def assertRpcStatusCode(
self, test_client: XdsTestClient, *,
expected: Iterable[ExpectedResult], length: int,
tolerance: float) -> None:
before_stats = test_client.get_load_balancer_accumulated_stats()
logging.info(
'Received LoadBalancerAccumulatedStatsResponse from test client %s: before:\n%s',
test_client.ip, before_stats)
time.sleep(length)
after_stats = test_client.get_load_balancer_accumulated_stats()
logging.info(
'Received LoadBalancerAccumulatedStatsResponse from test client %s: after: \n%s',
test_client.ip, after_stats)
for expected_result in expected:
rpc = expected_result.rpc_type
status = expected_result.status_code.value[0]
# to catch exceptions:
# https://developers.google.com/protocol-buffers/docs/reference/python-generated#undefined
seen_after = after_stats.stats_per_method[rpc].result[status]
seen_before = before_stats.stats_per_method[rpc].result[status]
seen = seen_after - seen_before
# Compute total number of RPC started
stats_per_method_after = after_stats.stats_per_method.get(
rpc, {}).result.items()
total_after = sum(
x[1] for x in stats_per_method_after) # (status_code, count)
stats_per_method_before = before_stats.stats_per_method.get(
rpc, {}).result.items()
total_before = sum(
x[1] for x in stats_per_method_before) # (status_code, count)
total = total_after - total_before
# Compute and validate the number
want = total * expected_result.ratio
diff_ratio = abs(seen - want) / total
self.assertLessEqual(
diff_ratio, tolerance,
(f'Expect rpc [{rpc}] to return '
f'[{expected_result.status_code}] at '
f'{expected_result.ratio:.2f} ratio: '
f'seen={seen} want={want} total={total} '
f'diff_ratio={diff_ratio:.4f} > {tolerance:.2f}'))
| true | true |
f7281ea47705ab62937db90e4ddff340c29763a6 | 196 | py | Python | setup.py | aakinlalu/my-data-science-template | 4126938ac2203aac9e6ab3b7d92c3f2c74203bee | [
"FTL"
] | null | null | null | setup.py | aakinlalu/my-data-science-template | 4126938ac2203aac9e6ab3b7d92c3f2c74203bee | [
"FTL"
] | null | null | null | setup.py | aakinlalu/my-data-science-template | 4126938ac2203aac9e6ab3b7d92c3f2c74203bee | [
"FTL"
] | null | null | null | from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.0.1',
description='to classify crime',
author='Adebayo',
license='',
)
| 17.818182 | 43 | 0.647959 | from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.0.1',
description='to classify crime',
author='Adebayo',
license='',
)
| true | true |
f7281f6965f2c2e3ad5eb6944d0956b099447978 | 10,060 | py | Python | bay/cli/tasks.py | eventbrite/bay | 3a157457a55713067213aeafe385a1cc49aa2698 | [
"Apache-2.0"
] | 22 | 2017-03-01T19:52:30.000Z | 2020-09-09T16:27:21.000Z | bay/cli/tasks.py | eventbrite/bay | 3a157457a55713067213aeafe385a1cc49aa2698 | [
"Apache-2.0"
] | 25 | 2017-02-23T23:08:56.000Z | 2019-10-09T00:02:52.000Z | bay/cli/tasks.py | eventbrite/bay | 3a157457a55713067213aeafe385a1cc49aa2698 | [
"Apache-2.0"
] | 4 | 2017-03-12T03:51:17.000Z | 2021-09-08T11:36:36.000Z | import contextlib
import shutil
import threading
import time
from .colors import CYAN, GREEN, RED, YELLOW
from ..utils.threading import ExceptionalThread
UP_ONE = "\033[A\033[1000D"
CLEAR_LINE = "\033[2K"
console_lock = threading.Lock()
class Task:
"""
Something that can be started (by being created), have progress reported, and then finished.
It can also have a number of sub-tasks, and arbitary lines of extra information
that should be shown to the user alongside progress messages or a progress bar.
"""
INDENT_AMOUNT = 2
FLAVOR_NEUTRAL = "neutral"
FLAVOR_GOOD = "good"
FLAVOR_BAD = "bad"
FLAVOR_WARNING = "warning"
def __init__(self, name, parent=None, hide_if_empty=False, collapse_if_finished=False, progress_formatter=None):
self.name = name
# If this task only displays if it has children
self.hide_if_empty = hide_if_empty
# If this task collapses to just the first line if it's finished
self.collapse_if_finished = collapse_if_finished
# Any parent tasks to trigger updates in
self.parent = parent
with console_lock:
if self.parent is not None:
self.parent.subtasks.append(self)
# Sub tasks to show under this one
self.subtasks = []
# The current status message
self.status = None
# The current progress from 0 - 1
self.progress = None
# The way to format the progress numbers
self.progress_formatter = progress_formatter or str
# The current status flavor (turns into a colour)
self.status_flavor = self.FLAVOR_NEUTRAL
# Extra lines of information to show underneath the task
self.extra_info = []
# If the task is complete
self.finished = False
# Number of lines we had previously cleared
self.cleared_lines = 0
# If the output is currently "paused" for other things to write to the console
self.output_paused = False
# Run update
self.update()
def update(self, status=None, status_flavor=None, progress=None, force=False):
"""
Update either the status message, the progress bar, or both.
If this is the topmost task, this will trigger a reprint on the console.
"""
if self.finished and not force:
raise ValueError("You cannot update() a finished task!")
with console_lock:
if status is not None:
self.status = status
if progress is not None:
if len(progress) != 2:
raise ValueError("Progress must be a 2-tuple of (count, total)")
self.progress = progress
if status_flavor is not None:
self.status_flavor = status_flavor
# Look for a parent to potentially trigger update on, or print ourselves
# if there isn't one
if self.parent is not None:
self.parent.update()
else:
self.clear_and_output()
def add_extra_info(self, message):
"""
Adds a line of extra info and triggers updates
"""
with console_lock:
self.extra_info.append(message)
if self.parent is not None:
self.parent.update()
def set_extra_info(self, messages):
"""
Sets all extra info and triggers updates
"""
with console_lock:
self.extra_info = messages
if self.parent is not None:
self.parent.update()
def finish(self, **kwargs):
"""
Marks the task as finished, meaning it can no longer be mutated.
Used to optimise terminal output only.
"""
self.finished = True
self.update(force=True, **kwargs)
def wrapped_extra_info(self, text_width):
"""
Returns extra_info wrapped to fit the terminal width.
"""
actual_output = []
for line in self.extra_info:
line = line.strip()
while line:
actual_output.append(line[:text_width])
line = line[text_width:]
return actual_output
def make_progress_bar(self, count, total, width=30):
"""
Helper for making progress bar text.
"""
progress = min(max(count / total, 0), 1)
bar_width = width - 2
bar_size = int(bar_width * progress)
return "[{}{}] {}/{}".format(
"=" * bar_size,
" " * (bar_width - bar_size),
self.progress_formatter(count),
self.progress_formatter(total),
)
def output(self, terminal_width, indent=0):
"""
Returns the lines to output for this task to the screen (as a generator)
"""
if self.hide_if_empty and not self.subtasks:
return
# Work out progress text
progress_string = ""
if self.progress is not None:
progress_string = self.make_progress_bar(*self.progress) + " "
# Work out status text
status_string = self.status or ""
if self.status_flavor == self.FLAVOR_BAD:
status_string = RED(status_string)
elif self.status_flavor == self.FLAVOR_GOOD:
status_string = GREEN(status_string)
elif self.status_flavor == self.FLAVOR_WARNING:
status_string = YELLOW(status_string)
# Print out our line
indent_string = " " * (self.INDENT_AMOUNT * indent)
main_line = "{}{}: {}{}".format(
indent_string,
CYAN(self.name),
progress_string,
status_string,
)
if indent > 0:
yield main_line
if not (self.finished and self.collapse_if_finished):
# Print out extra info
indent_string = (indent + 1) * (" " * self.INDENT_AMOUNT)
for info in self.wrapped_extra_info(terminal_width - len(indent_string)):
yield indent_string + info[:terminal_width - len(indent_string)].replace("\n", "")
# Print out subtasks
for subtask in self.subtasks:
yield from subtask.output(terminal_width, indent=indent + 1)
if indent == 0:
yield main_line
def clear_and_output(self):
"""
Clears the terminal up to the right line then outputs the information
of the task.
"""
# See if output is paused
if self.output_paused:
return
# OK, print
with console_lock:
# Get terminal width
terminal_width = shutil.get_terminal_size((80, 20)).columns
# Get the output we need to print
output = list(self.output(terminal_width))
# Scroll the terminal down/up enough for any new lines
needed_lines = len(output)
new_lines = needed_lines - self.cleared_lines
if new_lines > 0:
print("\n" * new_lines, flush=True, end="")
elif new_lines < 0:
print(
(UP_ONE + CLEAR_LINE) * abs(new_lines),
flush=True,
end="",
)
self.cleared_lines = needed_lines
# Move cursor to top of cleared section
print(
(UP_ONE + CLEAR_LINE) * needed_lines,
flush=True,
end="",
)
for line in output:
print(line)
def _pause_output(self, pause=True):
"""
Allows the output to be paused and unpaused by finding the parent and doing it there.
"""
if self.parent is None:
self.output_paused = pause
if not pause:
# Make the output rewrite from where it is
self.cleared_lines = 0
self.clear_and_output()
else:
self.parent._pause_output(pause)
@contextlib.contextmanager
def paused_output(self):
"""
Context manager that pauses printing of output until it's exited.
"""
self._pause_output(True)
yield
self._pause_output(False)
@contextlib.contextmanager
def rate_limit(self, interval=0.1):
"""
Context manager that rate-limits updates on tasks
"""
buffered_changes = {"running": True}
# Thread loop that flushes every interval
def flusher():
while buffered_changes['running']:
# Do any extra_info calls
if "set_extra_info" in buffered_changes:
self.set_extra_info(buffered_changes['set_extra_info'])
del buffered_changes['set_extra_info']
# Do any update calls
if "update" in buffered_changes:
self.update(**buffered_changes['update'])
del buffered_changes['update']
# Sleep
time.sleep(interval)
# Fake task object to provide out
class BufferedTask(object):
def set_extra_info(self, extra_info):
self.buffered_changes['set_extra_info'] = extra_info
def update(self, **kwargs):
self.buffered_changes['update'] = kwargs
# Start thread that flushes every interval
flush_thread = ExceptionalThread(target=flusher, daemon=True)
flush_thread.start()
# Run inner code
yield BufferedTask()
# Do one more flush and exit
buffered_changes['running'] = False
flush_thread.join()
class RootTask(Task):
"""
Special task subclass that represents the "root" task, the instance that
has no output of its own but encapsulates all other tasks in the app in order.
"""
def __init__(self):
super(RootTask, self).__init__("__root__")
def output(self, terminal_width):
for subtask in self.subtasks:
yield from subtask.output(terminal_width, indent=0)
| 35.052265 | 116 | 0.584195 | import contextlib
import shutil
import threading
import time
from .colors import CYAN, GREEN, RED, YELLOW
from ..utils.threading import ExceptionalThread
UP_ONE = "\033[A\033[1000D"
CLEAR_LINE = "\033[2K"
console_lock = threading.Lock()
class Task:
INDENT_AMOUNT = 2
FLAVOR_NEUTRAL = "neutral"
FLAVOR_GOOD = "good"
FLAVOR_BAD = "bad"
FLAVOR_WARNING = "warning"
def __init__(self, name, parent=None, hide_if_empty=False, collapse_if_finished=False, progress_formatter=None):
self.name = name
self.hide_if_empty = hide_if_empty
self.collapse_if_finished = collapse_if_finished
# Any parent tasks to trigger updates in
self.parent = parent
with console_lock:
if self.parent is not None:
self.parent.subtasks.append(self)
# Sub tasks to show under this one
self.subtasks = []
# The current status message
self.status = None
# The current progress from 0 - 1
self.progress = None
# The way to format the progress numbers
self.progress_formatter = progress_formatter or str
# The current status flavor (turns into a colour)
self.status_flavor = self.FLAVOR_NEUTRAL
# Extra lines of information to show underneath the task
self.extra_info = []
# If the task is complete
self.finished = False
# Number of lines we had previously cleared
self.cleared_lines = 0
# If the output is currently "paused" for other things to write to the console
self.output_paused = False
# Run update
self.update()
def update(self, status=None, status_flavor=None, progress=None, force=False):
if self.finished and not force:
raise ValueError("You cannot update() a finished task!")
with console_lock:
if status is not None:
self.status = status
if progress is not None:
if len(progress) != 2:
raise ValueError("Progress must be a 2-tuple of (count, total)")
self.progress = progress
if status_flavor is not None:
self.status_flavor = status_flavor
# Look for a parent to potentially trigger update on, or print ourselves
# if there isn't one
if self.parent is not None:
self.parent.update()
else:
self.clear_and_output()
def add_extra_info(self, message):
with console_lock:
self.extra_info.append(message)
if self.parent is not None:
self.parent.update()
def set_extra_info(self, messages):
with console_lock:
self.extra_info = messages
if self.parent is not None:
self.parent.update()
def finish(self, **kwargs):
self.finished = True
self.update(force=True, **kwargs)
def wrapped_extra_info(self, text_width):
actual_output = []
for line in self.extra_info:
line = line.strip()
while line:
actual_output.append(line[:text_width])
line = line[text_width:]
return actual_output
def make_progress_bar(self, count, total, width=30):
progress = min(max(count / total, 0), 1)
bar_width = width - 2
bar_size = int(bar_width * progress)
return "[{}{}] {}/{}".format(
"=" * bar_size,
" " * (bar_width - bar_size),
self.progress_formatter(count),
self.progress_formatter(total),
)
def output(self, terminal_width, indent=0):
if self.hide_if_empty and not self.subtasks:
return
progress_string = ""
if self.progress is not None:
progress_string = self.make_progress_bar(*self.progress) + " "
status_string = self.status or ""
if self.status_flavor == self.FLAVOR_BAD:
status_string = RED(status_string)
elif self.status_flavor == self.FLAVOR_GOOD:
status_string = GREEN(status_string)
elif self.status_flavor == self.FLAVOR_WARNING:
status_string = YELLOW(status_string)
indent_string = " " * (self.INDENT_AMOUNT * indent)
main_line = "{}{}: {}{}".format(
indent_string,
CYAN(self.name),
progress_string,
status_string,
)
if indent > 0:
yield main_line
if not (self.finished and self.collapse_if_finished):
indent_string = (indent + 1) * (" " * self.INDENT_AMOUNT)
for info in self.wrapped_extra_info(terminal_width - len(indent_string)):
yield indent_string + info[:terminal_width - len(indent_string)].replace("\n", "")
for subtask in self.subtasks:
yield from subtask.output(terminal_width, indent=indent + 1)
if indent == 0:
yield main_line
def clear_and_output(self):
if self.output_paused:
return
with console_lock:
terminal_width = shutil.get_terminal_size((80, 20)).columns
output = list(self.output(terminal_width))
needed_lines = len(output)
new_lines = needed_lines - self.cleared_lines
if new_lines > 0:
print("\n" * new_lines, flush=True, end="")
elif new_lines < 0:
print(
(UP_ONE + CLEAR_LINE) * abs(new_lines),
flush=True,
end="",
)
self.cleared_lines = needed_lines
print(
(UP_ONE + CLEAR_LINE) * needed_lines,
flush=True,
end="",
)
for line in output:
print(line)
def _pause_output(self, pause=True):
if self.parent is None:
self.output_paused = pause
if not pause:
self.cleared_lines = 0
self.clear_and_output()
else:
self.parent._pause_output(pause)
@contextlib.contextmanager
def paused_output(self):
self._pause_output(True)
yield
self._pause_output(False)
@contextlib.contextmanager
def rate_limit(self, interval=0.1):
buffered_changes = {"running": True}
def flusher():
while buffered_changes['running']:
if "set_extra_info" in buffered_changes:
self.set_extra_info(buffered_changes['set_extra_info'])
del buffered_changes['set_extra_info']
if "update" in buffered_changes:
self.update(**buffered_changes['update'])
del buffered_changes['update']
time.sleep(interval)
class BufferedTask(object):
def set_extra_info(self, extra_info):
self.buffered_changes['set_extra_info'] = extra_info
def update(self, **kwargs):
self.buffered_changes['update'] = kwargs
flush_thread = ExceptionalThread(target=flusher, daemon=True)
flush_thread.start()
yield BufferedTask()
buffered_changes['running'] = False
flush_thread.join()
class RootTask(Task):
def __init__(self):
super(RootTask, self).__init__("__root__")
def output(self, terminal_width):
for subtask in self.subtasks:
yield from subtask.output(terminal_width, indent=0)
| true | true |
f7281febef4aa8e8a1378bda0f0d3af1f2537596 | 5,092 | py | Python | ex1/daniel/imu_exercise_kalman.py | balintmaci/drone_intro_exercises | 1d8b839fecd6b0c5e33210b9a88fd741a71034cc | [
"Unlicense"
] | null | null | null | ex1/daniel/imu_exercise_kalman.py | balintmaci/drone_intro_exercises | 1d8b839fecd6b0c5e33210b9a88fd741a71034cc | [
"Unlicense"
] | null | null | null | ex1/daniel/imu_exercise_kalman.py | balintmaci/drone_intro_exercises | 1d8b839fecd6b0c5e33210b9a88fd741a71034cc | [
"Unlicense"
] | null | null | null | #!/usr/bin/python
# -*- coding: utf-8 -*-
# IMU exercise
# Copyright (c) 2015-2020 Kjeld Jensen kjen@mmmi.sdu.dk kj@kjen.dk
# import libraries
from math import pi, sqrt, atan2
import matplotlib.pyplot as plt
from pylab import ion
# name of the file to read ##
fileName = 'imu_razor_data_pitch_55deg.txt'
## IMU type
#imuType = 'vectornav_vn100'
imuType = 'sparkfun_razor'
# other parameters
showPlot = True
show3DLiveView = False
show3DLiveViewInterval = 3
if show3DLiveView == True:
from imu_box3d import imu_visualize
##### Insert initialize code below ###################
# approx. bias values determined by averaging over static measurements
bias_gyro_x = 3.95*3.14/180 # [rad/measurement]
bias_gyro_y = 2.85*3.14/180 # [rad/measurement]
bias_gyro_z = 0.41*3.14/180 # [rad/measurement]
# variances
gyroVar = 0.02
pitchVar = 0.01
# Kalman filter start guess
estAngle = 0
estVar = 3.14
# Kalman filter housekeeping variables
gyroVarAcc = 0.0
######################################################
## Variables for plotting ##
plotDataGyro = []
plotDataAcc = []
plotDataKalman = []
## Initialize your variables here ##
gyro_x_rel = 0.0
gyro_y_rel = 0.0
gyro_z_rel = 0.0
# open the imu data file
f = open (fileName, "r")
# initialize variables
count = 0
# initialize 3D liveview
if show3DLiveView == True:
imuview = imu_visualize()
imuview.set_axis (0, 0, 0)
imuview.update()
# looping through file
for line in f:
count += 1
# split the line into CSV formatted data
line = line.replace ('*',',') # make the checkum another csv value
csv = line.split(',')
# keep track of the timestamps
ts_recv = float(csv[0])
if count == 1:
ts_now = ts_recv # only the first time
ts_prev = ts_now
ts_now = ts_recv
if imuType == 'sparkfun_razor':
# import data from a SparkFun Razor IMU (SDU firmware)
# outputs ENU reference system
acc_x = int(csv[2]) / 1000.0 * 4 * 9.82;
acc_y = int(csv[3]) / 1000.0 * 4 * 9.82;
acc_z = int(csv[4]) / 1000.0 * 4 * 9.82;
gyro_x = int(csv[5]) * 1/14.375 * pi/180.0;
gyro_y = int(csv[6]) * 1/14.375 * pi/180.0;
gyro_z = int(csv[7]) * 1/14.375 * pi/180.0;
elif imuType == 'vectornav_vn100':
# import data from a VectorNav VN-100 configured to output $VNQMR
# outputs NED reference system (therefore converted to ENU)
acc_y = float(csv[9])
acc_x = float(csv[10])
acc_z = -float(csv[11])
gyro_y = float(csv[12])
gyro_x = float(csv[13])
gyro_z = -float(csv[14])
# subtract defined static bias for each gyro
gyro_x -= bias_gyro_x
gyro_y -= bias_gyro_y
gyro_z -= bias_gyro_z
##### Insert loop code below #########################
# Variables available
# ----------------------------------------------------
# count Current number of updates
# ts_prev Time stamp at the previous update
# ts_now Time stamp at this update
# acc_x Acceleration measured along the x axis
# acc_y Acceleration measured along the y axis
# acc_z Acceleration measured along the z axis
# gyro_x Angular velocity measured about the x axis
# gyro_y Angular velocity measured about the y axis
# gyro_z Angular velocity measured about the z axis
## Insert your code here ##
# calculate pitch (x-axis) and roll (y-axis) angles
pitch = atan2(acc_y,sqrt(acc_x*acc_x + acc_z*acc_z))
roll = atan2(-acc_x, acc_z)
# integrate gyro velocities to releative angles
gyro_x_rel += gyro_x*(ts_now-ts_prev)
gyro_y_rel += gyro_y*(ts_now-ts_prev)
gyro_z_rel += gyro_z*(ts_now-ts_prev)
# Kalman prediction step (we have new data in each iteration)
gyroVarAcc += gyroVar
estAngle += gyro_y*(ts_now-ts_prev)
estVar += gyroVarAcc*(ts_now-ts_prev)
# Kalman correction step (we have new data in each iteration)
K = estVar/(estVar+pitchVar)
estAngle += K*(roll-estAngle)
estVar *= (1-K)
gyroVarAcc = 0
# define which value to plot as the Kalman filter estimate
kalman_estimate = estAngle
# define which value to plot as the absolute value (pitch/roll)
pitch_roll_plot = roll
# define which value to plot as the relative gyro value
gyro_rel_plot = gyro_y_rel
######################################################
# if 3D liveview is enabled
if show3DLiveView == True and count % show3DLiveViewInterval == 0:
# determine what variables to liveview
roll_view = 0.0
yaw_view = 0.0
pitch_view = kalman_estimate
imuview.set_axis (-pitch_view, -yaw_view, roll_view)
imuview.update()
# if plotting is enabled
if showPlot == True:
plotDataGyro.append(gyro_rel_plot*180.0/pi)
plotDataAcc.append(pitch_roll_plot*180.0/pi)
plotDataKalman.append(kalman_estimate*180.0/pi)
# closing the file
f.close()
# show the plot
if showPlot == True:
ion()
plt.figure(1)
plt.title('Gyro integrated (relative) angle')
plt.plot(plotDataGyro)
plt.savefig('imu_exercise_gyro.png')
plt.figure(2)
plt.title('Accelerometer (blue) & Kalman estimation (red) angles')
plt.plot(plotDataAcc,'blue')
plt.plot(plotDataKalman,'red')
plt.savefig('imu_exercise_acc_kalman.png')
plt.draw()
print ('Press enter to quit')
real_raw_input = vars(__builtins__).get('raw_input',input)
real_raw_input()
| 26.112821 | 70 | 0.685389 |
from math import pi, sqrt, atan2
import matplotlib.pyplot as plt
from pylab import ion
leName = 'imu_razor_data_pitch_55deg.txt'
= 'sparkfun_razor'
showPlot = True
show3DLiveView = False
show3DLiveViewInterval = 3
if show3DLiveView == True:
from imu_box3d import imu_visualize
| true | true |
f7282111b09b84725bdd3773686ead033acf9be7 | 411 | py | Python | PlagiarismChecker/asgi.py | Esatyilmaz0/PlagiarismChecker | 1d345d131b69873e2238ac798d8cb142768ccb54 | [
"MIT"
] | null | null | null | PlagiarismChecker/asgi.py | Esatyilmaz0/PlagiarismChecker | 1d345d131b69873e2238ac798d8cb142768ccb54 | [
"MIT"
] | 2 | 2021-03-19T04:20:41.000Z | 2021-04-08T20:48:36.000Z | PlagiarismChecker/asgi.py | Esatyilmaz0/PlagiarismChecker | 1d345d131b69873e2238ac798d8cb142768ccb54 | [
"MIT"
] | null | null | null | """
ASGI config for PlagiarismChecker project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PlagiarismChecker.settings')
application = get_asgi_application()
| 24.176471 | 78 | 0.79562 |
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PlagiarismChecker.settings')
application = get_asgi_application()
| true | true |
f728212b851b7dbf65eadaf764ba43a74ab02d53 | 9,854 | py | Python | NeuralNetwok/NeuralNetwork.py | CanyellWang/MachineLearning_Python_wchy | d611538cdad31ab257baf837091f1dde2c3be5ec | [
"MIT"
] | 1 | 2018-07-07T08:32:18.000Z | 2018-07-07T08:32:18.000Z | NeuralNetwok/NeuralNetwork.py | EnochMHforever/MachineLearning_Python | 7eac77f7446a0c69bfb1a8be7da405895409d131 | [
"MIT"
] | null | null | null | NeuralNetwok/NeuralNetwork.py | EnochMHforever/MachineLearning_Python | 7eac77f7446a0c69bfb1a8be7da405895409d131 | [
"MIT"
] | 1 | 2020-09-29T14:10:27.000Z | 2020-09-29T14:10:27.000Z | #-*- coding: utf-8 -*-
import numpy as np
from scipy import io as spio
from matplotlib import pyplot as plt
from scipy import optimize
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14) # 解决windows环境下画图汉字乱码问题
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
import time
def neuralNetwork(input_layer_size,hidden_layer_size,out_put_layer):
data_img = loadmat_data("data_digits.mat")
X = data_img['X']
y = data_img['y']
'''scaler = StandardScaler()
scaler.fit(X)
X = scaler.transform(X)'''
m,n = X.shape
"""digits = datasets.load_digits()
X = digits.data
y = digits.target
m,n = X.shape
scaler = StandardScaler()
scaler.fit(X)
X = scaler.transform(X)"""
## 随机显示几行数据
rand_indices = [t for t in [np.random.randint(x-x, m) for x in range(100)]] # 生成100个0-m的随机数
display_data(X[rand_indices,:]) # 显示100个数字
#nn_params = np.vstack((Theta1.reshape(-1,1),Theta2.reshape(-1,1)))
Lambda = 1
initial_Theta1 = randInitializeWeights(input_layer_size,hidden_layer_size);
initial_Theta2 = randInitializeWeights(hidden_layer_size,out_put_layer)
initial_nn_params = np.vstack((initial_Theta1.reshape(-1,1),initial_Theta2.reshape(-1,1))) #展开theta
#np.savetxt("testTheta.csv",initial_nn_params,delimiter=",")
start = time.time()
result = optimize.fmin_cg(nnCostFunction, initial_nn_params, fprime=nnGradient, args=(input_layer_size,hidden_layer_size,out_put_layer,X,y,Lambda), maxiter=100)
print (u'执行时间:',time.time()-start)
print (result)
'''可视化 Theta1'''
length = result.shape[0]
Theta1 = result[0:hidden_layer_size*(input_layer_size+1)].reshape(hidden_layer_size,input_layer_size+1)
Theta2 = result[hidden_layer_size*(input_layer_size+1):length].reshape(out_put_layer,hidden_layer_size+1)
display_data(Theta1[:,1:length])
display_data(Theta2[:,1:length])
'''预测'''
p = predict(Theta1,Theta2,X)
print (u"预测准确度为:%f%%"%np.mean(np.float64(p == y.reshape(-1,1))*100))
res = np.hstack((p,y.reshape(-1,1)))
np.savetxt("predict.csv", res, delimiter=',')
# 加载mat文件
def loadmat_data(fileName):
return spio.loadmat(fileName)
# 显示100个数字
def display_data(imgData):
sum = 0
'''
显示100个数(若是一个一个绘制将会非常慢,可以将要画的数字整理好,放到一个矩阵中,显示这个矩阵即可)
- 初始化一个二维数组
- 将每行的数据调整成图像的矩阵,放进二维数组
- 显示即可
'''
m,n = imgData.shape
width = np.int32(np.round(np.sqrt(n)))
height = np.int32(n/width);
rows_count = np.int32(np.floor(np.sqrt(m)))
cols_count = np.int32(np.ceil(m/rows_count))
pad = 1
display_array = -np.ones((pad+rows_count*(height+pad),pad+cols_count*(width+pad)))
for i in range(rows_count):
for j in range(cols_count):
if sum >= m: #超过了行数,退出当前循环
break;
display_array[pad+i*(height+pad):pad+i*(height+pad)+height,pad+j*(width+pad):pad+j*(width+pad)+width] = imgData[sum,:].reshape(height,width,order="F") # order=F指定以列优先,在matlab中是这样的,python中需要指定,默认以行
sum += 1
if sum >= m: #超过了行数,退出当前循环
break;
plt.imshow(display_array,cmap='gray') #显示灰度图像
plt.axis('off')
plt.show()
# 代价函数
def nnCostFunction(nn_params,input_layer_size,hidden_layer_size,num_labels,X,y,Lambda):
length = nn_params.shape[0] # theta的中长度
# 还原theta1和theta2
Theta1 = nn_params[0:hidden_layer_size*(input_layer_size+1)].reshape(hidden_layer_size,input_layer_size+1)
Theta2 = nn_params[hidden_layer_size*(input_layer_size+1):length].reshape(num_labels,hidden_layer_size+1)
# np.savetxt("Theta1.csv",Theta1,delimiter=',')
m = X.shape[0]
class_y = np.zeros((m,num_labels)) # 数据的y对应0-9,需要映射为0/1的关系
# 映射y
for i in range(num_labels):
class_y[:,i] = np.int32(y==i).reshape(1,-1) # 注意reshape(1,-1)才可以赋值
'''去掉theta1和theta2的第一列,因为正则化时从1开始'''
Theta1_colCount = Theta1.shape[1]
Theta1_x = Theta1[:,1:Theta1_colCount]
Theta2_colCount = Theta2.shape[1]
Theta2_x = Theta2[:,1:Theta2_colCount]
# 正则化向theta^2
term = np.dot(np.transpose(np.vstack((Theta1_x.reshape(-1,1),Theta2_x.reshape(-1,1)))),np.vstack((Theta1_x.reshape(-1,1),Theta2_x.reshape(-1,1))))
'''正向传播,每次需要补上一列1的偏置bias'''
a1 = np.hstack((np.ones((m,1)),X))
z2 = np.dot(a1,np.transpose(Theta1))
a2 = sigmoid(z2)
a2 = np.hstack((np.ones((m,1)),a2))
z3 = np.dot(a2,np.transpose(Theta2))
h = sigmoid(z3)
'''代价'''
J = -(np.dot(np.transpose(class_y.reshape(-1,1)),np.log(h.reshape(-1,1)))+np.dot(np.transpose(1-class_y.reshape(-1,1)),np.log(1-h.reshape(-1,1)))-Lambda*term/2)/m
#temp1 = (h.reshape(-1,1)-class_y.reshape(-1,1))
#temp2 = (temp1**2).sum()
#J = 1/(2*m)*temp2
return np.ravel(J)
# 梯度
def nnGradient(nn_params,input_layer_size,hidden_layer_size,num_labels,X,y,Lambda):
length = nn_params.shape[0]
Theta1 = nn_params[0:hidden_layer_size*(input_layer_size+1)].reshape(hidden_layer_size,input_layer_size+1).copy() # 这里使用copy函数,否则下面修改Theta的值,nn_params也会一起修改
Theta2 = nn_params[hidden_layer_size*(input_layer_size+1):length].reshape(num_labels,hidden_layer_size+1).copy()
m = X.shape[0]
class_y = np.zeros((m,num_labels)) # 数据的y对应0-9,需要映射为0/1的关系
# 映射y
for i in range(num_labels):
class_y[:,i] = np.int32(y==i).reshape(1,-1) # 注意reshape(1,-1)才可以赋值
'''去掉theta1和theta2的第一列,因为正则化时从1开始'''
Theta1_colCount = Theta1.shape[1]
Theta1_x = Theta1[:,1:Theta1_colCount]
Theta2_colCount = Theta2.shape[1]
Theta2_x = Theta2[:,1:Theta2_colCount]
Theta1_grad = np.zeros((Theta1.shape)) #第一层到第二层的权重
Theta2_grad = np.zeros((Theta2.shape)) #第二层到第三层的权重
'''正向传播,每次需要补上一列1的偏置bias'''
a1 = np.hstack((np.ones((m,1)),X))
z2 = np.dot(a1,np.transpose(Theta1))
a2 = sigmoid(z2)
a2 = np.hstack((np.ones((m,1)),a2))
z3 = np.dot(a2,np.transpose(Theta2))
h = sigmoid(z3)
'''反向传播,delta为误差,'''
delta3 = np.zeros((m,num_labels))
delta2 = np.zeros((m,hidden_layer_size))
for i in range(m):
#delta3[i,:] = (h[i,:]-class_y[i,:])*sigmoidGradient(z3[i,:]) # 均方误差的误差率
delta3[i,:] = h[i,:]-class_y[i,:] # 交叉熵误差率
Theta2_grad = Theta2_grad+np.dot(np.transpose(delta3[i,:].reshape(1,-1)),a2[i,:].reshape(1,-1))
delta2[i,:] = np.dot(delta3[i,:].reshape(1,-1),Theta2_x)*sigmoidGradient(z2[i,:])
Theta1_grad = Theta1_grad+np.dot(np.transpose(delta2[i,:].reshape(1,-1)),a1[i,:].reshape(1,-1))
Theta1[:,0] = 0
Theta2[:,0] = 0
'''梯度'''
grad = (np.vstack((Theta1_grad.reshape(-1,1),Theta2_grad.reshape(-1,1)))+Lambda*np.vstack((Theta1.reshape(-1,1),Theta2.reshape(-1,1))))/m
return np.ravel(grad)
# S型函数
def sigmoid(z):
h = np.zeros((len(z),1)) # 初始化,与z的长度一致
h = 1.0/(1.0+np.exp(-z))
return h
# S型函数导数
def sigmoidGradient(z):
g = sigmoid(z)*(1-sigmoid(z))
return g
# 随机初始化权重theta
def randInitializeWeights(L_in,L_out):
W = np.zeros((L_out,1+L_in)) # 对应theta的权重
epsilon_init = (6.0/(L_out+L_in))**0.5
W = np.random.rand(L_out,1+L_in)*2*epsilon_init-epsilon_init # np.random.rand(L_out,1+L_in)产生L_out*(1+L_in)大小的随机矩阵
return W
# 检验梯度是否计算正确
def checkGradient(Lambda = 0):
'''构造一个小型的神经网络验证,因为数值法计算梯度很浪费时间,而且验证正确后之后就不再需要验证了'''
input_layer_size = 3
hidden_layer_size = 5
num_labels = 3
m = 5
initial_Theta1 = debugInitializeWeights(input_layer_size,hidden_layer_size);
initial_Theta2 = debugInitializeWeights(hidden_layer_size,num_labels)
X = debugInitializeWeights(input_layer_size-1,m)
y = 1+np.transpose(np.mod(np.arange(1,m+1), num_labels))# 初始化y
y = y.reshape(-1,1)
nn_params = np.vstack((initial_Theta1.reshape(-1,1),initial_Theta2.reshape(-1,1))) #展开theta
'''BP求出梯度'''
grad = nnGradient(nn_params, input_layer_size, hidden_layer_size,
num_labels, X, y, Lambda)
'''使用数值法计算梯度'''
num_grad = np.zeros((nn_params.shape[0]))
step = np.zeros((nn_params.shape[0]))
e = 1e-4
for i in range(nn_params.shape[0]):
step[i] = e
loss1 = nnCostFunction(nn_params-step.reshape(-1,1), input_layer_size, hidden_layer_size,
num_labels, X, y,
Lambda)
loss2 = nnCostFunction(nn_params+step.reshape(-1,1), input_layer_size, hidden_layer_size,
num_labels, X, y,
Lambda)
num_grad[i] = (loss2-loss1)/(2*e)
step[i]=0
# 显示两列比较
res = np.hstack((num_grad.reshape(-1,1),grad.reshape(-1,1)))
print("检查梯度的结果,第一列为数值法计算得到的,第二列为BP得到的:")
print (res)
# 初始化调试的theta权重
def debugInitializeWeights(fan_in,fan_out):
W = np.zeros((fan_out,fan_in+1))
x = np.arange(1,fan_out*(fan_in+1)+1)
W = np.sin(x).reshape(W.shape)/10
return W
# 预测
def predict(Theta1,Theta2,X):
m = X.shape[0]
num_labels = Theta2.shape[0]
#p = np.zeros((m,1))
'''正向传播,预测结果'''
X = np.hstack((np.ones((m,1)),X))
h1 = sigmoid(np.dot(X,np.transpose(Theta1)))
h1 = np.hstack((np.ones((m,1)),h1))
h2 = sigmoid(np.dot(h1,np.transpose(Theta2)))
'''
返回h中每一行最大值所在的列号
- np.max(h, axis=1)返回h中每一行的最大值(是某个数字的最大概率)
- 最后where找到的最大概率所在的列号(列号即是对应的数字)
'''
#np.savetxt("h2.csv",h2,delimiter=',')
p = np.array(np.where(h2[0,:] == np.max(h2, axis=1)[0]))
for i in np.arange(1, m):
t = np.array(np.where(h2[i,:] == np.max(h2, axis=1)[i]))
p = np.vstack((p,t))
return p
if __name__ == "__main__":
checkGradient()
neuralNetwork(400, 25, 10) | 37.045113 | 211 | 0.631926 |
import numpy as np
from scipy import io as spio
from matplotlib import pyplot as plt
from scipy import optimize
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
import time
def neuralNetwork(input_layer_size,hidden_layer_size,out_put_layer):
data_img = loadmat_data("data_digits.mat")
X = data_img['X']
y = data_img['y']
m,n = X.shape
indices = [t for t in [np.random.randint(x-x, m) for x in range(100)]]
display_data(X[rand_indices,:])
Lambda = 1
initial_Theta1 = randInitializeWeights(input_layer_size,hidden_layer_size);
initial_Theta2 = randInitializeWeights(hidden_layer_size,out_put_layer)
initial_nn_params = np.vstack((initial_Theta1.reshape(-1,1),initial_Theta2.reshape(-1,1)))
start = time.time()
result = optimize.fmin_cg(nnCostFunction, initial_nn_params, fprime=nnGradient, args=(input_layer_size,hidden_layer_size,out_put_layer,X,y,Lambda), maxiter=100)
print (u'执行时间:',time.time()-start)
print (result)
length = result.shape[0]
Theta1 = result[0:hidden_layer_size*(input_layer_size+1)].reshape(hidden_layer_size,input_layer_size+1)
Theta2 = result[hidden_layer_size*(input_layer_size+1):length].reshape(out_put_layer,hidden_layer_size+1)
display_data(Theta1[:,1:length])
display_data(Theta2[:,1:length])
p = predict(Theta1,Theta2,X)
print (u"预测准确度为:%f%%"%np.mean(np.float64(p == y.reshape(-1,1))*100))
res = np.hstack((p,y.reshape(-1,1)))
np.savetxt("predict.csv", res, delimiter=',')
def loadmat_data(fileName):
return spio.loadmat(fileName)
def display_data(imgData):
sum = 0
m,n = imgData.shape
width = np.int32(np.round(np.sqrt(n)))
height = np.int32(n/width);
rows_count = np.int32(np.floor(np.sqrt(m)))
cols_count = np.int32(np.ceil(m/rows_count))
pad = 1
display_array = -np.ones((pad+rows_count*(height+pad),pad+cols_count*(width+pad)))
for i in range(rows_count):
for j in range(cols_count):
if sum >= m:
break;
display_array[pad+i*(height+pad):pad+i*(height+pad)+height,pad+j*(width+pad):pad+j*(width+pad)+width] = imgData[sum,:].reshape(height,width,order="F")
sum += 1
if sum >= m:
break;
plt.imshow(display_array,cmap='gray')
plt.axis('off')
plt.show()
def nnCostFunction(nn_params,input_layer_size,hidden_layer_size,num_labels,X,y,Lambda):
length = nn_params.shape[0]
Theta1 = nn_params[0:hidden_layer_size*(input_layer_size+1)].reshape(hidden_layer_size,input_layer_size+1)
Theta2 = nn_params[hidden_layer_size*(input_layer_size+1):length].reshape(num_labels,hidden_layer_size+1)
m = X.shape[0]
class_y = np.zeros((m,num_labels))
for i in range(num_labels):
class_y[:,i] = np.int32(y==i).reshape(1,-1)
Theta1_colCount = Theta1.shape[1]
Theta1_x = Theta1[:,1:Theta1_colCount]
Theta2_colCount = Theta2.shape[1]
Theta2_x = Theta2[:,1:Theta2_colCount]
term = np.dot(np.transpose(np.vstack((Theta1_x.reshape(-1,1),Theta2_x.reshape(-1,1)))),np.vstack((Theta1_x.reshape(-1,1),Theta2_x.reshape(-1,1))))
a1 = np.hstack((np.ones((m,1)),X))
z2 = np.dot(a1,np.transpose(Theta1))
a2 = sigmoid(z2)
a2 = np.hstack((np.ones((m,1)),a2))
z3 = np.dot(a2,np.transpose(Theta2))
h = sigmoid(z3)
J = -(np.dot(np.transpose(class_y.reshape(-1,1)),np.log(h.reshape(-1,1)))+np.dot(np.transpose(1-class_y.reshape(-1,1)),np.log(1-h.reshape(-1,1)))-Lambda*term/2)/m
return np.ravel(J)
def nnGradient(nn_params,input_layer_size,hidden_layer_size,num_labels,X,y,Lambda):
length = nn_params.shape[0]
Theta1 = nn_params[0:hidden_layer_size*(input_layer_size+1)].reshape(hidden_layer_size,input_layer_size+1).copy()
Theta2 = nn_params[hidden_layer_size*(input_layer_size+1):length].reshape(num_labels,hidden_layer_size+1).copy()
m = X.shape[0]
class_y = np.zeros((m,num_labels))
for i in range(num_labels):
class_y[:,i] = np.int32(y==i).reshape(1,-1)
Theta1_colCount = Theta1.shape[1]
Theta1_x = Theta1[:,1:Theta1_colCount]
Theta2_colCount = Theta2.shape[1]
Theta2_x = Theta2[:,1:Theta2_colCount]
Theta1_grad = np.zeros((Theta1.shape))
Theta2_grad = np.zeros((Theta2.shape))
a1 = np.hstack((np.ones((m,1)),X))
z2 = np.dot(a1,np.transpose(Theta1))
a2 = sigmoid(z2)
a2 = np.hstack((np.ones((m,1)),a2))
z3 = np.dot(a2,np.transpose(Theta2))
h = sigmoid(z3)
delta3 = np.zeros((m,num_labels))
delta2 = np.zeros((m,hidden_layer_size))
for i in range(m):
elta3[i,:] = h[i,:]-class_y[i,:]
Theta2_grad = Theta2_grad+np.dot(np.transpose(delta3[i,:].reshape(1,-1)),a2[i,:].reshape(1,-1))
delta2[i,:] = np.dot(delta3[i,:].reshape(1,-1),Theta2_x)*sigmoidGradient(z2[i,:])
Theta1_grad = Theta1_grad+np.dot(np.transpose(delta2[i,:].reshape(1,-1)),a1[i,:].reshape(1,-1))
Theta1[:,0] = 0
Theta2[:,0] = 0
grad = (np.vstack((Theta1_grad.reshape(-1,1),Theta2_grad.reshape(-1,1)))+Lambda*np.vstack((Theta1.reshape(-1,1),Theta2.reshape(-1,1))))/m
return np.ravel(grad)
def sigmoid(z):
h = np.zeros((len(z),1))
h = 1.0/(1.0+np.exp(-z))
return h
def sigmoidGradient(z):
g = sigmoid(z)*(1-sigmoid(z))
return g
def randInitializeWeights(L_in,L_out):
W = np.zeros((L_out,1+L_in))
epsilon_init = (6.0/(L_out+L_in))**0.5
W = np.random.rand(L_out,1+L_in)*2*epsilon_init-epsilon_init
return W
def checkGradient(Lambda = 0):
input_layer_size = 3
hidden_layer_size = 5
num_labels = 3
m = 5
initial_Theta1 = debugInitializeWeights(input_layer_size,hidden_layer_size);
initial_Theta2 = debugInitializeWeights(hidden_layer_size,num_labels)
X = debugInitializeWeights(input_layer_size-1,m)
y = 1+np.transpose(np.mod(np.arange(1,m+1), num_labels))
y = y.reshape(-1,1)
nn_params = np.vstack((initial_Theta1.reshape(-1,1),initial_Theta2.reshape(-1,1)))
grad = nnGradient(nn_params, input_layer_size, hidden_layer_size,
num_labels, X, y, Lambda)
num_grad = np.zeros((nn_params.shape[0]))
step = np.zeros((nn_params.shape[0]))
e = 1e-4
for i in range(nn_params.shape[0]):
step[i] = e
loss1 = nnCostFunction(nn_params-step.reshape(-1,1), input_layer_size, hidden_layer_size,
num_labels, X, y,
Lambda)
loss2 = nnCostFunction(nn_params+step.reshape(-1,1), input_layer_size, hidden_layer_size,
num_labels, X, y,
Lambda)
num_grad[i] = (loss2-loss1)/(2*e)
step[i]=0
res = np.hstack((num_grad.reshape(-1,1),grad.reshape(-1,1)))
print("检查梯度的结果,第一列为数值法计算得到的,第二列为BP得到的:")
print (res)
def debugInitializeWeights(fan_in,fan_out):
W = np.zeros((fan_out,fan_in+1))
x = np.arange(1,fan_out*(fan_in+1)+1)
W = np.sin(x).reshape(W.shape)/10
return W
def predict(Theta1,Theta2,X):
m = X.shape[0]
num_labels = Theta2.shape[0]
X = np.hstack((np.ones((m,1)),X))
h1 = sigmoid(np.dot(X,np.transpose(Theta1)))
h1 = np.hstack((np.ones((m,1)),h1))
h2 = sigmoid(np.dot(h1,np.transpose(Theta2)))
p = np.array(np.where(h2[0,:] == np.max(h2, axis=1)[0]))
for i in np.arange(1, m):
t = np.array(np.where(h2[i,:] == np.max(h2, axis=1)[i]))
p = np.vstack((p,t))
return p
if __name__ == "__main__":
checkGradient()
neuralNetwork(400, 25, 10) | true | true |
f7282387d0e5f482087a84e3bc3f9fa8b9da6a4d | 2,948 | py | Python | httpie/config.py | Natim/httpie | 9fbe745987cd4faca843f9442e0240f84fcfff43 | [
"BSD-3-Clause"
] | 7 | 2017-08-03T03:11:44.000Z | 2022-03-25T14:52:52.000Z | httpie/config.py | Natim/httpie | 9fbe745987cd4faca843f9442e0240f84fcfff43 | [
"BSD-3-Clause"
] | 1 | 2017-01-09T12:45:19.000Z | 2017-01-09T12:52:06.000Z | httpie/config.py | Natim/httpie | 9fbe745987cd4faca843f9442e0240f84fcfff43 | [
"BSD-3-Clause"
] | 7 | 2016-09-07T10:08:59.000Z | 2017-05-17T08:06:45.000Z | import os
import json
import errno
from httpie import __version__
from httpie.compat import is_windows
DEFAULT_CONFIG_DIR = str(os.environ.get(
'HTTPIE_CONFIG_DIR',
os.path.expanduser('~/.httpie') if not is_windows else
os.path.expandvars(r'%APPDATA%\\httpie')
))
class BaseConfigDict(dict):
name = None
helpurl = None
about = None
def __getattr__(self, item):
return self[item]
def _get_path(self):
"""Return the config file path without side-effects."""
raise NotImplementedError()
@property
def path(self):
"""Return the config file path creating basedir, if needed."""
path = self._get_path()
try:
os.makedirs(os.path.dirname(path), mode=0o700)
except OSError as e:
if e.errno != errno.EEXIST:
raise
return path
def is_new(self):
return not os.path.exists(self._get_path())
def load(self):
try:
with open(self.path, 'rt') as f:
try:
data = json.load(f)
except ValueError as e:
raise ValueError(
'Invalid %s JSON: %s [%s]' %
(type(self).__name__, str(e), self.path)
)
self.update(data)
except IOError as e:
if e.errno != errno.ENOENT:
raise
def save(self):
self['__meta__'] = {
'httpie': __version__
}
if self.helpurl:
self['__meta__']['help'] = self.helpurl
if self.about:
self['__meta__']['about'] = self.about
with open(self.path, 'w') as f:
json.dump(self, f, indent=4, sort_keys=True, ensure_ascii=True)
f.write('\n')
def delete(self):
try:
os.unlink(self.path)
except OSError as e:
if e.errno != errno.ENOENT:
raise
class Config(BaseConfigDict):
name = 'config'
helpurl = 'https://github.com/jkbrzt/httpie#config'
about = 'HTTPie configuration file'
DEFAULTS = {
'default_options': []
}
def __init__(self, directory=DEFAULT_CONFIG_DIR):
super(Config, self).__init__()
self.update(self.DEFAULTS)
self.directory = directory
def load(self):
super(Config, self).load()
self._migrate_implicit_content_type()
def _get_path(self):
return os.path.join(self.directory, self.name + '.json')
def _migrate_implicit_content_type(self):
"""Migrate the removed implicit_content_type config option"""
try:
implicit_content_type = self.pop('implicit_content_type')
except KeyError:
pass
else:
if implicit_content_type == 'form':
self['default_options'].insert(0, '--form')
self.save()
self.load()
| 26.088496 | 75 | 0.552917 | import os
import json
import errno
from httpie import __version__
from httpie.compat import is_windows
DEFAULT_CONFIG_DIR = str(os.environ.get(
'HTTPIE_CONFIG_DIR',
os.path.expanduser('~/.httpie') if not is_windows else
os.path.expandvars(r'%APPDATA%\\httpie')
))
class BaseConfigDict(dict):
name = None
helpurl = None
about = None
def __getattr__(self, item):
return self[item]
def _get_path(self):
raise NotImplementedError()
@property
def path(self):
path = self._get_path()
try:
os.makedirs(os.path.dirname(path), mode=0o700)
except OSError as e:
if e.errno != errno.EEXIST:
raise
return path
def is_new(self):
return not os.path.exists(self._get_path())
def load(self):
try:
with open(self.path, 'rt') as f:
try:
data = json.load(f)
except ValueError as e:
raise ValueError(
'Invalid %s JSON: %s [%s]' %
(type(self).__name__, str(e), self.path)
)
self.update(data)
except IOError as e:
if e.errno != errno.ENOENT:
raise
def save(self):
self['__meta__'] = {
'httpie': __version__
}
if self.helpurl:
self['__meta__']['help'] = self.helpurl
if self.about:
self['__meta__']['about'] = self.about
with open(self.path, 'w') as f:
json.dump(self, f, indent=4, sort_keys=True, ensure_ascii=True)
f.write('\n')
def delete(self):
try:
os.unlink(self.path)
except OSError as e:
if e.errno != errno.ENOENT:
raise
class Config(BaseConfigDict):
name = 'config'
helpurl = 'https://github.com/jkbrzt/httpie#config'
about = 'HTTPie configuration file'
DEFAULTS = {
'default_options': []
}
def __init__(self, directory=DEFAULT_CONFIG_DIR):
super(Config, self).__init__()
self.update(self.DEFAULTS)
self.directory = directory
def load(self):
super(Config, self).load()
self._migrate_implicit_content_type()
def _get_path(self):
return os.path.join(self.directory, self.name + '.json')
def _migrate_implicit_content_type(self):
try:
implicit_content_type = self.pop('implicit_content_type')
except KeyError:
pass
else:
if implicit_content_type == 'form':
self['default_options'].insert(0, '--form')
self.save()
self.load()
| true | true |
f72823ae3f47dd0ed7719b074a8c86ef154f4075 | 16,177 | py | Python | ckanext/multilingual/plugin.py | doc22940/ckan | fb0174b77a5ac1c614717643d9b1b2a0c82ee088 | [
"Apache-2.0"
] | 58 | 2015-01-11T09:05:15.000Z | 2022-03-17T23:44:07.000Z | ckanext/multilingual/plugin.py | doc22940/ckan | fb0174b77a5ac1c614717643d9b1b2a0c82ee088 | [
"Apache-2.0"
] | 1,467 | 2015-01-01T16:47:44.000Z | 2022-02-28T16:51:20.000Z | ckanext/multilingual/plugin.py | cascaoSDC/ckan | 75a08caa7c688ce70229dfea7070cc667a15c5e8 | [
"BSD-3-Clause"
] | 17 | 2015-05-06T14:04:21.000Z | 2021-11-11T19:58:16.000Z | # encoding: utf-8
import six
from six import string_types
import ckan
from ckan.plugins import SingletonPlugin, implements, IPackageController
from ckan.plugins import IGroupController, IOrganizationController, ITagController, IResourceController
from ckan.common import request, config, c
from ckan.logic import get_action
try:
long # Python 2
except NameError:
long = int # Python 3
def translate_data_dict(data_dict):
'''Return the given dict (e.g. a dataset dict) with as many of its fields
as possible translated into the desired or the fallback language.
'''
desired_lang_code = request.environ['CKAN_LANG']
fallback_lang_code = config.get('ckan.locale_default', 'en')
# Get a flattened copy of data_dict to do the translation on.
flattened = ckan.lib.navl.dictization_functions.flatten_dict(
data_dict)
# Get a simple flat list of all the terms to be translated, from the
# flattened data dict.
terms = set()
for (key, value) in flattened.items():
if value in (None, True, False):
continue
elif isinstance(value, string_types):
terms.add(value)
elif isinstance(value, (int, long)):
continue
else:
for item in value:
if isinstance(value, dict):
if key == (u'organization',) and item == 'description':
terms.add(value[item])
else:
terms.add(item)
else:
terms.add(item)
# Get the translations of all the terms (as a list of dictionaries).
translations = get_action('term_translation_show')(
{'model': ckan.model},
{'terms': terms,
'lang_codes': (desired_lang_code, fallback_lang_code)})
# Transform the translations into a more convenient structure.
desired_translations = {}
fallback_translations = {}
for translation in translations:
if translation['lang_code'] == desired_lang_code:
desired_translations[translation['term']] = (
translation['term_translation'])
else:
assert translation['lang_code'] == fallback_lang_code
fallback_translations[translation['term']] = (
translation['term_translation'])
# Make a copy of the flattened data dict with all the terms replaced by
# their translations, where available.
translated_flattened = {}
for (key, value) in flattened.items():
# Don't translate names that are used for form URLs.
if key == ('name',):
translated_flattened[key] = value
elif (key[0] in ('tags', 'groups') and len(key) == 3
and key[2] == 'name'):
translated_flattened[key] = value
elif value in (None, True, False):
# Don't try to translate values that aren't strings.
translated_flattened[key] = value
elif isinstance(value, string_types):
if value in desired_translations:
translated_flattened[key] = desired_translations[value]
else:
translated_flattened[key] = fallback_translations.get(
value, value)
elif isinstance(value, (int, long, dict)):
if key == (u'organization',):
translated_flattened[key] = translate_data_dict(value);
else:
translated_flattened[key] = value
else:
translated_value = []
for item in value:
if item in desired_translations:
translated_value.append(desired_translations[item])
else:
translated_value.append(
fallback_translations.get(item, item)
)
translated_flattened[key] = translated_value
# Finally unflatten and return the translated data dict.
translated_data_dict = (ckan.lib.navl.dictization_functions
.unflatten(translated_flattened))
return translated_data_dict
def translate_resource_data_dict(data_dict):
'''Return the given dict with as many of its fields
as possible translated into the desired or the fallback language.
'''
desired_lang_code = request.environ['CKAN_LANG']
fallback_lang_code = config.get('ckan.locale_default', 'en')
# Get a flattened copy of data_dict to do the translation on.
flattened = ckan.lib.navl.dictization_functions.flatten_dict(
data_dict)
# Get a simple flat list of all the terms to be translated, from the
# flattened data dict.
terms = set()
for (key, value) in flattened.items():
if value in (None, True, False):
continue
elif isinstance(value, string_types):
terms.add(value)
elif isinstance(value, (int, long)):
continue
else:
for item in value:
terms.add(item)
# Get the translations of all the terms (as a list of dictionaries).
translations = ckan.logic.action.get.term_translation_show(
{'model': ckan.model},
{'terms': terms,
'lang_codes': (desired_lang_code, fallback_lang_code)})
# Transform the translations into a more convenient structure.
desired_translations = {}
fallback_translations = {}
for translation in translations:
if translation['lang_code'] == desired_lang_code:
desired_translations[translation['term']] = (
translation['term_translation'])
else:
assert translation['lang_code'] == fallback_lang_code
fallback_translations[translation['term']] = (
translation['term_translation'])
# Make a copy of the flattened data dict with all the terms replaced by
# their translations, where available.
translated_flattened = {}
for (key, value) in flattened.items():
# Don't translate names that are used for form URLs.
if key == ('name',):
if value in desired_translations:
translated_flattened[key] = desired_translations[value]
elif value in fallback_translations:
translated_flattened[key] = fallback_translations.get(value, value)
else:
translated_flattened[key] = value
elif value in (None, True, False):
# Don't try to translate values that aren't strings.
translated_flattened[key] = value
elif isinstance(value, string_types):
if value in desired_translations:
translated_flattened[key] = desired_translations[value]
else:
translated_flattened[key] = fallback_translations.get(
value, value)
elif isinstance(value, (int, long, dict)):
translated_flattened[key] = value
else:
translated_value = []
for item in value:
if item in desired_translations:
translated_value.append(desired_translations[item])
else:
translated_value.append(
fallback_translations.get(item, item)
)
translated_flattened[key] = translated_value
# Finally unflatten and return the translated data dict.
translated_data_dict = (ckan.lib.navl.dictization_functions
.unflatten(translated_flattened))
return translated_data_dict
KEYS_TO_IGNORE = ['state', 'revision_id', 'id', #title done seperately
'metadata_created', 'metadata_modified', 'site_id']
class MultilingualDataset(SingletonPlugin):
implements(IPackageController, inherit=True)
LANGS = config.get('ckan.locale_order', 'en').split(" ")
def before_index(self, search_data):
default_lang = search_data.get(
'lang_code',
config.get('ckan.locale_default', 'en')
)
## translate title
title = search_data.get('title')
search_data['title_' + default_lang] = title
title_translations = get_action('term_translation_show')(
{'model': ckan.model},
{'terms': [title],
'lang_codes': self.LANGS})
for translation in title_translations:
title_field = 'title_' + translation['lang_code']
search_data[title_field] = translation['term_translation']
## translate rest
all_terms = []
for key, value in sorted(six.iteritems(search_data)):
if key in KEYS_TO_IGNORE or key.startswith('title'):
continue
if not isinstance(value, list):
value = [value]
for item in value:
if isinstance(item, string_types):
all_terms.append(item)
field_translations = get_action('term_translation_show')(
{'model': ckan.model},
{'terms': all_terms,
'lang_codes': self.LANGS})
text_field_items = dict(('text_' + lang, []) for lang in self.LANGS)
text_field_items['text_' + default_lang].extend(all_terms)
for translation in sorted(field_translations, key=lambda tr: all_terms.index(tr['term'])):
lang_field = 'text_' + translation['lang_code']
text_field_items[lang_field].append(translation['term_translation'])
for key, value in six.iteritems(text_field_items):
search_data[key] = ' '.join(value)
return search_data
def before_search(self, search_params):
lang_set = set(self.LANGS)
try:
current_lang = request.environ['CKAN_LANG']
except TypeError as err:
if err.message == ('No object (name: request) has been registered '
'for this thread'):
# This happens when this code gets called as part of a paster
# command rather then as part of an HTTP request.
current_lang = config.get('ckan.locale_default')
else:
raise
except KeyError:
current_lang = config.get('ckan.locale_default')
# fallback to default locale if locale not in suported langs
if not current_lang in lang_set:
current_lang = config.get('ckan.locale_default')
# fallback to english if default locale is not supported
if not current_lang in lang_set:
current_lang = 'en'
# treat current lang differenly so remove from set
lang_set.remove(current_lang)
# weight current lang more highly
query_fields = 'title_%s^8 text_%s^4' % (current_lang, current_lang)
for lang in lang_set:
query_fields += ' title_%s^2 text_%s' % (lang, lang)
search_params['qf'] = query_fields
return search_params
def after_search(self, search_results, search_params):
# Translate the unselected search facets.
facets = search_results.get('search_facets')
if not facets:
return search_results
desired_lang_code = request.environ['CKAN_LANG']
fallback_lang_code = config.get('ckan.locale_default', 'en')
# Look up translations for all of the facets in one db query.
terms = set()
for facet in facets.values():
for item in facet['items']:
terms.add(item['display_name'])
translations = get_action('term_translation_show')(
{'model': ckan.model},
{'terms': terms,
'lang_codes': (desired_lang_code, fallback_lang_code)})
# Replace facet display names with translated ones.
for facet in facets.values():
for item in facet['items']:
matching_translations = [translation for
translation in translations
if translation['term'] == item['display_name']
and translation['lang_code'] == desired_lang_code]
if not matching_translations:
matching_translations = [translation for
translation in translations
if translation['term'] == item['display_name']
and translation['lang_code'] == fallback_lang_code]
if matching_translations:
assert len(matching_translations) == 1
item['display_name'] = (
matching_translations[0]['term_translation'])
return search_results
def before_view(self, dataset_dict):
# Translate any selected search facets (e.g. if we are rendering a
# group read page or the dataset index page): lookup translations of
# all the terms in c.fields (c.fields contains the selected facets)
# and save them in c.translated_fields where the templates can
# retrieve them later.
desired_lang_code = request.environ['CKAN_LANG']
fallback_lang_code = config.get('ckan.locale_default', 'en')
try:
fields = c.fields
except AttributeError:
return translate_data_dict(dataset_dict)
terms = [value for param, value in fields]
translations = get_action('term_translation_show')(
{'model': ckan.model},
{'terms': terms,
'lang_codes': (desired_lang_code, fallback_lang_code)})
c.translated_fields = {}
for param, value in fields:
matching_translations = [translation for translation in
translations if translation['term'] == value and
translation['lang_code'] == desired_lang_code]
if not matching_translations:
matching_translations = [translation for translation in
translations if translation['term'] == value and
translation['lang_code'] == fallback_lang_code]
if matching_translations:
assert len(matching_translations) == 1
translation = matching_translations[0]['term_translation']
c.translated_fields[(param, value)] = translation
# Now translate the fields of the dataset itself.
return translate_data_dict(dataset_dict)
class MultilingualGroup(SingletonPlugin):
'''The MultilingualGroup plugin translates group names and other group
fields on group read pages and on the group index page.
For example on the page /de/group/david the title "Dave's Books" at the
top of the page might be translated to "Dave's Bucher".
Datasets are also shown on group pages, but these are translated by the
MultilingualDataset plugin.
'''
implements(IGroupController, inherit=True)
implements(IOrganizationController, inherit=True)
def before_view(self, data_dict):
translated_data_dict = translate_data_dict(data_dict)
return translated_data_dict
class MultilingualTag(SingletonPlugin):
'''The MultilingualTag plugin translates tag names on tag read pages and
on the tag index page.
For example on the page /de/tag/tolstoy the title "Tag: tolstoy" at the
top of the page might be translated to "Tag: Tolstoi".
Datasets are also shown on tag pages, but these are translated by the
MultilingualDataset plugin.
'''
implements(ITagController, inherit=True)
def before_view(self, data_dict):
translated_data_dict = translate_data_dict(data_dict)
return translated_data_dict
class MultilingualResource(SingletonPlugin):
'''The MultilinguaResource plugin translate the selected resource name and description on resource
preview page.
'''
implements(IResourceController, inherit=True)
def before_show(self, data_dict):
translated_data_dict = translate_resource_data_dict(data_dict)
return translated_data_dict
| 39.456098 | 103 | 0.614885 |
import six
from six import string_types
import ckan
from ckan.plugins import SingletonPlugin, implements, IPackageController
from ckan.plugins import IGroupController, IOrganizationController, ITagController, IResourceController
from ckan.common import request, config, c
from ckan.logic import get_action
try:
long
except NameError:
long = int
def translate_data_dict(data_dict):
desired_lang_code = request.environ['CKAN_LANG']
fallback_lang_code = config.get('ckan.locale_default', 'en')
flattened = ckan.lib.navl.dictization_functions.flatten_dict(
data_dict)
terms = set()
for (key, value) in flattened.items():
if value in (None, True, False):
continue
elif isinstance(value, string_types):
terms.add(value)
elif isinstance(value, (int, long)):
continue
else:
for item in value:
if isinstance(value, dict):
if key == (u'organization',) and item == 'description':
terms.add(value[item])
else:
terms.add(item)
else:
terms.add(item)
translations = get_action('term_translation_show')(
{'model': ckan.model},
{'terms': terms,
'lang_codes': (desired_lang_code, fallback_lang_code)})
desired_translations = {}
fallback_translations = {}
for translation in translations:
if translation['lang_code'] == desired_lang_code:
desired_translations[translation['term']] = (
translation['term_translation'])
else:
assert translation['lang_code'] == fallback_lang_code
fallback_translations[translation['term']] = (
translation['term_translation'])
translated_flattened = {}
for (key, value) in flattened.items():
if key == ('name',):
translated_flattened[key] = value
elif (key[0] in ('tags', 'groups') and len(key) == 3
and key[2] == 'name'):
translated_flattened[key] = value
elif value in (None, True, False):
# Don't try to translate values that aren't strings.
translated_flattened[key] = value
elif isinstance(value, string_types):
if value in desired_translations:
translated_flattened[key] = desired_translations[value]
else:
translated_flattened[key] = fallback_translations.get(
value, value)
elif isinstance(value, (int, long, dict)):
if key == (u'organization',):
translated_flattened[key] = translate_data_dict(value);
else:
translated_flattened[key] = value
else:
translated_value = []
for item in value:
if item in desired_translations:
translated_value.append(desired_translations[item])
else:
translated_value.append(
fallback_translations.get(item, item)
)
translated_flattened[key] = translated_value
# Finally unflatten and return the translated data dict.
translated_data_dict = (ckan.lib.navl.dictization_functions
.unflatten(translated_flattened))
return translated_data_dict
def translate_resource_data_dict(data_dict):
desired_lang_code = request.environ['CKAN_LANG']
fallback_lang_code = config.get('ckan.locale_default', 'en')
# Get a flattened copy of data_dict to do the translation on.
flattened = ckan.lib.navl.dictization_functions.flatten_dict(
data_dict)
# Get a simple flat list of all the terms to be translated, from the
# flattened data dict.
terms = set()
for (key, value) in flattened.items():
if value in (None, True, False):
continue
elif isinstance(value, string_types):
terms.add(value)
elif isinstance(value, (int, long)):
continue
else:
for item in value:
terms.add(item)
# Get the translations of all the terms (as a list of dictionaries).
translations = ckan.logic.action.get.term_translation_show(
{'model': ckan.model},
{'terms': terms,
'lang_codes': (desired_lang_code, fallback_lang_code)})
# Transform the translations into a more convenient structure.
desired_translations = {}
fallback_translations = {}
for translation in translations:
if translation['lang_code'] == desired_lang_code:
desired_translations[translation['term']] = (
translation['term_translation'])
else:
assert translation['lang_code'] == fallback_lang_code
fallback_translations[translation['term']] = (
translation['term_translation'])
# Make a copy of the flattened data dict with all the terms replaced by
# their translations, where available.
translated_flattened = {}
for (key, value) in flattened.items():
# Don't translate names that are used for form URLs.
if key == ('name',):
if value in desired_translations:
translated_flattened[key] = desired_translations[value]
elif value in fallback_translations:
translated_flattened[key] = fallback_translations.get(value, value)
else:
translated_flattened[key] = value
elif value in (None, True, False):
translated_flattened[key] = value
elif isinstance(value, string_types):
if value in desired_translations:
translated_flattened[key] = desired_translations[value]
else:
translated_flattened[key] = fallback_translations.get(
value, value)
elif isinstance(value, (int, long, dict)):
translated_flattened[key] = value
else:
translated_value = []
for item in value:
if item in desired_translations:
translated_value.append(desired_translations[item])
else:
translated_value.append(
fallback_translations.get(item, item)
)
translated_flattened[key] = translated_value
translated_data_dict = (ckan.lib.navl.dictization_functions
.unflatten(translated_flattened))
return translated_data_dict
KEYS_TO_IGNORE = ['state', 'revision_id', 'id',
'metadata_created', 'metadata_modified', 'site_id']
class MultilingualDataset(SingletonPlugin):
implements(IPackageController, inherit=True)
LANGS = config.get('ckan.locale_order', 'en').split(" ")
def before_index(self, search_data):
default_lang = search_data.get(
'lang_code',
config.get('ckan.locale_default', 'en')
)
search_data.get('title')
search_data['title_' + default_lang] = title
title_translations = get_action('term_translation_show')(
{'model': ckan.model},
{'terms': [title],
'lang_codes': self.LANGS})
for translation in title_translations:
title_field = 'title_' + translation['lang_code']
search_data[title_field] = translation['term_translation']
ms = []
for key, value in sorted(six.iteritems(search_data)):
if key in KEYS_TO_IGNORE or key.startswith('title'):
continue
if not isinstance(value, list):
value = [value]
for item in value:
if isinstance(item, string_types):
all_terms.append(item)
field_translations = get_action('term_translation_show')(
{'model': ckan.model},
{'terms': all_terms,
'lang_codes': self.LANGS})
text_field_items = dict(('text_' + lang, []) for lang in self.LANGS)
text_field_items['text_' + default_lang].extend(all_terms)
for translation in sorted(field_translations, key=lambda tr: all_terms.index(tr['term'])):
lang_field = 'text_' + translation['lang_code']
text_field_items[lang_field].append(translation['term_translation'])
for key, value in six.iteritems(text_field_items):
search_data[key] = ' '.join(value)
return search_data
def before_search(self, search_params):
lang_set = set(self.LANGS)
try:
current_lang = request.environ['CKAN_LANG']
except TypeError as err:
if err.message == ('No object (name: request) has been registered '
'for this thread'):
current_lang = config.get('ckan.locale_default')
else:
raise
except KeyError:
current_lang = config.get('ckan.locale_default')
if not current_lang in lang_set:
current_lang = config.get('ckan.locale_default')
if not current_lang in lang_set:
current_lang = 'en'
lang_set.remove(current_lang)
query_fields = 'title_%s^8 text_%s^4' % (current_lang, current_lang)
for lang in lang_set:
query_fields += ' title_%s^2 text_%s' % (lang, lang)
search_params['qf'] = query_fields
return search_params
def after_search(self, search_results, search_params):
facets = search_results.get('search_facets')
if not facets:
return search_results
desired_lang_code = request.environ['CKAN_LANG']
fallback_lang_code = config.get('ckan.locale_default', 'en')
terms = set()
for facet in facets.values():
for item in facet['items']:
terms.add(item['display_name'])
translations = get_action('term_translation_show')(
{'model': ckan.model},
{'terms': terms,
'lang_codes': (desired_lang_code, fallback_lang_code)})
for facet in facets.values():
for item in facet['items']:
matching_translations = [translation for
translation in translations
if translation['term'] == item['display_name']
and translation['lang_code'] == desired_lang_code]
if not matching_translations:
matching_translations = [translation for
translation in translations
if translation['term'] == item['display_name']
and translation['lang_code'] == fallback_lang_code]
if matching_translations:
assert len(matching_translations) == 1
item['display_name'] = (
matching_translations[0]['term_translation'])
return search_results
def before_view(self, dataset_dict):
desired_lang_code = request.environ['CKAN_LANG']
fallback_lang_code = config.get('ckan.locale_default', 'en')
try:
fields = c.fields
except AttributeError:
return translate_data_dict(dataset_dict)
terms = [value for param, value in fields]
translations = get_action('term_translation_show')(
{'model': ckan.model},
{'terms': terms,
'lang_codes': (desired_lang_code, fallback_lang_code)})
c.translated_fields = {}
for param, value in fields:
matching_translations = [translation for translation in
translations if translation['term'] == value and
translation['lang_code'] == desired_lang_code]
if not matching_translations:
matching_translations = [translation for translation in
translations if translation['term'] == value and
translation['lang_code'] == fallback_lang_code]
if matching_translations:
assert len(matching_translations) == 1
translation = matching_translations[0]['term_translation']
c.translated_fields[(param, value)] = translation
return translate_data_dict(dataset_dict)
class MultilingualGroup(SingletonPlugin):
implements(IGroupController, inherit=True)
implements(IOrganizationController, inherit=True)
def before_view(self, data_dict):
translated_data_dict = translate_data_dict(data_dict)
return translated_data_dict
class MultilingualTag(SingletonPlugin):
implements(ITagController, inherit=True)
def before_view(self, data_dict):
translated_data_dict = translate_data_dict(data_dict)
return translated_data_dict
class MultilingualResource(SingletonPlugin):
implements(IResourceController, inherit=True)
def before_show(self, data_dict):
translated_data_dict = translate_resource_data_dict(data_dict)
return translated_data_dict
| true | true |
f72824c53c0c29f77fd3d7d7ea46704e9cd596b6 | 765 | py | Python | libcst/tests/test_tabs.py | hauntsaninja/LibCST | c023fa7c4caff3fd2b3946080f9a58b539b10363 | [
"Apache-2.0"
] | 3 | 2021-03-29T19:21:08.000Z | 2021-12-31T09:30:11.000Z | libcst/tests/test_tabs.py | hauntsaninja/LibCST | c023fa7c4caff3fd2b3946080f9a58b539b10363 | [
"Apache-2.0"
] | 1 | 2021-08-20T19:03:09.000Z | 2021-08-20T19:03:09.000Z | libcst/tests/test_tabs.py | hauntsaninja/LibCST | c023fa7c4caff3fd2b3946080f9a58b539b10363 | [
"Apache-2.0"
] | 3 | 2020-08-04T02:48:32.000Z | 2020-08-17T01:20:09.000Z | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from libcst._tabs import expand_tabs
from libcst.testing.utils import UnitTest, data_provider
class ExpandTabsTest(UnitTest):
@data_provider(
[
("\t", " " * 8),
("\t\t", " " * 16),
(" \t", " " * 8),
("\t ", " " * 12),
("abcd\t", "abcd "),
("abcdefg\t", "abcdefg "),
("abcdefgh\t", "abcdefgh "),
("\tsuffix", " suffix"),
]
)
def test_expand_tabs(self, input: str, output: str) -> None:
self.assertEqual(expand_tabs(input), output)
| 30.6 | 65 | 0.524183 |
from libcst._tabs import expand_tabs
from libcst.testing.utils import UnitTest, data_provider
class ExpandTabsTest(UnitTest):
@data_provider(
[
("\t", " " * 8),
("\t\t", " " * 16),
(" \t", " " * 8),
("\t ", " " * 12),
("abcd\t", "abcd "),
("abcdefg\t", "abcdefg "),
("abcdefgh\t", "abcdefgh "),
("\tsuffix", " suffix"),
]
)
def test_expand_tabs(self, input: str, output: str) -> None:
self.assertEqual(expand_tabs(input), output)
| true | true |
f728251641a661470d18227b859c49eb3a912a2b | 2,518 | py | Python | timer2.py | erictzimas/alarm | bb669ee365bb150c58d5629036b0447dedb5897e | [
"MIT"
] | null | null | null | timer2.py | erictzimas/alarm | bb669ee365bb150c58d5629036b0447dedb5897e | [
"MIT"
] | null | null | null | timer2.py | erictzimas/alarm | bb669ee365bb150c58d5629036b0447dedb5897e | [
"MIT"
] | null | null | null | from tkinter import *
import time
import os
from time import strftime
LARGE_FONT= ("Verdana", 12)
NORM_FONT = ("Helvetica", 10)
SMALL_FONT = ("Helvetica", 8)
global c
c = -1
global count
global solve
count = 0
counti = 0
def clicked():
global count
global secs
count += 1
secs=int(hms_to_seconds(te.get()))
global cii
cii = int(hms_to_seconds(te.get()))
lbl2.pack()
time2()
def clicked2():
global solve
time()
lbl.pack(anchor = 'center')
def time():
string = strftime('%H:%M:%S %p')
lbl.config(text = string)
lbl.after(1000, time)
def time2():
global cii
global solve
k=0
lbl2.config(text = convert(cii))
cii = cii - 1
if cii==-1:
popupmsg("Time is up!")
solve = lbl2.after(1000,time2)
def stop():
global solve
if solve:
lbl2.after_cancel(solve)
def popupmsg(msg):
global c
popup = Tk()
popup.resizable(False,False)
popup.geometry("200x100")
popup.wm_title("Alarm")
label = Label(popup, text=msg, font=(NORM_FONT, 30))
label.config(width=25)
os.system('say "Time is up"')
c = 0
B1 = Button(popup, text="Okay", command = popup.destroy)
B1.config(width=10)
label.pack()
B1.pack()
popup.mainloop()
def convert(seconds):
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
return "%d:%02d:%02d" % (hour, minutes, seconds)
def hms_to_seconds(t):
h, m, s = [int(i) for i in t.split(':')]
return 3600*h + 60*m + s
root = Tk()
root.title('Alarm')
w = Frame(root)
w.pack()
root.geometry("400x300")
lbl = Label(w,font = ('calibri', 40, 'bold'),
background = 'white',
foreground = 'black')
lbl.config(background='snow',fg='grey')
lbl2 = Label(w,font = ('calibri', 40, 'bold'),
background = 'white',
foreground = 'red')
button = Button(w,command = clicked,text = "Start")
button.config(width = 20)
button2 = Button(w,command = clicked2,text = "Clock")
button2.config(width = 20)
button3 = Button(w, command = stop ,text = 'Stop')
button3.config(width=20)
te = Entry(w,text = "time in minutes")
te.config(background='snow')
lab = Label(w,text = 'Enter time in seconds')
lab.config(background='snow')
lab.pack()
te.pack()
button2.pack()
button.pack()
button3.pack()
root.resizable(False,False)
mainloop()
| 19.826772 | 60 | 0.589357 | from tkinter import *
import time
import os
from time import strftime
LARGE_FONT= ("Verdana", 12)
NORM_FONT = ("Helvetica", 10)
SMALL_FONT = ("Helvetica", 8)
global c
c = -1
global count
global solve
count = 0
counti = 0
def clicked():
global count
global secs
count += 1
secs=int(hms_to_seconds(te.get()))
global cii
cii = int(hms_to_seconds(te.get()))
lbl2.pack()
time2()
def clicked2():
global solve
time()
lbl.pack(anchor = 'center')
def time():
string = strftime('%H:%M:%S %p')
lbl.config(text = string)
lbl.after(1000, time)
def time2():
global cii
global solve
k=0
lbl2.config(text = convert(cii))
cii = cii - 1
if cii==-1:
popupmsg("Time is up!")
solve = lbl2.after(1000,time2)
def stop():
global solve
if solve:
lbl2.after_cancel(solve)
def popupmsg(msg):
global c
popup = Tk()
popup.resizable(False,False)
popup.geometry("200x100")
popup.wm_title("Alarm")
label = Label(popup, text=msg, font=(NORM_FONT, 30))
label.config(width=25)
os.system('say "Time is up"')
c = 0
B1 = Button(popup, text="Okay", command = popup.destroy)
B1.config(width=10)
label.pack()
B1.pack()
popup.mainloop()
def convert(seconds):
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
return "%d:%02d:%02d" % (hour, minutes, seconds)
def hms_to_seconds(t):
h, m, s = [int(i) for i in t.split(':')]
return 3600*h + 60*m + s
root = Tk()
root.title('Alarm')
w = Frame(root)
w.pack()
root.geometry("400x300")
lbl = Label(w,font = ('calibri', 40, 'bold'),
background = 'white',
foreground = 'black')
lbl.config(background='snow',fg='grey')
lbl2 = Label(w,font = ('calibri', 40, 'bold'),
background = 'white',
foreground = 'red')
button = Button(w,command = clicked,text = "Start")
button.config(width = 20)
button2 = Button(w,command = clicked2,text = "Clock")
button2.config(width = 20)
button3 = Button(w, command = stop ,text = 'Stop')
button3.config(width=20)
te = Entry(w,text = "time in minutes")
te.config(background='snow')
lab = Label(w,text = 'Enter time in seconds')
lab.config(background='snow')
lab.pack()
te.pack()
button2.pack()
button.pack()
button3.pack()
root.resizable(False,False)
mainloop()
| true | true |
f728256f79b38f0f486a2e40550daf6dcc86f2fd | 684 | py | Python | lab/pytest/test_exercise_4.py | Christopher-MakeSchool/SPD-2.31-Testing-and-Architecture | 565f2d3c68c90f2d0aea2101dc6ad7f18b1c6c84 | [
"MIT"
] | null | null | null | lab/pytest/test_exercise_4.py | Christopher-MakeSchool/SPD-2.31-Testing-and-Architecture | 565f2d3c68c90f2d0aea2101dc6ad7f18b1c6c84 | [
"MIT"
] | null | null | null | lab/pytest/test_exercise_4.py | Christopher-MakeSchool/SPD-2.31-Testing-and-Architecture | 565f2d3c68c90f2d0aea2101dc6ad7f18b1c6c84 | [
"MIT"
] | null | null | null | # Test Exercise 4
import pytest
import math
from exercise_4 import extract_position
def test_extract_position():
assert extract_position(
'|error| numerical calculations could not converge.') == None
assert extract_position(
'|debug| numerical calculations could not converge.') == None
assert extract_position(
'|update| the positron location in the particle accelerator is x:21.432') == "21.432"
assert extract_position(
'|update| the positron location in the particle accelerator is x:43.283') == "43.283"
assert extract_position(
'|update| the positron location in the particle accelerator is x:175.319') == "175.319"
| 38 | 95 | 0.709064 |
import pytest
import math
from exercise_4 import extract_position
def test_extract_position():
assert extract_position(
'|error| numerical calculations could not converge.') == None
assert extract_position(
'|debug| numerical calculations could not converge.') == None
assert extract_position(
'|update| the positron location in the particle accelerator is x:21.432') == "21.432"
assert extract_position(
'|update| the positron location in the particle accelerator is x:43.283') == "43.283"
assert extract_position(
'|update| the positron location in the particle accelerator is x:175.319') == "175.319"
| true | true |
f72825b2522e09425a65482d219fd6fa130dbc48 | 1,046 | py | Python | openapi_core/deserializing/parameters/factories.py | Yarn-e/openapi-core | fda9fbd3bc1c0879818e00445e1ad0731f80b065 | [
"BSD-3-Clause"
] | 160 | 2017-11-20T13:39:04.000Z | 2022-03-31T14:48:27.000Z | openapi_core/deserializing/parameters/factories.py | Yarn-e/openapi-core | fda9fbd3bc1c0879818e00445e1ad0731f80b065 | [
"BSD-3-Clause"
] | 384 | 2017-09-21T12:42:31.000Z | 2022-03-21T17:21:05.000Z | openapi_core/deserializing/parameters/factories.py | Yarn-e/openapi-core | fda9fbd3bc1c0879818e00445e1ad0731f80b065 | [
"BSD-3-Clause"
] | 100 | 2017-11-21T08:07:01.000Z | 2022-01-20T20:32:52.000Z | from functools import partial
from openapi_core.deserializing.parameters.deserializers import (
CallableParameterDeserializer,
)
from openapi_core.deserializing.parameters.deserializers import (
UnsupportedStyleDeserializer,
)
from openapi_core.deserializing.parameters.util import split
from openapi_core.schema.parameters import get_style
class ParameterDeserializersFactory:
PARAMETER_STYLE_DESERIALIZERS = {
"form": partial(split, separator=","),
"simple": partial(split, separator=","),
"spaceDelimited": partial(split, separator=" "),
"pipeDelimited": partial(split, separator="|"),
}
def create(self, param_or_header):
style = get_style(param_or_header)
if style not in self.PARAMETER_STYLE_DESERIALIZERS:
return UnsupportedStyleDeserializer(param_or_header, style)
deserialize_callable = self.PARAMETER_STYLE_DESERIALIZERS[style]
return CallableParameterDeserializer(
param_or_header, style, deserialize_callable
)
| 32.6875 | 72 | 0.739006 | from functools import partial
from openapi_core.deserializing.parameters.deserializers import (
CallableParameterDeserializer,
)
from openapi_core.deserializing.parameters.deserializers import (
UnsupportedStyleDeserializer,
)
from openapi_core.deserializing.parameters.util import split
from openapi_core.schema.parameters import get_style
class ParameterDeserializersFactory:
PARAMETER_STYLE_DESERIALIZERS = {
"form": partial(split, separator=","),
"simple": partial(split, separator=","),
"spaceDelimited": partial(split, separator=" "),
"pipeDelimited": partial(split, separator="|"),
}
def create(self, param_or_header):
style = get_style(param_or_header)
if style not in self.PARAMETER_STYLE_DESERIALIZERS:
return UnsupportedStyleDeserializer(param_or_header, style)
deserialize_callable = self.PARAMETER_STYLE_DESERIALIZERS[style]
return CallableParameterDeserializer(
param_or_header, style, deserialize_callable
)
| true | true |
f72825e37db91a57dd111e97a492ed1ccc432677 | 1,560 | py | Python | app/models.py | wenzizone/simple-cmdb | 03e6c005e9e860531ffed72aacaf1ebf8c666035 | [
"Apache-2.0"
] | null | null | null | app/models.py | wenzizone/simple-cmdb | 03e6c005e9e860531ffed72aacaf1ebf8c666035 | [
"Apache-2.0"
] | null | null | null | app/models.py | wenzizone/simple-cmdb | 03e6c005e9e860531ffed72aacaf1ebf8c666035 | [
"Apache-2.0"
] | 1 | 2016-05-31T07:43:53.000Z | 2016-05-31T07:43:53.000Z | # -*- coding:utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
# 服务器所在机房
class Cloud(models.Model):
name = models.CharField(max_length=50)
comments = models.CharField(max_length=255, null=True)
# def __unicode__(self):
# return u'%d %s %s' % (self.id, self.name, self.comments)
# 服务项目
class Product(models.Model):
name = models.CharField(max_length=50)
subproduct = models.CharField(max_length=100)
product_info = models.CharField(max_length=255, null=True)
# def __unicode__(self):
# return u'%d %s %s %s' % (self.id, self.name, self.subproduct,
# self.product_info)
# 服务器信息
# 在添加服务器的时候人工输入或选择
class Server(models.Model):
public_ip = models.GenericIPAddressField()
cloud = models.ForeignKey(Cloud)
in_china = models.CharField(max_length=8)
product = models.ForeignKey(Product)
create_time = models.DateField()
server_status = models.CharField(max_length=20)
update_time = models.DateField(null=True)
# def __unicode__(self):
# return u'%d %s %s %s %s %s %s' % (self.id,
# self.objects.filter(cloud=models.Cloud.id), self.in_china, self.product,
# self.server_status, self.create_time, self.update_time)
# 服务器详细信息
# 在ansible执行的时候,自动更新
class Detail(models.Model):
server = models.ForeignKey(Server, unique=True)
hostname = models.CharField(max_length=255)
internal_ip = models.GenericIPAddressField()
system = models.CharField(max_length=50)
update_time = models.DateField(null=True)
| 28.363636 | 78 | 0.705769 |
from __future__ import unicode_literals
from django.db import models
class Cloud(models.Model):
name = models.CharField(max_length=50)
comments = models.CharField(max_length=255, null=True)
class Product(models.Model):
name = models.CharField(max_length=50)
subproduct = models.CharField(max_length=100)
product_info = models.CharField(max_length=255, null=True)
class Server(models.Model):
public_ip = models.GenericIPAddressField()
cloud = models.ForeignKey(Cloud)
in_china = models.CharField(max_length=8)
product = models.ForeignKey(Product)
create_time = models.DateField()
server_status = models.CharField(max_length=20)
update_time = models.DateField(null=True)
class Detail(models.Model):
server = models.ForeignKey(Server, unique=True)
hostname = models.CharField(max_length=255)
internal_ip = models.GenericIPAddressField()
system = models.CharField(max_length=50)
update_time = models.DateField(null=True)
| true | true |
f728269ce204904ddcf8174f285421600acaf66c | 286 | py | Python | setup.py | zaherweb/webcolors | e98b0827964e7fceab81561673354bee972440bf | [
"BSD-3-Clause"
] | 101 | 2015-04-07T22:26:04.000Z | 2022-03-31T21:13:07.000Z | setup.py | JeremyDemers/webcolors | 7950574f67eb156c0b5ae2a884652b7ab29f92f6 | [
"BSD-3-Clause"
] | 12 | 2015-06-07T00:19:51.000Z | 2021-08-02T18:31:44.000Z | setup.py | JeremyDemers/webcolors | 7950574f67eb156c0b5ae2a884652b7ab29f92f6 | [
"BSD-3-Clause"
] | 22 | 2016-04-29T18:28:56.000Z | 2022-03-16T08:54:17.000Z | from glob import glob
from os.path import basename, splitext
from setuptools import find_packages, setup
setup(
packages=find_packages("src"),
package_dir={"": "src"},
py_modules=[splitext(basename(path))[0] for path in glob("src/*.py")],
python_requires=">=3.5,",
)
| 22 | 74 | 0.688811 | from glob import glob
from os.path import basename, splitext
from setuptools import find_packages, setup
setup(
packages=find_packages("src"),
package_dir={"": "src"},
py_modules=[splitext(basename(path))[0] for path in glob("src/*.py")],
python_requires=">=3.5,",
)
| true | true |
f72827bfdd4377187c67cafc843a1a332d35b2e2 | 18,433 | py | Python | pyprob/nn/dataset.py | bayesianbrad/pyprob | a426fc51c1d6da13052979c21af447f9c4023642 | [
"BSD-2-Clause"
] | 1 | 2019-09-21T21:37:50.000Z | 2019-09-21T21:37:50.000Z | pyprob/nn/dataset.py | bayesianbrad/pyprob | a426fc51c1d6da13052979c21af447f9c4023642 | [
"BSD-2-Clause"
] | null | null | null | pyprob/nn/dataset.py | bayesianbrad/pyprob | a426fc51c1d6da13052979c21af447f9c4023642 | [
"BSD-2-Clause"
] | null | null | null | import torch
from torch.utils.data import Dataset, ConcatDataset, Sampler
import torch.distributed as dist
import math
import os
import sys
import shelve
from glob import glob
import numpy as np
import uuid
from termcolor import colored
from collections import Counter, OrderedDict
import random
from .. import util
from ..util import TraceMode, PriorInflation
from ..concurrency import ConcurrentShelf
class Batch():
def __init__(self, traces):
self.traces = traces
self.size = len(traces)
sub_batches = {}
total_length_controlled = 0
for trace in traces:
tl = trace.length_controlled
if tl == 0:
raise ValueError('Trace of length zero.')
total_length_controlled += tl
trace_hash = ''.join([variable.address for variable in trace.variables_controlled])
if trace_hash not in sub_batches:
sub_batches[trace_hash] = []
sub_batches[trace_hash].append(trace)
self.sub_batches = list(sub_batches.values())
self.mean_length_controlled = total_length_controlled / self.size
def __len__(self):
return len(self.traces)
def __getitem__(self, key):
return self.traces[key]
def to(self, device):
for trace in self.traces:
trace.to(device=device)
class OnlineDataset(Dataset):
def __init__(self, model, length=None, prior_inflation=PriorInflation.DISABLED):
self._model = model
if length is None:
length = int(1e6)
self._length = length
self._prior_inflation = prior_inflation
def __len__(self):
return self._length
def __getitem__(self, idx):
return next(self._model._trace_generator(trace_mode=TraceMode.PRIOR_FOR_INFERENCE_NETWORK, prior_inflation=self._prior_inflation))
@staticmethod
def _prune_trace(trace):
del(trace.variables)
# trace.variables_controlled = []
del(trace.variables_uncontrolled)
del(trace.variables_replaced)
del(trace.variables_observed)
del(trace.variables_observable)
del(trace.variables_tagged)
del(trace.variables_dict_address)
del(trace.variables_dict_address_base)
# trace.named_variables = {}
del(trace.result)
del(trace.log_prob)
del(trace.log_prob_observed)
# del(trace.log_importance_weight)
# trace.length = 0
# trace.length_controlled = 0
del(trace.execution_time_sec)
for variable in trace.variables_controlled:
# variable.distribution = distribution
# if value is None:
# variable.value = None
# else:
# variable.value = util.to_tensor(value)
del(variable.address_base)
# variable.address = address
del(variable.instance)
del(variable.log_prob)
del(variable.control)
del(variable.replace)
del(variable.name)
del(variable.observable)
del(variable.observed)
del(variable.reused)
del(variable.tagged)
for _, variable in trace.named_variables.items():
controlled = False
for v in trace.variables_controlled:
if variable is v: # Needs to be implemented this way to compare object references instead of object hashes (which change as a result of potentially deleted fields)
controlled = True
break
if not controlled:
del(variable.distribution)
# if value is None:
# variable.value = None
# else:
# variable.value = util.to_tensor(value)
del(variable.address_base)
del(variable.address)
del(variable.instance)
del(variable.log_prob)
del(variable.control)
del(variable.replace)
del(variable.name)
del(variable.observable)
del(variable.observed)
del(variable.reused)
del(variable.tagged)
def save_dataset(self, dataset_dir, num_traces, num_traces_per_file, *args, **kwargs):
num_files = math.ceil(num_traces / num_traces_per_file)
util.progress_bar_init('Saving offline dataset, traces:{}, traces per file:{}, files:{}'.format(num_traces, num_traces_per_file, num_files), num_traces, 'Traces')
i = 0
while i < num_traces:
i += num_traces_per_file
file_name = os.path.join(dataset_dir, 'pyprob_traces_{}_{}'.format(num_traces_per_file, str(uuid.uuid4())))
shelf = shelve.open(file_name, flag='c')
for j in range(num_traces_per_file):
trace = next(self._model._trace_generator(trace_mode=TraceMode.PRIOR, prior_inflation=self._prior_inflation, *args, **kwargs))
self._prune_trace(trace)
shelf[str(j)] = trace
shelf['__length'] = j + 1
shelf.close()
util.progress_bar_update(i)
util.progress_bar_end()
class OfflineDatasetFile(Dataset):
cache = OrderedDict()
cache_capacity = 8
def __init__(self, file_name):
self._file_name = file_name
self._closed = False
shelf = self._open()
self._length = shelf['__length']
def _open(self):
# idea from https://www.kunxi.org/2014/05/lru-cache-in-python
try:
shelf = OfflineDatasetFile.cache.pop(self._file_name)
# it was in the cache, put it back on the front
OfflineDatasetFile.cache[self._file_name] = shelf
return shelf
except KeyError:
# not in the cache
if len(OfflineDatasetFile.cache) >= OfflineDatasetFile.cache_capacity:
# cache is full, delete the last entry
n, s = OfflineDatasetFile.cache.popitem(last=False)
s.close()
shelf = shelve.open(self._file_name, flag='r')
OfflineDatasetFile.cache[self._file_name] = shelf
return shelf
def __len__(self):
return self._length
def __getitem__(self, idx):
shelf = self._open()
return shelf[str(idx)]
class OfflineDataset(ConcatDataset):
def __init__(self, dataset_dir):
self._dataset_dir = dataset_dir
# files = [name for name in os.listdir(self._dataset_dir)]
files = sorted(glob(os.path.join(self._dataset_dir, 'pyprob_traces_sorted_*')))
if len(files) > 0:
self._sorted_on_disk = True
else:
self._sorted_on_disk = False
files = sorted(glob(os.path.join(self._dataset_dir, 'pyprob_traces_*')))
if len(files) == 0:
raise RuntimeError('Cannot find any data set files at {}'.format(dataset_dir))
datasets = []
for file in files:
try:
dataset = OfflineDatasetFile(file)
datasets.append(dataset)
except Exception as e:
print(e)
print(colored('Warning: dataset file potentially corrupt, omitting: {}'.format(file), 'red', attrs=['bold']))
super().__init__(datasets)
print('OfflineDataset at: {}'.format(self._dataset_dir))
print('Num. traces : {:,}'.format(len(self)))
print('Sorted on disk : {}'.format(self._sorted_on_disk))
if self._sorted_on_disk:
self._sorted_indices = list(range(len(self)))
else:
file_name = os.path.join(self._dataset_dir, 'pyprob_hashes')
try:
hashes_file = shelve.open(file_name, 'r')
hashes_exist = 'hashes' in hashes_file
hashes_file.close()
except:
hashes_exist = False
if hashes_exist:
print('Using pre-computed hashes in: {}'.format(file_name))
hashes_file = shelve.open(file_name, 'r')
self._hashes = hashes_file['hashes']
self._sorted_indices = hashes_file['sorted_indices']
hashes_file.close()
if torch.is_tensor(self._hashes):
self._hashes = self._hashes.cpu().numpy()
if len(self._sorted_indices) != len(self):
raise RuntimeError('Length of pre-computed hashes ({}) and length of offline dataset ({}) do not match. Dataset files have been altered. Delete and re-generate pre-computed hash file: {}'.format(len(self._sorted_indices), len(self), file_name))
else:
print('No pre-computed hashes found, generating: {}'.format(file_name))
hashes_file = shelve.open(file_name, 'c')
hashes, sorted_indices = self._compute_hashes()
hashes_file['hashes'] = hashes
hashes_file['sorted_indices'] = sorted_indices
hashes_file.close()
self._sorted_indices = sorted_indices
self._hashes = hashes
print('Num. trace types : {:,}'.format(len(set(self._hashes))))
hashes_and_counts = OrderedDict(sorted(Counter(self._hashes).items()))
print('Trace hash\tCount')
for hash, count in hashes_and_counts.items():
print('{:.8f}\t{}'.format(hash, count))
print()
@staticmethod
def _trace_hash(trace):
h = hash(''.join([variable.address for variable in trace.variables_controlled])) + sys.maxsize + 1
return float('{}.{}'.format(trace.length_controlled, h))
def _compute_hashes(self):
hashes = torch.zeros(len(self))
util.progress_bar_init('Hashing offline dataset for sorting', len(self), 'Traces')
for i in range(len(self)):
hashes[i] = self._trace_hash(self[i])
util.progress_bar_update(i)
util.progress_bar_end()
print('Sorting offline dataset')
_, sorted_indices = torch.sort(hashes)
print('Sorting done')
return hashes.cpu().numpy(), sorted_indices.cpu().numpy()
def save_sorted(self, sorted_dataset_dir, num_traces_per_file=None, num_files=None, begin_file_index=None, end_file_index=None):
if num_traces_per_file is not None:
if num_files is not None:
raise ValueError('Expecting either num_traces_per_file or num_files')
else:
if num_files is None:
raise ValueError('Expecting either num_traces_per_file or num_files')
else:
num_traces_per_file = math.ceil(len(self) / num_files)
if os.path.exists(sorted_dataset_dir):
if len(glob(os.path.join(sorted_dataset_dir, '*'))) > 0:
print(colored('Warning: target directory is not empty: {})'.format(sorted_dataset_dir), 'red', attrs=['bold']))
util.create_path(sorted_dataset_dir, directory=True)
file_indices = list(util.chunks(list(self._sorted_indices), num_traces_per_file))
num_traces = len(self)
num_files = len(file_indices)
num_files_digits = len(str(num_files))
file_name_template = 'pyprob_traces_sorted_{{:d}}_{{:0{}d}}'.format(num_files_digits)
file_names = list(map(lambda x: os.path.join(sorted_dataset_dir, file_name_template.format(num_traces_per_file, x)), range(num_files)))
if begin_file_index is None:
begin_file_index = 0
if end_file_index is None:
end_file_index = num_files
if begin_file_index < 0 or begin_file_index > end_file_index or end_file_index > num_files or end_file_index < begin_file_index:
raise ValueError('Invalid indexes begin_file_index:{} and end_file_index: {}'.format(begin_file_index, end_file_index))
print('Sorted offline dataset, traces: {}, traces per file: {}, files: {} (overall)'.format(num_traces, num_traces_per_file, num_files))
util.progress_bar_init('Saving sorted files with indices in range [{}, {}) ({} of {} files overall)'.format(begin_file_index, end_file_index, end_file_index - begin_file_index, num_files), end_file_index - begin_file_index + 1, 'Files')
j = 0
for i in range(begin_file_index, end_file_index):
j += 1
file_name = file_names[i]
print(file_name)
shelf = ConcurrentShelf(file_name)
shelf.lock(write=True)
for new_i, old_i in enumerate(file_indices[i]):
shelf[str(new_i)] = self[old_i]
shelf['__length'] = len(file_indices[i])
shelf.unlock()
util.progress_bar_update(j)
util.progress_bar_end()
class TraceSampler(Sampler):
def __init__(self, offline_dataset):
if not isinstance(offline_dataset, OfflineDataset):
raise TypeError('Expecting an OfflineDataset instance.')
self._sorted_indices = offline_dataset._sorted_indices
def __iter__(self):
return iter(self._sorted_indices)
def __len__(self):
return len(self._offline_dataset)
class TraceBatchSampler(Sampler):
def __init__(self, offline_dataset, batch_size, shuffle_batches=True):
if not isinstance(offline_dataset, OfflineDataset):
raise TypeError('Expecting an OfflineDataset instance.')
self._batches = list(util.chunks(offline_dataset._sorted_indices, batch_size))
self._shuffle_batches = shuffle_batches
def __iter__(self):
if self._shuffle_batches:
np.random.shuffle(self._batches)
return iter(self._batches)
def __len__(self):
return len(self._batches)
class DistributedTraceBatchSampler(Sampler):
def __init__(self, offline_dataset, batch_size, shuffle_batches=True, num_buckets=None, shuffle_buckets=True):
if not isinstance(offline_dataset, OfflineDataset):
raise TypeError('Expecting an OfflineDataset instance.')
if not dist.is_available():
raise RuntimeError('Expecting distributed training.')
self._world_size = dist.get_world_size()
self._rank = dist.get_rank()
# Randomly drop a number of traces so that the number of all minibatches in the whole dataset is an integer multiple of world size
num_batches_to_drop = math.floor(len(offline_dataset._sorted_indices) / batch_size) % self._world_size
num_traces_to_drop = num_batches_to_drop * batch_size
# Ensure all ranks choose the same traces to drop
st = random.getstate()
random.seed(0)
self._batches = list(util.chunks(util.drop_items(list(offline_dataset._sorted_indices), num_traces_to_drop), batch_size)) # List of all minibatches, where each minibatch is a list of trace indices
random.setstate(st)
# Discard last minibatch if it's smaller than batch_size
if len(self._batches[-1]) < batch_size:
del(self._batches[-1])
if num_buckets is None:
num_buckets = len(self._batches) / self._world_size
self._num_buckets = num_buckets
self._bucket_size = math.ceil(len(self._batches) / num_buckets)
if self._bucket_size < self._world_size:
raise RuntimeError('offline_dataset:{}, batch_size:{} and num_buckets:{} imply a bucket_size:{} smaller than world_size:{}'.format(len(offline_dataset), batch_size, num_buckets, self._bucket_size, self._world_size))
# List of buckets, where each bucket is a list of minibatches
self._buckets = list(util.chunks(self._batches, self._bucket_size))
# Unify last two buckets if the last bucket is smaller than other buckets
if len(self._buckets[-1]) < self._bucket_size:
if len(self._buckets) < 2:
raise RuntimeError('offline_dataset:{} too small for given batch_size:{} and num_buckets:{}'.format(len(offline_dataset), batch_size, num_buckets))
self._buckets[-2].extend(self._buckets[-1])
del(self._buckets[-1])
self._shuffle_batches = shuffle_batches
self._shuffle_buckets = shuffle_buckets
self._epoch = 0
self._current_bucket_id = 0
print('DistributedTraceBatchSampler')
print('OfflineDataset size : {:,}'.format(len(offline_dataset)))
print('World size : {:,}'.format(self._world_size))
print('Batch size : {:,}'.format(batch_size))
print('Num. batches dropped: {:,}'.format(num_batches_to_drop))
print('Num. batches : {:,}'.format(len(self._batches)))
print('Bucket size : {:,}'.format(self._bucket_size))
print('Num. buckets : {:,}'.format(self._num_buckets))
def __iter__(self):
self._epoch += 1
bucket_ids = list(range(len(self._buckets)))
if self._shuffle_buckets:
# Shuffle the list of buckets (but not the order of minibatches inside each bucket) at the beginning of each epoch, deterministically based on the epoch number so that all nodes have the same bucket order
# Idea from: https://github.com/pytorch/pytorch/blob/a3fb004b1829880547dd7b3e2cd9d16af657b869/torch/utils/data/distributed.py#L44
st = np.random.get_state()
np.random.seed(self._epoch)
np.random.shuffle(bucket_ids)
np.random.set_state(st)
for bucket_id in bucket_ids:
bucket = self._buckets[bucket_id]
self._current_bucket_id = bucket_id
# num_batches is needed to ensure that all nodes have the same number of minibatches (iterations) in each bucket, in cases where the bucket size is not divisible by world_size.
num_batches = math.floor(len(bucket) / self._world_size)
# Select a num_batches-sized subset of the current bucket for the current node
# The part not selected by the current node will be selected by other nodes
batches = bucket[self._rank:len(bucket):self._world_size][:num_batches]
if self._shuffle_batches:
# Shuffle the list of minibatches (but not the order trace indices inside each minibatch) selected for the current node
np.random.shuffle(batches)
for batch in batches:
yield batch
def __len__(self):
return len(self._batches)
| 46.197995 | 264 | 0.632615 | import torch
from torch.utils.data import Dataset, ConcatDataset, Sampler
import torch.distributed as dist
import math
import os
import sys
import shelve
from glob import glob
import numpy as np
import uuid
from termcolor import colored
from collections import Counter, OrderedDict
import random
from .. import util
from ..util import TraceMode, PriorInflation
from ..concurrency import ConcurrentShelf
class Batch():
def __init__(self, traces):
self.traces = traces
self.size = len(traces)
sub_batches = {}
total_length_controlled = 0
for trace in traces:
tl = trace.length_controlled
if tl == 0:
raise ValueError('Trace of length zero.')
total_length_controlled += tl
trace_hash = ''.join([variable.address for variable in trace.variables_controlled])
if trace_hash not in sub_batches:
sub_batches[trace_hash] = []
sub_batches[trace_hash].append(trace)
self.sub_batches = list(sub_batches.values())
self.mean_length_controlled = total_length_controlled / self.size
def __len__(self):
return len(self.traces)
def __getitem__(self, key):
return self.traces[key]
def to(self, device):
for trace in self.traces:
trace.to(device=device)
class OnlineDataset(Dataset):
def __init__(self, model, length=None, prior_inflation=PriorInflation.DISABLED):
self._model = model
if length is None:
length = int(1e6)
self._length = length
self._prior_inflation = prior_inflation
def __len__(self):
return self._length
def __getitem__(self, idx):
return next(self._model._trace_generator(trace_mode=TraceMode.PRIOR_FOR_INFERENCE_NETWORK, prior_inflation=self._prior_inflation))
@staticmethod
def _prune_trace(trace):
del(trace.variables)
del(trace.variables_uncontrolled)
del(trace.variables_replaced)
del(trace.variables_observed)
del(trace.variables_observable)
del(trace.variables_tagged)
del(trace.variables_dict_address)
del(trace.variables_dict_address_base)
del(trace.result)
del(trace.log_prob)
del(trace.log_prob_observed)
del(trace.execution_time_sec)
for variable in trace.variables_controlled:
del(variable.address_base)
del(variable.instance)
del(variable.log_prob)
del(variable.control)
del(variable.replace)
del(variable.name)
del(variable.observable)
del(variable.observed)
del(variable.reused)
del(variable.tagged)
for _, variable in trace.named_variables.items():
controlled = False
for v in trace.variables_controlled:
if variable is v:
controlled = True
break
if not controlled:
del(variable.distribution)
del(variable.address_base)
del(variable.address)
del(variable.instance)
del(variable.log_prob)
del(variable.control)
del(variable.replace)
del(variable.name)
del(variable.observable)
del(variable.observed)
del(variable.reused)
del(variable.tagged)
def save_dataset(self, dataset_dir, num_traces, num_traces_per_file, *args, **kwargs):
num_files = math.ceil(num_traces / num_traces_per_file)
util.progress_bar_init('Saving offline dataset, traces:{}, traces per file:{}, files:{}'.format(num_traces, num_traces_per_file, num_files), num_traces, 'Traces')
i = 0
while i < num_traces:
i += num_traces_per_file
file_name = os.path.join(dataset_dir, 'pyprob_traces_{}_{}'.format(num_traces_per_file, str(uuid.uuid4())))
shelf = shelve.open(file_name, flag='c')
for j in range(num_traces_per_file):
trace = next(self._model._trace_generator(trace_mode=TraceMode.PRIOR, prior_inflation=self._prior_inflation, *args, **kwargs))
self._prune_trace(trace)
shelf[str(j)] = trace
shelf['__length'] = j + 1
shelf.close()
util.progress_bar_update(i)
util.progress_bar_end()
class OfflineDatasetFile(Dataset):
cache = OrderedDict()
cache_capacity = 8
def __init__(self, file_name):
self._file_name = file_name
self._closed = False
shelf = self._open()
self._length = shelf['__length']
def _open(self):
try:
shelf = OfflineDatasetFile.cache.pop(self._file_name)
OfflineDatasetFile.cache[self._file_name] = shelf
return shelf
except KeyError:
if len(OfflineDatasetFile.cache) >= OfflineDatasetFile.cache_capacity:
n, s = OfflineDatasetFile.cache.popitem(last=False)
s.close()
shelf = shelve.open(self._file_name, flag='r')
OfflineDatasetFile.cache[self._file_name] = shelf
return shelf
def __len__(self):
return self._length
def __getitem__(self, idx):
shelf = self._open()
return shelf[str(idx)]
class OfflineDataset(ConcatDataset):
def __init__(self, dataset_dir):
self._dataset_dir = dataset_dir
files = sorted(glob(os.path.join(self._dataset_dir, 'pyprob_traces_sorted_*')))
if len(files) > 0:
self._sorted_on_disk = True
else:
self._sorted_on_disk = False
files = sorted(glob(os.path.join(self._dataset_dir, 'pyprob_traces_*')))
if len(files) == 0:
raise RuntimeError('Cannot find any data set files at {}'.format(dataset_dir))
datasets = []
for file in files:
try:
dataset = OfflineDatasetFile(file)
datasets.append(dataset)
except Exception as e:
print(e)
print(colored('Warning: dataset file potentially corrupt, omitting: {}'.format(file), 'red', attrs=['bold']))
super().__init__(datasets)
print('OfflineDataset at: {}'.format(self._dataset_dir))
print('Num. traces : {:,}'.format(len(self)))
print('Sorted on disk : {}'.format(self._sorted_on_disk))
if self._sorted_on_disk:
self._sorted_indices = list(range(len(self)))
else:
file_name = os.path.join(self._dataset_dir, 'pyprob_hashes')
try:
hashes_file = shelve.open(file_name, 'r')
hashes_exist = 'hashes' in hashes_file
hashes_file.close()
except:
hashes_exist = False
if hashes_exist:
print('Using pre-computed hashes in: {}'.format(file_name))
hashes_file = shelve.open(file_name, 'r')
self._hashes = hashes_file['hashes']
self._sorted_indices = hashes_file['sorted_indices']
hashes_file.close()
if torch.is_tensor(self._hashes):
self._hashes = self._hashes.cpu().numpy()
if len(self._sorted_indices) != len(self):
raise RuntimeError('Length of pre-computed hashes ({}) and length of offline dataset ({}) do not match. Dataset files have been altered. Delete and re-generate pre-computed hash file: {}'.format(len(self._sorted_indices), len(self), file_name))
else:
print('No pre-computed hashes found, generating: {}'.format(file_name))
hashes_file = shelve.open(file_name, 'c')
hashes, sorted_indices = self._compute_hashes()
hashes_file['hashes'] = hashes
hashes_file['sorted_indices'] = sorted_indices
hashes_file.close()
self._sorted_indices = sorted_indices
self._hashes = hashes
print('Num. trace types : {:,}'.format(len(set(self._hashes))))
hashes_and_counts = OrderedDict(sorted(Counter(self._hashes).items()))
print('Trace hash\tCount')
for hash, count in hashes_and_counts.items():
print('{:.8f}\t{}'.format(hash, count))
print()
@staticmethod
def _trace_hash(trace):
h = hash(''.join([variable.address for variable in trace.variables_controlled])) + sys.maxsize + 1
return float('{}.{}'.format(trace.length_controlled, h))
def _compute_hashes(self):
hashes = torch.zeros(len(self))
util.progress_bar_init('Hashing offline dataset for sorting', len(self), 'Traces')
for i in range(len(self)):
hashes[i] = self._trace_hash(self[i])
util.progress_bar_update(i)
util.progress_bar_end()
print('Sorting offline dataset')
_, sorted_indices = torch.sort(hashes)
print('Sorting done')
return hashes.cpu().numpy(), sorted_indices.cpu().numpy()
def save_sorted(self, sorted_dataset_dir, num_traces_per_file=None, num_files=None, begin_file_index=None, end_file_index=None):
if num_traces_per_file is not None:
if num_files is not None:
raise ValueError('Expecting either num_traces_per_file or num_files')
else:
if num_files is None:
raise ValueError('Expecting either num_traces_per_file or num_files')
else:
num_traces_per_file = math.ceil(len(self) / num_files)
if os.path.exists(sorted_dataset_dir):
if len(glob(os.path.join(sorted_dataset_dir, '*'))) > 0:
print(colored('Warning: target directory is not empty: {})'.format(sorted_dataset_dir), 'red', attrs=['bold']))
util.create_path(sorted_dataset_dir, directory=True)
file_indices = list(util.chunks(list(self._sorted_indices), num_traces_per_file))
num_traces = len(self)
num_files = len(file_indices)
num_files_digits = len(str(num_files))
file_name_template = 'pyprob_traces_sorted_{{:d}}_{{:0{}d}}'.format(num_files_digits)
file_names = list(map(lambda x: os.path.join(sorted_dataset_dir, file_name_template.format(num_traces_per_file, x)), range(num_files)))
if begin_file_index is None:
begin_file_index = 0
if end_file_index is None:
end_file_index = num_files
if begin_file_index < 0 or begin_file_index > end_file_index or end_file_index > num_files or end_file_index < begin_file_index:
raise ValueError('Invalid indexes begin_file_index:{} and end_file_index: {}'.format(begin_file_index, end_file_index))
print('Sorted offline dataset, traces: {}, traces per file: {}, files: {} (overall)'.format(num_traces, num_traces_per_file, num_files))
util.progress_bar_init('Saving sorted files with indices in range [{}, {}) ({} of {} files overall)'.format(begin_file_index, end_file_index, end_file_index - begin_file_index, num_files), end_file_index - begin_file_index + 1, 'Files')
j = 0
for i in range(begin_file_index, end_file_index):
j += 1
file_name = file_names[i]
print(file_name)
shelf = ConcurrentShelf(file_name)
shelf.lock(write=True)
for new_i, old_i in enumerate(file_indices[i]):
shelf[str(new_i)] = self[old_i]
shelf['__length'] = len(file_indices[i])
shelf.unlock()
util.progress_bar_update(j)
util.progress_bar_end()
class TraceSampler(Sampler):
def __init__(self, offline_dataset):
if not isinstance(offline_dataset, OfflineDataset):
raise TypeError('Expecting an OfflineDataset instance.')
self._sorted_indices = offline_dataset._sorted_indices
def __iter__(self):
return iter(self._sorted_indices)
def __len__(self):
return len(self._offline_dataset)
class TraceBatchSampler(Sampler):
def __init__(self, offline_dataset, batch_size, shuffle_batches=True):
if not isinstance(offline_dataset, OfflineDataset):
raise TypeError('Expecting an OfflineDataset instance.')
self._batches = list(util.chunks(offline_dataset._sorted_indices, batch_size))
self._shuffle_batches = shuffle_batches
def __iter__(self):
if self._shuffle_batches:
np.random.shuffle(self._batches)
return iter(self._batches)
def __len__(self):
return len(self._batches)
class DistributedTraceBatchSampler(Sampler):
def __init__(self, offline_dataset, batch_size, shuffle_batches=True, num_buckets=None, shuffle_buckets=True):
if not isinstance(offline_dataset, OfflineDataset):
raise TypeError('Expecting an OfflineDataset instance.')
if not dist.is_available():
raise RuntimeError('Expecting distributed training.')
self._world_size = dist.get_world_size()
self._rank = dist.get_rank()
num_batches_to_drop = math.floor(len(offline_dataset._sorted_indices) / batch_size) % self._world_size
num_traces_to_drop = num_batches_to_drop * batch_size
st = random.getstate()
random.seed(0)
self._batches = list(util.chunks(util.drop_items(list(offline_dataset._sorted_indices), num_traces_to_drop), batch_size))
random.setstate(st)
if len(self._batches[-1]) < batch_size:
del(self._batches[-1])
if num_buckets is None:
num_buckets = len(self._batches) / self._world_size
self._num_buckets = num_buckets
self._bucket_size = math.ceil(len(self._batches) / num_buckets)
if self._bucket_size < self._world_size:
raise RuntimeError('offline_dataset:{}, batch_size:{} and num_buckets:{} imply a bucket_size:{} smaller than world_size:{}'.format(len(offline_dataset), batch_size, num_buckets, self._bucket_size, self._world_size))
# List of buckets, where each bucket is a list of minibatches
self._buckets = list(util.chunks(self._batches, self._bucket_size))
# Unify last two buckets if the last bucket is smaller than other buckets
if len(self._buckets[-1]) < self._bucket_size:
if len(self._buckets) < 2:
raise RuntimeError('offline_dataset:{} too small for given batch_size:{} and num_buckets:{}'.format(len(offline_dataset), batch_size, num_buckets))
self._buckets[-2].extend(self._buckets[-1])
del(self._buckets[-1])
self._shuffle_batches = shuffle_batches
self._shuffle_buckets = shuffle_buckets
self._epoch = 0
self._current_bucket_id = 0
print('DistributedTraceBatchSampler')
print('OfflineDataset size : {:,}'.format(len(offline_dataset)))
print('World size : {:,}'.format(self._world_size))
print('Batch size : {:,}'.format(batch_size))
print('Num. batches dropped: {:,}'.format(num_batches_to_drop))
print('Num. batches : {:,}'.format(len(self._batches)))
print('Bucket size : {:,}'.format(self._bucket_size))
print('Num. buckets : {:,}'.format(self._num_buckets))
def __iter__(self):
self._epoch += 1
bucket_ids = list(range(len(self._buckets)))
if self._shuffle_buckets:
# Shuffle the list of buckets (but not the order of minibatches inside each bucket) at the beginning of each epoch, deterministically based on the epoch number so that all nodes have the same bucket order
# Idea from: https://github.com/pytorch/pytorch/blob/a3fb004b1829880547dd7b3e2cd9d16af657b869/torch/utils/data/distributed.py#L44
st = np.random.get_state()
np.random.seed(self._epoch)
np.random.shuffle(bucket_ids)
np.random.set_state(st)
for bucket_id in bucket_ids:
bucket = self._buckets[bucket_id]
self._current_bucket_id = bucket_id
# num_batches is needed to ensure that all nodes have the same number of minibatches (iterations) in each bucket, in cases where the bucket size is not divisible by world_size.
num_batches = math.floor(len(bucket) / self._world_size)
# Select a num_batches-sized subset of the current bucket for the current node
# The part not selected by the current node will be selected by other nodes
batches = bucket[self._rank:len(bucket):self._world_size][:num_batches]
if self._shuffle_batches:
# Shuffle the list of minibatches (but not the order trace indices inside each minibatch) selected for the current node
np.random.shuffle(batches)
for batch in batches:
yield batch
def __len__(self):
return len(self._batches)
| true | true |
f72828788d1ad9cd20a5b3b3b4fd765d532bed8c | 5,084 | py | Python | day18/test_lib.py | heijp06/AoC-2021 | f6afead5e1fe9a839d608a5792f84e54803742c1 | [
"MIT"
] | null | null | null | day18/test_lib.py | heijp06/AoC-2021 | f6afead5e1fe9a839d608a5792f84e54803742c1 | [
"MIT"
] | null | null | null | day18/test_lib.py | heijp06/AoC-2021 | f6afead5e1fe9a839d608a5792f84e54803742c1 | [
"MIT"
] | null | null | null | import pytest
from lib import part1, part2, sum_list
from snailfish import Parser, RootSnailFish, Snailfish, ValueSnailfish, parse
from functools import reduce
def test_part1():
assert part1(data) == 4140
def test_part2():
assert part2(data) == 3993
@pytest.mark.parametrize(["row", "expected"], (
("1", 1),
("[1,2]", 7),
("[[1,2],[[3,4],5]]", 143),
("[[[[0,7],4],[[7,8],[6,0]]],[8,1]]", 1384),
("[[[[1,1],[2,2]],[3,3]],[4,4]]", 445),
("[[[[3,0],[5,3]],[4,4]],[5,5]]", 791),
("[[[[5,0],[7,4]],[5,5]],[6,6]]", 1137),
("[[[[8,7],[7,7]],[[8,6],[7,7]]],[[[0,7],[6,6]],[8,7]]]", 3488),
))
def test_magnitude(row, expected):
snailfish = parse(row)
assert snailfish.magnitude() == expected
@pytest.mark.parametrize(["row", "result", "expected"], (
("1", False, "1"),
("[1,2]", False, "[1,2]"),
("[[[[[9,8],1],2],3],4]", True, "[[[[0,9],2],3],4]"),
("[7,[6,[5,[4,[3,2]]]]]", True, "[7,[6,[5,[7,0]]]]"),
("[[6,[5,[4,[3,2]]]],1]", True, "[[6,[5,[7,0]]],3]"),
("[[3,[2,[1,[7,3]]]],[6,[5,[4,[3,2]]]]]",
True, "[[3,[2,[8,0]]],[9,[5,[4,[3,2]]]]]"),
("[[3,[2,[8,0]]],[9,[5,[4,[3,2]]]]]", True, "[[3,[2,[8,0]]],[9,[5,[7,0]]]]"),
("[[[[0,7],4],[[7,8],[0,[6,7]]]],[1,1]]",
True, "[[[[0,7],4],[[7,8],[6,0]]],[8,1]]"),
))
def test_explode(row, result, expected):
snailfish = parse(row)
changed = snailfish.explode()
assert changed == result
assert str(snailfish) == expected
@pytest.mark.parametrize(["row", "first_left", "first_right"], (
("[1,2]", "1", "2"),
("[1,[2,3]]", "1", "2"),
("[[1,2],3]", "2", "3"),
("[[[[1,2],3],4],5]", "4", "5"),
("[1,[2,[3,[4,5]]]]", "1", "2"),
("[[1,[2,[3,4]]],5]", "4", "5"),
("[1,[[[2,3],4],5]]", "1", "2"),
))
def test_first_left_and_first_right(row, first_left, first_right):
snailfish = parse(row).child
assert str(snailfish.left.first_right()) == first_right
assert str(snailfish.left.first_left()) == "None"
assert str(snailfish.right.first_right()) == "None"
assert str(snailfish.right.first_left()) == first_left
def test_parent():
snailfish = parse("1")
assert snailfish.parent is None
snailfish = parse("[1,2]")
assert snailfish.parent is None
assert snailfish.child.left.parent == snailfish.child
assert snailfish.child.right.parent == snailfish.child
@pytest.mark.parametrize(["row", "expected"], (
("10", "[5,5]"),
("11", "[5,6]"),
("12", "[6,6]"),
("[[[[0,7],4],[15,[0,13]]],[1,1]]", "[[[[0,7],4],[[7,8],[0,13]]],[1,1]]"),
("[[[[0,7],4],[[7,8],[0,13]]],[1,1]]",
"[[[[0,7],4],[[7,8],[0,[6,7]]]],[1,1]]"),
))
def test_split(row, expected):
snailfish = parse(row)
assert snailfish.split()
assert str(snailfish) == expected
def test_reduce():
snailfish = parse("[[[[[4,3],4],4],[7,[[8,4],9]]],[1,1]]")
snailfish.reduce()
assert str(snailfish) == "[[[[0,7],4],[[7,8],[6,0]]],[8,1]]"
def test_root_replace():
snailfish = parse("1")
value = ValueSnailfish(2)
snailfish.replace(snailfish.child, value)
assert snailfish.child == value
assert value.parent == snailfish
def test_pair_replace():
snailfish = parse("[1,2]")
pair = snailfish.child
left = ValueSnailfish("3")
right = ValueSnailfish("4")
pair.replace(pair.left, left)
pair.replace(pair.right, right)
assert pair.left == left
assert pair.right == right
assert left.parent == pair
assert right.parent == pair
@pytest.mark.parametrize(["rows", "expected"], (
([
"[[[[4,3],4],4],[7,[[8,4],9]]]",
"[1,1]"
], "[[[[0,7],4],[[7,8],[6,0]]],[8,1]]"),
([
"[1,1]",
"[2,2]",
"[3,3]",
"[4,4]",
], "[[[[1,1],[2,2]],[3,3]],[4,4]]"),
([
"[1,1]",
"[2,2]",
"[3,3]",
"[4,4]",
"[5,5]",
], "[[[[3,0],[5,3]],[4,4]],[5,5]]"),
([
"[1,1]",
"[2,2]",
"[3,3]",
"[4,4]",
"[5,5]",
"[6,6]",
], "[[[[5,0],[7,4]],[5,5]],[6,6]]"),
([
"[[[0,[4,5]],[0,0]],[[[4,5],[2,6]],[9,5]]]",
"[7,[[[3,7],[4,3]],[[6,3],[8,8]]]]",
"[[2,[[0,8],[3,4]]],[[[6,7],1],[7,[1,6]]]]",
"[[[[2,4],7],[6,[0,5]]],[[[6,8],[2,8]],[[2,1],[4,5]]]]",
"[7,[5,[[3,8],[1,4]]]]",
"[[2,[2,2]],[8,[8,1]]]",
"[2,9]",
"[1,[[[9,3],9],[[9,0],[0,7]]]]",
"[[[5,[7,4]],7],1]",
"[[[[4,2],2],6],[8,7]]",
], "[[[[8,7],[7,7]],[[8,6],[7,7]]],[[[0,7],[6,6]],[8,7]]]")
))
def test_addition(rows, expected):
snailfish = sum_list(rows)
assert str(snailfish) == expected
data = [
"[[[0,[5,8]],[[1,7],[9,6]]],[[4,[1,2]],[[1,4],2]]]",
"[[[5,[2,8]],4],[5,[[9,9],0]]]",
"[6,[[[6,2],[5,6]],[[7,6],[4,7]]]]",
"[[[6,[0,7]],[0,9]],[4,[9,[9,0]]]]",
"[[[7,[6,4]],[3,[1,3]]],[[[5,5],1],9]]",
"[[6,[[7,3],[3,2]]],[[[3,8],[5,7]],4]]",
"[[[[5,4],[7,7]],8],[[8,3],8]]",
"[[9,3],[[9,9],[6,[4,9]]]]",
"[[2,[[7,7],7]],[[5,8],[[9,3],[0,2]]]]",
"[[[[5,2],5],[8,[3,7]]],[[5,[7,5]],[4,4]]]"
]
| 27.934066 | 81 | 0.426436 | import pytest
from lib import part1, part2, sum_list
from snailfish import Parser, RootSnailFish, Snailfish, ValueSnailfish, parse
from functools import reduce
def test_part1():
assert part1(data) == 4140
def test_part2():
assert part2(data) == 3993
@pytest.mark.parametrize(["row", "expected"], (
("1", 1),
("[1,2]", 7),
("[[1,2],[[3,4],5]]", 143),
("[[[[0,7],4],[[7,8],[6,0]]],[8,1]]", 1384),
("[[[[1,1],[2,2]],[3,3]],[4,4]]", 445),
("[[[[3,0],[5,3]],[4,4]],[5,5]]", 791),
("[[[[5,0],[7,4]],[5,5]],[6,6]]", 1137),
("[[[[8,7],[7,7]],[[8,6],[7,7]]],[[[0,7],[6,6]],[8,7]]]", 3488),
))
def test_magnitude(row, expected):
snailfish = parse(row)
assert snailfish.magnitude() == expected
@pytest.mark.parametrize(["row", "result", "expected"], (
("1", False, "1"),
("[1,2]", False, "[1,2]"),
("[[[[[9,8],1],2],3],4]", True, "[[[[0,9],2],3],4]"),
("[7,[6,[5,[4,[3,2]]]]]", True, "[7,[6,[5,[7,0]]]]"),
("[[6,[5,[4,[3,2]]]],1]", True, "[[6,[5,[7,0]]],3]"),
("[[3,[2,[1,[7,3]]]],[6,[5,[4,[3,2]]]]]",
True, "[[3,[2,[8,0]]],[9,[5,[4,[3,2]]]]]"),
("[[3,[2,[8,0]]],[9,[5,[4,[3,2]]]]]", True, "[[3,[2,[8,0]]],[9,[5,[7,0]]]]"),
("[[[[0,7],4],[[7,8],[0,[6,7]]]],[1,1]]",
True, "[[[[0,7],4],[[7,8],[6,0]]],[8,1]]"),
))
def test_explode(row, result, expected):
snailfish = parse(row)
changed = snailfish.explode()
assert changed == result
assert str(snailfish) == expected
@pytest.mark.parametrize(["row", "first_left", "first_right"], (
("[1,2]", "1", "2"),
("[1,[2,3]]", "1", "2"),
("[[1,2],3]", "2", "3"),
("[[[[1,2],3],4],5]", "4", "5"),
("[1,[2,[3,[4,5]]]]", "1", "2"),
("[[1,[2,[3,4]]],5]", "4", "5"),
("[1,[[[2,3],4],5]]", "1", "2"),
))
def test_first_left_and_first_right(row, first_left, first_right):
snailfish = parse(row).child
assert str(snailfish.left.first_right()) == first_right
assert str(snailfish.left.first_left()) == "None"
assert str(snailfish.right.first_right()) == "None"
assert str(snailfish.right.first_left()) == first_left
def test_parent():
snailfish = parse("1")
assert snailfish.parent is None
snailfish = parse("[1,2]")
assert snailfish.parent is None
assert snailfish.child.left.parent == snailfish.child
assert snailfish.child.right.parent == snailfish.child
@pytest.mark.parametrize(["row", "expected"], (
("10", "[5,5]"),
("11", "[5,6]"),
("12", "[6,6]"),
("[[[[0,7],4],[15,[0,13]]],[1,1]]", "[[[[0,7],4],[[7,8],[0,13]]],[1,1]]"),
("[[[[0,7],4],[[7,8],[0,13]]],[1,1]]",
"[[[[0,7],4],[[7,8],[0,[6,7]]]],[1,1]]"),
))
def test_split(row, expected):
snailfish = parse(row)
assert snailfish.split()
assert str(snailfish) == expected
def test_reduce():
snailfish = parse("[[[[[4,3],4],4],[7,[[8,4],9]]],[1,1]]")
snailfish.reduce()
assert str(snailfish) == "[[[[0,7],4],[[7,8],[6,0]]],[8,1]]"
def test_root_replace():
snailfish = parse("1")
value = ValueSnailfish(2)
snailfish.replace(snailfish.child, value)
assert snailfish.child == value
assert value.parent == snailfish
def test_pair_replace():
snailfish = parse("[1,2]")
pair = snailfish.child
left = ValueSnailfish("3")
right = ValueSnailfish("4")
pair.replace(pair.left, left)
pair.replace(pair.right, right)
assert pair.left == left
assert pair.right == right
assert left.parent == pair
assert right.parent == pair
@pytest.mark.parametrize(["rows", "expected"], (
([
"[[[[4,3],4],4],[7,[[8,4],9]]]",
"[1,1]"
], "[[[[0,7],4],[[7,8],[6,0]]],[8,1]]"),
([
"[1,1]",
"[2,2]",
"[3,3]",
"[4,4]",
], "[[[[1,1],[2,2]],[3,3]],[4,4]]"),
([
"[1,1]",
"[2,2]",
"[3,3]",
"[4,4]",
"[5,5]",
], "[[[[3,0],[5,3]],[4,4]],[5,5]]"),
([
"[1,1]",
"[2,2]",
"[3,3]",
"[4,4]",
"[5,5]",
"[6,6]",
], "[[[[5,0],[7,4]],[5,5]],[6,6]]"),
([
"[[[0,[4,5]],[0,0]],[[[4,5],[2,6]],[9,5]]]",
"[7,[[[3,7],[4,3]],[[6,3],[8,8]]]]",
"[[2,[[0,8],[3,4]]],[[[6,7],1],[7,[1,6]]]]",
"[[[[2,4],7],[6,[0,5]]],[[[6,8],[2,8]],[[2,1],[4,5]]]]",
"[7,[5,[[3,8],[1,4]]]]",
"[[2,[2,2]],[8,[8,1]]]",
"[2,9]",
"[1,[[[9,3],9],[[9,0],[0,7]]]]",
"[[[5,[7,4]],7],1]",
"[[[[4,2],2],6],[8,7]]",
], "[[[[8,7],[7,7]],[[8,6],[7,7]]],[[[0,7],[6,6]],[8,7]]]")
))
def test_addition(rows, expected):
snailfish = sum_list(rows)
assert str(snailfish) == expected
data = [
"[[[0,[5,8]],[[1,7],[9,6]]],[[4,[1,2]],[[1,4],2]]]",
"[[[5,[2,8]],4],[5,[[9,9],0]]]",
"[6,[[[6,2],[5,6]],[[7,6],[4,7]]]]",
"[[[6,[0,7]],[0,9]],[4,[9,[9,0]]]]",
"[[[7,[6,4]],[3,[1,3]]],[[[5,5],1],9]]",
"[[6,[[7,3],[3,2]]],[[[3,8],[5,7]],4]]",
"[[[[5,4],[7,7]],8],[[8,3],8]]",
"[[9,3],[[9,9],[6,[4,9]]]]",
"[[2,[[7,7],7]],[[5,8],[[9,3],[0,2]]]]",
"[[[[5,2],5],[8,[3,7]]],[[5,[7,5]],[4,4]]]"
]
| true | true |
f728291c9bf908695b13e8fe19d70230254fe714 | 9,815 | py | Python | reports/configs/only_logs_dmpnn4_1/other_config.py | hengwei-chan/graph_network_demo | 542f2a59b1b9708abdc718d77db7111f3ba2df96 | [
"MIT"
] | 1 | 2021-10-18T03:44:53.000Z | 2021-10-18T03:44:53.000Z | reports/configs/only_logs_dmpnn4_1/other_config.py | hengwei-chan/graph_network_demo | 542f2a59b1b9708abdc718d77db7111f3ba2df96 | [
"MIT"
] | null | null | null | reports/configs/only_logs_dmpnn4_1/other_config.py | hengwei-chan/graph_network_demo | 542f2a59b1b9708abdc718d77db7111f3ba2df96 | [
"MIT"
] | 1 | 2022-02-22T08:32:01.000Z | 2022-02-22T08:32:01.000Z | from dataclasses import dataclass, field
from typing import List
import tensorflow as tf
from graph_networks.utilities import *
import logging
import os
ATOM_FEATURE_DIM = DGIN4_ATOM_FEATURE_DIM
EDGE_FEATURE_DIM = DGIN4_EDGE_FEATURE_DIM
@dataclass
class BasicModelConfig:
"""
Config for model1/2/3 run file.
General model parameters
"""
model_name: str = 'only_logs_dmpnn4_1' # without h_w in DGIN gin part - added h_v_0 instead
# whole train/eval split - no more double split within train data set
# random train/test split in get_data_sd - only change overall_seed
# CHANGES dgin3 10.02.2021:
# *added new bondFeaturesDGIN2 and atomFeaturesDGIN2; DGIN2_ATOM_FEATURE_DIM; DGIN2_EDGE_FEATURE_DIM
# *from project_path+'data/processed/lipo/pickled/train_frags3/' to project_path+'data/processed/lipo/pickled/test_frags3/'
# CHANGES dgin3 16.02.2021:
# *added new bondFeaturesDGIN3 and atomFeaturesDGIN3; DGIN3_ATOM_FEATURE_DIM; DGIN3_EDGE_FEATURE_DIM
# *from project_path+'data/processed/lipo/pickled/train_frags_dgin3/' to project_path+'data/processed/lipo/pickled/test_frags_dgin3/'
# CHANGES dgin4 16.02.2021:
# *added add_species bool in model1 config - previously not there; for dgin2 featurization adds the species type after the dgin
# encoding before logD prediction
# test_frags_dgin4 was added for species inclusion in model2 call()
batch_size: int =15
override_if_exists: bool = True
overall_seed: int = 2
# path to the project folder
project_path:str = "./"
retrain_model: bool = False
retrain_model_name: str = ''
retrain_model_epoch: str = ''
retrain_model_weights_dir: str = project_path+'reports/model_weights/'+retrain_model_name+'/epoch_'+retrain_model_epoch+'/checkp_'+retrain_model_epoch
train_data_dir: str = project_path+'data/processed/lipo/pickled/train_dgin4_logs/'
test_data_dir: str = project_path+'data/processed/lipo/pickled/test_dgin4_logs/'
combined_dataset: bool = False
add_train_data_dir: str = project_path+'data/processed/lipo/pickled/train_dgin4_logs/'
add_test_data_dir: str = project_path+'data/processed/lipo/pickled/test_dgin4_logs/'
test_model: bool = False
test_model_epoch: str = '887'
# define the number or test runs for the CI.
# the mean and std of the RMSE and r^2 of the combined runs are taken as the output.
test_n_times: int = 1
# do you want to test the model with consensus mode?
# if yes, a defined ML model will be included in the consensus predictions during the testing.
consensus: bool = False
# include dropout during testing?
include_dropout: bool = False
test_model_weights_dir: str = project_path+'reports/model_weights/'+model_name+'/epoch_'+test_model_epoch+'/checkp_'+test_model_epoch
# To save the prediction values for each property set to True
# When this flag is True - the whole test dataset is taken an test_n_times is set to zero!
save_predictions: bool = False
# define the folder where you want to save the predictions.
# For each property, a file is created under the property name ("./logd.txt","./logs.txt","./logp.txt","./others.txt")
test_prediction_output_folder: str = project_path+"reports/predictions/"+model_name+"/"
encode_hidden: bool = False
log_dir: str = project_path+'reports/logs/'+model_name+'.log'
verbosity_level = logging.INFO
model_type: str = 'DMPNN' # added 31.03.2021 to compare models like 'GIN' 'DMPNN' 'DGIN' 'MLP'
plot_dir: str = project_path+'reports/figures/'+model_name+'/'
tensorboard_log_dir: str = project_path+'reports/tensorboard/'+model_name+'/'
config_log_dir: str = project_path+'reports/configs/'+model_name+'/'
model_weights_dir: str = project_path+'reports/model_weights/'+model_name+'/'
stats_log_dir: str = project_path+'reports/stats/'+model_name+'/'
@dataclass
class DGINConfig:
"""
Config for direcpted-mpnn class.
"""
dropout_aggregate_dmpnn: bool = False
layernorm_aggregate_dmpnn: bool = True
dropout_passing_dmpnn: bool = False
layernorm_passing_dmpnn: bool = True
dropout_aggregate_gin: bool = False
layernorm_aggregate_gin: bool = True
dropout_passing_gin: bool = False
layernorm_passing_gin: bool = True
gin_aggregate_bias: bool = False
dmpnn_passing_bias: bool = False
init_bias: bool = False
massge_iteration_dmpnn: int = 4
message_iterations_gin: int = 4
dropout_rate: float = 0.15
input_size: int = (ATOM_FEATURE_DIM+EDGE_FEATURE_DIM) # combination of node feature len (33) and edge feature len (12)
passing_hidden_size: int = 56 # this can be changed
input_size_gin: int = (ATOM_FEATURE_DIM) # changed 31.03.2021
return_hv: bool = True # model3 parameter
@dataclass
class Model1Config:
"""
Config model1 class - no subclass configs are defined here.
"""
validation_split: float = 0.90
learning_rate: float = 0.004
clip_rate: float = 0.6
optimizer = tf.keras.optimizers.Adam(learning_rate)
lipo_loss_mse = tf.keras.losses.mse
lipo_loss_mae = tf.keras.losses.mae
logP_loss_mse = tf.keras.losses.mse
logS_loss_mse = tf.keras.losses.mse
other_loss_mse = tf.keras.losses.mse
mw_loss_mse = tf.keras.losses.mse
metric = tf.keras.losses.mae
epochs: int = 1600
# define the number of epochs for each test run.
save_after_epoch: int = 3
# dropout rate for the general model - mainly the MLP for the different log predictions
dropout_rate: float = 0.15 # the overall dropout rate of the readout functions
# the seed to shuffle the training/validation dataset; For the same dataset, even when
# combined_dataset is True, it is the same training/valiation instances
train_data_seed: int = 0
dropout_rate: float = 0.15 # the overall dropout rate of the readout functions
train_data_seed: int = 0
hidden_readout_1: int = 32
hidden_readout_2: int = 14
activation_func_readout = tf.nn.relu
include_logD: bool = False
include_logS: bool = True
include_logP: bool = False
include_other: bool = False
include_mw: bool = False
include_rot_bond: bool = False
include_HBA: bool = False
include_HBD: bool = False
# define the starting threshold for the RMSE of the model. When the comnbined RMSE
# is below this threshold, the model weights are being safed and a new threshold
# is set. It only serves as a starting threshold so that not too many models
# are being safed. Depends on how many log endpoints are being taken into
# consideration - as three endpoints have a higher combined RMSE as only one
# endpoint.
best_evaluation_threshold: float = 2.45 #was introduced on the 25.03.2021/
# define the individual thresholds. If one model is better, the corresponding
# model weights are being saved.
best_evaluation_threshold_logd: float = 1.85
best_evaluation_threshold_logp: float = 1.65
best_evaluation_threshold_logs: float = 2.15
best_evaluation_threshold_other: float = 2.15
# 2.45 for all_logs
# 0.70 logP
# 0.75 logD
# 1.00 logS
# 1.75 logSD
# 1.70 logSP
# 1.45 logDP
include_fragment_conv: bool = False # was introduced on the 4.12.2020
use_rmse: bool = True # uses RMSE instead of MSE for only lipo_loss
shuffle_inside: bool = True # reshuffles the train/valid test seach in each epoch (generalizes)
add_species: bool = False # 16.02 introduction; previously not there; for dgin3 adds the species type after the dgin encoding before logD prediction
@dataclass
class FrACConfig:
"""
Config fragment aggregation class - no subclass configs are defined here.
"""
input_size_gin: int = 28
layernorm_aggregate: bool = True
reduce_mean: bool = True # when false -> reduce_sum
@dataclass
class MLConfig:
"""
Configs for the ML algorithm
"""
# which algorithm do you want to use for the consensus?
# possibilities are: "SVM", "RF", "KNN" or "LR" - all are regression models!
# SVM: Support Vector Machine; RF: Random Forest, KNN: K-Nearest Neigbors; LR: Linear Regression;
algorithm: str = "SVM"
# which fingerprint to use - possibilities are: "ECFP" or "MACCS"
fp_types: str = "ECFP"
# If 'ECFP' fingerprint is used, define the number of bits - maximum is 2048!
n_bits: int = 2048
# If "ECFP" fingerprint is used, define the radius
radius: int = 4
# define if descriptors should be included into the non-GNN molecular representation
include_descriptors: bool = True
# define if the descriptors should be standardizedby scaling and centering (Sklearn)
standardize: bool = True
@dataclass
class Config():
"""
Overall config class for model2 and run file.
Includes all submodels config
"""
basic_model_config: BasicModelConfig
model1_config: Model1Config
d_gin_config: DGINConfig
frag_acc_config: FrACConfig
ml_config: MLConfig
model: str = 'model11' | 44.013453 | 169 | 0.669791 | from dataclasses import dataclass, field
from typing import List
import tensorflow as tf
from graph_networks.utilities import *
import logging
import os
ATOM_FEATURE_DIM = DGIN4_ATOM_FEATURE_DIM
EDGE_FEATURE_DIM = DGIN4_EDGE_FEATURE_DIM
@dataclass
class BasicModelConfig:
model_name: str = 'only_logs_dmpnn4_1'
batch_size: int =15
override_if_exists: bool = True
overall_seed: int = 2
project_path:str = "./"
retrain_model: bool = False
retrain_model_name: str = ''
retrain_model_epoch: str = ''
retrain_model_weights_dir: str = project_path+'reports/model_weights/'+retrain_model_name+'/epoch_'+retrain_model_epoch+'/checkp_'+retrain_model_epoch
train_data_dir: str = project_path+'data/processed/lipo/pickled/train_dgin4_logs/'
test_data_dir: str = project_path+'data/processed/lipo/pickled/test_dgin4_logs/'
combined_dataset: bool = False
add_train_data_dir: str = project_path+'data/processed/lipo/pickled/train_dgin4_logs/'
add_test_data_dir: str = project_path+'data/processed/lipo/pickled/test_dgin4_logs/'
test_model: bool = False
test_model_epoch: str = '887'
test_n_times: int = 1
consensus: bool = False
include_dropout: bool = False
test_model_weights_dir: str = project_path+'reports/model_weights/'+model_name+'/epoch_'+test_model_epoch+'/checkp_'+test_model_epoch
save_predictions: bool = False
test_prediction_output_folder: str = project_path+"reports/predictions/"+model_name+"/"
encode_hidden: bool = False
log_dir: str = project_path+'reports/logs/'+model_name+'.log'
verbosity_level = logging.INFO
model_type: str = 'DMPNN'
plot_dir: str = project_path+'reports/figures/'+model_name+'/'
tensorboard_log_dir: str = project_path+'reports/tensorboard/'+model_name+'/'
config_log_dir: str = project_path+'reports/configs/'+model_name+'/'
model_weights_dir: str = project_path+'reports/model_weights/'+model_name+'/'
stats_log_dir: str = project_path+'reports/stats/'+model_name+'/'
@dataclass
class DGINConfig:
dropout_aggregate_dmpnn: bool = False
layernorm_aggregate_dmpnn: bool = True
dropout_passing_dmpnn: bool = False
layernorm_passing_dmpnn: bool = True
dropout_aggregate_gin: bool = False
layernorm_aggregate_gin: bool = True
dropout_passing_gin: bool = False
layernorm_passing_gin: bool = True
gin_aggregate_bias: bool = False
dmpnn_passing_bias: bool = False
init_bias: bool = False
massge_iteration_dmpnn: int = 4
message_iterations_gin: int = 4
dropout_rate: float = 0.15
input_size: int = (ATOM_FEATURE_DIM+EDGE_FEATURE_DIM)
passing_hidden_size: int = 56
input_size_gin: int = (ATOM_FEATURE_DIM)
return_hv: bool = True
@dataclass
class Model1Config:
validation_split: float = 0.90
learning_rate: float = 0.004
clip_rate: float = 0.6
optimizer = tf.keras.optimizers.Adam(learning_rate)
lipo_loss_mse = tf.keras.losses.mse
lipo_loss_mae = tf.keras.losses.mae
logP_loss_mse = tf.keras.losses.mse
logS_loss_mse = tf.keras.losses.mse
other_loss_mse = tf.keras.losses.mse
mw_loss_mse = tf.keras.losses.mse
metric = tf.keras.losses.mae
epochs: int = 1600
save_after_epoch: int = 3
dropout_rate: float = 0.15
train_data_seed: int = 0
dropout_rate: float = 0.15
train_data_seed: int = 0
hidden_readout_1: int = 32
hidden_readout_2: int = 14
activation_func_readout = tf.nn.relu
include_logD: bool = False
include_logS: bool = True
include_logP: bool = False
include_other: bool = False
include_mw: bool = False
include_rot_bond: bool = False
include_HBA: bool = False
include_HBD: bool = False
best_evaluation_threshold: float = 2.45
best_evaluation_threshold_logd: float = 1.85
best_evaluation_threshold_logp: float = 1.65
best_evaluation_threshold_logs: float = 2.15
best_evaluation_threshold_other: float = 2.15
include_fragment_conv: bool = False
use_rmse: bool = True
shuffle_inside: bool = True
add_species: bool = False
@dataclass
class FrACConfig:
input_size_gin: int = 28
layernorm_aggregate: bool = True
reduce_mean: bool = True
@dataclass
class MLConfig:
algorithm: str = "SVM"
fp_types: str = "ECFP"
n_bits: int = 2048
radius: int = 4
include_descriptors: bool = True
standardize: bool = True
@dataclass
class Config():
basic_model_config: BasicModelConfig
model1_config: Model1Config
d_gin_config: DGINConfig
frag_acc_config: FrACConfig
ml_config: MLConfig
model: str = 'model11' | true | true |
f72829ee3c90f92142527d7278c8a2015e22a7b6 | 561 | py | Python | exercises/es/test_01_07.py | tuanducdesign/spacy-course | f8d092c5fa2997fccb3f367d174dce8667932b3d | [
"MIT"
] | 2 | 2020-07-07T01:46:37.000Z | 2021-04-20T03:19:43.000Z | exercises/es/test_01_07.py | tuanducdesign/spacy-course | f8d092c5fa2997fccb3f367d174dce8667932b3d | [
"MIT"
] | null | null | null | exercises/es/test_01_07.py | tuanducdesign/spacy-course | f8d092c5fa2997fccb3f367d174dce8667932b3d | [
"MIT"
] | null | null | null | def test():
assert "spacy.load" in __solution__, "¿Estás llamando a spacy.load?"
assert nlp.meta["lang"] == "es", "¿Estás cargando el modelo correcto?"
assert nlp.meta["name"] == "core_news_sm", "¿Estás cargando el modelo correcto?"
assert "nlp(text)" in __solution__, "¿Procesaste el texto correctamente?"
assert (
"print(doc.text)" in __solution__
), "¿Estás imprimiendo en pantalla el texto del Doc?"
__msg__.good(
"¡Bien hecho! Ahora que practicaste cargando modelos, miremos algunas de sus predicciones."
)
| 43.153846 | 99 | 0.673797 | def test():
assert "spacy.load" in __solution__, "¿Estás llamando a spacy.load?"
assert nlp.meta["lang"] == "es", "¿Estás cargando el modelo correcto?"
assert nlp.meta["name"] == "core_news_sm", "¿Estás cargando el modelo correcto?"
assert "nlp(text)" in __solution__, "¿Procesaste el texto correctamente?"
assert (
"print(doc.text)" in __solution__
), "¿Estás imprimiendo en pantalla el texto del Doc?"
__msg__.good(
"¡Bien hecho! Ahora que practicaste cargando modelos, miremos algunas de sus predicciones."
)
| true | true |
f7282a2f924b102e07ba4f411ea0993a9dbb6052 | 8,869 | py | Python | Code/sorting.py | siko408/CS-1.3-Core-Data-Structures | 4277c7c026b4aa38510f83f37c19b21ea64828a2 | [
"MIT"
] | null | null | null | Code/sorting.py | siko408/CS-1.3-Core-Data-Structures | 4277c7c026b4aa38510f83f37c19b21ea64828a2 | [
"MIT"
] | 4 | 2020-02-17T23:16:41.000Z | 2020-03-10T08:56:27.000Z | Code/sorting.py | siko408/CS-1.3-Core-Data-Structures | 4277c7c026b4aa38510f83f37c19b21ea64828a2 | [
"MIT"
] | null | null | null | #!python
from binarytree import *
def is_sorted(items):
"""Return a boolean indicating whether given items are in sorted order.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
# TODO: Check that all adjacent items are in order, return early if not
def bubble_sort(items):
"""Sort given items by swapping adjacent items that are out of order, and
repeating until all items are in sorted order.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
# TODO: Repeat until all items are in sorted order
# TODO: Swap adjacent items that are out of order
def selection_sort(items):
"""Sort given items by finding minimum item, swapping it with first
unsorted item, and repeating until all items are in sorted order.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
# TODO: Repeat until all items are in sorted order
# TODO: Find minimum item in unsorted items
# TODO: Swap it with first unsorted item
def insertion_sort(items):
"""Sort given items by taking first unsorted item, inserting it in sorted
order in front of items, and repeating until all items are in order.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
# TODO: Repeat until all items are in sorted order
# TODO: Take first unsorted item
# TODO: Insert it in sorted order in front of items
def merge(items1, items2):
"""Merge given lists of items, each assumed to already be in sorted order,
and return a new list containing all items in sorted order.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
# TODO: Repeat until one list is empty
# TODO: Find minimum item in both lists and append it to new list
# TODO: Append remaining items in non-empty list to new list
def split_sort_merge(items):
"""Sort given items by splitting list into two approximately equal halves,
sorting each with an iterative sorting algorithm, and merging results into
a list in sorted order.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
# TODO: Split items list into approximately equal halves
# TODO: Sort each half using any other sorting algorithm
# TODO: Merge sorted halves into one list in sorted order
def merge_sort(items):
"""Sort given items by splitting list into two approximately equal halves,
sorting each recursively, and merging results into a list in sorted order.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
# TODO: Check if list is so small it's already sorted (base case)
# TODO: Split items list into approximately equal halves
# TODO: Sort each half by recursively calling merge sort
# TODO: Merge sorted halves into one list in sorted order
def partition(items, low, high):
"""Return index `p` after in-place partitioning given items in range
`[low...high]` by choosing a pivot (TODO: document your method here) from
that range, moving pivot into index `p`, items less than pivot into range
`[low...p-1]`, and items greater than pivot into range `[p+1...high]`.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
# TODO: Choose a pivot any way and document your method in docstring above
# TODO: Loop through all items in range [low...high]
# TODO: Move items less than pivot into front of range [low...p-1]
# TODO: Move items greater than pivot into back of range [p+1...high]
# TODO: Move pivot item into final position [p] and return index p
def quick_sort(items, low=None, high=None):
"""Sort given items in place by partitioning items in range `[low...high]`
around a pivot item and recursively sorting each remaining sublist range.
TODO: Best case running time: ??? Why and under what conditions?
TODO: Worst case running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
# TODO: Check if high and low range bounds have default values (not given)
# TODO: Check if list or range is so small it's already sorted (base case)
# TODO: Partition items in-place around a pivot and get index of pivot
# TODO: Sort each sublist range by recursively calling quick sort
def counting_sort(numbers):
"""Sort given numbers (integers) by counting occurrences of each number,
then looping over counts and copying that many numbers into output list.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
# TODO: Find range of given numbers (minimum and maximum integer values)
# TODO: Create list of counts with a slot for each number in input range
# TODO: Loop over given numbers and increment each number's count
# TODO: Loop over counts and append that many numbers into output list
# FIXME: Improve this to mutate input instead of creating new output list
def bucket_sort(numbers, num_buckets=10):
"""Sort given numbers by distributing into buckets representing subranges,
sorting each bucket, and combining contents of all buckets in sorted order.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
# TODO: Find range of given numbers (minimum and maximum integer values)
# TODO: Create list of buckets to store numbers in subranges of input range
# TODO: Loop over given numbers and place each item in appropriate bucket
# TODO: Sort each bucket using any sorting algorithm (recursive or another)
# TODO: Loop over buckets and append each bucket's numbers into output list
# FIXME: Improve this to mutate input instead of creating new output list
def random_ints(count=20, min=1, max=50):
"""Return a list of `count` integers sampled uniformly at random from
given range [`min`...`max`] with replacement (duplicates are allowed)."""
import random
return [random.randint(min, max) for _ in range(count)]
def test_sorting(sort=bubble_sort, num_items=20, max_value=50):
"""Test sorting algorithms with a small list of random items."""
# Create a list of items randomly sampled from range [1...max_value]
items = random_ints(num_items, 1, max_value)
print('Initial items: {!r}'.format(items))
print('Sorted order? {!r}'.format(is_sorted(items)))
# Change this sort variable to the sorting algorithm you want to test
# sort = bubble_sort
print('Sorting items with {}(items)'.format(sort.__name__))
sort(items)
print('Sorted items: {!r}'.format(items))
print('Sorted order? {!r}'.format(is_sorted(items)))
def main():
"""Read command-line arguments and test sorting algorithms."""
import sys
args = sys.argv[1:] # Ignore script file name
if len(args) == 0:
script = sys.argv[0] # Get script file name
print('Usage: {} sort num max'.format(script))
print('Test sorting algorithm `sort` with a list of `num` integers')
print(' randomly sampled from the range [1...`max`] (inclusive)')
print('\nExample: {} bubble_sort 10 20'.format(script))
print('Initial items: [3, 15, 4, 7, 20, 6, 18, 11, 9, 7]')
print('Sorting items with bubble_sort(items)')
print('Sorted items: [3, 4, 6, 7, 7, 9, 11, 15, 18, 20]')
return
# Get sort function by name
if len(args) >= 1:
sort_name = args[0]
# Terrible hack abusing globals
if sort_name in globals():
sort_function = globals()[sort_name]
else:
# Don't explode, just warn user and show list of sorting functions
print('Sorting function {!r} does not exist'.format(sort_name))
print('Available sorting functions:')
for name in globals():
if name.find('sort') >= 0:
print(' {}'.format(name))
return
# Get num_items and max_value, but don't explode if input is not an integer
try:
num_items = int(args[1]) if len(args) >= 2 else 20
max_value = int(args[2]) if len(args) >= 3 else 50
# print('Num items: {}, max value: {}'.format(num_items, max_value))
except ValueError:
print('Integer required for `num` and `max` command-line arguments')
return
# Test sort function
test_sorting(sort_function, num_items, max_value)
if __name__ == '__main__':
main()
| 46.192708 | 79 | 0.685083 |
from binarytree import *
def is_sorted(items):
def bubble_sort(items):
def selection_sort(items):
def insertion_sort(items):
def merge(items1, items2):
def split_sort_merge(items):
def merge_sort(items):
# TODO: Split items list into approximately equal halves
# TODO: Sort each half by recursively calling merge sort
# TODO: Merge sorted halves into one list in sorted order
def partition(items, low, high):
# TODO: Choose a pivot any way and document your method in docstring above
# TODO: Loop through all items in range [low...high]
# TODO: Move items less than pivot into front of range [low...p-1]
# TODO: Move items greater than pivot into back of range [p+1...high]
# TODO: Move pivot item into final position [p] and return index p
def quick_sort(items, low=None, high=None):
# TODO: Check if high and low range bounds have default values (not given)
# TODO: Check if list or range is so small it's already sorted (base case)
def counting_sort(numbers):
# TODO: Loop over counts and append that many numbers into output list
# FIXME: Improve this to mutate input instead of creating new output list
def bucket_sort(numbers, num_buckets=10):
# TODO: Find range of given numbers (minimum and maximum integer values)
# TODO: Create list of buckets to store numbers in subranges of input range
# TODO: Loop over given numbers and place each item in appropriate bucket
# TODO: Sort each bucket using any sorting algorithm (recursive or another)
# TODO: Loop over buckets and append each bucket's numbers into output list
def random_ints(count=20, min=1, max=50):
import random
return [random.randint(min, max) for _ in range(count)]
def test_sorting(sort=bubble_sort, num_items=20, max_value=50):
items = random_ints(num_items, 1, max_value)
print('Initial items: {!r}'.format(items))
print('Sorted order? {!r}'.format(is_sorted(items)))
print('Sorting items with {}(items)'.format(sort.__name__))
sort(items)
print('Sorted items: {!r}'.format(items))
print('Sorted order? {!r}'.format(is_sorted(items)))
def main():
import sys
args = sys.argv[1:]
if len(args) == 0:
script = sys.argv[0]
print('Usage: {} sort num max'.format(script))
print('Test sorting algorithm `sort` with a list of `num` integers')
print(' randomly sampled from the range [1...`max`] (inclusive)')
print('\nExample: {} bubble_sort 10 20'.format(script))
print('Initial items: [3, 15, 4, 7, 20, 6, 18, 11, 9, 7]')
print('Sorting items with bubble_sort(items)')
print('Sorted items: [3, 4, 6, 7, 7, 9, 11, 15, 18, 20]')
return
if len(args) >= 1:
sort_name = args[0]
if sort_name in globals():
sort_function = globals()[sort_name]
else:
print('Sorting function {!r} does not exist'.format(sort_name))
print('Available sorting functions:')
for name in globals():
if name.find('sort') >= 0:
print(' {}'.format(name))
return
# Get num_items and max_value, but don't explode if input is not an integer
try:
num_items = int(args[1]) if len(args) >= 2 else 20
max_value = int(args[2]) if len(args) >= 3 else 50
except ValueError:
print('Integer required for `num` and `max` command-line arguments')
return
test_sorting(sort_function, num_items, max_value)
if __name__ == '__main__':
main()
| true | true |
f7282ab5b450a61c8b20960d685ccc0d070b6634 | 25,444 | py | Python | kuryr_kubernetes/controller/drivers/network_policy_security_groups.py | openshift-cherrypick-robot/kuryr-kubernetes | 8bb955ac520b5f7a15c97b5b97d53a2069befd99 | [
"Apache-2.0"
] | null | null | null | kuryr_kubernetes/controller/drivers/network_policy_security_groups.py | openshift-cherrypick-robot/kuryr-kubernetes | 8bb955ac520b5f7a15c97b5b97d53a2069befd99 | [
"Apache-2.0"
] | null | null | null | kuryr_kubernetes/controller/drivers/network_policy_security_groups.py | openshift-cherrypick-robot/kuryr-kubernetes | 8bb955ac520b5f7a15c97b5b97d53a2069befd99 | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from kuryr_kubernetes import clients
from kuryr_kubernetes import config
from kuryr_kubernetes import constants
from kuryr_kubernetes.controller.drivers import base
from kuryr_kubernetes.controller.drivers import utils as driver_utils
from kuryr_kubernetes import exceptions
from oslo_config import cfg
from oslo_log import log as logging
LOG = logging.getLogger(__name__)
def _get_namespace_labels(namespace):
kubernetes = clients.get_kubernetes_client()
try:
path = '{}/{}'.format(
constants.K8S_API_NAMESPACES, namespace)
LOG.debug("K8s API Query %s", path)
namespaces = kubernetes.get(path)
LOG.debug("Return Namespace: %s", namespaces)
except exceptions.K8sResourceNotFound:
LOG.exception("Namespace not found")
raise
except exceptions.K8sClientException:
LOG.exception("Kubernetes Client Exception")
raise
return namespaces['metadata'].get('labels')
def _create_sg_rule(sg_id, direction, cidr, port=None, namespace=None):
if port:
sg_rule = driver_utils.create_security_group_rule_body(
sg_id, direction, port.get('port'),
protocol=port.get('protocol'), cidr=cidr, namespace=namespace)
else:
sg_rule = driver_utils.create_security_group_rule_body(
sg_id, direction, port_range_min=1,
port_range_max=65535, cidr=cidr, namespace=namespace)
sgr_id = driver_utils.create_security_group_rule(sg_rule)
sg_rule['security_group_rule']['id'] = sgr_id
return sg_rule
def _get_crd_rule(crd_rules, container_port):
"""Returns a CRD rule that matches a container port
Retrieves the CRD rule that contains a given port in
the range of the rule ports.
"""
for crd_rule in crd_rules:
remote_ip_prefixes = crd_rule.get('remote_ip_prefixes')
min_port = crd_rule['security_group_rule'].get('port_range_min')
max_port = crd_rule['security_group_rule'].get('port_range_max')
if (remote_ip_prefixes and (
min_port >= container_port and
container_port <= max_port)):
return crd_rule
def _create_sg_rules_with_container_ports(matched_pods, container_ports,
allow_all, namespace, matched,
crd_rules, sg_id, direction,
port, rule_selected_pod):
"""Create security group rules based on container ports
If it's an allow from/to everywhere rule or a rule with a
NamespaceSelector, updates a sg rule that might already exist
and match the named port or creates a new one with the
remote_ip_prefixes field containing the matched pod info.
Otherwise, creates rules for each container port without
a remote_ip_prefixes field.
param matched_pods: List of dicts where the key is a container
port and value is the pods that have the port
param container_ports: List of tuples with pods and port values
param allow_all: True is it's an allow from/to everywhere rule,
False otherwise.
param namespace: Namespace name
param matched: If a sg rule was created for the NP rule
param crd_rules: List of sg rules to update when patching the CRD
param sg_id: ID of the security group
param direction: String representing rule direction, ingress or egress
param port: Dict containing port and protocol
param rule_selected_pod: K8s Pod object selected by the rules selectors
return: True if a sg rule was created, False otherwise.
"""
for pod, container_port in container_ports:
pod_namespace = pod['metadata']['namespace']
pod_ip = driver_utils.get_pod_ip(pod)
if not pod_ip:
LOG.debug("Skipping SG rule creation for pod %s due to "
"no IP assigned", pod['metadata']['name'])
continue
pod_info = {pod_ip: pod_namespace}
matched = True
if allow_all or namespace:
crd_rule = _get_crd_rule(crd_rules, container_port)
if crd_rule:
crd_rule['remote_ip_prefixes'].update(pod_info)
else:
if container_port in matched_pods:
matched_pods[container_port].update(pod_info)
else:
matched_pods[container_port] = pod_info
else:
pod_ip = driver_utils.get_pod_ip(rule_selected_pod)
if not pod_ip:
LOG.debug("Skipping SG rule creation for pod %s due to no IP "
"assigned", rule_selected_pod['metadata']['name'])
continue
sg_rule = driver_utils.create_security_group_rule_body(
sg_id, direction, container_port,
protocol=port.get('protocol'),
cidr=pod_ip, pods=pod_info)
sgr_id = driver_utils.create_security_group_rule(sg_rule)
sg_rule['security_group_rule']['id'] = sgr_id
if sg_rule not in crd_rules:
crd_rules.append(sg_rule)
return matched
def _create_sg_rule_on_text_port(sg_id, direction, port, rule_selected_pods,
crd_rules, matched, crd,
allow_all=False, namespace=None):
matched_pods = {}
spec_pod_selector = crd['spec'].get('podSelector')
policy_namespace = crd['metadata']['namespace']
spec_pods = driver_utils.get_pods(
spec_pod_selector, policy_namespace).get('items')
if direction == 'ingress':
for spec_pod in spec_pods:
container_ports = driver_utils.get_ports(spec_pod, port)
for rule_selected_pod in rule_selected_pods:
matched = _create_sg_rules_with_container_ports(
matched_pods, container_ports, allow_all, namespace,
matched, crd_rules, sg_id, direction, port,
rule_selected_pod)
elif direction == 'egress':
for rule_selected_pod in rule_selected_pods:
pod_label = rule_selected_pod['metadata'].get('labels')
pod_ns = rule_selected_pod['metadata'].get('namespace')
# NOTE(maysams) Do not allow egress traffic to the actual
# set of pods the NP is enforced on.
if (driver_utils.match_selector(spec_pod_selector, pod_label) and
policy_namespace == pod_ns):
continue
container_ports = driver_utils.get_ports(
rule_selected_pod, port)
matched = _create_sg_rules_with_container_ports(
matched_pods, container_ports, allow_all,
namespace, matched, crd_rules, sg_id, direction,
port, rule_selected_pod)
for container_port, pods in matched_pods.items():
if allow_all:
sg_rule = driver_utils.create_security_group_rule_body(
sg_id, direction, container_port,
protocol=port.get('protocol'),
pods=pods)
else:
namespace_obj = driver_utils.get_namespace(namespace)
namespace_cidr = driver_utils.get_namespace_subnet_cidr(
namespace_obj)
sg_rule = driver_utils.create_security_group_rule_body(
sg_id, direction, container_port,
protocol=port.get('protocol'), cidr=namespace_cidr,
pods=pods)
sgr_id = driver_utils.create_security_group_rule(sg_rule)
sg_rule['security_group_rule']['id'] = sgr_id
crd_rules.append(sg_rule)
return matched
def _create_sg_rules(crd, pod, pod_selector, rule_block,
crd_rules, direction, matched, namespace=None,
allow_all=False):
pod_labels = pod['metadata'].get('labels')
pod_ip = driver_utils.get_pod_ip(pod)
if not pod_ip:
LOG.debug("Skipping SG rule creation for pod %s due to "
"no IP assigned", pod['metadata']['name'])
return None
# NOTE (maysams) No need to differentiate between podSelector
# with empty value or with '{}', as they have same result in here.
if pod_selector:
if driver_utils.match_selector(pod_selector, pod_labels):
sg_id = crd['spec']['securityGroupId']
if 'ports' in rule_block:
for port in rule_block['ports']:
if type(port.get('port')) is not int:
matched = _create_sg_rule_on_text_port(
sg_id, direction, port, [pod],
crd_rules, matched, crd)
else:
matched = True
sg_rule = _create_sg_rule(
sg_id, direction, cidr=pod_ip, port=port,
namespace=namespace)
crd_rules.append(sg_rule)
else:
matched = True
sg_rule = _create_sg_rule(
sg_id, direction, cidr=pod_ip, namespace=namespace)
crd_rules.append(sg_rule)
else:
# NOTE (maysams) When a policy with namespaceSelector and text port
# is applied the port on the pods needs to be retrieved.
sg_id = crd['spec']['securityGroupId']
if 'ports' in rule_block:
for port in rule_block['ports']:
if type(port.get('port')) is not int:
matched = (
_create_sg_rule_on_text_port(
sg_id, direction, port, [pod],
crd_rules, matched, crd,
allow_all=allow_all, namespace=namespace))
return matched
def _parse_selectors_on_pod(crd, pod, pod_selector, namespace_selector,
rule_block, crd_rules, direction, matched):
pod_namespace = pod['metadata']['namespace']
pod_namespace_labels = _get_namespace_labels(pod_namespace)
policy_namespace = crd['metadata']['namespace']
if namespace_selector == {}:
matched = _create_sg_rules(crd, pod, pod_selector, rule_block,
crd_rules, direction, matched,
allow_all=True)
elif namespace_selector:
if (pod_namespace_labels and
driver_utils.match_selector(namespace_selector,
pod_namespace_labels)):
matched = _create_sg_rules(crd, pod, pod_selector,
rule_block, crd_rules,
direction, matched,
namespace=pod_namespace)
else:
if pod_namespace == policy_namespace:
matched = _create_sg_rules(crd, pod, pod_selector, rule_block,
crd_rules, direction, matched,
namespace=pod_namespace)
return matched, crd_rules
def _parse_selectors_on_namespace(crd, direction, pod_selector,
ns_selector, rule_block, crd_rules,
namespace, matched):
ns_name = namespace['metadata'].get('name')
ns_labels = namespace['metadata'].get('labels')
sg_id = crd['spec']['securityGroupId']
if (ns_selector and ns_labels and
driver_utils.match_selector(ns_selector, ns_labels)):
if pod_selector:
pods = driver_utils.get_pods(pod_selector, ns_name).get('items')
if 'ports' in rule_block:
for port in rule_block['ports']:
if type(port.get('port')) is not int:
matched = (
_create_sg_rule_on_text_port(
sg_id, direction, port, pods,
crd_rules, matched, crd))
else:
matched = True
for pod in pods:
pod_ip = driver_utils.get_pod_ip(pod)
if not pod_ip:
pod_name = pod['metadata']['name']
LOG.debug("Skipping SG rule creation for pod "
"%s due to no IP assigned", pod_name)
continue
crd_rules.append(_create_sg_rule(
sg_id, direction, pod_ip, port=port,
namespace=ns_name))
else:
for pod in pods:
pod_ip = driver_utils.get_pod_ip(pod)
if not pod_ip:
pod_name = pod['metadata']['name']
LOG.debug("Skipping SG rule creation for pod %s due"
" to no IP assigned", pod_name)
continue
matched = True
crd_rules.append(_create_sg_rule(
sg_id, direction, pod_ip,
namespace=ns_name))
else:
ns_pods = driver_utils.get_pods(ns_selector)
ns_cidr = driver_utils.get_namespace_subnet_cidr(namespace)
if 'ports' in rule_block:
for port in rule_block['ports']:
if type(port.get('port')) is not int:
matched = (
_create_sg_rule_on_text_port(
sg_id, direction, port, ns_pods,
crd_rules, matched, crd))
else:
matched = True
crd_rules.append(_create_sg_rule(
sg_id, direction, ns_cidr,
port=port, namespace=ns_name))
else:
matched = True
crd_rules.append(_create_sg_rule(
sg_id, direction, ns_cidr,
namespace=ns_name))
return matched, crd_rules
def _parse_rules(direction, crd, pod=None, namespace=None):
policy = crd['spec']['networkpolicy_spec']
rule_direction = 'from'
crd_rules = crd['spec'].get('ingressSgRules')
if direction == 'egress':
rule_direction = 'to'
crd_rules = crd['spec'].get('egressSgRules')
matched = False
rule_list = policy.get(direction, [])
for rule_block in rule_list:
for rule in rule_block.get(rule_direction, []):
namespace_selector = rule.get('namespaceSelector')
pod_selector = rule.get('podSelector')
if pod:
matched, crd_rules = _parse_selectors_on_pod(
crd, pod, pod_selector, namespace_selector,
rule_block, crd_rules, direction, matched)
elif namespace:
matched, crd_rules = _parse_selectors_on_namespace(
crd, direction, pod_selector, namespace_selector,
rule_block, crd_rules, namespace, matched)
# NOTE(maysams): Cover the case of a network policy that allows
# from everywhere on a named port, e.g., when there is no 'from'
# specified.
if pod and not matched:
for port in rule_block.get('ports', []):
if type(port.get('port')) is not int:
sg_id = crd['spec']['securityGroupId']
if (not rule_block.get(rule_direction, [])
or direction == "ingress"):
matched = (_create_sg_rule_on_text_port(
sg_id, direction, port, [pod],
crd_rules, matched, crd,
allow_all=True))
return matched, crd_rules
def _parse_rules_on_delete_namespace(rule_list, direction, ns_name):
matched = False
rules = []
for rule in rule_list:
LOG.debug('Parsing %(dir)s Rule %(r)s', {'dir': direction,
'r': rule})
rule_namespace = rule.get('namespace', None)
remote_ip_prefixes = rule.get('remote_ip_prefixes', [])
if rule_namespace and rule_namespace == ns_name:
matched = True
driver_utils.delete_security_group_rule(
rule['security_group_rule']['id'])
for remote_ip, namespace in remote_ip_prefixes:
if namespace == ns_name:
matched = True
remote_ip_prefixes.pop(remote_ip)
if remote_ip_prefixes:
rule['remote_ip_prefixes'] = remote_ip_prefixes
rules.append(rule)
else:
rules.append(rule)
return matched, rules
def _parse_rules_on_delete_pod(rule_list, direction, pod_ip):
matched = False
rules = []
for rule in rule_list:
LOG.debug('Parsing %(dir)s Rule %(r)s', {'dir': direction,
'r': rule})
remote_ip_prefix = rule['security_group_rule'].get(
'remote_ip_prefix')
remote_ip_prefixes = rule.get('remote_ip_prefixes', [])
if remote_ip_prefix and remote_ip_prefix == pod_ip:
matched = True
driver_utils.delete_security_group_rule(
rule['security_group_rule']['id'])
elif remote_ip_prefixes:
if pod_ip in remote_ip_prefixes:
matched = True
remote_ip_prefixes.pop(pod_ip)
if remote_ip_prefixes:
rule['remote_ip_prefixes'] = remote_ip_prefixes
rules.append(rule)
else:
rules.append(rule)
return matched, rules
def _get_pod_sgs(pod, project_id):
sg_list = []
pod_labels = pod['metadata'].get('labels')
pod_namespace = pod['metadata']['namespace']
knp_crds = driver_utils.get_kuryrnetpolicy_crds(
namespace=pod_namespace)
for crd in knp_crds.get('items'):
pod_selector = crd['spec'].get('podSelector')
if pod_selector:
if driver_utils.match_selector(pod_selector, pod_labels):
LOG.debug("Appending %s",
str(crd['spec']['securityGroupId']))
sg_list.append(str(crd['spec']['securityGroupId']))
else:
LOG.debug("Appending %s", str(crd['spec']['securityGroupId']))
sg_list.append(str(crd['spec']['securityGroupId']))
# NOTE(maysams) Pods that are not selected by any Networkpolicy
# are fully accessible. Thus, the default security group is associated.
if not sg_list:
sg_list = config.CONF.neutron_defaults.pod_security_groups
if not sg_list:
raise cfg.RequiredOptError('pod_security_groups',
cfg.OptGroup('neutron_defaults'))
return sg_list[:]
class NetworkPolicySecurityGroupsDriver(base.PodSecurityGroupsDriver):
"""Provides security groups for pods based on network policies"""
def get_security_groups(self, pod, project_id):
return _get_pod_sgs(pod, project_id)
def create_sg_rules(self, pod):
LOG.debug("Creating sg rule for pod: %s", pod['metadata']['name'])
crd_pod_selectors = []
knp_crds = driver_utils.get_kuryrnetpolicy_crds()
for crd in knp_crds.get('items'):
crd_selector = crd['spec'].get('podSelector')
i_matched, i_rules = _parse_rules('ingress', crd, pod=pod)
e_matched, e_rules = _parse_rules('egress', crd, pod=pod)
if i_matched or e_matched:
driver_utils.patch_kuryrnetworkpolicy_crd(crd, i_rules,
e_rules,
crd_selector)
crd_pod_selectors.append(crd_selector)
return crd_pod_selectors
def delete_sg_rules(self, pod):
LOG.debug("Deleting sg rule for pod: %s", pod['metadata']['name'])
pod_ip = driver_utils.get_pod_ip(pod)
if not pod_ip:
LOG.debug("Skipping SG rule deletion as pod %s has no IP assigned",
pod['metadata']['name'])
return None
crd_pod_selectors = []
knp_crds = driver_utils.get_kuryrnetpolicy_crds()
for crd in knp_crds.get('items'):
crd_selector = crd['spec'].get('podSelector')
ingress_rule_list = crd['spec'].get('ingressSgRules')
egress_rule_list = crd['spec'].get('egressSgRules')
i_matched, i_rules = _parse_rules_on_delete_pod(
ingress_rule_list, "ingress", pod_ip)
e_matched, e_rules = _parse_rules_on_delete_pod(
egress_rule_list, "egress", pod_ip)
if i_matched or e_matched:
driver_utils.patch_kuryrnetworkpolicy_crd(crd, i_rules,
e_rules,
crd_selector)
crd_pod_selectors.append(crd_selector)
return crd_pod_selectors
def update_sg_rules(self, pod):
LOG.debug("Updating sg rule for pod: %s", pod['metadata']['name'])
crd_pod_selectors = []
crd_pod_selectors.extend(self.delete_sg_rules(pod))
crd_pod_selectors.extend(self.create_sg_rules(pod))
return crd_pod_selectors
def delete_namespace_sg_rules(self, namespace):
ns_name = namespace['metadata']['name']
LOG.debug("Deleting sg rule for namespace: %s",
ns_name)
knp_crds = driver_utils.get_kuryrnetpolicy_crds()
for crd in knp_crds.get('items'):
crd_selector = crd['spec'].get('podSelector')
ingress_rule_list = crd['spec'].get('ingressSgRules')
egress_rule_list = crd['spec'].get('egressSgRules')
i_matched, i_rules = _parse_rules_on_delete_namespace(
ingress_rule_list, "ingress", ns_name)
e_matched, e_rules = _parse_rules_on_delete_namespace(
egress_rule_list, "egress", ns_name)
if i_matched or e_matched:
driver_utils.patch_kuryrnetworkpolicy_crd(
crd, i_rules, e_rules, crd_selector)
def create_namespace_sg_rules(self, namespace):
kubernetes = clients.get_kubernetes_client()
ns_name = namespace['metadata']['name']
LOG.debug("Creating sg rule for namespace: %s", ns_name)
namespace = kubernetes.get(
'{}/namespaces/{}'.format(constants.K8S_API_BASE, ns_name))
knp_crds = driver_utils.get_kuryrnetpolicy_crds()
for crd in knp_crds.get('items'):
crd_selector = crd['spec'].get('podSelector')
i_matched, i_rules = _parse_rules(
'ingress', crd, namespace=namespace)
e_matched, e_rules = _parse_rules(
'egress', crd, namespace=namespace)
if i_matched or e_matched:
driver_utils.patch_kuryrnetworkpolicy_crd(crd, i_rules,
e_rules,
crd_selector)
def update_namespace_sg_rules(self, namespace):
LOG.debug("Updating sg rule for namespace: %s",
namespace['metadata']['name'])
self.delete_namespace_sg_rules(namespace)
self.create_namespace_sg_rules(namespace)
def create_namespace_sg(self, namespace, project_id, crd_spec):
LOG.debug("Security group driver does not create SGs for the "
"namespaces.")
return {}
def delete_sg(self, sg_id):
LOG.debug("Security group driver does not implement deleting "
"SGs.")
class NetworkPolicyServiceSecurityGroupsDriver(
base.ServiceSecurityGroupsDriver):
"""Provides security groups for services based on network policies"""
def get_security_groups(self, service, project_id):
sg_list = []
svc_namespace = service['metadata']['namespace']
svc_selector = service['spec'].get('selector')
# skip is no selector
if svc_selector:
# get affected pods by svc selector
pods = driver_utils.get_pods({'selector': svc_selector},
svc_namespace).get('items')
# NOTE(ltomasbo): We assume all the pods pointed by a service
# have the same labels, and the same policy will be applied to
# all of them. Hence only considering the security groups applied
# to the first one.
if pods:
return _get_pod_sgs(pods[0], project_id)
return sg_list[:]
| 43.568493 | 79 | 0.583438 |
from kuryr_kubernetes import clients
from kuryr_kubernetes import config
from kuryr_kubernetes import constants
from kuryr_kubernetes.controller.drivers import base
from kuryr_kubernetes.controller.drivers import utils as driver_utils
from kuryr_kubernetes import exceptions
from oslo_config import cfg
from oslo_log import log as logging
LOG = logging.getLogger(__name__)
def _get_namespace_labels(namespace):
kubernetes = clients.get_kubernetes_client()
try:
path = '{}/{}'.format(
constants.K8S_API_NAMESPACES, namespace)
LOG.debug("K8s API Query %s", path)
namespaces = kubernetes.get(path)
LOG.debug("Return Namespace: %s", namespaces)
except exceptions.K8sResourceNotFound:
LOG.exception("Namespace not found")
raise
except exceptions.K8sClientException:
LOG.exception("Kubernetes Client Exception")
raise
return namespaces['metadata'].get('labels')
def _create_sg_rule(sg_id, direction, cidr, port=None, namespace=None):
if port:
sg_rule = driver_utils.create_security_group_rule_body(
sg_id, direction, port.get('port'),
protocol=port.get('protocol'), cidr=cidr, namespace=namespace)
else:
sg_rule = driver_utils.create_security_group_rule_body(
sg_id, direction, port_range_min=1,
port_range_max=65535, cidr=cidr, namespace=namespace)
sgr_id = driver_utils.create_security_group_rule(sg_rule)
sg_rule['security_group_rule']['id'] = sgr_id
return sg_rule
def _get_crd_rule(crd_rules, container_port):
for crd_rule in crd_rules:
remote_ip_prefixes = crd_rule.get('remote_ip_prefixes')
min_port = crd_rule['security_group_rule'].get('port_range_min')
max_port = crd_rule['security_group_rule'].get('port_range_max')
if (remote_ip_prefixes and (
min_port >= container_port and
container_port <= max_port)):
return crd_rule
def _create_sg_rules_with_container_ports(matched_pods, container_ports,
allow_all, namespace, matched,
crd_rules, sg_id, direction,
port, rule_selected_pod):
for pod, container_port in container_ports:
pod_namespace = pod['metadata']['namespace']
pod_ip = driver_utils.get_pod_ip(pod)
if not pod_ip:
LOG.debug("Skipping SG rule creation for pod %s due to "
"no IP assigned", pod['metadata']['name'])
continue
pod_info = {pod_ip: pod_namespace}
matched = True
if allow_all or namespace:
crd_rule = _get_crd_rule(crd_rules, container_port)
if crd_rule:
crd_rule['remote_ip_prefixes'].update(pod_info)
else:
if container_port in matched_pods:
matched_pods[container_port].update(pod_info)
else:
matched_pods[container_port] = pod_info
else:
pod_ip = driver_utils.get_pod_ip(rule_selected_pod)
if not pod_ip:
LOG.debug("Skipping SG rule creation for pod %s due to no IP "
"assigned", rule_selected_pod['metadata']['name'])
continue
sg_rule = driver_utils.create_security_group_rule_body(
sg_id, direction, container_port,
protocol=port.get('protocol'),
cidr=pod_ip, pods=pod_info)
sgr_id = driver_utils.create_security_group_rule(sg_rule)
sg_rule['security_group_rule']['id'] = sgr_id
if sg_rule not in crd_rules:
crd_rules.append(sg_rule)
return matched
def _create_sg_rule_on_text_port(sg_id, direction, port, rule_selected_pods,
crd_rules, matched, crd,
allow_all=False, namespace=None):
matched_pods = {}
spec_pod_selector = crd['spec'].get('podSelector')
policy_namespace = crd['metadata']['namespace']
spec_pods = driver_utils.get_pods(
spec_pod_selector, policy_namespace).get('items')
if direction == 'ingress':
for spec_pod in spec_pods:
container_ports = driver_utils.get_ports(spec_pod, port)
for rule_selected_pod in rule_selected_pods:
matched = _create_sg_rules_with_container_ports(
matched_pods, container_ports, allow_all, namespace,
matched, crd_rules, sg_id, direction, port,
rule_selected_pod)
elif direction == 'egress':
for rule_selected_pod in rule_selected_pods:
pod_label = rule_selected_pod['metadata'].get('labels')
pod_ns = rule_selected_pod['metadata'].get('namespace')
if (driver_utils.match_selector(spec_pod_selector, pod_label) and
policy_namespace == pod_ns):
continue
container_ports = driver_utils.get_ports(
rule_selected_pod, port)
matched = _create_sg_rules_with_container_ports(
matched_pods, container_ports, allow_all,
namespace, matched, crd_rules, sg_id, direction,
port, rule_selected_pod)
for container_port, pods in matched_pods.items():
if allow_all:
sg_rule = driver_utils.create_security_group_rule_body(
sg_id, direction, container_port,
protocol=port.get('protocol'),
pods=pods)
else:
namespace_obj = driver_utils.get_namespace(namespace)
namespace_cidr = driver_utils.get_namespace_subnet_cidr(
namespace_obj)
sg_rule = driver_utils.create_security_group_rule_body(
sg_id, direction, container_port,
protocol=port.get('protocol'), cidr=namespace_cidr,
pods=pods)
sgr_id = driver_utils.create_security_group_rule(sg_rule)
sg_rule['security_group_rule']['id'] = sgr_id
crd_rules.append(sg_rule)
return matched
def _create_sg_rules(crd, pod, pod_selector, rule_block,
crd_rules, direction, matched, namespace=None,
allow_all=False):
pod_labels = pod['metadata'].get('labels')
pod_ip = driver_utils.get_pod_ip(pod)
if not pod_ip:
LOG.debug("Skipping SG rule creation for pod %s due to "
"no IP assigned", pod['metadata']['name'])
return None
if pod_selector:
if driver_utils.match_selector(pod_selector, pod_labels):
sg_id = crd['spec']['securityGroupId']
if 'ports' in rule_block:
for port in rule_block['ports']:
if type(port.get('port')) is not int:
matched = _create_sg_rule_on_text_port(
sg_id, direction, port, [pod],
crd_rules, matched, crd)
else:
matched = True
sg_rule = _create_sg_rule(
sg_id, direction, cidr=pod_ip, port=port,
namespace=namespace)
crd_rules.append(sg_rule)
else:
matched = True
sg_rule = _create_sg_rule(
sg_id, direction, cidr=pod_ip, namespace=namespace)
crd_rules.append(sg_rule)
else:
sg_id = crd['spec']['securityGroupId']
if 'ports' in rule_block:
for port in rule_block['ports']:
if type(port.get('port')) is not int:
matched = (
_create_sg_rule_on_text_port(
sg_id, direction, port, [pod],
crd_rules, matched, crd,
allow_all=allow_all, namespace=namespace))
return matched
def _parse_selectors_on_pod(crd, pod, pod_selector, namespace_selector,
rule_block, crd_rules, direction, matched):
pod_namespace = pod['metadata']['namespace']
pod_namespace_labels = _get_namespace_labels(pod_namespace)
policy_namespace = crd['metadata']['namespace']
if namespace_selector == {}:
matched = _create_sg_rules(crd, pod, pod_selector, rule_block,
crd_rules, direction, matched,
allow_all=True)
elif namespace_selector:
if (pod_namespace_labels and
driver_utils.match_selector(namespace_selector,
pod_namespace_labels)):
matched = _create_sg_rules(crd, pod, pod_selector,
rule_block, crd_rules,
direction, matched,
namespace=pod_namespace)
else:
if pod_namespace == policy_namespace:
matched = _create_sg_rules(crd, pod, pod_selector, rule_block,
crd_rules, direction, matched,
namespace=pod_namespace)
return matched, crd_rules
def _parse_selectors_on_namespace(crd, direction, pod_selector,
ns_selector, rule_block, crd_rules,
namespace, matched):
ns_name = namespace['metadata'].get('name')
ns_labels = namespace['metadata'].get('labels')
sg_id = crd['spec']['securityGroupId']
if (ns_selector and ns_labels and
driver_utils.match_selector(ns_selector, ns_labels)):
if pod_selector:
pods = driver_utils.get_pods(pod_selector, ns_name).get('items')
if 'ports' in rule_block:
for port in rule_block['ports']:
if type(port.get('port')) is not int:
matched = (
_create_sg_rule_on_text_port(
sg_id, direction, port, pods,
crd_rules, matched, crd))
else:
matched = True
for pod in pods:
pod_ip = driver_utils.get_pod_ip(pod)
if not pod_ip:
pod_name = pod['metadata']['name']
LOG.debug("Skipping SG rule creation for pod "
"%s due to no IP assigned", pod_name)
continue
crd_rules.append(_create_sg_rule(
sg_id, direction, pod_ip, port=port,
namespace=ns_name))
else:
for pod in pods:
pod_ip = driver_utils.get_pod_ip(pod)
if not pod_ip:
pod_name = pod['metadata']['name']
LOG.debug("Skipping SG rule creation for pod %s due"
" to no IP assigned", pod_name)
continue
matched = True
crd_rules.append(_create_sg_rule(
sg_id, direction, pod_ip,
namespace=ns_name))
else:
ns_pods = driver_utils.get_pods(ns_selector)
ns_cidr = driver_utils.get_namespace_subnet_cidr(namespace)
if 'ports' in rule_block:
for port in rule_block['ports']:
if type(port.get('port')) is not int:
matched = (
_create_sg_rule_on_text_port(
sg_id, direction, port, ns_pods,
crd_rules, matched, crd))
else:
matched = True
crd_rules.append(_create_sg_rule(
sg_id, direction, ns_cidr,
port=port, namespace=ns_name))
else:
matched = True
crd_rules.append(_create_sg_rule(
sg_id, direction, ns_cidr,
namespace=ns_name))
return matched, crd_rules
def _parse_rules(direction, crd, pod=None, namespace=None):
policy = crd['spec']['networkpolicy_spec']
rule_direction = 'from'
crd_rules = crd['spec'].get('ingressSgRules')
if direction == 'egress':
rule_direction = 'to'
crd_rules = crd['spec'].get('egressSgRules')
matched = False
rule_list = policy.get(direction, [])
for rule_block in rule_list:
for rule in rule_block.get(rule_direction, []):
namespace_selector = rule.get('namespaceSelector')
pod_selector = rule.get('podSelector')
if pod:
matched, crd_rules = _parse_selectors_on_pod(
crd, pod, pod_selector, namespace_selector,
rule_block, crd_rules, direction, matched)
elif namespace:
matched, crd_rules = _parse_selectors_on_namespace(
crd, direction, pod_selector, namespace_selector,
rule_block, crd_rules, namespace, matched)
if pod and not matched:
for port in rule_block.get('ports', []):
if type(port.get('port')) is not int:
sg_id = crd['spec']['securityGroupId']
if (not rule_block.get(rule_direction, [])
or direction == "ingress"):
matched = (_create_sg_rule_on_text_port(
sg_id, direction, port, [pod],
crd_rules, matched, crd,
allow_all=True))
return matched, crd_rules
def _parse_rules_on_delete_namespace(rule_list, direction, ns_name):
matched = False
rules = []
for rule in rule_list:
LOG.debug('Parsing %(dir)s Rule %(r)s', {'dir': direction,
'r': rule})
rule_namespace = rule.get('namespace', None)
remote_ip_prefixes = rule.get('remote_ip_prefixes', [])
if rule_namespace and rule_namespace == ns_name:
matched = True
driver_utils.delete_security_group_rule(
rule['security_group_rule']['id'])
for remote_ip, namespace in remote_ip_prefixes:
if namespace == ns_name:
matched = True
remote_ip_prefixes.pop(remote_ip)
if remote_ip_prefixes:
rule['remote_ip_prefixes'] = remote_ip_prefixes
rules.append(rule)
else:
rules.append(rule)
return matched, rules
def _parse_rules_on_delete_pod(rule_list, direction, pod_ip):
matched = False
rules = []
for rule in rule_list:
LOG.debug('Parsing %(dir)s Rule %(r)s', {'dir': direction,
'r': rule})
remote_ip_prefix = rule['security_group_rule'].get(
'remote_ip_prefix')
remote_ip_prefixes = rule.get('remote_ip_prefixes', [])
if remote_ip_prefix and remote_ip_prefix == pod_ip:
matched = True
driver_utils.delete_security_group_rule(
rule['security_group_rule']['id'])
elif remote_ip_prefixes:
if pod_ip in remote_ip_prefixes:
matched = True
remote_ip_prefixes.pop(pod_ip)
if remote_ip_prefixes:
rule['remote_ip_prefixes'] = remote_ip_prefixes
rules.append(rule)
else:
rules.append(rule)
return matched, rules
def _get_pod_sgs(pod, project_id):
sg_list = []
pod_labels = pod['metadata'].get('labels')
pod_namespace = pod['metadata']['namespace']
knp_crds = driver_utils.get_kuryrnetpolicy_crds(
namespace=pod_namespace)
for crd in knp_crds.get('items'):
pod_selector = crd['spec'].get('podSelector')
if pod_selector:
if driver_utils.match_selector(pod_selector, pod_labels):
LOG.debug("Appending %s",
str(crd['spec']['securityGroupId']))
sg_list.append(str(crd['spec']['securityGroupId']))
else:
LOG.debug("Appending %s", str(crd['spec']['securityGroupId']))
sg_list.append(str(crd['spec']['securityGroupId']))
if not sg_list:
sg_list = config.CONF.neutron_defaults.pod_security_groups
if not sg_list:
raise cfg.RequiredOptError('pod_security_groups',
cfg.OptGroup('neutron_defaults'))
return sg_list[:]
class NetworkPolicySecurityGroupsDriver(base.PodSecurityGroupsDriver):
def get_security_groups(self, pod, project_id):
return _get_pod_sgs(pod, project_id)
def create_sg_rules(self, pod):
LOG.debug("Creating sg rule for pod: %s", pod['metadata']['name'])
crd_pod_selectors = []
knp_crds = driver_utils.get_kuryrnetpolicy_crds()
for crd in knp_crds.get('items'):
crd_selector = crd['spec'].get('podSelector')
i_matched, i_rules = _parse_rules('ingress', crd, pod=pod)
e_matched, e_rules = _parse_rules('egress', crd, pod=pod)
if i_matched or e_matched:
driver_utils.patch_kuryrnetworkpolicy_crd(crd, i_rules,
e_rules,
crd_selector)
crd_pod_selectors.append(crd_selector)
return crd_pod_selectors
def delete_sg_rules(self, pod):
LOG.debug("Deleting sg rule for pod: %s", pod['metadata']['name'])
pod_ip = driver_utils.get_pod_ip(pod)
if not pod_ip:
LOG.debug("Skipping SG rule deletion as pod %s has no IP assigned",
pod['metadata']['name'])
return None
crd_pod_selectors = []
knp_crds = driver_utils.get_kuryrnetpolicy_crds()
for crd in knp_crds.get('items'):
crd_selector = crd['spec'].get('podSelector')
ingress_rule_list = crd['spec'].get('ingressSgRules')
egress_rule_list = crd['spec'].get('egressSgRules')
i_matched, i_rules = _parse_rules_on_delete_pod(
ingress_rule_list, "ingress", pod_ip)
e_matched, e_rules = _parse_rules_on_delete_pod(
egress_rule_list, "egress", pod_ip)
if i_matched or e_matched:
driver_utils.patch_kuryrnetworkpolicy_crd(crd, i_rules,
e_rules,
crd_selector)
crd_pod_selectors.append(crd_selector)
return crd_pod_selectors
def update_sg_rules(self, pod):
LOG.debug("Updating sg rule for pod: %s", pod['metadata']['name'])
crd_pod_selectors = []
crd_pod_selectors.extend(self.delete_sg_rules(pod))
crd_pod_selectors.extend(self.create_sg_rules(pod))
return crd_pod_selectors
def delete_namespace_sg_rules(self, namespace):
ns_name = namespace['metadata']['name']
LOG.debug("Deleting sg rule for namespace: %s",
ns_name)
knp_crds = driver_utils.get_kuryrnetpolicy_crds()
for crd in knp_crds.get('items'):
crd_selector = crd['spec'].get('podSelector')
ingress_rule_list = crd['spec'].get('ingressSgRules')
egress_rule_list = crd['spec'].get('egressSgRules')
i_matched, i_rules = _parse_rules_on_delete_namespace(
ingress_rule_list, "ingress", ns_name)
e_matched, e_rules = _parse_rules_on_delete_namespace(
egress_rule_list, "egress", ns_name)
if i_matched or e_matched:
driver_utils.patch_kuryrnetworkpolicy_crd(
crd, i_rules, e_rules, crd_selector)
def create_namespace_sg_rules(self, namespace):
kubernetes = clients.get_kubernetes_client()
ns_name = namespace['metadata']['name']
LOG.debug("Creating sg rule for namespace: %s", ns_name)
namespace = kubernetes.get(
'{}/namespaces/{}'.format(constants.K8S_API_BASE, ns_name))
knp_crds = driver_utils.get_kuryrnetpolicy_crds()
for crd in knp_crds.get('items'):
crd_selector = crd['spec'].get('podSelector')
i_matched, i_rules = _parse_rules(
'ingress', crd, namespace=namespace)
e_matched, e_rules = _parse_rules(
'egress', crd, namespace=namespace)
if i_matched or e_matched:
driver_utils.patch_kuryrnetworkpolicy_crd(crd, i_rules,
e_rules,
crd_selector)
def update_namespace_sg_rules(self, namespace):
LOG.debug("Updating sg rule for namespace: %s",
namespace['metadata']['name'])
self.delete_namespace_sg_rules(namespace)
self.create_namespace_sg_rules(namespace)
def create_namespace_sg(self, namespace, project_id, crd_spec):
LOG.debug("Security group driver does not create SGs for the "
"namespaces.")
return {}
def delete_sg(self, sg_id):
LOG.debug("Security group driver does not implement deleting "
"SGs.")
class NetworkPolicyServiceSecurityGroupsDriver(
base.ServiceSecurityGroupsDriver):
def get_security_groups(self, service, project_id):
sg_list = []
svc_namespace = service['metadata']['namespace']
svc_selector = service['spec'].get('selector')
if svc_selector:
pods = driver_utils.get_pods({'selector': svc_selector},
svc_namespace).get('items')
if pods:
return _get_pod_sgs(pods[0], project_id)
return sg_list[:]
| true | true |
f7282be0d76c30f36cb396659fd797b2a1a3d258 | 9,755 | py | Python | tools/r3det_gwd/train.py | Artcs1/RotationDetection | 095be17345ee9984d8de8f24eb6b5a0b2d764a06 | [
"Apache-2.0"
] | 850 | 2020-10-27T08:51:54.000Z | 2022-03-30T15:12:06.000Z | tools/r3det_gwd/train.py | Artcs1/RotationDetection | 095be17345ee9984d8de8f24eb6b5a0b2d764a06 | [
"Apache-2.0"
] | 94 | 2020-12-01T02:18:47.000Z | 2022-03-30T08:14:27.000Z | tools/r3det_gwd/train.py | Artcs1/RotationDetection | 095be17345ee9984d8de8f24eb6b5a0b2d764a06 | [
"Apache-2.0"
] | 149 | 2020-10-29T03:30:32.000Z | 2022-03-29T09:53:23.000Z | # -*- coding:utf-8 -*-
# Author: Xue Yang <yangxue-2019-sjtu@sjtu.edu.cn>
#
# License: Apache-2.0 license
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import os
import sys
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
sys.path.append("../../")
from tools.train_base import Train
from libs.configs import cfgs
from libs.models.detectors.r3det_gwd import build_whole_network
from libs.utils.coordinate_convert import backward_convert, get_horizen_minAreaRectangle
from dataloader.pretrained_weights.pretrain_zoo import PretrainModelZoo
os.environ["CUDA_VISIBLE_DEVICES"] = cfgs.GPU_GROUP
class TrainR3DetGWD(Train):
def get_gtboxes_and_label(self, gtboxes_and_label_h, gtboxes_and_label_r, num_objects):
return gtboxes_and_label_h[:int(num_objects), :].astype(np.float32), \
gtboxes_and_label_r[:int(num_objects), :].astype(np.float32)
def main(self):
with tf.Graph().as_default() as graph, tf.device('/cpu:0'):
num_gpu = len(cfgs.GPU_GROUP.strip().split(','))
global_step = slim.get_or_create_global_step()
lr = self.warmup_lr(cfgs.LR, global_step, cfgs.WARM_SETP, num_gpu)
tf.summary.scalar('lr', lr)
optimizer = tf.train.MomentumOptimizer(lr, momentum=cfgs.MOMENTUM)
r3det_gwd = build_whole_network.DetectionNetworkR3DetGWD(cfgs=self.cfgs,
is_training=True)
with tf.name_scope('get_batch'):
if cfgs.IMAGE_PYRAMID:
shortside_len_list = tf.constant(cfgs.IMG_SHORT_SIDE_LEN)
shortside_len = tf.random_shuffle(shortside_len_list)[0]
else:
shortside_len = cfgs.IMG_SHORT_SIDE_LEN
img_name_batch, img_batch, gtboxes_and_label_batch, num_objects_batch, img_h_batch, img_w_batch = \
self.reader.next_batch(dataset_name=cfgs.DATASET_NAME,
batch_size=cfgs.BATCH_SIZE * num_gpu,
shortside_len=shortside_len,
is_training=True)
# data processing
inputs_list = []
for i in range(num_gpu):
img = tf.expand_dims(img_batch[i], axis=0)
pretrain_zoo = PretrainModelZoo()
if self.cfgs.NET_NAME in pretrain_zoo.pth_zoo or self.cfgs.NET_NAME in pretrain_zoo.mxnet_zoo:
img = img / tf.constant([cfgs.PIXEL_STD])
gtboxes_and_label_r = tf.py_func(backward_convert,
inp=[gtboxes_and_label_batch[i]],
Tout=tf.float32)
gtboxes_and_label_r = tf.reshape(gtboxes_and_label_r, [-1, 6])
gtboxes_and_label_h = get_horizen_minAreaRectangle(gtboxes_and_label_batch[i])
gtboxes_and_label_h = tf.reshape(gtboxes_and_label_h, [-1, 5])
num_objects = num_objects_batch[i]
num_objects = tf.cast(tf.reshape(num_objects, [-1, ]), tf.float32)
img_h = img_h_batch[i]
img_w = img_w_batch[i]
inputs_list.append([img, gtboxes_and_label_h, gtboxes_and_label_r, num_objects, img_h, img_w])
tower_grads = []
biases_regularizer = tf.no_regularizer
weights_regularizer = tf.contrib.layers.l2_regularizer(cfgs.WEIGHT_DECAY)
with tf.variable_scope(tf.get_variable_scope()):
for i in range(num_gpu):
with tf.device('/gpu:%d' % i):
with tf.name_scope('tower_%d' % i):
with slim.arg_scope(
[slim.model_variable, slim.variable],
device='/device:CPU:0'):
with slim.arg_scope([slim.conv2d, slim.conv2d_in_plane,
slim.conv2d_transpose, slim.separable_conv2d,
slim.fully_connected],
weights_regularizer=weights_regularizer,
biases_regularizer=biases_regularizer,
biases_initializer=tf.constant_initializer(0.0)):
gtboxes_and_label_h, gtboxes_and_label_r = tf.py_func(self.get_gtboxes_and_label,
inp=[inputs_list[i][1],
inputs_list[i][2],
inputs_list[i][3]],
Tout=[tf.float32, tf.float32])
gtboxes_and_label_h = tf.reshape(gtboxes_and_label_h, [-1, 5])
gtboxes_and_label_r = tf.reshape(gtboxes_and_label_r, [-1, 6])
img = inputs_list[i][0]
img_shape = inputs_list[i][-2:]
img = tf.image.crop_to_bounding_box(image=img,
offset_height=0,
offset_width=0,
target_height=tf.cast(img_shape[0], tf.int32),
target_width=tf.cast(img_shape[1], tf.int32))
outputs = r3det_gwd.build_whole_detection_network(input_img_batch=img,
gtboxes_batch_h=gtboxes_and_label_h,
gtboxes_batch_r=gtboxes_and_label_r,
gpu_id=i)
gtboxes_in_img_h = self.drawer.draw_boxes_with_categories(img_batch=img,
boxes=gtboxes_and_label_h[
:, :-1],
labels=gtboxes_and_label_h[
:, -1],
method=0)
gtboxes_in_img_r = self.drawer.draw_boxes_with_categories(img_batch=img,
boxes=gtboxes_and_label_r[
:, :-1],
labels=gtboxes_and_label_r[
:, -1],
method=1)
tf.summary.image('Compare/gtboxes_h_gpu:%d' % i, gtboxes_in_img_h)
tf.summary.image('Compare/gtboxes_r_gpu:%d' % i, gtboxes_in_img_r)
if cfgs.ADD_BOX_IN_TENSORBOARD:
detections_in_img = self.drawer.draw_boxes_with_categories_and_scores(
img_batch=img,
boxes=outputs[0],
scores=outputs[1],
labels=outputs[2],
method=1)
tf.summary.image('Compare/final_detection_gpu:%d' % i, detections_in_img)
loss_dict = outputs[-1]
total_loss_dict, total_losses = self.loss_dict(loss_dict, num_gpu)
if i == num_gpu - 1:
regularization_losses = tf.get_collection(
tf.GraphKeys.REGULARIZATION_LOSSES)
# weight_decay_loss = tf.add_n(slim.losses.get_regularization_losses())
total_losses = total_losses + tf.add_n(regularization_losses)
tf.get_variable_scope().reuse_variables()
grads = optimizer.compute_gradients(total_losses)
if cfgs.GRADIENT_CLIPPING_BY_NORM is not None:
grads = slim.learning.clip_gradient_norms(grads, cfgs.GRADIENT_CLIPPING_BY_NORM)
tower_grads.append(grads)
self.log_printer(r3det_gwd, optimizer, global_step, tower_grads, total_loss_dict, num_gpu, graph)
if __name__ == '__main__':
trainer = TrainR3DetGWD(cfgs)
trainer.main() | 59.846626 | 122 | 0.445003 |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import os
import sys
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
sys.path.append("../../")
from tools.train_base import Train
from libs.configs import cfgs
from libs.models.detectors.r3det_gwd import build_whole_network
from libs.utils.coordinate_convert import backward_convert, get_horizen_minAreaRectangle
from dataloader.pretrained_weights.pretrain_zoo import PretrainModelZoo
os.environ["CUDA_VISIBLE_DEVICES"] = cfgs.GPU_GROUP
class TrainR3DetGWD(Train):
def get_gtboxes_and_label(self, gtboxes_and_label_h, gtboxes_and_label_r, num_objects):
return gtboxes_and_label_h[:int(num_objects), :].astype(np.float32), \
gtboxes_and_label_r[:int(num_objects), :].astype(np.float32)
def main(self):
with tf.Graph().as_default() as graph, tf.device('/cpu:0'):
num_gpu = len(cfgs.GPU_GROUP.strip().split(','))
global_step = slim.get_or_create_global_step()
lr = self.warmup_lr(cfgs.LR, global_step, cfgs.WARM_SETP, num_gpu)
tf.summary.scalar('lr', lr)
optimizer = tf.train.MomentumOptimizer(lr, momentum=cfgs.MOMENTUM)
r3det_gwd = build_whole_network.DetectionNetworkR3DetGWD(cfgs=self.cfgs,
is_training=True)
with tf.name_scope('get_batch'):
if cfgs.IMAGE_PYRAMID:
shortside_len_list = tf.constant(cfgs.IMG_SHORT_SIDE_LEN)
shortside_len = tf.random_shuffle(shortside_len_list)[0]
else:
shortside_len = cfgs.IMG_SHORT_SIDE_LEN
img_name_batch, img_batch, gtboxes_and_label_batch, num_objects_batch, img_h_batch, img_w_batch = \
self.reader.next_batch(dataset_name=cfgs.DATASET_NAME,
batch_size=cfgs.BATCH_SIZE * num_gpu,
shortside_len=shortside_len,
is_training=True)
inputs_list = []
for i in range(num_gpu):
img = tf.expand_dims(img_batch[i], axis=0)
pretrain_zoo = PretrainModelZoo()
if self.cfgs.NET_NAME in pretrain_zoo.pth_zoo or self.cfgs.NET_NAME in pretrain_zoo.mxnet_zoo:
img = img / tf.constant([cfgs.PIXEL_STD])
gtboxes_and_label_r = tf.py_func(backward_convert,
inp=[gtboxes_and_label_batch[i]],
Tout=tf.float32)
gtboxes_and_label_r = tf.reshape(gtboxes_and_label_r, [-1, 6])
gtboxes_and_label_h = get_horizen_minAreaRectangle(gtboxes_and_label_batch[i])
gtboxes_and_label_h = tf.reshape(gtboxes_and_label_h, [-1, 5])
num_objects = num_objects_batch[i]
num_objects = tf.cast(tf.reshape(num_objects, [-1, ]), tf.float32)
img_h = img_h_batch[i]
img_w = img_w_batch[i]
inputs_list.append([img, gtboxes_and_label_h, gtboxes_and_label_r, num_objects, img_h, img_w])
tower_grads = []
biases_regularizer = tf.no_regularizer
weights_regularizer = tf.contrib.layers.l2_regularizer(cfgs.WEIGHT_DECAY)
with tf.variable_scope(tf.get_variable_scope()):
for i in range(num_gpu):
with tf.device('/gpu:%d' % i):
with tf.name_scope('tower_%d' % i):
with slim.arg_scope(
[slim.model_variable, slim.variable],
device='/device:CPU:0'):
with slim.arg_scope([slim.conv2d, slim.conv2d_in_plane,
slim.conv2d_transpose, slim.separable_conv2d,
slim.fully_connected],
weights_regularizer=weights_regularizer,
biases_regularizer=biases_regularizer,
biases_initializer=tf.constant_initializer(0.0)):
gtboxes_and_label_h, gtboxes_and_label_r = tf.py_func(self.get_gtboxes_and_label,
inp=[inputs_list[i][1],
inputs_list[i][2],
inputs_list[i][3]],
Tout=[tf.float32, tf.float32])
gtboxes_and_label_h = tf.reshape(gtboxes_and_label_h, [-1, 5])
gtboxes_and_label_r = tf.reshape(gtboxes_and_label_r, [-1, 6])
img = inputs_list[i][0]
img_shape = inputs_list[i][-2:]
img = tf.image.crop_to_bounding_box(image=img,
offset_height=0,
offset_width=0,
target_height=tf.cast(img_shape[0], tf.int32),
target_width=tf.cast(img_shape[1], tf.int32))
outputs = r3det_gwd.build_whole_detection_network(input_img_batch=img,
gtboxes_batch_h=gtboxes_and_label_h,
gtboxes_batch_r=gtboxes_and_label_r,
gpu_id=i)
gtboxes_in_img_h = self.drawer.draw_boxes_with_categories(img_batch=img,
boxes=gtboxes_and_label_h[
:, :-1],
labels=gtboxes_and_label_h[
:, -1],
method=0)
gtboxes_in_img_r = self.drawer.draw_boxes_with_categories(img_batch=img,
boxes=gtboxes_and_label_r[
:, :-1],
labels=gtboxes_and_label_r[
:, -1],
method=1)
tf.summary.image('Compare/gtboxes_h_gpu:%d' % i, gtboxes_in_img_h)
tf.summary.image('Compare/gtboxes_r_gpu:%d' % i, gtboxes_in_img_r)
if cfgs.ADD_BOX_IN_TENSORBOARD:
detections_in_img = self.drawer.draw_boxes_with_categories_and_scores(
img_batch=img,
boxes=outputs[0],
scores=outputs[1],
labels=outputs[2],
method=1)
tf.summary.image('Compare/final_detection_gpu:%d' % i, detections_in_img)
loss_dict = outputs[-1]
total_loss_dict, total_losses = self.loss_dict(loss_dict, num_gpu)
if i == num_gpu - 1:
regularization_losses = tf.get_collection(
tf.GraphKeys.REGULARIZATION_LOSSES)
total_losses = total_losses + tf.add_n(regularization_losses)
tf.get_variable_scope().reuse_variables()
grads = optimizer.compute_gradients(total_losses)
if cfgs.GRADIENT_CLIPPING_BY_NORM is not None:
grads = slim.learning.clip_gradient_norms(grads, cfgs.GRADIENT_CLIPPING_BY_NORM)
tower_grads.append(grads)
self.log_printer(r3det_gwd, optimizer, global_step, tower_grads, total_loss_dict, num_gpu, graph)
if __name__ == '__main__':
trainer = TrainR3DetGWD(cfgs)
trainer.main() | true | true |
f7282d249dac2d7f722b3793a7a371b8a033b7fe | 1,887 | py | Python | apps/win/sublime_text/sublime_text.py | PetrKryslUCSD/knausj_talon_pk | 6612adb1794e0b02ce8b1c2b478b74cd6858954b | [
"MIT"
] | 1 | 2020-11-13T18:02:12.000Z | 2020-11-13T18:02:12.000Z | apps/win/sublime_text/sublime_text.py | PetrKryslUCSD/knausj_talon_pk | 6612adb1794e0b02ce8b1c2b478b74cd6858954b | [
"MIT"
] | null | null | null | apps/win/sublime_text/sublime_text.py | PetrKryslUCSD/knausj_talon_pk | 6612adb1794e0b02ce8b1c2b478b74cd6858954b | [
"MIT"
] | null | null | null | from talon import Context, actions, Module
mod = Module()
ctx = Context()
# ctx.matches = r"""
# app.bundle: com.sublimetext.4
# """
# ctx.matches = r"""
# os: windows
# and app.name: Sublime Text
# """
ctx.matches = r"""
os: windows
and app.exe: sublime_text.exe
"""
@ctx.action_class("edit")
class edit_actions:
def jump_line(n: int):
actions.key("ctrl-g")
actions.insert(str(n))
actions.key("enter")
def line_clone():
actions.key("ctrl-shift-d")
@ctx.action_class("user")
class user_actions:
def find(text: str):
actions.key("ctrl-f")
actions.insert(text)
def find_everywhere(text: str):
actions.key("ctrl-shift-f")
actions.insert(text)
def replace(text: str):
actions.key("ctrl-alt-f")
actions.insert(text)
replace_everywhere = find_everywhere
def copy_to_clipboard(number: int):
"""Copy a string to the clipboard """
clip.set_text(f"{number}")
# @ctx.action_class("win")
# class win_actions:
# def filename():
# title = actions.win.title()
# result = title.split(" — ")[0]
# return result if "." in result else ""
# def file_ext():
# return actions.win.filename().split(".")[-1]
# @ctx.action_class("win")
# class win_actions:
# def filename():
# title = actions.win.title()
# result = title.rsplit(" (", 1)[0]
# return result if "." in result else ""
@ctx.action_class("win")
class win_actions:
def filename():
title = actions.win.title()
result = title.rsplit(" - Sublime Text", 1)[0]
result = result.rsplit(" (", 1)[0]
result = result.rsplit(" •", 1)[0]
result.strip()
# print('*********comment**', result)
return result if "." in result else ""
# To be removed in talon 0.2. Not needed 04/27/2021
# def file_ext():
# e = "." + actions.win.filename().split(".")[-1]
# print(f'*****{e}******')
# return e
| 22.464286 | 57 | 0.606253 | from talon import Context, actions, Module
mod = Module()
ctx = Context()
# app.bundle: com.sublimetext.4
# """
# os: windows
# and app.name: Sublime Text
# """
ctx.matches = r"""
os: windows
and app.exe: sublime_text.exe
"""
@ctx.action_class("edit")
class edit_actions:
def jump_line(n: int):
actions.key("ctrl-g")
actions.insert(str(n))
actions.key("enter")
def line_clone():
actions.key("ctrl-shift-d")
@ctx.action_class("user")
class user_actions:
def find(text: str):
actions.key("ctrl-f")
actions.insert(text)
def find_everywhere(text: str):
actions.key("ctrl-shift-f")
actions.insert(text)
def replace(text: str):
actions.key("ctrl-alt-f")
actions.insert(text)
replace_everywhere = find_everywhere
def copy_to_clipboard(number: int):
clip.set_text(f"{number}")
@ctx.action_class("win")
class win_actions:
def filename():
title = actions.win.title()
result = title.rsplit(" - Sublime Text", 1)[0]
result = result.rsplit(" (", 1)[0]
result = result.rsplit(" •", 1)[0]
result.strip()
return result if "." in result else ""
| true | true |
f7282dfc82b8b13ce2fcbc18c60d131314e16b61 | 27,440 | py | Python | openmdao/core/tests/test_connections.py | wright/OpenMDAO | 0996d562aa04ad864c44f91c60c0f33024e09d5f | [
"Apache-2.0"
] | null | null | null | openmdao/core/tests/test_connections.py | wright/OpenMDAO | 0996d562aa04ad864c44f91c60c0f33024e09d5f | [
"Apache-2.0"
] | 1 | 2018-06-18T15:09:10.000Z | 2018-06-18T15:09:10.000Z | openmdao/core/tests/test_connections.py | bbrelje/OpenMDAO | 58f9ff47197531f4fb4ef632c6bcca11e799ccf0 | [
"Apache-2.0"
] | 1 | 2021-04-15T13:33:39.000Z | 2021-04-15T13:33:39.000Z | """ Tests related to connecing inputs to outputs."""
import unittest
import numpy as np
from io import StringIO
import openmdao.api as om
from openmdao.utils.assert_utils import assert_near_equal, assert_warning
from openmdao.utils.mpi import MPI
try:
from openmdao.vectors.petsc_vector import PETScVector
except ImportError:
PETScVector = None
class TestConnections(unittest.TestCase):
def setUp(self):
self.setup_model(None, None)
def setup_model(self, c1meta=None, c3meta=None):
self.p = om.Problem()
root = self.p.model
if c1meta is None:
c1meta = {}
if c3meta is None:
c3meta = {}
self.G1 = root.add_subsystem("G1", om.Group())
self.G2 = self.G1.add_subsystem("G2", om.Group())
self.C1 = self.G2.add_subsystem("C1", om.ExecComp('y=x*2.0', **c1meta))
self.C2 = self.G2.add_subsystem("C2", om.IndepVarComp('x', 1.0))
self.G3 = root.add_subsystem("G3", om.Group())
self.G4 = self.G3.add_subsystem("G4", om.Group())
self.C3 = self.G4.add_subsystem("C3", om.ExecComp('y=x*2.0', **c3meta))
self.C4 = self.G4.add_subsystem("C4", om.ExecComp('y=x*2.0'))
def test_no_conns(self):
self.p.setup()
self.p['G1.G2.C1.x'] = 111.
self.p['G3.G4.C3.x'] = 222.
self.p['G3.G4.C4.x'] = 333.
self.p.run_model()
self.assertEqual(self.C1._inputs['x'], 111.)
self.assertEqual(self.C3._inputs['x'], 222.)
self.assertEqual(self.C4._inputs['x'], 333.)
def test_pull_size_from_source(self):
raise unittest.SkipTest("setting input size based on src size not supported yet")
class Src(ExplicitComponent):
def setup(self):
self.add_input('x', 2.0)
self.add_output('y1', np.zeros((3, )))
self.add_output('y2', shape=((3, )))
def solve_nonlinear(self, inputs, outputs, resids):
x = inputs['x']
outputs['y1'] = x * np.array([1.0, 2.0, 3.0])
outputs['y2'] = x * np.array([1.0, 2.0, 3.0])
class Tgt(ExplicitComponent):
def setup(self):
self.add_input('x1')
self.add_input('x2')
self.add_output('y1', 0.0)
self.add_output('y2', 0.0)
def solve_nonlinear(self, inputs, outputs, resids):
x1 = inputs['x1']
x2 = inputs['x2']
outputs['y1'] = np.sum(x1)
outputs['y2'] = np.sum(x2)
p = om.Problem()
p.model.add_subsystem('src', Src())
p.model.add_subsystem('tgt', Tgt())
p.model.connect('src.y1', 'tgt.x1')
p.model.connect('src.y2', 'tgt.x2')
p.setup()
p.run_model()
self.assertEqual(p['tgt.y1'], 12.0)
self.assertEqual(p['tgt.y2'], 12.0)
def test_pull_size_from_source_with_indices(self):
raise unittest.SkipTest("setting input size based on src size not supported yet")
class Src(ExplicitComponent):
def setup(self):
self.add_input('x', 2.0)
self.add_output('y1', np.zeros((3, )))
self.add_output('y2', shape=((3, )))
self.add_output('y3', 3.0)
def solve_nonlinear(self, inputs, outputs, resids):
""" counts up. """
x = inputs['x']
outputs['y1'] = x * np.array([1.0, 2.0, 3.0])
outputs['y2'] = x * np.array([1.0, 2.0, 3.0])
outputs['y3'] = x * 4.0
class Tgt(ExplicitComponent):
def setup(self):
self.add_input('x1')
self.add_input('x2')
self.add_input('x3')
self.add_output('y1', 0.0)
self.add_output('y2', 0.0)
self.add_output('y3', 0.0)
def solve_nonlinear(self, inputs, outputs, resids):
""" counts up. """
x1 = inputs['x1']
x2 = inputs['x2']
x3 = inputs['x3']
outputs['y1'] = np.sum(x1)
outputs['y2'] = np.sum(x2)
outputs['y3'] = np.sum(x3)
top = om.Problem()
top.model.add_subsystem('src', Src())
top.model.add_subsystem('tgt', Tgt())
top.model.connect('src.y1', 'tgt.x1', src_indices=(0, 1))
top.model.connect('src.y2', 'tgt.x2', src_indices=(0, 1))
top.model.connect('src.y3', 'tgt.x3')
top.setup()
top.run_model()
self.assertEqual(top['tgt.y1'], 6.0)
self.assertEqual(top['tgt.y2'], 6.0)
self.assertEqual(top['tgt.y3'], 8.0)
def test_inp_inp_conn_no_src(self):
raise unittest.SkipTest("no setup testing yet")
self.p.model.connect('G3.G4.C3.x', 'G3.G4.C4.x')
stream = StringIO()
self.p.setup(out_stream=stream)
self.p['G3.G4.C3.x'] = 999.
self.assertEqual(self.p.model.G3.G4.C3._inputs['x'], 999.)
self.assertEqual(self.p.model.G3.G4.C4._inputs['x'], 999.)
content = stream.getvalue()
self.assertTrue("The following parameters have no associated unknowns:\n"
"G1.G2.C1.x\nG3.G4.C3.x\nG3.G4.C4.x" in content)
self.assertTrue("The following components have no connections:\n"
"G1.G2.C1\nG1.G2.C2\nG3.G4.C3\nG3.G4.C4\n" in content)
self.assertTrue("No recorders have been specified, so no data will be saved." in content)
class TestConnectionsPromoted(unittest.TestCase):
def test_inp_inp_promoted_w_prom_src(self):
p = om.Problem()
root = p.model
G1 = root.add_subsystem("G1", om.Group(), promotes=['x'])
G2 = G1.add_subsystem("G2", om.Group(), promotes=['x'])
G2.add_subsystem("C1", om.ExecComp('y=x*2.0'))
G2.add_subsystem("C2", om.IndepVarComp('x', 1.0), promotes=['x'])
G3 = root.add_subsystem("G3", om.Group(), promotes=['x'])
G4 = G3.add_subsystem("G4", om.Group(), promotes=['x'])
C3 = G4.add_subsystem("C3", om.ExecComp('y=x*2.0'), promotes=['x'])
C4 = G4.add_subsystem("C4", om.ExecComp('y=x*2.0'), promotes=['x'])
p.setup()
p.set_solver_print(level=0)
# setting promoted name will set the value into the outputs, but will
# not propagate it to the inputs. That will happen during run_model().
p['x'] = 999.
p.run_model()
self.assertEqual(C3._inputs['x'], 999.)
self.assertEqual(C4._inputs['x'], 999.)
def test_inp_inp_promoted_w_explicit_src(self):
p = om.Problem()
root = p.model
G1 = root.add_subsystem("G1", om.Group())
G2 = G1.add_subsystem("G2", om.Group(), promotes=['x'])
G2.add_subsystem("C1", om.ExecComp('y=x*2.0'))
G2.add_subsystem("C2", om.IndepVarComp('x', 1.0), promotes=['x'])
G3 = root.add_subsystem("G3", om.Group())
G4 = G3.add_subsystem("G4", om.Group(), promotes=['x'])
C3 = G4.add_subsystem("C3", om.ExecComp('y=x*2.0'), promotes=['x'])
C4 = G4.add_subsystem("C4", om.ExecComp('y=x*2.0'), promotes=['x'])
p.model.connect('G1.x', 'G3.x')
p.setup()
p.set_solver_print(level=0)
# setting promoted name will set the value into the outputs, but will
# not propagate it to the inputs. That will happen during run_model().
p['G1.x'] = 999.
p.run_model()
self.assertEqual(C3._inputs['x'], 999.)
self.assertEqual(C4._inputs['x'], 999.)
def test_overlapping_system_names(self):
# This ensures that _setup_connections does not think g1 and g1a are the same system
prob = om.Problem()
model = prob.model
g1 = model.add_subsystem('g1', om.Group())
g1a = model.add_subsystem('g1a', om.Group())
g1.add_subsystem('c', om.ExecComp('y=x'))
g1a.add_subsystem('c', om.ExecComp('y=x'))
model.connect('g1.c.y', 'g1a.c.x')
model.connect('g1a.c.y', 'g1.c.x')
prob.setup(check=True)
class TestConnectionsIndices(unittest.TestCase):
def setUp(self):
class ArrayComp(om.ExplicitComponent):
def setup(self):
self.add_input('inp', val=np.ones((2)))
self.add_input('inp1', val=0)
self.add_output('out', val=np.zeros((2)))
def compute(self, inputs, outputs):
outputs['out'] = inputs['inp'] * 2.
indep_var_comp = om.IndepVarComp()
indep_var_comp.add_output('blammo', val=3.)
indep_var_comp.add_output('arrout', val=np.ones(5))
prob = om.Problem()
prob.model.add_subsystem('idvp', indep_var_comp)
prob.model.add_subsystem('arraycomp', ArrayComp())
self.prob = prob
def test_bad_shapes(self):
# Should not be allowed because the source and target shapes do not match
self.prob.model.connect('idvp.blammo', 'arraycomp.inp')
expected = "<model> <class Group>: The source and target shapes do not match or are " + \
"ambiguous for the connection 'idvp.blammo' to 'arraycomp.inp'. " + \
"The source shape is (1,) but the target shape is (2,)."
try:
self.prob.setup()
except ValueError as err:
self.assertEqual(str(err), expected)
else:
self.fail('Exception expected.')
self.prob.model._raise_connection_errors = False
with assert_warning(UserWarning, expected):
self.prob.setup()
def test_bad_length(self):
# Should not be allowed because the length of src_indices is greater than
# the shape of arraycomp.inp
self.prob.model.connect('idvp.blammo', 'arraycomp.inp', src_indices=[0, 1, 0])
expected = "<model> <class Group>: The source indices [0 1 0] do not specify a valid shape " + \
"for the connection 'idvp.blammo' to 'arraycomp.inp'. The target shape is " + \
"(2,) but indices are (3,)."
try:
self.prob.setup()
except ValueError as err:
self.assertEqual(str(err), expected)
else:
self.fail('Exception expected.')
self.prob.model._raise_connection_errors = False
with assert_warning(UserWarning, expected):
self.prob.setup()
def test_bad_value(self):
# Should not be allowed because the index value within src_indices is outside
# the valid range for the source
self.prob.model.connect('idvp.arrout', 'arraycomp.inp1', src_indices=[100000])
expected = "<model> <class Group>: The source indices do not specify a valid index " + \
"for the connection 'idvp.arrout' to 'arraycomp.inp1'. " + \
"Index '100000' is out of range for source dimension of size 5."
try:
self.prob.setup()
except ValueError as err:
self.assertEqual(str(err), expected)
else:
self.fail('Exception expected.')
self.prob.model._raise_connection_errors = False
with assert_warning(UserWarning, expected):
self.prob.setup()
def test_bad_value_bug(self):
# Should not be allowed because the 2nd index value within src_indices is outside
# the valid range for the source. A bug prevented this from being checked.
self.prob.model.connect('idvp.arrout', 'arraycomp.inp', src_indices=[0, 100000])
expected = "<model> <class Group>: The source indices do not specify a valid index " + \
"for the connection 'idvp.arrout' to 'arraycomp.inp'. " + \
"Index '100000' is out of range for source dimension of size 5."
try:
self.prob.setup()
except ValueError as err:
self.assertEqual(str(err), expected)
else:
self.fail('Exception expected.')
self.prob.model._raise_connection_errors = False
with assert_warning(UserWarning, expected):
self.prob.setup()
class TestShapes(unittest.TestCase):
def test_connect_flat_array_to_row_vector(self):
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', val=np.arange(10)))
p.model.add_subsystem('C1',
om.ExecComp('y=dot(x, A)',
x={'value': np.zeros((1, 10))},
A={'value': np.eye(10)},
y={'value': np.zeros((1, 10))}))
p.model.connect('indep.x', 'C1.x')
p.setup()
p.run_model()
assert_near_equal(p['C1.y'], np.arange(10)[np.newaxis, :])
def test_connect_flat_array_to_col_vector(self):
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', val=np.arange(10)))
p.model.add_subsystem('C1',
om.ExecComp('y=dot(A, x)',
x={'value': np.zeros((10, 1))},
A={'value': np.eye(10)},
y={'value': np.zeros((10, 1))}))
p.model.connect('indep.x', 'C1.x')
p.setup()
p.run_model()
assert_near_equal(p['C1.y'], np.arange(10)[:, np.newaxis])
def test_connect_row_vector_to_flat_array(self):
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', val=np.arange(10)[np.newaxis, :]))
p.model.add_subsystem('C1', om.ExecComp('y=5*x',
x={'value': np.zeros(10)},
y={'value': np.zeros(10)}))
p.model.connect('indep.x', 'C1.x')
p.setup()
p.run_model()
assert_near_equal(p['C1.y'], 5 * np.arange(10))
def test_connect_col_vector_to_flat_array(self):
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', val=np.arange(10)[:, np.newaxis]))
p.model.add_subsystem('C1', om.ExecComp('y=5*x',
x={'value': np.zeros(10)},
y={'value': np.zeros(10)}))
p.model.connect('indep.x', 'C1.x')
p.setup()
p.run_model()
assert_near_equal(p['C1.y'], 5 * np.arange(10))
def test_connect_flat_to_3d_array(self):
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', val=np.arange(10)))
p.model.add_subsystem('C1', om.ExecComp('y=5*x',
x={'value': np.zeros((1, 10, 1))},
y={'value': np.zeros((1, 10, 1))}))
p.model.connect('indep.x', 'C1.x')
p.setup()
p.run_model()
assert_near_equal(p['C1.y'], 5 * np.arange(10)[np.newaxis, :, np.newaxis])
def test_connect_flat_nd_to_flat_nd(self):
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x',
val=np.arange(10)[np.newaxis, :, np.newaxis,
np.newaxis]))
p.model.add_subsystem('C1', om.ExecComp('y=5*x',
x={'value': np.zeros((1, 1, 1, 10))},
y={'value': np.zeros((1, 1, 1, 10))}))
p.model.connect('indep.x', 'C1.x')
p.setup()
p.run_model()
assert_near_equal(p['C1.y'],
5 * np.arange(10)[np.newaxis, np.newaxis, np.newaxis, :])
def test_connect_incompatible_shapes(self):
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', val=np.arange(10)[np.newaxis, :,
np.newaxis, np.newaxis]))
p.model.add_subsystem('C1', om.ExecComp('y=5*x',
x={'value': np.zeros((5, 2))},
y={'value': np.zeros((5, 2))}))
p.model.connect('indep.x', 'C1.x')
expected = "<model> <class Group>: The source and target shapes do not match or are " + \
"ambiguous for the connection 'indep.x' to 'C1.x'. The source shape is " + \
"(1, 10, 1, 1) but the target shape is (5, 2)."
with self.assertRaises(Exception) as context:
p.setup()
self.assertEqual(str(context.exception), expected)
p.model._raise_connection_errors = False
with assert_warning(UserWarning, expected):
p.setup()
class TestMultiConns(unittest.TestCase):
def test_mult_conns(self):
class SubGroup(om.Group):
def setup(self):
self.add_subsystem('c1', om.ExecComp('y = 2*x', x=np.ones(4), y=2*np.ones(4)),
promotes=['y', 'x'])
self.add_subsystem('c2', om.ExecComp('z = 2*y', y=np.ones(4), z=2*np.ones(4)),
promotes=['z', 'y'])
prob = om.Problem()
indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*'])
indeps.add_output('x', 10*np.ones(4))
indeps.add_output('y', np.ones(4))
prob.model.add_subsystem('sub', SubGroup())
prob.model.connect('x', 'sub.x')
prob.model.connect('y', 'sub.y')
expected = "<model> <class Group>: The following inputs have multiple connections: " + \
"sub.c2.y from ['indeps.y', 'sub.c1.y']"
with self.assertRaises(Exception) as context:
prob.setup()
self.assertEqual(str(context.exception), expected)
prob.model._raise_connection_errors = False
with assert_warning(UserWarning, expected):
prob.setup()
def test_mixed_conns_same_level(self):
prob = om.Problem()
indeps = prob.model.add_subsystem('indeps', om.IndepVarComp())
indeps.add_output('x', 10*np.ones(4))
# c2.y is implicitly connected to c1.y
prob.model.add_subsystem('c1', om.ExecComp('y = 2*x', x=np.ones(4), y=2*np.ones(4)),
promotes=['y'])
prob.model.add_subsystem('c2', om.ExecComp('z = 2*y', y=np.ones(4), z=2*np.ones(4)),
promotes=['y'])
# make a second, explicit, connection to y (which is c2.y promoted)
prob.model.connect('indeps.x', 'y')
expected = "<model> <class Group>: Input 'c2.y' cannot be connected to 'indeps.x' " + \
"because it's already connected to 'c1.y'"
with self.assertRaises(Exception) as context:
prob.setup()
prob.final_setup()
self.assertEqual(str(context.exception), expected)
prob.model._raise_connection_errors = False
with assert_warning(UserWarning, expected):
prob.setup()
def test_auto_ivc_ambiguous_with_src_indices_msg(self):
class TComp(om.ExplicitComponent):
def initialize(self):
self.options.declare('src_idx', [0, 1])
def setup(self):
src = self.options['src_idx']
self.add_input('x', shape=2, src_indices=src, val=-2038.0)
self.add_output('y', shape=2)
self.declare_partials('y', 'x')
def compute(self, inputs, outputs):
outputs['y'] = 2.0 * inputs['x']
prob = om.Problem()
model = prob.model
prob.model.add_subsystem('c1', TComp(src_idx=[0, 1]), promotes_inputs=['x'])
prob.model.add_subsystem('c2', TComp(src_idx=[2, 3]), promotes_inputs=['x'])
prob.model.add_subsystem('d1', TComp(src_idx=[0, 1]), promotes_inputs=[('x', 'zz')])
prob.model.add_subsystem('d2', TComp(src_idx=[1, 2]), promotes_inputs=[('x', 'zz')])
with self.assertRaises(RuntimeError) as context:
prob.setup()
msg = "The following inputs ['c1.x', 'c2.x'] are defined using src_indices but the total source "
msg += "size is undetermined. You can specify the src size by setting 'val' or 'src_shape' in a call to set_input_defaults, or by adding an IndepVarComp as the source."
err_msg = str(context.exception).split(':')[-1]
self.assertEqual(err_msg, msg)
@unittest.skipUnless(MPI and PETScVector, "MPI and PETSc are required.")
class TestConnectionsDistrib(unittest.TestCase):
N_PROCS = 2
def test_serial_mpi_error(self):
# Should still catch the bad index when we are running under mpi with no distributed comps.
# A bug formerly prevented this.
class TestComp(om.ExplicitComponent):
def initialize(self):
self.options['distributed'] = False
def setup(self):
self.add_input('x', shape=2, src_indices=[1, 2], val=-2038.0)
self.add_output('y', shape=1)
self.declare_partials('y', 'x')
def compute(self, inputs, outputs):
outputs['y'] = np.sum(inputs['x'])
def compute_partials(self, inputs, J):
J['y', 'x'] = np.ones((2,))
prob = om.Problem()
model = prob.model
model.add_subsystem('p1', om.IndepVarComp('x', np.array([1.0, 3.0])))
model.add_subsystem('c3', TestComp())
model.connect("p1.x", "c3.x")
rank = prob.comm.rank
expected = f"Exception raised on rank {rank}: <model> <class Group>: The source indices do not specify a valid index " + \
"for the connection 'p1.x' to 'c3.x'. " + \
"Index '2' is out of range for source dimension of size 2."
try:
prob.setup()
except Exception as err:
self.assertEqual(str(err).splitlines()[-1], expected)
else:
self.fail('Exception expected.')
def test_serial_mpi_error_flat(self):
# Make sure the flat branch works too.
class TestComp(om.ExplicitComponent):
def initialize(self):
self.options['distributed'] = False
def setup(self):
self.add_input('x', shape=2, src_indices=[1, 2], val=-2038.0, flat_src_indices=True)
self.add_output('y', shape=1)
self.declare_partials('y', 'x')
def compute(self, inputs, outputs):
outputs['y'] = np.sum(inputs['x'])
def compute_partials(self, inputs, J):
J['y', 'x'] = np.ones((2,))
prob = om.Problem()
model = prob.model
model.add_subsystem('p1', om.IndepVarComp('x', np.array([1.0, 3.0])))
model.add_subsystem('c3', TestComp())
model.connect("p1.x", "c3.x")
rank = prob.comm.rank
expected = f"Exception raised on rank {rank}: <model> <class Group>: The source indices do not specify a valid index " + \
"for the connection 'p1.x' to 'c3.x'. " + \
"Index '2' is out of range for source dimension of size 2."
try:
prob.setup()
except Exception as err:
self.assertEqual(str(err).splitlines()[-1], expected)
else:
self.fail('Exception expected.')
@unittest.skipUnless(MPI, "MPI is required.")
class TestConnectionsError(unittest.TestCase):
N_PROCS = 2
def test_incompatible_src_indices(self):
class TestCompDist(om.ExplicitComponent):
# this comp is distributed and forces PETScTransfer
def initialize(self):
self.options['distributed'] = True
def setup(self):
self.add_input('x', shape=2)
self.add_output('y', shape=1)
self.declare_partials('y', 'x', val=1.0)
def compute(self, inputs, outputs):
outputs['y'] = np.sum(inputs['x'])
class TestComp(om.ExplicitComponent):
def initialize(self):
self.options['distributed'] = False
def setup(self):
# read SRC_INDICES on each proc
self.add_input('x', shape=2, src_indices=[1, 2], val=-2038.0)
self.add_output('y', shape=1)
self.declare_partials('y', 'x')
def compute(self, inputs, outputs):
outputs['y'] = np.sum(inputs['x'])
def compute_partials(self, inputs, J):
J['y', 'x'] = np.ones((2,))
prob = om.Problem()
model = prob.model
rank = prob.comm.rank
if rank == 0:
setval = np.array([2.0, 3.0])
else:
setval = np.array([10.0, 20.0])
# no parallel or distributed comps, so default_vector is used (local xfer only)
model.add_subsystem('p1', om.IndepVarComp('x', setval))
model.add_subsystem('c3', TestComp())
model.add_subsystem('c4', TestCompDist())
model.connect("p1.x", "c3.x")
model.connect("c3.y", "c4.x")
with self.assertRaises(ValueError) as context:
prob.setup(check=False, mode='fwd')
self.assertEqual(str(context.exception),
f"Exception raised on rank {rank}: <model> <class Group>: The source indices do not specify a valid index for "
"the connection 'p1.x' to 'c3.x'. Index '2' is out of range for source "
"dimension of size 2.")
@unittest.skipUnless(MPI, "MPI is required.")
class TestConnectionsMPIBug(unittest.TestCase):
N_PROCS = 2
def test_bug_2d_src_indices(self):
# This model gave an exception during setup.
class Burn(om.ExplicitComponent):
def setup(self):
self.add_input('x', np.arange(12))
self.add_output('y', np.arange(12))
def compute(self, inputs, outputs):
outputs['y'] = inputs['x'] * 2.0
class LinkageComp(om.ExplicitComponent):
def setup(self):
self.add_input('in1', np.zeros((3, 2)))
self.add_input('in2', np.zeros((3, 2)))
self.add_output('out', np.zeros((3, 2)))
def compute(self, inputs, outputs):
outputs['out'] = 3 * inputs['in2'] - 2.5 * inputs['in1']
class Phases(om.ParallelGroup):
def setup(self):
self.add_subsystem('burn1', Burn())
self.add_subsystem('burn2', Burn())
class Linkages(om.Group):
def setup(self):
self.add_subsystem('linkage', LinkageComp())
class Traj(om.Group):
def setup(self):
self.add_subsystem('phases', Phases())
self.add_subsystem('linkages', Linkages())
def configure(self):
self.connect('phases.burn1.y', 'linkages.linkage.in1', src_indices=np.array([[0, 3], [4, 6], [2, 1]]))
self.connect('phases.burn2.y', 'linkages.linkage.in2', src_indices=np.array([[0, 3], [4, 6], [2, 1]]))
prob = om.Problem(model=Traj())
prob.setup()
prob.run_model()
if __name__ == "__main__":
unittest.main()
| 37.081081 | 177 | 0.543477 |
import unittest
import numpy as np
from io import StringIO
import openmdao.api as om
from openmdao.utils.assert_utils import assert_near_equal, assert_warning
from openmdao.utils.mpi import MPI
try:
from openmdao.vectors.petsc_vector import PETScVector
except ImportError:
PETScVector = None
class TestConnections(unittest.TestCase):
def setUp(self):
self.setup_model(None, None)
def setup_model(self, c1meta=None, c3meta=None):
self.p = om.Problem()
root = self.p.model
if c1meta is None:
c1meta = {}
if c3meta is None:
c3meta = {}
self.G1 = root.add_subsystem("G1", om.Group())
self.G2 = self.G1.add_subsystem("G2", om.Group())
self.C1 = self.G2.add_subsystem("C1", om.ExecComp('y=x*2.0', **c1meta))
self.C2 = self.G2.add_subsystem("C2", om.IndepVarComp('x', 1.0))
self.G3 = root.add_subsystem("G3", om.Group())
self.G4 = self.G3.add_subsystem("G4", om.Group())
self.C3 = self.G4.add_subsystem("C3", om.ExecComp('y=x*2.0', **c3meta))
self.C4 = self.G4.add_subsystem("C4", om.ExecComp('y=x*2.0'))
def test_no_conns(self):
self.p.setup()
self.p['G1.G2.C1.x'] = 111.
self.p['G3.G4.C3.x'] = 222.
self.p['G3.G4.C4.x'] = 333.
self.p.run_model()
self.assertEqual(self.C1._inputs['x'], 111.)
self.assertEqual(self.C3._inputs['x'], 222.)
self.assertEqual(self.C4._inputs['x'], 333.)
def test_pull_size_from_source(self):
raise unittest.SkipTest("setting input size based on src size not supported yet")
class Src(ExplicitComponent):
def setup(self):
self.add_input('x', 2.0)
self.add_output('y1', np.zeros((3, )))
self.add_output('y2', shape=((3, )))
def solve_nonlinear(self, inputs, outputs, resids):
x = inputs['x']
outputs['y1'] = x * np.array([1.0, 2.0, 3.0])
outputs['y2'] = x * np.array([1.0, 2.0, 3.0])
class Tgt(ExplicitComponent):
def setup(self):
self.add_input('x1')
self.add_input('x2')
self.add_output('y1', 0.0)
self.add_output('y2', 0.0)
def solve_nonlinear(self, inputs, outputs, resids):
x1 = inputs['x1']
x2 = inputs['x2']
outputs['y1'] = np.sum(x1)
outputs['y2'] = np.sum(x2)
p = om.Problem()
p.model.add_subsystem('src', Src())
p.model.add_subsystem('tgt', Tgt())
p.model.connect('src.y1', 'tgt.x1')
p.model.connect('src.y2', 'tgt.x2')
p.setup()
p.run_model()
self.assertEqual(p['tgt.y1'], 12.0)
self.assertEqual(p['tgt.y2'], 12.0)
def test_pull_size_from_source_with_indices(self):
raise unittest.SkipTest("setting input size based on src size not supported yet")
class Src(ExplicitComponent):
def setup(self):
self.add_input('x', 2.0)
self.add_output('y1', np.zeros((3, )))
self.add_output('y2', shape=((3, )))
self.add_output('y3', 3.0)
def solve_nonlinear(self, inputs, outputs, resids):
x = inputs['x']
outputs['y1'] = x * np.array([1.0, 2.0, 3.0])
outputs['y2'] = x * np.array([1.0, 2.0, 3.0])
outputs['y3'] = x * 4.0
class Tgt(ExplicitComponent):
def setup(self):
self.add_input('x1')
self.add_input('x2')
self.add_input('x3')
self.add_output('y1', 0.0)
self.add_output('y2', 0.0)
self.add_output('y3', 0.0)
def solve_nonlinear(self, inputs, outputs, resids):
x1 = inputs['x1']
x2 = inputs['x2']
x3 = inputs['x3']
outputs['y1'] = np.sum(x1)
outputs['y2'] = np.sum(x2)
outputs['y3'] = np.sum(x3)
top = om.Problem()
top.model.add_subsystem('src', Src())
top.model.add_subsystem('tgt', Tgt())
top.model.connect('src.y1', 'tgt.x1', src_indices=(0, 1))
top.model.connect('src.y2', 'tgt.x2', src_indices=(0, 1))
top.model.connect('src.y3', 'tgt.x3')
top.setup()
top.run_model()
self.assertEqual(top['tgt.y1'], 6.0)
self.assertEqual(top['tgt.y2'], 6.0)
self.assertEqual(top['tgt.y3'], 8.0)
def test_inp_inp_conn_no_src(self):
raise unittest.SkipTest("no setup testing yet")
self.p.model.connect('G3.G4.C3.x', 'G3.G4.C4.x')
stream = StringIO()
self.p.setup(out_stream=stream)
self.p['G3.G4.C3.x'] = 999.
self.assertEqual(self.p.model.G3.G4.C3._inputs['x'], 999.)
self.assertEqual(self.p.model.G3.G4.C4._inputs['x'], 999.)
content = stream.getvalue()
self.assertTrue("The following parameters have no associated unknowns:\n"
"G1.G2.C1.x\nG3.G4.C3.x\nG3.G4.C4.x" in content)
self.assertTrue("The following components have no connections:\n"
"G1.G2.C1\nG1.G2.C2\nG3.G4.C3\nG3.G4.C4\n" in content)
self.assertTrue("No recorders have been specified, so no data will be saved." in content)
class TestConnectionsPromoted(unittest.TestCase):
def test_inp_inp_promoted_w_prom_src(self):
p = om.Problem()
root = p.model
G1 = root.add_subsystem("G1", om.Group(), promotes=['x'])
G2 = G1.add_subsystem("G2", om.Group(), promotes=['x'])
G2.add_subsystem("C1", om.ExecComp('y=x*2.0'))
G2.add_subsystem("C2", om.IndepVarComp('x', 1.0), promotes=['x'])
G3 = root.add_subsystem("G3", om.Group(), promotes=['x'])
G4 = G3.add_subsystem("G4", om.Group(), promotes=['x'])
C3 = G4.add_subsystem("C3", om.ExecComp('y=x*2.0'), promotes=['x'])
C4 = G4.add_subsystem("C4", om.ExecComp('y=x*2.0'), promotes=['x'])
p.setup()
p.set_solver_print(level=0)
p['x'] = 999.
p.run_model()
self.assertEqual(C3._inputs['x'], 999.)
self.assertEqual(C4._inputs['x'], 999.)
def test_inp_inp_promoted_w_explicit_src(self):
p = om.Problem()
root = p.model
G1 = root.add_subsystem("G1", om.Group())
G2 = G1.add_subsystem("G2", om.Group(), promotes=['x'])
G2.add_subsystem("C1", om.ExecComp('y=x*2.0'))
G2.add_subsystem("C2", om.IndepVarComp('x', 1.0), promotes=['x'])
G3 = root.add_subsystem("G3", om.Group())
G4 = G3.add_subsystem("G4", om.Group(), promotes=['x'])
C3 = G4.add_subsystem("C3", om.ExecComp('y=x*2.0'), promotes=['x'])
C4 = G4.add_subsystem("C4", om.ExecComp('y=x*2.0'), promotes=['x'])
p.model.connect('G1.x', 'G3.x')
p.setup()
p.set_solver_print(level=0)
p['G1.x'] = 999.
p.run_model()
self.assertEqual(C3._inputs['x'], 999.)
self.assertEqual(C4._inputs['x'], 999.)
def test_overlapping_system_names(self):
prob = om.Problem()
model = prob.model
g1 = model.add_subsystem('g1', om.Group())
g1a = model.add_subsystem('g1a', om.Group())
g1.add_subsystem('c', om.ExecComp('y=x'))
g1a.add_subsystem('c', om.ExecComp('y=x'))
model.connect('g1.c.y', 'g1a.c.x')
model.connect('g1a.c.y', 'g1.c.x')
prob.setup(check=True)
class TestConnectionsIndices(unittest.TestCase):
def setUp(self):
class ArrayComp(om.ExplicitComponent):
def setup(self):
self.add_input('inp', val=np.ones((2)))
self.add_input('inp1', val=0)
self.add_output('out', val=np.zeros((2)))
def compute(self, inputs, outputs):
outputs['out'] = inputs['inp'] * 2.
indep_var_comp = om.IndepVarComp()
indep_var_comp.add_output('blammo', val=3.)
indep_var_comp.add_output('arrout', val=np.ones(5))
prob = om.Problem()
prob.model.add_subsystem('idvp', indep_var_comp)
prob.model.add_subsystem('arraycomp', ArrayComp())
self.prob = prob
def test_bad_shapes(self):
self.prob.model.connect('idvp.blammo', 'arraycomp.inp')
expected = "<model> <class Group>: The source and target shapes do not match or are " + \
"ambiguous for the connection 'idvp.blammo' to 'arraycomp.inp'. " + \
"The source shape is (1,) but the target shape is (2,)."
try:
self.prob.setup()
except ValueError as err:
self.assertEqual(str(err), expected)
else:
self.fail('Exception expected.')
self.prob.model._raise_connection_errors = False
with assert_warning(UserWarning, expected):
self.prob.setup()
def test_bad_length(self):
self.prob.model.connect('idvp.blammo', 'arraycomp.inp', src_indices=[0, 1, 0])
expected = "<model> <class Group>: The source indices [0 1 0] do not specify a valid shape " + \
"for the connection 'idvp.blammo' to 'arraycomp.inp'. The target shape is " + \
"(2,) but indices are (3,)."
try:
self.prob.setup()
except ValueError as err:
self.assertEqual(str(err), expected)
else:
self.fail('Exception expected.')
self.prob.model._raise_connection_errors = False
with assert_warning(UserWarning, expected):
self.prob.setup()
def test_bad_value(self):
self.prob.model.connect('idvp.arrout', 'arraycomp.inp1', src_indices=[100000])
expected = "<model> <class Group>: The source indices do not specify a valid index " + \
"for the connection 'idvp.arrout' to 'arraycomp.inp1'. " + \
"Index '100000' is out of range for source dimension of size 5."
try:
self.prob.setup()
except ValueError as err:
self.assertEqual(str(err), expected)
else:
self.fail('Exception expected.')
self.prob.model._raise_connection_errors = False
with assert_warning(UserWarning, expected):
self.prob.setup()
def test_bad_value_bug(self):
self.prob.model.connect('idvp.arrout', 'arraycomp.inp', src_indices=[0, 100000])
expected = "<model> <class Group>: The source indices do not specify a valid index " + \
"for the connection 'idvp.arrout' to 'arraycomp.inp'. " + \
"Index '100000' is out of range for source dimension of size 5."
try:
self.prob.setup()
except ValueError as err:
self.assertEqual(str(err), expected)
else:
self.fail('Exception expected.')
self.prob.model._raise_connection_errors = False
with assert_warning(UserWarning, expected):
self.prob.setup()
class TestShapes(unittest.TestCase):
def test_connect_flat_array_to_row_vector(self):
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', val=np.arange(10)))
p.model.add_subsystem('C1',
om.ExecComp('y=dot(x, A)',
x={'value': np.zeros((1, 10))},
A={'value': np.eye(10)},
y={'value': np.zeros((1, 10))}))
p.model.connect('indep.x', 'C1.x')
p.setup()
p.run_model()
assert_near_equal(p['C1.y'], np.arange(10)[np.newaxis, :])
def test_connect_flat_array_to_col_vector(self):
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', val=np.arange(10)))
p.model.add_subsystem('C1',
om.ExecComp('y=dot(A, x)',
x={'value': np.zeros((10, 1))},
A={'value': np.eye(10)},
y={'value': np.zeros((10, 1))}))
p.model.connect('indep.x', 'C1.x')
p.setup()
p.run_model()
assert_near_equal(p['C1.y'], np.arange(10)[:, np.newaxis])
def test_connect_row_vector_to_flat_array(self):
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', val=np.arange(10)[np.newaxis, :]))
p.model.add_subsystem('C1', om.ExecComp('y=5*x',
x={'value': np.zeros(10)},
y={'value': np.zeros(10)}))
p.model.connect('indep.x', 'C1.x')
p.setup()
p.run_model()
assert_near_equal(p['C1.y'], 5 * np.arange(10))
def test_connect_col_vector_to_flat_array(self):
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', val=np.arange(10)[:, np.newaxis]))
p.model.add_subsystem('C1', om.ExecComp('y=5*x',
x={'value': np.zeros(10)},
y={'value': np.zeros(10)}))
p.model.connect('indep.x', 'C1.x')
p.setup()
p.run_model()
assert_near_equal(p['C1.y'], 5 * np.arange(10))
def test_connect_flat_to_3d_array(self):
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', val=np.arange(10)))
p.model.add_subsystem('C1', om.ExecComp('y=5*x',
x={'value': np.zeros((1, 10, 1))},
y={'value': np.zeros((1, 10, 1))}))
p.model.connect('indep.x', 'C1.x')
p.setup()
p.run_model()
assert_near_equal(p['C1.y'], 5 * np.arange(10)[np.newaxis, :, np.newaxis])
def test_connect_flat_nd_to_flat_nd(self):
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x',
val=np.arange(10)[np.newaxis, :, np.newaxis,
np.newaxis]))
p.model.add_subsystem('C1', om.ExecComp('y=5*x',
x={'value': np.zeros((1, 1, 1, 10))},
y={'value': np.zeros((1, 1, 1, 10))}))
p.model.connect('indep.x', 'C1.x')
p.setup()
p.run_model()
assert_near_equal(p['C1.y'],
5 * np.arange(10)[np.newaxis, np.newaxis, np.newaxis, :])
def test_connect_incompatible_shapes(self):
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', val=np.arange(10)[np.newaxis, :,
np.newaxis, np.newaxis]))
p.model.add_subsystem('C1', om.ExecComp('y=5*x',
x={'value': np.zeros((5, 2))},
y={'value': np.zeros((5, 2))}))
p.model.connect('indep.x', 'C1.x')
expected = "<model> <class Group>: The source and target shapes do not match or are " + \
"ambiguous for the connection 'indep.x' to 'C1.x'. The source shape is " + \
"(1, 10, 1, 1) but the target shape is (5, 2)."
with self.assertRaises(Exception) as context:
p.setup()
self.assertEqual(str(context.exception), expected)
p.model._raise_connection_errors = False
with assert_warning(UserWarning, expected):
p.setup()
class TestMultiConns(unittest.TestCase):
def test_mult_conns(self):
class SubGroup(om.Group):
def setup(self):
self.add_subsystem('c1', om.ExecComp('y = 2*x', x=np.ones(4), y=2*np.ones(4)),
promotes=['y', 'x'])
self.add_subsystem('c2', om.ExecComp('z = 2*y', y=np.ones(4), z=2*np.ones(4)),
promotes=['z', 'y'])
prob = om.Problem()
indeps = prob.model.add_subsystem('indeps', om.IndepVarComp(), promotes=['*'])
indeps.add_output('x', 10*np.ones(4))
indeps.add_output('y', np.ones(4))
prob.model.add_subsystem('sub', SubGroup())
prob.model.connect('x', 'sub.x')
prob.model.connect('y', 'sub.y')
expected = "<model> <class Group>: The following inputs have multiple connections: " + \
"sub.c2.y from ['indeps.y', 'sub.c1.y']"
with self.assertRaises(Exception) as context:
prob.setup()
self.assertEqual(str(context.exception), expected)
prob.model._raise_connection_errors = False
with assert_warning(UserWarning, expected):
prob.setup()
def test_mixed_conns_same_level(self):
prob = om.Problem()
indeps = prob.model.add_subsystem('indeps', om.IndepVarComp())
indeps.add_output('x', 10*np.ones(4))
prob.model.add_subsystem('c1', om.ExecComp('y = 2*x', x=np.ones(4), y=2*np.ones(4)),
promotes=['y'])
prob.model.add_subsystem('c2', om.ExecComp('z = 2*y', y=np.ones(4), z=2*np.ones(4)),
promotes=['y'])
prob.model.connect('indeps.x', 'y')
expected = "<model> <class Group>: Input 'c2.y' cannot be connected to 'indeps.x' " + \
"because it's already connected to 'c1.y'"
with self.assertRaises(Exception) as context:
prob.setup()
prob.final_setup()
self.assertEqual(str(context.exception), expected)
prob.model._raise_connection_errors = False
with assert_warning(UserWarning, expected):
prob.setup()
def test_auto_ivc_ambiguous_with_src_indices_msg(self):
class TComp(om.ExplicitComponent):
def initialize(self):
self.options.declare('src_idx', [0, 1])
def setup(self):
src = self.options['src_idx']
self.add_input('x', shape=2, src_indices=src, val=-2038.0)
self.add_output('y', shape=2)
self.declare_partials('y', 'x')
def compute(self, inputs, outputs):
outputs['y'] = 2.0 * inputs['x']
prob = om.Problem()
model = prob.model
prob.model.add_subsystem('c1', TComp(src_idx=[0, 1]), promotes_inputs=['x'])
prob.model.add_subsystem('c2', TComp(src_idx=[2, 3]), promotes_inputs=['x'])
prob.model.add_subsystem('d1', TComp(src_idx=[0, 1]), promotes_inputs=[('x', 'zz')])
prob.model.add_subsystem('d2', TComp(src_idx=[1, 2]), promotes_inputs=[('x', 'zz')])
with self.assertRaises(RuntimeError) as context:
prob.setup()
msg = "The following inputs ['c1.x', 'c2.x'] are defined using src_indices but the total source "
msg += "size is undetermined. You can specify the src size by setting 'val' or 'src_shape' in a call to set_input_defaults, or by adding an IndepVarComp as the source."
err_msg = str(context.exception).split(':')[-1]
self.assertEqual(err_msg, msg)
@unittest.skipUnless(MPI and PETScVector, "MPI and PETSc are required.")
class TestConnectionsDistrib(unittest.TestCase):
N_PROCS = 2
def test_serial_mpi_error(self):
# Should still catch the bad index when we are running under mpi with no distributed comps.
# A bug formerly prevented this.
class TestComp(om.ExplicitComponent):
def initialize(self):
self.options['distributed'] = False
def setup(self):
self.add_input('x', shape=2, src_indices=[1, 2], val=-2038.0)
self.add_output('y', shape=1)
self.declare_partials('y', 'x')
def compute(self, inputs, outputs):
outputs['y'] = np.sum(inputs['x'])
def compute_partials(self, inputs, J):
J['y', 'x'] = np.ones((2,))
prob = om.Problem()
model = prob.model
model.add_subsystem('p1', om.IndepVarComp('x', np.array([1.0, 3.0])))
model.add_subsystem('c3', TestComp())
model.connect("p1.x", "c3.x")
rank = prob.comm.rank
expected = f"Exception raised on rank {rank}: <model> <class Group>: The source indices do not specify a valid index " + \
"for the connection 'p1.x' to 'c3.x'. " + \
"Index '2' is out of range for source dimension of size 2."
try:
prob.setup()
except Exception as err:
self.assertEqual(str(err).splitlines()[-1], expected)
else:
self.fail('Exception expected.')
def test_serial_mpi_error_flat(self):
# Make sure the flat branch works too.
class TestComp(om.ExplicitComponent):
def initialize(self):
self.options['distributed'] = False
def setup(self):
self.add_input('x', shape=2, src_indices=[1, 2], val=-2038.0, flat_src_indices=True)
self.add_output('y', shape=1)
self.declare_partials('y', 'x')
def compute(self, inputs, outputs):
outputs['y'] = np.sum(inputs['x'])
def compute_partials(self, inputs, J):
J['y', 'x'] = np.ones((2,))
prob = om.Problem()
model = prob.model
model.add_subsystem('p1', om.IndepVarComp('x', np.array([1.0, 3.0])))
model.add_subsystem('c3', TestComp())
model.connect("p1.x", "c3.x")
rank = prob.comm.rank
expected = f"Exception raised on rank {rank}: <model> <class Group>: The source indices do not specify a valid index " + \
"for the connection 'p1.x' to 'c3.x'. " + \
"Index '2' is out of range for source dimension of size 2."
try:
prob.setup()
except Exception as err:
self.assertEqual(str(err).splitlines()[-1], expected)
else:
self.fail('Exception expected.')
@unittest.skipUnless(MPI, "MPI is required.")
class TestConnectionsError(unittest.TestCase):
N_PROCS = 2
def test_incompatible_src_indices(self):
class TestCompDist(om.ExplicitComponent):
# this comp is distributed and forces PETScTransfer
def initialize(self):
self.options['distributed'] = True
def setup(self):
self.add_input('x', shape=2)
self.add_output('y', shape=1)
self.declare_partials('y', 'x', val=1.0)
def compute(self, inputs, outputs):
outputs['y'] = np.sum(inputs['x'])
class TestComp(om.ExplicitComponent):
def initialize(self):
self.options['distributed'] = False
def setup(self):
# read SRC_INDICES on each proc
self.add_input('x', shape=2, src_indices=[1, 2], val=-2038.0)
self.add_output('y', shape=1)
self.declare_partials('y', 'x')
def compute(self, inputs, outputs):
outputs['y'] = np.sum(inputs['x'])
def compute_partials(self, inputs, J):
J['y', 'x'] = np.ones((2,))
prob = om.Problem()
model = prob.model
rank = prob.comm.rank
if rank == 0:
setval = np.array([2.0, 3.0])
else:
setval = np.array([10.0, 20.0])
# no parallel or distributed comps, so default_vector is used (local xfer only)
model.add_subsystem('p1', om.IndepVarComp('x', setval))
model.add_subsystem('c3', TestComp())
model.add_subsystem('c4', TestCompDist())
model.connect("p1.x", "c3.x")
model.connect("c3.y", "c4.x")
with self.assertRaises(ValueError) as context:
prob.setup(check=False, mode='fwd')
self.assertEqual(str(context.exception),
f"Exception raised on rank {rank}: <model> <class Group>: The source indices do not specify a valid index for "
"the connection 'p1.x' to 'c3.x'. Index '2' is out of range for source "
"dimension of size 2.")
@unittest.skipUnless(MPI, "MPI is required.")
class TestConnectionsMPIBug(unittest.TestCase):
N_PROCS = 2
def test_bug_2d_src_indices(self):
# This model gave an exception during setup.
class Burn(om.ExplicitComponent):
def setup(self):
self.add_input('x', np.arange(12))
self.add_output('y', np.arange(12))
def compute(self, inputs, outputs):
outputs['y'] = inputs['x'] * 2.0
class LinkageComp(om.ExplicitComponent):
def setup(self):
self.add_input('in1', np.zeros((3, 2)))
self.add_input('in2', np.zeros((3, 2)))
self.add_output('out', np.zeros((3, 2)))
def compute(self, inputs, outputs):
outputs['out'] = 3 * inputs['in2'] - 2.5 * inputs['in1']
class Phases(om.ParallelGroup):
def setup(self):
self.add_subsystem('burn1', Burn())
self.add_subsystem('burn2', Burn())
class Linkages(om.Group):
def setup(self):
self.add_subsystem('linkage', LinkageComp())
class Traj(om.Group):
def setup(self):
self.add_subsystem('phases', Phases())
self.add_subsystem('linkages', Linkages())
def configure(self):
self.connect('phases.burn1.y', 'linkages.linkage.in1', src_indices=np.array([[0, 3], [4, 6], [2, 1]]))
self.connect('phases.burn2.y', 'linkages.linkage.in2', src_indices=np.array([[0, 3], [4, 6], [2, 1]]))
prob = om.Problem(model=Traj())
prob.setup()
prob.run_model()
if __name__ == "__main__":
unittest.main()
| true | true |
f7282e604acd8671472608a64329d71637642de8 | 4,853 | py | Python | goldminer/world.py | adael/goldminer | 47571c71c7f815eccb455a7d9e11d0e3892e9a5d | [
"MIT"
] | 2 | 2016-11-08T14:32:40.000Z | 2018-06-12T11:44:24.000Z | goldminer/world.py | adael/goldminer | 47571c71c7f815eccb455a7d9e11d0e3892e9a5d | [
"MIT"
] | null | null | null | goldminer/world.py | adael/goldminer | 47571c71c7f815eccb455a7d9e11d0e3892e9a5d | [
"MIT"
] | null | null | null | import random
from goldminer import settings, pgc, game, geom, texts, audio
from goldminer.camera import Camera
from goldminer.actor import Actor
from goldminer.worldmap import WorldMap
class World:
def __init__(self, world_map: WorldMap, player: Actor, seed):
self.world_map = world_map
self.actors = []
self.player = player
self.player.world = self
self.seed = seed
self.camera = Camera(
width=settings.map_rect.w,
height=settings.map_rect.h,
map_width=self.world_map.width,
map_height=self.world_map.height,
offset_x=settings.map_rect.x,
offset_y=settings.map_rect.y
)
self.camera.update(self.player.x, self.player.y)
self.stored_player_position = None
def inside_map(self, x, y):
return self.world_map.inside_map(x, y)
def tile(self, x, y):
return self.world_map.tile(x, y)
def set_tile(self, x, y, tile):
self.world_map.set_tile(x, y, tile)
def add(self, actor):
actor.set_world(self)
self.actors.append(actor)
return actor
def is_walkable(self, x, y):
return self.world_map.is_walkable(x, y)
def actor_move(self, actor, x, y):
(dx, dy) = actor.x + x, actor.y + y
if self.is_walkable(dx, dy):
actor.move(x, y)
def player_move(self, x, y):
if self.player.resting:
return
(dx, dy) = self.player.x + x, self.player.y + y
self.player.orientation = (x, y)
if self.is_walkable(dx, dy):
self.player.move(x, y)
# Currently fov is computed in each logic update
# self.compute_fov()
return
tile = self.tile(dx, dy)
if tile.door:
if tile.door.opened:
if tile.door.leave:
self.leave_room()
else:
self.enter_room(dx, dy)
else:
self.player.see("{0} ({1})".format("a door", "closed" if tile.door.closed else "opened"))
elif tile.resource:
self.player.see("{0} ({1})".format(tile.resource.item.description, tile.resource.quantity))
def player_primary_action(self):
(x, y) = self.player.looking_position()
tile = self.tile(x, y)
if tile.resource:
self.player_gather_resource(tile)
elif tile.door:
self.player_handle_door(tile, x, y)
def player_handle_door(self, tile, dx, dy):
if tile.door.closed:
tile.door.open()
else:
tile.door.close()
def player_gather_resource(self, tile):
if self.player.inventory.is_full():
self.player.think(texts.inventory_is_full)
return
audio.pick_axe.play()
tile.resource.health -= 1
self.player.waste(tile.resource.hardness)
if tile.resource.health <= 0:
if tile.resource.item:
self.player.inventory.add(tile.resource.item)
if tile.resource.quantity > 0:
tile.resource.quantity -= 1
tile.resource.restore_health()
if tile.resource.depleted:
self.player.think("This resource is depleted")
tile.resource = None
def actor_heal(self, actor, amount):
actor.heal(amount)
def actor_say(self, actor, messages):
if actor is self.player or actor.distance_to(self.player) < 10:
self.player.listen(actor.name + " says: " + random.choice(messages))
def logic(self):
if self.player.resting:
self.player.think("Zzz ...")
self.player.restore()
self.camera.update(self.player.x, self.player.y)
def enter_room(self, x, y):
self.stored_player_position = self.player.position
(dox, doy) = geom.orientation(self.player.x, self.player.y, x, y)
print("Door orientation:", (dox, doy))
hseed = "room_{}x{}_{}".format(x, y, self.seed)
(house, door_x, door_y) = pgc.create_house(hseed, dox, doy)
self.player.set_position(door_x - dox, door_y - doy)
new_world = World(house, self.player, hseed)
game.get_game_state().enter_world(new_world)
def leave_room(self):
game.get_game_state().leave_world()
def restore_player_position(self):
self.player.position = self.stored_player_position
def compute_fov(self):
positions = geom.positions_in_radius(self.player.x, self.player.y, 6)
for (x, y) in positions:
if self.world_map.inside_map(x, y):
tile = self.tile(x, y)
dist = self.player.distance(x, y)
tile.in_sight = dist < 4
def place_item(self, x, y, item):
self.tile(x, y).place_item(item)
| 31.108974 | 105 | 0.585823 | import random
from goldminer import settings, pgc, game, geom, texts, audio
from goldminer.camera import Camera
from goldminer.actor import Actor
from goldminer.worldmap import WorldMap
class World:
def __init__(self, world_map: WorldMap, player: Actor, seed):
self.world_map = world_map
self.actors = []
self.player = player
self.player.world = self
self.seed = seed
self.camera = Camera(
width=settings.map_rect.w,
height=settings.map_rect.h,
map_width=self.world_map.width,
map_height=self.world_map.height,
offset_x=settings.map_rect.x,
offset_y=settings.map_rect.y
)
self.camera.update(self.player.x, self.player.y)
self.stored_player_position = None
def inside_map(self, x, y):
return self.world_map.inside_map(x, y)
def tile(self, x, y):
return self.world_map.tile(x, y)
def set_tile(self, x, y, tile):
self.world_map.set_tile(x, y, tile)
def add(self, actor):
actor.set_world(self)
self.actors.append(actor)
return actor
def is_walkable(self, x, y):
return self.world_map.is_walkable(x, y)
def actor_move(self, actor, x, y):
(dx, dy) = actor.x + x, actor.y + y
if self.is_walkable(dx, dy):
actor.move(x, y)
def player_move(self, x, y):
if self.player.resting:
return
(dx, dy) = self.player.x + x, self.player.y + y
self.player.orientation = (x, y)
if self.is_walkable(dx, dy):
self.player.move(x, y)
return
tile = self.tile(dx, dy)
if tile.door:
if tile.door.opened:
if tile.door.leave:
self.leave_room()
else:
self.enter_room(dx, dy)
else:
self.player.see("{0} ({1})".format("a door", "closed" if tile.door.closed else "opened"))
elif tile.resource:
self.player.see("{0} ({1})".format(tile.resource.item.description, tile.resource.quantity))
def player_primary_action(self):
(x, y) = self.player.looking_position()
tile = self.tile(x, y)
if tile.resource:
self.player_gather_resource(tile)
elif tile.door:
self.player_handle_door(tile, x, y)
def player_handle_door(self, tile, dx, dy):
if tile.door.closed:
tile.door.open()
else:
tile.door.close()
def player_gather_resource(self, tile):
if self.player.inventory.is_full():
self.player.think(texts.inventory_is_full)
return
audio.pick_axe.play()
tile.resource.health -= 1
self.player.waste(tile.resource.hardness)
if tile.resource.health <= 0:
if tile.resource.item:
self.player.inventory.add(tile.resource.item)
if tile.resource.quantity > 0:
tile.resource.quantity -= 1
tile.resource.restore_health()
if tile.resource.depleted:
self.player.think("This resource is depleted")
tile.resource = None
def actor_heal(self, actor, amount):
actor.heal(amount)
def actor_say(self, actor, messages):
if actor is self.player or actor.distance_to(self.player) < 10:
self.player.listen(actor.name + " says: " + random.choice(messages))
def logic(self):
if self.player.resting:
self.player.think("Zzz ...")
self.player.restore()
self.camera.update(self.player.x, self.player.y)
def enter_room(self, x, y):
self.stored_player_position = self.player.position
(dox, doy) = geom.orientation(self.player.x, self.player.y, x, y)
print("Door orientation:", (dox, doy))
hseed = "room_{}x{}_{}".format(x, y, self.seed)
(house, door_x, door_y) = pgc.create_house(hseed, dox, doy)
self.player.set_position(door_x - dox, door_y - doy)
new_world = World(house, self.player, hseed)
game.get_game_state().enter_world(new_world)
def leave_room(self):
game.get_game_state().leave_world()
def restore_player_position(self):
self.player.position = self.stored_player_position
def compute_fov(self):
positions = geom.positions_in_radius(self.player.x, self.player.y, 6)
for (x, y) in positions:
if self.world_map.inside_map(x, y):
tile = self.tile(x, y)
dist = self.player.distance(x, y)
tile.in_sight = dist < 4
def place_item(self, x, y, item):
self.tile(x, y).place_item(item)
| true | true |
f7282f631d271d7217711cbe9225772cf3c3323a | 2,540 | py | Python | setup.py | brianmwaters/vt-police-tools | 2619cec4fbf1a9fba4fbbfab7d5c14b83b6e6be0 | [
"CC0-1.0"
] | 1 | 2020-06-22T20:05:34.000Z | 2020-06-22T20:05:34.000Z | setup.py | brianmwaters/vt-police-tools | 2619cec4fbf1a9fba4fbbfab7d5c14b83b6e6be0 | [
"CC0-1.0"
] | null | null | null | setup.py | brianmwaters/vt-police-tools | 2619cec4fbf1a9fba4fbbfab7d5c14b83b6e6be0 | [
"CC0-1.0"
] | null | null | null | """Setup script."""
import glob
import importlib
import os
import setuptools
import vt_police_tools
def components(path):
"""Split a POSIX path into components."""
head, tail = os.path.split(os.path.normpath(path))
if head == "":
return [tail]
elif head == "/":
return [head + tail]
else:
return components(head) + [tail]
def strip_leading_component(path):
"""Remove the leading component from a POSIX path."""
return os.path.join(*components(path)[1:])
def _package_data_glob(glob_):
return [strip_leading_component(path) for path in
glob.iglob(glob_, recursive=True)]
def _package_data_globs(*globs):
paths = []
for glob_ in globs:
paths += _package_data_glob(glob_)
return paths
def _read_readme(readme):
with open(readme, "r") as file_:
return file_.read()
setuptools.setup(
name="vt-police-tools",
version=vt_police_tools.__version__,
description="Tools for cleaning Vermont police data",
long_description=_read_readme("README.rst"),
long_description_content_type="text/x-rst",
keywords="police vermont",
author="BTV CopWatch",
author_email="info@btvcopwatch.org",
url="https://github.com/brianmwaters/vt-police-tools/",
project_urls={
"BTV CopWatch": "https://www.btvcopwatch.org/",
"OpenOversight": "https://www.openoversight.com/",
},
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Intended Audience :: Other Audience",
"License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication",
"Natural Language :: English",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: Implementation :: CPython",
"Topic :: Other/Nonlisted Topic",
],
python_requires="~=3.7",
install_requires=[
"pandas~=1.1.0",
],
packages=setuptools.find_packages(),
entry_points={
"console_scripts": [
"vpt=vt_police_tools.cli:main",
],
},
package_data={
"vt_police_tools": _package_data_globs(
"vt_police_tools/data/**",
"vt_police_tools/migrations/**",
),
},
exclude_package_data={
"vt_police_tools": [
"data/*/*/imported/*.csv",
"migrations/*.log",
],
},
)
| 27.021277 | 74 | 0.612992 |
import glob
import importlib
import os
import setuptools
import vt_police_tools
def components(path):
head, tail = os.path.split(os.path.normpath(path))
if head == "":
return [tail]
elif head == "/":
return [head + tail]
else:
return components(head) + [tail]
def strip_leading_component(path):
return os.path.join(*components(path)[1:])
def _package_data_glob(glob_):
return [strip_leading_component(path) for path in
glob.iglob(glob_, recursive=True)]
def _package_data_globs(*globs):
paths = []
for glob_ in globs:
paths += _package_data_glob(glob_)
return paths
def _read_readme(readme):
with open(readme, "r") as file_:
return file_.read()
setuptools.setup(
name="vt-police-tools",
version=vt_police_tools.__version__,
description="Tools for cleaning Vermont police data",
long_description=_read_readme("README.rst"),
long_description_content_type="text/x-rst",
keywords="police vermont",
author="BTV CopWatch",
author_email="info@btvcopwatch.org",
url="https://github.com/brianmwaters/vt-police-tools/",
project_urls={
"BTV CopWatch": "https://www.btvcopwatch.org/",
"OpenOversight": "https://www.openoversight.com/",
},
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Intended Audience :: Other Audience",
"License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication",
"Natural Language :: English",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: Implementation :: CPython",
"Topic :: Other/Nonlisted Topic",
],
python_requires="~=3.7",
install_requires=[
"pandas~=1.1.0",
],
packages=setuptools.find_packages(),
entry_points={
"console_scripts": [
"vpt=vt_police_tools.cli:main",
],
},
package_data={
"vt_police_tools": _package_data_globs(
"vt_police_tools/data/**",
"vt_police_tools/migrations/**",
),
},
exclude_package_data={
"vt_police_tools": [
"data/*/*/imported/*.csv",
"migrations/*.log",
],
},
)
| true | true |
f7282f8fe7c42b66565b59e947ca13c634d5ca89 | 12,583 | py | Python | extractViewAngle.py | sgascoin/extractViewAngle | 2ec54426714eac9628fa73b622519c88b8ab96b2 | [
"Apache-2.0"
] | null | null | null | extractViewAngle.py | sgascoin/extractViewAngle | 2ec54426714eac9628fa73b622519c88b8ab96b2 | [
"Apache-2.0"
] | 1 | 2020-05-08T22:51:08.000Z | 2020-05-08T22:51:08.000Z | extractViewAngle.py | sgascoin/extractViewAngle | 2ec54426714eac9628fa73b622519c88b8ab96b2 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/python
"""
extractViewAngle.py
Scope: export points or raster of viewing incidences angles from a Theia L2A product (rasters are scaled by 100 as UInt16)
Author: simon.gascoin@cesbio.cnes.fr
"""
import csv
import gdal
import numpy as np
import ogr
import os
import osr
import sys
import xml.etree.ElementTree as ET
# function to read points file as lon lat values delimited by tab without header line
def readPoints(f):
with open(f,'r') as csvfile:
reader = csv.reader(csvfile,delimiter=',')
data = [r for r in reader]
return data
# function to write points values as csv
def writePoints(newPointsFn,outDictList):
with open(newPointsFn, 'w') as csvfile:
fieldnames = list(outDictList[0].keys())
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for ouDict in outDictList:
writer.writerow(ouDict)
# function to write an array to a (multiband) geotiff
def array2geotiff(newRasterFn,geoTransform,array,noData,outSpatialRef,dataType=gdal.GDT_Float64):
cols = array.shape[1]
rows = array.shape[0]
bands = array.shape[2]
driver = gdal.GetDriverByName('GTiff')
outRaster = driver.Create(newRasterFn, cols, rows, bands, dataType, options=['COMPRESS=DEFLATE'])
outRaster.SetGeoTransform(geoTransform)
# write bands
for i in range(bands):
outband = outRaster.GetRasterBand(i+1) # 1-based index
outband.WriteArray(array[:,:,i])
outband.SetNoDataValue(noData)
outRaster.SetProjection(outSpatialRef.ExportToWkt())
outRaster.FlushCache()
# function to get mask file name and bit number to test which detector was used
def getDetector(productFolder,root,bandId,detectorId):
# find node containing detector metadata based on the presence of attribute "detector_id" in subnodes
n = root.find(".//Product_Organisation//*[@detector_id]/..")
if n is None:
print('this product version does not provide detector mask')
maskFn = bitNumber = None
else:
# get MASK_FILE element for target band and detector
s = "./MASK_FILE/[@band_id='{}'][@detector_id='{}']".format(bandId,detectorId)
element = n.find(s)
# get detector mask file from element value
maskFn = os.path.join(productFolder,element.text)
# get detector bit number from element attribute
bitNumber = int(element.attrib['bit_number'])
return maskFn, bitNumber
# function to test if detector was used at this point
def testDetector(point,maskFn,bitNumber):
# open the raster file
ds = gdal.Open(maskFn,gdal.GA_ReadOnly)
if ds is None:
print('Could not open the mask file')
sys.exit(1)
band = ds.GetRasterBand(1) # 1-based index
data = band.ReadAsArray() # we could save memory and time by reading only the pixel using ReadRaster?
geoTransform = ds.GetGeoTransform()
# get position in array
col,row = pix2map(point.GetX(),point.GetY(),geoTransform)
# check if point is outside the mask
if (col < 0 or row < 0 or col > band.XSize or row > band.YSize):
print('Point is outside the product mask extent')
test = False
else:
value = data[int(col)][int(row)]
test = testBit(value, bitNumber)
return test
# function which returns True if the bit number n is 1 in an integer value of base 10.
def testBit(value, n):
mask = 1 << (n - 1) # bitNumber is 1-based index
return(value & mask > 0)
# find position of x,y coordinates in georeferenced array with the same projection system
def pix2map(x,y,geoTransform):
col = np.floor((x - geoTransform[0]) / geoTransform[1]) #x pixel
row = np.floor((y - geoTransform[3]) / geoTransform[5]) #y pixel
return col,row
# main function
def main(productFolder,outputFolder,points=None):
# scale factor to export angles
scale = 100
# set no data value for UInt16 export
noDataRaster = np.iinfo(np.uint16).max
# set no data value for csv export
noDataCsv = -10000
# MTD angle grid always have a 5 km resolution
colstep = 5000
rowstep = -5000
# MTD angle grid always have an size of 23x23
nx = ny = 23
# open metadata file
MTDFile = os.path.join(productFolder,os.path.basename(os.path.abspath(productFolder)+'_MTD_ALL.xml'))
tree = ET.parse(MTDFile)
root = tree.getroot()
# get product id
productId = root.find(".//PRODUCT_ID").text
# get EPSG code
epsg = root.find(".//HORIZONTAL_CS_CODE").text
# get grid corners coordinates (warning in array geometry the lower left corner is the upper left in raster geometry)
ulx = float(root.find(".//*[@name='upperLeft']/X").text)
uly = float(root.find(".//*[@name='upperLeft']/Y").text)
lrx = float(root.find(".//*[@name='lowerRight']/X").text)
lry = float(root.find(".//*[@name='lowerRight']/Y").text)
# We assume that the above coordinates correspond to the *centers* of corner pixels
# otherwise the 23x23 grid would have an extra row and column somewhere
ulxMTD = ulx - colstep/2
ulyMTD = uly - rowstep/2
# define the affine transformation coefficients
geoTransform = (ulxMTD, colstep, 0, ulyMTD, 0, rowstep)
# create output spatial reference
outSpatialRef = osr.SpatialReference()
outSpatialRef.ImportFromEPSG(int(epsg))
if points is not None:
# create coordinate transformation
inSpatialRef = osr.SpatialReference()
inSpatialRef.ImportFromEPSG(4326)
# keep the traditionnal GIS order even if GDAL > 3
try:
inSpatialRef.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
except:
pass
coordTransform = osr.CoordinateTransformation(inSpatialRef, outSpatialRef)
# loop through angle definition
for angle in ('Azimuth','Zenith'):
# initialize output list of dictionnaries for points
if points is not None:
outDictList = list()
[outDictList.append(dict()) for i in points]
# loop through bands
for band in root.iter('Band_Viewing_Incidence_Angles_Grids_List'):
# init stack of grids
Zd = np.array([], dtype=float).reshape(nx,ny,0)
# loop through detectors
for detector in band.iter('Viewing_Incidence_Angles_Grids'):
rows = detector.find(angle).findall('.//VALUES')
grid = ''
# loop through grid rows to read grid values as a string
for row in iter(rows):
grid = grid + row.text + '\n'
# array with grid values
Z = np.fromstring(grid, dtype=float, sep=' ')
# reshape to 2D array
Z = Z.reshape((len(rows),-1))
# add to the stack of detector grids
Zd = np.dstack((Zd,Z))
# display mean value for this angle and band
bandId = band.attrib.get('band_id')
print('{:s} {:s} mean value: {:g}'.format(bandId,angle,np.nanmean(Zd)))
# export as multiband geotiff (we don't flatten the stack since the detector arrays overlap)
if points is None:
newRasterFn = os.path.join(\
outputFolder,'{:s}_{:s}_{:s}{:d}.tif'.format(productId,bandId,angle,scale))
# scale
Zd = scale * Zd
# set no data
Zd[np.isnan(Zd)] = noDataRaster
# write to disk
array2geotiff(newRasterFn,geoTransform,Zd,noDataRaster,outSpatialRef,gdal.GDT_UInt16)
# find values at points
else:
for ipoint,pointCoord in enumerate(points):
lon,lat = float(pointCoord[0]),float(pointCoord[1])
# create a geometry from coordinates
point = ogr.Geometry(ogr.wkbPoint)
point.AddPoint(lon, lat) # traditionnal GIS order
# transform point
point.Transform(coordTransform)
# find position in array
col,row = pix2map(point.GetX(),point.GetY(),geoTransform)
# check if point is out of the grid
if (col < 0 or row < 0 or col > nx or row > ny):
v = noDataCsv
# otherwise retrieve the values in all bands
else:
vd = Zd[int(row),int(col),:]
# select the non-NaN value(s)
v = vd[np.isfinite(vd)]
# check if point is in no data area
if len(v) == 0:
v = noDataCsv
# check if more than one value is found in the stack
# this can occur because angle grids overlap due to their coarse resolution
elif len(v) > 1:
print('solving an ambiguity for band = ' + bandId + ' at point ' + str(pointCoord))
detectorList = [d.attrib for d in band.iter('Viewing_Incidence_Angles_Grids')]
# indices where are the finite values
indexList = np.argwhere(np.isfinite(vd))
# look into the detector mask files to find which detector has measured this point
test = False
for ix in indexList :
detectorId = detectorList[int(ix)]['detector_id']
print('testing detector = ' + detectorId)
maskFn,bitNumber = getDetector(productFolder,root,bandId,detectorId)
# if the detector mask file is provided then we assign the first value
if maskFn is None :
print('takes first detector value by default')
test = True
test = testDetector(point,maskFn,bitNumber)
if test:
print('found it!')
v = vd[ix]
break
# if test always false (point outside the mask) returns no data
if test is False:
v = noDataCsv
outDictList[ipoint]['lon'] = lon
outDictList[ipoint]['lat'] = lat
# add this value to the output dictionnary
if bandId in outDictList[ipoint]:
outDictList[ipoint][bandId].append(float(v))
else:
outDictList[ipoint][bandId] = float(v)
# dump data to text file for this angle and band
if points is not None:
newPointsFn = os.path.join(\
outputFolder,'{:s}_{:s}.csv'.format(productId,angle))
writePoints(newPointsFn,outDictList)
if __name__ == "__main__":
# check arguments
if len(sys.argv) == 4:
print("Point mode")
pointFile = sys.argv[3]
# check if input file exists
if not(os.path.exists(pointFile)):
print("Error: input point file does not exists")
sys.exit(1)
points = readPoints(pointFile)
elif len(sys.argv) == 3:
print("Raster mode")
points = None
else:
print("Error: missing arguments\n")
print("usage in raster mode: extractViewAngle.py productFolder outputFolder\n")
print("usage in point mode: extractViewAngle.py productFolder outputFolder point_table_as_lon_lat.csv\n")
print("example: python extractViewAngle.py SENTINEL2A_20180224-103018-463_L2A_T31TGK_C_V2-2 angles\n")
print("example: python extractViewAngle.py SENTINEL2A_20180224-103018-463_L2A_T31TGK_C_V2-2 angles points.csv\n")
sys.exit(1)
# check if input file exists
productFolder = sys.argv[1]
if not(os.path.exists(productFolder)):
print ("Error: input folder does not exists")
sys.exit(1)
# check if folder can be created
outputFolder = sys.argv[2]
try:
os.makedirs(outputFolder,exist_ok=True)
except OSError:
print ("Error: cannot create output folder")
sys.exit(1)
else:
main(productFolder,outputFolder,points)
| 41.120915 | 123 | 0.590718 |
import csv
import gdal
import numpy as np
import ogr
import os
import osr
import sys
import xml.etree.ElementTree as ET
def readPoints(f):
with open(f,'r') as csvfile:
reader = csv.reader(csvfile,delimiter=',')
data = [r for r in reader]
return data
def writePoints(newPointsFn,outDictList):
with open(newPointsFn, 'w') as csvfile:
fieldnames = list(outDictList[0].keys())
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for ouDict in outDictList:
writer.writerow(ouDict)
def array2geotiff(newRasterFn,geoTransform,array,noData,outSpatialRef,dataType=gdal.GDT_Float64):
cols = array.shape[1]
rows = array.shape[0]
bands = array.shape[2]
driver = gdal.GetDriverByName('GTiff')
outRaster = driver.Create(newRasterFn, cols, rows, bands, dataType, options=['COMPRESS=DEFLATE'])
outRaster.SetGeoTransform(geoTransform)
for i in range(bands):
outband = outRaster.GetRasterBand(i+1)
outband.WriteArray(array[:,:,i])
outband.SetNoDataValue(noData)
outRaster.SetProjection(outSpatialRef.ExportToWkt())
outRaster.FlushCache()
def getDetector(productFolder,root,bandId,detectorId):
n = root.find(".//Product_Organisation//*[@detector_id]/..")
if n is None:
print('this product version does not provide detector mask')
maskFn = bitNumber = None
else:
s = "./MASK_FILE/[@band_id='{}'][@detector_id='{}']".format(bandId,detectorId)
element = n.find(s)
maskFn = os.path.join(productFolder,element.text)
bitNumber = int(element.attrib['bit_number'])
return maskFn, bitNumber
def testDetector(point,maskFn,bitNumber):
ds = gdal.Open(maskFn,gdal.GA_ReadOnly)
if ds is None:
print('Could not open the mask file')
sys.exit(1)
band = ds.GetRasterBand(1)
data = band.ReadAsArray()
geoTransform = ds.GetGeoTransform()
col,row = pix2map(point.GetX(),point.GetY(),geoTransform)
if (col < 0 or row < 0 or col > band.XSize or row > band.YSize):
print('Point is outside the product mask extent')
test = False
else:
value = data[int(col)][int(row)]
test = testBit(value, bitNumber)
return test
def testBit(value, n):
mask = 1 << (n - 1)
return(value & mask > 0)
def pix2map(x,y,geoTransform):
col = np.floor((x - geoTransform[0]) / geoTransform[1])
row = np.floor((y - geoTransform[3]) / geoTransform[5])
return col,row
def main(productFolder,outputFolder,points=None):
scale = 100
noDataRaster = np.iinfo(np.uint16).max
noDataCsv = -10000
colstep = 5000
rowstep = -5000
nx = ny = 23
MTDFile = os.path.join(productFolder,os.path.basename(os.path.abspath(productFolder)+'_MTD_ALL.xml'))
tree = ET.parse(MTDFile)
root = tree.getroot()
productId = root.find(".//PRODUCT_ID").text
epsg = root.find(".//HORIZONTAL_CS_CODE").text
ulx = float(root.find(".//*[@name='upperLeft']/X").text)
uly = float(root.find(".//*[@name='upperLeft']/Y").text)
lrx = float(root.find(".//*[@name='lowerRight']/X").text)
lry = float(root.find(".//*[@name='lowerRight']/Y").text)
ulxMTD = ulx - colstep/2
ulyMTD = uly - rowstep/2
geoTransform = (ulxMTD, colstep, 0, ulyMTD, 0, rowstep)
outSpatialRef = osr.SpatialReference()
outSpatialRef.ImportFromEPSG(int(epsg))
if points is not None:
inSpatialRef = osr.SpatialReference()
inSpatialRef.ImportFromEPSG(4326)
try:
inSpatialRef.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
except:
pass
coordTransform = osr.CoordinateTransformation(inSpatialRef, outSpatialRef)
for angle in ('Azimuth','Zenith'):
if points is not None:
outDictList = list()
[outDictList.append(dict()) for i in points]
for band in root.iter('Band_Viewing_Incidence_Angles_Grids_List'):
Zd = np.array([], dtype=float).reshape(nx,ny,0)
for detector in band.iter('Viewing_Incidence_Angles_Grids'):
rows = detector.find(angle).findall('.//VALUES')
grid = ''
for row in iter(rows):
grid = grid + row.text + '\n'
Z = np.fromstring(grid, dtype=float, sep=' ')
Z = Z.reshape((len(rows),-1))
Zd = np.dstack((Zd,Z))
bandId = band.attrib.get('band_id')
print('{:s} {:s} mean value: {:g}'.format(bandId,angle,np.nanmean(Zd)))
if points is None:
newRasterFn = os.path.join(\
outputFolder,'{:s}_{:s}_{:s}{:d}.tif'.format(productId,bandId,angle,scale))
# scale
Zd = scale * Zd
# set no data
Zd[np.isnan(Zd)] = noDataRaster
# write to disk
array2geotiff(newRasterFn,geoTransform,Zd,noDataRaster,outSpatialRef,gdal.GDT_UInt16)
# find values at points
else:
for ipoint,pointCoord in enumerate(points):
lon,lat = float(pointCoord[0]),float(pointCoord[1])
# create a geometry from coordinates
point = ogr.Geometry(ogr.wkbPoint)
point.AddPoint(lon, lat) # traditionnal GIS order
# transform point
point.Transform(coordTransform)
# find position in array
col,row = pix2map(point.GetX(),point.GetY(),geoTransform)
# check if point is out of the grid
if (col < 0 or row < 0 or col > nx or row > ny):
v = noDataCsv
# otherwise retrieve the values in all bands
else:
vd = Zd[int(row),int(col),:]
# select the non-NaN value(s)
v = vd[np.isfinite(vd)]
# check if point is in no data area
if len(v) == 0:
v = noDataCsv
# check if more than one value is found in the stack
# this can occur because angle grids overlap due to their coarse resolution
elif len(v) > 1:
print('solving an ambiguity for band = ' + bandId + ' at point ' + str(pointCoord))
detectorList = [d.attrib for d in band.iter('Viewing_Incidence_Angles_Grids')]
# indices where are the finite values
indexList = np.argwhere(np.isfinite(vd))
# look into the detector mask files to find which detector has measured this point
test = False
for ix in indexList :
detectorId = detectorList[int(ix)]['detector_id']
print('testing detector = ' + detectorId)
maskFn,bitNumber = getDetector(productFolder,root,bandId,detectorId)
# if the detector mask file is provided then we assign the first value
if maskFn is None :
print('takes first detector value by default')
test = True
test = testDetector(point,maskFn,bitNumber)
if test:
print('found it!')
v = vd[ix]
break
# if test always false (point outside the mask) returns no data
if test is False:
v = noDataCsv
outDictList[ipoint]['lon'] = lon
outDictList[ipoint]['lat'] = lat
# add this value to the output dictionnary
if bandId in outDictList[ipoint]:
outDictList[ipoint][bandId].append(float(v))
else:
outDictList[ipoint][bandId] = float(v)
# dump data to text file for this angle and band
if points is not None:
newPointsFn = os.path.join(\
outputFolder,'{:s}_{:s}.csv'.format(productId,angle))
writePoints(newPointsFn,outDictList)
if __name__ == "__main__":
# check arguments
if len(sys.argv) == 4:
print("Point mode")
pointFile = sys.argv[3]
# check if input file exists
if not(os.path.exists(pointFile)):
print("Error: input point file does not exists")
sys.exit(1)
points = readPoints(pointFile)
elif len(sys.argv) == 3:
print("Raster mode")
points = None
else:
print("Error: missing arguments\n")
print("usage in raster mode: extractViewAngle.py productFolder outputFolder\n")
print("usage in point mode: extractViewAngle.py productFolder outputFolder point_table_as_lon_lat.csv\n")
print("example: python extractViewAngle.py SENTINEL2A_20180224-103018-463_L2A_T31TGK_C_V2-2 angles\n")
print("example: python extractViewAngle.py SENTINEL2A_20180224-103018-463_L2A_T31TGK_C_V2-2 angles points.csv\n")
sys.exit(1)
# check if input file exists
productFolder = sys.argv[1]
if not(os.path.exists(productFolder)):
print ("Error: input folder does not exists")
sys.exit(1)
# check if folder can be created
outputFolder = sys.argv[2]
try:
os.makedirs(outputFolder,exist_ok=True)
except OSError:
print ("Error: cannot create output folder")
sys.exit(1)
else:
main(productFolder,outputFolder,points)
| true | true |
f728309ee84e1f5907f5d1c8d6b8fbfbc11e9b8f | 1,275 | py | Python | backend/users/migrations/0002_auto_20210715_1151.py | crowdbotics-apps/dsfs-28863 | fea2672275927bd37d23e2267273e0eae54340d2 | [
"FTL",
"AML",
"RSA-MD"
] | null | null | null | backend/users/migrations/0002_auto_20210715_1151.py | crowdbotics-apps/dsfs-28863 | fea2672275927bd37d23e2267273e0eae54340d2 | [
"FTL",
"AML",
"RSA-MD"
] | null | null | null | backend/users/migrations/0002_auto_20210715_1151.py | crowdbotics-apps/dsfs-28863 | fea2672275927bd37d23e2267273e0eae54340d2 | [
"FTL",
"AML",
"RSA-MD"
] | null | null | null | # Generated by Django 2.2.24 on 2021-07-15 11:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='last_updated',
field=models.DateTimeField(auto_now=True, null=True),
),
migrations.AddField(
model_name='user',
name='timestamp_created',
field=models.DateTimeField(auto_now_add=True, null=True),
),
migrations.AlterField(
model_name='user',
name='email',
field=models.EmailField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='user',
name='first_name',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='user',
name='last_name',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='user',
name='name',
field=models.CharField(blank=True, max_length=255, null=True),
),
]
| 28.977273 | 75 | 0.560784 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='last_updated',
field=models.DateTimeField(auto_now=True, null=True),
),
migrations.AddField(
model_name='user',
name='timestamp_created',
field=models.DateTimeField(auto_now_add=True, null=True),
),
migrations.AlterField(
model_name='user',
name='email',
field=models.EmailField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='user',
name='first_name',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='user',
name='last_name',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='user',
name='name',
field=models.CharField(blank=True, max_length=255, null=True),
),
]
| true | true |
f728321268f92165324f6342c6c0d7554a2a65bb | 5,569 | py | Python | my_replay_buffer.py | yannikkellerde/TD3 | 6101baaa38a53bdaa34e33105f4e016eb84cf5a9 | [
"MIT"
] | null | null | null | my_replay_buffer.py | yannikkellerde/TD3 | 6101baaa38a53bdaa34e33105f4e016eb84cf5a9 | [
"MIT"
] | null | null | null | my_replay_buffer.py | yannikkellerde/TD3 | 6101baaa38a53bdaa34e33105f4e016eb84cf5a9 | [
"MIT"
] | null | null | null | import numpy as np
import torch
import pickle
import os
class ReplayBuffer_particles(object):
def __init__(self, obs_space, action_space, max_size=int(1e6), load_folder=None):
self.max_size = max_size
self.store_np = ["state_features","state_particles","action",
"next_state_features","next_state_particles","reward",
"not_done"]
self.store_pkl = ["ptr","size"]
if load_folder is None:
self.ptr = 0
self.size = 0
self.state_features = np.zeros((max_size,obs_space[0].shape[0]))
self.state_particles = np.zeros((max_size, *obs_space[1].shape))
self.action = np.zeros((max_size, action_space.shape[0]))
self.next_state_features = np.zeros((max_size,obs_space[0].shape[0]))
self.next_state_particles = np.zeros((max_size, *obs_space[1].shape))
self.reward = np.zeros((max_size, 1))
self.not_done = np.zeros((max_size, 1))
else:
self.load(load_folder)
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def save(self,folder):
os.makedirs(folder,exist_ok=True)
for attrib in self.store_pkl:
with open(os.path.join(folder,attrib+".pkl"), "wb") as f:
pickle.dump(self.__dict__[attrib],f,protocol=4)
for attrib in self.store_np:
with open(os.path.join(folder,attrib+".pkl"), "wb") as f:
np.save(f,self.__dict__[attrib])
def load(self,folder):
for attrib in self.store_pkl:
with open(os.path.join(folder,attrib+".pkl"), "rb") as f:
self.__dict__[attrib] = pickle.load(f)
for attrib in self.store_np:
with open(os.path.join(folder,attrib+".pkl"), "rb") as f:
self.__dict__[attrib] = np.load(f)
def add(self, state, action, next_state, reward, done):
self.state_features[self.ptr] = state[0]
self.state_particles[self.ptr] = state[1]
self.action[self.ptr] = action
self.next_state_features[self.ptr] = next_state[0]
self.next_state_particles[self.ptr] = next_state[1]
self.reward[self.ptr] = reward
self.not_done[self.ptr] = 1. - done
self.ptr = (self.ptr + 1) % self.max_size
self.size = min(self.size + 1, self.max_size)
def sample(self, batch_size):
ind = np.random.randint(0, self.size, size=batch_size)
return (
torch.FloatTensor(self.state_features[ind]).to(self.device),
torch.FloatTensor(self.state_particles[ind]).to(self.device),
torch.FloatTensor(self.action[ind]).to(self.device),
torch.FloatTensor(self.next_state_features[ind]).to(self.device),
torch.FloatTensor(self.next_state_particles[ind]).to(self.device),
torch.FloatTensor(self.reward[ind]).to(self.device),
torch.FloatTensor(self.not_done[ind]).to(self.device)
)
class ReplayBuffer_featured(object):
def __init__(self, obs_space, action_space, max_size=int(1e6),load_folder=None):
self.max_size = max_size
self.ptr = 0
self.size = 0
self.store_np = ["state","action","next_state","reward","not_done"]
self.store_pkl = ["ptr","size"]
if load_folder is None:
self.state = np.zeros((max_size, obs_space.shape[0]))
self.action = np.zeros((max_size, action_space.shape[0]))
self.next_state = np.zeros((max_size, obs_space.shape[0]))
self.reward = np.zeros((max_size, 1))
self.not_done = np.zeros((max_size, 1))
else:
self.load(load_folder)
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def save(self,folder):
os.makedirs(folder,exist_ok=True)
for attrib in self.store_pkl:
with open(os.path.join(folder,attrib+".pkl"), "wb") as f:
pickle.dump(self.__dict__[attrib],f,protocol=4)
for attrib in self.store_np:
with open(os.path.join(folder,attrib+".pkl"), "wb") as f:
np.save(f,self.__dict__[attrib])
def load(self,folder):
for attrib in self.store_pkl:
with open(os.path.join(folder,attrib+".pkl"), "rb") as f:
self.__dict__[attrib] = pickle.load(f)
for attrib in self.store_np:
with open(os.path.join(folder,attrib+".pkl"), "rb") as f:
self.__dict__[attrib] = np.load(f)
def add(self, state, action, next_state, reward, done):
self.state[self.ptr] = state
self.action[self.ptr] = action
self.next_state[self.ptr] = next_state
self.reward[self.ptr] = reward
self.not_done[self.ptr] = 1. - done
self.ptr = (self.ptr + 1) % self.max_size
self.size = min(self.size + 1, self.max_size)
def sample(self, batch_size):
ind = np.random.randint(0, self.size, size=batch_size)
return (
torch.FloatTensor(self.state[ind]).to(self.device),
torch.FloatTensor(self.action[ind]).to(self.device),
torch.FloatTensor(self.next_state[ind]).to(self.device),
torch.FloatTensor(self.reward[ind]).to(self.device),
torch.FloatTensor(self.not_done[ind]).to(self.device)
)
if __name__ == "__main__":
env = gym.make("water_pouring:Pouring-mdp-full-v0")
r = ReplayBuffer(env.observation_space, env.action_space)
r.save("test.pkl") | 41.87218 | 85 | 0.604597 | import numpy as np
import torch
import pickle
import os
class ReplayBuffer_particles(object):
def __init__(self, obs_space, action_space, max_size=int(1e6), load_folder=None):
self.max_size = max_size
self.store_np = ["state_features","state_particles","action",
"next_state_features","next_state_particles","reward",
"not_done"]
self.store_pkl = ["ptr","size"]
if load_folder is None:
self.ptr = 0
self.size = 0
self.state_features = np.zeros((max_size,obs_space[0].shape[0]))
self.state_particles = np.zeros((max_size, *obs_space[1].shape))
self.action = np.zeros((max_size, action_space.shape[0]))
self.next_state_features = np.zeros((max_size,obs_space[0].shape[0]))
self.next_state_particles = np.zeros((max_size, *obs_space[1].shape))
self.reward = np.zeros((max_size, 1))
self.not_done = np.zeros((max_size, 1))
else:
self.load(load_folder)
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def save(self,folder):
os.makedirs(folder,exist_ok=True)
for attrib in self.store_pkl:
with open(os.path.join(folder,attrib+".pkl"), "wb") as f:
pickle.dump(self.__dict__[attrib],f,protocol=4)
for attrib in self.store_np:
with open(os.path.join(folder,attrib+".pkl"), "wb") as f:
np.save(f,self.__dict__[attrib])
def load(self,folder):
for attrib in self.store_pkl:
with open(os.path.join(folder,attrib+".pkl"), "rb") as f:
self.__dict__[attrib] = pickle.load(f)
for attrib in self.store_np:
with open(os.path.join(folder,attrib+".pkl"), "rb") as f:
self.__dict__[attrib] = np.load(f)
def add(self, state, action, next_state, reward, done):
self.state_features[self.ptr] = state[0]
self.state_particles[self.ptr] = state[1]
self.action[self.ptr] = action
self.next_state_features[self.ptr] = next_state[0]
self.next_state_particles[self.ptr] = next_state[1]
self.reward[self.ptr] = reward
self.not_done[self.ptr] = 1. - done
self.ptr = (self.ptr + 1) % self.max_size
self.size = min(self.size + 1, self.max_size)
def sample(self, batch_size):
ind = np.random.randint(0, self.size, size=batch_size)
return (
torch.FloatTensor(self.state_features[ind]).to(self.device),
torch.FloatTensor(self.state_particles[ind]).to(self.device),
torch.FloatTensor(self.action[ind]).to(self.device),
torch.FloatTensor(self.next_state_features[ind]).to(self.device),
torch.FloatTensor(self.next_state_particles[ind]).to(self.device),
torch.FloatTensor(self.reward[ind]).to(self.device),
torch.FloatTensor(self.not_done[ind]).to(self.device)
)
class ReplayBuffer_featured(object):
def __init__(self, obs_space, action_space, max_size=int(1e6),load_folder=None):
self.max_size = max_size
self.ptr = 0
self.size = 0
self.store_np = ["state","action","next_state","reward","not_done"]
self.store_pkl = ["ptr","size"]
if load_folder is None:
self.state = np.zeros((max_size, obs_space.shape[0]))
self.action = np.zeros((max_size, action_space.shape[0]))
self.next_state = np.zeros((max_size, obs_space.shape[0]))
self.reward = np.zeros((max_size, 1))
self.not_done = np.zeros((max_size, 1))
else:
self.load(load_folder)
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def save(self,folder):
os.makedirs(folder,exist_ok=True)
for attrib in self.store_pkl:
with open(os.path.join(folder,attrib+".pkl"), "wb") as f:
pickle.dump(self.__dict__[attrib],f,protocol=4)
for attrib in self.store_np:
with open(os.path.join(folder,attrib+".pkl"), "wb") as f:
np.save(f,self.__dict__[attrib])
def load(self,folder):
for attrib in self.store_pkl:
with open(os.path.join(folder,attrib+".pkl"), "rb") as f:
self.__dict__[attrib] = pickle.load(f)
for attrib in self.store_np:
with open(os.path.join(folder,attrib+".pkl"), "rb") as f:
self.__dict__[attrib] = np.load(f)
def add(self, state, action, next_state, reward, done):
self.state[self.ptr] = state
self.action[self.ptr] = action
self.next_state[self.ptr] = next_state
self.reward[self.ptr] = reward
self.not_done[self.ptr] = 1. - done
self.ptr = (self.ptr + 1) % self.max_size
self.size = min(self.size + 1, self.max_size)
def sample(self, batch_size):
ind = np.random.randint(0, self.size, size=batch_size)
return (
torch.FloatTensor(self.state[ind]).to(self.device),
torch.FloatTensor(self.action[ind]).to(self.device),
torch.FloatTensor(self.next_state[ind]).to(self.device),
torch.FloatTensor(self.reward[ind]).to(self.device),
torch.FloatTensor(self.not_done[ind]).to(self.device)
)
if __name__ == "__main__":
env = gym.make("water_pouring:Pouring-mdp-full-v0")
r = ReplayBuffer(env.observation_space, env.action_space)
r.save("test.pkl") | true | true |
f72832377fdf7269cdd940f641f5e93da1048678 | 47,946 | py | Python | locust/stats.py | DDSystemLab/ddsl_locust | e98455592a2e8c6722f1ba1fd3700fcf69a8744a | [
"MIT"
] | null | null | null | locust/stats.py | DDSystemLab/ddsl_locust | e98455592a2e8c6722f1ba1fd3700fcf69a8744a | [
"MIT"
] | 1 | 2021-01-16T17:56:48.000Z | 2021-01-16T17:56:48.000Z | locust/stats.py | DDSystemLab/ddsl_locust | e98455592a2e8c6722f1ba1fd3700fcf69a8744a | [
"MIT"
] | 1 | 2019-10-18T20:36:13.000Z | 2019-10-18T20:36:13.000Z | import datetime
import hashlib
import time
from collections import namedtuple, OrderedDict
from copy import copy
from itertools import chain
import csv
import gevent
from .exception import StopUser, CatchResponseError
import logging
console_logger = logging.getLogger("locust.stats_logger")
STATS_NAME_WIDTH = 60
STATS_TYPE_WIDTH = 8
"""Default interval for how frequently results are written to console."""
CONSOLE_STATS_INTERVAL_SEC = 2
"""Default interval for how frequently results are written to history."""
HISTORY_STATS_INTERVAL_SEC = 5
"""Default interval for how frequently CSV files are written if this option is configured."""
CSV_STATS_INTERVAL_SEC = 1
CSV_STATS_FLUSH_INTERVAL_SEC = 10
"""
Default window size/resolution - in seconds - when calculating the current
response time percentile
"""
CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW = 10
CachedResponseTimes = namedtuple("CachedResponseTimes", ["response_times", "num_requests"])
PERCENTILES_TO_REPORT = [0.50, 0.66, 0.75, 0.80, 0.90, 0.95, 0.98, 0.99, 0.999, 0.9999, 1.0]
class RequestStatsAdditionError(Exception):
pass
def get_readable_percentiles(percentile_list):
"""
Converts a list of percentiles from 0-1 fraction to 0%-100% view for using in console & csv reporting
:param percentile_list: The list of percentiles in range 0-1
:return: The list of string representation for each percentile in 0%-100% view
"""
return [
f"{int(percentile * 100) if (percentile * 100).is_integer() else round(100 * percentile, 6)}%"
for percentile in percentile_list
]
def calculate_response_time_percentile(response_times, num_requests, percent):
"""
Get the response time that a certain number of percent of the requests
finished within. Arguments:
response_times: A StatsEntry.response_times dict
num_requests: Number of request made (could be derived from response_times,
but we save some CPU cycles by using the value which we already store)
percent: The percentile we want to calculate. Specified in range: 0.0 - 1.0
"""
num_of_request = int((num_requests * percent))
processed_count = 0
for response_time in sorted(response_times.keys(), reverse=True):
processed_count += response_times[response_time]
if num_requests - processed_count <= num_of_request:
return response_time
# if all response times were None
return 0
def calculate_response_time_average(response_times, num_requests):
"""
Get the response time that a certain number of percent of the requests
finished within. Arguments:
response_times: A StatsEntry.response_times dict
num_requests: Number of request made (could be derived from response_times,
but we save some CPU cycles by using the value which we already store)
percent: The percentile we want to calculate. Specified in range: 0.0 - 1.0
"""
num_of_request = int(num_requests)
sum_val = 0
processed_count = 0
for response_time in sorted(response_times.keys(), reverse=True):
processed_count += response_times[response_time]
sum_val += response_time * response_times[response_time]
num_of_request = processed_count
if num_of_request > 0:
return int(sum_val / float(num_of_request))
else:
return 0
def calculate_response_time_max(response_times, num_requests):
"""
Get the response time that a certain number of percent of the requests
finished within. Arguments:
response_times: A StatsEntry.response_times dict
num_requests: Number of request made (could be derived from response_times,
but we save some CPU cycles by using the value which we already store)
percent: The percentile we want to calculate. Specified in range: 0.0 - 1.0
"""
num_of_request = int(num_requests)
max_val = 0
processed_count = 0
for response_time in sorted(response_times.keys(), reverse=True):
processed_count += response_times[response_time]
if response_time > max_val:
max_val = response_time
if max_val is None:
return None
return int(max_val)
def calculate_response_time_min(response_times, num_requests):
"""
Get the response time that a certain number of percent of the requests
finished within. Arguments:
response_times: A StatsEntry.response_times dict
num_requests: Number of request made (could be derived from response_times,
but we save some CPU cycles by using the value which we already store)
percent: The percentile we want to calculate. Specified in range: 0.0 - 1.0
"""
num_of_request = int(num_requests)
min_val = None
processed_count = 0
for response_time in sorted(response_times.keys(), reverse=True):
processed_count += response_times[response_time]
if min_val is None:
min_val = response_time
elif response_time < min_val:
min_val = response_time
if min_val is None:
return None
return int(min_val)
def diff_response_time_dicts(latest, old):
"""
Returns the delta between two {response_times:request_count} dicts.
Used together with the response_times cache to get the response times for the
last X seconds, which in turn is used to calculate the current response time
percentiles.
"""
new = {}
for t in latest:
diff = latest[t] - old.get(t, 0)
if diff:
new[t] = diff
return new
class RequestStats:
"""
Class that holds the request statistics.
"""
def __init__(self, use_response_times_cache=True):
"""
:param use_response_times_cache: The value of use_response_times_cache will be set for each StatsEntry()
when they are created. Settings it to False saves some memory and CPU
cycles which we can do on Worker nodes where the response_times_cache
is not needed.
"""
self.use_response_times_cache = use_response_times_cache
self.entries = {}
self.errors = {}
self.total = StatsEntry(self, "Aggregated", None, use_response_times_cache=self.use_response_times_cache)
self.history = []
@property
def num_requests(self):
return self.total.num_requests
@property
def num_none_requests(self):
return self.total.num_none_requests
@property
def num_failures(self):
return self.total.num_failures
@property
def last_request_timestamp(self):
return self.total.last_request_timestamp
@property
def start_time(self):
return self.total.start_time
def log_request(self, method, name, response_time, content_length):
self.total.log(response_time, content_length)
self.get(name, method).log(response_time, content_length)
def log_error(self, method, name, error):
self.total.log_error(error)
self.get(name, method).log_error(error)
# store error in errors dict
key = StatsError.create_key(method, name, error)
entry = self.errors.get(key)
if not entry:
entry = StatsError(method, name, error)
self.errors[key] = entry
entry.occurred()
def get(self, name, method):
"""
Retrieve a StatsEntry instance by name and method
"""
entry = self.entries.get((name, method))
if not entry:
entry = StatsEntry(self, name, method, use_response_times_cache=self.use_response_times_cache)
self.entries[(name, method)] = entry
return entry
def reset_all(self):
"""
Go through all stats entries and reset them to zero
"""
self.total.reset()
self.errors = {}
for r in self.entries.values():
r.reset()
self.history = []
def clear_all(self):
"""
Remove all stats entries and errors
"""
self.total = StatsEntry(self, "Aggregated", None, use_response_times_cache=self.use_response_times_cache)
self.entries = {}
self.errors = {}
self.history = []
def serialize_stats(self):
return [
self.entries[key].get_stripped_report()
for key in self.entries.keys()
if not (self.entries[key].num_requests == 0 and self.entries[key].num_failures == 0)
]
def serialize_errors(self):
return dict([(k, e.to_dict()) for k, e in self.errors.items()])
class StatsEntry:
"""
Represents a single stats entry (name and method)
"""
name = None
""" Name (URL) of this stats entry """
method = None
""" Method (GET, POST, PUT, etc.) """
num_requests = None
""" The number of requests made """
num_none_requests = None
""" The number of requests made with a None response time (typically async requests) """
num_failures = None
""" Number of failed request """
total_response_time = None
""" Total sum of the response times """
min_response_time = None
""" Minimum response time """
max_response_time = None
""" Maximum response time """
num_reqs_per_sec = None
""" A {second => request_count} dict that holds the number of requests made per second """
num_fail_per_sec = None
""" A (second => failure_count) dict that hold the number of failures per second """
response_times = None
"""
A {response_time => count} dict that holds the response time distribution of all
the requests.
The keys (the response time in ms) are rounded to store 1, 2, ... 9, 10, 20. .. 90,
100, 200 .. 900, 1000, 2000 ... 9000, in order to save memory.
This dict is used to calculate the median and percentile response times.
"""
use_response_times_cache = False
"""
If set to True, the copy of the response_time dict will be stored in response_times_cache
every second, and kept for 20 seconds (by default, will be CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW + 10).
We can use this dict to calculate the *current* median response time, as well as other response
time percentiles.
"""
response_times_cache = None
"""
If use_response_times_cache is set to True, this will be a {timestamp => CachedResponseTimes()}
OrderedDict that holds a copy of the response_times dict for each of the last 20 seconds.
"""
total_content_length = None
""" The sum of the content length of all the requests for this entry """
start_time = None
""" Time of the first request for this entry """
last_request_timestamp = None
""" Time of the last request for this entry """
def __init__(self, stats, name, method, use_response_times_cache=False):
self.stats = stats
self.name = name
self.method = method
self.use_response_times_cache = use_response_times_cache
self.reset()
def reset(self):
self.start_time = time.time()
self.num_requests = 0
self.num_none_requests = 0
self.num_failures = 0
self.total_response_time = 0
self.response_times = {}
self.min_response_time = None
self.max_response_time = 0
self.last_request_timestamp = None
self.num_reqs_per_sec = {}
self.num_fail_per_sec = {}
self.total_content_length = 0
if self.use_response_times_cache:
self.response_times_cache = OrderedDict()
self._cache_response_times(int(time.time()))
def log(self, response_time, content_length):
# get the time
current_time = time.time()
t = int(current_time)
if self.use_response_times_cache and self.last_request_timestamp and t > int(self.last_request_timestamp):
# see if we shall make a copy of the response_times dict and store in the cache
self._cache_response_times(t - 1)
self.num_requests += 1
self._log_time_of_request(current_time)
self._log_response_time(response_time)
# increase total content-length
self.total_content_length += content_length
def _log_time_of_request(self, current_time):
t = int(current_time)
self.num_reqs_per_sec[t] = self.num_reqs_per_sec.setdefault(t, 0) + 1
self.last_request_timestamp = current_time
def _log_response_time(self, response_time):
if response_time is None:
self.num_none_requests += 1
return
self.total_response_time += response_time
if self.min_response_time is None:
self.min_response_time = response_time
self.min_response_time = min(self.min_response_time, response_time)
self.max_response_time = max(self.max_response_time, response_time)
# to avoid to much data that has to be transferred to the master node when
# running in distributed mode, we save the response time rounded in a dict
# so that 147 becomes 150, 3432 becomes 3400 and 58760 becomes 59000
if response_time < 100:
rounded_response_time = round(response_time)
elif response_time < 1000:
rounded_response_time = round(response_time, -1)
elif response_time < 10000:
rounded_response_time = round(response_time, -2)
else:
rounded_response_time = round(response_time, -3)
# increase request count for the rounded key in response time dict
self.response_times.setdefault(rounded_response_time, 0)
self.response_times[rounded_response_time] += 1
def log_error(self, error):
self.num_failures += 1
t = int(time.time())
self.num_fail_per_sec[t] = self.num_fail_per_sec.setdefault(t, 0) + 1
@property
def fail_ratio(self):
try:
return float(self.num_failures) / self.num_requests
except ZeroDivisionError:
if self.num_failures > 0:
return 1.0
else:
return 0.0
@property
def avg_response_time(self):
try:
return float(self.total_response_time) / (self.num_requests - self.num_none_requests)
except ZeroDivisionError:
return 0
@property
def median_response_time(self):
if not self.response_times:
return 0
median = median_from_dict(self.num_requests - self.num_none_requests, self.response_times) or 0
# Since we only use two digits of precision when calculating the median response time
# while still using the exact values for min and max response times, the following checks
# makes sure that we don't report a median > max or median < min when a StatsEntry only
# have one (or very few) really slow requests
if median > self.max_response_time:
median = self.max_response_time
elif median < self.min_response_time:
median = self.min_response_time
return median
@property
def current_rps(self):
if self.stats.last_request_timestamp is None:
return 0
slice_start_time = max(int(self.stats.last_request_timestamp) - 12, int(self.stats.start_time or 0))
reqs = [
self.num_reqs_per_sec.get(t, 0) for t in range(slice_start_time, int(self.stats.last_request_timestamp) - 2)
]
return avg(reqs)
@property
def current_fail_per_sec(self):
if self.stats.last_request_timestamp is None:
return 0
slice_start_time = max(int(self.stats.last_request_timestamp) - 12, int(self.stats.start_time or 0))
reqs = [
self.num_fail_per_sec.get(t, 0) for t in range(slice_start_time, int(self.stats.last_request_timestamp) - 2)
]
return avg(reqs)
@property
def total_rps(self):
if not self.stats.last_request_timestamp or not self.stats.start_time:
return 0.0
try:
return self.num_requests / (self.stats.last_request_timestamp - self.stats.start_time)
except ZeroDivisionError:
return 0.0
@property
def total_fail_per_sec(self):
if not self.stats.last_request_timestamp or not self.stats.start_time:
return 0.0
try:
return self.num_failures / (self.stats.last_request_timestamp - self.stats.start_time)
except ZeroDivisionError:
return 0.0
@property
def avg_content_length(self):
try:
return self.total_content_length / self.num_requests
except ZeroDivisionError:
return 0
def extend(self, other):
"""
Extend the data from the current StatsEntry with the stats from another
StatsEntry instance.
"""
# save the old last_request_timestamp, to see if we should store a new copy
# of the response times in the response times cache
old_last_request_timestamp = self.last_request_timestamp
if self.last_request_timestamp is not None and other.last_request_timestamp is not None:
self.last_request_timestamp = max(self.last_request_timestamp, other.last_request_timestamp)
elif other.last_request_timestamp is not None:
self.last_request_timestamp = other.last_request_timestamp
self.start_time = min(self.start_time, other.start_time)
self.num_requests = self.num_requests + other.num_requests
self.num_none_requests = self.num_none_requests + other.num_none_requests
self.num_failures = self.num_failures + other.num_failures
self.total_response_time = self.total_response_time + other.total_response_time
self.max_response_time = max(self.max_response_time, other.max_response_time)
if self.min_response_time is not None and other.min_response_time is not None:
self.min_response_time = min(self.min_response_time, other.min_response_time)
elif other.min_response_time is not None:
# this means self.min_response_time is None, so we can safely replace it
self.min_response_time = other.min_response_time
self.total_content_length = self.total_content_length + other.total_content_length
for key in other.response_times:
self.response_times[key] = self.response_times.get(key, 0) + other.response_times[key]
for key in other.num_reqs_per_sec:
self.num_reqs_per_sec[key] = self.num_reqs_per_sec.get(key, 0) + other.num_reqs_per_sec[key]
for key in other.num_fail_per_sec:
self.num_fail_per_sec[key] = self.num_fail_per_sec.get(key, 0) + other.num_fail_per_sec[key]
if self.use_response_times_cache:
# If we've entered a new second, we'll cache the response times. Note that there
# might still be reports from other worker nodes - that contains requests for the same
# time periods - that hasn't been received/accounted for yet. This will cause the cache to
# lag behind a second or two, but since StatsEntry.current_response_time_percentile()
# (which is what the response times cache is used for) uses an approximation of the
# last 10 seconds anyway, it should be fine to ignore this.
last_time = self.last_request_timestamp and int(self.last_request_timestamp) or None
if last_time and last_time > (old_last_request_timestamp and int(old_last_request_timestamp) or 0):
self._cache_response_times(last_time)
def serialize(self):
return {
"name": self.name,
"method": self.method,
"last_request_timestamp": self.last_request_timestamp,
"start_time": self.start_time,
"num_requests": self.num_requests,
"num_none_requests": self.num_none_requests,
"num_failures": self.num_failures,
"total_response_time": self.total_response_time,
"max_response_time": self.max_response_time,
"min_response_time": self.min_response_time,
"total_content_length": self.total_content_length,
"response_times": self.response_times,
"num_reqs_per_sec": self.num_reqs_per_sec,
"num_fail_per_sec": self.num_fail_per_sec,
}
@classmethod
def unserialize(cls, data):
obj = cls(None, data["name"], data["method"])
for key in [
"last_request_timestamp",
"start_time",
"num_requests",
"num_none_requests",
"num_failures",
"total_response_time",
"max_response_time",
"min_response_time",
"total_content_length",
"response_times",
"num_reqs_per_sec",
"num_fail_per_sec",
]:
setattr(obj, key, data[key])
return obj
def get_stripped_report(self):
"""
Return the serialized version of this StatsEntry, and then clear the current stats.
"""
report = self.serialize()
self.reset()
return report
def to_string(self, current=True):
"""
Return the stats as a string suitable for console output. If current is True, it'll show
the RPS and failure rate for the last 10 seconds. If it's false, it'll show the total stats
for the whole run.
"""
if current:
rps = self.current_rps
fail_per_sec = self.current_fail_per_sec
else:
rps = self.total_rps
fail_per_sec = self.total_fail_per_sec
return (" %-" + str(STATS_NAME_WIDTH) + "s %7d %12s | %7d %7d %7d %7d | %7.2f %7.2f") % (
(self.method and self.method + " " or "") + self.name,
self.num_requests,
"%d(%.2f%%)" % (self.num_failures, self.fail_ratio * 100),
self.avg_response_time,
self.min_response_time or 0,
self.max_response_time,
self.median_response_time or 0,
rps or 0,
fail_per_sec or 0,
)
def __str__(self):
return self.to_string(current=True)
def get_response_time_percentile(self, percent):
"""
Get the response time that a certain number of percent of the requests
finished within.
Percent specified in range: 0.0 - 1.0
"""
return calculate_response_time_percentile(self.response_times, self.num_requests, percent)
def get_current_response_time_average(self):
"""
Calculate the *current* response time for a certain percentile. We use a sliding
window of (approximately) the last 10 seconds (specified by CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW)
when calculating this.
"""
if not self.use_response_times_cache:
raise ValueError("StatsEntry.use_response_times_cache must be set to True if we should be able to calculate the _current_ response time percentile")
# First, we want to determine which of the cached response_times dicts we should
# use to get response_times for approximately 10 seconds ago.
t = int(time.time())
# Since we can't be sure that the cache contains an entry for every second.
# We'll construct a list of timestamps which we consider acceptable keys to be used
# when trying to fetch the cached response_times. We construct this list in such a way
# that it's ordered by preference by starting to add t-10, then t-11, t-9, t-12, t-8,
# and so on
acceptable_timestamps = []
for i in range(9):
acceptable_timestamps.append(t-CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW-i)
acceptable_timestamps.append(t-CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW+i)
cached = None
for ts in acceptable_timestamps:
if ts in self.response_times_cache:
cached = self.response_times_cache[ts]
break
if cached:
# If we fond an acceptable cached response times, we'll calculate a new response
# times dict of the last 10 seconds (approximately) by diffing it with the current
# total response times. Then we'll use that to calculate a response time percentile
# for that timeframe
return calculate_response_time_average(
diff_response_time_dicts(self.response_times, cached.response_times),
self.num_requests - cached.num_requests,
)
def get_current_response_time_max(self):
"""
Calculate the *current* response time for a certain percentile. We use a sliding
window of (approximately) the last 10 seconds (specified by CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW)
when calculating this.
"""
if not self.use_response_times_cache:
raise ValueError("StatsEntry.use_response_times_cache must be set to True if we should be able to calculate the _current_ response time percentile")
# First, we want to determine which of the cached response_times dicts we should
# use to get response_times for approximately 10 seconds ago.
t = int(time.time())
# Since we can't be sure that the cache contains an entry for every second.
# We'll construct a list of timestamps which we consider acceptable keys to be used
# when trying to fetch the cached response_times. We construct this list in such a way
# that it's ordered by preference by starting to add t-10, then t-11, t-9, t-12, t-8,
# and so on
acceptable_timestamps = []
for i in range(9):
acceptable_timestamps.append(t-CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW-i)
acceptable_timestamps.append(t-CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW+i)
cached = None
for ts in acceptable_timestamps:
if ts in self.response_times_cache:
cached = self.response_times_cache[ts]
break
if cached:
# If we fond an acceptable cached response times, we'll calculate a new response
# times dict of the last 10 seconds (approximately) by diffing it with the current
# total response times. Then we'll use that to calculate a response time percentile
# for that timeframe
return calculate_response_time_max(
diff_response_time_dicts(self.response_times, cached.response_times),
self.num_requests - cached.num_requests,
)
def get_current_response_time_min(self):
"""
Calculate the *current* response time for a certain percentile. We use a sliding
window of (approximately) the last 10 seconds (specified by CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW)
when calculating this.
"""
if not self.use_response_times_cache:
raise ValueError("StatsEntry.use_response_times_cache must be set to True if we should be able to calculate the _current_ response time percentile")
# First, we want to determine which of the cached response_times dicts we should
# use to get response_times for approximately 10 seconds ago.
t = int(time.time())
# Since we can't be sure that the cache contains an entry for every second.
# We'll construct a list of timestamps which we consider acceptable keys to be used
# when trying to fetch the cached response_times. We construct this list in such a way
# that it's ordered by preference by starting to add t-10, then t-11, t-9, t-12, t-8,
# and so on
acceptable_timestamps = []
for i in range(9):
acceptable_timestamps.append(t - CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW - i)
acceptable_timestamps.append(t - CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW + i)
cached = None
for ts in acceptable_timestamps:
if ts in self.response_times_cache:
cached = self.response_times_cache[ts]
break
if cached:
# If we fond an acceptable cached response times, we'll calculate a new response
# times dict of the last 10 seconds (approximately) by diffing it with the current
# total response times. Then we'll use that to calculate a response time percentile
# for that timeframe
return calculate_response_time_min(
diff_response_time_dicts(self.response_times, cached.response_times),
self.num_requests - cached.num_requests,
)
def get_current_response_time_percentile(self, percent):
"""
Calculate the *current* response time for a certain percentile. We use a sliding
window of (approximately) the last 10 seconds (specified by CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW)
when calculating this.
"""
if not self.use_response_times_cache:
raise ValueError(
"StatsEntry.use_response_times_cache must be set to True if we should be able to calculate the _current_ response time percentile"
)
# First, we want to determine which of the cached response_times dicts we should
# use to get response_times for approximately 10 seconds ago.
t = int(time.time())
# Since we can't be sure that the cache contains an entry for every second.
# We'll construct a list of timestamps which we consider acceptable keys to be used
# when trying to fetch the cached response_times. We construct this list in such a way
# that it's ordered by preference by starting to add t-10, then t-11, t-9, t-12, t-8,
# and so on
acceptable_timestamps = []
acceptable_timestamps.append(t - CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW)
for i in range(1, 9):
acceptable_timestamps.append(t - CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW - i)
acceptable_timestamps.append(t - CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW + i)
cached = None
for ts in acceptable_timestamps:
if ts in self.response_times_cache:
cached = self.response_times_cache[ts]
break
if cached:
# If we fond an acceptable cached response times, we'll calculate a new response
# times dict of the last 10 seconds (approximately) by diffing it with the current
# total response times. Then we'll use that to calculate a response time percentile
# for that timeframe
return calculate_response_time_percentile(
diff_response_time_dicts(self.response_times, cached.response_times),
self.num_requests - cached.num_requests,
percent,
)
def percentile(self):
if not self.num_requests:
raise ValueError("Can't calculate percentile on url with no successful requests")
tpl = f" %-{str(STATS_TYPE_WIDTH)}s %-{str(STATS_NAME_WIDTH)}s %8d {' '.join(['%6d'] * len(PERCENTILES_TO_REPORT))}"
return tpl % (
(self.method, self.name)
+ tuple([self.get_response_time_percentile(p) for p in PERCENTILES_TO_REPORT])
+ (self.num_requests,)
)
def _cache_response_times(self, t):
self.response_times_cache[t] = CachedResponseTimes(
response_times=copy(self.response_times),
num_requests=self.num_requests,
)
# We'll use a cache size of CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW + 10 since - in the extreme case -
# we might still use response times (from the cache) for t-CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW-10
# to calculate the current response time percentile, if we're missing cached values for the subsequent
# 20 seconds
cache_size = CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW + 10
if len(self.response_times_cache) > cache_size:
# only keep the latest 20 response_times dicts
for i in range(len(self.response_times_cache) - cache_size):
self.response_times_cache.popitem(last=False)
class StatsError:
def __init__(self, method, name, error, occurrences=0):
self.method = method
self.name = name
self.error = error
self.occurrences = occurrences
@classmethod
def parse_error(cls, error):
string_error = repr(error)
target = "object at 0x"
target_index = string_error.find(target)
if target_index < 0:
return string_error
start = target_index + len(target) - 2
end = string_error.find(">", start)
if end < 0:
return string_error
hex_address = string_error[start:end]
return string_error.replace(hex_address, "0x....")
@classmethod
def create_key(cls, method, name, error):
key = "%s.%s.%r" % (method, name, StatsError.parse_error(error))
return hashlib.md5(key.encode("utf-8")).hexdigest()
def occurred(self):
self.occurrences += 1
def to_name(self):
error = self.error
if isinstance(error, CatchResponseError):
# standalone
unwrapped_error = error.args[0]
if isinstance(error, str) and error.startswith("CatchResponseError("):
# distributed
length = len("CatchResponseError(")
unwrapped_error = error[length:-1]
else:
# standalone, unwrapped exception
unwrapped_error = repr(error)
return "%s %s: %s" % (self.method, self.name, unwrapped_error)
def to_dict(self):
return {
"method": self.method,
"name": self.name,
"error": StatsError.parse_error(self.error),
"occurrences": self.occurrences,
}
@classmethod
def from_dict(cls, data):
return cls(data["method"], data["name"], data["error"], data["occurrences"])
def avg(values):
return sum(values, 0.0) / max(len(values), 1)
def median_from_dict(total, count):
"""
total is the number of requests made
count is a dict {response_time: count}
"""
pos = (total - 1) / 2
for k in sorted(count.keys()):
if pos < count[k]:
return k
pos -= count[k]
def setup_distributed_stats_event_listeners(events, stats):
def on_report_to_master(client_id, data):
data["stats"] = stats.serialize_stats()
data["stats_total"] = stats.total.get_stripped_report()
data["errors"] = stats.serialize_errors()
stats.errors = {}
def on_worker_report(client_id, data):
for stats_data in data["stats"]:
entry = StatsEntry.unserialize(stats_data)
request_key = (entry.name, entry.method)
if not request_key in stats.entries:
stats.entries[request_key] = StatsEntry(stats, entry.name, entry.method, use_response_times_cache=True)
stats.entries[request_key].extend(entry)
for error_key, error in data["errors"].items():
if error_key not in stats.errors:
stats.errors[error_key] = StatsError.from_dict(error)
else:
stats.errors[error_key].occurrences += error["occurrences"]
stats.total.extend(StatsEntry.unserialize(data["stats_total"]))
events.report_to_master.add_listener(on_report_to_master)
events.worker_report.add_listener(on_worker_report)
def print_stats(stats, current=True):
console_logger.info(
(" %-" + str(STATS_NAME_WIDTH) + "s %7s %12s | %7s %7s %7s %7s | %7s %7s")
% ("Name", "# reqs", "# fails", "Avg", "Min", "Max", "Median", "req/s", "failures/s")
)
console_logger.info("-" * (80 + STATS_NAME_WIDTH))
for key in sorted(stats.entries.keys()):
r = stats.entries[key]
console_logger.info(r.to_string(current=current))
console_logger.info("-" * (80 + STATS_NAME_WIDTH))
console_logger.info(stats.total.to_string(current=current))
console_logger.info("")
def print_percentile_stats(stats):
console_logger.info("Response time percentiles (approximated)")
headers = ("Type", "Name") + tuple(get_readable_percentiles(PERCENTILES_TO_REPORT)) + ("# reqs",)
console_logger.info(
(
f" %-{str(STATS_TYPE_WIDTH)}s %-{str(STATS_NAME_WIDTH)}s %8s "
f"{' '.join(['%6s'] * len(PERCENTILES_TO_REPORT))}"
)
% headers
)
separator = (
f'{"-" * STATS_TYPE_WIDTH}|{"-" * STATS_NAME_WIDTH}|{"-" * 9}|{("-" * 6 + "|") * len(PERCENTILES_TO_REPORT)}'
)
console_logger.info(separator)
for key in sorted(stats.entries.keys()):
r = stats.entries[key]
if r.response_times:
console_logger.info(r.percentile())
console_logger.info(separator)
if stats.total.response_times:
console_logger.info(stats.total.percentile())
console_logger.info("")
def print_error_report(stats):
if not len(stats.errors):
return
console_logger.info("Error report")
console_logger.info(" %-18s %-100s" % ("# occurrences", "Error"))
console_logger.info("-" * (80 + STATS_NAME_WIDTH))
for error in stats.errors.values():
console_logger.info(" %-18i %-100s" % (error.occurrences, error.to_name()))
console_logger.info("-" * (80 + STATS_NAME_WIDTH))
console_logger.info("")
def stats_printer(stats):
def stats_printer_func():
while True:
print_stats(stats)
gevent.sleep(CONSOLE_STATS_INTERVAL_SEC)
return stats_printer_func
def sort_stats(stats):
return [stats[key] for key in sorted(stats.keys())]
def stats_history(runner):
"""Save current stats info to history for charts of report."""
while True:
stats = runner.stats
if not stats.total.use_response_times_cache:
break
r = {
"time": datetime.datetime.now().strftime("%H:%M:%S"),
"current_rps": stats.total.current_rps or 0,
"current_fail_per_sec": stats.total.current_fail_per_sec or 0,
"response_time_percentile_95": stats.total.get_current_response_time_percentile(0.95) or 0,
"response_time_percentile_50": stats.total.get_current_response_time_percentile(0.5) or 0,
"user_count": runner.user_count or 0,
}
stats.history.append(r)
gevent.sleep(HISTORY_STATS_INTERVAL_SEC)
class StatsCSV:
"""Write statistics to csv_writer stream."""
def __init__(self, environment, percentiles_to_report):
super().__init__()
self.environment = environment
self.percentiles_to_report = percentiles_to_report
self.percentiles_na = ["N/A"] * len(self.percentiles_to_report)
self.requests_csv_columns = [
"Type",
"Name",
"Request Count",
"Failure Count",
"Median Response Time",
"Average Response Time",
"Min Response Time",
"Max Response Time",
"Average Content Size",
"Requests/s",
"Failures/s",
] + get_readable_percentiles(self.percentiles_to_report)
self.failures_columns = [
"Method",
"Name",
"Error",
"Occurrences",
]
self.exceptions_columns = [
"Count",
"Message",
"Traceback",
"Nodes",
]
def _percentile_fields(self, stats_entry):
return (
[int(stats_entry.get_response_time_percentile(x) or 0) for x in self.percentiles_to_report]
if stats_entry.num_requests
else self.percentiles_na
)
def requests_csv(self, csv_writer):
"""Write requests csv with header and data rows."""
csv_writer.writerow(self.requests_csv_columns)
self._requests_data_rows(csv_writer)
def _requests_data_rows(self, csv_writer):
"""Write requests csv data row, excluding header."""
stats = self.environment.stats
for stats_entry in chain(sort_stats(stats.entries), [stats.total]):
csv_writer.writerow(
chain(
[
stats_entry.method,
stats_entry.name,
stats_entry.num_requests,
stats_entry.num_failures,
stats_entry.median_response_time,
stats_entry.avg_response_time,
stats_entry.min_response_time or 0,
stats_entry.max_response_time,
stats_entry.avg_content_length,
stats_entry.total_rps,
stats_entry.total_fail_per_sec,
],
self._percentile_fields(stats_entry),
)
)
def failures_csv(self, csv_writer):
csv_writer.writerow(self.failures_columns)
self._failures_data_rows(csv_writer)
def _failures_data_rows(self, csv_writer):
for stats_error in sort_stats(self.environment.stats.errors):
csv_writer.writerow(
[
stats_error.method,
stats_error.name,
stats_error.error,
stats_error.occurrences,
]
)
def exceptions_csv(self, csv_writer):
csv_writer.writerow(self.exceptions_columns)
self._exceptions_data_rows(csv_writer)
def _exceptions_data_rows(self, csv_writer):
for exc in self.environment.runner.exceptions.values():
csv_writer.writerow(
[
exc["count"],
exc["msg"],
exc["traceback"],
", ".join(exc["nodes"])
]
)
class StatsCSVFileWriter(StatsCSV):
"""Write statistics to to CSV files"""
def __init__(self, environment, percentiles_to_report, base_filepath, full_history=False):
super().__init__(environment, percentiles_to_report)
self.base_filepath = base_filepath
self.full_history = full_history
self.requests_csv_filehandle = open(self.base_filepath + "_stats.csv", "w")
self.requests_csv_writer = csv.writer(self.requests_csv_filehandle)
self.stats_history_csv_filehandle = open(self.stats_history_file_name(), "w")
self.stats_history_csv_writer = csv.writer(self.stats_history_csv_filehandle)
self.failures_csv_filehandle = open(self.base_filepath + "_failures.csv", "w")
self.failures_csv_writer = csv.writer(self.failures_csv_filehandle)
self.failures_csv_data_start = 0
self.exceptions_csv_filehandle = open(self.base_filepath + "_exceptions.csv", "w")
self.exceptions_csv_writer = csv.writer(self.exceptions_csv_filehandle)
self.exceptions_csv_data_start = 0
self.stats_history_csv_columns = [
"Timestamp",
"User Count",
"Type",
"Name",
"Requests/s",
"Failures/s",
*get_readable_percentiles(self.percentiles_to_report),
"Total Request Count",
"Total Failure Count",
"Total Median Response Time",
"Total Average Response Time",
"Total Min Response Time",
"Total Max Response Time",
"Total Average Content Size",
]
def __call__(self):
self.stats_writer()
def stats_writer(self):
"""Writes all the csv files for the locust run."""
# Write header row for all files and save position for non-append files
self.requests_csv_writer.writerow(self.requests_csv_columns)
requests_csv_data_start = self.requests_csv_filehandle.tell()
self.stats_history_csv_writer.writerow(self.stats_history_csv_columns)
self.failures_csv_writer.writerow(self.failures_columns)
self.failures_csv_data_start = self.failures_csv_filehandle.tell()
self.exceptions_csv_writer.writerow(self.exceptions_columns)
self.exceptions_csv_data_start = self.exceptions_csv_filehandle.tell()
# Continuously write date rows for all files
last_flush_time = 0
while True:
now = time.time()
self.requests_csv_filehandle.seek(requests_csv_data_start)
self._requests_data_rows(self.requests_csv_writer)
self.requests_csv_filehandle.truncate()
self._stats_history_data_rows(self.stats_history_csv_writer, now)
self.failures_csv_filehandle.seek(self.failures_csv_data_start)
self._failures_data_rows(self.failures_csv_writer)
self.failures_csv_filehandle.truncate()
self.exceptions_csv_filehandle.seek((self.exceptions_csv_data_start))
self._exceptions_data_rows(self.exceptions_csv_writer)
self.exceptions_csv_filehandle.truncate()
if now - last_flush_time > CSV_STATS_FLUSH_INTERVAL_SEC:
self.requests_flush()
self.stats_history_flush()
self.failures_flush()
self.exceptions_flush()
last_flush_time = now
gevent.sleep(CSV_STATS_INTERVAL_SEC)
def _stats_history_data_rows(self, csv_writer, now):
"""
Write CSV rows with the *current* stats. By default only includes the
Aggregated stats entry, but if self.full_history is set to True, a row for each entry will
will be included.
Note that this method differs from the other methods as it appends time-stamped data to the file, whereas the other methods overwrites the data.
"""
stats = self.environment.stats
timestamp = int(now)
stats_entries = []
if self.full_history:
stats_entries = sort_stats(stats.entries)
for stats_entry in chain(stats_entries, [stats.total]):
csv_writer.writerow(
chain(
(
timestamp,
self.environment.runner.user_count,
stats_entry.method or "",
stats_entry.name,
f"{stats_entry.current_rps:2f}",
f"{stats_entry.current_fail_per_sec:2f}",
),
self._percentile_fields(stats_entry),
(
stats_entry.num_requests,
stats_entry.num_failures,
stats_entry.median_response_time,
stats_entry.avg_response_time,
stats_entry.min_response_time or 0,
stats_entry.max_response_time,
stats_entry.avg_content_length,
),
)
)
def requests_flush(self):
self.requests_csv_filehandle.flush()
def stats_history_flush(self):
self.stats_history_csv_filehandle.flush()
def failures_flush(self):
self.failures_csv_filehandle.flush()
def exceptions_flush(self):
self.exceptions_csv_filehandle.flush()
def close_files(self):
self.requests_csv_filehandle.close()
self.stats_history_csv_filehandle.close()
self.failures_csv_filehandle.close()
self.exceptions_csv_filehandle.close()
def stats_history_file_name(self):
return self.base_filepath + "_stats_history.csv"
| 38.822672 | 160 | 0.643119 | import datetime
import hashlib
import time
from collections import namedtuple, OrderedDict
from copy import copy
from itertools import chain
import csv
import gevent
from .exception import StopUser, CatchResponseError
import logging
console_logger = logging.getLogger("locust.stats_logger")
STATS_NAME_WIDTH = 60
STATS_TYPE_WIDTH = 8
CONSOLE_STATS_INTERVAL_SEC = 2
HISTORY_STATS_INTERVAL_SEC = 5
CSV_STATS_INTERVAL_SEC = 1
CSV_STATS_FLUSH_INTERVAL_SEC = 10
CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW = 10
CachedResponseTimes = namedtuple("CachedResponseTimes", ["response_times", "num_requests"])
PERCENTILES_TO_REPORT = [0.50, 0.66, 0.75, 0.80, 0.90, 0.95, 0.98, 0.99, 0.999, 0.9999, 1.0]
class RequestStatsAdditionError(Exception):
pass
def get_readable_percentiles(percentile_list):
return [
f"{int(percentile * 100) if (percentile * 100).is_integer() else round(100 * percentile, 6)}%"
for percentile in percentile_list
]
def calculate_response_time_percentile(response_times, num_requests, percent):
num_of_request = int((num_requests * percent))
processed_count = 0
for response_time in sorted(response_times.keys(), reverse=True):
processed_count += response_times[response_time]
if num_requests - processed_count <= num_of_request:
return response_time
return 0
def calculate_response_time_average(response_times, num_requests):
num_of_request = int(num_requests)
sum_val = 0
processed_count = 0
for response_time in sorted(response_times.keys(), reverse=True):
processed_count += response_times[response_time]
sum_val += response_time * response_times[response_time]
num_of_request = processed_count
if num_of_request > 0:
return int(sum_val / float(num_of_request))
else:
return 0
def calculate_response_time_max(response_times, num_requests):
num_of_request = int(num_requests)
max_val = 0
processed_count = 0
for response_time in sorted(response_times.keys(), reverse=True):
processed_count += response_times[response_time]
if response_time > max_val:
max_val = response_time
if max_val is None:
return None
return int(max_val)
def calculate_response_time_min(response_times, num_requests):
num_of_request = int(num_requests)
min_val = None
processed_count = 0
for response_time in sorted(response_times.keys(), reverse=True):
processed_count += response_times[response_time]
if min_val is None:
min_val = response_time
elif response_time < min_val:
min_val = response_time
if min_val is None:
return None
return int(min_val)
def diff_response_time_dicts(latest, old):
new = {}
for t in latest:
diff = latest[t] - old.get(t, 0)
if diff:
new[t] = diff
return new
class RequestStats:
def __init__(self, use_response_times_cache=True):
self.use_response_times_cache = use_response_times_cache
self.entries = {}
self.errors = {}
self.total = StatsEntry(self, "Aggregated", None, use_response_times_cache=self.use_response_times_cache)
self.history = []
@property
def num_requests(self):
return self.total.num_requests
@property
def num_none_requests(self):
return self.total.num_none_requests
@property
def num_failures(self):
return self.total.num_failures
@property
def last_request_timestamp(self):
return self.total.last_request_timestamp
@property
def start_time(self):
return self.total.start_time
def log_request(self, method, name, response_time, content_length):
self.total.log(response_time, content_length)
self.get(name, method).log(response_time, content_length)
def log_error(self, method, name, error):
self.total.log_error(error)
self.get(name, method).log_error(error)
key = StatsError.create_key(method, name, error)
entry = self.errors.get(key)
if not entry:
entry = StatsError(method, name, error)
self.errors[key] = entry
entry.occurred()
def get(self, name, method):
entry = self.entries.get((name, method))
if not entry:
entry = StatsEntry(self, name, method, use_response_times_cache=self.use_response_times_cache)
self.entries[(name, method)] = entry
return entry
def reset_all(self):
self.total.reset()
self.errors = {}
for r in self.entries.values():
r.reset()
self.history = []
def clear_all(self):
self.total = StatsEntry(self, "Aggregated", None, use_response_times_cache=self.use_response_times_cache)
self.entries = {}
self.errors = {}
self.history = []
def serialize_stats(self):
return [
self.entries[key].get_stripped_report()
for key in self.entries.keys()
if not (self.entries[key].num_requests == 0 and self.entries[key].num_failures == 0)
]
def serialize_errors(self):
return dict([(k, e.to_dict()) for k, e in self.errors.items()])
class StatsEntry:
name = None
method = None
num_requests = None
num_none_requests = None
num_failures = None
total_response_time = None
min_response_time = None
max_response_time = None
num_reqs_per_sec = None
num_fail_per_sec = None
response_times = None
use_response_times_cache = False
response_times_cache = None
total_content_length = None
start_time = None
last_request_timestamp = None
def __init__(self, stats, name, method, use_response_times_cache=False):
self.stats = stats
self.name = name
self.method = method
self.use_response_times_cache = use_response_times_cache
self.reset()
def reset(self):
self.start_time = time.time()
self.num_requests = 0
self.num_none_requests = 0
self.num_failures = 0
self.total_response_time = 0
self.response_times = {}
self.min_response_time = None
self.max_response_time = 0
self.last_request_timestamp = None
self.num_reqs_per_sec = {}
self.num_fail_per_sec = {}
self.total_content_length = 0
if self.use_response_times_cache:
self.response_times_cache = OrderedDict()
self._cache_response_times(int(time.time()))
def log(self, response_time, content_length):
current_time = time.time()
t = int(current_time)
if self.use_response_times_cache and self.last_request_timestamp and t > int(self.last_request_timestamp):
self._cache_response_times(t - 1)
self.num_requests += 1
self._log_time_of_request(current_time)
self._log_response_time(response_time)
self.total_content_length += content_length
def _log_time_of_request(self, current_time):
t = int(current_time)
self.num_reqs_per_sec[t] = self.num_reqs_per_sec.setdefault(t, 0) + 1
self.last_request_timestamp = current_time
def _log_response_time(self, response_time):
if response_time is None:
self.num_none_requests += 1
return
self.total_response_time += response_time
if self.min_response_time is None:
self.min_response_time = response_time
self.min_response_time = min(self.min_response_time, response_time)
self.max_response_time = max(self.max_response_time, response_time)
if response_time < 100:
rounded_response_time = round(response_time)
elif response_time < 1000:
rounded_response_time = round(response_time, -1)
elif response_time < 10000:
rounded_response_time = round(response_time, -2)
else:
rounded_response_time = round(response_time, -3)
self.response_times.setdefault(rounded_response_time, 0)
self.response_times[rounded_response_time] += 1
def log_error(self, error):
self.num_failures += 1
t = int(time.time())
self.num_fail_per_sec[t] = self.num_fail_per_sec.setdefault(t, 0) + 1
@property
def fail_ratio(self):
try:
return float(self.num_failures) / self.num_requests
except ZeroDivisionError:
if self.num_failures > 0:
return 1.0
else:
return 0.0
@property
def avg_response_time(self):
try:
return float(self.total_response_time) / (self.num_requests - self.num_none_requests)
except ZeroDivisionError:
return 0
@property
def median_response_time(self):
if not self.response_times:
return 0
median = median_from_dict(self.num_requests - self.num_none_requests, self.response_times) or 0
# have one (or very few) really slow requests
if median > self.max_response_time:
median = self.max_response_time
elif median < self.min_response_time:
median = self.min_response_time
return median
@property
def current_rps(self):
if self.stats.last_request_timestamp is None:
return 0
slice_start_time = max(int(self.stats.last_request_timestamp) - 12, int(self.stats.start_time or 0))
reqs = [
self.num_reqs_per_sec.get(t, 0) for t in range(slice_start_time, int(self.stats.last_request_timestamp) - 2)
]
return avg(reqs)
@property
def current_fail_per_sec(self):
if self.stats.last_request_timestamp is None:
return 0
slice_start_time = max(int(self.stats.last_request_timestamp) - 12, int(self.stats.start_time or 0))
reqs = [
self.num_fail_per_sec.get(t, 0) for t in range(slice_start_time, int(self.stats.last_request_timestamp) - 2)
]
return avg(reqs)
@property
def total_rps(self):
if not self.stats.last_request_timestamp or not self.stats.start_time:
return 0.0
try:
return self.num_requests / (self.stats.last_request_timestamp - self.stats.start_time)
except ZeroDivisionError:
return 0.0
@property
def total_fail_per_sec(self):
if not self.stats.last_request_timestamp or not self.stats.start_time:
return 0.0
try:
return self.num_failures / (self.stats.last_request_timestamp - self.stats.start_time)
except ZeroDivisionError:
return 0.0
@property
def avg_content_length(self):
try:
return self.total_content_length / self.num_requests
except ZeroDivisionError:
return 0
def extend(self, other):
# save the old last_request_timestamp, to see if we should store a new copy
# of the response times in the response times cache
old_last_request_timestamp = self.last_request_timestamp
if self.last_request_timestamp is not None and other.last_request_timestamp is not None:
self.last_request_timestamp = max(self.last_request_timestamp, other.last_request_timestamp)
elif other.last_request_timestamp is not None:
self.last_request_timestamp = other.last_request_timestamp
self.start_time = min(self.start_time, other.start_time)
self.num_requests = self.num_requests + other.num_requests
self.num_none_requests = self.num_none_requests + other.num_none_requests
self.num_failures = self.num_failures + other.num_failures
self.total_response_time = self.total_response_time + other.total_response_time
self.max_response_time = max(self.max_response_time, other.max_response_time)
if self.min_response_time is not None and other.min_response_time is not None:
self.min_response_time = min(self.min_response_time, other.min_response_time)
elif other.min_response_time is not None:
# this means self.min_response_time is None, so we can safely replace it
self.min_response_time = other.min_response_time
self.total_content_length = self.total_content_length + other.total_content_length
for key in other.response_times:
self.response_times[key] = self.response_times.get(key, 0) + other.response_times[key]
for key in other.num_reqs_per_sec:
self.num_reqs_per_sec[key] = self.num_reqs_per_sec.get(key, 0) + other.num_reqs_per_sec[key]
for key in other.num_fail_per_sec:
self.num_fail_per_sec[key] = self.num_fail_per_sec.get(key, 0) + other.num_fail_per_sec[key]
if self.use_response_times_cache:
# If we've entered a new second, we'll cache the response times. Note that there
# might still be reports from other worker nodes - that contains requests for the same
# time periods - that hasn't been received/accounted for yet. This will cause the cache to
last_time = self.last_request_timestamp and int(self.last_request_timestamp) or None
if last_time and last_time > (old_last_request_timestamp and int(old_last_request_timestamp) or 0):
self._cache_response_times(last_time)
def serialize(self):
return {
"name": self.name,
"method": self.method,
"last_request_timestamp": self.last_request_timestamp,
"start_time": self.start_time,
"num_requests": self.num_requests,
"num_none_requests": self.num_none_requests,
"num_failures": self.num_failures,
"total_response_time": self.total_response_time,
"max_response_time": self.max_response_time,
"min_response_time": self.min_response_time,
"total_content_length": self.total_content_length,
"response_times": self.response_times,
"num_reqs_per_sec": self.num_reqs_per_sec,
"num_fail_per_sec": self.num_fail_per_sec,
}
@classmethod
def unserialize(cls, data):
obj = cls(None, data["name"], data["method"])
for key in [
"last_request_timestamp",
"start_time",
"num_requests",
"num_none_requests",
"num_failures",
"total_response_time",
"max_response_time",
"min_response_time",
"total_content_length",
"response_times",
"num_reqs_per_sec",
"num_fail_per_sec",
]:
setattr(obj, key, data[key])
return obj
def get_stripped_report(self):
report = self.serialize()
self.reset()
return report
def to_string(self, current=True):
if current:
rps = self.current_rps
fail_per_sec = self.current_fail_per_sec
else:
rps = self.total_rps
fail_per_sec = self.total_fail_per_sec
return (" %-" + str(STATS_NAME_WIDTH) + "s %7d %12s | %7d %7d %7d %7d | %7.2f %7.2f") % (
(self.method and self.method + " " or "") + self.name,
self.num_requests,
"%d(%.2f%%)" % (self.num_failures, self.fail_ratio * 100),
self.avg_response_time,
self.min_response_time or 0,
self.max_response_time,
self.median_response_time or 0,
rps or 0,
fail_per_sec or 0,
)
def __str__(self):
return self.to_string(current=True)
def get_response_time_percentile(self, percent):
return calculate_response_time_percentile(self.response_times, self.num_requests, percent)
def get_current_response_time_average(self):
if not self.use_response_times_cache:
raise ValueError("StatsEntry.use_response_times_cache must be set to True if we should be able to calculate the _current_ response time percentile")
t = int(time.time())
# We'll construct a list of timestamps which we consider acceptable keys to be used
# and so on
acceptable_timestamps = []
for i in range(9):
acceptable_timestamps.append(t-CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW-i)
acceptable_timestamps.append(t-CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW+i)
cached = None
for ts in acceptable_timestamps:
if ts in self.response_times_cache:
cached = self.response_times_cache[ts]
break
if cached:
# If we fond an acceptable cached response times, we'll calculate a new response
# for that timeframe
return calculate_response_time_average(
diff_response_time_dicts(self.response_times, cached.response_times),
self.num_requests - cached.num_requests,
)
def get_current_response_time_max(self):
if not self.use_response_times_cache:
raise ValueError("StatsEntry.use_response_times_cache must be set to True if we should be able to calculate the _current_ response time percentile")
# First, we want to determine which of the cached response_times dicts we should
# use to get response_times for approximately 10 seconds ago.
t = int(time.time())
# Since we can't be sure that the cache contains an entry for every second.
# when trying to fetch the cached response_times. We construct this list in such a way
# that it's ordered by preference by starting to add t-10, then t-11, t-9, t-12, t-8,
acceptable_timestamps = []
for i in range(9):
acceptable_timestamps.append(t-CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW-i)
acceptable_timestamps.append(t-CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW+i)
cached = None
for ts in acceptable_timestamps:
if ts in self.response_times_cache:
cached = self.response_times_cache[ts]
break
if cached:
# times dict of the last 10 seconds (approximately) by diffing it with the current
# total response times. Then we'll use that to calculate a response time percentile
return calculate_response_time_max(
diff_response_time_dicts(self.response_times, cached.response_times),
self.num_requests - cached.num_requests,
)
def get_current_response_time_min(self):
if not self.use_response_times_cache:
raise ValueError("StatsEntry.use_response_times_cache must be set to True if we should be able to calculate the _current_ response time percentile")
t = int(time.time())
# We'll construct a list of timestamps which we consider acceptable keys to be used
# and so on
acceptable_timestamps = []
for i in range(9):
acceptable_timestamps.append(t - CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW - i)
acceptable_timestamps.append(t - CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW + i)
cached = None
for ts in acceptable_timestamps:
if ts in self.response_times_cache:
cached = self.response_times_cache[ts]
break
if cached:
# If we fond an acceptable cached response times, we'll calculate a new response
# for that timeframe
return calculate_response_time_min(
diff_response_time_dicts(self.response_times, cached.response_times),
self.num_requests - cached.num_requests,
)
def get_current_response_time_percentile(self, percent):
if not self.use_response_times_cache:
raise ValueError(
"StatsEntry.use_response_times_cache must be set to True if we should be able to calculate the _current_ response time percentile"
)
# First, we want to determine which of the cached response_times dicts we should
# use to get response_times for approximately 10 seconds ago.
t = int(time.time())
# Since we can't be sure that the cache contains an entry for every second.
# when trying to fetch the cached response_times. We construct this list in such a way
# that it's ordered by preference by starting to add t-10, then t-11, t-9, t-12, t-8,
acceptable_timestamps = []
acceptable_timestamps.append(t - CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW)
for i in range(1, 9):
acceptable_timestamps.append(t - CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW - i)
acceptable_timestamps.append(t - CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW + i)
cached = None
for ts in acceptable_timestamps:
if ts in self.response_times_cache:
cached = self.response_times_cache[ts]
break
if cached:
# times dict of the last 10 seconds (approximately) by diffing it with the current
# total response times. Then we'll use that to calculate a response time percentile
return calculate_response_time_percentile(
diff_response_time_dicts(self.response_times, cached.response_times),
self.num_requests - cached.num_requests,
percent,
)
def percentile(self):
if not self.num_requests:
raise ValueError("Can't calculate percentile on url with no successful requests")
tpl = f" %-{str(STATS_TYPE_WIDTH)}s %-{str(STATS_NAME_WIDTH)}s %8d {' '.join(['%6d'] * len(PERCENTILES_TO_REPORT))}"
return tpl % (
(self.method, self.name)
+ tuple([self.get_response_time_percentile(p) for p in PERCENTILES_TO_REPORT])
+ (self.num_requests,)
)
def _cache_response_times(self, t):
self.response_times_cache[t] = CachedResponseTimes(
response_times=copy(self.response_times),
num_requests=self.num_requests,
)
# We'll use a cache size of CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW + 10 since - in the extreme case -
# 20 seconds
cache_size = CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW + 10
if len(self.response_times_cache) > cache_size:
# only keep the latest 20 response_times dicts
for i in range(len(self.response_times_cache) - cache_size):
self.response_times_cache.popitem(last=False)
class StatsError:
def __init__(self, method, name, error, occurrences=0):
self.method = method
self.name = name
self.error = error
self.occurrences = occurrences
@classmethod
def parse_error(cls, error):
string_error = repr(error)
target = "object at 0x"
target_index = string_error.find(target)
if target_index < 0:
return string_error
start = target_index + len(target) - 2
end = string_error.find(">", start)
if end < 0:
return string_error
hex_address = string_error[start:end]
return string_error.replace(hex_address, "0x....")
@classmethod
def create_key(cls, method, name, error):
key = "%s.%s.%r" % (method, name, StatsError.parse_error(error))
return hashlib.md5(key.encode("utf-8")).hexdigest()
def occurred(self):
self.occurrences += 1
def to_name(self):
error = self.error
if isinstance(error, CatchResponseError):
# standalone
unwrapped_error = error.args[0]
if isinstance(error, str) and error.startswith("CatchResponseError("):
# distributed
length = len("CatchResponseError(")
unwrapped_error = error[length:-1]
else:
# standalone, unwrapped exception
unwrapped_error = repr(error)
return "%s %s: %s" % (self.method, self.name, unwrapped_error)
def to_dict(self):
return {
"method": self.method,
"name": self.name,
"error": StatsError.parse_error(self.error),
"occurrences": self.occurrences,
}
@classmethod
def from_dict(cls, data):
return cls(data["method"], data["name"], data["error"], data["occurrences"])
def avg(values):
return sum(values, 0.0) / max(len(values), 1)
def median_from_dict(total, count):
pos = (total - 1) / 2
for k in sorted(count.keys()):
if pos < count[k]:
return k
pos -= count[k]
def setup_distributed_stats_event_listeners(events, stats):
def on_report_to_master(client_id, data):
data["stats"] = stats.serialize_stats()
data["stats_total"] = stats.total.get_stripped_report()
data["errors"] = stats.serialize_errors()
stats.errors = {}
def on_worker_report(client_id, data):
for stats_data in data["stats"]:
entry = StatsEntry.unserialize(stats_data)
request_key = (entry.name, entry.method)
if not request_key in stats.entries:
stats.entries[request_key] = StatsEntry(stats, entry.name, entry.method, use_response_times_cache=True)
stats.entries[request_key].extend(entry)
for error_key, error in data["errors"].items():
if error_key not in stats.errors:
stats.errors[error_key] = StatsError.from_dict(error)
else:
stats.errors[error_key].occurrences += error["occurrences"]
stats.total.extend(StatsEntry.unserialize(data["stats_total"]))
events.report_to_master.add_listener(on_report_to_master)
events.worker_report.add_listener(on_worker_report)
def print_stats(stats, current=True):
console_logger.info(
(" %-" + str(STATS_NAME_WIDTH) + "s %7s %12s | %7s %7s %7s %7s | %7s %7s")
% ("Name", "# reqs", "# fails", "Avg", "Min", "Max", "Median", "req/s", "failures/s")
)
console_logger.info("-" * (80 + STATS_NAME_WIDTH))
for key in sorted(stats.entries.keys()):
r = stats.entries[key]
console_logger.info(r.to_string(current=current))
console_logger.info("-" * (80 + STATS_NAME_WIDTH))
console_logger.info(stats.total.to_string(current=current))
console_logger.info("")
def print_percentile_stats(stats):
console_logger.info("Response time percentiles (approximated)")
headers = ("Type", "Name") + tuple(get_readable_percentiles(PERCENTILES_TO_REPORT)) + ("# reqs",)
console_logger.info(
(
f" %-{str(STATS_TYPE_WIDTH)}s %-{str(STATS_NAME_WIDTH)}s %8s "
f"{' '.join(['%6s'] * len(PERCENTILES_TO_REPORT))}"
)
% headers
)
separator = (
f'{"-" * STATS_TYPE_WIDTH}|{"-" * STATS_NAME_WIDTH}|{"-" * 9}|{("-" * 6 + "|") * len(PERCENTILES_TO_REPORT)}'
)
console_logger.info(separator)
for key in sorted(stats.entries.keys()):
r = stats.entries[key]
if r.response_times:
console_logger.info(r.percentile())
console_logger.info(separator)
if stats.total.response_times:
console_logger.info(stats.total.percentile())
console_logger.info("")
def print_error_report(stats):
if not len(stats.errors):
return
console_logger.info("Error report")
console_logger.info(" %-18s %-100s" % ("# occurrences", "Error"))
console_logger.info("-" * (80 + STATS_NAME_WIDTH))
for error in stats.errors.values():
console_logger.info(" %-18i %-100s" % (error.occurrences, error.to_name()))
console_logger.info("-" * (80 + STATS_NAME_WIDTH))
console_logger.info("")
def stats_printer(stats):
def stats_printer_func():
while True:
print_stats(stats)
gevent.sleep(CONSOLE_STATS_INTERVAL_SEC)
return stats_printer_func
def sort_stats(stats):
return [stats[key] for key in sorted(stats.keys())]
def stats_history(runner):
while True:
stats = runner.stats
if not stats.total.use_response_times_cache:
break
r = {
"time": datetime.datetime.now().strftime("%H:%M:%S"),
"current_rps": stats.total.current_rps or 0,
"current_fail_per_sec": stats.total.current_fail_per_sec or 0,
"response_time_percentile_95": stats.total.get_current_response_time_percentile(0.95) or 0,
"response_time_percentile_50": stats.total.get_current_response_time_percentile(0.5) or 0,
"user_count": runner.user_count or 0,
}
stats.history.append(r)
gevent.sleep(HISTORY_STATS_INTERVAL_SEC)
class StatsCSV:
def __init__(self, environment, percentiles_to_report):
super().__init__()
self.environment = environment
self.percentiles_to_report = percentiles_to_report
self.percentiles_na = ["N/A"] * len(self.percentiles_to_report)
self.requests_csv_columns = [
"Type",
"Name",
"Request Count",
"Failure Count",
"Median Response Time",
"Average Response Time",
"Min Response Time",
"Max Response Time",
"Average Content Size",
"Requests/s",
"Failures/s",
] + get_readable_percentiles(self.percentiles_to_report)
self.failures_columns = [
"Method",
"Name",
"Error",
"Occurrences",
]
self.exceptions_columns = [
"Count",
"Message",
"Traceback",
"Nodes",
]
def _percentile_fields(self, stats_entry):
return (
[int(stats_entry.get_response_time_percentile(x) or 0) for x in self.percentiles_to_report]
if stats_entry.num_requests
else self.percentiles_na
)
def requests_csv(self, csv_writer):
csv_writer.writerow(self.requests_csv_columns)
self._requests_data_rows(csv_writer)
def _requests_data_rows(self, csv_writer):
stats = self.environment.stats
for stats_entry in chain(sort_stats(stats.entries), [stats.total]):
csv_writer.writerow(
chain(
[
stats_entry.method,
stats_entry.name,
stats_entry.num_requests,
stats_entry.num_failures,
stats_entry.median_response_time,
stats_entry.avg_response_time,
stats_entry.min_response_time or 0,
stats_entry.max_response_time,
stats_entry.avg_content_length,
stats_entry.total_rps,
stats_entry.total_fail_per_sec,
],
self._percentile_fields(stats_entry),
)
)
def failures_csv(self, csv_writer):
csv_writer.writerow(self.failures_columns)
self._failures_data_rows(csv_writer)
def _failures_data_rows(self, csv_writer):
for stats_error in sort_stats(self.environment.stats.errors):
csv_writer.writerow(
[
stats_error.method,
stats_error.name,
stats_error.error,
stats_error.occurrences,
]
)
def exceptions_csv(self, csv_writer):
csv_writer.writerow(self.exceptions_columns)
self._exceptions_data_rows(csv_writer)
def _exceptions_data_rows(self, csv_writer):
for exc in self.environment.runner.exceptions.values():
csv_writer.writerow(
[
exc["count"],
exc["msg"],
exc["traceback"],
", ".join(exc["nodes"])
]
)
class StatsCSVFileWriter(StatsCSV):
def __init__(self, environment, percentiles_to_report, base_filepath, full_history=False):
super().__init__(environment, percentiles_to_report)
self.base_filepath = base_filepath
self.full_history = full_history
self.requests_csv_filehandle = open(self.base_filepath + "_stats.csv", "w")
self.requests_csv_writer = csv.writer(self.requests_csv_filehandle)
self.stats_history_csv_filehandle = open(self.stats_history_file_name(), "w")
self.stats_history_csv_writer = csv.writer(self.stats_history_csv_filehandle)
self.failures_csv_filehandle = open(self.base_filepath + "_failures.csv", "w")
self.failures_csv_writer = csv.writer(self.failures_csv_filehandle)
self.failures_csv_data_start = 0
self.exceptions_csv_filehandle = open(self.base_filepath + "_exceptions.csv", "w")
self.exceptions_csv_writer = csv.writer(self.exceptions_csv_filehandle)
self.exceptions_csv_data_start = 0
self.stats_history_csv_columns = [
"Timestamp",
"User Count",
"Type",
"Name",
"Requests/s",
"Failures/s",
*get_readable_percentiles(self.percentiles_to_report),
"Total Request Count",
"Total Failure Count",
"Total Median Response Time",
"Total Average Response Time",
"Total Min Response Time",
"Total Max Response Time",
"Total Average Content Size",
]
def __call__(self):
self.stats_writer()
def stats_writer(self):
# Write header row for all files and save position for non-append files
self.requests_csv_writer.writerow(self.requests_csv_columns)
requests_csv_data_start = self.requests_csv_filehandle.tell()
self.stats_history_csv_writer.writerow(self.stats_history_csv_columns)
self.failures_csv_writer.writerow(self.failures_columns)
self.failures_csv_data_start = self.failures_csv_filehandle.tell()
self.exceptions_csv_writer.writerow(self.exceptions_columns)
self.exceptions_csv_data_start = self.exceptions_csv_filehandle.tell()
# Continuously write date rows for all files
last_flush_time = 0
while True:
now = time.time()
self.requests_csv_filehandle.seek(requests_csv_data_start)
self._requests_data_rows(self.requests_csv_writer)
self.requests_csv_filehandle.truncate()
self._stats_history_data_rows(self.stats_history_csv_writer, now)
self.failures_csv_filehandle.seek(self.failures_csv_data_start)
self._failures_data_rows(self.failures_csv_writer)
self.failures_csv_filehandle.truncate()
self.exceptions_csv_filehandle.seek((self.exceptions_csv_data_start))
self._exceptions_data_rows(self.exceptions_csv_writer)
self.exceptions_csv_filehandle.truncate()
if now - last_flush_time > CSV_STATS_FLUSH_INTERVAL_SEC:
self.requests_flush()
self.stats_history_flush()
self.failures_flush()
self.exceptions_flush()
last_flush_time = now
gevent.sleep(CSV_STATS_INTERVAL_SEC)
def _stats_history_data_rows(self, csv_writer, now):
stats = self.environment.stats
timestamp = int(now)
stats_entries = []
if self.full_history:
stats_entries = sort_stats(stats.entries)
for stats_entry in chain(stats_entries, [stats.total]):
csv_writer.writerow(
chain(
(
timestamp,
self.environment.runner.user_count,
stats_entry.method or "",
stats_entry.name,
f"{stats_entry.current_rps:2f}",
f"{stats_entry.current_fail_per_sec:2f}",
),
self._percentile_fields(stats_entry),
(
stats_entry.num_requests,
stats_entry.num_failures,
stats_entry.median_response_time,
stats_entry.avg_response_time,
stats_entry.min_response_time or 0,
stats_entry.max_response_time,
stats_entry.avg_content_length,
),
)
)
def requests_flush(self):
self.requests_csv_filehandle.flush()
def stats_history_flush(self):
self.stats_history_csv_filehandle.flush()
def failures_flush(self):
self.failures_csv_filehandle.flush()
def exceptions_flush(self):
self.exceptions_csv_filehandle.flush()
def close_files(self):
self.requests_csv_filehandle.close()
self.stats_history_csv_filehandle.close()
self.failures_csv_filehandle.close()
self.exceptions_csv_filehandle.close()
def stats_history_file_name(self):
return self.base_filepath + "_stats_history.csv"
| true | true |
f7283271316cefc390f77373b1c822358d1536f2 | 24,260 | py | Python | src/c4/cmany/build.py | biojppm/cmany | b20c24169d60077122ae29a0c09526913340fd5c | [
"MIT"
] | 20 | 2017-05-17T18:43:08.000Z | 2021-02-13T16:20:53.000Z | src/c4/cmany/build.py | biojppm/cmany | b20c24169d60077122ae29a0c09526913340fd5c | [
"MIT"
] | 8 | 2017-06-04T17:01:06.000Z | 2022-03-17T12:43:32.000Z | src/c4/cmany/build.py | biojppm/cmany | b20c24169d60077122ae29a0c09526913340fd5c | [
"MIT"
] | 1 | 2017-06-04T13:09:19.000Z | 2017-06-04T13:09:19.000Z | import os
import copy
import re
import dill
import subprocess
from datetime import datetime
from collections import OrderedDict as odict
from .generator import Generator
from . import util, cmake, vsinfo
from .named_item import NamedItem
from .variant import Variant
from .build_flags import BuildFlags
from .compiler import Compiler
from .architecture import Architecture
from . import err
from .util import logdbg as dbg
# experimental. I don't think it will stay unless conan starts accepting args
from .conan import Conan
# -----------------------------------------------------------------------------
class Build(NamedItem):
"""Holds a build's settings"""
pfile = "cmany_preload.cmake"
sfile = "cmany_build.dill"
def __init__(self, proj_root, build_root, install_root,
system, arch, build_type, compiler, variant, flags,
num_jobs, kwargs):
#
self.kwargs = kwargs
self.export_compile = self.kwargs.get('export_compile', True)
#
self.projdir = util.chkf(proj_root)
self.buildroot = util.abspath(build_root)
self.installroot = util.abspath(install_root)
#
self.flags = flags
self.system = system
self.architecture = arch
self.build_type = build_type
self.compiler = compiler
self.variant = variant
#
self.adjusted = False
#
if util.in_64bit and self.architecture.is32:
if self.compiler.gcclike:
dbg("making 32 bit")
self.compiler.make_32bit()
elif util.in_32bit and self.architecture.is64:
if self.compiler.gcclike:
dbg("making 64 bit")
self.compiler.make_64bit()
#
tag = self._set_name_and_paths()
super().__init__(tag)
#
self.toolchain_file = self._get_toolchain()
if self.toolchain_file:
comps = cmake.extract_toolchain_compilers(self.toolchain_file)
c = Compiler(comps['CMAKE_CXX_COMPILER'])
self.adjust(compiler=c)
#
# WATCHOUT: this may trigger a readjustment of this build's parameters
self.generator = self.create_generator(num_jobs)
#
# This will load the vars from the builddir cache, if it exists.
# It should be done only after creating the generator.
self.varcache = cmake.CMakeCache(self.builddir)
# ... and this will overwrite (in memory) the vars with the input
# arguments. This will make the cache dirty and so we know when it
# needs to be committed back to CMakeCache.txt
self.gather_input_cache_vars()
#
self.deps = kwargs.get('deps', '')
if self.deps and not os.path.isabs(self.deps):
self.deps = os.path.abspath(self.deps)
self.deps_prefix = kwargs.get('deps_prefix')
if self.deps_prefix and not os.path.isabs(self.deps_prefix):
self.deps_prefix = os.path.abspath(self.deps_prefix)
if not self.deps_prefix:
self.deps_prefix = self.builddir
def _set_name_and_paths(self):
self.tag = __class__.get_tag(
self.system, self.architecture,
self.compiler, self.build_type, self.variant, '-')
self.buildtag = self.tag
self.installtag = self.tag # this was different in the past and may become so in the future
self.builddir = os.path.join(self.buildroot, self.buildtag)
self.installdir = os.path.join(self.installroot, self.installtag)
self.preload_file = os.path.join(self.builddir, Build.pfile)
self.cachefile = os.path.join(self.builddir, 'CMakeCache.txt')
for prop in "projdir buildroot installroot buildtag installtag builddir installdir preload_file cachefile".split(" "):
dbg(" {}: {}={}".format(self.tag, prop, getattr(self, prop)))
return self.tag
def create_generator(self, num_jobs, fallback_generator="Unix Makefiles"):
"""create a generator, adjusting the build parameters if necessary"""
#if self.toolchain_file is not None:
# toolchain_cache = cmake.get_toolchain_cache(self.toolchain_file)
# print(toolchain_cache)
# self.adjust(compiler=toolchain_cache['CMAKE_CXX_COMPILER'])
if self.compiler.is_msvc:
vsi = vsinfo.VisualStudioInfo(self.compiler.name)
g = Generator(vsi.gen, self, num_jobs)
arch = Architecture(vsi.architecture)
self.adjust(architecture=arch)
self.vsinfo = vsi
return g
else:
if self.system.name == "windows":
return Generator(fallback_generator, self, num_jobs)
else:
return Generator(Generator.default_str(), self, num_jobs)
def adjust(self, **kwargs):
for k, _ in kwargs.items():
supported = ('architecture', 'compiler')
if k not in supported:
raise err.NoSupport(f"build adjustment for {k}. Must be one of {supported}")
a = kwargs.get('architecture')
if a and a != self.architecture:
dbg(self, "adjusting architecture:", self.architecture, "---->", a)
self.adjusted = True
self.architecture = a
c = kwargs.get('compiler')
if c and c != self.compiler:
dbg(self, "adjusting compiler:", self.compiler, "---->", a)
self.adjusted = True
self.compiler = c
self._set_name_and_paths()
@staticmethod
def get_tag(s, a, c, t, v, sep='-'):
# some utilities (eg, ar) dont deal well with + in the path
# so replace + with x
# eg see https://sourceforge.net/p/mingw/bugs/1429/
sc = __class__.sanitize_compiler_name(c)
s = str(s) + sep + str(a) + sep + sc + sep + str(t)
if v is not None and isinstance(v, Variant):
v = v.name
if v and v != "none":
s += "{sep}{var}".format(sep=sep, var=str(v))
return s
@staticmethod
def sanitize_compiler_name(c):
sc = re.sub(r'\+', 'x', str(c))
return sc
def create_dir(self):
if not os.path.exists(self.builddir):
os.makedirs(self.builddir)
def _serialize(self):
# https://stackoverflow.com/questions/4529815/saving-an-object-data-persistence
protocol = 0 # serialize in ASCII
fn = os.path.join(self.builddir, __class__.sfile)
with open(fn, 'wb') as f:
dill.dump(self, f, protocol)
@staticmethod
def deserialize(builddir):
# https://stackoverflow.com/questions/4529815/saving-an-object-data-persistence
if not os.path.exists(builddir):
raise err.BuildDirNotFound(builddir)
fn = os.path.join(builddir, __class__.sfile)
if not os.path.exists(fn):
raise err.BuildSerializationNotFound(fn, builddir)
with open(fn, 'rb') as f:
return dill.load(f)
def configure_cmd(self, for_json=False):
if for_json:
return ('-C ' + self.preload_file
+ ' ' + self.generator.configure_args(for_json=for_json))
cmd = (['cmake', '-C', self.preload_file]
+ self.generator.configure_args(export_compile_commands=self.export_compile))
if self.toolchain_file:
cmd.append('-DCMAKE_TOOLCHAIN_FILE=' + self.toolchain_file)
cmd.append(self.projdir)
return cmd
def configure(self):
self.create_dir()
self.create_preload_file()
self.handle_deps()
if self.needs_cache_regeneration():
self.varcache.commit(self.builddir)
with util.setcwd(self.builddir, silent=False):
cmd = self.configure_cmd()
try:
util.runsyscmd(cmd)
self.mark_configure_done(cmd)
except Exception as e:
raise err.ConfigureFailed(self, cmd, e)
if self.export_compile:
if not self.generator.exports_compile_commands:
util.logwarn("WARNING: this generator cannot export compile commands. Use 'cmany export_compile_commands/xcc to export the compile commands.'")
def export_compile_commands(self):
# some generators (notably VS/msbuild) cannot export compile
# commands, so to get that, we'll configure a second build using the
# ninja generator so that compile_commands.json is generated;
# finally, copy over that file to this build directory
if self.needs_configure():
self.configure()
trickdir = os.path.join(self.builddir, '.export_compile_commands')
if not os.path.exists(trickdir):
os.makedirs(trickdir)
with util.setcwd(trickdir, silent=False):
cmd = ['cmake', '-G', 'Ninja', '-DCMAKE_EXPORT_COMPILE_COMMANDS=ON', '-C', self.preload_file, self.projdir]
try:
if not self.compiler.is_msvc:
util.runsyscmd(cmd)
else:
self.vsinfo.runsyscmd(cmd)
except Exception as e:
raise err.ConfigureFailed(self, cmd, e)
src = os.path.join(trickdir, "compile_commands.json")
dst = os.path.join(self.builddir, "compile_commands.json")
if os.path.exists(src):
from shutil import copyfile
if os.path.exists(dst):
os.remove(dst)
copyfile(src, dst)
util.loginfo("exported compile_commands.json:", dst)
def run_custom_cmd(self, cmd, **subprocess_args):
try:
util.runcmd(cmd, **subprocess_args, cwd=self.builddir)
except subprocess.CalledProcessError as exc:
raise err.RunCmdFailed(self, cmd, exc)
def reconfigure(self):
"""reconfigure a build directory, without touching any cache entry"""
self._check_successful_configure('reconfigure')
with util.setcwd(self.builddir, silent=False):
cmd = ['cmake', self.projdir]
try:
util.runsyscmd(cmd)
except Exception as e:
raise err.ConfigureFailed(self, cmd, e)
def _check_successful_configure(self, purpose):
if not os.path.exists(self.builddir):
raise err.BuildDirNotFound(self.builddir, purpose)
if not os.path.exists(self.varcache.cache_file):
raise err.CacheFileNotFound(self.varcache.cache_file, self.builddir, purpose)
pkf = os.path.join(self.builddir, __class__.sfile)
if not os.path.exists(pkf):
raise err.BuildSerializationNotFound(pkf, self.builddir)
def mark_configure_done(self, cmd):
self._serialize()
with util.setcwd(self.builddir):
with open("cmany_configure.done", "w") as f:
f.write(" ".join(cmd) + "\n")
def needs_configure(self):
if not os.path.exists(self.builddir):
return True
with util.setcwd(self.builddir):
if not os.path.exists("cmany_configure.done"):
return True
if self.needs_cache_regeneration():
return True
return False
def needs_cache_regeneration(self):
if os.path.exists(self.cachefile) and self.varcache.dirty:
return True
return False
def build(self, targets=[]):
self.create_dir()
with util.setcwd(self.builddir, silent=False):
if self.needs_configure():
self.configure()
self.handle_deps()
if len(targets) == 0:
if self.compiler.is_msvc:
targets = ["ALL_BUILD"]
else:
targets = ["all"]
# cmake --build and visual studio won't handle
# multiple targets at once, so loop over them.
for t in targets:
try:
cmd = self.generator.cmd([t])
util.runsyscmd(cmd)
except Exception as e:
raise err.CompileFailed(self, cmd, e)
# this was written before using the loop above.
# it can come to fail in some corner cases.
self.mark_build_done(cmd)
def rebuild(self, targets=[]):
self._check_successful_configure('rebuild')
with util.setcwd(self.builddir, silent=False):
if len(targets) == 0:
if self.compiler.is_msvc:
targets = ["ALL_BUILD"]
else:
targets = ["all"]
# cmake --build and visual studio won't handle
# multiple targets at once, so loop over them.
for t in targets:
cmd = self.generator.cmd([t])
try:
util.runsyscmd(cmd)
except Exception as e:
raise err.CompileFailed(self, cmd, e)
def mark_build_done(self, cmd):
with util.setcwd(self.builddir):
with open("cmany_build.done", "w") as f:
f.write(" ".join(cmd) + "\n")
def needs_build(self):
if not os.path.exists(self.builddir):
return True
with util.setcwd(self.builddir):
if not os.path.exists("cmany_build.done"):
return True
if self.needs_cache_regeneration():
return True
return False
def install(self):
self.create_dir()
with util.setcwd(self.builddir, silent=False):
if self.needs_build():
self.build()
cmd = self.generator.install()
try:
util.runsyscmd(cmd)
except Exception as e:
raise err.InstallFailed(self, cmd, e)
def reinstall(self):
self._check_successful_configure('reinstall')
with util.setcwd(self.builddir, silent=False):
if self.needs_build():
self.build()
cmd = self.generator.install()
try:
util.runsyscmd(cmd)
except Exception as e:
raise err.InstallFailed(self, cmd, e)
def clean(self):
self.create_dir()
with util.setcwd(self.builddir):
cmd = self.generator.cmd(['clean'])
util.runsyscmd(cmd)
os.remove("cmany_build.done")
def _get_flagseq(self):
return (
self.flags,
self.system.flags,
self.architecture.flags,
self.compiler.flags,
self.build_type.flags,
self.variant.flags
)
def _get_toolchain(self):
tc = None
for fs in self._get_flagseq():
tc = BuildFlags.merge_toolchains(tc, fs.toolchain)
if not tc:
return None
if not os.path.isabs(tc):
tc = os.path.join(os.getcwd(), tc)
tc = os.path.abspath(tc)
if not os.path.exists(tc):
raise err.ToolchainFileNotFound(tc)
return tc
def _gather_flags(self, which, append_to_sysinfo_var=None, with_defines=False):
flags = []
if append_to_sysinfo_var:
try:
flags = [cmake.CMakeSysInfo.var(append_to_sysinfo_var, self.generator)]
except RuntimeError:
pass
# append overall build flags
# append variant flags
flagseq = self._get_flagseq()
for fs in flagseq:
wf = getattr(fs, which)
for f in wf:
if isinstance(f, str):
r = f
elif isinstance(f, CFlag):
r = f.get(self.compiler)
flags.append(r)
if with_defines:
flags += fs.defines
# we're done
return flags
def _gather_cmake_vars(self):
flagseq = self._get_flagseq()
for fs in flagseq:
for v in fs.cmake_vars:
spl = v.split('=')
vval = ''.join(spl[1:]) if len(spl) > 1 else ''
nspl = spl[0].split(':')
if len(nspl) == 1:
self.varcache.setvar(nspl[0], vval, from_input=True)
elif len(nspl) == 2:
self.varcache.setvar(nspl[0], vval, nspl[1], from_input=True)
else:
raise err.Error('could not parse variable specification: {}', v)
def gather_input_cache_vars(self):
self._gather_cmake_vars()
vc = self.varcache
#
def _set(pfn, pname, pval): pfn(pname, pval, from_input=True)
if (not self.generator.is_msvc) and (not self.toolchain_file):
_set(vc.f, 'CMAKE_C_COMPILER', self.compiler.c_compiler)
_set(vc.f, 'CMAKE_CXX_COMPILER', self.compiler.path)
_set(vc.s, 'CMAKE_BUILD_TYPE', str(self.build_type))
_set(vc.p, 'CMAKE_INSTALL_PREFIX', self.installdir)
#
cflags = self._gather_flags('cflags', 'CMAKE_C_FLAGS_INIT', with_defines=True)
if cflags:
_set(vc.s, 'CMAKE_C_FLAGS', ' '.join(cflags))
#
cxxflags = self._gather_flags('cxxflags', 'CMAKE_CXX_FLAGS_INIT', with_defines=True)
if cxxflags:
_set(vc.s, 'CMAKE_CXX_FLAGS', ' '.join(cxxflags))
#
# if self.flags.include_dirs:
# _set(vc.s, 'CMANY_INCLUDE_DIRECTORIES', ';'.join(self.flags.include_dirs))
#
# if self.flags.link_dirs:
# _set(vc.s, 'CMAKE_LINK_DIRECTORIES', ';'.join(self.flags.link_dirs))
#
def create_preload_file(self):
# http://stackoverflow.com/questions/17597673/cmake-preload-script-for-cache
self.create_dir()
lines = []
s = '_cmany_set({} "{}" {})'
for _, v in self.varcache.items():
if v.from_input:
lines.append(s.format(v.name, v.val, v.vartype))
if lines:
tpl = _preload_file_tpl
else:
tpl = _preload_file_tpl_empty
now = datetime.now().strftime("%Y/%m/%d %H:%m")
txt = tpl.format(date=now, vars="\n".join(lines))
with open(self.preload_file, "w") as f:
f.write(txt)
return self.preload_file
@property
def deps_done(self):
dmark = os.path.join(self.builddir, "cmany_deps.done")
exists = os.path.exists(dmark)
return exists
def mark_deps_done(self):
with util.setcwd(self.builddir):
with open("cmany_deps.done", "w") as f:
s = ''
if self.deps:
s += self.deps + '\n'
if self.deps_prefix:
s += self.deps_prefix + '\n'
f.write(s)
def handle_deps(self):
if self.deps_done:
return
if not self.deps:
self.handle_conan()
self.mark_deps_done()
return
util.lognotice(self.tag + ': building dependencies', self.deps)
dup = copy.copy(self)
dup.builddir = os.path.join(self.builddir, 'cmany_deps-build')
dup.installdir = self.deps_prefix
util.logwarn('installdir:', dup.installdir)
dup.projdir = self.deps
dup.preload_file = os.path.join(self.builddir, self.preload_file)
dup.deps = None
dup.generator.build = dup
dup.configure()
dup.build()
try:
# if the dependencies cmake project is purely consisted of
# external projects, there won't be an install target.
dup.install()
except Exception as e:
util.logwarn(self.name + ": could not install. Maybe there's no install target?")
util.logdone(self.name + ': finished building dependencies. Install dir=', self.installdir)
self.varcache.p('CMAKE_PREFIX_PATH', self.installdir)
self.mark_deps_done()
def handle_conan(self):
if not self.kwargs.get('with_conan'):
return
doit = False
f = None
for fn in ('conanfile.py', 'conanfile.txt'):
f = os.path.join(self.projdir, fn)
cf = os.path.join(self.builddir, 'conanbuildinfo.cmake')
if os.path.exists(f) and not os.path.exists(cf):
doit = True
break
if not doit:
return
util.logdone('found conan file')
c = Conan()
c.install(self)
def json_data(self):
"""
https://blogs.msdn.microsoft.com/vcblog/2016/11/16/cmake-support-in-visual-studio-the-visual-studio-2017-rc-update/
https://blogs.msdn.microsoft.com/vcblog/2016/12/20/cmake-support-in-visual-studio-2017-whats-new-in-the-rc-update/
"""
builddir = self.builddir.replace(self.projdir, '${projectDir}')
builddir = re.sub(r'\\', r'/', builddir)
return odict([
('name', self.tag),
('generator', self.generator.name),
('configurationType', self.build_type.name),
('buildRoot', builddir),
('cmakeCommandArgs', self.configure_cmd(for_json=True)),
# ('variables', []), # this is not needed since the vars are set in the preload file
])
def get_targets(self):
with util.setcwd(self.builddir):
if self.generator.is_msvc:
# each target in MSVC has a corresponding vcxproj file
files = list(util.find_files_with_ext(self.builddir, ".vcxproj"))
files = [os.path.basename(f) for f in files]
files = [os.path.splitext(f)[0] for f in files]
return files
elif self.generator.is_makefile:
output = util.runsyscmd(["make", "help"], echo_cmd=False,
echo_output=False, capture_output=True)
output = output.split("\n")
output = output[1:] # The following are some of the valid targets....
output = [o[4:] for o in output] # take off the initial "... "
output = [re.sub(r'(.*)\ \(the default if no target.*\)', r'\1', o) for o in output]
output = sorted(output)
result = []
for o in output:
if o:
result.append(o)
return result
else:
util.logerr("sorry, feature not implemented for this generator: " +
str(self.generator))
def show_properties(self):
util.logcmd(self.name)
def p(n, v): print("{}={}".format(n, v))
if self.toolchain_file:
p('CMAKE_TOOLCHAIN_FILE', self.toolchain_file)
p('CMAKE_C_COMPILER', self.compiler.c_compiler)
p('CMAKE_CXX_COMPILER', self.compiler.path)
dont_show = ('CMAKE_INSTALL_PREFIX', 'CMAKE_CXX_COMPILER', 'CMAKE_C_COMPILER')
for _, v in self.varcache.items():
if v.from_input:
if v.name in dont_show:
continue
p(v.name, v.val)
p("PROJECT_BINARY_DIR", self.builddir)
p("CMAKE_INSTALL_PREFIX", self.installdir)
# -----------------------------------------------------------------------------
_preload_file_tpl = ("""\
# Do not edit. Will be overwritten.
# Generated by cmany on {date}
if(NOT _cmany_set_def)
set(_cmany_set_def ON)
function(_cmany_set var value type)
set(${{var}} "${{value}}" CACHE ${{type}} "")
message(STATUS "cmany: ${{var}}=${{value}}")
endfunction(_cmany_set)
endif(NOT _cmany_set_def)
message(STATUS "cmany:preload----------------------")
{vars}
message(STATUS "cmany:preload----------------------")
# if(CMANY_INCLUDE_DIRECTORIES)
# include_directories(${{CMANY_INCLUDE_DIRECTORIES}})
# endif()
#
# if(CMANY_LINK_DIRECTORIES)
# link_directories(${{CMANY_LINK_DIRECTORIES}})
# endif()
# Do not edit. Will be overwritten.
# Generated by cmany on {date}
""")
# -----------------------------------------------------------------------------
_preload_file_tpl_empty = ("""\
# Do not edit. Will be overwritten.
# Generated by cmany on {date}
message(STATUS "cmany: nothing to preload...")
""")
| 38.94061 | 159 | 0.571805 | import os
import copy
import re
import dill
import subprocess
from datetime import datetime
from collections import OrderedDict as odict
from .generator import Generator
from . import util, cmake, vsinfo
from .named_item import NamedItem
from .variant import Variant
from .build_flags import BuildFlags
from .compiler import Compiler
from .architecture import Architecture
from . import err
from .util import logdbg as dbg
from .conan import Conan
# -----------------------------------------------------------------------------
class Build(NamedItem):
pfile = "cmany_preload.cmake"
sfile = "cmany_build.dill"
def __init__(self, proj_root, build_root, install_root,
system, arch, build_type, compiler, variant, flags,
num_jobs, kwargs):
#
self.kwargs = kwargs
self.export_compile = self.kwargs.get('export_compile', True)
#
self.projdir = util.chkf(proj_root)
self.buildroot = util.abspath(build_root)
self.installroot = util.abspath(install_root)
#
self.flags = flags
self.system = system
self.architecture = arch
self.build_type = build_type
self.compiler = compiler
self.variant = variant
#
self.adjusted = False
#
if util.in_64bit and self.architecture.is32:
if self.compiler.gcclike:
dbg("making 32 bit")
self.compiler.make_32bit()
elif util.in_32bit and self.architecture.is64:
if self.compiler.gcclike:
dbg("making 64 bit")
self.compiler.make_64bit()
#
tag = self._set_name_and_paths()
super().__init__(tag)
#
self.toolchain_file = self._get_toolchain()
if self.toolchain_file:
comps = cmake.extract_toolchain_compilers(self.toolchain_file)
c = Compiler(comps['CMAKE_CXX_COMPILER'])
self.adjust(compiler=c)
#
# WATCHOUT: this may trigger a readjustment of this build's parameters
self.generator = self.create_generator(num_jobs)
self.varcache = cmake.CMakeCache(self.builddir)
self.gather_input_cache_vars()
self.deps = kwargs.get('deps', '')
if self.deps and not os.path.isabs(self.deps):
self.deps = os.path.abspath(self.deps)
self.deps_prefix = kwargs.get('deps_prefix')
if self.deps_prefix and not os.path.isabs(self.deps_prefix):
self.deps_prefix = os.path.abspath(self.deps_prefix)
if not self.deps_prefix:
self.deps_prefix = self.builddir
def _set_name_and_paths(self):
self.tag = __class__.get_tag(
self.system, self.architecture,
self.compiler, self.build_type, self.variant, '-')
self.buildtag = self.tag
self.installtag = self.tag
self.builddir = os.path.join(self.buildroot, self.buildtag)
self.installdir = os.path.join(self.installroot, self.installtag)
self.preload_file = os.path.join(self.builddir, Build.pfile)
self.cachefile = os.path.join(self.builddir, 'CMakeCache.txt')
for prop in "projdir buildroot installroot buildtag installtag builddir installdir preload_file cachefile".split(" "):
dbg(" {}: {}={}".format(self.tag, prop, getattr(self, prop)))
return self.tag
def create_generator(self, num_jobs, fallback_generator="Unix Makefiles"):
if self.compiler.is_msvc:
vsi = vsinfo.VisualStudioInfo(self.compiler.name)
g = Generator(vsi.gen, self, num_jobs)
arch = Architecture(vsi.architecture)
self.adjust(architecture=arch)
self.vsinfo = vsi
return g
else:
if self.system.name == "windows":
return Generator(fallback_generator, self, num_jobs)
else:
return Generator(Generator.default_str(), self, num_jobs)
def adjust(self, **kwargs):
for k, _ in kwargs.items():
supported = ('architecture', 'compiler')
if k not in supported:
raise err.NoSupport(f"build adjustment for {k}. Must be one of {supported}")
a = kwargs.get('architecture')
if a and a != self.architecture:
dbg(self, "adjusting architecture:", self.architecture, "---->", a)
self.adjusted = True
self.architecture = a
c = kwargs.get('compiler')
if c and c != self.compiler:
dbg(self, "adjusting compiler:", self.compiler, "---->", a)
self.adjusted = True
self.compiler = c
self._set_name_and_paths()
@staticmethod
def get_tag(s, a, c, t, v, sep='-'):
sc = __class__.sanitize_compiler_name(c)
s = str(s) + sep + str(a) + sep + sc + sep + str(t)
if v is not None and isinstance(v, Variant):
v = v.name
if v and v != "none":
s += "{sep}{var}".format(sep=sep, var=str(v))
return s
@staticmethod
def sanitize_compiler_name(c):
sc = re.sub(r'\+', 'x', str(c))
return sc
def create_dir(self):
if not os.path.exists(self.builddir):
os.makedirs(self.builddir)
def _serialize(self):
protocol = 0
fn = os.path.join(self.builddir, __class__.sfile)
with open(fn, 'wb') as f:
dill.dump(self, f, protocol)
@staticmethod
def deserialize(builddir):
if not os.path.exists(builddir):
raise err.BuildDirNotFound(builddir)
fn = os.path.join(builddir, __class__.sfile)
if not os.path.exists(fn):
raise err.BuildSerializationNotFound(fn, builddir)
with open(fn, 'rb') as f:
return dill.load(f)
def configure_cmd(self, for_json=False):
if for_json:
return ('-C ' + self.preload_file
+ ' ' + self.generator.configure_args(for_json=for_json))
cmd = (['cmake', '-C', self.preload_file]
+ self.generator.configure_args(export_compile_commands=self.export_compile))
if self.toolchain_file:
cmd.append('-DCMAKE_TOOLCHAIN_FILE=' + self.toolchain_file)
cmd.append(self.projdir)
return cmd
def configure(self):
self.create_dir()
self.create_preload_file()
self.handle_deps()
if self.needs_cache_regeneration():
self.varcache.commit(self.builddir)
with util.setcwd(self.builddir, silent=False):
cmd = self.configure_cmd()
try:
util.runsyscmd(cmd)
self.mark_configure_done(cmd)
except Exception as e:
raise err.ConfigureFailed(self, cmd, e)
if self.export_compile:
if not self.generator.exports_compile_commands:
util.logwarn("WARNING: this generator cannot export compile commands. Use 'cmany export_compile_commands/xcc to export the compile commands.'")
def export_compile_commands(self):
# ninja generator so that compile_commands.json is generated;
# finally, copy over that file to this build directory
if self.needs_configure():
self.configure()
trickdir = os.path.join(self.builddir, '.export_compile_commands')
if not os.path.exists(trickdir):
os.makedirs(trickdir)
with util.setcwd(trickdir, silent=False):
cmd = ['cmake', '-G', 'Ninja', '-DCMAKE_EXPORT_COMPILE_COMMANDS=ON', '-C', self.preload_file, self.projdir]
try:
if not self.compiler.is_msvc:
util.runsyscmd(cmd)
else:
self.vsinfo.runsyscmd(cmd)
except Exception as e:
raise err.ConfigureFailed(self, cmd, e)
src = os.path.join(trickdir, "compile_commands.json")
dst = os.path.join(self.builddir, "compile_commands.json")
if os.path.exists(src):
from shutil import copyfile
if os.path.exists(dst):
os.remove(dst)
copyfile(src, dst)
util.loginfo("exported compile_commands.json:", dst)
def run_custom_cmd(self, cmd, **subprocess_args):
try:
util.runcmd(cmd, **subprocess_args, cwd=self.builddir)
except subprocess.CalledProcessError as exc:
raise err.RunCmdFailed(self, cmd, exc)
def reconfigure(self):
self._check_successful_configure('reconfigure')
with util.setcwd(self.builddir, silent=False):
cmd = ['cmake', self.projdir]
try:
util.runsyscmd(cmd)
except Exception as e:
raise err.ConfigureFailed(self, cmd, e)
def _check_successful_configure(self, purpose):
if not os.path.exists(self.builddir):
raise err.BuildDirNotFound(self.builddir, purpose)
if not os.path.exists(self.varcache.cache_file):
raise err.CacheFileNotFound(self.varcache.cache_file, self.builddir, purpose)
pkf = os.path.join(self.builddir, __class__.sfile)
if not os.path.exists(pkf):
raise err.BuildSerializationNotFound(pkf, self.builddir)
def mark_configure_done(self, cmd):
self._serialize()
with util.setcwd(self.builddir):
with open("cmany_configure.done", "w") as f:
f.write(" ".join(cmd) + "\n")
def needs_configure(self):
if not os.path.exists(self.builddir):
return True
with util.setcwd(self.builddir):
if not os.path.exists("cmany_configure.done"):
return True
if self.needs_cache_regeneration():
return True
return False
def needs_cache_regeneration(self):
if os.path.exists(self.cachefile) and self.varcache.dirty:
return True
return False
def build(self, targets=[]):
self.create_dir()
with util.setcwd(self.builddir, silent=False):
if self.needs_configure():
self.configure()
self.handle_deps()
if len(targets) == 0:
if self.compiler.is_msvc:
targets = ["ALL_BUILD"]
else:
targets = ["all"]
# cmake --build and visual studio won't handle
for t in targets:
try:
cmd = self.generator.cmd([t])
util.runsyscmd(cmd)
except Exception as e:
raise err.CompileFailed(self, cmd, e)
self.mark_build_done(cmd)
def rebuild(self, targets=[]):
self._check_successful_configure('rebuild')
with util.setcwd(self.builddir, silent=False):
if len(targets) == 0:
if self.compiler.is_msvc:
targets = ["ALL_BUILD"]
else:
targets = ["all"]
# multiple targets at once, so loop over them.
for t in targets:
cmd = self.generator.cmd([t])
try:
util.runsyscmd(cmd)
except Exception as e:
raise err.CompileFailed(self, cmd, e)
def mark_build_done(self, cmd):
with util.setcwd(self.builddir):
with open("cmany_build.done", "w") as f:
f.write(" ".join(cmd) + "\n")
def needs_build(self):
if not os.path.exists(self.builddir):
return True
with util.setcwd(self.builddir):
if not os.path.exists("cmany_build.done"):
return True
if self.needs_cache_regeneration():
return True
return False
def install(self):
self.create_dir()
with util.setcwd(self.builddir, silent=False):
if self.needs_build():
self.build()
cmd = self.generator.install()
try:
util.runsyscmd(cmd)
except Exception as e:
raise err.InstallFailed(self, cmd, e)
def reinstall(self):
self._check_successful_configure('reinstall')
with util.setcwd(self.builddir, silent=False):
if self.needs_build():
self.build()
cmd = self.generator.install()
try:
util.runsyscmd(cmd)
except Exception as e:
raise err.InstallFailed(self, cmd, e)
def clean(self):
self.create_dir()
with util.setcwd(self.builddir):
cmd = self.generator.cmd(['clean'])
util.runsyscmd(cmd)
os.remove("cmany_build.done")
def _get_flagseq(self):
return (
self.flags,
self.system.flags,
self.architecture.flags,
self.compiler.flags,
self.build_type.flags,
self.variant.flags
)
def _get_toolchain(self):
tc = None
for fs in self._get_flagseq():
tc = BuildFlags.merge_toolchains(tc, fs.toolchain)
if not tc:
return None
if not os.path.isabs(tc):
tc = os.path.join(os.getcwd(), tc)
tc = os.path.abspath(tc)
if not os.path.exists(tc):
raise err.ToolchainFileNotFound(tc)
return tc
def _gather_flags(self, which, append_to_sysinfo_var=None, with_defines=False):
flags = []
if append_to_sysinfo_var:
try:
flags = [cmake.CMakeSysInfo.var(append_to_sysinfo_var, self.generator)]
except RuntimeError:
pass
# append overall build flags
# append variant flags
flagseq = self._get_flagseq()
for fs in flagseq:
wf = getattr(fs, which)
for f in wf:
if isinstance(f, str):
r = f
elif isinstance(f, CFlag):
r = f.get(self.compiler)
flags.append(r)
if with_defines:
flags += fs.defines
# we're done
return flags
def _gather_cmake_vars(self):
flagseq = self._get_flagseq()
for fs in flagseq:
for v in fs.cmake_vars:
spl = v.split('=')
vval = ''.join(spl[1:]) if len(spl) > 1 else ''
nspl = spl[0].split(':')
if len(nspl) == 1:
self.varcache.setvar(nspl[0], vval, from_input=True)
elif len(nspl) == 2:
self.varcache.setvar(nspl[0], vval, nspl[1], from_input=True)
else:
raise err.Error('could not parse variable specification: {}', v)
def gather_input_cache_vars(self):
self._gather_cmake_vars()
vc = self.varcache
def _set(pfn, pname, pval): pfn(pname, pval, from_input=True)
if (not self.generator.is_msvc) and (not self.toolchain_file):
_set(vc.f, 'CMAKE_C_COMPILER', self.compiler.c_compiler)
_set(vc.f, 'CMAKE_CXX_COMPILER', self.compiler.path)
_set(vc.s, 'CMAKE_BUILD_TYPE', str(self.build_type))
_set(vc.p, 'CMAKE_INSTALL_PREFIX', self.installdir)
cflags = self._gather_flags('cflags', 'CMAKE_C_FLAGS_INIT', with_defines=True)
if cflags:
_set(vc.s, 'CMAKE_C_FLAGS', ' '.join(cflags))
cxxflags = self._gather_flags('cxxflags', 'CMAKE_CXX_FLAGS_INIT', with_defines=True)
if cxxflags:
_set(vc.s, 'CMAKE_CXX_FLAGS', ' '.join(cxxflags))
def create_preload_file(self):
self.create_dir()
lines = []
s = '_cmany_set({} "{}" {})'
for _, v in self.varcache.items():
if v.from_input:
lines.append(s.format(v.name, v.val, v.vartype))
if lines:
tpl = _preload_file_tpl
else:
tpl = _preload_file_tpl_empty
now = datetime.now().strftime("%Y/%m/%d %H:%m")
txt = tpl.format(date=now, vars="\n".join(lines))
with open(self.preload_file, "w") as f:
f.write(txt)
return self.preload_file
@property
def deps_done(self):
dmark = os.path.join(self.builddir, "cmany_deps.done")
exists = os.path.exists(dmark)
return exists
def mark_deps_done(self):
with util.setcwd(self.builddir):
with open("cmany_deps.done", "w") as f:
s = ''
if self.deps:
s += self.deps + '\n'
if self.deps_prefix:
s += self.deps_prefix + '\n'
f.write(s)
def handle_deps(self):
if self.deps_done:
return
if not self.deps:
self.handle_conan()
self.mark_deps_done()
return
util.lognotice(self.tag + ': building dependencies', self.deps)
dup = copy.copy(self)
dup.builddir = os.path.join(self.builddir, 'cmany_deps-build')
dup.installdir = self.deps_prefix
util.logwarn('installdir:', dup.installdir)
dup.projdir = self.deps
dup.preload_file = os.path.join(self.builddir, self.preload_file)
dup.deps = None
dup.generator.build = dup
dup.configure()
dup.build()
try:
dup.install()
except Exception as e:
util.logwarn(self.name + ": could not install. Maybe there's no install target?")
util.logdone(self.name + ': finished building dependencies. Install dir=', self.installdir)
self.varcache.p('CMAKE_PREFIX_PATH', self.installdir)
self.mark_deps_done()
def handle_conan(self):
if not self.kwargs.get('with_conan'):
return
doit = False
f = None
for fn in ('conanfile.py', 'conanfile.txt'):
f = os.path.join(self.projdir, fn)
cf = os.path.join(self.builddir, 'conanbuildinfo.cmake')
if os.path.exists(f) and not os.path.exists(cf):
doit = True
break
if not doit:
return
util.logdone('found conan file')
c = Conan()
c.install(self)
def json_data(self):
builddir = self.builddir.replace(self.projdir, '${projectDir}')
builddir = re.sub(r'\\', r'/', builddir)
return odict([
('name', self.tag),
('generator', self.generator.name),
('configurationType', self.build_type.name),
('buildRoot', builddir),
('cmakeCommandArgs', self.configure_cmd(for_json=True)),
d(self.builddir):
if self.generator.is_msvc:
files = list(util.find_files_with_ext(self.builddir, ".vcxproj"))
files = [os.path.basename(f) for f in files]
files = [os.path.splitext(f)[0] for f in files]
return files
elif self.generator.is_makefile:
output = util.runsyscmd(["make", "help"], echo_cmd=False,
echo_output=False, capture_output=True)
output = output.split("\n")
output = output[1:]
output = [o[4:] for o in output]
output = [re.sub(r'(.*)\ \(the default if no target.*\)', r'\1', o) for o in output]
output = sorted(output)
result = []
for o in output:
if o:
result.append(o)
return result
else:
util.logerr("sorry, feature not implemented for this generator: " +
str(self.generator))
def show_properties(self):
util.logcmd(self.name)
def p(n, v): print("{}={}".format(n, v))
if self.toolchain_file:
p('CMAKE_TOOLCHAIN_FILE', self.toolchain_file)
p('CMAKE_C_COMPILER', self.compiler.c_compiler)
p('CMAKE_CXX_COMPILER', self.compiler.path)
dont_show = ('CMAKE_INSTALL_PREFIX', 'CMAKE_CXX_COMPILER', 'CMAKE_C_COMPILER')
for _, v in self.varcache.items():
if v.from_input:
if v.name in dont_show:
continue
p(v.name, v.val)
p("PROJECT_BINARY_DIR", self.builddir)
p("CMAKE_INSTALL_PREFIX", self.installdir)
_preload_file_tpl = ("""\
# Do not edit. Will be overwritten.
# Generated by cmany on {date}
if(NOT _cmany_set_def)
set(_cmany_set_def ON)
function(_cmany_set var value type)
set(${{var}} "${{value}}" CACHE ${{type}} "")
message(STATUS "cmany: ${{var}}=${{value}}")
endfunction(_cmany_set)
endif(NOT _cmany_set_def)
message(STATUS "cmany:preload----------------------")
{vars}
message(STATUS "cmany:preload----------------------")
# if(CMANY_INCLUDE_DIRECTORIES)
# include_directories(${{CMANY_INCLUDE_DIRECTORIES}})
# endif()
#
# if(CMANY_LINK_DIRECTORIES)
# link_directories(${{CMANY_LINK_DIRECTORIES}})
# endif()
# Do not edit. Will be overwritten.
# Generated by cmany on {date}
""")
_preload_file_tpl_empty = ("""\
# Do not edit. Will be overwritten.
# Generated by cmany on {date}
message(STATUS "cmany: nothing to preload...")
""")
| true | true |
f72832b743dddc38a07d02e41bb07d0fda8ea72c | 3,919 | py | Python | canu/utils/inventory.py | Cray-HPE/canu | 3a92ce1e9b63f35aa30b9135afaa734e61909407 | [
"MIT"
] | 6 | 2021-09-16T22:02:48.000Z | 2022-02-04T18:08:57.000Z | canu/utils/inventory.py | Cray-HPE/canu | 3a92ce1e9b63f35aa30b9135afaa734e61909407 | [
"MIT"
] | 57 | 2021-09-17T17:15:59.000Z | 2022-03-31T20:56:21.000Z | canu/utils/inventory.py | Cray-HPE/canu | 3a92ce1e9b63f35aa30b9135afaa734e61909407 | [
"MIT"
] | 4 | 2022-01-06T17:09:02.000Z | 2022-02-04T18:09:33.000Z | # MIT License
#
# (C) Copyright [2022] Hewlett Packard Enterprise Development LP
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
"""Create Nornir Inventory from SLS."""
import json
import click
from canu.utils.sls import pull_sls_hardware, pull_sls_networks
def inventory(username, password, network, sls_json=None):
"""Build Nornir inventory from sls_input."""
inventory = {"groups": "shasta", "hosts": {}}
if sls_json:
try:
input_json = json.load(sls_json)
except (json.JSONDecodeError, UnicodeDecodeError):
click.secho(
f"The file {sls_json.name} is not valid JSON.",
fg="red",
)
return
sls_variables = pull_sls_networks(input_json)
sls_hardware = pull_sls_hardware(input_json)
else:
sls_variables = pull_sls_networks()
sls_hardware = pull_sls_hardware()
for k in sls_variables[network + "_IPs"]:
if "sw" in k:
inventory["hosts"].update(
{
k: {
"hostname": str(sls_variables[network + "_IPs"][k]),
"platform": "",
"username": username,
"password": password,
"data": {"type": ""},
},
},
)
# pull in the platform type from sls hardware data
for x in sls_hardware:
if (
x["Type"] == "comptype_hl_switch"
or x["Type"] == "comptype_mgmt_switch"
or x["Type"] == "comptype_cdu_mgmt_switch"
):
for host in inventory["hosts"]:
if host == x["ExtraProperties"]["Aliases"][0]:
if x["ExtraProperties"]["Brand"] == "Aruba":
inventory["hosts"][host]["platform"] = "aruba_os"
elif x["ExtraProperties"]["Brand"] == "Dell":
inventory["hosts"][host]["platform"] = "dell_os10"
elif x["ExtraProperties"]["Brand"] == "Mellanox":
inventory["hosts"][host]["platform"] = "mellanox"
else:
inventory["hosts"][host]["platform"] = "generic"
if "sw-leaf-bmc" in host:
inventory["hosts"][host]["data"]["type"] = "leaf-bmc"
elif "sw-leaf" in host:
inventory["hosts"][host]["data"]["type"] = "leaf"
elif "sw-spine" in host:
inventory["hosts"][host]["data"]["type"] = "spine"
elif "sw-cdu" in host:
inventory["hosts"][host]["data"]["type"] = "cdu"
inventory = {
"plugin": "DictInventory",
"options": {
"hosts": inventory["hosts"],
"groups": {},
"defaults": {},
},
}
return inventory
| 40.822917 | 76 | 0.56494 |
import json
import click
from canu.utils.sls import pull_sls_hardware, pull_sls_networks
def inventory(username, password, network, sls_json=None):
inventory = {"groups": "shasta", "hosts": {}}
if sls_json:
try:
input_json = json.load(sls_json)
except (json.JSONDecodeError, UnicodeDecodeError):
click.secho(
f"The file {sls_json.name} is not valid JSON.",
fg="red",
)
return
sls_variables = pull_sls_networks(input_json)
sls_hardware = pull_sls_hardware(input_json)
else:
sls_variables = pull_sls_networks()
sls_hardware = pull_sls_hardware()
for k in sls_variables[network + "_IPs"]:
if "sw" in k:
inventory["hosts"].update(
{
k: {
"hostname": str(sls_variables[network + "_IPs"][k]),
"platform": "",
"username": username,
"password": password,
"data": {"type": ""},
},
},
)
for x in sls_hardware:
if (
x["Type"] == "comptype_hl_switch"
or x["Type"] == "comptype_mgmt_switch"
or x["Type"] == "comptype_cdu_mgmt_switch"
):
for host in inventory["hosts"]:
if host == x["ExtraProperties"]["Aliases"][0]:
if x["ExtraProperties"]["Brand"] == "Aruba":
inventory["hosts"][host]["platform"] = "aruba_os"
elif x["ExtraProperties"]["Brand"] == "Dell":
inventory["hosts"][host]["platform"] = "dell_os10"
elif x["ExtraProperties"]["Brand"] == "Mellanox":
inventory["hosts"][host]["platform"] = "mellanox"
else:
inventory["hosts"][host]["platform"] = "generic"
if "sw-leaf-bmc" in host:
inventory["hosts"][host]["data"]["type"] = "leaf-bmc"
elif "sw-leaf" in host:
inventory["hosts"][host]["data"]["type"] = "leaf"
elif "sw-spine" in host:
inventory["hosts"][host]["data"]["type"] = "spine"
elif "sw-cdu" in host:
inventory["hosts"][host]["data"]["type"] = "cdu"
inventory = {
"plugin": "DictInventory",
"options": {
"hosts": inventory["hosts"],
"groups": {},
"defaults": {},
},
}
return inventory
| true | true |
f72832e0efafdb5da91882119166814ebcaf4039 | 207 | py | Python | output/models/ms_data/datatypes/facets/negative_integer/negative_integer_total_digits003_xsd/__init__.py | tefra/xsdata-w3c-tests | b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f | [
"MIT"
] | 1 | 2021-08-14T17:59:21.000Z | 2021-08-14T17:59:21.000Z | output/models/ms_data/datatypes/facets/negative_integer/negative_integer_total_digits003_xsd/__init__.py | tefra/xsdata-w3c-tests | b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f | [
"MIT"
] | 4 | 2020-02-12T21:30:44.000Z | 2020-04-15T20:06:46.000Z | output/models/ms_data/datatypes/facets/negative_integer/negative_integer_total_digits003_xsd/__init__.py | tefra/xsdata-w3c-tests | b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f | [
"MIT"
] | null | null | null | from output.models.ms_data.datatypes.facets.negative_integer.negative_integer_total_digits003_xsd.negative_integer_total_digits003 import (
FooType,
Test,
)
__all__ = [
"FooType",
"Test",
]
| 20.7 | 139 | 0.758454 | from output.models.ms_data.datatypes.facets.negative_integer.negative_integer_total_digits003_xsd.negative_integer_total_digits003 import (
FooType,
Test,
)
__all__ = [
"FooType",
"Test",
]
| true | true |
f72833ccdad8202a2c57ba9edaf8b81c8c0faafa | 693 | py | Python | networkit/test/test_independentset.py | krzysztof-turowski/networkit | b0db9e30be1a7f7dcf74eaff2a013988a81973ce | [
"MIT"
] | 194 | 2016-10-21T22:56:49.000Z | 2019-06-21T03:04:22.000Z | networkit/test/test_independentset.py | krzysztof-turowski/networkit | b0db9e30be1a7f7dcf74eaff2a013988a81973ce | [
"MIT"
] | 215 | 2017-02-06T09:12:54.000Z | 2019-06-24T10:52:24.000Z | networkit/test/test_independentset.py | krzysztof-turowski/networkit | b0db9e30be1a7f7dcf74eaff2a013988a81973ce | [
"MIT"
] | 93 | 2017-01-10T10:51:01.000Z | 2019-06-20T13:58:57.000Z | #!/usr/bin/env python3
import unittest
import networkit as nk
class TestGraphTools(unittest.TestCase):
def testLubyAlgorithm(self):
G = nk.Graph(4, False, False)
G.addEdge(0, 1)
G.addEdge(0, 2)
G.addEdge(1, 2)
G.addEdge(2, 3)
luby = nk.independentset.Luby()
res = luby.run(G)
count = sum(res)
# The are several valid outcomes, with either one or two nodes being independent.
self.assertGreaterEqual(count, 1)
self.assertLessEqual(count, 2)
G.addEdge(0, 3)
G.addEdge(1, 3)
res = luby.run(G)
count = sum(res)
# Only a single node can be independent since the graph is fully connected.
self.assertEqual(count, 1)
if __name__ == "__main__":
unittest.main()
| 23.896552 | 83 | 0.698413 |
import unittest
import networkit as nk
class TestGraphTools(unittest.TestCase):
def testLubyAlgorithm(self):
G = nk.Graph(4, False, False)
G.addEdge(0, 1)
G.addEdge(0, 2)
G.addEdge(1, 2)
G.addEdge(2, 3)
luby = nk.independentset.Luby()
res = luby.run(G)
count = sum(res)
self.assertGreaterEqual(count, 1)
self.assertLessEqual(count, 2)
G.addEdge(0, 3)
G.addEdge(1, 3)
res = luby.run(G)
count = sum(res)
self.assertEqual(count, 1)
if __name__ == "__main__":
unittest.main()
| true | true |
f72833dd50109fe208c3cdeb6c934bc3c7e0fd11 | 753 | py | Python | TTS.py | mahmoud-x923/TTS-STT-python | c225deedbbb5b3ded9be02f2edf39765a67dfe27 | [
"Apache-2.0"
] | null | null | null | TTS.py | mahmoud-x923/TTS-STT-python | c225deedbbb5b3ded9be02f2edf39765a67dfe27 | [
"Apache-2.0"
] | null | null | null | TTS.py | mahmoud-x923/TTS-STT-python | c225deedbbb5b3ded9be02f2edf39765a67dfe27 | [
"Apache-2.0"
] | null | null | null | from ibm_watson import TextToSpeechV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
def main(text,audio):
authenticator = IAMAuthenticator('7-KyTRyrBXQSuRQO7wazH5Q-Q_5QzDs6R0qOZqD1hyu6')
text_to_speech = TextToSpeechV1(
authenticator=authenticator
)
text_to_speech.set_service_url('https://api.us-east.text-to-speech.watson.cloud.ibm.com')
audio_file = open(audio, 'wb')
res = text_to_speech.synthesize(text, accept='audio/mp3', voice='en-US_AllisonV3Voice').get_result()
audio_file.write(res.content)
audio_file.close()
if __name__ == "__main__":
main('In order to get a final response from STT we send a stop, this will force a final=True return message.','./output.mp3') | 44.294118 | 129 | 0.73838 | from ibm_watson import TextToSpeechV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
def main(text,audio):
authenticator = IAMAuthenticator('7-KyTRyrBXQSuRQO7wazH5Q-Q_5QzDs6R0qOZqD1hyu6')
text_to_speech = TextToSpeechV1(
authenticator=authenticator
)
text_to_speech.set_service_url('https://api.us-east.text-to-speech.watson.cloud.ibm.com')
audio_file = open(audio, 'wb')
res = text_to_speech.synthesize(text, accept='audio/mp3', voice='en-US_AllisonV3Voice').get_result()
audio_file.write(res.content)
audio_file.close()
if __name__ == "__main__":
main('In order to get a final response from STT we send a stop, this will force a final=True return message.','./output.mp3') | true | true |
f72834f75e285301d289bba68e29608e0903c060 | 743 | py | Python | src/Javinizer/translate_deepl.py | Toastyice/Javinizer | 017b3aa84a9017c4b38f3b2938a4e20340219d68 | [
"MIT"
] | 340 | 2019-12-03T08:38:45.000Z | 2022-03-30T18:01:22.000Z | src/Javinizer/translate_deepl.py | Toastyice/Javinizer | 017b3aa84a9017c4b38f3b2938a4e20340219d68 | [
"MIT"
] | 227 | 2019-12-25T07:44:53.000Z | 2022-03-24T08:53:29.000Z | src/Javinizer/translate_deepl.py | Toastyice/Javinizer | 017b3aa84a9017c4b38f3b2938a4e20340219d68 | [
"MIT"
] | 65 | 2019-12-21T18:22:35.000Z | 2022-03-25T01:48:58.000Z | import sys
import requests
import tempfile
import os
import json
#Select Url based on key provided (free keys always end in :fx)
baseurl = "https://api-free.deepl.com/v2/translate" if sys.argv[3].endswith(":fx") else "https://api.deepl.com/v2/translate"
url = "{}?auth_key={}&text={}&target_lang={}".format(baseurl, sys.argv[3], sys.argv[1], sys.argv[2])
r = requests.get(url)
j = json.loads(r.text)
n = j['translations'][0]['text']
text = n.encode('utf8')
# Write the translated text to a temporary file to bypass encoding issues when redirecting the text to PowerShell
new_file, filename = tempfile.mkstemp()
os.write(new_file, text)
os.close(new_file)
# Return the path to the temporary file to read it from PowerShell
print(filename)
| 30.958333 | 124 | 0.732167 | import sys
import requests
import tempfile
import os
import json
baseurl = "https://api-free.deepl.com/v2/translate" if sys.argv[3].endswith(":fx") else "https://api.deepl.com/v2/translate"
url = "{}?auth_key={}&text={}&target_lang={}".format(baseurl, sys.argv[3], sys.argv[1], sys.argv[2])
r = requests.get(url)
j = json.loads(r.text)
n = j['translations'][0]['text']
text = n.encode('utf8')
new_file, filename = tempfile.mkstemp()
os.write(new_file, text)
os.close(new_file)
print(filename)
| true | true |
f72835d20f5516cdcbaab205140d2862cc287eae | 2,246 | py | Python | userbot/modules/shortlink.py | kuinginngopi/Rpan-Userbot | 2e9bbd98a242e82e4c44e95c15c6669df81934b9 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | userbot/modules/shortlink.py | kuinginngopi/Rpan-Userbot | 2e9bbd98a242e82e4c44e95c15c6669df81934b9 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | userbot/modules/shortlink.py | kuinginngopi/Rpan-Userbot | 2e9bbd98a242e82e4c44e95c15c6669df81934b9 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | from asyncio.exceptions import TimeoutError
from telethon.errors.rpcerrorlist import YouBlockedUserError
from telethon.tl.functions.contacts import UnblockRequest
from userbot import CMD_HANDLER as cmd
from userbot import CMD_HELP
from userbot.utils import edit_or_reply, man_cmd
@man_cmd(pattern="short(?: |$)(.*)")
async def _(event):
if event.fwd_from:
return
msg_link = await event.get_reply_message()
d_link = event.pattern_match.group(1)
if msg_link:
d_link = msg_link.text
xx = await edit_or_reply(event, "`Shortening replied link...`")
elif "https" not in d_link:
await edit_or_reply(
event,
"**Masukkan link, pastikan dimulai dengan** `http://` **atau** `https://`",
)
else:
xx = await edit_or_reply(event, "`Shortening link...`")
chat = "@ShortUrlBot"
try:
async with event.client.conversation(chat) as conv:
try:
msg_start = await conv.send_message("/start")
bot_reply = await conv.get_response()
msg = await conv.send_message(d_link)
response = await conv.get_response()
url = await conv.get_response()
sponser = await conv.get_response()
await event.client.send_read_acknowledge(conv.chat_id)
await event.edit(response.text)
except YouBlockedUserError:
await event.client(UnblockRequest(chat))
return await xx.edit("**Silahkan Unblock @ShortUrlBot dan coba lagi**")
await event.client.send_message(event.chat_id, url)
await event.client.delete_messages(
conv.chat_id,
[msg_start.id, response.id, msg.id, bot_reply.id, sponser.id, url.id],
)
await event.delete()
except TimeoutError:
return await xx.edit(
"**ERROR: @ShortUrlBot tidak merespon silahkan coba lagi nanti**"
)
CMD_HELP.update(
{
"shortlink": f"**Plugin : **`shortlink`\
\n\n • **Syntax :** `{cmd}short` <url/reply link>\
\n • **Function : **Untuk menyimpelkan link url menjadi pendek menggunakan @ShortUrlBot\
"
}
)
| 36.225806 | 98 | 0.609083 | from asyncio.exceptions import TimeoutError
from telethon.errors.rpcerrorlist import YouBlockedUserError
from telethon.tl.functions.contacts import UnblockRequest
from userbot import CMD_HANDLER as cmd
from userbot import CMD_HELP
from userbot.utils import edit_or_reply, man_cmd
@man_cmd(pattern="short(?: |$)(.*)")
async def _(event):
if event.fwd_from:
return
msg_link = await event.get_reply_message()
d_link = event.pattern_match.group(1)
if msg_link:
d_link = msg_link.text
xx = await edit_or_reply(event, "`Shortening replied link...`")
elif "https" not in d_link:
await edit_or_reply(
event,
"**Masukkan link, pastikan dimulai dengan** `http://` **atau** `https://`",
)
else:
xx = await edit_or_reply(event, "`Shortening link...`")
chat = "@ShortUrlBot"
try:
async with event.client.conversation(chat) as conv:
try:
msg_start = await conv.send_message("/start")
bot_reply = await conv.get_response()
msg = await conv.send_message(d_link)
response = await conv.get_response()
url = await conv.get_response()
sponser = await conv.get_response()
await event.client.send_read_acknowledge(conv.chat_id)
await event.edit(response.text)
except YouBlockedUserError:
await event.client(UnblockRequest(chat))
return await xx.edit("**Silahkan Unblock @ShortUrlBot dan coba lagi**")
await event.client.send_message(event.chat_id, url)
await event.client.delete_messages(
conv.chat_id,
[msg_start.id, response.id, msg.id, bot_reply.id, sponser.id, url.id],
)
await event.delete()
except TimeoutError:
return await xx.edit(
"**ERROR: @ShortUrlBot tidak merespon silahkan coba lagi nanti**"
)
CMD_HELP.update(
{
"shortlink": f"**Plugin : **`shortlink`\
\n\n • **Syntax :** `{cmd}short` <url/reply link>\
\n • **Function : **Untuk menyimpelkan link url menjadi pendek menggunakan @ShortUrlBot\
"
}
)
| true | true |
f728362a23cfcc135a81ab7ad984b23e49570023 | 458 | py | Python | sermepa/admin.py | Etxea/django-sermepa | 1be9173c4786e138b4dafce830f6d8e22a6762e6 | [
"MIT"
] | 3 | 2015-12-15T09:49:36.000Z | 2018-06-28T10:29:00.000Z | sermepa/admin.py | Etxea/django-sermepa | 1be9173c4786e138b4dafce830f6d8e22a6762e6 | [
"MIT"
] | null | null | null | sermepa/admin.py | Etxea/django-sermepa | 1be9173c4786e138b4dafce830f6d8e22a6762e6 | [
"MIT"
] | 4 | 2015-12-15T09:49:40.000Z | 2021-09-10T10:07:02.000Z | # -*- coding: utf-8 -*-
from django.contrib import admin
from .models import SermepaResponse, SermepaIdTPV
class SermepaResponseAdmin(admin.ModelAdmin):
search_fields = ['Ds_Order']
list_display = ('creation_date', 'Ds_Order', 'Ds_Amount',
'Ds_Response', 'Ds_TransactionType', 'check_signature')
list_filter = ('creation_date',)
admin.site.register(SermepaResponse, SermepaResponseAdmin)
admin.site.register(SermepaIdTPV,)
| 32.714286 | 75 | 0.727074 |
from django.contrib import admin
from .models import SermepaResponse, SermepaIdTPV
class SermepaResponseAdmin(admin.ModelAdmin):
search_fields = ['Ds_Order']
list_display = ('creation_date', 'Ds_Order', 'Ds_Amount',
'Ds_Response', 'Ds_TransactionType', 'check_signature')
list_filter = ('creation_date',)
admin.site.register(SermepaResponse, SermepaResponseAdmin)
admin.site.register(SermepaIdTPV,)
| true | true |
f7283677a1370620e01303326e72b7c4aee83574 | 12,213 | py | Python | examples/trials/cifar10_grad_match/cords/selectionstrategies/supervisedlearning/submodularselectionstrategy.py | savan77/nni | 510213393d9cae58c5a8cccd21f322f7bba4e0cf | [
"MIT"
] | null | null | null | examples/trials/cifar10_grad_match/cords/selectionstrategies/supervisedlearning/submodularselectionstrategy.py | savan77/nni | 510213393d9cae58c5a8cccd21f322f7bba4e0cf | [
"MIT"
] | null | null | null | examples/trials/cifar10_grad_match/cords/selectionstrategies/supervisedlearning/submodularselectionstrategy.py | savan77/nni | 510213393d9cae58c5a8cccd21f322f7bba4e0cf | [
"MIT"
] | null | null | null | import apricot
import numpy as np
import torch
import torch.nn.functional as F
from scipy.sparse import csr_matrix
from .dataselectionstrategy import DataSelectionStrategy
from torch.utils.data.sampler import SubsetRandomSampler
class SubmodularSelectionStrategy(DataSelectionStrategy):
"""
This class extends :class:`selectionstrategies.supervisedlearning.dataselectionstrategy.DataSelectionStrategy`
to include submodular optmization functions using apricot for data selection.
Parameters
----------
trainloader: class
Loading the training data using pytorch DataLoader
valloader: class
Loading the validation data using pytorch DataLoader
model: class
Model architecture used for training
loss_type: class
The type of loss criterion
device: str
The device being utilized - cpu | cuda
num_classes: int
The number of target classes in the dataset
linear_layer: bool
Apply linear transformation to the data
if_convex: bool
If convex or not
selection_type: str
PerClass or Supervised
submod_func_type: str
The type of submodular optimization function. Must be one of
'facility-location', 'graph-cut', 'sum-redundancy', 'saturated-coverage'
"""
def __init__(self, trainloader, valloader, model, loss_type,
device, num_classes, linear_layer, if_convex, selection_type, submod_func_type):
"""
Constructer method
"""
super().__init__(trainloader, valloader, model, num_classes, linear_layer)
self.loss_type = loss_type # Make sure it has reduction='none' instead of default
self.device = device
self.if_convex = if_convex
self.selection_type = selection_type
self.submod_func_type = submod_func_type
def distance(self, x, y, exp=2):
"""
Compute the distance.
Parameters
----------
x: Tensor
First input tensor
y: Tensor
Second input tensor
exp: float, optional
The exponent value (default: 2)
Returns
----------
dist: Tensor
Output tensor
"""
n = x.size(0)
m = y.size(0)
d = x.size(1)
x = x.unsqueeze(1).expand(n, m, d)
y = y.unsqueeze(0).expand(n, m, d)
dist = torch.pow(x - y, exp).sum(2)
#dist = torch.exp(-1 * torch.pow(x - y, 2).sum(2))
return dist
def compute_score(self, model_params, idxs):
"""
Compute the score of the indices.
Parameters
----------
model_params: OrderedDict
Python dictionary object containing models parameters
idxs: list
The indices
"""
trainset = self.trainloader.sampler.data_source
subset_loader = torch.utils.data.DataLoader(trainset, batch_size=self.trainloader.batch_size, shuffle=False,
sampler=SubsetRandomSampler(idxs),
pin_memory=True)
self.model.load_state_dict(model_params)
self.N = 0
g_is = []
with torch.no_grad():
if self.if_convex:
for batch_idx, (inputs, targets) in enumerate(subset_loader):
inputs, targets = inputs, targets
self.N += inputs.size()[0]
g_is.append(inputs.view(inputs.size()[0], -1))
else:
embDim = self.model.get_embedding_dim()
for batch_idx, (inputs, targets) in enumerate(subset_loader):
inputs, targets = inputs.to(self.device), targets.to(self.device, non_blocking=True)
self.N += inputs.size()[0]
with torch.no_grad():
out, l1 = self.model(inputs, last=True)
data = F.softmax(out, dim=1)
outputs = torch.zeros(len(inputs), self.num_classes).to(self.device)
outputs.scatter_(1, targets.view(-1, 1), 1)
l0_grads = data - outputs
if self.linear_layer:
l0_expand = torch.repeat_interleave(l0_grads, embDim, dim=1)
l1_grads = l0_expand * l1.repeat(1, self.num_classes)
g_is.append(torch.cat((l0_grads, l1_grads), dim=1))
else:
g_is.append(l0_grads)
self.dist_mat = torch.zeros([self.N, self.N], dtype=torch.float32)
first_i = True
for i, g_i in enumerate(g_is, 0):
if first_i:
size_b = g_i.size(0)
first_i = False
for j, g_j in enumerate(g_is, 0):
self.dist_mat[i * size_b: i * size_b + g_i.size(0),
j * size_b: j * size_b + g_j.size(0)] = self.distance(g_i, g_j)
self.const = torch.max(self.dist_mat).item()
self.dist_mat = (self.const - self.dist_mat).numpy()
def compute_gamma(self, idxs):
"""
Compute the gamma values for the indices.
Parameters
----------
idxs: list
The indices
Returns
----------
gamma: list
Gradient values of the input indices
"""
if self.selection_type == 'PerClass':
gamma = [0 for i in range(len(idxs))]
best = self.dist_mat[idxs] # .to(self.device)
rep = np.argmax(best, axis=0)
for i in rep:
gamma[i] += 1
elif self.selection_type == 'Supervised':
gamma = [0 for i in range(len(idxs))]
best = self.dist_mat[idxs] # .to(self.device)
rep = np.argmax(best, axis=0)
for i in range(rep.shape[1]):
gamma[rep[0, i]] += 1
return gamma
def get_similarity_kernel(self):
"""
Obtain the similarity kernel.
Returns
----------
kernel: ndarray
Array of kernel values
"""
for batch_idx, (inputs, targets) in enumerate(self.trainloader):
if batch_idx == 0:
labels = targets
else:
tmp_target_i = targets
labels = torch.cat((labels, tmp_target_i), dim=0)
kernel = np.zeros((labels.shape[0], labels.shape[0]))
for target in np.unique(labels):
x = np.where(labels == target)[0]
# prod = np.transpose([np.tile(x, len(x)), np.repeat(x, len(x))])
for i in x:
kernel[i, x] = 1
return kernel
def select(self, budget, model_params, optimizer):
"""
Data selection method using different submodular optimization
functions.
Parameters
----------
budget: int
The number of data points to be selected
model_params: OrderedDict
Python dictionary object containing models parameters
optimizer: str
The optimization approach for data selection. Must be one of
'random', 'modular', 'naive', 'lazy', 'approximate-lazy', 'two-stage',
'stochastic', 'sample', 'greedi', 'bidirectional'
Returns
----------
total_greedy_list: list
List containing indices of the best datapoints
gammas: list
List containing gradients of datapoints present in greedySet
"""
for batch_idx, (inputs, targets) in enumerate(self.trainloader):
if batch_idx == 0:
x_trn, labels = inputs, targets
else:
tmp_inputs, tmp_target_i = inputs, targets
labels = torch.cat((labels, tmp_target_i), dim=0)
per_class_bud = int(budget / self.num_classes)
total_greedy_list = []
gammas = []
if self.selection_type == 'PerClass':
for i in range(self.num_classes):
idxs = torch.where(labels == i)[0]
self.compute_score(model_params, idxs)
if self.submod_func_type == 'facility-location':
fl = apricot.functions.facilityLocation.FacilityLocationSelection(random_state=0, metric='precomputed',
n_samples=per_class_bud, optimizer=optimizer)
elif self.submod_func_type == 'graph-cut':
fl = apricot.functions.graphCut.GraphCutSelection(random_state=0, metric='precomputed',
n_samples=per_class_bud, optimizer=optimizer)
elif self.submod_func_type == 'sum-redundancy':
fl = apricot.functions.sumRedundancy.SumRedundancySelection(random_state=0, metric='precomputed',
n_samples=per_class_bud, optimizer=optimizer)
elif self.submod_func_type == 'saturated-coverage':
fl = apricot.functions.saturatedCoverage.SaturatedCoverageSelection(random_state=0, metric='precomputed',
n_samples=per_class_bud, optimizer=optimizer)
sim_sub = fl.fit_transform(self.dist_mat)
greedyList = list(np.argmax(sim_sub, axis=1))
gamma = self.compute_gamma(greedyList)
total_greedy_list.extend(idxs[greedyList])
gammas.extend(gamma)
elif self.selection_type == 'Supervised':
for i in range(self.num_classes):
if i == 0:
idxs = torch.where(labels == i)[0]
N = len(idxs)
self.compute_score(model_params, idxs)
row = idxs.repeat_interleave(N)
col = idxs.repeat(N)
data = self.dist_mat.flatten()
else:
idxs = torch.where(labels == i)[0]
N = len(idxs)
self.compute_score(model_params, idxs)
row = torch.cat((row, idxs.repeat_interleave(N)), dim=0)
col = torch.cat((col, idxs.repeat(N)), dim=0)
data = np.concatenate([data, self.dist_mat.flatten()], axis=0)
sparse_simmat = csr_matrix((data, (row.numpy(), col.numpy())), shape=(self.N_trn, self.N_trn))
self.dist_mat = sparse_simmat
if self.submod_func_type == 'facility-location':
fl = apricot.functions.facilityLocation.FacilityLocationSelection(random_state=0, metric='precomputed',
n_samples=per_class_bud, optimizer=optimizer)
elif self.submod_func_type == 'graph-cut':
fl = apricot.functions.graphCut.GraphCutSelection(random_state=0, metric='precomputed',
n_samples=per_class_bud, optimizer=optimizer)
elif self.submod_func_type == 'sum-redundancy':
fl = apricot.functions.sumRedundancy.SumRedundancySelection(random_state=0, metric='precomputed',
n_samples=per_class_bud, optimizer=optimizer)
elif self.submod_func_type == 'saturated-coverage':
fl = apricot.functions.saturatedCoverage.SaturatedCoverageSelection(random_state=0, metric='precomputed',
n_samples=per_class_bud, optimizer=optimizer)
sim_sub = fl.fit_transform(sparse_simmat)
total_greedy_list = list(np.array(np.argmax(sim_sub, axis=1)).reshape(-1))
gammas = self.compute_gamma(total_greedy_list)
return total_greedy_list, gammas
| 42.554007 | 125 | 0.540326 | import apricot
import numpy as np
import torch
import torch.nn.functional as F
from scipy.sparse import csr_matrix
from .dataselectionstrategy import DataSelectionStrategy
from torch.utils.data.sampler import SubsetRandomSampler
class SubmodularSelectionStrategy(DataSelectionStrategy):
def __init__(self, trainloader, valloader, model, loss_type,
device, num_classes, linear_layer, if_convex, selection_type, submod_func_type):
super().__init__(trainloader, valloader, model, num_classes, linear_layer)
self.loss_type = loss_type
self.device = device
self.if_convex = if_convex
self.selection_type = selection_type
self.submod_func_type = submod_func_type
def distance(self, x, y, exp=2):
n = x.size(0)
m = y.size(0)
d = x.size(1)
x = x.unsqueeze(1).expand(n, m, d)
y = y.unsqueeze(0).expand(n, m, d)
dist = torch.pow(x - y, exp).sum(2)
return dist
def compute_score(self, model_params, idxs):
trainset = self.trainloader.sampler.data_source
subset_loader = torch.utils.data.DataLoader(trainset, batch_size=self.trainloader.batch_size, shuffle=False,
sampler=SubsetRandomSampler(idxs),
pin_memory=True)
self.model.load_state_dict(model_params)
self.N = 0
g_is = []
with torch.no_grad():
if self.if_convex:
for batch_idx, (inputs, targets) in enumerate(subset_loader):
inputs, targets = inputs, targets
self.N += inputs.size()[0]
g_is.append(inputs.view(inputs.size()[0], -1))
else:
embDim = self.model.get_embedding_dim()
for batch_idx, (inputs, targets) in enumerate(subset_loader):
inputs, targets = inputs.to(self.device), targets.to(self.device, non_blocking=True)
self.N += inputs.size()[0]
with torch.no_grad():
out, l1 = self.model(inputs, last=True)
data = F.softmax(out, dim=1)
outputs = torch.zeros(len(inputs), self.num_classes).to(self.device)
outputs.scatter_(1, targets.view(-1, 1), 1)
l0_grads = data - outputs
if self.linear_layer:
l0_expand = torch.repeat_interleave(l0_grads, embDim, dim=1)
l1_grads = l0_expand * l1.repeat(1, self.num_classes)
g_is.append(torch.cat((l0_grads, l1_grads), dim=1))
else:
g_is.append(l0_grads)
self.dist_mat = torch.zeros([self.N, self.N], dtype=torch.float32)
first_i = True
for i, g_i in enumerate(g_is, 0):
if first_i:
size_b = g_i.size(0)
first_i = False
for j, g_j in enumerate(g_is, 0):
self.dist_mat[i * size_b: i * size_b + g_i.size(0),
j * size_b: j * size_b + g_j.size(0)] = self.distance(g_i, g_j)
self.const = torch.max(self.dist_mat).item()
self.dist_mat = (self.const - self.dist_mat).numpy()
def compute_gamma(self, idxs):
if self.selection_type == 'PerClass':
gamma = [0 for i in range(len(idxs))]
best = self.dist_mat[idxs]
rep = np.argmax(best, axis=0)
for i in rep:
gamma[i] += 1
elif self.selection_type == 'Supervised':
gamma = [0 for i in range(len(idxs))]
best = self.dist_mat[idxs]
rep = np.argmax(best, axis=0)
for i in range(rep.shape[1]):
gamma[rep[0, i]] += 1
return gamma
def get_similarity_kernel(self):
for batch_idx, (inputs, targets) in enumerate(self.trainloader):
if batch_idx == 0:
labels = targets
else:
tmp_target_i = targets
labels = torch.cat((labels, tmp_target_i), dim=0)
kernel = np.zeros((labels.shape[0], labels.shape[0]))
for target in np.unique(labels):
x = np.where(labels == target)[0]
for i in x:
kernel[i, x] = 1
return kernel
def select(self, budget, model_params, optimizer):
for batch_idx, (inputs, targets) in enumerate(self.trainloader):
if batch_idx == 0:
x_trn, labels = inputs, targets
else:
tmp_inputs, tmp_target_i = inputs, targets
labels = torch.cat((labels, tmp_target_i), dim=0)
per_class_bud = int(budget / self.num_classes)
total_greedy_list = []
gammas = []
if self.selection_type == 'PerClass':
for i in range(self.num_classes):
idxs = torch.where(labels == i)[0]
self.compute_score(model_params, idxs)
if self.submod_func_type == 'facility-location':
fl = apricot.functions.facilityLocation.FacilityLocationSelection(random_state=0, metric='precomputed',
n_samples=per_class_bud, optimizer=optimizer)
elif self.submod_func_type == 'graph-cut':
fl = apricot.functions.graphCut.GraphCutSelection(random_state=0, metric='precomputed',
n_samples=per_class_bud, optimizer=optimizer)
elif self.submod_func_type == 'sum-redundancy':
fl = apricot.functions.sumRedundancy.SumRedundancySelection(random_state=0, metric='precomputed',
n_samples=per_class_bud, optimizer=optimizer)
elif self.submod_func_type == 'saturated-coverage':
fl = apricot.functions.saturatedCoverage.SaturatedCoverageSelection(random_state=0, metric='precomputed',
n_samples=per_class_bud, optimizer=optimizer)
sim_sub = fl.fit_transform(self.dist_mat)
greedyList = list(np.argmax(sim_sub, axis=1))
gamma = self.compute_gamma(greedyList)
total_greedy_list.extend(idxs[greedyList])
gammas.extend(gamma)
elif self.selection_type == 'Supervised':
for i in range(self.num_classes):
if i == 0:
idxs = torch.where(labels == i)[0]
N = len(idxs)
self.compute_score(model_params, idxs)
row = idxs.repeat_interleave(N)
col = idxs.repeat(N)
data = self.dist_mat.flatten()
else:
idxs = torch.where(labels == i)[0]
N = len(idxs)
self.compute_score(model_params, idxs)
row = torch.cat((row, idxs.repeat_interleave(N)), dim=0)
col = torch.cat((col, idxs.repeat(N)), dim=0)
data = np.concatenate([data, self.dist_mat.flatten()], axis=0)
sparse_simmat = csr_matrix((data, (row.numpy(), col.numpy())), shape=(self.N_trn, self.N_trn))
self.dist_mat = sparse_simmat
if self.submod_func_type == 'facility-location':
fl = apricot.functions.facilityLocation.FacilityLocationSelection(random_state=0, metric='precomputed',
n_samples=per_class_bud, optimizer=optimizer)
elif self.submod_func_type == 'graph-cut':
fl = apricot.functions.graphCut.GraphCutSelection(random_state=0, metric='precomputed',
n_samples=per_class_bud, optimizer=optimizer)
elif self.submod_func_type == 'sum-redundancy':
fl = apricot.functions.sumRedundancy.SumRedundancySelection(random_state=0, metric='precomputed',
n_samples=per_class_bud, optimizer=optimizer)
elif self.submod_func_type == 'saturated-coverage':
fl = apricot.functions.saturatedCoverage.SaturatedCoverageSelection(random_state=0, metric='precomputed',
n_samples=per_class_bud, optimizer=optimizer)
sim_sub = fl.fit_transform(sparse_simmat)
total_greedy_list = list(np.array(np.argmax(sim_sub, axis=1)).reshape(-1))
gammas = self.compute_gamma(total_greedy_list)
return total_greedy_list, gammas
| true | true |
f72837d3e6a151d44880e1c180f038707d36feb6 | 3,110 | py | Python | data/p2DJ/New/R2/benchmark/startQiskit_Class124.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | data/p2DJ/New/R2/benchmark/startQiskit_Class124.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | data/p2DJ/New/R2/benchmark/startQiskit_Class124.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | # qubit number=2
# total number=9
import cirq
import qiskit
from qiskit import IBMQ
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2,floor, sqrt, pi
import numpy as np
import networkx as nx
def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f^\pm
# NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate
# or multi_control_Z_gate (issue #127)
controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
oracle.mct(controls, target[0], None, mode='noancilla')
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
# oracle.barrier()
# oracle.draw('mpl', filename='circuit/deutsch-oracle.png')
return oracle
def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n, "qc")
target = QuantumRegister(1, "qt")
prog = QuantumCircuit(input_qubit, target)
# inverse last one (can be omitted if using O_f^\pm)
prog.x(target)
# apply H to get superposition
for i in range(n):
prog.h(input_qubit[i])
prog.h(input_qubit[1]) # number=1
prog.h(input_qubit[1]) # number=4
prog.h(target)
prog.barrier()
# apply oracle O_f
oracle = build_oracle(n, f)
prog.append(
oracle.to_gate(),
[input_qubit[i] for i in range(n)] + [target])
# apply H back (QFT on Z_2^n)
for i in range(n):
prog.h(input_qubit[i])
prog.barrier()
# measure
prog.x(input_qubit[1]) # number=2
prog.x(input_qubit[1]) # number=3
prog.cx(input_qubit[1],input_qubit[0]) # number=5
prog.cx(input_qubit[1],input_qubit[0]) # number=6
prog.cx(input_qubit[1],input_qubit[0]) # number=7
prog.cx(input_qubit[1],input_qubit[0]) # number=8
# circuit end
return prog
if __name__ == '__main__':
n = 2
f = lambda rep: rep[-1]
# f = lambda rep: "1" if rep[0:2] == "01" or rep[0:2] == "10" else "0"
# f = lambda rep: "0"
prog = make_circuit(n, f)
sample_shot =2800
backend = BasicAer.get_backend('statevector_simulator')
circuit1 = transpile(prog,FakeVigo())
circuit1.x(qubit=3)
circuit1.x(qubit=3)
prog = circuit1
info = execute(prog, backend=backend).result().get_statevector()
qubits = round(log2(len(info)))
info = {
np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)
for i in range(2 ** qubits)
}
writefile = open("../data/startQiskit_Class124.csv","w")
print(info,file=writefile)
print("results end", file=writefile)
print(circuit1.depth(),file=writefile)
print(circuit1,file=writefile)
writefile.close()
| 28.272727 | 80 | 0.619936 |
import cirq
import qiskit
from qiskit import IBMQ
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2,floor, sqrt, pi
import numpy as np
import networkx as nx
def build_oracle(n: int, f) -> QuantumCircuit:
controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
oracle.mct(controls, target[0], None, mode='noancilla')
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
return oracle
def make_circuit(n:int,f) -> QuantumCircuit:
input_qubit = QuantumRegister(n, "qc")
target = QuantumRegister(1, "qt")
prog = QuantumCircuit(input_qubit, target)
prog.x(target)
for i in range(n):
prog.h(input_qubit[i])
prog.h(input_qubit[1])
prog.h(input_qubit[1])
prog.h(target)
prog.barrier()
oracle = build_oracle(n, f)
prog.append(
oracle.to_gate(),
[input_qubit[i] for i in range(n)] + [target])
for i in range(n):
prog.h(input_qubit[i])
prog.barrier()
prog.x(input_qubit[1])
prog.x(input_qubit[1])
prog.cx(input_qubit[1],input_qubit[0])
prog.cx(input_qubit[1],input_qubit[0])
prog.cx(input_qubit[1],input_qubit[0])
prog.cx(input_qubit[1],input_qubit[0])
return prog
if __name__ == '__main__':
n = 2
f = lambda rep: rep[-1]
prog = make_circuit(n, f)
sample_shot =2800
backend = BasicAer.get_backend('statevector_simulator')
circuit1 = transpile(prog,FakeVigo())
circuit1.x(qubit=3)
circuit1.x(qubit=3)
prog = circuit1
info = execute(prog, backend=backend).result().get_statevector()
qubits = round(log2(len(info)))
info = {
np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)
for i in range(2 ** qubits)
}
writefile = open("../data/startQiskit_Class124.csv","w")
print(info,file=writefile)
print("results end", file=writefile)
print(circuit1.depth(),file=writefile)
print(circuit1,file=writefile)
writefile.close()
| true | true |
f7283818fe3ff5c8ba8e1316cf68b465d6417b2f | 1,900 | py | Python | google/cloud/resourcemanager/v3/resourcemanager-v3-py/setup.py | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 7 | 2021-02-21T10:39:41.000Z | 2021-12-07T07:31:28.000Z | google/cloud/resourcemanager/v3/resourcemanager-v3-py/setup.py | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 6 | 2021-02-02T23:46:11.000Z | 2021-11-15T01:46:02.000Z | google/cloud/resourcemanager/v3/resourcemanager-v3-py/setup.py | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 4 | 2021-01-28T23:25:45.000Z | 2021-08-30T01:55:16.000Z | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import io
import os
import setuptools # type: ignore
version = '0.1.0'
package_root = os.path.abspath(os.path.dirname(__file__))
readme_filename = os.path.join(package_root, 'README.rst')
with io.open(readme_filename, encoding='utf-8') as readme_file:
readme = readme_file.read()
setuptools.setup(
name='google-cloud-resourcemanager',
version=version,
long_description=readme,
packages=setuptools.PEP420PackageFinder.find(),
namespace_packages=('google', 'google.cloud'),
platforms='Posix; MacOS X; Windows',
include_package_data=True,
install_requires=(
'google-api-core[grpc] >= 1.27.0, < 3.0.0dev',
'libcst >= 0.2.5',
'proto-plus >= 1.15.0',
'packaging >= 14.3', 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', ),
python_requires='>=3.6',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Topic :: Internet',
'Topic :: Software Development :: Libraries :: Python Modules',
],
zip_safe=False,
)
| 34.545455 | 84 | 0.662105 |
import io
import os
import setuptools
version = '0.1.0'
package_root = os.path.abspath(os.path.dirname(__file__))
readme_filename = os.path.join(package_root, 'README.rst')
with io.open(readme_filename, encoding='utf-8') as readme_file:
readme = readme_file.read()
setuptools.setup(
name='google-cloud-resourcemanager',
version=version,
long_description=readme,
packages=setuptools.PEP420PackageFinder.find(),
namespace_packages=('google', 'google.cloud'),
platforms='Posix; MacOS X; Windows',
include_package_data=True,
install_requires=(
'google-api-core[grpc] >= 1.27.0, < 3.0.0dev',
'libcst >= 0.2.5',
'proto-plus >= 1.15.0',
'packaging >= 14.3', 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', ),
python_requires='>=3.6',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Topic :: Internet',
'Topic :: Software Development :: Libraries :: Python Modules',
],
zip_safe=False,
)
| true | true |
f728382502116d54ffa9b7e1ccbe2024ad4effea | 85,815 | py | Python | jax/interpreters/pxla.py | cloudhan/jax | 9781f365a1c5dbdf57bf78b98831c4390eb9ca5f | [
"Apache-2.0"
] | null | null | null | jax/interpreters/pxla.py | cloudhan/jax | 9781f365a1c5dbdf57bf78b98831c4390eb9ca5f | [
"Apache-2.0"
] | 6 | 2021-11-25T07:58:40.000Z | 2022-01-31T21:15:49.000Z | jax/interpreters/pxla.py | cloudhan/jax | 9781f365a1c5dbdf57bf78b98831c4390eb9ca5f | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implementation of pmap and related functionality."""
# A ShardingSpec describes at a high level how a logical array is sharded across
# devices (each ShardedDeviceArray has a ShardingSpec, and ShardingSpecs also
# describe how to shard inputs to a parallel computation). spec_to_indices()
# encodes exactly how a given ShardingSpec is translated to device buffers, i.e.
# how the sharded array is "laid out" across devices. Given a sequence of
# devices, we shard the data across the devices in row-major order, with
# replication treated as an extra inner dimension.
#
# For example, given the logical data array [1, 2, 3, 4], if we were to
# partition this array 4 ways with a replication factor of 2, for a total of 8
# devices, the data on each device would be: [1, 1], [2, 2], [3, 3], [4, 4].
#
# This encoding is assumed by various parts of the system, e.g. generating
# replica groups for collective operations.
from contextlib import contextmanager
from collections import defaultdict, OrderedDict
import dataclasses
from functools import partial
import itertools as it
import operator as op
import threading
from typing import (Any, Callable, Dict, List, NamedTuple, Optional,
Sequence, Set, Tuple, Type, Union, Iterable)
import sys
from absl import logging
import numpy as np
from .._src.config import config
from .. import core
from .. import linear_util as lu
from jax._src.abstract_arrays import array_types
from ..core import ConcreteArray, ShapedArray
from jax._src import device_array
from .._src import source_info_util
from .._src.util import (unzip3, prod, safe_map, safe_zip,
extend_name_stack, wrap_name, assert_unreachable,
tuple_insert, tuple_delete, distributed_debug_log)
from ..errors import JAXTypeError
from jax._src import dispatch
from jax._src.lib import xla_bridge as xb
from jax._src.lib import xla_client as xc
from jax._src.lib import pmap_lib
from ..tree_util import tree_flatten, tree_map
from . import batching
from . import partial_eval as pe
from . import xla
from . import ad
# Built in Python lists don't support weak refs but subclasses of lists do.
class WeakRefList(list):
pass
if sys.version_info >= (3, 8):
from functools import cached_property as maybe_cached_property
else:
maybe_cached_property = property
if sys.version_info >= (3, 9):
OrderedDictType = OrderedDict
else:
OrderedDictType = Dict
xops = xc.ops
unsafe_map, map = map, safe_map # type: ignore
Index = Union[int, slice, Tuple[Union[int, slice], ...]]
NoSharding = pmap_lib.NoSharding
Chunked = pmap_lib.Chunked
Unstacked = pmap_lib.Unstacked
ShardedAxis = pmap_lib.ShardedAxis
Replicated = pmap_lib.Replicated
_UNSHARDED_INSTANCE = NoSharding()
AvalDimSharding = Union[Unstacked, Chunked, NoSharding]
MeshDimAssignment = Union[ShardedAxis, Replicated]
ShardingSpec = pmap_lib.ShardingSpec
def sharding_spec_mesh_shape(self):
sharded_axis_sizes = []
for sharding in self.sharding:
if isinstance(sharding, NoSharding):
continue
elif isinstance(sharding, Unstacked):
sharded_axis_sizes.append(sharding.size)
elif isinstance(sharding, Chunked):
sharded_axis_sizes.extend(sharding.chunks)
else:
assert_unreachable(sharding)
return tuple(sharded_axis_sizes[a.axis] if isinstance(a, ShardedAxis) else a.replicas
for a in self.mesh_mapping)
def sharding_spec_sharding_proto(self):
"""Converts a ShardingSpec to an OpSharding proto.
See
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/compiler/xla/xla_data.proto#L601
for details on the OpSharding proto.
Unfortunately the semantics are not very well described in the proto spec, but the code here might help:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/compiler/xla/experimental/xla_sharding/xla_sharding.py
"""
mesh_shape = self.mesh_shape
mesh = np.arange(np.prod(mesh_shape)).reshape(mesh_shape)
sharded_axes = {} # maps sharded axis identifiers to mesh axis indices to which they're mapped
replicated_maxes = [] # lists mesh axis identifiers to replicate over
for maxis, assignment in enumerate(self.mesh_mapping):
if isinstance(assignment, Replicated):
replicated_maxes.append(maxis)
elif isinstance(assignment, ShardedAxis):
sharded_axes[assignment.axis] = maxis
else:
assert_unreachable(assignment)
proto = xc.OpSharding()
if len(replicated_maxes) == len(self.mesh_mapping):
proto.type = xc.OpSharding.Type.REPLICATED
return proto
else:
proto.type = xc.OpSharding.Type.OTHER
mesh_permutation = []
new_mesh_shape = []
next_sharded_axis = 0
for axis, sharding in enumerate(self.sharding):
if isinstance(sharding, NoSharding):
new_mesh_shape.append(1) # Add a dummy mesh axis we won't be sharding over
elif isinstance(sharding, Chunked):
for nchunks in sharding.chunks:
maxis = sharded_axes[next_sharded_axis]
assert mesh_shape[maxis] == nchunks
mesh_permutation.append(maxis)
next_sharded_axis += 1
new_mesh_shape.append(int(np.prod(sharding.chunks)))
elif isinstance(sharding, Unstacked):
raise RuntimeError("Cannot convert unstacked sharding specs to XLA OpSharding")
else:
assert_unreachable(sharding)
# Create the partial sharding proto if tensor is replicated over some mesh axes
if replicated_maxes:
new_mesh_shape.append(-1)
mesh_permutation.extend(replicated_maxes)
proto.replicate_on_last_tile_dim = True
proto_mesh = mesh.transpose(mesh_permutation).reshape(new_mesh_shape)
proto.tile_assignment_dimensions = list(proto_mesh.shape)
proto.tile_assignment_devices = list(proto_mesh.flat)
return proto
def sharding_spec_indices(self, shape: Tuple[int, ...]) -> np.ndarray:
"""Returns NumPy-style indices corresponding to a sharding spec.
Args:
shape: The shape of the logical array being sharded.
Returns:
An ndarray with the same shape as the logical mesh (as derived form
`mesh_mapping`). Each entry is a NumPy-style index selecting the subset of
the data array to be placed on a corresponding device. The indices can be
ints, slice objects with step=1, or tuples of those.
"""
assert len(shape) == len(self.sharding), (shape, self.sharding)
axis_indices: List[Sequence[Index]] = []
shard_indices_shape = []
for dim, sharding in enumerate(self.sharding):
axis_size = shape[dim]
if isinstance(sharding, NoSharding):
axis_indices.append([slice(None)])
# NOTE: We don't append unsharded dimensions to shard_indices_shape here,
# because they do not appear in the mesh mapping.
elif isinstance(sharding, Unstacked):
assert axis_size == sharding.size, f'{axis_size} != {sharding.size}'
axis_indices.append(range(axis_size))
shard_indices_shape.append(axis_size)
elif isinstance(sharding, Chunked):
total_chunks = int(np.prod(sharding.chunks))
shard_size, ragged = divmod(axis_size, total_chunks)
assert not ragged, (axis_size, total_chunks, dim)
axis_indices.append([slice(i * shard_size, (i + 1) * shard_size)
for i in range(total_chunks)])
shard_indices_shape.extend(sharding.chunks)
else:
assert_unreachable(sharding)
# shard_indices is an ndarray representing the sharded axes of the logical array,
# with each dimension having size equal to the number of shards across the corresponding
# logical array dimension, and each element containing the multi-dimensional index that
# is used to extract the corresponding shard of the logical array.
shard_indices = np.empty([prod(shard_indices_shape)], dtype=np.object_)
for i, idxs in enumerate(it.product(*axis_indices)):
shard_indices[i] = idxs
shard_indices = shard_indices.reshape(shard_indices_shape)
# Ensure that each sharded axis is used exactly once in the mesh mapping
num_sharded_dim = len(shard_indices_shape)
sharded_dim_perm = [a.axis for a in self.mesh_mapping if isinstance(a, ShardedAxis)]
assert (set(sharded_dim_perm) == set(range(num_sharded_dim)) and
len(sharded_dim_perm) == num_sharded_dim)
# Replicate/reorder the indices according to the mesh mapping
replica_sizes = tuple(a.replicas for a in self.mesh_mapping if isinstance(a, Replicated))
replica_dim, sharded_dim = it.count(0), iter(sharded_dim_perm)
perm = [next(replica_dim) if isinstance(a, Replicated) else
len(replica_sizes) + next(sharded_dim)
for a in self.mesh_mapping]
return (np.broadcast_to(shard_indices, replica_sizes + shard_indices.shape)
.transpose(perm))
def sharding_spec_repr(self):
return f'ShardingSpec({self.sharding}, {self.mesh_mapping})'
ShardingSpec.mesh_shape = property(sharding_spec_mesh_shape)
ShardingSpec.sharding_proto = sharding_spec_sharding_proto
ShardingSpec.indices = sharding_spec_indices
# mypy raises: error: Cannot assign to a method [assignment]
ShardingSpec.__repr__ = sharding_spec_repr # type: ignore
# Do not pollute the namespace
del sharding_spec_mesh_shape, sharding_spec_indices, sharding_spec_repr
def spec_to_indices(shape: Tuple[int, ...],
spec: ShardingSpec) -> Tuple[Index, ...]:
"""Returns numpy-style indices corresponding to a sharding spec.
Each index describes a shard of the array. The order of the indices is the
same as the device_buffers of a ShardedDeviceArray (i.e. the data is laid out
row-major).
Args:
shape: The shape of the logical array being sharded.
spec: Describes how the array is sharded and how the shards are assigned to
the logical mesh.
Returns:
A tuple of length equal to the size of the mesh (inferred as the product of
sharded dimension sizes and all replication factors). Each element is an
int, a slice object with step=1, or a tuple thereof, to be treated as an
index into the full logical array.
"""
return tuple(spec.indices(shape).flat) # type: ignore
### util
def identity(x): return x
def _shard_arg(arg, devices, arg_indices):
"""Returns a list of size len(devices) containing per-device buffers.
For the C++ pmap path, we fallback to Python (this function) to shard
arguments that are not supported by the C++ `ShardArg`.
Arrgs:
arg: The Python argument.
devices: The list of devices to shard over.
arg_indices: A list of `len(devices)` indices to use to shard the argument.
"""
if isinstance(arg, ShardedDeviceArray) and arg_indices == arg.indices:
# The shard_arg_handlers allow an extensible set of types to be sharded, but
# inline handling for ShardedDeviceArray as a special case for performance
# NOTE: we compare indices instead of sharding_spec because
# pmap_benchmark.pmap_shard_args_benchmark indicates this is faster.
return [
buf if buf.device() == d else buf.copy_to_device(d)
for d, buf in zip(devices, arg.device_buffers)
]
else:
arg = xla.canonicalize_dtype(arg)
return shard_arg_handlers[type(arg)](arg, devices, arg_indices)
def shard_args(devices: Sequence[xb.xla_client.Device],
indices: Sequence[Sequence[Index]],
args) -> Sequence[Sequence[xb.xla_client.Buffer]]:
"""Shard each argument data array along its leading axis.
Args:
devices: sequence of Devices mapping replica index to a physical device.
indices: sequence of the same length as `args` describing how each arg
should be sharded/replicated across `devices`. Each element in `indices`
is the same length as `devices`.
args: a sequence of JaxTypes representing arguments to be sharded according
to `indices` and placed on `devices`.
Returns:
A list of length matching args, containing lists of per-device buffers
for each argument.
"""
return [_shard_arg(arg, devices, indices[a]) for a, arg in enumerate(args)]
shard_arg_handlers: Dict[Any, Callable[[Any, Any, Any], Sequence[Any]]] = {}
shard_arg_handlers[core.Unit] = \
lambda x, devices, _: device_put(core.unit, devices, replicate=True)
def _shard_array(x, devices, indices):
return device_put([x[i] for i in indices], devices)
for _t in array_types:
shard_arg_handlers[_t] = _shard_array
def _shard_device_array(x, devices, indices):
start_indices, limit_indices, removed_dims = unzip3(
_as_slice_indices(x, idx) for idx in indices)
shards = x._multi_slice(start_indices, limit_indices, removed_dims)
return device_put(shards, devices)
for t in device_array.device_array_types:
shard_arg_handlers[t] = _shard_device_array
# NOTE(skye): we could refactor to generate _multi_slice parameters directly
# from the input ShardingSpec, rather than the indices. However, this would
# require duplicating the ordering logic of spec_to_indices, which is more
# subtle and more likely to change than the index logic we have to support here.
def _as_slice_indices(arr: device_array.DeviceArrayProtocol, idx: Index) -> Tuple[
Tuple[int, ...], Tuple[int, ...], Tuple[int, ...]]:
"""Returns start_indices, limit_indices, removed_dims"""
start_indices = [0] * arr.ndim
limit_indices = list(arr.shape)
removed_dims = []
tuple_idx = idx if isinstance(idx, tuple) else (idx,)
for dim, sub_idx in enumerate(tuple_idx):
if isinstance(sub_idx, int):
start_indices[dim] = sub_idx
limit_indices[dim] = sub_idx + 1
removed_dims.append(dim)
elif sub_idx == slice(None):
continue
else:
assert isinstance(sub_idx, slice), sub_idx
assert isinstance(sub_idx.start, int), sub_idx
assert isinstance(sub_idx.stop, int), sub_idx
start_indices[dim] = sub_idx.start
limit_indices[dim] = sub_idx.stop
return tuple(start_indices), tuple(limit_indices), tuple(removed_dims) # type: ignore
def shard_aval(size, axis: int, aval):
try:
return shard_aval_handlers[type(aval)](size, axis, aval)
except KeyError as err:
raise TypeError(f"No shard_aval handler for type: {type(aval)}") from err
shard_aval_handlers: Dict[Type[core.AbstractValue], Callable[[int, int, Any], Any]] = {}
shard_aval_handlers[core.AbstractUnit] = lambda size, axis, x: x
def _shard_abstract_array(size, axis: int, x):
try:
if x.shape[axis] != size:
raise ValueError(f"Axis size {size} does not match dimension {axis} of "
f"shape {x.shape}")
except IndexError:
raise ValueError("Cannot split a {x.dim}D value along axis {axis}") from None
return x.update(shape=tuple_delete(x.shape, axis))
shard_aval_handlers[ShapedArray] = _shard_abstract_array
MeshAxisName = Any
"""
ArrayMapping specifies how an ndarray should map to mesh axes.
Note that the ordering is crucial for the cases when this mapping is non-injective
(i.e. when multiple mesh axes map to the same positional axis). Then, the
order of entries of the mapping determines a major-to-minor order on mesh axes,
according to which chunks of the value along the repeated dimension will be assigned.
For example, consider a mapping {'x': 1, 'y': 1} and a mesh with shape {'x': 2, 'y': 3}.
The second dimension of the value would get chunked into 6 pieces, and assigned to the
mesh in a way that treats 'y' as the fastest changing (minor) dimension. In this case,
that would mean that a flat list of chunks would get assigned to a flattened list of
mesh devices without any modifications. If the mapping was {'y': 1, 'x': 1}, then the
mesh devices ndarray would have to be transposed before flattening and assignment.
"""
ArrayMapping = OrderedDictType[MeshAxisName, int]
AxisResource = Tuple[Optional[Tuple[Any, ...]], ...]
def array_mapping_to_axis_resources(array_mapping: ArrayMapping) -> AxisResource:
if not array_mapping:
return tuple()
max_index = array_mapping[max(array_mapping, key=array_mapping.get)] # type: ignore
reverse_map = defaultdict(list)
for axis, index in array_mapping.items():
reverse_map[index].append(axis)
return tuple(
tuple(reverse_map[i]) if reverse_map[i] else None for i in range(max_index + 1)
)
def aval_to_result_handler(
sharding_spec: Optional[ShardingSpec],
indices: Optional[Tuple[Index]],
aval: core.AbstractValue,
global_aval: Optional[ShapedArray] = None,
out_axis_resources: Optional[AxisResource] = None,
global_mesh = None,
) -> Callable[[List[xb.xla_client.Buffer]], Any]:
"""Returns a function for handling the raw buffers of a single output aval.
Args:
sharding_spec: Indicates how the output is sharded across devices, or None
for non-array avals.
indices: The pre-computed result of spec_to_indices, or None for non-array
avals.
aval: The output AbstractValue.
global_aval: Global output AbstractValue. Used for creating GSDAs.
out_axis_resources: A tuple specifying the sharding of outputs.
Used for creating GSDAs.
global_mesh: The global device mesh that generated this output. Used
for creating GSDAs.
Returns:
A function for handling the Buffers that will eventually be produced
for this output. The function will return an object suitable for returning
to the user, e.g. a ShardedDeviceArray.
"""
try:
return pxla_result_handlers[type(aval)](sharding_spec, indices, aval,
global_aval, out_axis_resources, global_mesh)
except KeyError as err:
raise TypeError("No pxla_result_handler for type: {}".format(type(aval))
) from err
PxlaResultHandler = Callable[..., Callable[[List[xb.xla_client.Buffer]], Any]]
pxla_result_handlers: Dict[Type[core.AbstractValue], PxlaResultHandler] = {}
pxla_result_handlers[core.AbstractUnit] = lambda *_: lambda _: core.unit
def array_result_handler(sharding_spec, indices, aval: ShapedArray, global_aval,
out_axis_resources, global_mesh):
if config.jax_gsda_out:
return gsda_array_result_handler(global_aval, global_mesh, out_axis_resources)
else:
return sda_array_result_handler(sharding_spec, indices, aval)
pxla_result_handlers[ShapedArray] = array_result_handler
pxla_result_handlers[ConcreteArray] = array_result_handler
def sda_array_result_handler(sharding_spec, indices, aval: ShapedArray):
return lambda bufs: make_sharded_device_array(aval, sharding_spec, bufs,
indices)
def gsda_array_result_handler(global_aval, global_mesh, out_axis_resources):
from ..experimental.gsda import GlobalShardedDeviceArray
return lambda bufs: GlobalShardedDeviceArray(
global_aval.shape, global_mesh, out_axis_resources, bufs)
### lazy device-memory persistence and result handling
# TODO(jblespiau): Consider removing this option.
_USE_CPP_SDA = True
def make_sharded_device_array(
aval: ShapedArray,
sharding_spec: Optional[ShardingSpec],
# Any is for JAX extensions implementing their own buffer.
device_buffers: List[Union[Any, xb.xla_client.Buffer]],
indices: Optional[Tuple[Index, ...]] = None,
):
"""Returns a ShardedDeviceArray implementation based on arguments.
Returns either a C++ SDA or a Python DeviceArray when the buffers are not
JAX buffers.
Args:
aval: The `ShapedArray` for this array.
sharding_spec: If `None`, assumes a pmap-style ShardedDeviceArrays over the
first dimension.
device_buffers: If a list of Jax `Buffer` objects, a C++ SDA will be
returned (if the version is high enough). Otherwise, a Python object will
be returned, for JAX extensions not implementing the C++ API.
indices: For caching purposes, will be computed if `None`.
"""
if sharding_spec is None:
sharded_aval = aval.update(shape=aval.shape[1:])
sharding_spec = _pmap_sharding_spec(aval.shape[0], aval.shape[0], 1, None,
sharded_aval, 0)
if indices is None:
indices = spec_to_indices(aval.shape, sharding_spec)
if (_USE_CPP_SDA and
(not device_buffers or
isinstance(device_buffers[0], xb.xla_client.Buffer))):
return pmap_lib.ShardedDeviceArray.make(
aval, sharding_spec, device_buffers,
indices, aval.weak_type)
return _ShardedDeviceArray(aval, sharding_spec, device_buffers, indices)
if _USE_CPP_SDA:
ShardedDeviceArrayBase = pmap_lib.ShardedDeviceArrayBase # type: ignore
# We want the C++ SDA to extend the DeviceArrayBase. We want this both to
# benefit from its methods, and to have isinstance(x, DeviceArray) return true
ShardedDeviceArrayBase.__bases__ = ((device_array.DeviceArray,) + # type: ignore
ShardedDeviceArrayBase.__bases__)
_SDA_BASE_CLASS = pmap_lib.ShardedDeviceArrayBase # type: ignore
else:
_SDA_BASE_CLASS: Type[device_array.DeviceArray] = device_array.DeviceArray # type: ignore
class _ShardedDeviceArray(_SDA_BASE_CLASS): # type: ignore
"""A ShardedDeviceArray is an ndarray sharded across devices.
The purpose of a ShardedDeviceArray is to reduce the number of transfers when
executing replicated computations, by allowing results to persist on the
devices that produced them. That way dispatching a similarly replicated
computation that consumes the same sharded memory layout does not incur any
transfers.
A ShardedDeviceArray represents one logical ndarray value, and simulates the
behavior of an ndarray so that it can be treated by user code as an ndarray;
that is, it is only an optimization to reduce transfers.
Attributes:
aval: A ShapedArray indicating the shape and dtype of this array.
sharding_spec: describes how this array is sharded across `device_buffers`.
device_buffers: the buffers containing the data for this array. Each buffer
is the same shape and on a different device. Buffers are in row-major
order, with replication treated as an extra innermost dimension.
indices: the result of spec_to_indices(sharding_spec). Can optionally be
precomputed for efficiency. A list the same length as
`device_buffers`. Each index indicates what portion of the full array is
stored in the corresponding device buffer, i.e. `array[indices[i]] ==
device_buffers[i].to_py()`.
"""
__slots__ = [
"aval", "device_buffers", "sharding_spec", "indices",
"_one_replica_buffer_indices", "_npy_value"
]
def __init__(self,
aval: ShapedArray,
sharding_spec: ShardingSpec,
device_buffers: List[xb.xla_client.Buffer],
indices: Optional[Tuple[Index, ...]] = None):
super().__init__()
# TODO(skye): assert invariants. Keep performance in mind though.
if indices is None:
indices = spec_to_indices(aval.shape, sharding_spec)
self.aval = aval
self.device_buffers = device_buffers
self.sharding_spec = sharding_spec
self.indices = indices
self._npy_value = None
self._one_replica_buffer_indices = None
if config.jax_enable_checks:
assert type(aval) is ShapedArray
@property
def shape(self):
return self.aval.shape
@property
def dtype(self):
return self.aval.dtype
@property
def size(self):
return prod(self.aval.shape)
@property
def ndim(self):
return len(self.aval.shape)
def delete(self):
if self.device_buffers is None:
return
for buf in self.device_buffers:
buf.delete()
self.device_buffers = None
self._npy_value = None
def _sda_one_replica_buffer_indices(self):
"""Indices of buffers containing one complete copy of the array data."""
if self._one_replica_buffer_indices is None:
one_replica_indices = []
seen_index_hashes = set()
for i, index in enumerate(self.indices):
hashed_index = _hashable_index(index)
if hashed_index not in seen_index_hashes:
one_replica_indices.append(i)
seen_index_hashes.add(hashed_index)
self._one_replica_buffer_indices = one_replica_indices
return self._one_replica_buffer_indices
def _sda_copy_to_host_async(self):
for buffer_index in self.one_replica_buffer_indices:
self.device_buffers[buffer_index].copy_to_host_async()
def _sda_check_if_deleted(self):
if self.device_buffers is None:
raise ValueError("ShardedDeviceArray has been deleted.")
def _sda_block_until_ready(self):
self._check_if_deleted()
for buf in self.device_buffers:
buf.block_host_until_ready()
return self
def _sda_value(self):
if self._npy_value is None:
self.copy_to_host_async()
npy_value = np.empty(self.aval.shape, self.aval.dtype)
for i in self.one_replica_buffer_indices:
npy_value[self.indices[i]] = self.device_buffers[i].to_py()
self._npy_value = npy_value
return self._npy_value
def _sda__getitem__(self, idx):
self._check_if_deleted()
if not isinstance(idx, tuple):
cidx = (idx,) + (slice(None),) * (len(self.aval.shape) - 1)
else:
cidx = idx + (slice(None),) * (len(self.aval.shape) - len(idx))
if self._npy_value is None:
try:
buf_idx = self.indices.index(cidx)
except ValueError:
buf_idx = None
if buf_idx is not None:
buf = self.device_buffers[buf_idx]
aval = ShapedArray(buf.xla_shape().dimensions(), self.aval.dtype)
return device_array.make_device_array(aval, None, buf)
return super(self.__class__, self).__getitem__(idx)
def _sda__iter__(self):
if self.ndim == 0:
raise TypeError("iteration over a 0-d array") # same as numpy error
else:
return (self[i] for i in range(self.shape[0]))
def _sda__reversed__(self):
if self.ndim == 0:
raise TypeError("iteration over a 0-d array") # same as numpy error
else:
return (self[i] for i in range(self.shape[0] - 1, -1, -1))
for sda in [_ShardedDeviceArray, pmap_lib.ShardedDeviceArray]:
setattr(sda, "one_replica_buffer_indices",
property(_sda_one_replica_buffer_indices))
setattr(sda, "copy_to_host_async", _sda_copy_to_host_async)
setattr(sda, "_check_if_deleted", _sda_check_if_deleted)
setattr(sda, "block_until_ready", _sda_block_until_ready)
setattr(sda, "_value", property(_sda_value))
setattr(sda, "__getitem__", _sda__getitem__)
setattr(sda, "__iter__", _sda__iter__)
setattr(sda, "__reversed__", _sda__reversed__)
del (_sda_one_replica_buffer_indices, _sda_copy_to_host_async,
_sda_check_if_deleted, _sda_block_until_ready, _sda_value, _sda__getitem__)
ShardedDeviceArray: Type[object]
if _USE_CPP_SDA:
ShardedDeviceArray = pmap_lib.ShardedDeviceArrayBase
else:
ShardedDeviceArray = _ShardedDeviceArray
def _hashable_index(idx):
return tree_map(lambda x: (x.start, x.stop) if type(x) == slice else x,
idx)
# The fast path is handled directly in shard_args().
# TODO(skye): is there a simpler way to rewrite this using sharding_spec?
def _shard_sharded_device_array_slow_path(x, devices, indices):
candidates = defaultdict(list)
for buf, idx in safe_zip(x.device_buffers, x.indices):
candidates[_hashable_index(idx)].append(buf)
bufs = []
for idx, device in safe_zip(indices, devices):
# Look up all buffers that contain the correct slice of the logical array.
candidates_list = candidates[_hashable_index(idx)]
if not candidates_list:
# This array isn't sharded correctly. Reshard it via host roundtrip.
# TODO(skye): more efficient reshard?
return shard_arg_handlers[type(x._value)](x._value, devices, indices)
# Try to find a candidate buffer already on the correct device,
# otherwise copy one of them.
for buf in candidates_list:
if buf.device() == device:
bufs.append(buf)
break
else:
bufs.append(buf.copy_to_device(device))
return bufs
def _sharded_device_array_constant_handler(c, val, canonicalize_types=True):
return xla.pyval_to_ir_constants(c, np.asarray(val),
canonicalize_types=canonicalize_types)
def _register_handlers_for_sharded_device_array(sda):
shard_arg_handlers[sda] = _shard_sharded_device_array_slow_path
xla.register_constant_handler(sda, _sharded_device_array_constant_handler)
core.pytype_aval_mappings[sda] = ConcreteArray
dispatch.device_put_handlers[sda] = dispatch._device_put_array
xla.pytype_aval_mappings[sda] = op.attrgetter("aval")
xla.canonicalize_dtype_handlers[sda] = identity
_register_handlers_for_sharded_device_array(_ShardedDeviceArray)
_register_handlers_for_sharded_device_array(pmap_lib.ShardedDeviceArray)
### the xla_pmap primitive and its rules are comparable to xla_call in xla.py
def xla_pmap_impl(fun: lu.WrappedFun, *args,
backend: Optional[str],
axis_name: core.AxisName,
axis_size: int,
global_axis_size: Optional[int],
devices: Optional[Sequence[Any]],
name: str,
in_axes: Sequence[Optional[int]],
out_axes_thunk: Callable[[], Sequence[Optional[int]]],
donated_invars: Sequence[bool],
global_arg_shapes: Sequence[Optional[Tuple[int, ...]]]):
abstract_args = unsafe_map(xla.abstractify, args)
compiled_fun, fingerprint = parallel_callable(
fun, backend, axis_name, axis_size, global_axis_size, devices, name,
in_axes, out_axes_thunk, donated_invars, global_arg_shapes,
*abstract_args)
# Don't re-abstractify args unless logging is enabled for performance.
if config.jax_distributed_debug:
distributed_debug_log(("Running pmapped function", name),
("python function", fun.f),
("devices", devices),
("abstract args", map(xla.abstractify, args)),
("fingerprint", fingerprint))
return compiled_fun(*args)
@lu.cache
def parallel_callable(fun: lu.WrappedFun,
backend_name: Optional[str],
axis_name: core.AxisName,
axis_size: int,
global_axis_size: Optional[int],
devices: Optional[Sequence[Any]],
name: str,
in_axes: Sequence[Optional[int]],
out_axes_thunk: Callable[[], Sequence[Optional[int]]],
donated_invars: Sequence[bool],
global_arg_shapes: Sequence[Optional[Tuple[int, ...]]],
*avals):
pmap_computation = lower_parallel_callable(
fun, backend_name, axis_name, axis_size, global_axis_size, devices, name,
in_axes, out_axes_thunk, donated_invars, global_arg_shapes, avals)
pmap_executable = pmap_computation.compile()
return WeakRefList([pmap_executable.unsafe_call, pmap_executable.fingerprint])
@dataclasses.dataclass(frozen=True)
class ParallelCallableInfo:
backend: Any # TODO(frostig): really xla.Backend, fix xla_bridge annotations
axis_name: core.AxisName
axis_size: int
global_axis_size: Optional[int]
devices: Optional[Sequence[xla.Device]]
in_axes: Iterable[Optional[int]]
out_axes_thunk: Callable[[], Sequence[Optional[int]]]
avals: Sequence[core.AbstractValue]
@maybe_cached_property
def local_devices(self):
if self.devices:
out = [d for d in self.devices
if d.process_index == xb.process_index(self.backend)]
assert len(out) > 0
else:
out = None # type: ignore
return out
@maybe_cached_property
def out_axes(self):
return self.out_axes_thunk()
class ShardInfo(NamedTuple):
sharded_avals: Sequence[core.AbstractValue]
out_sharded_avals: Sequence[core.AbstractValue]
global_sharded_avals: Sequence[core.AbstractValue]
num_local_shards: int
num_global_shards: int
class ReplicaInfo(NamedTuple):
jaxpr_replicas: int
num_local_replicas: int
num_global_replicas: int
def find_replicas(jaxpr, axis_size, global_axis_size):
# TODO(skyewm): replace this with a chain of pmaps and/or sharded_jits
jaxpr_replicas = dispatch.jaxpr_replicas(jaxpr)
num_local_replicas = axis_size * jaxpr_replicas
num_global_replicas = global_axis_size * jaxpr_replicas
return ReplicaInfo(jaxpr_replicas, num_local_replicas, num_global_replicas)
def tuple_args(shards: ShardInfo):
# tuplify long arg lists for TPU
return len(shards.global_sharded_avals) > 100
def stage_parallel_callable(
pci: ParallelCallableInfo,
fun: lu.WrappedFun,
global_arg_shapes: Sequence[Optional[Tuple[int, ...]]]):
sharded_avals = tuple(
shard_aval(pci.axis_size, axis, aval) if axis is not None else aval
for axis, aval in safe_zip(pci.in_axes, pci.avals))
if any(s is not None for s in global_arg_shapes):
# TODO(skye): we could take this branch unconditionally if we handled
# grad of global_arg_shapes correctly.
global_sharded_avals = [
aval.update(shape=shape) if shape is not None else aval
for shape, aval in safe_zip(global_arg_shapes, sharded_avals)]
else:
global_sharded_avals = sharded_avals # type: ignore
with core.extend_axis_env(pci.axis_name, pci.global_axis_size, None): # type: ignore
jaxpr, out_sharded_avals, consts = pe.trace_to_jaxpr_final(
fun, global_sharded_avals, pe.debug_info_final(fun, "pmap"))
jaxpr = dispatch.apply_outfeed_rewriter(jaxpr)
assert len(out_sharded_avals) == len(pci.out_axes), (
len(out_sharded_avals), len(pci.out_axes))
# TODO(skye,mattjj): allow more collectives on multi-host as we test them, but
# for now raise an error
if pci.devices is not None:
is_multi_host_pmap = len(pci.local_devices) != len(pci.devices)
else:
is_multi_host_pmap = xb.process_count(pci.backend) > 1
if is_multi_host_pmap:
check_multihost_collective_allowlist(jaxpr)
replicas = find_replicas(jaxpr, pci.axis_size, pci.global_axis_size)
parts = find_partitions(jaxpr)
num_local_shards = replicas.num_local_replicas * parts.local_num_partitions
num_global_shards = replicas.num_global_replicas * parts.num_partitions
shards = ShardInfo(
sharded_avals, out_sharded_avals, global_sharded_avals,
num_local_shards, num_global_shards)
return jaxpr, consts, replicas, parts, shards
def lower_parallel_callable(
fun: lu.WrappedFun,
backend_name: Optional[str],
axis_name: core.AxisName,
axis_size: int,
global_axis_size: Optional[int],
devices: Optional[Sequence[xla.Device]],
name: str,
in_axes: Iterable[Optional[int]],
out_axes_thunk: Callable[[], Sequence[Optional[int]]],
donated_invars: Sequence[bool],
global_arg_shapes: Sequence[Optional[Tuple[int, ...]]],
avals: Sequence[core.AbstractValue]):
if devices is not None and len(devices) == 0:
raise ValueError("'devices' argument to pmap must be non-empty, or None.")
# Determine global_axis_size for use in AxisEnv.
# TODO(mattjj,skyewm): revive this check (inner_pmap always False now)
# if xb.process_count() > 1 and global_axis_size is None and inner_pmap:
# raise ValueError("'axis_size' must be specified for nested multi-host pmaps")
if (xb.process_count() == 1 and global_axis_size is not None and
global_axis_size != axis_size):
raise ValueError(
f"Specified axis_size {global_axis_size} doesn't match received "
f"axis_size {axis_size}.")
if devices is not None and backend_name is None:
backend = xb.get_device_backend(devices[0])
else:
backend = xb.get_backend(backend_name)
must_run_on_all_devices = False
no_nested_sharding = False
if global_axis_size is None:
if xb.process_count(backend) == 1:
global_axis_size = axis_size
elif devices:
# This allows each host in a multi-host pmap to run on a different number
# of devices, but precludes nested sharding (i.e. inner pmaps or
# sharded_jits).
global_axis_size = len(devices)
no_nested_sharding = True
else:
# This assumes all hosts run on the same number of devices. We make sure
# this assumption is true by requiring that the pmap is run on all devices
# (and making the further assumption that each host has the same number of
# devices). Nested sharding is ok in this case.
global_axis_size = axis_size * xb.process_count(backend)
assert all(
len(xb.local_devices(process_index, backend)) == xb.local_device_count(backend)
for process_index in range(xb.process_count(backend)))
must_run_on_all_devices = True
pci = ParallelCallableInfo(
backend, axis_name, axis_size, global_axis_size, devices, in_axes,
out_axes_thunk, avals)
jaxpr, consts, replicas, parts, shards = stage_parallel_callable(
pci, fun, global_arg_shapes)
if logging.vlog_is_on(2):
logging.vlog(2, "sharded_avals: %s", shards.sharded_avals)
logging.vlog(2, "global_sharded_avals: %s", shards.global_sharded_avals)
logging.vlog(2, "num_replicas: %d num_local_replicas: %d",
replicas.num_global_replicas, replicas.num_local_replicas)
logging.vlog(2, "num_partitions: %d local_num_partitions: %d",
parts.num_partitions, parts.local_num_partitions)
logging.vlog(2, "arg_parts: %s", parts.arg_parts)
logging.vlog(2, "local_arg_parts: %s", parts.local_arg_parts)
logging.vlog(2, "out_parts: %s", parts.out_parts)
logging.vlog(2, "local_out_parts: %s", parts.local_out_parts)
logging.vlog(2, "devices: %s", devices)
logging.vlog(2, "local_devices: %s", pci.local_devices)
if (xb.process_count(backend) > 1 and must_run_on_all_devices and
shards.num_local_shards != xb.local_device_count(backend)):
if shards.num_local_shards == axis_size:
raise ValueError(
f"On multi-host platforms, the input to pmapped functions must have "
f"leading axis size equal to the number of local devices if no "
f"`devices` argument is specified. Got axis_size={axis_size}, "
f"num_local_devices={xb.local_device_count(backend)}")
else:
raise ValueError(
f"On multi-host platforms, pmapped functions must run across all "
f"devices, i.e. num_replicas * num_partitions should equal the "
f"number of local devices. Got "
f"num_replicas={replicas.num_local_replicas}, "
f"num_partitions={parts.num_partitions}, and "
f"num_local_devices={xb.local_device_count(backend)}")
if no_nested_sharding and (
replicas.jaxpr_replicas > 1 or parts.num_partitions > 1):
raise ValueError(
f"On multi-host platforms, pmapped functions that both have `devices` "
f"specified and contain an inner_pmap or sharded_jit must specify an "
f"`axis_size` (or remove the `devices` argument). Got nested_replicas="
f"{replicas.jaxpr_replicas} and nested_partitions={parts.num_partitions}")
log_priority = logging.WARNING if config.jax_log_compiles else logging.DEBUG
logging.log(log_priority,
"Compiling %s (%d) for %d devices with args %s. (num_replicas=%d"
" num_partitions=%d)", fun.__name__, id(fun),
shards.num_global_shards, avals, replicas.num_global_replicas,
parts.num_partitions)
axis_env = xla.AxisEnv(
replicas.num_global_replicas, (axis_name,), (global_axis_size,))
c = xc.XlaBuilder("pmap_{}".format(fun.__name__))
xla_consts = map(partial(xla.pyval_to_ir_constant, c), consts)
replicated_args = [axis is None for axis in in_axes]
xla_args, donated_invars = xla._xla_callable_args(
c, shards.global_sharded_avals, tuple_args(shards),
replicated=replicated_args,
partitions=parts.arg_parts,
donated_invars=donated_invars)
with maybe_extend_axis_env(axis_name, global_axis_size, None): # type: ignore
ctx = xla.TranslationContext(c, backend.platform, axis_env,
extend_name_stack(wrap_name(name, 'pmap')))
out_nodes = xla.jaxpr_subcomp(ctx, jaxpr, xla_consts, *xla_args)
build_out_tuple = partial(xops.Tuple, c, out_nodes)
if parts.out_parts is not None:
out_tuple = xb.with_sharding(c, parts.out_parts, build_out_tuple)
else:
out_tuple = build_out_tuple()
if backend.platform in ("gpu", "tpu"):
donated_invars = xla.set_up_aliases(c, xla_args, c.GetShape(out_tuple),
donated_invars, tuple_args(shards))
built = c.Build(out_tuple)
return PmapComputation(built, pci, replicas, parts, shards)
class PmapComputation:
def __init__(self, hlo, *compile_args):
self._executable = None
self.hlo = hlo
self.compile_args = compile_args
def compile(self):
if self._executable is None:
self._executable = PmapExecutable.from_hlo(self.hlo, *self.compile_args)
return self._executable
class PmapExecutable:
__slots__ = ['xla_executable', 'unsafe_call', 'fingerprint', 'in_avals']
def __init__(self, xla_executable, unsafe_call, fingerprint, in_avals):
self.xla_executable = xla_executable
self.unsafe_call = unsafe_call
self.fingerprint = fingerprint
self.in_avals = in_avals
@staticmethod
def from_hlo(xla_computation,
pci: ParallelCallableInfo,
replicas: ReplicaInfo,
parts: 'PartitionInfo',
shards: ShardInfo):
devices = pci.devices
if devices is None:
if shards.num_global_shards > xb.device_count(pci.backend):
msg = ("compiling computation that requires {} logical devices, but only {} XLA "
"devices are available (num_replicas={}, num_partitions={})")
raise ValueError(msg.format(shards.num_global_shards,
xb.device_count(pci.backend),
replicas.num_global_replicas,
parts.num_partitions))
# On a single host, we use the platform's default device assignment to
# potentially take advantage of device locality. On multiple hosts, the
# default device assignment may interleave different hosts' replicas,
# violating pmap's semantics where data is sharded across replicas in
# row-major order. Instead, manually create a device assignment that ensures
# each host is responsible for a continguous set of replicas.
if shards.num_global_shards > shards.num_local_shards:
# TODO(skye): use a locality-aware assignment that satisfies the above
# constraint.
devices = [d for process_index in range(xb.process_count(pci.backend))
for d in xb.local_devices(process_index, pci.backend)]
else:
devices = xb.get_backend(pci.backend).get_default_device_assignment(
replicas.num_global_replicas, parts.num_partitions)
else:
if shards.num_local_shards != len(pci.local_devices):
local_devices_str = ", ".join(map(str, pci.local_devices))
if shards.num_local_shards == pci.axis_size:
raise ValueError(
f"Leading axis size of input to pmapped function must equal the "
f"number of local devices passed to pmap. Got axis_size="
f"{pci.axis_size}, num_local_devices={len(pci.local_devices)}.\n"
f"(Local devices available to pmap: {local_devices_str})")
else:
raise ValueError(
f"pmapped function requires {shards.num_local_shards} local "
f"devices to run due to nested pmapped or other parallel "
f"functions, but only {len(pci.local_devices)} are available.\n"
f"(outer axis size: {pci.axis_size}, local devices available to "
f"pmap: {local_devices_str})")
if shards.num_global_shards != len(devices):
raise ValueError("compiling computation that creates %s shards, "
"but %s devices were specified" %
(shards.num_global_shards, len(devices)))
# 'devices' may be 1D or 2D at this point (e.g.
# get_default_device_assignment() returns 2D assignment, caller may have
# provided 1D list of devices).
device_assignment = tree_map(lambda d: d.id, devices)
# Convert to 2D in case it's 1D and we have > 1 partitions.
device_assignment = np.array(device_assignment).reshape(
(replicas.num_global_replicas, parts.num_partitions))
# TODO(b/162356737): Enabling SPMD partitioning causes issues with some
# non-partitioned workloads, so disable unless needed.
use_spmd_partitioning = parts.num_partitions > 1
compile_options = xb.get_compile_options(
num_replicas=replicas.num_global_replicas,
num_partitions=parts.num_partitions,
device_assignment=device_assignment,
use_spmd_partitioning=use_spmd_partitioning,
)
compile_options.parameter_is_tupled_arguments = tuple_args(shards)
local_arg_parts_ = parts.local_arg_parts or [None] * len(pci.avals)
input_sharding_specs = [
_pmap_sharding_spec(replicas.num_local_replicas, pci.axis_size,
parts.local_num_partitions, arg_parts, aval, in_axis)
if aval is not core.abstract_unit else None
for aval, arg_parts, in_axis in safe_zip(
shards.sharded_avals, local_arg_parts_, pci.in_axes)]
input_indices = [spec_to_indices(aval.shape, spec)
if spec is not None else None
for aval, spec in safe_zip(pci.avals, input_sharding_specs)]
nouts = len(shards.out_sharded_avals)
out_parts, local_out_parts = parts.out_parts, parts.local_out_parts
if parts.out_parts is None:
out_parts = (None,) * nouts
if parts.local_out_parts is None:
local_out_parts = (None,) * nouts
local_out_avals = [
get_local_aval(aval, parts, lparts)
for aval, parts, lparts
in safe_zip(shards.out_sharded_avals, out_parts, local_out_parts)]
local_unmapped_avals = [
core.unmapped_aval(pci.axis_size, pci.axis_name, out_axis, aval)
if out_axis is not None else aval
for aval, out_axis in safe_zip(local_out_avals, pci.out_axes)]
out_specs = [
_pmap_sharding_spec(replicas.num_local_replicas, pci.axis_size,
parts.local_num_partitions, out_parts, aval, out_axis)
if aval is not core.abstract_unit else None
for out_parts, aval, out_axis in safe_zip(
local_out_parts, local_out_avals, pci.out_axes)]
handle_outs = avals_to_results_handler(
replicas.num_local_replicas, parts.local_num_partitions, out_specs,
local_unmapped_avals)
if hasattr(pci.backend, "compile_replicated"):
execute_fun = pci.backend.compile_replicated(
xla_computation, compile_options, input_indices, input_sharding_specs,
handle_outs)
# TODO(frostig): need `compile_replicated` to give us the XLA executable
return PmapExecutable(None, execute_fun, None, pci.avals)
compiled = dispatch.compile_or_get_cached(
pci.backend, xla_computation, compile_options)
handle_args = InputsHandler(
compiled.local_devices(), input_sharding_specs, input_indices)
execute_fun = partial(
execute_replicated, compiled, pci.backend, handle_args, handle_outs)
fingerprint = getattr(compiled, "fingerprint", None)
return PmapExecutable(compiled, execute_fun, fingerprint, pci.avals)
def call(self, *args):
# TODO(frostig): do we need to check sharding and sharded avals?
arg_avals = map(xla.abstractify, args)
dispatch.check_arg_avals_for_call(self.in_avals, arg_avals)
return self.unsafe_call(*args)
multi_host_supported_collectives: Set[core.Primitive] = set()
def check_multihost_collective_allowlist(jaxpr):
used_collectives = set(xla.jaxpr_collectives(jaxpr))
if not used_collectives.issubset(multi_host_supported_collectives):
bad_collectives = used_collectives - multi_host_supported_collectives
msg = "using collectives that aren't supported for multi-host: {}"
raise TypeError(msg.format(", ".join(map(str, bad_collectives))))
PartitionsOrReplicated = Optional[Tuple[int, ...]]
class PartitionInfo(NamedTuple):
arg_parts: Optional[Tuple[PartitionsOrReplicated, ...]]
out_parts: Optional[Tuple[PartitionsOrReplicated, ...]]
num_partitions: int
local_arg_parts: Optional[Tuple[PartitionsOrReplicated, ...]]
local_out_parts: Optional[Tuple[PartitionsOrReplicated, ...]]
local_num_partitions: Optional[int]
def _find_partitions(jaxpr):
"""Returns (in_partitions, out_partitions, num_partitions, local_in_parts,
local_out_parts, local_num_partitions).
"""
for eqn in jaxpr.eqns:
if eqn.primitive.name == "sharded_call":
if len(jaxpr.eqns) > 1:
raise NotImplementedError(
"pmap of sharded_jit + non-sharded operations not yet implemented.")
num_partitions = reconcile_num_partitions(eqn.params["call_jaxpr"],
eqn.params["nparts"])
return (eqn.params["in_parts"],
eqn.params["out_parts_thunk"](),
num_partitions,
eqn.params["local_in_parts"],
eqn.params["local_out_parts_thunk"](),
eqn.params["local_nparts"])
return None, None, 1, None, None, None
def find_partitions(jaxpr) -> PartitionInfo:
(arg_parts, out_parts, num_partitions, local_arg_parts, local_out_parts,
local_num_partitions) = _find_partitions(jaxpr)
if local_num_partitions is None:
local_num_partitions = num_partitions
if local_arg_parts is None:
local_arg_parts = arg_parts
if local_out_parts is None:
local_out_parts = out_parts
return PartitionInfo(arg_parts, out_parts, num_partitions,
local_arg_parts, local_out_parts, local_num_partitions)
def reconcile_num_partitions(jaxpr, outer_num_parts: Optional[int]):
"""Returns the total number of partitions to use.
Validates that any inner partitioning matches outer_num_parts if provided, and
returns the number of partitions to use based on outer_num_parts and any inner
partitioning.
"""
inner_num_parts = _inner_partitions(jaxpr, outer_num_parts)
if outer_num_parts is None and inner_num_parts is None:
# No partitions specified anywhere, everything is replicated.
return 1
if outer_num_parts is None:
return inner_num_parts
return outer_num_parts
def _inner_partitions(jaxpr, expected_num_parts: Optional[int]):
"""Returns the total number of partitions from PartitionSpecs inside `jaxpr`.
Also validates that this number matches `expected_num_parts` if provided.
"""
for eqn in jaxpr.eqns:
if eqn.primitive.name in ["sharding_constraint", "infeed"]:
parts = eqn.params["partitions"]
nparts = get_num_partitions(parts)
if expected_num_parts is None:
expected_num_parts = nparts
elif nparts is not None and nparts != expected_num_parts:
# TODO(skye): raise this error as we trace the jaxpr
raise ValueError(
f"with_sharding_constraint with partitions={parts} "
f"(total partitions: {nparts}) doesn't match expected number of "
f"partitions: {expected_num_parts}. If these partitions look "
f"right, check outer sharded_jit and/or other "
f"with_sharding_constraint calls.")
else:
for subjaxpr in core.jaxprs_in_params(eqn.params):
expected_num_parts = _inner_partitions(subjaxpr, expected_num_parts)
return expected_num_parts
def get_num_partitions(*partitions):
partition_specs = tree_flatten(partitions)[0]
if len(partition_specs) == 0:
# Everything is specified as replicated (all Nones).
return None
num_partitions_set = {np.prod(spec) for spec in partition_specs}
if len(num_partitions_set) > 1:
raise ValueError(
f"All partition specs must use the same number of total partitions, "
f"got {partitions}, with distinct number of partitions "
f"{num_partitions_set} (the total number of partitions is the product "
f"of a partition spec)")
assert len(num_partitions_set) == 1
return num_partitions_set.pop()
def get_global_aval(local_aval, global_parts: PartitionsOrReplicated,
local_parts: PartitionsOrReplicated):
if local_aval is core.abstract_unit:
return local_aval
if global_parts is None:
return local_aval
assert local_parts is not None
global_shape = [dim * _safe_div(ngparts, nlparts)
for dim, ngparts, nlparts
in safe_zip(local_aval.shape, global_parts, local_parts)]
return local_aval.update(shape=global_shape)
def get_local_aval(global_aval, global_parts: PartitionsOrReplicated,
local_parts: PartitionsOrReplicated):
if global_aval is core.abstract_unit:
return global_aval
if global_parts is None:
return global_aval
assert local_parts is not None
local_shape = [_safe_div(dim, _safe_div(ngparts, nlparts))
for dim, ngparts, nlparts
in safe_zip(global_aval.shape, global_parts, local_parts)]
return global_aval.update(shape=local_shape)
def _safe_div(x, y):
result, ragged = divmod(x, y)
assert not ragged, f"{x} % {y} != 0"
return result
class InputsHandler:
__slots__ = ("handler", "local_devices", "sharding_specs", "input_indices")
def __init__(self, local_devices, sharding_specs, input_indices):
self.handler = partial(shard_args, local_devices, input_indices)
self.local_devices = local_devices
self.sharding_specs = sharding_specs
self.input_indices = input_indices
def __call__(self, input_buffers):
return self.handler(input_buffers)
class ResultsHandler:
__slots__ = ("handlers", "out_specs", "out_indices", "unmapped_local_out_avals")
def __init__(self, handlers, out_specs, out_indices, unmapped_local_out_avals):
self.out_specs = out_specs
self.out_indices = out_indices
self.handlers = handlers
self.unmapped_local_out_avals = unmapped_local_out_avals
def __call__(self, out_bufs):
return [h(bufs) for h, bufs in safe_zip(self.handlers, out_bufs)]
def avals_to_results_handler(
nrep,
npart,
out_specs,
unmapped_local_out_avals,
global_out_avals: Optional[Sequence[ShapedArray]] = None,
out_axis_resources: Optional[Sequence[AxisResource]] = None,
global_mesh=None):
out_indices = [spec_to_indices(aval.shape, spec)
if aval is not core.abstract_unit else None
for aval, spec in safe_zip(unmapped_local_out_avals, out_specs)] # pytype: disable=attribute-error
if global_out_avals and out_axis_resources and global_mesh:
handlers = [
aval_to_result_handler(spec, idcs, aval, global_aval, out_axis, global_mesh)
for spec, idcs, aval, global_aval, out_axis in safe_zip(
out_specs, out_indices, unmapped_local_out_avals,
global_out_avals, out_axis_resources)
]
else:
handlers = [
aval_to_result_handler(spec, idcs, aval)
for spec, idcs, aval, in safe_zip(out_specs, out_indices,
unmapped_local_out_avals)
]
return ResultsHandler(handlers, out_specs, out_indices, unmapped_local_out_avals)
def replicate(val, axis_size, nrep, devices=None, backend=None, in_axis=0):
"""Replicates ``val`` across multiple devices.
Args:
val: the value to be replicated.
axis_size: the length of the output, i.e. the logical number of replicas to
create. Usually equal to `nrep`, but in the case of nested pmaps, `nrep` may
be a multiple of `axis_size`.
nrep: the number of replicas to create. If ``devices`` is set, must be equal
to ``len(devices)``.
devices: the devices to replicate across. If None, ``nrep`` will be used to
generate a default device assignment.
backend: string specifying which backend to use.
in_axis: axis along which the value is to be replciated.
Returns:
A ShardedDeviceArray of length `axis_size` where each shard is equal to
``val``.
"""
device_count = (len(devices) if devices else xb.local_device_count(backend))
if nrep > device_count:
msg = ("Cannot replicate across %d replicas because only %d local devices "
"are available." % (nrep, device_count))
if devices:
msg += (" (local devices = %s)"
% ", ".join(map(str, devices)) if devices else str(None))
raise ValueError(msg)
if devices is None:
assert nrep is not None
# TODO(skye): use different device assignment on multihost
devices = xb.get_backend(backend).get_default_device_assignment(nrep)
assert nrep == len(devices)
aval = xla.abstractify(val) # type: ShapedArray
if in_axis is not None:
replicated_aval = aval.update(shape=(axis_size,) + aval.shape)
else:
replicated_aval = aval
# TODO(skye): figure out how partitioning should work here
sharding_spec = _pmap_sharding_spec(nrep, axis_size, 1, None, aval, in_axis)
device_buffers = device_put(val, devices, replicate=True)
return make_sharded_device_array(replicated_aval, sharding_spec,
device_buffers)
def _pmap_sharding_spec(nrep, axis_size, npart, parts, sharded_aval,
map_axis: Optional[int]) -> ShardingSpec:
"""Sharding spec for arguments or results of a pmap.
Args:
nrep: number of local XLA replicas (product of local axis sizes)
axis_size: local axis size for outer pmap
npart: total number of XLA partitions (required by sharded_jit calls)
parts: the partitioning of the value or None
sharded_aval: the aval of the value inside the outer pmap, an instance of
a ShapedArray.
map_axis: the axis along which the value is mapped in the outer pmap
Returns:
A ShardingSpec.
"""
assert isinstance(sharded_aval, ShapedArray), sharded_aval
replication_factor, ragged = divmod(nrep, axis_size)
assert not ragged
# get the sharding spec from inner sharded_jits as if we weren't in a pmap
pspec = partitioned_sharding_spec(npart, parts, sharded_aval)
maybe_replicate = () if replication_factor == 1 else (Replicated(replication_factor),)
if map_axis is not None:
sharded_in_axis = sum(not isinstance(s, NoSharding) for s in pspec.sharding[:map_axis])
def shift_sharded_axis(a: MeshDimAssignment):
if isinstance(a, ShardedAxis) and a.axis >= sharded_in_axis:
return ShardedAxis(a.axis + 1)
return a
# replication_factor represents the product of inner pmaps, so it goes
# after the outer pmapped axis at index 0
return ShardingSpec(
sharding=tuple_insert(pspec.sharding, map_axis, Unstacked(axis_size)),
mesh_mapping=it.chain([ShardedAxis(sharded_in_axis)],
maybe_replicate,
map(shift_sharded_axis, pspec.mesh_mapping)))
else:
return ShardingSpec(
sharding=pspec.sharding,
mesh_mapping=(Replicated(axis_size),) + maybe_replicate + pspec.mesh_mapping)
def partitioned_sharding_spec(num_partitions: int,
partitions: Optional[Sequence[int]],
aval) -> ShardingSpec:
if partitions is None:
maybe_replicate = () if num_partitions == 1 else (Replicated(num_partitions),)
return ShardingSpec(
sharding=[_UNSHARDED_INSTANCE] * len(aval.shape),
mesh_mapping=maybe_replicate)
else:
assert len(partitions) == len(aval.shape)
return ShardingSpec(
# Chunked expects a list of integers
sharding=map(Chunked, [[x] for x in partitions]),
mesh_mapping=map(ShardedAxis, range(len(partitions))))
def execute_replicated(compiled, backend, in_handler, out_handler, *args):
input_bufs = in_handler(args)
out_bufs = compiled.execute_sharded_on_local_devices(input_bufs)
if dispatch.needs_check_special():
for bufs in out_bufs:
dispatch.check_special("parallel computation", bufs)
return out_handler(out_bufs)
xla_pmap_p = core.MapPrimitive('xla_pmap')
xla_pmap = xla_pmap_p.bind
xla_pmap_p.def_impl(xla_pmap_impl)
# Set param update handlers to update `donated_invars` just like xla_call_p
pe.call_param_updaters[xla_pmap_p] = pe.call_param_updaters[xla.xla_call_p]
ad.call_param_updaters[xla_pmap_p] = ad.call_param_updaters[xla.xla_call_p]
ad.call_transpose_param_updaters[xla_pmap_p] = \
ad.call_transpose_param_updaters[xla.xla_call_p]
def _pmap_translation_rule(c, axis_env,
in_nodes, name_stack, axis_name, axis_size,
global_axis_size, devices, name,
call_jaxpr, *, backend=None, in_axes, out_axes,
donated_invars, global_arg_shapes):
del donated_invars # Unused.
# We in-line here rather than generating a Call HLO as in the xla_call
# translation rule just because the extra tuple stuff is a pain.
if axis_env.names and devices is not None:
raise ValueError("Nested pmap with explicit devices argument.")
if global_axis_size is None:
global_axis_size = axis_size
new_env = xla.extend_axis_env(axis_env, axis_name, global_axis_size)
# Shard the in_nodes that are mapped
in_avals = [v.aval for v in call_jaxpr.invars]
in_nodes_sharded = (
_xla_shard(c, aval, new_env, in_node, in_axis) if in_axis is not None else in_node
for aval, in_node, in_axis in safe_zip(in_avals, in_nodes, in_axes))
with maybe_extend_axis_env(axis_name, global_axis_size, None): # type: ignore
ctx = xla.TranslationContext(
c, backend, new_env,
extend_name_stack(name_stack, wrap_name(name, 'pmap')))
sharded_outs = xla.jaxpr_subcomp(ctx, call_jaxpr, (), *in_nodes_sharded)
out_avals = [v.aval for v in call_jaxpr.outvars]
outs = [_xla_unshard(c, aval, new_env, out_axis, shard, backend=backend)
for aval, out_axis, shard in safe_zip(out_avals, out_axes, sharded_outs)]
return xops.Tuple(c, outs)
xla.call_translations[xla_pmap_p] = _pmap_translation_rule
ad.primitive_transposes[xla_pmap_p] = partial(ad.map_transpose, xla_pmap_p)
def _xla_shard(c, aval, axis_env, x, in_axis):
if aval is core.abstract_unit:
return x
elif aval is core.abstract_token:
return x
elif isinstance(aval, ShapedArray):
dims = list(c.get_shape(x).dimensions())
zero = xops.Constant(c, np.zeros((), dtype=np.uint32))
idxs = [zero] * (len(dims) - 1)
idxs.insert(in_axis, _unravel_index(c, axis_env))
dims_unsqueezed = dims.copy()
dims_unsqueezed[in_axis] = 1
dims_squeezed = dims.copy()
dims_squeezed.pop(in_axis)
return xops.Reshape(xops.DynamicSlice(x, idxs, dims_unsqueezed), dims_squeezed)
else:
raise TypeError((aval, c.get_shape(x)))
# TODO(b/110096942): more efficient gather
def _xla_unshard(c, aval, axis_env, out_axis, x, backend):
if aval is core.abstract_unit:
return x
elif aval is core.abstract_token:
return x
elif isinstance(aval, ShapedArray):
# TODO(mattjj): remove this logic when AllReduce PRED supported on CPU / GPU
convert_bool = (np.issubdtype(aval.dtype, np.bool_)
and xb.get_backend(backend).platform in ('cpu', 'gpu'))
if convert_bool:
x = xops.ConvertElementType(
x, xla.dtype_to_primitive_type(np.dtype(np.float32)))
xla_shape = c.get_shape(x)
dims = list(xla_shape.dimensions())
padded = xops.Broadcast(
xops.Constant(c, np.array(0, xla_shape.numpy_dtype())),
[axis_env.sizes[-1]] + dims)
zero = xops.Constant(c, np.zeros((), dtype=np.uint32))
idxs = [_unravel_index(c, axis_env)] + [zero] * len(dims)
padded = xops.DynamicUpdateSlice(padded, xops.Reshape(x, [1] + dims), idxs)
replica_groups_protos = xc.make_replica_groups(
xla.axis_groups(axis_env, axis_env.names[-1]))
out = xops.CrossReplicaSum(padded, replica_groups_protos)
if out_axis != 0:
# TODO(apaszke,mattjj): Change the indices to DynamicUpdateSlice instead
perm = list(range(1, len(dims)))
perm.insert(out_axis, 0)
out = xops.Transpose(out, perm)
# TODO(mattjj): remove this logic when AllReduce PRED supported on CPU / GPU
if convert_bool:
nonzero = xops.Ne(out, xops.Constant(c, np.array(0, dtype=np.float32)))
out = xops.ConvertElementType(
nonzero, xla.dtype_to_primitive_type(np.dtype(np.bool_)))
return out
else:
raise TypeError((aval, c.get_shape(x)))
def _unravel_index(c, axis_env):
div = xops.Constant(c, np.array(axis_env.nreps // prod(axis_env.sizes),
np.uint32))
mod = xops.Constant(c, np.array(axis_env.sizes[-1], np.uint32))
return xops.Rem(xops.Div(xops.ReplicaId(c), div), mod)
# ------------------- xmap -------------------
class Mesh:
def __init__(self, devices: np.ndarray, axis_names: Sequence[MeshAxisName]):
assert devices.ndim == len(axis_names)
# TODO: Make sure that devices are unique? At least with the quick and
# dirty check that the array size is not larger than the number of
# available devices?
self.devices = devices.copy()
self.devices.flags.writeable = False
self.axis_names = tuple(axis_names)
def __eq__(self, other):
if not isinstance(other, Mesh):
return False
return (self.axis_names == other.axis_names and
np.array_equal(self.devices, other.devices))
def __hash__(self):
if not hasattr(self, '_hash'):
self._hash = hash((self.axis_names, tuple(self.devices.flat)))
return self._hash
def __setattr__(self, name, value):
if hasattr(self, name):
raise RuntimeError("Cannot reassign attributes of immutable mesh objects")
super().__setattr__(name, value)
@property
def shape(self):
return OrderedDict((name, size) for name, size in safe_zip(self.axis_names, self.devices.shape))
@property
def size(self):
return np.prod(list(self.shape.values()))
@property
def empty(self):
return self.devices.ndim == 0
@property
def is_multi_process(self):
return self.shape != self.local_mesh.shape
@maybe_cached_property
def local_mesh(self):
if self.empty:
return self
process_index = xb.process_index()
is_local_device = np.vectorize(
lambda d: d.process_index == process_index, otypes=[bool])(self.devices)
subcube_indices = []
# We take the smallest slice of each dimension that doesn't skip any local device.
for axis in range(self.devices.ndim):
other_axes = tuple_delete(tuple(range(self.devices.ndim)), axis)
# NOTE: This re-reduces over many axes multiple times, so we could definitely
# optimize it, but I hope it won't be a bottleneck anytime soon.
local_slices = is_local_device.any(other_axes, keepdims=False)
nonzero_indices = np.flatnonzero(local_slices)
start, end = int(np.min(nonzero_indices)), int(np.max(nonzero_indices))
subcube_indices.append(slice(start, end + 1))
subcube_indices = tuple(subcube_indices)
# We only end up with all conditions being true if the local devices formed a
# subcube of the full array. This is because we were biased towards taking a
# "hull" spanned by the devices, and in case the local devices don't form a
# subcube that hull will contain non-local devices.
if not is_local_device[subcube_indices].all():
raise ValueError("Devices connected to a single host must form a contiguous "
"subcube of the global device mesh")
return Mesh(self.devices[subcube_indices], self.axis_names)
@property
def device_ids(self):
assert not self.empty
return np.vectorize(lambda d: d.id, otypes=[int])(self.devices)
def __repr__(self):
if self.empty:
return "Mesh([], ())"
return f"Mesh({self.device_ids!r}, {self.axis_names!r})"
@maybe_cached_property
def local_devices(self):
process_index = xb.process_index()
return [d for d in self.devices.flat if d.process_index == process_index]
def local_to_global(self, axes: ArrayMapping, aval):
return untile_aval_nd(self.shape, axes,
tile_aval_nd(self.local_mesh.shape, axes, aval))
def global_to_local(self, axes: ArrayMapping, aval):
return untile_aval_nd(self.local_mesh.shape, axes,
tile_aval_nd(self.shape, axes, aval))
def tile_aval_nd(axis_sizes, in_axes: ArrayMapping, aval, tiling_sizes=None):
if tiling_sizes is None:
tiling_sizes = axis_sizes
if aval is core.abstract_unit:
return aval
assert isinstance(aval, ShapedArray)
shape = list(aval.shape)
named_shape = dict(aval.named_shape)
for name, axis in in_axes.items():
assert shape[axis] % tiling_sizes[name] == 0
assert name not in named_shape
named_shape[name] = axis_sizes[name]
shape[axis] //= tiling_sizes[name]
return aval.update(shape=tuple(shape), named_shape=named_shape)
def untile_aval_nd(axis_sizes, out_axes: ArrayMapping, aval):
if aval is core.abstract_unit:
return aval
assert isinstance(aval, ShapedArray)
shape = list(aval.shape)
named_shape = dict(aval.named_shape)
for name, axis in out_axes.items():
shape[axis] *= axis_sizes[name]
named_shape.pop(name, None) # The name might be missing --- it's a broadcast.
return aval.update(shape=tuple(shape), named_shape=named_shape)
class SPMDBatchTrace(batching.BatchTrace):
def get_axis_primitive_batcher(self, primitive, frame):
if primitive in spmd_primitive_batchers:
return partial(spmd_primitive_batchers[primitive],
frame.size, frame.name, frame.main_trace.trace_type)
return super().get_axis_primitive_batcher(primitive, frame)
spmd_primitive_batchers: Dict[core.Primitive, Callable] = {}
def vtile_by_mesh(fun: lu.WrappedFun,
mesh: Mesh,
in_axes: Sequence[ArrayMapping],
out_axes: Sequence[ArrayMapping]):
# We vectorize in reversed order, because vmap is often biased towards
# moving the batch axis to the front, and this way of stacking transforms
# will order the batch axes according to the mesh axis order.
# Not strictly necessary, but seems nicer than reversing it?
for name, size in reversed(mesh.shape.items()):
fun = batching.vtile(fun,
tuple(a.get(name, None) for a in in_axes),
tuple(a.get(name, None) for a in out_axes),
tile_size=size,
axis_name=name,
main_type=SPMDBatchTrace)
return fun
def lower_mesh_computation(
fun: lu.WrappedFun,
transformed_name: str,
mesh: Mesh,
in_axes: Sequence[ArrayMapping],
out_axes: Union[Sequence[ArrayMapping], Callable[[], Sequence[ArrayMapping]]],
donated_invars: Sequence[bool],
spmd_lowering: bool,
local_in_untiled_avals: Sequence[core.ShapedArray],
tile_by_mesh_axes: bool):
assert not mesh.empty
backend = xb.get_device_backend(mesh.devices.flat[0])
local_mesh = mesh.local_mesh
global_axis_sizes = mesh.shape
local_axis_sizes = local_mesh.shape
log_priority = logging.WARNING if config.jax_log_compiles else logging.DEBUG
logging.log(log_priority,
"Compiling %s (%d) for %s mesh with args %s. Argument mapping: "
"%s.",
getattr(fun, '__name__', '<unnamed function>'), id(fun),
tuple(global_axis_sizes.items()), local_in_untiled_avals,
in_axes)
# 1. Trace to jaxpr and preprocess/verify it
# Note that we tile by the local axis sizes, but use global axis sizes for named_shape
in_tiled_avals = [tile_aval_nd(global_axis_sizes, aval_in_axes, aval,
tiling_sizes=local_axis_sizes)
for aval, aval_in_axes in safe_zip(local_in_untiled_avals, in_axes)]
if spmd_lowering:
# TODO: Consider handling xmap's 'vectorize' in here. We can vmap once instead of vtile twice!
if tile_by_mesh_axes:
assert not callable(out_axes)
fun = vtile_by_mesh(fun, mesh, in_axes, out_axes)
global_in_untiled_avals = [untile_aval_nd(global_axis_sizes, aval_in_axes, aval)
for aval, aval_in_axes in safe_zip(in_tiled_avals, in_axes)]
in_jaxpr_avals = global_in_untiled_avals
else:
assert tile_by_mesh_axes
in_jaxpr_avals = in_tiled_avals
with core.extend_axis_env_nd(mesh.shape.items()):
jaxpr, out_jaxpr_avals, consts = pe.trace_to_jaxpr_final(fun, in_jaxpr_avals)
if callable(out_axes):
out_axes = out_axes()
assert len(out_axes) == len(out_jaxpr_avals)
if spmd_lowering:
global_out_untiled_avals = out_jaxpr_avals
out_tiled_avals = [tile_aval_nd(global_axis_sizes, aval_out_axes, aval)
for aval, aval_out_axes in safe_zip(global_out_untiled_avals, out_axes)]
else:
out_tiled_avals = out_jaxpr_avals
local_out_untiled_avals = [untile_aval_nd(local_axis_sizes, aval_out_axes, aval)
for aval, aval_out_axes in safe_zip(out_tiled_avals, out_axes)]
_sanitize_mesh_jaxpr(jaxpr)
if local_mesh.shape != mesh.shape:
check_multihost_collective_allowlist(jaxpr)
jaxpr = dispatch.apply_outfeed_rewriter(jaxpr)
# 3. Build up the HLO
c = xc.XlaBuilder(f"xmap_{fun.__name__}")
xla_consts = map(partial(xla.pyval_to_ir_constant, c), consts)
tuple_args = len(in_jaxpr_avals) > 100 # pass long arg lists as tuple for TPU
in_partitions: Optional[List]
if spmd_lowering:
replicated_args = [False] * len(in_jaxpr_avals)
global_sharding_spec = mesh_sharding_specs(global_axis_sizes, mesh.axis_names)
in_partitions = [global_sharding_spec(aval, aval_in_axes).sharding_proto()
if aval is not core.abstract_unit else None
for aval, aval_in_axes in safe_zip(global_in_untiled_avals, in_axes)]
out_partitions = [global_sharding_spec(aval, aval_out_axes).sharding_proto()
for aval, aval_out_axes in safe_zip(global_out_untiled_avals, out_axes)]
partitions_proto = True
axis_env = xla.AxisEnv(nreps=1, names=(), sizes=()) # All named axes have been vmapped
else:
replicated_args = [not axis for axis in in_axes]
in_partitions = None
partitions_proto = False
axis_env = xla.AxisEnv(nreps=mesh.size,
names=tuple(global_axis_sizes.keys()),
sizes=tuple(global_axis_sizes.values()))
xla_args, donated_invars = xla._xla_callable_args(
c, in_jaxpr_avals, tuple_args,
replicated=replicated_args,
partitions=in_partitions,
partitions_proto=partitions_proto,
donated_invars=donated_invars)
with core.extend_axis_env_nd(mesh.shape.items()):
ctx = xla.TranslationContext(
c, backend.platform, axis_env,
extend_name_stack(wrap_name(transformed_name, 'xmap')))
out_nodes = xla.jaxpr_subcomp(ctx, jaxpr, xla_consts, *xla_args)
if spmd_lowering:
out_partitions_t = xb.tuple_sharding_proto(out_partitions)
out_tuple = xb.with_sharding_proto(c, out_partitions_t, xops.Tuple, c, out_nodes)
else:
out_tuple = xops.Tuple(c, out_nodes)
if backend.platform in ("gpu", "tpu"):
xla.set_up_aliases(c, xla_args, c.GetShape(out_tuple), donated_invars,
tuple_args)
# TODO: Warn about unused donations?
built = c.Build(out_tuple)
return MeshComputation(
built, donated_invars, mesh, local_in_untiled_avals,
local_out_untiled_avals, (out_jaxpr_avals if spmd_lowering else None),
in_axes, out_axes, spmd_lowering, tuple_args)
class MeshComputation:
def __init__(self, hlo, donated_invars, *compile_args):
self._executable = None
self._hlo = hlo
self._donated_invars = donated_invars
self.compile_args = compile_args
def hlo(self):
# this is a method for api consistency with xla.XlaComputation
return self._hlo
def compile(self,
_allow_propagation_to_outputs : bool = False,
_allow_compile_replicated : bool = True) -> 'MeshExecutable':
if self._executable is None:
self._executable = MeshExecutable.from_hlo(
self._hlo, *self.compile_args,
_allow_propagation_to_outputs=_allow_propagation_to_outputs,
_allow_compile_replicated=_allow_compile_replicated) # type: ignore
return self._executable
class MeshExecutable:
__slots__ = ['xla_executable', 'unsafe_call', '_local_in_untiled_avals']
def __init__(self, xla_executable, unsafe_call, local_in_untiled_avals):
self.xla_executable = xla_executable
self.unsafe_call = unsafe_call
self._local_in_untiled_avals = local_in_untiled_avals
@staticmethod
def from_hlo(computation: xc.XlaComputation,
mesh: Mesh,
local_in_untiled_avals: Sequence[ShapedArray],
local_out_untiled_avals: Sequence[ShapedArray],
global_out_avals: Optional[Sequence[ShapedArray]],
in_axes: Sequence[ArrayMapping],
out_axes: Sequence[ArrayMapping],
spmd_lowering: bool, tuple_args: bool,
_allow_propagation_to_outputs: bool,
_allow_compile_replicated: bool):
assert not mesh.empty
backend = xb.get_device_backend(mesh.devices.flat[0])
local_mesh = mesh.local_mesh
local_axis_sizes = local_mesh.shape
if spmd_lowering:
num_replicas, num_partitions = 1, mesh.size
num_local_replicas, num_local_partitions = 1, local_mesh.size
else:
num_replicas, num_partitions = mesh.size, 1
num_local_replicas, num_local_partitions = local_mesh.size, 1
device_assignment = mesh.device_ids.reshape((num_replicas, num_partitions))
compile_options = xb.get_compile_options(
num_replicas=num_replicas,
num_partitions=num_partitions,
device_assignment=device_assignment,
use_spmd_partitioning=spmd_lowering,
)
compile_options.parameter_is_tupled_arguments = tuple_args
compile_options.executable_build_options.allow_spmd_sharding_propagation_to_output = \
_allow_propagation_to_outputs
local_sharding_spec = mesh_sharding_specs(local_axis_sizes, mesh.axis_names)
local_input_specs = [local_sharding_spec(aval, aval_in_axes)
if aval is not core.abstract_unit else None
for aval, aval_in_axes in safe_zip(local_in_untiled_avals, in_axes)]
input_indices = [spec_to_indices(aval.shape, spec)
if spec is not None else None
for aval, spec in safe_zip(local_in_untiled_avals, local_input_specs)]
local_output_specs = [local_sharding_spec(aval, aval_out_axes)
for aval, aval_out_axes in safe_zip(local_out_untiled_avals, out_axes)]
out_axis_resources = [array_mapping_to_axis_resources(o) for o in out_axes]
handle_outs = avals_to_results_handler(num_local_replicas, num_local_partitions,
local_output_specs, local_out_untiled_avals,
global_out_avals, out_axis_resources, mesh)
if _allow_compile_replicated and hasattr(backend, "compile_replicated"):
unsafe_call = backend.compile_replicated(
computation, compile_options,
input_indices, local_input_specs,
handle_outs)
xla_executable = None
else:
compiled = dispatch.compile_or_get_cached(backend, computation, compile_options)
handle_args = InputsHandler(compiled.local_devices(), local_input_specs,
input_indices)
unsafe_call = partial(execute_replicated, compiled, backend, handle_args, handle_outs)
xla_executable = compiled
return MeshExecutable(xla_executable, unsafe_call, local_in_untiled_avals)
def call(self, *args):
arg_avals = map(xla.abstractify, args)
ref_avals = self._local_in_untiled_avals
dispatch.check_arg_avals_for_call(ref_avals, arg_avals)
return self.unsafe_call(*args)
_forbidden_primitives = {
'xla_pmap': 'pmap',
'sharded_call': 'sharded_jit',
}
def _sanitize_mesh_jaxpr(jaxpr):
if isinstance(jaxpr, core.ClosedJaxpr):
jaxpr = jaxpr.jaxpr
for eqn in jaxpr.eqns:
if eqn.primitive.name in _forbidden_primitives:
raise RuntimeError(f"Nesting {_forbidden_primitives[eqn.primitive.name]} "
f"inside xmaps not supported!")
core.traverse_jaxpr_params(_sanitize_mesh_jaxpr, eqn.params)
custom_resource_typing_rules: Dict[core.Primitive, Callable] = {}
def resource_typecheck(jaxpr, resource_env, axis_resources, what_jaxpr_thunk):
if isinstance(jaxpr, core.ClosedJaxpr):
jaxpr = jaxpr.jaxpr
def _check_aval(aval, what_thunk):
if not hasattr(aval, 'named_shape'):
return
resource_to_axis = {}
for axis in aval.named_shape:
for resource in axis_resources[axis]:
if resource in resource_to_axis:
other_axis = resource_to_axis[resource]
axis, other_axis = sorted([str(axis), str(other_axis)])
raise JAXTypeError(
f"Axes `{axis}` and `{other_axis}` are both mapped to the "
f"resource `{resource}`, but they coincide in the named_shape "
f"of {what_thunk()}")
resource_to_axis[resource] = axis
what_thunk = lambda: (f"an input to {what_jaxpr_thunk()}")
for v in jaxpr.constvars:
_check_aval(v.aval, what_thunk)
for v in jaxpr.invars:
_check_aval(v.aval, what_thunk)
what_thunk = lambda: (f"a value returned from a primitive {eqn.primitive} created "
f"at {source_info_util.summarize(eqn.source_info)}")
rec_what_jaxpr_thunk = lambda: (f"a primitive {eqn.primitive} created at"
f"{source_info_util.summarize(eqn.source_info)}")
for eqn in jaxpr.eqns:
typing_rule = custom_resource_typing_rules.get(eqn.primitive, None)
if typing_rule:
typing_rule([v.aval for v in eqn.invars], eqn.params, eqn.source_info,
resource_env, axis_resources)
else:
core.traverse_jaxpr_params(partial(resource_typecheck,
resource_env=resource_env,
axis_resources=axis_resources,
what_jaxpr_thunk=rec_what_jaxpr_thunk),
eqn.params)
for v in eqn.outvars:
_check_aval(v.aval, what_thunk)
def mesh_sharding_specs(axis_sizes, axis_names):
mesh_axis_pos = {name: i for i, name in enumerate(axis_names)}
# NOTE: This takes in the non-sharded avals!
def mk_sharding_spec(aval, aval_axes):
mesh_mapping = [Replicated(axis_size) for axis_size in axis_sizes.values()]
if aval is core.abstract_token:
assert not aval_axes
return ShardingSpec([], mesh_mapping)
sharding = [_UNSHARDED_INSTANCE] * len(aval.shape)
next_sharded_axis = 0
aval_shape = list(aval.shape)
# NOTE: sorted is stable, which is important when multiple resources
# map to the same axis.
for name, axis in sorted(aval_axes.items(), key=lambda x: x[1]):
assert aval_shape[axis] % axis_sizes[name] == 0, (axis_sizes[name], aval.shape[axis])
aval_shape[axis] //= axis_sizes[name]
if isinstance(sharding[axis], NoSharding):
sharding[axis] = Chunked([])
sharding[axis] = Chunked(sharding[axis].chunks + [axis_sizes[name]])
assert isinstance(mesh_mapping[mesh_axis_pos[name]], Replicated), \
"Value mapped to the same mesh axis twice"
mesh_mapping[mesh_axis_pos[name]] = ShardedAxis(next_sharded_axis)
next_sharded_axis += 1
return ShardingSpec(sharding, mesh_mapping)
return mk_sharding_spec
@contextmanager
def maybe_extend_axis_env(*args, **kwargs):
with core.extend_axis_env(*args, **kwargs):
yield
class DynamicAxisEnvFrame(object):
__slots__ = ["name", "pmap_trace", "hard_size"]
def __init__(self, name, pmap_trace, hard_size):
self.name = name
self.pmap_trace = pmap_trace
self.hard_size = hard_size
class DynamicAxisEnv(list):
def __contains__(self, axis_name):
return axis_name in (frame.name for frame in self)
def __getitem__(self, axis_name):
if axis_name not in self:
raise NameError("unbound axis name: {}".format(axis_name))
for frame in reversed(self):
if frame.name == axis_name:
return frame
raise AssertionError
@property
def sizes(self):
return tuple(frame.hard_size for frame in self)
@property
def nreps(self):
return prod(frame.hard_size for frame in self)
class _ThreadLocalState(threading.local):
def __init__(self):
self.dynamic_axis_env = DynamicAxisEnv()
_thread_local_state = _ThreadLocalState()
def device_put(x, devices: Sequence[xb.xla_client.Device], replicate: bool=False) -> List[xb.xla_client.Buffer]:
"""Call device_put on a sequence of devices and return a flat sequence of buffers."""
if replicate:
return list(it.chain.from_iterable(dispatch.device_put(x, device) for device in devices))
else:
return list(it.chain.from_iterable(dispatch.device_put(val, device) for val, device in safe_zip(x, devices)))
| 41.376567 | 120 | 0.709911 |
from contextlib import contextmanager
from collections import defaultdict, OrderedDict
import dataclasses
from functools import partial
import itertools as it
import operator as op
import threading
from typing import (Any, Callable, Dict, List, NamedTuple, Optional,
Sequence, Set, Tuple, Type, Union, Iterable)
import sys
from absl import logging
import numpy as np
from .._src.config import config
from .. import core
from .. import linear_util as lu
from jax._src.abstract_arrays import array_types
from ..core import ConcreteArray, ShapedArray
from jax._src import device_array
from .._src import source_info_util
from .._src.util import (unzip3, prod, safe_map, safe_zip,
extend_name_stack, wrap_name, assert_unreachable,
tuple_insert, tuple_delete, distributed_debug_log)
from ..errors import JAXTypeError
from jax._src import dispatch
from jax._src.lib import xla_bridge as xb
from jax._src.lib import xla_client as xc
from jax._src.lib import pmap_lib
from ..tree_util import tree_flatten, tree_map
from . import batching
from . import partial_eval as pe
from . import xla
from . import ad
class WeakRefList(list):
pass
if sys.version_info >= (3, 8):
from functools import cached_property as maybe_cached_property
else:
maybe_cached_property = property
if sys.version_info >= (3, 9):
OrderedDictType = OrderedDict
else:
OrderedDictType = Dict
xops = xc.ops
unsafe_map, map = map, safe_map # type: ignore
Index = Union[int, slice, Tuple[Union[int, slice], ...]]
NoSharding = pmap_lib.NoSharding
Chunked = pmap_lib.Chunked
Unstacked = pmap_lib.Unstacked
ShardedAxis = pmap_lib.ShardedAxis
Replicated = pmap_lib.Replicated
_UNSHARDED_INSTANCE = NoSharding()
AvalDimSharding = Union[Unstacked, Chunked, NoSharding]
MeshDimAssignment = Union[ShardedAxis, Replicated]
ShardingSpec = pmap_lib.ShardingSpec
def sharding_spec_mesh_shape(self):
sharded_axis_sizes = []
for sharding in self.sharding:
if isinstance(sharding, NoSharding):
continue
elif isinstance(sharding, Unstacked):
sharded_axis_sizes.append(sharding.size)
elif isinstance(sharding, Chunked):
sharded_axis_sizes.extend(sharding.chunks)
else:
assert_unreachable(sharding)
return tuple(sharded_axis_sizes[a.axis] if isinstance(a, ShardedAxis) else a.replicas
for a in self.mesh_mapping)
def sharding_spec_sharding_proto(self):
mesh_shape = self.mesh_shape
mesh = np.arange(np.prod(mesh_shape)).reshape(mesh_shape)
sharded_axes = {} # maps sharded axis identifiers to mesh axis indices to which they're mapped
replicated_maxes = []
for maxis, assignment in enumerate(self.mesh_mapping):
if isinstance(assignment, Replicated):
replicated_maxes.append(maxis)
elif isinstance(assignment, ShardedAxis):
sharded_axes[assignment.axis] = maxis
else:
assert_unreachable(assignment)
proto = xc.OpSharding()
if len(replicated_maxes) == len(self.mesh_mapping):
proto.type = xc.OpSharding.Type.REPLICATED
return proto
else:
proto.type = xc.OpSharding.Type.OTHER
mesh_permutation = []
new_mesh_shape = []
next_sharded_axis = 0
for axis, sharding in enumerate(self.sharding):
if isinstance(sharding, NoSharding):
new_mesh_shape.append(1)
elif isinstance(sharding, Chunked):
for nchunks in sharding.chunks:
maxis = sharded_axes[next_sharded_axis]
assert mesh_shape[maxis] == nchunks
mesh_permutation.append(maxis)
next_sharded_axis += 1
new_mesh_shape.append(int(np.prod(sharding.chunks)))
elif isinstance(sharding, Unstacked):
raise RuntimeError("Cannot convert unstacked sharding specs to XLA OpSharding")
else:
assert_unreachable(sharding)
# Create the partial sharding proto if tensor is replicated over some mesh axes
if replicated_maxes:
new_mesh_shape.append(-1)
mesh_permutation.extend(replicated_maxes)
proto.replicate_on_last_tile_dim = True
proto_mesh = mesh.transpose(mesh_permutation).reshape(new_mesh_shape)
proto.tile_assignment_dimensions = list(proto_mesh.shape)
proto.tile_assignment_devices = list(proto_mesh.flat)
return proto
def sharding_spec_indices(self, shape: Tuple[int, ...]) -> np.ndarray:
assert len(shape) == len(self.sharding), (shape, self.sharding)
axis_indices: List[Sequence[Index]] = []
shard_indices_shape = []
for dim, sharding in enumerate(self.sharding):
axis_size = shape[dim]
if isinstance(sharding, NoSharding):
axis_indices.append([slice(None)])
# NOTE: We don't append unsharded dimensions to shard_indices_shape here,
elif isinstance(sharding, Unstacked):
assert axis_size == sharding.size, f'{axis_size} != {sharding.size}'
axis_indices.append(range(axis_size))
shard_indices_shape.append(axis_size)
elif isinstance(sharding, Chunked):
total_chunks = int(np.prod(sharding.chunks))
shard_size, ragged = divmod(axis_size, total_chunks)
assert not ragged, (axis_size, total_chunks, dim)
axis_indices.append([slice(i * shard_size, (i + 1) * shard_size)
for i in range(total_chunks)])
shard_indices_shape.extend(sharding.chunks)
else:
assert_unreachable(sharding)
shard_indices = np.empty([prod(shard_indices_shape)], dtype=np.object_)
for i, idxs in enumerate(it.product(*axis_indices)):
shard_indices[i] = idxs
shard_indices = shard_indices.reshape(shard_indices_shape)
num_sharded_dim = len(shard_indices_shape)
sharded_dim_perm = [a.axis for a in self.mesh_mapping if isinstance(a, ShardedAxis)]
assert (set(sharded_dim_perm) == set(range(num_sharded_dim)) and
len(sharded_dim_perm) == num_sharded_dim)
replica_sizes = tuple(a.replicas for a in self.mesh_mapping if isinstance(a, Replicated))
replica_dim, sharded_dim = it.count(0), iter(sharded_dim_perm)
perm = [next(replica_dim) if isinstance(a, Replicated) else
len(replica_sizes) + next(sharded_dim)
for a in self.mesh_mapping]
return (np.broadcast_to(shard_indices, replica_sizes + shard_indices.shape)
.transpose(perm))
def sharding_spec_repr(self):
return f'ShardingSpec({self.sharding}, {self.mesh_mapping})'
ShardingSpec.mesh_shape = property(sharding_spec_mesh_shape)
ShardingSpec.sharding_proto = sharding_spec_sharding_proto
ShardingSpec.indices = sharding_spec_indices
ShardingSpec.__repr__ = sharding_spec_repr
del sharding_spec_mesh_shape, sharding_spec_indices, sharding_spec_repr
def spec_to_indices(shape: Tuple[int, ...],
spec: ShardingSpec) -> Tuple[Index, ...]:
return tuple(spec.indices(shape).flat)
y(x): return x
def _shard_arg(arg, devices, arg_indices):
if isinstance(arg, ShardedDeviceArray) and arg_indices == arg.indices:
return [
buf if buf.device() == d else buf.copy_to_device(d)
for d, buf in zip(devices, arg.device_buffers)
]
else:
arg = xla.canonicalize_dtype(arg)
return shard_arg_handlers[type(arg)](arg, devices, arg_indices)
def shard_args(devices: Sequence[xb.xla_client.Device],
indices: Sequence[Sequence[Index]],
args) -> Sequence[Sequence[xb.xla_client.Buffer]]:
return [_shard_arg(arg, devices, indices[a]) for a, arg in enumerate(args)]
shard_arg_handlers: Dict[Any, Callable[[Any, Any, Any], Sequence[Any]]] = {}
shard_arg_handlers[core.Unit] = \
lambda x, devices, _: device_put(core.unit, devices, replicate=True)
def _shard_array(x, devices, indices):
return device_put([x[i] for i in indices], devices)
for _t in array_types:
shard_arg_handlers[_t] = _shard_array
def _shard_device_array(x, devices, indices):
start_indices, limit_indices, removed_dims = unzip3(
_as_slice_indices(x, idx) for idx in indices)
shards = x._multi_slice(start_indices, limit_indices, removed_dims)
return device_put(shards, devices)
for t in device_array.device_array_types:
shard_arg_handlers[t] = _shard_device_array
def _as_slice_indices(arr: device_array.DeviceArrayProtocol, idx: Index) -> Tuple[
Tuple[int, ...], Tuple[int, ...], Tuple[int, ...]]:
start_indices = [0] * arr.ndim
limit_indices = list(arr.shape)
removed_dims = []
tuple_idx = idx if isinstance(idx, tuple) else (idx,)
for dim, sub_idx in enumerate(tuple_idx):
if isinstance(sub_idx, int):
start_indices[dim] = sub_idx
limit_indices[dim] = sub_idx + 1
removed_dims.append(dim)
elif sub_idx == slice(None):
continue
else:
assert isinstance(sub_idx, slice), sub_idx
assert isinstance(sub_idx.start, int), sub_idx
assert isinstance(sub_idx.stop, int), sub_idx
start_indices[dim] = sub_idx.start
limit_indices[dim] = sub_idx.stop
return tuple(start_indices), tuple(limit_indices), tuple(removed_dims)
def shard_aval(size, axis: int, aval):
try:
return shard_aval_handlers[type(aval)](size, axis, aval)
except KeyError as err:
raise TypeError(f"No shard_aval handler for type: {type(aval)}") from err
shard_aval_handlers: Dict[Type[core.AbstractValue], Callable[[int, int, Any], Any]] = {}
shard_aval_handlers[core.AbstractUnit] = lambda size, axis, x: x
def _shard_abstract_array(size, axis: int, x):
try:
if x.shape[axis] != size:
raise ValueError(f"Axis size {size} does not match dimension {axis} of "
f"shape {x.shape}")
except IndexError:
raise ValueError("Cannot split a {x.dim}D value along axis {axis}") from None
return x.update(shape=tuple_delete(x.shape, axis))
shard_aval_handlers[ShapedArray] = _shard_abstract_array
MeshAxisName = Any
ArrayMapping = OrderedDictType[MeshAxisName, int]
AxisResource = Tuple[Optional[Tuple[Any, ...]], ...]
def array_mapping_to_axis_resources(array_mapping: ArrayMapping) -> AxisResource:
if not array_mapping:
return tuple()
max_index = array_mapping[max(array_mapping, key=array_mapping.get)]
reverse_map = defaultdict(list)
for axis, index in array_mapping.items():
reverse_map[index].append(axis)
return tuple(
tuple(reverse_map[i]) if reverse_map[i] else None for i in range(max_index + 1)
)
def aval_to_result_handler(
sharding_spec: Optional[ShardingSpec],
indices: Optional[Tuple[Index]],
aval: core.AbstractValue,
global_aval: Optional[ShapedArray] = None,
out_axis_resources: Optional[AxisResource] = None,
global_mesh = None,
) -> Callable[[List[xb.xla_client.Buffer]], Any]:
try:
return pxla_result_handlers[type(aval)](sharding_spec, indices, aval,
global_aval, out_axis_resources, global_mesh)
except KeyError as err:
raise TypeError("No pxla_result_handler for type: {}".format(type(aval))
) from err
PxlaResultHandler = Callable[..., Callable[[List[xb.xla_client.Buffer]], Any]]
pxla_result_handlers: Dict[Type[core.AbstractValue], PxlaResultHandler] = {}
pxla_result_handlers[core.AbstractUnit] = lambda *_: lambda _: core.unit
def array_result_handler(sharding_spec, indices, aval: ShapedArray, global_aval,
out_axis_resources, global_mesh):
if config.jax_gsda_out:
return gsda_array_result_handler(global_aval, global_mesh, out_axis_resources)
else:
return sda_array_result_handler(sharding_spec, indices, aval)
pxla_result_handlers[ShapedArray] = array_result_handler
pxla_result_handlers[ConcreteArray] = array_result_handler
def sda_array_result_handler(sharding_spec, indices, aval: ShapedArray):
return lambda bufs: make_sharded_device_array(aval, sharding_spec, bufs,
indices)
def gsda_array_result_handler(global_aval, global_mesh, out_axis_resources):
from ..experimental.gsda import GlobalShardedDeviceArray
return lambda bufs: GlobalShardedDeviceArray(
global_aval.shape, global_mesh, out_axis_resources, bufs)
l[ShardingSpec],
device_buffers: List[Union[Any, xb.xla_client.Buffer]],
indices: Optional[Tuple[Index, ...]] = None,
):
if sharding_spec is None:
sharded_aval = aval.update(shape=aval.shape[1:])
sharding_spec = _pmap_sharding_spec(aval.shape[0], aval.shape[0], 1, None,
sharded_aval, 0)
if indices is None:
indices = spec_to_indices(aval.shape, sharding_spec)
if (_USE_CPP_SDA and
(not device_buffers or
isinstance(device_buffers[0], xb.xla_client.Buffer))):
return pmap_lib.ShardedDeviceArray.make(
aval, sharding_spec, device_buffers,
indices, aval.weak_type)
return _ShardedDeviceArray(aval, sharding_spec, device_buffers, indices)
if _USE_CPP_SDA:
ShardedDeviceArrayBase = pmap_lib.ShardedDeviceArrayBase
ShardedDeviceArrayBase.__bases__ = ((device_array.DeviceArray,) +
ShardedDeviceArrayBase.__bases__)
_SDA_BASE_CLASS = pmap_lib.ShardedDeviceArrayBase
else:
_SDA_BASE_CLASS: Type[device_array.DeviceArray] = device_array.DeviceArray
class _ShardedDeviceArray(_SDA_BASE_CLASS):
__slots__ = [
"aval", "device_buffers", "sharding_spec", "indices",
"_one_replica_buffer_indices", "_npy_value"
]
def __init__(self,
aval: ShapedArray,
sharding_spec: ShardingSpec,
device_buffers: List[xb.xla_client.Buffer],
indices: Optional[Tuple[Index, ...]] = None):
super().__init__()
if indices is None:
indices = spec_to_indices(aval.shape, sharding_spec)
self.aval = aval
self.device_buffers = device_buffers
self.sharding_spec = sharding_spec
self.indices = indices
self._npy_value = None
self._one_replica_buffer_indices = None
if config.jax_enable_checks:
assert type(aval) is ShapedArray
@property
def shape(self):
return self.aval.shape
@property
def dtype(self):
return self.aval.dtype
@property
def size(self):
return prod(self.aval.shape)
@property
def ndim(self):
return len(self.aval.shape)
def delete(self):
if self.device_buffers is None:
return
for buf in self.device_buffers:
buf.delete()
self.device_buffers = None
self._npy_value = None
def _sda_one_replica_buffer_indices(self):
if self._one_replica_buffer_indices is None:
one_replica_indices = []
seen_index_hashes = set()
for i, index in enumerate(self.indices):
hashed_index = _hashable_index(index)
if hashed_index not in seen_index_hashes:
one_replica_indices.append(i)
seen_index_hashes.add(hashed_index)
self._one_replica_buffer_indices = one_replica_indices
return self._one_replica_buffer_indices
def _sda_copy_to_host_async(self):
for buffer_index in self.one_replica_buffer_indices:
self.device_buffers[buffer_index].copy_to_host_async()
def _sda_check_if_deleted(self):
if self.device_buffers is None:
raise ValueError("ShardedDeviceArray has been deleted.")
def _sda_block_until_ready(self):
self._check_if_deleted()
for buf in self.device_buffers:
buf.block_host_until_ready()
return self
def _sda_value(self):
if self._npy_value is None:
self.copy_to_host_async()
npy_value = np.empty(self.aval.shape, self.aval.dtype)
for i in self.one_replica_buffer_indices:
npy_value[self.indices[i]] = self.device_buffers[i].to_py()
self._npy_value = npy_value
return self._npy_value
def _sda__getitem__(self, idx):
self._check_if_deleted()
if not isinstance(idx, tuple):
cidx = (idx,) + (slice(None),) * (len(self.aval.shape) - 1)
else:
cidx = idx + (slice(None),) * (len(self.aval.shape) - len(idx))
if self._npy_value is None:
try:
buf_idx = self.indices.index(cidx)
except ValueError:
buf_idx = None
if buf_idx is not None:
buf = self.device_buffers[buf_idx]
aval = ShapedArray(buf.xla_shape().dimensions(), self.aval.dtype)
return device_array.make_device_array(aval, None, buf)
return super(self.__class__, self).__getitem__(idx)
def _sda__iter__(self):
if self.ndim == 0:
raise TypeError("iteration over a 0-d array")
else:
return (self[i] for i in range(self.shape[0]))
def _sda__reversed__(self):
if self.ndim == 0:
raise TypeError("iteration over a 0-d array")
else:
return (self[i] for i in range(self.shape[0] - 1, -1, -1))
for sda in [_ShardedDeviceArray, pmap_lib.ShardedDeviceArray]:
setattr(sda, "one_replica_buffer_indices",
property(_sda_one_replica_buffer_indices))
setattr(sda, "copy_to_host_async", _sda_copy_to_host_async)
setattr(sda, "_check_if_deleted", _sda_check_if_deleted)
setattr(sda, "block_until_ready", _sda_block_until_ready)
setattr(sda, "_value", property(_sda_value))
setattr(sda, "__getitem__", _sda__getitem__)
setattr(sda, "__iter__", _sda__iter__)
setattr(sda, "__reversed__", _sda__reversed__)
del (_sda_one_replica_buffer_indices, _sda_copy_to_host_async,
_sda_check_if_deleted, _sda_block_until_ready, _sda_value, _sda__getitem__)
ShardedDeviceArray: Type[object]
if _USE_CPP_SDA:
ShardedDeviceArray = pmap_lib.ShardedDeviceArrayBase
else:
ShardedDeviceArray = _ShardedDeviceArray
def _hashable_index(idx):
return tree_map(lambda x: (x.start, x.stop) if type(x) == slice else x,
idx)
def _shard_sharded_device_array_slow_path(x, devices, indices):
candidates = defaultdict(list)
for buf, idx in safe_zip(x.device_buffers, x.indices):
candidates[_hashable_index(idx)].append(buf)
bufs = []
for idx, device in safe_zip(indices, devices):
candidates_list = candidates[_hashable_index(idx)]
if not candidates_list:
# TODO(skye): more efficient reshard?
return shard_arg_handlers[type(x._value)](x._value, devices, indices)
# Try to find a candidate buffer already on the correct device,
# otherwise copy one of them.
for buf in candidates_list:
if buf.device() == device:
bufs.append(buf)
break
else:
bufs.append(buf.copy_to_device(device))
return bufs
def _sharded_device_array_constant_handler(c, val, canonicalize_types=True):
return xla.pyval_to_ir_constants(c, np.asarray(val),
canonicalize_types=canonicalize_types)
def _register_handlers_for_sharded_device_array(sda):
shard_arg_handlers[sda] = _shard_sharded_device_array_slow_path
xla.register_constant_handler(sda, _sharded_device_array_constant_handler)
core.pytype_aval_mappings[sda] = ConcreteArray
dispatch.device_put_handlers[sda] = dispatch._device_put_array
xla.pytype_aval_mappings[sda] = op.attrgetter("aval")
xla.canonicalize_dtype_handlers[sda] = identity
_register_handlers_for_sharded_device_array(_ShardedDeviceArray)
_register_handlers_for_sharded_device_array(pmap_lib.ShardedDeviceArray)
### the xla_pmap primitive and its rules are comparable to xla_call in xla.py
def xla_pmap_impl(fun: lu.WrappedFun, *args,
backend: Optional[str],
axis_name: core.AxisName,
axis_size: int,
global_axis_size: Optional[int],
devices: Optional[Sequence[Any]],
name: str,
in_axes: Sequence[Optional[int]],
out_axes_thunk: Callable[[], Sequence[Optional[int]]],
donated_invars: Sequence[bool],
global_arg_shapes: Sequence[Optional[Tuple[int, ...]]]):
abstract_args = unsafe_map(xla.abstractify, args)
compiled_fun, fingerprint = parallel_callable(
fun, backend, axis_name, axis_size, global_axis_size, devices, name,
in_axes, out_axes_thunk, donated_invars, global_arg_shapes,
*abstract_args)
# Don't re-abstractify args unless logging is enabled for performance.
if config.jax_distributed_debug:
distributed_debug_log(("Running pmapped function", name),
("python function", fun.f),
("devices", devices),
("abstract args", map(xla.abstractify, args)),
("fingerprint", fingerprint))
return compiled_fun(*args)
@lu.cache
def parallel_callable(fun: lu.WrappedFun,
backend_name: Optional[str],
axis_name: core.AxisName,
axis_size: int,
global_axis_size: Optional[int],
devices: Optional[Sequence[Any]],
name: str,
in_axes: Sequence[Optional[int]],
out_axes_thunk: Callable[[], Sequence[Optional[int]]],
donated_invars: Sequence[bool],
global_arg_shapes: Sequence[Optional[Tuple[int, ...]]],
*avals):
pmap_computation = lower_parallel_callable(
fun, backend_name, axis_name, axis_size, global_axis_size, devices, name,
in_axes, out_axes_thunk, donated_invars, global_arg_shapes, avals)
pmap_executable = pmap_computation.compile()
return WeakRefList([pmap_executable.unsafe_call, pmap_executable.fingerprint])
@dataclasses.dataclass(frozen=True)
class ParallelCallableInfo:
backend: Any
axis_name: core.AxisName
axis_size: int
global_axis_size: Optional[int]
devices: Optional[Sequence[xla.Device]]
in_axes: Iterable[Optional[int]]
out_axes_thunk: Callable[[], Sequence[Optional[int]]]
avals: Sequence[core.AbstractValue]
@maybe_cached_property
def local_devices(self):
if self.devices:
out = [d for d in self.devices
if d.process_index == xb.process_index(self.backend)]
assert len(out) > 0
else:
out = None
return out
@maybe_cached_property
def out_axes(self):
return self.out_axes_thunk()
class ShardInfo(NamedTuple):
sharded_avals: Sequence[core.AbstractValue]
out_sharded_avals: Sequence[core.AbstractValue]
global_sharded_avals: Sequence[core.AbstractValue]
num_local_shards: int
num_global_shards: int
class ReplicaInfo(NamedTuple):
jaxpr_replicas: int
num_local_replicas: int
num_global_replicas: int
def find_replicas(jaxpr, axis_size, global_axis_size):
jaxpr_replicas = dispatch.jaxpr_replicas(jaxpr)
num_local_replicas = axis_size * jaxpr_replicas
num_global_replicas = global_axis_size * jaxpr_replicas
return ReplicaInfo(jaxpr_replicas, num_local_replicas, num_global_replicas)
def tuple_args(shards: ShardInfo):
return len(shards.global_sharded_avals) > 100
def stage_parallel_callable(
pci: ParallelCallableInfo,
fun: lu.WrappedFun,
global_arg_shapes: Sequence[Optional[Tuple[int, ...]]]):
sharded_avals = tuple(
shard_aval(pci.axis_size, axis, aval) if axis is not None else aval
for axis, aval in safe_zip(pci.in_axes, pci.avals))
if any(s is not None for s in global_arg_shapes):
global_sharded_avals = [
aval.update(shape=shape) if shape is not None else aval
for shape, aval in safe_zip(global_arg_shapes, sharded_avals)]
else:
global_sharded_avals = sharded_avals
with core.extend_axis_env(pci.axis_name, pci.global_axis_size, None):
jaxpr, out_sharded_avals, consts = pe.trace_to_jaxpr_final(
fun, global_sharded_avals, pe.debug_info_final(fun, "pmap"))
jaxpr = dispatch.apply_outfeed_rewriter(jaxpr)
assert len(out_sharded_avals) == len(pci.out_axes), (
len(out_sharded_avals), len(pci.out_axes))
if pci.devices is not None:
is_multi_host_pmap = len(pci.local_devices) != len(pci.devices)
else:
is_multi_host_pmap = xb.process_count(pci.backend) > 1
if is_multi_host_pmap:
check_multihost_collective_allowlist(jaxpr)
replicas = find_replicas(jaxpr, pci.axis_size, pci.global_axis_size)
parts = find_partitions(jaxpr)
num_local_shards = replicas.num_local_replicas * parts.local_num_partitions
num_global_shards = replicas.num_global_replicas * parts.num_partitions
shards = ShardInfo(
sharded_avals, out_sharded_avals, global_sharded_avals,
num_local_shards, num_global_shards)
return jaxpr, consts, replicas, parts, shards
def lower_parallel_callable(
fun: lu.WrappedFun,
backend_name: Optional[str],
axis_name: core.AxisName,
axis_size: int,
global_axis_size: Optional[int],
devices: Optional[Sequence[xla.Device]],
name: str,
in_axes: Iterable[Optional[int]],
out_axes_thunk: Callable[[], Sequence[Optional[int]]],
donated_invars: Sequence[bool],
global_arg_shapes: Sequence[Optional[Tuple[int, ...]]],
avals: Sequence[core.AbstractValue]):
if devices is not None and len(devices) == 0:
raise ValueError("'devices' argument to pmap must be non-empty, or None.")
if (xb.process_count() == 1 and global_axis_size is not None and
global_axis_size != axis_size):
raise ValueError(
f"Specified axis_size {global_axis_size} doesn't match received "
f"axis_size {axis_size}.")
if devices is not None and backend_name is None:
backend = xb.get_device_backend(devices[0])
else:
backend = xb.get_backend(backend_name)
must_run_on_all_devices = False
no_nested_sharding = False
if global_axis_size is None:
if xb.process_count(backend) == 1:
global_axis_size = axis_size
elif devices:
# This allows each host in a multi-host pmap to run on a different number
# of devices, but precludes nested sharding (i.e. inner pmaps or
# sharded_jits).
global_axis_size = len(devices)
no_nested_sharding = True
else:
# This assumes all hosts run on the same number of devices. We make sure
# this assumption is true by requiring that the pmap is run on all devices
# (and making the further assumption that each host has the same number of
# devices). Nested sharding is ok in this case.
global_axis_size = axis_size * xb.process_count(backend)
assert all(
len(xb.local_devices(process_index, backend)) == xb.local_device_count(backend)
for process_index in range(xb.process_count(backend)))
must_run_on_all_devices = True
pci = ParallelCallableInfo(
backend, axis_name, axis_size, global_axis_size, devices, in_axes,
out_axes_thunk, avals)
jaxpr, consts, replicas, parts, shards = stage_parallel_callable(
pci, fun, global_arg_shapes)
if logging.vlog_is_on(2):
logging.vlog(2, "sharded_avals: %s", shards.sharded_avals)
logging.vlog(2, "global_sharded_avals: %s", shards.global_sharded_avals)
logging.vlog(2, "num_replicas: %d num_local_replicas: %d",
replicas.num_global_replicas, replicas.num_local_replicas)
logging.vlog(2, "num_partitions: %d local_num_partitions: %d",
parts.num_partitions, parts.local_num_partitions)
logging.vlog(2, "arg_parts: %s", parts.arg_parts)
logging.vlog(2, "local_arg_parts: %s", parts.local_arg_parts)
logging.vlog(2, "out_parts: %s", parts.out_parts)
logging.vlog(2, "local_out_parts: %s", parts.local_out_parts)
logging.vlog(2, "devices: %s", devices)
logging.vlog(2, "local_devices: %s", pci.local_devices)
if (xb.process_count(backend) > 1 and must_run_on_all_devices and
shards.num_local_shards != xb.local_device_count(backend)):
if shards.num_local_shards == axis_size:
raise ValueError(
f"On multi-host platforms, the input to pmapped functions must have "
f"leading axis size equal to the number of local devices if no "
f"`devices` argument is specified. Got axis_size={axis_size}, "
f"num_local_devices={xb.local_device_count(backend)}")
else:
raise ValueError(
f"On multi-host platforms, pmapped functions must run across all "
f"devices, i.e. num_replicas * num_partitions should equal the "
f"number of local devices. Got "
f"num_replicas={replicas.num_local_replicas}, "
f"num_partitions={parts.num_partitions}, and "
f"num_local_devices={xb.local_device_count(backend)}")
if no_nested_sharding and (
replicas.jaxpr_replicas > 1 or parts.num_partitions > 1):
raise ValueError(
f"On multi-host platforms, pmapped functions that both have `devices` "
f"specified and contain an inner_pmap or sharded_jit must specify an "
f"`axis_size` (or remove the `devices` argument). Got nested_replicas="
f"{replicas.jaxpr_replicas} and nested_partitions={parts.num_partitions}")
log_priority = logging.WARNING if config.jax_log_compiles else logging.DEBUG
logging.log(log_priority,
"Compiling %s (%d) for %d devices with args %s. (num_replicas=%d"
" num_partitions=%d)", fun.__name__, id(fun),
shards.num_global_shards, avals, replicas.num_global_replicas,
parts.num_partitions)
axis_env = xla.AxisEnv(
replicas.num_global_replicas, (axis_name,), (global_axis_size,))
c = xc.XlaBuilder("pmap_{}".format(fun.__name__))
xla_consts = map(partial(xla.pyval_to_ir_constant, c), consts)
replicated_args = [axis is None for axis in in_axes]
xla_args, donated_invars = xla._xla_callable_args(
c, shards.global_sharded_avals, tuple_args(shards),
replicated=replicated_args,
partitions=parts.arg_parts,
donated_invars=donated_invars)
with maybe_extend_axis_env(axis_name, global_axis_size, None): # type: ignore
ctx = xla.TranslationContext(c, backend.platform, axis_env,
extend_name_stack(wrap_name(name, 'pmap')))
out_nodes = xla.jaxpr_subcomp(ctx, jaxpr, xla_consts, *xla_args)
build_out_tuple = partial(xops.Tuple, c, out_nodes)
if parts.out_parts is not None:
out_tuple = xb.with_sharding(c, parts.out_parts, build_out_tuple)
else:
out_tuple = build_out_tuple()
if backend.platform in ("gpu", "tpu"):
donated_invars = xla.set_up_aliases(c, xla_args, c.GetShape(out_tuple),
donated_invars, tuple_args(shards))
built = c.Build(out_tuple)
return PmapComputation(built, pci, replicas, parts, shards)
class PmapComputation:
def __init__(self, hlo, *compile_args):
self._executable = None
self.hlo = hlo
self.compile_args = compile_args
def compile(self):
if self._executable is None:
self._executable = PmapExecutable.from_hlo(self.hlo, *self.compile_args)
return self._executable
class PmapExecutable:
__slots__ = ['xla_executable', 'unsafe_call', 'fingerprint', 'in_avals']
def __init__(self, xla_executable, unsafe_call, fingerprint, in_avals):
self.xla_executable = xla_executable
self.unsafe_call = unsafe_call
self.fingerprint = fingerprint
self.in_avals = in_avals
@staticmethod
def from_hlo(xla_computation,
pci: ParallelCallableInfo,
replicas: ReplicaInfo,
parts: 'PartitionInfo',
shards: ShardInfo):
devices = pci.devices
if devices is None:
if shards.num_global_shards > xb.device_count(pci.backend):
msg = ("compiling computation that requires {} logical devices, but only {} XLA "
"devices are available (num_replicas={}, num_partitions={})")
raise ValueError(msg.format(shards.num_global_shards,
xb.device_count(pci.backend),
replicas.num_global_replicas,
parts.num_partitions))
# On a single host, we use the platform's default device assignment to
# violating pmap's semantics where data is sharded across replicas in
if shards.num_global_shards > shards.num_local_shards:
devices = [d for process_index in range(xb.process_count(pci.backend))
for d in xb.local_devices(process_index, pci.backend)]
else:
devices = xb.get_backend(pci.backend).get_default_device_assignment(
replicas.num_global_replicas, parts.num_partitions)
else:
if shards.num_local_shards != len(pci.local_devices):
local_devices_str = ", ".join(map(str, pci.local_devices))
if shards.num_local_shards == pci.axis_size:
raise ValueError(
f"Leading axis size of input to pmapped function must equal the "
f"number of local devices passed to pmap. Got axis_size="
f"{pci.axis_size}, num_local_devices={len(pci.local_devices)}.\n"
f"(Local devices available to pmap: {local_devices_str})")
else:
raise ValueError(
f"pmapped function requires {shards.num_local_shards} local "
f"devices to run due to nested pmapped or other parallel "
f"functions, but only {len(pci.local_devices)} are available.\n"
f"(outer axis size: {pci.axis_size}, local devices available to "
f"pmap: {local_devices_str})")
if shards.num_global_shards != len(devices):
raise ValueError("compiling computation that creates %s shards, "
"but %s devices were specified" %
(shards.num_global_shards, len(devices)))
device_assignment = tree_map(lambda d: d.id, devices)
device_assignment = np.array(device_assignment).reshape(
(replicas.num_global_replicas, parts.num_partitions))
# TODO(b/162356737): Enabling SPMD partitioning causes issues with some
# non-partitioned workloads, so disable unless needed.
use_spmd_partitioning = parts.num_partitions > 1
compile_options = xb.get_compile_options(
num_replicas=replicas.num_global_replicas,
num_partitions=parts.num_partitions,
device_assignment=device_assignment,
use_spmd_partitioning=use_spmd_partitioning,
)
compile_options.parameter_is_tupled_arguments = tuple_args(shards)
local_arg_parts_ = parts.local_arg_parts or [None] * len(pci.avals)
input_sharding_specs = [
_pmap_sharding_spec(replicas.num_local_replicas, pci.axis_size,
parts.local_num_partitions, arg_parts, aval, in_axis)
if aval is not core.abstract_unit else None
for aval, arg_parts, in_axis in safe_zip(
shards.sharded_avals, local_arg_parts_, pci.in_axes)]
input_indices = [spec_to_indices(aval.shape, spec)
if spec is not None else None
for aval, spec in safe_zip(pci.avals, input_sharding_specs)]
nouts = len(shards.out_sharded_avals)
out_parts, local_out_parts = parts.out_parts, parts.local_out_parts
if parts.out_parts is None:
out_parts = (None,) * nouts
if parts.local_out_parts is None:
local_out_parts = (None,) * nouts
local_out_avals = [
get_local_aval(aval, parts, lparts)
for aval, parts, lparts
in safe_zip(shards.out_sharded_avals, out_parts, local_out_parts)]
local_unmapped_avals = [
core.unmapped_aval(pci.axis_size, pci.axis_name, out_axis, aval)
if out_axis is not None else aval
for aval, out_axis in safe_zip(local_out_avals, pci.out_axes)]
out_specs = [
_pmap_sharding_spec(replicas.num_local_replicas, pci.axis_size,
parts.local_num_partitions, out_parts, aval, out_axis)
if aval is not core.abstract_unit else None
for out_parts, aval, out_axis in safe_zip(
local_out_parts, local_out_avals, pci.out_axes)]
handle_outs = avals_to_results_handler(
replicas.num_local_replicas, parts.local_num_partitions, out_specs,
local_unmapped_avals)
if hasattr(pci.backend, "compile_replicated"):
execute_fun = pci.backend.compile_replicated(
xla_computation, compile_options, input_indices, input_sharding_specs,
handle_outs)
# TODO(frostig): need `compile_replicated` to give us the XLA executable
return PmapExecutable(None, execute_fun, None, pci.avals)
compiled = dispatch.compile_or_get_cached(
pci.backend, xla_computation, compile_options)
handle_args = InputsHandler(
compiled.local_devices(), input_sharding_specs, input_indices)
execute_fun = partial(
execute_replicated, compiled, pci.backend, handle_args, handle_outs)
fingerprint = getattr(compiled, "fingerprint", None)
return PmapExecutable(compiled, execute_fun, fingerprint, pci.avals)
def call(self, *args):
# TODO(frostig): do we need to check sharding and sharded avals?
arg_avals = map(xla.abstractify, args)
dispatch.check_arg_avals_for_call(self.in_avals, arg_avals)
return self.unsafe_call(*args)
multi_host_supported_collectives: Set[core.Primitive] = set()
def check_multihost_collective_allowlist(jaxpr):
used_collectives = set(xla.jaxpr_collectives(jaxpr))
if not used_collectives.issubset(multi_host_supported_collectives):
bad_collectives = used_collectives - multi_host_supported_collectives
msg = "using collectives that aren't supported for multi-host: {}"
raise TypeError(msg.format(", ".join(map(str, bad_collectives))))
PartitionsOrReplicated = Optional[Tuple[int, ...]]
class PartitionInfo(NamedTuple):
arg_parts: Optional[Tuple[PartitionsOrReplicated, ...]]
out_parts: Optional[Tuple[PartitionsOrReplicated, ...]]
num_partitions: int
local_arg_parts: Optional[Tuple[PartitionsOrReplicated, ...]]
local_out_parts: Optional[Tuple[PartitionsOrReplicated, ...]]
local_num_partitions: Optional[int]
def _find_partitions(jaxpr):
for eqn in jaxpr.eqns:
if eqn.primitive.name == "sharded_call":
if len(jaxpr.eqns) > 1:
raise NotImplementedError(
"pmap of sharded_jit + non-sharded operations not yet implemented.")
num_partitions = reconcile_num_partitions(eqn.params["call_jaxpr"],
eqn.params["nparts"])
return (eqn.params["in_parts"],
eqn.params["out_parts_thunk"](),
num_partitions,
eqn.params["local_in_parts"],
eqn.params["local_out_parts_thunk"](),
eqn.params["local_nparts"])
return None, None, 1, None, None, None
def find_partitions(jaxpr) -> PartitionInfo:
(arg_parts, out_parts, num_partitions, local_arg_parts, local_out_parts,
local_num_partitions) = _find_partitions(jaxpr)
if local_num_partitions is None:
local_num_partitions = num_partitions
if local_arg_parts is None:
local_arg_parts = arg_parts
if local_out_parts is None:
local_out_parts = out_parts
return PartitionInfo(arg_parts, out_parts, num_partitions,
local_arg_parts, local_out_parts, local_num_partitions)
def reconcile_num_partitions(jaxpr, outer_num_parts: Optional[int]):
inner_num_parts = _inner_partitions(jaxpr, outer_num_parts)
if outer_num_parts is None and inner_num_parts is None:
return 1
if outer_num_parts is None:
return inner_num_parts
return outer_num_parts
def _inner_partitions(jaxpr, expected_num_parts: Optional[int]):
for eqn in jaxpr.eqns:
if eqn.primitive.name in ["sharding_constraint", "infeed"]:
parts = eqn.params["partitions"]
nparts = get_num_partitions(parts)
if expected_num_parts is None:
expected_num_parts = nparts
elif nparts is not None and nparts != expected_num_parts:
raise ValueError(
f"with_sharding_constraint with partitions={parts} "
f"(total partitions: {nparts}) doesn't match expected number of "
f"partitions: {expected_num_parts}. If these partitions look "
f"right, check outer sharded_jit and/or other "
f"with_sharding_constraint calls.")
else:
for subjaxpr in core.jaxprs_in_params(eqn.params):
expected_num_parts = _inner_partitions(subjaxpr, expected_num_parts)
return expected_num_parts
def get_num_partitions(*partitions):
partition_specs = tree_flatten(partitions)[0]
if len(partition_specs) == 0:
# Everything is specified as replicated (all Nones).
return None
num_partitions_set = {np.prod(spec) for spec in partition_specs}
if len(num_partitions_set) > 1:
raise ValueError(
f"All partition specs must use the same number of total partitions, "
f"got {partitions}, with distinct number of partitions "
f"{num_partitions_set} (the total number of partitions is the product "
f"of a partition spec)")
assert len(num_partitions_set) == 1
return num_partitions_set.pop()
def get_global_aval(local_aval, global_parts: PartitionsOrReplicated,
local_parts: PartitionsOrReplicated):
if local_aval is core.abstract_unit:
return local_aval
if global_parts is None:
return local_aval
assert local_parts is not None
global_shape = [dim * _safe_div(ngparts, nlparts)
for dim, ngparts, nlparts
in safe_zip(local_aval.shape, global_parts, local_parts)]
return local_aval.update(shape=global_shape)
def get_local_aval(global_aval, global_parts: PartitionsOrReplicated,
local_parts: PartitionsOrReplicated):
if global_aval is core.abstract_unit:
return global_aval
if global_parts is None:
return global_aval
assert local_parts is not None
local_shape = [_safe_div(dim, _safe_div(ngparts, nlparts))
for dim, ngparts, nlparts
in safe_zip(global_aval.shape, global_parts, local_parts)]
return global_aval.update(shape=local_shape)
def _safe_div(x, y):
result, ragged = divmod(x, y)
assert not ragged, f"{x} % {y} != 0"
return result
class InputsHandler:
__slots__ = ("handler", "local_devices", "sharding_specs", "input_indices")
def __init__(self, local_devices, sharding_specs, input_indices):
self.handler = partial(shard_args, local_devices, input_indices)
self.local_devices = local_devices
self.sharding_specs = sharding_specs
self.input_indices = input_indices
def __call__(self, input_buffers):
return self.handler(input_buffers)
class ResultsHandler:
__slots__ = ("handlers", "out_specs", "out_indices", "unmapped_local_out_avals")
def __init__(self, handlers, out_specs, out_indices, unmapped_local_out_avals):
self.out_specs = out_specs
self.out_indices = out_indices
self.handlers = handlers
self.unmapped_local_out_avals = unmapped_local_out_avals
def __call__(self, out_bufs):
return [h(bufs) for h, bufs in safe_zip(self.handlers, out_bufs)]
def avals_to_results_handler(
nrep,
npart,
out_specs,
unmapped_local_out_avals,
global_out_avals: Optional[Sequence[ShapedArray]] = None,
out_axis_resources: Optional[Sequence[AxisResource]] = None,
global_mesh=None):
out_indices = [spec_to_indices(aval.shape, spec)
if aval is not core.abstract_unit else None
for aval, spec in safe_zip(unmapped_local_out_avals, out_specs)] # pytype: disable=attribute-error
if global_out_avals and out_axis_resources and global_mesh:
handlers = [
aval_to_result_handler(spec, idcs, aval, global_aval, out_axis, global_mesh)
for spec, idcs, aval, global_aval, out_axis in safe_zip(
out_specs, out_indices, unmapped_local_out_avals,
global_out_avals, out_axis_resources)
]
else:
handlers = [
aval_to_result_handler(spec, idcs, aval)
for spec, idcs, aval, in safe_zip(out_specs, out_indices,
unmapped_local_out_avals)
]
return ResultsHandler(handlers, out_specs, out_indices, unmapped_local_out_avals)
def replicate(val, axis_size, nrep, devices=None, backend=None, in_axis=0):
device_count = (len(devices) if devices else xb.local_device_count(backend))
if nrep > device_count:
msg = ("Cannot replicate across %d replicas because only %d local devices "
"are available." % (nrep, device_count))
if devices:
msg += (" (local devices = %s)"
% ", ".join(map(str, devices)) if devices else str(None))
raise ValueError(msg)
if devices is None:
assert nrep is not None
# TODO(skye): use different device assignment on multihost
devices = xb.get_backend(backend).get_default_device_assignment(nrep)
assert nrep == len(devices)
aval = xla.abstractify(val) # type: ShapedArray
if in_axis is not None:
replicated_aval = aval.update(shape=(axis_size,) + aval.shape)
else:
replicated_aval = aval
# TODO(skye): figure out how partitioning should work here
sharding_spec = _pmap_sharding_spec(nrep, axis_size, 1, None, aval, in_axis)
device_buffers = device_put(val, devices, replicate=True)
return make_sharded_device_array(replicated_aval, sharding_spec,
device_buffers)
def _pmap_sharding_spec(nrep, axis_size, npart, parts, sharded_aval,
map_axis: Optional[int]) -> ShardingSpec:
assert isinstance(sharded_aval, ShapedArray), sharded_aval
replication_factor, ragged = divmod(nrep, axis_size)
assert not ragged
# get the sharding spec from inner sharded_jits as if we weren't in a pmap
pspec = partitioned_sharding_spec(npart, parts, sharded_aval)
maybe_replicate = () if replication_factor == 1 else (Replicated(replication_factor),)
if map_axis is not None:
sharded_in_axis = sum(not isinstance(s, NoSharding) for s in pspec.sharding[:map_axis])
def shift_sharded_axis(a: MeshDimAssignment):
if isinstance(a, ShardedAxis) and a.axis >= sharded_in_axis:
return ShardedAxis(a.axis + 1)
return a
return ShardingSpec(
sharding=tuple_insert(pspec.sharding, map_axis, Unstacked(axis_size)),
mesh_mapping=it.chain([ShardedAxis(sharded_in_axis)],
maybe_replicate,
map(shift_sharded_axis, pspec.mesh_mapping)))
else:
return ShardingSpec(
sharding=pspec.sharding,
mesh_mapping=(Replicated(axis_size),) + maybe_replicate + pspec.mesh_mapping)
def partitioned_sharding_spec(num_partitions: int,
partitions: Optional[Sequence[int]],
aval) -> ShardingSpec:
if partitions is None:
maybe_replicate = () if num_partitions == 1 else (Replicated(num_partitions),)
return ShardingSpec(
sharding=[_UNSHARDED_INSTANCE] * len(aval.shape),
mesh_mapping=maybe_replicate)
else:
assert len(partitions) == len(aval.shape)
return ShardingSpec(
sharding=map(Chunked, [[x] for x in partitions]),
mesh_mapping=map(ShardedAxis, range(len(partitions))))
def execute_replicated(compiled, backend, in_handler, out_handler, *args):
input_bufs = in_handler(args)
out_bufs = compiled.execute_sharded_on_local_devices(input_bufs)
if dispatch.needs_check_special():
for bufs in out_bufs:
dispatch.check_special("parallel computation", bufs)
return out_handler(out_bufs)
xla_pmap_p = core.MapPrimitive('xla_pmap')
xla_pmap = xla_pmap_p.bind
xla_pmap_p.def_impl(xla_pmap_impl)
pe.call_param_updaters[xla_pmap_p] = pe.call_param_updaters[xla.xla_call_p]
ad.call_param_updaters[xla_pmap_p] = ad.call_param_updaters[xla.xla_call_p]
ad.call_transpose_param_updaters[xla_pmap_p] = \
ad.call_transpose_param_updaters[xla.xla_call_p]
def _pmap_translation_rule(c, axis_env,
in_nodes, name_stack, axis_name, axis_size,
global_axis_size, devices, name,
call_jaxpr, *, backend=None, in_axes, out_axes,
donated_invars, global_arg_shapes):
del donated_invars
if axis_env.names and devices is not None:
raise ValueError("Nested pmap with explicit devices argument.")
if global_axis_size is None:
global_axis_size = axis_size
new_env = xla.extend_axis_env(axis_env, axis_name, global_axis_size)
in_avals = [v.aval for v in call_jaxpr.invars]
in_nodes_sharded = (
_xla_shard(c, aval, new_env, in_node, in_axis) if in_axis is not None else in_node
for aval, in_node, in_axis in safe_zip(in_avals, in_nodes, in_axes))
with maybe_extend_axis_env(axis_name, global_axis_size, None):
ctx = xla.TranslationContext(
c, backend, new_env,
extend_name_stack(name_stack, wrap_name(name, 'pmap')))
sharded_outs = xla.jaxpr_subcomp(ctx, call_jaxpr, (), *in_nodes_sharded)
out_avals = [v.aval for v in call_jaxpr.outvars]
outs = [_xla_unshard(c, aval, new_env, out_axis, shard, backend=backend)
for aval, out_axis, shard in safe_zip(out_avals, out_axes, sharded_outs)]
return xops.Tuple(c, outs)
xla.call_translations[xla_pmap_p] = _pmap_translation_rule
ad.primitive_transposes[xla_pmap_p] = partial(ad.map_transpose, xla_pmap_p)
def _xla_shard(c, aval, axis_env, x, in_axis):
if aval is core.abstract_unit:
return x
elif aval is core.abstract_token:
return x
elif isinstance(aval, ShapedArray):
dims = list(c.get_shape(x).dimensions())
zero = xops.Constant(c, np.zeros((), dtype=np.uint32))
idxs = [zero] * (len(dims) - 1)
idxs.insert(in_axis, _unravel_index(c, axis_env))
dims_unsqueezed = dims.copy()
dims_unsqueezed[in_axis] = 1
dims_squeezed = dims.copy()
dims_squeezed.pop(in_axis)
return xops.Reshape(xops.DynamicSlice(x, idxs, dims_unsqueezed), dims_squeezed)
else:
raise TypeError((aval, c.get_shape(x)))
def _xla_unshard(c, aval, axis_env, out_axis, x, backend):
if aval is core.abstract_unit:
return x
elif aval is core.abstract_token:
return x
elif isinstance(aval, ShapedArray):
convert_bool = (np.issubdtype(aval.dtype, np.bool_)
and xb.get_backend(backend).platform in ('cpu', 'gpu'))
if convert_bool:
x = xops.ConvertElementType(
x, xla.dtype_to_primitive_type(np.dtype(np.float32)))
xla_shape = c.get_shape(x)
dims = list(xla_shape.dimensions())
padded = xops.Broadcast(
xops.Constant(c, np.array(0, xla_shape.numpy_dtype())),
[axis_env.sizes[-1]] + dims)
zero = xops.Constant(c, np.zeros((), dtype=np.uint32))
idxs = [_unravel_index(c, axis_env)] + [zero] * len(dims)
padded = xops.DynamicUpdateSlice(padded, xops.Reshape(x, [1] + dims), idxs)
replica_groups_protos = xc.make_replica_groups(
xla.axis_groups(axis_env, axis_env.names[-1]))
out = xops.CrossReplicaSum(padded, replica_groups_protos)
if out_axis != 0:
perm = list(range(1, len(dims)))
perm.insert(out_axis, 0)
out = xops.Transpose(out, perm)
if convert_bool:
nonzero = xops.Ne(out, xops.Constant(c, np.array(0, dtype=np.float32)))
out = xops.ConvertElementType(
nonzero, xla.dtype_to_primitive_type(np.dtype(np.bool_)))
return out
else:
raise TypeError((aval, c.get_shape(x)))
def _unravel_index(c, axis_env):
div = xops.Constant(c, np.array(axis_env.nreps // prod(axis_env.sizes),
np.uint32))
mod = xops.Constant(c, np.array(axis_env.sizes[-1], np.uint32))
return xops.Rem(xops.Div(xops.ReplicaId(c), div), mod)
class Mesh:
def __init__(self, devices: np.ndarray, axis_names: Sequence[MeshAxisName]):
assert devices.ndim == len(axis_names)
self.devices = devices.copy()
self.devices.flags.writeable = False
self.axis_names = tuple(axis_names)
def __eq__(self, other):
if not isinstance(other, Mesh):
return False
return (self.axis_names == other.axis_names and
np.array_equal(self.devices, other.devices))
def __hash__(self):
if not hasattr(self, '_hash'):
self._hash = hash((self.axis_names, tuple(self.devices.flat)))
return self._hash
def __setattr__(self, name, value):
if hasattr(self, name):
raise RuntimeError("Cannot reassign attributes of immutable mesh objects")
super().__setattr__(name, value)
@property
def shape(self):
return OrderedDict((name, size) for name, size in safe_zip(self.axis_names, self.devices.shape))
@property
def size(self):
return np.prod(list(self.shape.values()))
@property
def empty(self):
return self.devices.ndim == 0
@property
def is_multi_process(self):
return self.shape != self.local_mesh.shape
@maybe_cached_property
def local_mesh(self):
if self.empty:
return self
process_index = xb.process_index()
is_local_device = np.vectorize(
lambda d: d.process_index == process_index, otypes=[bool])(self.devices)
subcube_indices = []
for axis in range(self.devices.ndim):
other_axes = tuple_delete(tuple(range(self.devices.ndim)), axis)
# NOTE: This re-reduces over many axes multiple times, so we could definitely
# optimize it, but I hope it won't be a bottleneck anytime soon.
local_slices = is_local_device.any(other_axes, keepdims=False)
nonzero_indices = np.flatnonzero(local_slices)
start, end = int(np.min(nonzero_indices)), int(np.max(nonzero_indices))
subcube_indices.append(slice(start, end + 1))
subcube_indices = tuple(subcube_indices)
# subcube that hull will contain non-local devices.
if not is_local_device[subcube_indices].all():
raise ValueError("Devices connected to a single host must form a contiguous "
"subcube of the global device mesh")
return Mesh(self.devices[subcube_indices], self.axis_names)
@property
def device_ids(self):
assert not self.empty
return np.vectorize(lambda d: d.id, otypes=[int])(self.devices)
def __repr__(self):
if self.empty:
return "Mesh([], ())"
return f"Mesh({self.device_ids!r}, {self.axis_names!r})"
@maybe_cached_property
def local_devices(self):
process_index = xb.process_index()
return [d for d in self.devices.flat if d.process_index == process_index]
def local_to_global(self, axes: ArrayMapping, aval):
return untile_aval_nd(self.shape, axes,
tile_aval_nd(self.local_mesh.shape, axes, aval))
def global_to_local(self, axes: ArrayMapping, aval):
return untile_aval_nd(self.local_mesh.shape, axes,
tile_aval_nd(self.shape, axes, aval))
def tile_aval_nd(axis_sizes, in_axes: ArrayMapping, aval, tiling_sizes=None):
if tiling_sizes is None:
tiling_sizes = axis_sizes
if aval is core.abstract_unit:
return aval
assert isinstance(aval, ShapedArray)
shape = list(aval.shape)
named_shape = dict(aval.named_shape)
for name, axis in in_axes.items():
assert shape[axis] % tiling_sizes[name] == 0
assert name not in named_shape
named_shape[name] = axis_sizes[name]
shape[axis] //= tiling_sizes[name]
return aval.update(shape=tuple(shape), named_shape=named_shape)
def untile_aval_nd(axis_sizes, out_axes: ArrayMapping, aval):
if aval is core.abstract_unit:
return aval
assert isinstance(aval, ShapedArray)
shape = list(aval.shape)
named_shape = dict(aval.named_shape)
for name, axis in out_axes.items():
shape[axis] *= axis_sizes[name]
named_shape.pop(name, None) # The name might be missing --- it's a broadcast.
return aval.update(shape=tuple(shape), named_shape=named_shape)
class SPMDBatchTrace(batching.BatchTrace):
def get_axis_primitive_batcher(self, primitive, frame):
if primitive in spmd_primitive_batchers:
return partial(spmd_primitive_batchers[primitive],
frame.size, frame.name, frame.main_trace.trace_type)
return super().get_axis_primitive_batcher(primitive, frame)
spmd_primitive_batchers: Dict[core.Primitive, Callable] = {}
def vtile_by_mesh(fun: lu.WrappedFun,
mesh: Mesh,
in_axes: Sequence[ArrayMapping],
out_axes: Sequence[ArrayMapping]):
for name, size in reversed(mesh.shape.items()):
fun = batching.vtile(fun,
tuple(a.get(name, None) for a in in_axes),
tuple(a.get(name, None) for a in out_axes),
tile_size=size,
axis_name=name,
main_type=SPMDBatchTrace)
return fun
def lower_mesh_computation(
fun: lu.WrappedFun,
transformed_name: str,
mesh: Mesh,
in_axes: Sequence[ArrayMapping],
out_axes: Union[Sequence[ArrayMapping], Callable[[], Sequence[ArrayMapping]]],
donated_invars: Sequence[bool],
spmd_lowering: bool,
local_in_untiled_avals: Sequence[core.ShapedArray],
tile_by_mesh_axes: bool):
assert not mesh.empty
backend = xb.get_device_backend(mesh.devices.flat[0])
local_mesh = mesh.local_mesh
global_axis_sizes = mesh.shape
local_axis_sizes = local_mesh.shape
log_priority = logging.WARNING if config.jax_log_compiles else logging.DEBUG
logging.log(log_priority,
"Compiling %s (%d) for %s mesh with args %s. Argument mapping: "
"%s.",
getattr(fun, '__name__', '<unnamed function>'), id(fun),
tuple(global_axis_sizes.items()), local_in_untiled_avals,
in_axes)
in_tiled_avals = [tile_aval_nd(global_axis_sizes, aval_in_axes, aval,
tiling_sizes=local_axis_sizes)
for aval, aval_in_axes in safe_zip(local_in_untiled_avals, in_axes)]
if spmd_lowering:
if tile_by_mesh_axes:
assert not callable(out_axes)
fun = vtile_by_mesh(fun, mesh, in_axes, out_axes)
global_in_untiled_avals = [untile_aval_nd(global_axis_sizes, aval_in_axes, aval)
for aval, aval_in_axes in safe_zip(in_tiled_avals, in_axes)]
in_jaxpr_avals = global_in_untiled_avals
else:
assert tile_by_mesh_axes
in_jaxpr_avals = in_tiled_avals
with core.extend_axis_env_nd(mesh.shape.items()):
jaxpr, out_jaxpr_avals, consts = pe.trace_to_jaxpr_final(fun, in_jaxpr_avals)
if callable(out_axes):
out_axes = out_axes()
assert len(out_axes) == len(out_jaxpr_avals)
if spmd_lowering:
global_out_untiled_avals = out_jaxpr_avals
out_tiled_avals = [tile_aval_nd(global_axis_sizes, aval_out_axes, aval)
for aval, aval_out_axes in safe_zip(global_out_untiled_avals, out_axes)]
else:
out_tiled_avals = out_jaxpr_avals
local_out_untiled_avals = [untile_aval_nd(local_axis_sizes, aval_out_axes, aval)
for aval, aval_out_axes in safe_zip(out_tiled_avals, out_axes)]
_sanitize_mesh_jaxpr(jaxpr)
if local_mesh.shape != mesh.shape:
check_multihost_collective_allowlist(jaxpr)
jaxpr = dispatch.apply_outfeed_rewriter(jaxpr)
# 3. Build up the HLO
c = xc.XlaBuilder(f"xmap_{fun.__name__}")
xla_consts = map(partial(xla.pyval_to_ir_constant, c), consts)
tuple_args = len(in_jaxpr_avals) > 100 # pass long arg lists as tuple for TPU
in_partitions: Optional[List]
if spmd_lowering:
replicated_args = [False] * len(in_jaxpr_avals)
global_sharding_spec = mesh_sharding_specs(global_axis_sizes, mesh.axis_names)
in_partitions = [global_sharding_spec(aval, aval_in_axes).sharding_proto()
if aval is not core.abstract_unit else None
for aval, aval_in_axes in safe_zip(global_in_untiled_avals, in_axes)]
out_partitions = [global_sharding_spec(aval, aval_out_axes).sharding_proto()
for aval, aval_out_axes in safe_zip(global_out_untiled_avals, out_axes)]
partitions_proto = True
axis_env = xla.AxisEnv(nreps=1, names=(), sizes=()) # All named axes have been vmapped
else:
replicated_args = [not axis for axis in in_axes]
in_partitions = None
partitions_proto = False
axis_env = xla.AxisEnv(nreps=mesh.size,
names=tuple(global_axis_sizes.keys()),
sizes=tuple(global_axis_sizes.values()))
xla_args, donated_invars = xla._xla_callable_args(
c, in_jaxpr_avals, tuple_args,
replicated=replicated_args,
partitions=in_partitions,
partitions_proto=partitions_proto,
donated_invars=donated_invars)
with core.extend_axis_env_nd(mesh.shape.items()):
ctx = xla.TranslationContext(
c, backend.platform, axis_env,
extend_name_stack(wrap_name(transformed_name, 'xmap')))
out_nodes = xla.jaxpr_subcomp(ctx, jaxpr, xla_consts, *xla_args)
if spmd_lowering:
out_partitions_t = xb.tuple_sharding_proto(out_partitions)
out_tuple = xb.with_sharding_proto(c, out_partitions_t, xops.Tuple, c, out_nodes)
else:
out_tuple = xops.Tuple(c, out_nodes)
if backend.platform in ("gpu", "tpu"):
xla.set_up_aliases(c, xla_args, c.GetShape(out_tuple), donated_invars,
tuple_args)
# TODO: Warn about unused donations?
built = c.Build(out_tuple)
return MeshComputation(
built, donated_invars, mesh, local_in_untiled_avals,
local_out_untiled_avals, (out_jaxpr_avals if spmd_lowering else None),
in_axes, out_axes, spmd_lowering, tuple_args)
class MeshComputation:
def __init__(self, hlo, donated_invars, *compile_args):
self._executable = None
self._hlo = hlo
self._donated_invars = donated_invars
self.compile_args = compile_args
def hlo(self):
# this is a method for api consistency with xla.XlaComputation
return self._hlo
def compile(self,
_allow_propagation_to_outputs : bool = False,
_allow_compile_replicated : bool = True) -> 'MeshExecutable':
if self._executable is None:
self._executable = MeshExecutable.from_hlo(
self._hlo, *self.compile_args,
_allow_propagation_to_outputs=_allow_propagation_to_outputs,
_allow_compile_replicated=_allow_compile_replicated) # type: ignore
return self._executable
class MeshExecutable:
__slots__ = ['xla_executable', 'unsafe_call', '_local_in_untiled_avals']
def __init__(self, xla_executable, unsafe_call, local_in_untiled_avals):
self.xla_executable = xla_executable
self.unsafe_call = unsafe_call
self._local_in_untiled_avals = local_in_untiled_avals
@staticmethod
def from_hlo(computation: xc.XlaComputation,
mesh: Mesh,
local_in_untiled_avals: Sequence[ShapedArray],
local_out_untiled_avals: Sequence[ShapedArray],
global_out_avals: Optional[Sequence[ShapedArray]],
in_axes: Sequence[ArrayMapping],
out_axes: Sequence[ArrayMapping],
spmd_lowering: bool, tuple_args: bool,
_allow_propagation_to_outputs: bool,
_allow_compile_replicated: bool):
assert not mesh.empty
backend = xb.get_device_backend(mesh.devices.flat[0])
local_mesh = mesh.local_mesh
local_axis_sizes = local_mesh.shape
if spmd_lowering:
num_replicas, num_partitions = 1, mesh.size
num_local_replicas, num_local_partitions = 1, local_mesh.size
else:
num_replicas, num_partitions = mesh.size, 1
num_local_replicas, num_local_partitions = local_mesh.size, 1
device_assignment = mesh.device_ids.reshape((num_replicas, num_partitions))
compile_options = xb.get_compile_options(
num_replicas=num_replicas,
num_partitions=num_partitions,
device_assignment=device_assignment,
use_spmd_partitioning=spmd_lowering,
)
compile_options.parameter_is_tupled_arguments = tuple_args
compile_options.executable_build_options.allow_spmd_sharding_propagation_to_output = \
_allow_propagation_to_outputs
local_sharding_spec = mesh_sharding_specs(local_axis_sizes, mesh.axis_names)
local_input_specs = [local_sharding_spec(aval, aval_in_axes)
if aval is not core.abstract_unit else None
for aval, aval_in_axes in safe_zip(local_in_untiled_avals, in_axes)]
input_indices = [spec_to_indices(aval.shape, spec)
if spec is not None else None
for aval, spec in safe_zip(local_in_untiled_avals, local_input_specs)]
local_output_specs = [local_sharding_spec(aval, aval_out_axes)
for aval, aval_out_axes in safe_zip(local_out_untiled_avals, out_axes)]
out_axis_resources = [array_mapping_to_axis_resources(o) for o in out_axes]
handle_outs = avals_to_results_handler(num_local_replicas, num_local_partitions,
local_output_specs, local_out_untiled_avals,
global_out_avals, out_axis_resources, mesh)
if _allow_compile_replicated and hasattr(backend, "compile_replicated"):
unsafe_call = backend.compile_replicated(
computation, compile_options,
input_indices, local_input_specs,
handle_outs)
xla_executable = None
else:
compiled = dispatch.compile_or_get_cached(backend, computation, compile_options)
handle_args = InputsHandler(compiled.local_devices(), local_input_specs,
input_indices)
unsafe_call = partial(execute_replicated, compiled, backend, handle_args, handle_outs)
xla_executable = compiled
return MeshExecutable(xla_executable, unsafe_call, local_in_untiled_avals)
def call(self, *args):
arg_avals = map(xla.abstractify, args)
ref_avals = self._local_in_untiled_avals
dispatch.check_arg_avals_for_call(ref_avals, arg_avals)
return self.unsafe_call(*args)
_forbidden_primitives = {
'xla_pmap': 'pmap',
'sharded_call': 'sharded_jit',
}
def _sanitize_mesh_jaxpr(jaxpr):
if isinstance(jaxpr, core.ClosedJaxpr):
jaxpr = jaxpr.jaxpr
for eqn in jaxpr.eqns:
if eqn.primitive.name in _forbidden_primitives:
raise RuntimeError(f"Nesting {_forbidden_primitives[eqn.primitive.name]} "
f"inside xmaps not supported!")
core.traverse_jaxpr_params(_sanitize_mesh_jaxpr, eqn.params)
custom_resource_typing_rules: Dict[core.Primitive, Callable] = {}
def resource_typecheck(jaxpr, resource_env, axis_resources, what_jaxpr_thunk):
if isinstance(jaxpr, core.ClosedJaxpr):
jaxpr = jaxpr.jaxpr
def _check_aval(aval, what_thunk):
if not hasattr(aval, 'named_shape'):
return
resource_to_axis = {}
for axis in aval.named_shape:
for resource in axis_resources[axis]:
if resource in resource_to_axis:
other_axis = resource_to_axis[resource]
axis, other_axis = sorted([str(axis), str(other_axis)])
raise JAXTypeError(
f"Axes `{axis}` and `{other_axis}` are both mapped to the "
f"resource `{resource}`, but they coincide in the named_shape "
f"of {what_thunk()}")
resource_to_axis[resource] = axis
what_thunk = lambda: (f"an input to {what_jaxpr_thunk()}")
for v in jaxpr.constvars:
_check_aval(v.aval, what_thunk)
for v in jaxpr.invars:
_check_aval(v.aval, what_thunk)
what_thunk = lambda: (f"a value returned from a primitive {eqn.primitive} created "
f"at {source_info_util.summarize(eqn.source_info)}")
rec_what_jaxpr_thunk = lambda: (f"a primitive {eqn.primitive} created at"
f"{source_info_util.summarize(eqn.source_info)}")
for eqn in jaxpr.eqns:
typing_rule = custom_resource_typing_rules.get(eqn.primitive, None)
if typing_rule:
typing_rule([v.aval for v in eqn.invars], eqn.params, eqn.source_info,
resource_env, axis_resources)
else:
core.traverse_jaxpr_params(partial(resource_typecheck,
resource_env=resource_env,
axis_resources=axis_resources,
what_jaxpr_thunk=rec_what_jaxpr_thunk),
eqn.params)
for v in eqn.outvars:
_check_aval(v.aval, what_thunk)
def mesh_sharding_specs(axis_sizes, axis_names):
mesh_axis_pos = {name: i for i, name in enumerate(axis_names)}
# NOTE: This takes in the non-sharded avals!
def mk_sharding_spec(aval, aval_axes):
mesh_mapping = [Replicated(axis_size) for axis_size in axis_sizes.values()]
if aval is core.abstract_token:
assert not aval_axes
return ShardingSpec([], mesh_mapping)
sharding = [_UNSHARDED_INSTANCE] * len(aval.shape)
next_sharded_axis = 0
aval_shape = list(aval.shape)
# NOTE: sorted is stable, which is important when multiple resources
# map to the same axis.
for name, axis in sorted(aval_axes.items(), key=lambda x: x[1]):
assert aval_shape[axis] % axis_sizes[name] == 0, (axis_sizes[name], aval.shape[axis])
aval_shape[axis] //= axis_sizes[name]
if isinstance(sharding[axis], NoSharding):
sharding[axis] = Chunked([])
sharding[axis] = Chunked(sharding[axis].chunks + [axis_sizes[name]])
assert isinstance(mesh_mapping[mesh_axis_pos[name]], Replicated), \
"Value mapped to the same mesh axis twice"
mesh_mapping[mesh_axis_pos[name]] = ShardedAxis(next_sharded_axis)
next_sharded_axis += 1
return ShardingSpec(sharding, mesh_mapping)
return mk_sharding_spec
@contextmanager
def maybe_extend_axis_env(*args, **kwargs):
with core.extend_axis_env(*args, **kwargs):
yield
class DynamicAxisEnvFrame(object):
__slots__ = ["name", "pmap_trace", "hard_size"]
def __init__(self, name, pmap_trace, hard_size):
self.name = name
self.pmap_trace = pmap_trace
self.hard_size = hard_size
class DynamicAxisEnv(list):
def __contains__(self, axis_name):
return axis_name in (frame.name for frame in self)
def __getitem__(self, axis_name):
if axis_name not in self:
raise NameError("unbound axis name: {}".format(axis_name))
for frame in reversed(self):
if frame.name == axis_name:
return frame
raise AssertionError
@property
def sizes(self):
return tuple(frame.hard_size for frame in self)
@property
def nreps(self):
return prod(frame.hard_size for frame in self)
class _ThreadLocalState(threading.local):
def __init__(self):
self.dynamic_axis_env = DynamicAxisEnv()
_thread_local_state = _ThreadLocalState()
def device_put(x, devices: Sequence[xb.xla_client.Device], replicate: bool=False) -> List[xb.xla_client.Buffer]:
if replicate:
return list(it.chain.from_iterable(dispatch.device_put(x, device) for device in devices))
else:
return list(it.chain.from_iterable(dispatch.device_put(val, device) for val, device in safe_zip(x, devices)))
| true | true |
f72838bf20112d8e79c4ac5d0568dc33060c0ae6 | 1,960 | py | Python | assembler.py | martimfj/VBA-Compiler | c5a88843a0d13d561f4baba312bbaf7f8a2e5ca0 | [
"MIT"
] | null | null | null | assembler.py | martimfj/VBA-Compiler | c5a88843a0d13d561f4baba312bbaf7f8a2e5ca0 | [
"MIT"
] | 9 | 2019-02-23T13:19:30.000Z | 2019-06-08T14:34:23.000Z | assembler.py | martimfj/VBA-Compiler | c5a88843a0d13d561f4baba312bbaf7f8a2e5ca0 | [
"MIT"
] | null | null | null | CONSTANTS = [
"SYS_EXIT equ 1",
"SYS_READ equ 3",
"SYS_WRITE equ 4",
"STDIN equ 0",
"STDOUT equ 1",
"True equ 1",
"False equ 0"
]
DATA_SEG = [
"segment .data"
]
BSS_SEG = [
"segment .bss",
" res RESB 1"
]
TEXT_SEG =[
"section .text",
" global _start"
]
PRINT_SUBROUTINE = [
"print:",
" PUSH EBP",
" MOV EBP, ESP",
" MOV EAX, [EBP+8]",
" XOR ESI, ESI",
"print_dec:",
" MOV EDX, 0",
" MOV EBX, 0x000A",
" DIV EBX",
" ADD EDX, '0'",
" PUSH EDX",
" INC ESI",
" CMP EAX, 0",
" JZ print_next",
" JMP print_dec",
"print_next:",
" CMP ESI, 0",
" JZ print_exit",
" DEC ESI",
" MOV EAX, SYS_WRITE",
" MOV EBX, STDOUT",
" POP ECX",
" MOV [res], ECX",
" MOV ECX, res",
" MOV EDX, 1",
" INT 0x80",
" JMP print_next",
"print_exit:",
" POP EBP",
" RET"
]
IF_WHILE_SUBROUTINE = [
"binop_je:",
" JE binop_true",
" JMP binop_false",
"binop_jg:",
" JG binop_true",
" JMP binop_false",
"binop_jl:",
" JL binop_true",
" JMP binop_false",
"binop_false:",
" MOV EBX, False",
" JMP binop_exit",
"binop_true:",
" MOV EBX, True",
"binop_exit:",
" RET"
]
INTERRUPT = [
" POP EBP",
" MOV EAX, 1",
" INT 0x80"
]
class Assembler:
program = ["_start:", " PUSH EBP", " MOV EBP, ESP"]
@staticmethod
def write_line(line):
Assembler.program.append(" " + line)
@staticmethod
def write_comment(line):
Assembler.program.append("\n ; " + line)
@staticmethod
def clean_line():
Assembler.program.append("\r")
@staticmethod
def write_file():
code = []
sections = [CONSTANTS, DATA_SEG, BSS_SEG, TEXT_SEG, PRINT_SUBROUTINE, IF_WHILE_SUBROUTINE, Assembler.program, INTERRUPT]
for section in sections:
code.extend(section)
code.append("\r")
with open("program.asm", "w") as myfile:
for line in code:
myfile.write(line + "\n") | 16.896552 | 128 | 0.554082 | CONSTANTS = [
"SYS_EXIT equ 1",
"SYS_READ equ 3",
"SYS_WRITE equ 4",
"STDIN equ 0",
"STDOUT equ 1",
"True equ 1",
"False equ 0"
]
DATA_SEG = [
"segment .data"
]
BSS_SEG = [
"segment .bss",
" res RESB 1"
]
TEXT_SEG =[
"section .text",
" global _start"
]
PRINT_SUBROUTINE = [
"print:",
" PUSH EBP",
" MOV EBP, ESP",
" MOV EAX, [EBP+8]",
" XOR ESI, ESI",
"print_dec:",
" MOV EDX, 0",
" MOV EBX, 0x000A",
" DIV EBX",
" ADD EDX, '0'",
" PUSH EDX",
" INC ESI",
" CMP EAX, 0",
" JZ print_next",
" JMP print_dec",
"print_next:",
" CMP ESI, 0",
" JZ print_exit",
" DEC ESI",
" MOV EAX, SYS_WRITE",
" MOV EBX, STDOUT",
" POP ECX",
" MOV [res], ECX",
" MOV ECX, res",
" MOV EDX, 1",
" INT 0x80",
" JMP print_next",
"print_exit:",
" POP EBP",
" RET"
]
IF_WHILE_SUBROUTINE = [
"binop_je:",
" JE binop_true",
" JMP binop_false",
"binop_jg:",
" JG binop_true",
" JMP binop_false",
"binop_jl:",
" JL binop_true",
" JMP binop_false",
"binop_false:",
" MOV EBX, False",
" JMP binop_exit",
"binop_true:",
" MOV EBX, True",
"binop_exit:",
" RET"
]
INTERRUPT = [
" POP EBP",
" MOV EAX, 1",
" INT 0x80"
]
class Assembler:
program = ["_start:", " PUSH EBP", " MOV EBP, ESP"]
@staticmethod
def write_line(line):
Assembler.program.append(" " + line)
@staticmethod
def write_comment(line):
Assembler.program.append("\n ; " + line)
@staticmethod
def clean_line():
Assembler.program.append("\r")
@staticmethod
def write_file():
code = []
sections = [CONSTANTS, DATA_SEG, BSS_SEG, TEXT_SEG, PRINT_SUBROUTINE, IF_WHILE_SUBROUTINE, Assembler.program, INTERRUPT]
for section in sections:
code.extend(section)
code.append("\r")
with open("program.asm", "w") as myfile:
for line in code:
myfile.write(line + "\n") | true | true |
f7283953cc559dbedfe2237debe920767512e3e6 | 1,115 | py | Python | share/rpcuser/rpcuser.py | DTL-UWM/SOISCOIN | dd9553a5f79fab4a044eaae1423426346d9c4a53 | [
"MIT"
] | null | null | null | share/rpcuser/rpcuser.py | DTL-UWM/SOISCOIN | dd9553a5f79fab4a044eaae1423426346d9c4a53 | [
"MIT"
] | null | null | null | share/rpcuser/rpcuser.py | DTL-UWM/SOISCOIN | dd9553a5f79fab4a044eaae1423426346d9c4a53 | [
"MIT"
] | null | null | null | #!/usr/bin/env python2
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import hashlib
import sys
import os
from random import SystemRandom
import base64
import hmac
if len(sys.argv) < 2:
sys.stderr.write('Please include username as an argument.\n')
sys.exit(0)
username = sys.argv[1]
#This uses os.urandom() underneath
cryptogen = SystemRandom()
#Create 16 byte hex salt
salt_sequence = [cryptogen.randrange(256) for i in range(16)]
hexseq = list(map(hex, salt_sequence))
salt = "".join([x[2:] for x in hexseq])
#Create 32 byte b64 password
password = base64.urlsafe_b64encode(os.urandom(32))
digestmod = hashlib.sha256
if sys.version_info.major >= 3:
password = password.decode('utf-8')
digestmod = 'SHA256'
m = hmac.new(bytearray(salt, 'utf-8'), bytearray(password, 'utf-8'), digestmod)
result = m.hexdigest()
print("String to be appended to soiscoin.conf:")
print("rpcauth="+username+":"+salt+"$"+result)
print("Your password:\n"+password)
| 26.547619 | 79 | 0.728251 |
import hashlib
import sys
import os
from random import SystemRandom
import base64
import hmac
if len(sys.argv) < 2:
sys.stderr.write('Please include username as an argument.\n')
sys.exit(0)
username = sys.argv[1]
cryptogen = SystemRandom()
salt_sequence = [cryptogen.randrange(256) for i in range(16)]
hexseq = list(map(hex, salt_sequence))
salt = "".join([x[2:] for x in hexseq])
password = base64.urlsafe_b64encode(os.urandom(32))
digestmod = hashlib.sha256
if sys.version_info.major >= 3:
password = password.decode('utf-8')
digestmod = 'SHA256'
m = hmac.new(bytearray(salt, 'utf-8'), bytearray(password, 'utf-8'), digestmod)
result = m.hexdigest()
print("String to be appended to soiscoin.conf:")
print("rpcauth="+username+":"+salt+"$"+result)
print("Your password:\n"+password)
| true | true |
f72839a973138a4955ecdaae9704a9b1a0d96162 | 6,700 | py | Python | mne/time_frequency/_stft.py | enricovara/mne-python | f6f2aa7a97c3ae7ae5276202805d2f45de7b64cc | [
"BSD-3-Clause"
] | 1 | 2021-03-13T04:41:45.000Z | 2021-03-13T04:41:45.000Z | mne/time_frequency/_stft.py | enricovara/mne-python | f6f2aa7a97c3ae7ae5276202805d2f45de7b64cc | [
"BSD-3-Clause"
] | 1 | 2021-01-29T19:35:06.000Z | 2021-01-29T19:35:06.000Z | mne/time_frequency/_stft.py | enricovara/mne-python | f6f2aa7a97c3ae7ae5276202805d2f45de7b64cc | [
"BSD-3-Clause"
] | null | null | null | from math import ceil
import numpy as np
from ..fixes import rfft, irfft, rfftfreq
from ..utils import logger, verbose
@verbose
def stft(x, wsize, tstep=None, verbose=None):
"""STFT Short-Term Fourier Transform using a sine window.
The transformation is designed to be a tight frame that can be
perfectly inverted. It only returns the positive frequencies.
Parameters
----------
x : array, shape (n_signals, n_times)
Containing multi-channels signal.
wsize : int
Length of the STFT window in samples (must be a multiple of 4).
tstep : int
Step between successive windows in samples (must be a multiple of 2,
a divider of wsize and smaller than wsize/2) (default: wsize/2).
%(verbose)s
Returns
-------
X : array, shape (n_signals, wsize // 2 + 1, n_step)
STFT coefficients for positive frequencies with
``n_step = ceil(T / tstep)``.
See Also
--------
istft
stftfreq
"""
if not np.isrealobj(x):
raise ValueError("x is not a real valued array")
if x.ndim == 1:
x = x[None, :]
n_signals, T = x.shape
wsize = int(wsize)
# Errors and warnings
if wsize % 4:
raise ValueError('The window length must be a multiple of 4.')
if tstep is None:
tstep = wsize / 2
tstep = int(tstep)
if (wsize % tstep) or (tstep % 2):
raise ValueError('The step size must be a multiple of 2 and a '
'divider of the window length.')
if tstep > wsize / 2:
raise ValueError('The step size must be smaller than half the '
'window length.')
n_step = int(ceil(T / float(tstep)))
n_freq = wsize // 2 + 1
logger.info("Number of frequencies: %d" % n_freq)
logger.info("Number of time steps: %d" % n_step)
X = np.zeros((n_signals, n_freq, n_step), dtype=np.complex128)
if n_signals == 0:
return X
# Defining sine window
win = np.sin(np.arange(.5, wsize + .5) / wsize * np.pi)
win2 = win ** 2
swin = np.zeros((n_step - 1) * tstep + wsize)
for t in range(n_step):
swin[t * tstep:t * tstep + wsize] += win2
swin = np.sqrt(wsize * swin)
# Zero-padding and Pre-processing for edges
xp = np.zeros((n_signals, wsize + (n_step - 1) * tstep),
dtype=x.dtype)
xp[:, (wsize - tstep) // 2: (wsize - tstep) // 2 + T] = x
x = xp
for t in range(n_step):
# Framing
wwin = win / swin[t * tstep: t * tstep + wsize]
frame = x[:, t * tstep: t * tstep + wsize] * wwin[None, :]
# FFT
X[:, :, t] = rfft(frame)
return X
def istft(X, tstep=None, Tx=None):
"""ISTFT Inverse Short-Term Fourier Transform using a sine window.
Parameters
----------
X : array, shape (..., wsize / 2 + 1, n_step)
The STFT coefficients for positive frequencies.
tstep : int
Step between successive windows in samples (must be a multiple of 2,
a divider of wsize and smaller than wsize/2) (default: wsize/2).
Tx : int
Length of returned signal. If None Tx = n_step * tstep.
Returns
-------
x : array, shape (Tx,)
Array containing the inverse STFT signal.
See Also
--------
stft
"""
# Errors and warnings
X = np.asarray(X)
if X.ndim < 2:
raise ValueError(f'X must have ndim >= 2, got {X.ndim}')
n_win, n_step = X.shape[-2:]
signal_shape = X.shape[:-2]
if n_win % 2 == 0:
raise ValueError('The number of rows of the STFT matrix must be odd.')
wsize = 2 * (n_win - 1)
if tstep is None:
tstep = wsize / 2
if wsize % tstep:
raise ValueError('The step size must be a divider of two times the '
'number of rows of the STFT matrix minus two.')
if wsize % 2:
raise ValueError('The step size must be a multiple of 2.')
if tstep > wsize / 2:
raise ValueError('The step size must be smaller than the number of '
'rows of the STFT matrix minus one.')
if Tx is None:
Tx = n_step * tstep
T = n_step * tstep
x = np.zeros(signal_shape + (T + wsize - tstep,), dtype=np.float64)
if np.prod(signal_shape) == 0:
return x[..., :Tx]
# Defining sine window
win = np.sin(np.arange(.5, wsize + .5) / wsize * np.pi)
# win = win / norm(win);
# Pre-processing for edges
swin = np.zeros(T + wsize - tstep, dtype=np.float64)
for t in range(n_step):
swin[t * tstep:t * tstep + wsize] += win ** 2
swin = np.sqrt(swin / wsize)
for t in range(n_step):
# IFFT
frame = irfft(X[..., t], wsize)
# Overlap-add
frame *= win / swin[t * tstep:t * tstep + wsize]
x[..., t * tstep: t * tstep + wsize] += frame
# Truncation
x = x[..., (wsize - tstep) // 2: (wsize - tstep) // 2 + T + 1]
x = x[..., :Tx].copy()
return x
def stftfreq(wsize, sfreq=None): # noqa: D401
"""Compute frequencies of stft transformation.
Parameters
----------
wsize : int
Size of stft window.
sfreq : float
Sampling frequency. If None the frequencies are given between 0 and pi
otherwise it's given in Hz.
Returns
-------
freqs : array
The positive frequencies returned by stft.
See Also
--------
stft
istft
"""
freqs = rfftfreq(wsize)
if sfreq is not None:
freqs *= float(sfreq)
return freqs
def stft_norm2(X):
"""Compute L2 norm of STFT transform.
It takes into account that stft only return positive frequencies.
As we use tight frame this quantity is conserved by the stft.
Parameters
----------
X : 3D complex array
The STFT transforms
Returns
-------
norms2 : array
The squared L2 norm of every row of X.
"""
X2 = (X * X.conj()).real
# compute all L2 coefs and remove first and last frequency once.
norms2 = (2. * X2.sum(axis=2).sum(axis=1) - np.sum(X2[:, 0, :], axis=1) -
np.sum(X2[:, -1, :], axis=1))
return norms2
def stft_norm1(X):
"""Compute L1 norm of STFT transform.
It takes into account that stft only return positive frequencies.
Parameters
----------
X : 3D complex array
The STFT transforms
Returns
-------
norms : array
The L1 norm of every row of X.
"""
X_abs = np.abs(X)
# compute all L1 coefs and remove first and last frequency once.
norms = (2. * X_abs.sum(axis=(1, 2)) -
np.sum(X_abs[:, 0, :], axis=1) - np.sum(X_abs[:, -1, :], axis=1))
return norms
| 27.125506 | 78 | 0.568209 | from math import ceil
import numpy as np
from ..fixes import rfft, irfft, rfftfreq
from ..utils import logger, verbose
@verbose
def stft(x, wsize, tstep=None, verbose=None):
if not np.isrealobj(x):
raise ValueError("x is not a real valued array")
if x.ndim == 1:
x = x[None, :]
n_signals, T = x.shape
wsize = int(wsize)
if wsize % 4:
raise ValueError('The window length must be a multiple of 4.')
if tstep is None:
tstep = wsize / 2
tstep = int(tstep)
if (wsize % tstep) or (tstep % 2):
raise ValueError('The step size must be a multiple of 2 and a '
'divider of the window length.')
if tstep > wsize / 2:
raise ValueError('The step size must be smaller than half the '
'window length.')
n_step = int(ceil(T / float(tstep)))
n_freq = wsize // 2 + 1
logger.info("Number of frequencies: %d" % n_freq)
logger.info("Number of time steps: %d" % n_step)
X = np.zeros((n_signals, n_freq, n_step), dtype=np.complex128)
if n_signals == 0:
return X
win = np.sin(np.arange(.5, wsize + .5) / wsize * np.pi)
win2 = win ** 2
swin = np.zeros((n_step - 1) * tstep + wsize)
for t in range(n_step):
swin[t * tstep:t * tstep + wsize] += win2
swin = np.sqrt(wsize * swin)
xp = np.zeros((n_signals, wsize + (n_step - 1) * tstep),
dtype=x.dtype)
xp[:, (wsize - tstep) // 2: (wsize - tstep) // 2 + T] = x
x = xp
for t in range(n_step):
wwin = win / swin[t * tstep: t * tstep + wsize]
frame = x[:, t * tstep: t * tstep + wsize] * wwin[None, :]
X[:, :, t] = rfft(frame)
return X
def istft(X, tstep=None, Tx=None):
X = np.asarray(X)
if X.ndim < 2:
raise ValueError(f'X must have ndim >= 2, got {X.ndim}')
n_win, n_step = X.shape[-2:]
signal_shape = X.shape[:-2]
if n_win % 2 == 0:
raise ValueError('The number of rows of the STFT matrix must be odd.')
wsize = 2 * (n_win - 1)
if tstep is None:
tstep = wsize / 2
if wsize % tstep:
raise ValueError('The step size must be a divider of two times the '
'number of rows of the STFT matrix minus two.')
if wsize % 2:
raise ValueError('The step size must be a multiple of 2.')
if tstep > wsize / 2:
raise ValueError('The step size must be smaller than the number of '
'rows of the STFT matrix minus one.')
if Tx is None:
Tx = n_step * tstep
T = n_step * tstep
x = np.zeros(signal_shape + (T + wsize - tstep,), dtype=np.float64)
if np.prod(signal_shape) == 0:
return x[..., :Tx]
win = np.sin(np.arange(.5, wsize + .5) / wsize * np.pi)
swin = np.zeros(T + wsize - tstep, dtype=np.float64)
for t in range(n_step):
swin[t * tstep:t * tstep + wsize] += win ** 2
swin = np.sqrt(swin / wsize)
for t in range(n_step):
frame = irfft(X[..., t], wsize)
frame *= win / swin[t * tstep:t * tstep + wsize]
x[..., t * tstep: t * tstep + wsize] += frame
x = x[..., (wsize - tstep) // 2: (wsize - tstep) // 2 + T + 1]
x = x[..., :Tx].copy()
return x
def stftfreq(wsize, sfreq=None):
freqs = rfftfreq(wsize)
if sfreq is not None:
freqs *= float(sfreq)
return freqs
def stft_norm2(X):
X2 = (X * X.conj()).real
norms2 = (2. * X2.sum(axis=2).sum(axis=1) - np.sum(X2[:, 0, :], axis=1) -
np.sum(X2[:, -1, :], axis=1))
return norms2
def stft_norm1(X):
X_abs = np.abs(X)
norms = (2. * X_abs.sum(axis=(1, 2)) -
np.sum(X_abs[:, 0, :], axis=1) - np.sum(X_abs[:, -1, :], axis=1))
return norms
| true | true |
f72839c01680fa5e8dca84f89e02ed7c86a3f02b | 6,728 | py | Python | hw4/p2_Parsons_Ross.py | rp779/Python-COP-4045 | 2feabafef4a3ee04d593a35aa77f45b5d25d3754 | [
"MIT"
] | null | null | null | hw4/p2_Parsons_Ross.py | rp779/Python-COP-4045 | 2feabafef4a3ee04d593a35aa77f45b5d25d3754 | [
"MIT"
] | null | null | null | hw4/p2_Parsons_Ross.py | rp779/Python-COP-4045 | 2feabafef4a3ee04d593a35aa77f45b5d25d3754 | [
"MIT"
] | null | null | null | # Problem 2
# @author: Ross
import sys # sys.exit()
import testif # testif module
import turtle # Part A
def draw_leaf_straight(length, level):
"""PART A: The draw_leaf_straight() function takes two arguments (length and level) and returns a graphic that depicts a leaf drawn in turtle graphics. """
if level <= 0: # base cass
return
else: # recursive case
turtle.forward(length)
draw_leaf_straight(0.6*length, level-1) # draws all middle branches
turtle.left(45)
draw_leaf_straight(0.6*length, level-1) # draws all left branches
turtle.right(90)
draw_leaf_straight(0.6*length, level-1) # draws all left branches
turtle.left(45)
turtle.backward(length)
return
def strB(n, base=10):
""" PART B: strB converts n (which is in base 10) to any base between 2 and 26. This is done by checking a string containing 26 items, for the 26 possible bases the user can convert to. n is divided by base using integer division (//) and the remainder is collected (the remainder will always be less than the base) by searching in alpha_num_str. """
class BadBase(Exception):
""" BadBase is a subclass of the exception class. This class is used to raise an exception if a user enters a base that is not between 2 and 26, BadBase will be raised. """
pass
try:
if base < 2 or base > 26:
raise BadBase
except BadBase:
print('Base must be between 2 and 26. Exiting...')
sys.exit()
else:
# a string representation to allow for conversion to any base between 2 and 26.
alpha_num_str = '0123456789ABCDEFGHIJKLMNOPQ'
# base case - if the number is less than the base, just look for the number in alpha_num_str and return it.
if n < base:
return alpha_num_str[n]
else:
# recursive case - to convert any base 10 number to any base, the general algorithm is to find the remainder of n / base, followed by n / new quotient. Continue doing this successively and collecting the remainders on each calculation. Then return the remainders in reverse order. In strB, the remainders are calculated by n % base and then searched for in alpha_num_str and concatenated together.
return strB(n // base, base) + alpha_num_str[n % base]
def Cnk_m(n, k):
""" PART C: Cnk_m returns a function that tests whether the n-choose-k values have been calculated yet and stores them in a dictionary so they can be returned instead re-calculated. """
# a dictionary that stores n-choose-k values e.g. { (n,k): value, (n,k):value } the key is a tuple - (n,k)
cache = dict()
def memoization_step(n, k):
""" inner function that runs recursively. """
if (n, k) not in cache: # first check these particular values of (n, k) have already been calculated.
if k == 0 or k == n: # base case
return 1
else: # recursive step. (n,k) have not been calculated and stored in the cache, so calculate them and store them in cache
cache[(n, k)] = memoization_step(
n-1, k-1) + memoization_step(n-1, k)
# if (n, k) have been calculated, simply return their value.
return cache[(n, k)]
return memoization_step(n, k)
def make_pairs(seq1, seq2, merge_list, accumulator=0):
""" PART D: make_pairs() takes in two sequences (seq1, seq2) and returns a list of tuples. Each tuple contains a value from seq1 whose index matches the value in seq2. The "accumulator" argument is set to a default value of zero. On each recursive call the accumulator is incremented by 1. merge_list is passed in as an argument because the list is mutable. """
# Get the smaller sequence
smaller = seq1 if len(seq1) <= len(seq2) else seq2
if accumulator == len(smaller): # base case
return merge_list
else: # recursive case
# append values from seq1 whose index matches the index in seq2.
merge_list.append((seq1[accumulator], seq2[accumulator]))
accumulator += 1
return make_pairs(seq1, seq2, merge_list, accumulator)
def main():
# Testing functionality of Part A: draw_leaf()
turtle.left(90)
turtle.speed(10)
draw_leaf_straight(120, 6)
turtle.done()
# Unit tests for Part B: strB()
testif.testif(strB(100, base=2) == '1100100',
'Test 1: 100 -> base 2', 'PASSED: 100 converted to base 2 = 1100100', 'FAILED')
testif.testif(strB(123456789, base=26) == 'AA44A1',
'Test 2: 123456789 -> base 26', 'PASSED: 123456789 converted to base 26 = AA44A1', 'FAILED')
testif.testif(strB(1234, base=10) == '1234',
'Test 3: 1234 -> base 10', 'PASSED: 1234 converted to base 10 = 1234', 'FAILED')
testif.testif(strB(100, base=16) == '64',
'Test 4: 100 -> base 16', 'PASSED: 100 converted to base 16 = 64', 'FAILED')
# Unit tests for Part C: Cnk_m()
testif.testif(Cnk_m(10, 3) == 120, 'Test 1: n-choose-k : n=10, k=3',
"PASSED: 10-choose-3 is 120", 'FAILED')
testif.testif(Cnk_m(39, 12) == 3910797436, 'Test 2: n-choose-k : n=39, k=12',
"PASSED: 39-choose-12 is 3910797436", 'FAILED')
testif.testif(Cnk_m(20, 4) == 4845, 'Test 3: n-choose-k : n=20, k=4',
"PASSED: 20-choose-4 is 4845", 'FAILED')
testif.testif(Cnk_m(15, 8) == 6435, 'Test 4: n-choose-k : n=15, k=8',
"PASSED: 15-choose-8 is 6435", 'FAILED')
# Unit tests for Part D: make_pairs()
testif.testif(make_pairs([1, 2, 3], [4, 5, 6], []) == [(1, 4), (2, 5), (3, 6)],
'Test 1: make_pairs : seq1=[1,2,3], seq2=[4,5,6]', "PASSED: make_pairs([1,2,3], [4,5,6]) = [(1,4),(2,5),(3,6)]", 'FAILED')
testif.testif(make_pairs([2, 5, 8, 11], [4, 5, 6], []) == [(2, 4), (5, 5), (8, 6)],
'Test 2: make_pairs : seq1=[2,5,8,11], seq2=[4,5,6]', "PASSED: make_pairs([1,2,3], [4,5,6]) == [(1,4),(2,5),(3,6)]", 'FAILED')
testif.testif(make_pairs([], [99, 17, 4], []) == [
], 'Test 3: make_pairs : seq1=[], seq2=[99,17,4]', "PASSED: make_pairs([], [99,17,4]) == []", 'FAILED')
testif.testif(make_pairs([0, 3, 4, 9, 4, 5], [7, 8, 33], []) == [(0, 7), (3, 8), (4, 33)],
'Test 4: make_pairs: seq1 = [0,3,4,9,4,5] seq2 = [7,8,33]', "PASSED: make_pairs([1,2,3], [4,5,6]) == [(1,4),(2,5),(3,6)]", 'FAILED')
testif.testif(make_pairs([10, 11, 20], [2, 4, 6, 0], []) == [(10, 2), (11, 4), (20, 6)],
'Test 5: make_pairs : seq1=[10,11,20], seq2=[2,4,6,0]', "PASSED: make_pairs([10,11,20], [2,4,6,0]) == [(10,2),(11,4),(20,6)", 'FAILED')
main()
| 50.969697 | 410 | 0.609394 |
import sys
import testif
import turtle
def draw_leaf_straight(length, level):
if level <= 0:
return
else:
turtle.forward(length)
draw_leaf_straight(0.6*length, level-1)
turtle.left(45)
draw_leaf_straight(0.6*length, level-1)
turtle.right(90)
draw_leaf_straight(0.6*length, level-1)
turtle.left(45)
turtle.backward(length)
return
def strB(n, base=10):
class BadBase(Exception):
pass
try:
if base < 2 or base > 26:
raise BadBase
except BadBase:
print('Base must be between 2 and 26. Exiting...')
sys.exit()
else:
alpha_num_str = '0123456789ABCDEFGHIJKLMNOPQ'
if n < base:
return alpha_num_str[n]
else:
return strB(n // base, base) + alpha_num_str[n % base]
def Cnk_m(n, k):
cache = dict()
def memoization_step(n, k):
if (n, k) not in cache:
if k == 0 or k == n:
return 1
else:
cache[(n, k)] = memoization_step(
n-1, k-1) + memoization_step(n-1, k)
return cache[(n, k)]
return memoization_step(n, k)
def make_pairs(seq1, seq2, merge_list, accumulator=0):
smaller = seq1 if len(seq1) <= len(seq2) else seq2
if accumulator == len(smaller):
return merge_list
else:
merge_list.append((seq1[accumulator], seq2[accumulator]))
accumulator += 1
return make_pairs(seq1, seq2, merge_list, accumulator)
def main():
turtle.left(90)
turtle.speed(10)
draw_leaf_straight(120, 6)
turtle.done()
testif.testif(strB(100, base=2) == '1100100',
'Test 1: 100 -> base 2', 'PASSED: 100 converted to base 2 = 1100100', 'FAILED')
testif.testif(strB(123456789, base=26) == 'AA44A1',
'Test 2: 123456789 -> base 26', 'PASSED: 123456789 converted to base 26 = AA44A1', 'FAILED')
testif.testif(strB(1234, base=10) == '1234',
'Test 3: 1234 -> base 10', 'PASSED: 1234 converted to base 10 = 1234', 'FAILED')
testif.testif(strB(100, base=16) == '64',
'Test 4: 100 -> base 16', 'PASSED: 100 converted to base 16 = 64', 'FAILED')
testif.testif(Cnk_m(10, 3) == 120, 'Test 1: n-choose-k : n=10, k=3',
"PASSED: 10-choose-3 is 120", 'FAILED')
testif.testif(Cnk_m(39, 12) == 3910797436, 'Test 2: n-choose-k : n=39, k=12',
"PASSED: 39-choose-12 is 3910797436", 'FAILED')
testif.testif(Cnk_m(20, 4) == 4845, 'Test 3: n-choose-k : n=20, k=4',
"PASSED: 20-choose-4 is 4845", 'FAILED')
testif.testif(Cnk_m(15, 8) == 6435, 'Test 4: n-choose-k : n=15, k=8',
"PASSED: 15-choose-8 is 6435", 'FAILED')
testif.testif(make_pairs([1, 2, 3], [4, 5, 6], []) == [(1, 4), (2, 5), (3, 6)],
'Test 1: make_pairs : seq1=[1,2,3], seq2=[4,5,6]', "PASSED: make_pairs([1,2,3], [4,5,6]) = [(1,4),(2,5),(3,6)]", 'FAILED')
testif.testif(make_pairs([2, 5, 8, 11], [4, 5, 6], []) == [(2, 4), (5, 5), (8, 6)],
'Test 2: make_pairs : seq1=[2,5,8,11], seq2=[4,5,6]', "PASSED: make_pairs([1,2,3], [4,5,6]) == [(1,4),(2,5),(3,6)]", 'FAILED')
testif.testif(make_pairs([], [99, 17, 4], []) == [
], 'Test 3: make_pairs : seq1=[], seq2=[99,17,4]', "PASSED: make_pairs([], [99,17,4]) == []", 'FAILED')
testif.testif(make_pairs([0, 3, 4, 9, 4, 5], [7, 8, 33], []) == [(0, 7), (3, 8), (4, 33)],
'Test 4: make_pairs: seq1 = [0,3,4,9,4,5] seq2 = [7,8,33]', "PASSED: make_pairs([1,2,3], [4,5,6]) == [(1,4),(2,5),(3,6)]", 'FAILED')
testif.testif(make_pairs([10, 11, 20], [2, 4, 6, 0], []) == [(10, 2), (11, 4), (20, 6)],
'Test 5: make_pairs : seq1=[10,11,20], seq2=[2,4,6,0]', "PASSED: make_pairs([10,11,20], [2,4,6,0]) == [(10,2),(11,4),(20,6)", 'FAILED')
main()
| true | true |
f7283b2b432fc5e9e9ae4ff0badca1280da5923a | 9,648 | py | Python | tests/instantiate/__init__.py | sara-nl/hydra | 8fd0d23d71cf528528ca5eda26e0c1f0c1e973d7 | [
"MIT"
] | null | null | null | tests/instantiate/__init__.py | sara-nl/hydra | 8fd0d23d71cf528528ca5eda26e0c1f0c1e973d7 | [
"MIT"
] | null | null | null | tests/instantiate/__init__.py | sara-nl/hydra | 8fd0d23d71cf528528ca5eda26e0c1f0c1e973d7 | [
"MIT"
] | null | null | null | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import collections
import collections.abc
from dataclasses import dataclass
from functools import partial
from typing import Any, Dict, List, NoReturn, Optional, Tuple
from omegaconf import MISSING, DictConfig, ListConfig
from hydra.types import TargetConf
from tests.instantiate.module_shadowed_by_function import a_function
module_shadowed_by_function = a_function
def _convert_type(obj: Any) -> Any:
if isinstance(obj, DictConfig):
obj = dict(obj)
elif isinstance(obj, ListConfig):
obj = list(obj)
return obj
def partial_equal(obj1: Any, obj2: Any) -> bool:
if obj1 == obj2:
return True
obj1, obj2 = _convert_type(obj1), _convert_type(obj2)
if type(obj1) != type(obj2):
return False
if isinstance(obj1, dict):
if len(obj1) != len(obj2):
return False
for i in obj1.keys():
if not partial_equal(obj1[i], obj2[i]):
return False
return True
if isinstance(obj1, list):
if len(obj1) != len(obj2):
return False
return all([partial_equal(obj1[i], obj2[i]) for i in range(len(obj1))])
if not (isinstance(obj1, partial) and isinstance(obj2, partial)):
return False
return all(
[
partial_equal(getattr(obj1, attr), getattr(obj2, attr))
for attr in ["func", "args", "keywords"]
]
)
class ArgsClass:
def __init__(self, *args: Any, **kwargs: Any) -> None:
assert isinstance(args, tuple)
assert isinstance(kwargs, dict)
self.args = args
self.kwargs = kwargs
def __repr__(self) -> str:
return f"self.args={self.args},self.kwarg={self.kwargs}"
def __eq__(self, other: Any) -> Any:
if isinstance(other, ArgsClass):
return self.args == other.args and self.kwargs == other.kwargs
else:
return NotImplemented
class OuterClass:
def __init__(self) -> None:
pass
@staticmethod
def method() -> str:
return "OuterClass.method return"
class Nested:
def __init__(self) -> None:
pass
@staticmethod
def method() -> str:
return "OuterClass.Nested.method return"
def add_values(a: int, b: int) -> int:
return a + b
def module_function(x: int) -> int:
return x
def module_function2() -> str:
return "fn return"
class ExceptionTakingNoArgument(Exception):
def __init__(self) -> None:
"""Init method taking only one argument (self)"""
super().__init__("Err message")
def raise_exception_taking_no_argument() -> NoReturn:
raise ExceptionTakingNoArgument()
@dataclass
class AClass:
a: Any
b: Any
c: Any
d: Any = "default_value"
@staticmethod
def static_method(z: int) -> int:
return z
@dataclass
class BClass:
a: Any
b: Any
c: Any = "c"
d: Any = "d"
@dataclass
class KeywordsInParamsClass:
target: Any
partial: Any
@dataclass
class UntypedPassthroughConf:
_target_: str = "tests.instantiate.UntypedPassthroughClass"
a: Any = MISSING
@dataclass
class UntypedPassthroughClass:
a: Any
# Type not legal in a config
class IllegalType:
def __eq__(self, other: Any) -> Any:
return isinstance(other, IllegalType)
@dataclass
class AnotherClass:
x: int
class ASubclass(AnotherClass):
@classmethod
def class_method(cls, y: int) -> Any:
return cls(y + 1)
@staticmethod
def static_method(z: int) -> int:
return z
class Parameters:
def __init__(self, params: List[float]):
self.params = params
def __eq__(self, other: Any) -> Any:
if isinstance(other, Parameters):
return self.params == other.params
return False
def __deepcopy__(self, memodict: Any = {}) -> Any:
raise NotImplementedError("Pytorch parameters does not support deepcopy")
@dataclass
class Adam:
params: Parameters
lr: float = 0.001
betas: Tuple[float, ...] = (0.9, 0.999)
eps: float = 1e-08
weight_decay: int = 0
amsgrad: bool = False
@dataclass
class NestingClass:
a: ASubclass = ASubclass(10)
nesting = NestingClass()
class ClassWithMissingModule:
def __init__(self) -> None:
import some_missing_module # type: ignore # noqa: F401
self.x = 1
@dataclass
class AdamConf:
_target_: str = "tests.instantiate.Adam"
lr: float = 0.001
betas: Tuple[float, ...] = (0.9, 0.999)
eps: float = 1e-08
weight_decay: int = 0
amsgrad: bool = False
@dataclass
class BadAdamConf(TargetConf):
# Missing str annotation
_target_ = "tests.instantiate.Adam"
@dataclass
class User:
name: str = MISSING
age: int = MISSING
@dataclass
class UserGroup:
name: str = MISSING
users: List[User] = MISSING
# RECURSIVE
# Classes
class Transform:
...
class CenterCrop(Transform):
def __init__(self, size: int):
self.size = size
def __eq__(self, other: Any) -> Any:
if isinstance(other, type(self)):
return self.size == other.size
else:
return False
class Rotation(Transform):
def __init__(self, degrees: int):
self.degrees = degrees
def __eq__(self, other: Any) -> Any:
if isinstance(other, type(self)):
return self.degrees == other.degrees
else:
return False
class Compose:
transforms: List[Transform]
def __init__(self, transforms: List[Transform]):
self.transforms = transforms
def __eq__(self, other: Any) -> Any:
return partial_equal(self.transforms, other.transforms)
class Tree:
value: Any
# annotated any because of non recursive instantiation tests
left: Any = None
right: Any = None
def __init__(self, value: Any, left: Any = None, right: Any = None) -> None:
self.value = value
self.left = left
self.right = right
def __eq__(self, other: Any) -> Any:
if isinstance(other, type(self)):
return (
partial_equal(self.value, other.value)
and partial_equal(self.left, other.left)
and partial_equal(self.right, other.right)
)
else:
return False
def __repr__(self) -> str:
return f"Tree(value={self.value}, left={self.left}, right={self.right})"
class Mapping:
dictionary: Optional[Dict[str, "Mapping"]] = None
value: Any = None
def __init__(
self, value: Any = None, dictionary: Optional[Dict[str, "Mapping"]] = None
) -> None:
self.dictionary = dictionary
self.value = value
def __eq__(self, other: Any) -> Any:
if isinstance(other, type(self)):
return partial_equal(self.dictionary, other.dictionary) and partial_equal(
self.value, other.value
)
else:
return False
def __repr__(self) -> str:
return f"dictionary={self.dictionary}"
# Configs
@dataclass
class TransformConf:
...
@dataclass
class CenterCropConf(TransformConf):
_target_: str = "tests.instantiate.CenterCrop"
_partial_: bool = False
size: int = MISSING
@dataclass
class RotationConf(TransformConf):
_target_: str = "tests.instantiate.Rotation"
degrees: int = MISSING
@dataclass
class ComposeConf:
_target_: str = "tests.instantiate.Compose"
_partial_: bool = False
transforms: List[TransformConf] = MISSING
@dataclass
class TreeConf:
_target_: str = "tests.instantiate.Tree"
_partial_: bool = False
left: Optional["TreeConf"] = None
right: Optional["TreeConf"] = None
value: Any = MISSING
@dataclass
class MappingConf:
_target_: str = "tests.instantiate.Mapping"
_partial_: bool = False
dictionary: Optional[Dict[str, "MappingConf"]] = None
def __init__(
self,
dictionary: Optional[Dict[str, "MappingConf"]] = None,
_partial_: bool = False,
):
self.dictionary = dictionary
self._partial_ = _partial_
@dataclass
class SimpleDataClass:
a: Any = None
b: Any = None
class SimpleClass:
a: Any = None
b: Any = None
def __init__(self, a: Any, b: Any) -> None:
self.a = a
self.b = b
def __eq__(self, other: Any) -> Any:
if isinstance(other, SimpleClass):
return self.a == other.a and self.b == other.b
return False
@dataclass
class SimpleClassPrimitiveConf:
_target_: str = "tests.instantiate.SimpleClass"
_convert_: str = "partial"
a: Any = None
b: Any = None
@dataclass
class SimpleClassNonPrimitiveConf:
_target_: str = "tests.instantiate.SimpleClass"
_convert_: str = "none"
a: Any = None
b: Any = None
@dataclass
class SimpleClassDefaultPrimitiveConf:
_target_: str = "tests.instantiate.SimpleClass"
a: Any = None
b: Any = None
@dataclass
class NestedConf:
_target_: str = "tests.instantiate.SimpleClass"
a: Any = User(name="a", age=1)
b: Any = User(name="b", age=2)
def recisinstance(got: Any, expected: Any) -> bool:
"""Compare got with expected type, recursively on dict and list."""
if not isinstance(got, type(expected)):
return False
if isinstance(expected, collections.abc.Mapping):
return all(recisinstance(got[key], expected[key]) for key in expected)
elif isinstance(expected, collections.abc.Iterable):
return all(recisinstance(got[idx], exp) for idx, exp in enumerate(expected))
return True
| 22.542056 | 86 | 0.630493 |
import collections
import collections.abc
from dataclasses import dataclass
from functools import partial
from typing import Any, Dict, List, NoReturn, Optional, Tuple
from omegaconf import MISSING, DictConfig, ListConfig
from hydra.types import TargetConf
from tests.instantiate.module_shadowed_by_function import a_function
module_shadowed_by_function = a_function
def _convert_type(obj: Any) -> Any:
if isinstance(obj, DictConfig):
obj = dict(obj)
elif isinstance(obj, ListConfig):
obj = list(obj)
return obj
def partial_equal(obj1: Any, obj2: Any) -> bool:
if obj1 == obj2:
return True
obj1, obj2 = _convert_type(obj1), _convert_type(obj2)
if type(obj1) != type(obj2):
return False
if isinstance(obj1, dict):
if len(obj1) != len(obj2):
return False
for i in obj1.keys():
if not partial_equal(obj1[i], obj2[i]):
return False
return True
if isinstance(obj1, list):
if len(obj1) != len(obj2):
return False
return all([partial_equal(obj1[i], obj2[i]) for i in range(len(obj1))])
if not (isinstance(obj1, partial) and isinstance(obj2, partial)):
return False
return all(
[
partial_equal(getattr(obj1, attr), getattr(obj2, attr))
for attr in ["func", "args", "keywords"]
]
)
class ArgsClass:
def __init__(self, *args: Any, **kwargs: Any) -> None:
assert isinstance(args, tuple)
assert isinstance(kwargs, dict)
self.args = args
self.kwargs = kwargs
def __repr__(self) -> str:
return f"self.args={self.args},self.kwarg={self.kwargs}"
def __eq__(self, other: Any) -> Any:
if isinstance(other, ArgsClass):
return self.args == other.args and self.kwargs == other.kwargs
else:
return NotImplemented
class OuterClass:
def __init__(self) -> None:
pass
@staticmethod
def method() -> str:
return "OuterClass.method return"
class Nested:
def __init__(self) -> None:
pass
@staticmethod
def method() -> str:
return "OuterClass.Nested.method return"
def add_values(a: int, b: int) -> int:
return a + b
def module_function(x: int) -> int:
return x
def module_function2() -> str:
return "fn return"
class ExceptionTakingNoArgument(Exception):
def __init__(self) -> None:
super().__init__("Err message")
def raise_exception_taking_no_argument() -> NoReturn:
raise ExceptionTakingNoArgument()
@dataclass
class AClass:
a: Any
b: Any
c: Any
d: Any = "default_value"
@staticmethod
def static_method(z: int) -> int:
return z
@dataclass
class BClass:
a: Any
b: Any
c: Any = "c"
d: Any = "d"
@dataclass
class KeywordsInParamsClass:
target: Any
partial: Any
@dataclass
class UntypedPassthroughConf:
_target_: str = "tests.instantiate.UntypedPassthroughClass"
a: Any = MISSING
@dataclass
class UntypedPassthroughClass:
a: Any
class IllegalType:
def __eq__(self, other: Any) -> Any:
return isinstance(other, IllegalType)
@dataclass
class AnotherClass:
x: int
class ASubclass(AnotherClass):
@classmethod
def class_method(cls, y: int) -> Any:
return cls(y + 1)
@staticmethod
def static_method(z: int) -> int:
return z
class Parameters:
def __init__(self, params: List[float]):
self.params = params
def __eq__(self, other: Any) -> Any:
if isinstance(other, Parameters):
return self.params == other.params
return False
def __deepcopy__(self, memodict: Any = {}) -> Any:
raise NotImplementedError("Pytorch parameters does not support deepcopy")
@dataclass
class Adam:
params: Parameters
lr: float = 0.001
betas: Tuple[float, ...] = (0.9, 0.999)
eps: float = 1e-08
weight_decay: int = 0
amsgrad: bool = False
@dataclass
class NestingClass:
a: ASubclass = ASubclass(10)
nesting = NestingClass()
class ClassWithMissingModule:
def __init__(self) -> None:
import some_missing_module lf.x = 1
@dataclass
class AdamConf:
_target_: str = "tests.instantiate.Adam"
lr: float = 0.001
betas: Tuple[float, ...] = (0.9, 0.999)
eps: float = 1e-08
weight_decay: int = 0
amsgrad: bool = False
@dataclass
class BadAdamConf(TargetConf):
_target_ = "tests.instantiate.Adam"
@dataclass
class User:
name: str = MISSING
age: int = MISSING
@dataclass
class UserGroup:
name: str = MISSING
users: List[User] = MISSING
class Transform:
...
class CenterCrop(Transform):
def __init__(self, size: int):
self.size = size
def __eq__(self, other: Any) -> Any:
if isinstance(other, type(self)):
return self.size == other.size
else:
return False
class Rotation(Transform):
def __init__(self, degrees: int):
self.degrees = degrees
def __eq__(self, other: Any) -> Any:
if isinstance(other, type(self)):
return self.degrees == other.degrees
else:
return False
class Compose:
transforms: List[Transform]
def __init__(self, transforms: List[Transform]):
self.transforms = transforms
def __eq__(self, other: Any) -> Any:
return partial_equal(self.transforms, other.transforms)
class Tree:
value: Any
left: Any = None
right: Any = None
def __init__(self, value: Any, left: Any = None, right: Any = None) -> None:
self.value = value
self.left = left
self.right = right
def __eq__(self, other: Any) -> Any:
if isinstance(other, type(self)):
return (
partial_equal(self.value, other.value)
and partial_equal(self.left, other.left)
and partial_equal(self.right, other.right)
)
else:
return False
def __repr__(self) -> str:
return f"Tree(value={self.value}, left={self.left}, right={self.right})"
class Mapping:
dictionary: Optional[Dict[str, "Mapping"]] = None
value: Any = None
def __init__(
self, value: Any = None, dictionary: Optional[Dict[str, "Mapping"]] = None
) -> None:
self.dictionary = dictionary
self.value = value
def __eq__(self, other: Any) -> Any:
if isinstance(other, type(self)):
return partial_equal(self.dictionary, other.dictionary) and partial_equal(
self.value, other.value
)
else:
return False
def __repr__(self) -> str:
return f"dictionary={self.dictionary}"
@dataclass
class TransformConf:
...
@dataclass
class CenterCropConf(TransformConf):
_target_: str = "tests.instantiate.CenterCrop"
_partial_: bool = False
size: int = MISSING
@dataclass
class RotationConf(TransformConf):
_target_: str = "tests.instantiate.Rotation"
degrees: int = MISSING
@dataclass
class ComposeConf:
_target_: str = "tests.instantiate.Compose"
_partial_: bool = False
transforms: List[TransformConf] = MISSING
@dataclass
class TreeConf:
_target_: str = "tests.instantiate.Tree"
_partial_: bool = False
left: Optional["TreeConf"] = None
right: Optional["TreeConf"] = None
value: Any = MISSING
@dataclass
class MappingConf:
_target_: str = "tests.instantiate.Mapping"
_partial_: bool = False
dictionary: Optional[Dict[str, "MappingConf"]] = None
def __init__(
self,
dictionary: Optional[Dict[str, "MappingConf"]] = None,
_partial_: bool = False,
):
self.dictionary = dictionary
self._partial_ = _partial_
@dataclass
class SimpleDataClass:
a: Any = None
b: Any = None
class SimpleClass:
a: Any = None
b: Any = None
def __init__(self, a: Any, b: Any) -> None:
self.a = a
self.b = b
def __eq__(self, other: Any) -> Any:
if isinstance(other, SimpleClass):
return self.a == other.a and self.b == other.b
return False
@dataclass
class SimpleClassPrimitiveConf:
_target_: str = "tests.instantiate.SimpleClass"
_convert_: str = "partial"
a: Any = None
b: Any = None
@dataclass
class SimpleClassNonPrimitiveConf:
_target_: str = "tests.instantiate.SimpleClass"
_convert_: str = "none"
a: Any = None
b: Any = None
@dataclass
class SimpleClassDefaultPrimitiveConf:
_target_: str = "tests.instantiate.SimpleClass"
a: Any = None
b: Any = None
@dataclass
class NestedConf:
_target_: str = "tests.instantiate.SimpleClass"
a: Any = User(name="a", age=1)
b: Any = User(name="b", age=2)
def recisinstance(got: Any, expected: Any) -> bool:
if not isinstance(got, type(expected)):
return False
if isinstance(expected, collections.abc.Mapping):
return all(recisinstance(got[key], expected[key]) for key in expected)
elif isinstance(expected, collections.abc.Iterable):
return all(recisinstance(got[idx], exp) for idx, exp in enumerate(expected))
return True
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.