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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1c2ba2dff95300359a057ddf7d9c01dfcbbf9944 | 950 | py | Python | util/test/tests/D3D12/D3D12_Untyped_Backbuffer_Descriptor.py | PLohrmannAMD/renderdoc | ea16d31aa340581f5e505e0c734a8468e5d3d47f | [
"MIT"
] | 20 | 2020-10-03T18:03:34.000Z | 2021-01-15T02:53:29.000Z | util/test/tests/D3D12/D3D12_Untyped_Backbuffer_Descriptor.py | PLohrmannAMD/renderdoc | ea16d31aa340581f5e505e0c734a8468e5d3d47f | [
"MIT"
] | null | null | null | util/test/tests/D3D12/D3D12_Untyped_Backbuffer_Descriptor.py | PLohrmannAMD/renderdoc | ea16d31aa340581f5e505e0c734a8468e5d3d47f | [
"MIT"
] | 5 | 2020-10-03T18:13:37.000Z | 2021-01-15T02:53:35.000Z | import renderdoc as rd
import rdtest
class D3D12_Untyped_Backbuffer_Descriptor(rdtest.TestCase):
demos_test_name = 'D3D12_Untyped_Backbuffer_Descriptor'
def check_capture(self):
# find the first draw
draw = self.find_draw("Draw")
self.controller.SetFrameEvent(draw.eventId, False)
pipe: rd.PipeState = self.controller.GetPipelineState()
self.check_pixel_value(pipe.GetOutputTargets()[0].resourceId, 0.25, 0.5, [1.0, 1.0, 1.0, 1.0])
rdtest.log.success("Picked value for first draw is as expected")
# find the second draw
draw = self.find_draw("Draw", draw.eventId+1)
self.controller.SetFrameEvent(draw.eventId, False)
pipe: rd.PipeState = self.controller.GetPipelineState()
self.check_pixel_value(pipe.GetOutputTargets()[0].resourceId, 0.75, 0.5, [1.0, 1.0, 1.0, 1.0])
rdtest.log.success("Picked value for second draw is as expected")
| 31.666667 | 102 | 0.685263 | import renderdoc as rd
import rdtest
class D3D12_Untyped_Backbuffer_Descriptor(rdtest.TestCase):
demos_test_name = 'D3D12_Untyped_Backbuffer_Descriptor'
def check_capture(self):
draw = self.find_draw("Draw")
self.controller.SetFrameEvent(draw.eventId, False)
pipe: rd.PipeState = self.controller.GetPipelineState()
self.check_pixel_value(pipe.GetOutputTargets()[0].resourceId, 0.25, 0.5, [1.0, 1.0, 1.0, 1.0])
rdtest.log.success("Picked value for first draw is as expected")
draw = self.find_draw("Draw", draw.eventId+1)
self.controller.SetFrameEvent(draw.eventId, False)
pipe: rd.PipeState = self.controller.GetPipelineState()
self.check_pixel_value(pipe.GetOutputTargets()[0].resourceId, 0.75, 0.5, [1.0, 1.0, 1.0, 1.0])
rdtest.log.success("Picked value for second draw is as expected")
| true | true |
1c2ba388d555fe306d4df71a24831fe113ccf007 | 408 | py | Python | powerstation_graphs/migrations/0002_auto_20180824_1503.py | Red-Teapot/bbyaworld.com-django | 6eb8febd2cfa304a062ac924240cbdf060499cfc | [
"MIT"
] | 1 | 2020-01-11T18:04:15.000Z | 2020-01-11T18:04:15.000Z | powerstation_graphs/migrations/0002_auto_20180824_1503.py | Red-Teapot/bbyaworld.com-django | 6eb8febd2cfa304a062ac924240cbdf060499cfc | [
"MIT"
] | 2 | 2018-08-24T08:53:27.000Z | 2019-07-05T16:08:28.000Z | powerstation_graphs/migrations/0002_auto_20180824_1503.py | Red-Teapot/bbyaworld.com-django | 6eb8febd2cfa304a062ac924240cbdf060499cfc | [
"MIT"
] | 1 | 2018-11-22T16:19:52.000Z | 2018-11-22T16:19:52.000Z | # Generated by Django 2.1 on 2018-08-24 12:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('powerstation_graphs', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='measurement',
name='type',
field=models.SmallIntegerField(db_index=True, default=-1),
),
]
| 21.473684 | 70 | 0.612745 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('powerstation_graphs', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='measurement',
name='type',
field=models.SmallIntegerField(db_index=True, default=-1),
),
]
| true | true |
1c2ba3bd05dbfd3aed897c5862514a20dd316d5f | 3,201 | py | Python | ui/nngenanticipate.py | LouisRoss/spiking-core | dd880a9d812b587172fd760813dc80c7ddc963d3 | [
"MIT"
] | null | null | null | ui/nngenanticipate.py | LouisRoss/spiking-core | dd880a9d812b587172fd760813dc80c7ddc963d3 | [
"MIT"
] | null | null | null | ui/nngenanticipate.py | LouisRoss/spiking-core | dd880a9d812b587172fd760813dc80c7ddc963d3 | [
"MIT"
] | null | null | null | #!/usr/bin/python3
import json
import collections
from pathlib import Path
from mes import configuration
# TODO make this configurable or in some other repository.
signal_delay_time = 7
class AnticipateGenerator:
configuration = None
signal_to_inject = {}
width = 50
height = 25
def __init__(self, configuration):
''' Confirm all required configuration elements are present in the
configuration, and make sure the path to the record location exists.
'''
self.configuration = configuration
if 'Model' in self.configuration.configuration:
if 'Dimensions' in self.configuration.configuration['Model']:
dimensions = self.configuration.configuration['Model']['Dimensions']
self.width = dimensions[0]
self.height = dimensions[1]
if 'PostProcessing' not in self.configuration.configuration:
print('Required "PostProcessing" section not in configuration file')
return
if 'RecordLocation' not in self.configuration.configuration['PostProcessing']:
print('Required subkey "RecordLocation" not in configuration file "PostProcessing" section')
return
if 'SensorInputFile' not in self.configuration.configuration['PostProcessing']:
print('Required subkey "SensorInputFile" not in configuration file "PostProcessing" section')
return
record_path = self.configuration.configuration['PostProcessing']['RecordLocation']
Path(record_path).mkdir(parents=True, exist_ok=True)
def get_sensor_input_file_path(self):
''' Develop the full file path to the sensor input file,
placing it in the project path of the record path.
'''
project_path = self.configuration.find_projectpath()
file_name = self.configuration.configuration['PostProcessing']['SensorInputFile']
return project_path + file_name
def generate_anticipate(self, configuration):
global signal_delay_time
self.signal_to_inject = {}
i1_index = configuration.get_neuron_index("I1")
i2_index = configuration.get_neuron_index("I2")
for i in range(0, 8000, 200):
self.insert_signal(i, i1_index)
self.insert_signal(i+(signal_delay_time*4)+2, i2_index)
self.signal_to_inject = collections.OrderedDict(sorted(self.signal_to_inject.items()))
def insert_signal(self, tick, index):
if tick not in self.signal_to_inject:
self.signal_to_inject[tick] = []
self.signal_to_inject[tick].append(index)
def write_streaming_input_file(self):
file_path = self.get_sensor_input_file_path()
print('writing streaming input file to ' + file_path)
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(self.signal_to_inject, f, ensure_ascii=False, indent=4)
def execute(configuration):
generator = AnticipateGenerator(configuration)
generator.generate_anticipate(configuration)
generator.write_streaming_input_file()
def run():
conf = configuration()
execute(conf)
if __name__ == "__main__":
run()
| 36.375 | 105 | 0.683536 |
import json
import collections
from pathlib import Path
from mes import configuration
signal_delay_time = 7
class AnticipateGenerator:
configuration = None
signal_to_inject = {}
width = 50
height = 25
def __init__(self, configuration):
self.configuration = configuration
if 'Model' in self.configuration.configuration:
if 'Dimensions' in self.configuration.configuration['Model']:
dimensions = self.configuration.configuration['Model']['Dimensions']
self.width = dimensions[0]
self.height = dimensions[1]
if 'PostProcessing' not in self.configuration.configuration:
print('Required "PostProcessing" section not in configuration file')
return
if 'RecordLocation' not in self.configuration.configuration['PostProcessing']:
print('Required subkey "RecordLocation" not in configuration file "PostProcessing" section')
return
if 'SensorInputFile' not in self.configuration.configuration['PostProcessing']:
print('Required subkey "SensorInputFile" not in configuration file "PostProcessing" section')
return
record_path = self.configuration.configuration['PostProcessing']['RecordLocation']
Path(record_path).mkdir(parents=True, exist_ok=True)
def get_sensor_input_file_path(self):
project_path = self.configuration.find_projectpath()
file_name = self.configuration.configuration['PostProcessing']['SensorInputFile']
return project_path + file_name
def generate_anticipate(self, configuration):
global signal_delay_time
self.signal_to_inject = {}
i1_index = configuration.get_neuron_index("I1")
i2_index = configuration.get_neuron_index("I2")
for i in range(0, 8000, 200):
self.insert_signal(i, i1_index)
self.insert_signal(i+(signal_delay_time*4)+2, i2_index)
self.signal_to_inject = collections.OrderedDict(sorted(self.signal_to_inject.items()))
def insert_signal(self, tick, index):
if tick not in self.signal_to_inject:
self.signal_to_inject[tick] = []
self.signal_to_inject[tick].append(index)
def write_streaming_input_file(self):
file_path = self.get_sensor_input_file_path()
print('writing streaming input file to ' + file_path)
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(self.signal_to_inject, f, ensure_ascii=False, indent=4)
def execute(configuration):
generator = AnticipateGenerator(configuration)
generator.generate_anticipate(configuration)
generator.write_streaming_input_file()
def run():
conf = configuration()
execute(conf)
if __name__ == "__main__":
run()
| true | true |
1c2ba46835cc8ddf66ba698d54ba354765070ef4 | 764 | py | Python | src/encoded/audit/dataset.py | KCL-ORG/encoded | 5a1904e948bfd652e8a8d52c6717d7fc0b56b681 | [
"MIT"
] | 4 | 2018-01-04T22:31:08.000Z | 2021-07-15T17:39:16.000Z | src/encoded/audit/dataset.py | KCL-ORG/encoded | 5a1904e948bfd652e8a8d52c6717d7fc0b56b681 | [
"MIT"
] | 7 | 2017-10-31T23:47:47.000Z | 2022-01-10T00:12:42.000Z | src/encoded/audit/dataset.py | KCL-ORG/encoded | 5a1904e948bfd652e8a8d52c6717d7fc0b56b681 | [
"MIT"
] | 10 | 2017-09-14T00:57:07.000Z | 2021-07-27T23:41:14.000Z | from snovault import (
AuditFailure,
audit_checker,
)
@audit_checker('Dataset', frame=['original_files'])
def audit_experiment_released_with_unreleased_files(value, system):
if value['status'] != 'released':
return
if 'original_files' not in value:
return
for f in value['original_files']:
if f['status'] not in ['released', 'deleted',
'revoked', 'replaced',
'archived']:
detail = 'Released dataset {} '.format(value['@id']) + \
'contains file {} '.format(f['@id']) + \
'that has not been released.'
yield AuditFailure('mismatched file status', detail, level='INTERNAL_ACTION')
return
| 34.727273 | 89 | 0.556283 | from snovault import (
AuditFailure,
audit_checker,
)
@audit_checker('Dataset', frame=['original_files'])
def audit_experiment_released_with_unreleased_files(value, system):
if value['status'] != 'released':
return
if 'original_files' not in value:
return
for f in value['original_files']:
if f['status'] not in ['released', 'deleted',
'revoked', 'replaced',
'archived']:
detail = 'Released dataset {} '.format(value['@id']) + \
'contains file {} '.format(f['@id']) + \
'that has not been released.'
yield AuditFailure('mismatched file status', detail, level='INTERNAL_ACTION')
return
| true | true |
1c2ba55d545befabf68d77a7f3dd47035c7b8290 | 8,271 | py | Python | bartpy/diagnostics/features.py | danielremo/bartpy | f299d8be9378daf75ee1a6b1527de5cb0f0ced89 | [
"MIT"
] | null | null | null | bartpy/diagnostics/features.py | danielremo/bartpy | f299d8be9378daf75ee1a6b1527de5cb0f0ced89 | [
"MIT"
] | null | null | null | bartpy/diagnostics/features.py | danielremo/bartpy | f299d8be9378daf75ee1a6b1527de5cb0f0ced89 | [
"MIT"
] | null | null | null | from collections import Counter
from typing import List, Mapping, Union, Optional
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
from bartpy.runner import run_models
from bartpy.sklearnmodel import SklearnModel
ImportanceMap = Mapping[int, float]
ImportanceDistributionMap = Mapping[int, List[float]]
def feature_split_proportions(model: SklearnModel, columns: Optional[List[int]]=None) -> Mapping[int, float]:
split_variables = []
for sample in model.model_samples:
for tree in sample.trees:
for node in tree.nodes:
splitting_var = node.split.splitting_variable
split_variables.append(splitting_var)
counter = Counter(split_variables)
if columns is None:
columns = sorted(list([x for x in counter.keys() if x is not None]))
proportions = {}
for column in columns:
if column in counter.keys():
proportions[column] = counter[column] / len(split_variables)
else:
proportions[column] = 0.0
return proportions
def plot_feature_split_proportions(model: SklearnModel, ax=None):
if ax is None:
fig, ax = plt.subplots(1, 1)
proportions = feature_split_proportions(model)
y_pos = np.arange(len(proportions))
name, count = list(proportions.keys()), list(proportions.values())
props = pd.DataFrame({"name": name, "counts": count}).sort_values("name", ascending=True)
plt.barh(y_pos, props.counts, align='center', alpha=0.5)
plt.yticks(y_pos, props.name)
plt.xlabel('Proportion of all splits')
plt.ylabel('Feature')
plt.title('Proportion of Splits Made on Each Variable')
return ax
def null_feature_split_proportions_distribution(model: SklearnModel,
X: Union[pd.DataFrame, np.ndarray],
y: np.ndarray,
n_permutations: int=10) -> Mapping[int, List[float]]:
"""
Calculate a null distribution of proportion of splits on each variable in X
Works by randomly permuting y to remove any true dependence of y on X and calculating feature importance
Parameters
----------
model: SklearnModel
Model specification to work with
X: np.ndarray
Covariate matrix
y: np.ndarray
Target data
n_permutations: int
How many permutations to run
The higher the number of permutations, the more accurate the null distribution, but the longer it will take to run
Returns
-------
Mapping[int, List[float]]
A list of inclusion proportions for each variable in X
"""
inclusion_dict = {x: [] for x in range(X.shape[1])}
y_s = [np.random.permutation(y) for _ in range(n_permutations)]
X_s = [X for _ in y_s]
fit_models = run_models(model, X_s, y_s)
for model in fit_models:
splits_run = feature_split_proportions(model, list(range(X.shape[1])))
for key, value in splits_run.items():
inclusion_dict[key].append(value)
return inclusion_dict
def plot_null_feature_importance_distributions(null_distributions: Mapping[int, List[float]], ax=None) -> None:
if ax is None:
fig, ax = plt.subplots(1, 1)
df = pd.DataFrame(null_distributions)
df = pd.DataFrame(df.unstack()).reset_index().drop("level_1", axis=1)
df.columns = ["variable", "p"]
sns.boxplot(x="variable", y="p", data=df, ax=ax)
ax.set_title("Null Feature Importance Distribution")
return ax
def local_thresholds(null_distributions: ImportanceDistributionMap, percentile: float) -> Mapping[int, float]:
"""
Calculate the required proportion of splits to be selected by variable
Creates a null distribution for each variable based on the % of splits including that variable in each of the permuted models
Each variable has its own threshold that is independent of the other variables
Note - this is significantly less stringent than the global threshold
Parameters
----------
null_distributions: ImportanceDistributionMap
A mapping from variable to distribution of split inclusion proportions under the null
percentile: float
The percentile of the null distribution to use as a cutoff.
The closer to 1.0, the more stringent the threshold
Returns
-------
Mapping[int, float]
A lookup from column to % inclusion threshold
"""
return {feature: np.percentile(null_distributions[feature], percentile) for feature in null_distributions}
def global_thresholds(null_distributions: ImportanceDistributionMap, percentile: float) -> Mapping[int, float]:
"""
Calculate the required proportion of splits to be selected by variable
Creates a distribution of the _highest_ inclusion percentage of any variable in each of the permuted models
Threshold is set as a percentile of this distribution
All variables have the same threshold
Note that this is significantly more stringent than the local threshold
Parameters
----------
null_distributions: ImportanceDistributionMap
A mapping from variable to distribution of split inclusion proportions under the null
percentile: float
The percentile of the null distribution to use as a cutoff.
The closer to 1.0, the more stringent the threshold
Returns
-------
Mapping[int, float]
A lookup from column to % inclusion threshold
"""
q_s = []
df = pd.DataFrame(null_distributions)
for row in df.iter_rows():
q_s.append(np.max(row))
threshold = np.percentile(q_s, percentile)
return {feature: threshold for feature in null_distributions}
def kept_features(feature_proportions: Mapping[int, float], thresholds: Mapping[int, float]) -> List[int]:
"""
Extract the features to keep
Parameters
----------
feature_proportions: Mapping[int, float]
Lookup from variable to % of splits in the model that use that variable
thresholds: Mapping[int, float]
Lookup from variable to required % of splits in the model to be kept
Returns
-------
List[int]
Variable selected for inclusion in the final model
"""
return [x[0] for x in zip(sorted(feature_proportions.keys()), is_kept(feature_proportions, thresholds)) if x[1]]
def is_kept(feature_proportions: Mapping[int, float], thresholds: Mapping[int, float]) -> List[bool]:
"""
Determine whether each variable should be kept after selection
Parameters
----------
feature_proportions: Mapping[int, float]
Lookup from variable to % of splits in the model that use that variable
thresholds: Mapping[int, float]
Lookup from variable to required % of splits in the model to be kept
Returns
-------
List[bool]
An array of length equal to the width of the covariate matrix
True if the variable should be kept, False otherwise
"""
print(sorted(list(feature_proportions.keys())))
return [feature_proportions[feature] > thresholds[feature] for feature in sorted(list(feature_proportions.keys()))]
def partition_into_passed_and_failed_features(feature_proportions, thresholds):
kept = kept_features(feature_proportions, thresholds)
passed_features = {x[0]: x[1] for x in feature_proportions.items() if x[0] in kept}
failed_features = {x[0]: x[1] for x in feature_proportions.items() if x[0] not in kept}
return passed_features, failed_features
def plot_feature_proportions_against_thresholds(feature_proportions, thresholds, ax=None):
if ax is None:
fig, ax = plt.subplots(1, 1)
passed_features, failed_features = partition_into_passed_and_failed_features(feature_proportions, thresholds)
ax.bar(thresholds.keys(), [x * 100 for x in thresholds.values()], width=0.01, color="black", alpha=0.5)
ax.scatter(passed_features.keys(), [x * 100 for x in passed_features.values()], c="g")
ax.scatter(failed_features.keys(), [x * 100 for x in failed_features.values()], c="r")
ax.set_title("Feature Importance Compared to Threshold")
ax.set_xlabel("Feature")
ax.set_ylabel("% Splits")
return ax
| 37.089686 | 129 | 0.688309 | from collections import Counter
from typing import List, Mapping, Union, Optional
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
from bartpy.runner import run_models
from bartpy.sklearnmodel import SklearnModel
ImportanceMap = Mapping[int, float]
ImportanceDistributionMap = Mapping[int, List[float]]
def feature_split_proportions(model: SklearnModel, columns: Optional[List[int]]=None) -> Mapping[int, float]:
split_variables = []
for sample in model.model_samples:
for tree in sample.trees:
for node in tree.nodes:
splitting_var = node.split.splitting_variable
split_variables.append(splitting_var)
counter = Counter(split_variables)
if columns is None:
columns = sorted(list([x for x in counter.keys() if x is not None]))
proportions = {}
for column in columns:
if column in counter.keys():
proportions[column] = counter[column] / len(split_variables)
else:
proportions[column] = 0.0
return proportions
def plot_feature_split_proportions(model: SklearnModel, ax=None):
if ax is None:
fig, ax = plt.subplots(1, 1)
proportions = feature_split_proportions(model)
y_pos = np.arange(len(proportions))
name, count = list(proportions.keys()), list(proportions.values())
props = pd.DataFrame({"name": name, "counts": count}).sort_values("name", ascending=True)
plt.barh(y_pos, props.counts, align='center', alpha=0.5)
plt.yticks(y_pos, props.name)
plt.xlabel('Proportion of all splits')
plt.ylabel('Feature')
plt.title('Proportion of Splits Made on Each Variable')
return ax
def null_feature_split_proportions_distribution(model: SklearnModel,
X: Union[pd.DataFrame, np.ndarray],
y: np.ndarray,
n_permutations: int=10) -> Mapping[int, List[float]]:
inclusion_dict = {x: [] for x in range(X.shape[1])}
y_s = [np.random.permutation(y) for _ in range(n_permutations)]
X_s = [X for _ in y_s]
fit_models = run_models(model, X_s, y_s)
for model in fit_models:
splits_run = feature_split_proportions(model, list(range(X.shape[1])))
for key, value in splits_run.items():
inclusion_dict[key].append(value)
return inclusion_dict
def plot_null_feature_importance_distributions(null_distributions: Mapping[int, List[float]], ax=None) -> None:
if ax is None:
fig, ax = plt.subplots(1, 1)
df = pd.DataFrame(null_distributions)
df = pd.DataFrame(df.unstack()).reset_index().drop("level_1", axis=1)
df.columns = ["variable", "p"]
sns.boxplot(x="variable", y="p", data=df, ax=ax)
ax.set_title("Null Feature Importance Distribution")
return ax
def local_thresholds(null_distributions: ImportanceDistributionMap, percentile: float) -> Mapping[int, float]:
return {feature: np.percentile(null_distributions[feature], percentile) for feature in null_distributions}
def global_thresholds(null_distributions: ImportanceDistributionMap, percentile: float) -> Mapping[int, float]:
q_s = []
df = pd.DataFrame(null_distributions)
for row in df.iter_rows():
q_s.append(np.max(row))
threshold = np.percentile(q_s, percentile)
return {feature: threshold for feature in null_distributions}
def kept_features(feature_proportions: Mapping[int, float], thresholds: Mapping[int, float]) -> List[int]:
return [x[0] for x in zip(sorted(feature_proportions.keys()), is_kept(feature_proportions, thresholds)) if x[1]]
def is_kept(feature_proportions: Mapping[int, float], thresholds: Mapping[int, float]) -> List[bool]:
print(sorted(list(feature_proportions.keys())))
return [feature_proportions[feature] > thresholds[feature] for feature in sorted(list(feature_proportions.keys()))]
def partition_into_passed_and_failed_features(feature_proportions, thresholds):
kept = kept_features(feature_proportions, thresholds)
passed_features = {x[0]: x[1] for x in feature_proportions.items() if x[0] in kept}
failed_features = {x[0]: x[1] for x in feature_proportions.items() if x[0] not in kept}
return passed_features, failed_features
def plot_feature_proportions_against_thresholds(feature_proportions, thresholds, ax=None):
if ax is None:
fig, ax = plt.subplots(1, 1)
passed_features, failed_features = partition_into_passed_and_failed_features(feature_proportions, thresholds)
ax.bar(thresholds.keys(), [x * 100 for x in thresholds.values()], width=0.01, color="black", alpha=0.5)
ax.scatter(passed_features.keys(), [x * 100 for x in passed_features.values()], c="g")
ax.scatter(failed_features.keys(), [x * 100 for x in failed_features.values()], c="r")
ax.set_title("Feature Importance Compared to Threshold")
ax.set_xlabel("Feature")
ax.set_ylabel("% Splits")
return ax
| true | true |
1c2ba633bcabd078485558dc038d761e962f1c89 | 19,289 | py | Python | api/app/resources/bookings/walkin/walkin.py | krishnan-aot/queue-management | 0710ef268b288feeb7776882e618f974d4b84f6f | [
"Apache-2.0"
] | 30 | 2018-09-19T03:30:51.000Z | 2022-03-07T02:57:05.000Z | api/app/resources/bookings/walkin/walkin.py | WalterMoar/queue-management | c7698501dafebe3b5dc6bb602b5ab57ca56572a7 | [
"Apache-2.0"
] | 159 | 2018-09-17T23:45:58.000Z | 2022-03-30T17:35:05.000Z | api/app/resources/bookings/walkin/walkin.py | tyu-avo/queue-management | 0710ef268b288feeb7776882e618f974d4b84f6f | [
"Apache-2.0"
] | 52 | 2018-05-18T18:30:06.000Z | 2021-08-25T12:00:29.000Z | '''Copyright 2018 Province of British Columbia
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 pytz
from pprint import pprint
from datetime import datetime, timedelta
from flask import request, g
from flask_restx import Resource
from qsystem import api, api_call_with_retry, db, socketio, my_print, application
from app.models.theq import Citizen, CSR, Counter, Office, CitizenState, ServiceReq
from app.models.bookings import Appointment
from marshmallow import ValidationError
from app.schemas.theq import CitizenSchema, OfficeSchema
from app.schemas.bookings import AppointmentSchema
from sqlalchemy import exc
from app.utilities.snowplow import SnowPlow
from app.utilities.auth_util import Role, has_any_role
from app.auth.auth import jwt
from app.utilities.email import send_email, get_walkin_reminder_email_contents
from app.utilities.sms import send_walkin_reminder_sms
@api.route("/citizen/all-walkin/<string:id>/", methods=["GET"])
class WalkinDetail(Resource):
citizen_schema = CitizenSchema()
citizens_schema = CitizenSchema(many=True)
appointment_schema = AppointmentSchema(many=True)
office_schema = OfficeSchema()
def get(self, id):
try:
citizen = Citizen.query.filter_by(walkin_unique_id=id).join(CitizenState)\
.filter(CitizenState.cs_state_name == 'Active')\
.order_by(Citizen.citizen_id.desc()).first()
if citizen:
res_list = []
# office time zone
local_timezone = self.get_my_office_timezone(citizen = citizen)
# am i on hold
am_on_hold = self.am_i_on_hold(citizen)
show_estimate = application.config.get('SHOW_ESTIMATE_TIME_WALKIN', False)
# result= all citizen in q
result = self.get_all_citizen_in_q(citizen = citizen)
# process result
booked_check_app, walkin_app = self.process_all_citizen_in_q(result, citizen, am_on_hold, local_timezone)
# get all app from agenda panel
result_in_book = self.get_all_app_from_agenda_panel(citizen=citizen)
# processing agenda panel appointmnets:
booked_not_checkin = self.process_agenda_panel(result_in_book, local_timezone)
# sorting-maintaing the order group
# serving people dont want see
res_list = tuple(booked_check_app + booked_not_checkin + walkin_app)
return {'citizen': res_list, 'show_estimate': show_estimate}, 200
return {}
except exc.SQLAlchemyError as e:
print(e)
return {'message': 'API is down'}, 500
def get_my_office_timezone(self, citizen=False, office=False):
office_id = False
local_timezone = False
if citizen:
office_id = citizen.office_id
if office:
office_id = office.office_id
if office_id:
my_office = Office.query.filter_by(office_id=office_id).first()
my_office_data = self.office_schema.dump(my_office)
if my_office_data:
my_time_zone = my_office_data['timezone']['timezone_name']
local_timezone = pytz.timezone(my_time_zone)
return local_timezone
def am_i_on_hold(self, citizen):
my_result = self.citizen_schema.dump(citizen)
am_on_hold = False
citizen_service_reqs = my_result.get('service_reqs', [])
for j in citizen_service_reqs:
my_served_period = sorted(j['periods'], key= lambda x:x['period_id'], reverse=True)[0]
if my_served_period:
if (my_served_period['ps']['ps_name'] == 'On hold'):
am_on_hold = True
return am_on_hold
def get_all_citizen_in_q(self, citizen=False, office=False):
office_id = False
result = []
if citizen:
office_id = citizen.office_id
if office:
office_id = office.office_id
if office_id:
all_citizen_in_q = Citizen.query.filter_by(office_id=office_id) \
.join(CitizenState)\
.filter(CitizenState.cs_state_name == 'Active')\
.order_by(Citizen.priority) \
.join(Citizen.service_reqs).all()
result = self.citizens_schema.dump(all_citizen_in_q)
return result
def process_all_citizen_in_q(self, result, citizen, am_on_hold, local_timezone):
booked_check_app = []
walkin_app = []
for each in result:
data_dict = {}
if bool(each.get('service_reqs', False)):
for i in each['service_reqs']:
served_period = sorted(i['periods'], key= lambda x:x['period_id'], reverse=True)[0]
if served_period:
if (not (served_period['time_end']) and (served_period['ps']['ps_name'] in ('Waiting', 'Invited'))):
not_booked_flag = False
data_dict = {}
data_dict['ticket_number'] = each.get('ticket_number', '')
data_dict['walkin_unique_id'] = each.get('walkin_unique_id', '')
if (each.get('citizen_comments', '')):
if '|||' in each['citizen_comments']:
data_dict['flag'] = 'booked_app'
booked_check_app.append(data_dict)
data_dict = {}
break
else:
not_booked_flag = True
else:
not_booked_flag = True
if not_booked_flag and each.get('cs', False):
if each['cs'].get('cs_state_name', '') == 'Active':
each_time_obj = datetime.strptime(each['start_time'], '%Y-%m-%dT%H:%M:%SZ')
# start
local_datetime_start = each_time_obj.replace(tzinfo=pytz.utc).astimezone(local_timezone)
#end
local_datetime_end = citizen.start_time.replace(tzinfo=pytz.utc).astimezone(local_timezone)
if am_on_hold:
data_dict['flag'] = 'walkin_app'
walkin_app.append(data_dict)
data_dict = {}
break
else:
if local_datetime_start <= local_datetime_end:
data_dict['flag'] = 'walkin_app'
walkin_app.append(data_dict)
data_dict = {}
break
return booked_check_app, walkin_app
def get_all_app_from_agenda_panel(self, citizen=False, office=False):
office_id = False
result_in_book = []
if citizen:
office_id = citizen.office_id
if office:
office_id = office.office_id
if office_id:
past_hour = datetime.utcnow() - timedelta(minutes=15)
future_hour = datetime.utcnow() + timedelta(minutes=15)
local_past = pytz.utc.localize(past_hour)
local_future = pytz.utc.localize(future_hour)
# getting agenda panel app
appointments = Appointment.query.filter_by(office_id=office_id)\
.filter(Appointment.start_time <= local_future)\
.filter(Appointment.start_time >= local_past)\
.filter(Appointment.checked_in_time == None)\
.order_by(Appointment.start_time)\
.all()
result_in_book = self.appointment_schema.dump(appointments)
return result_in_book
def process_agenda_panel(self, result_in_book, local_timezone):
booked_not_checkin = []
for app in result_in_book:
if not (app.get('is_draft', True)) and (app.get('blackout_flag', 'N') == 'N') and not (app.get('stat_flag', True)):
data_dict = {}
data_dict['flag'] = 'agenda_panel'
data_dict['start_time'] = app.get('start_time', '')
if data_dict['start_time'] and local_timezone:
if (len(data_dict['start_time']) >= 3):
if ':' in data_dict['start_time'][-3]:
data_dict['start_time'] = '{}{}'.format(data_dict['start_time'][:-3], data_dict['start_time'][-2:])
utc_datetime = datetime.strptime(data_dict['start_time'], '%Y-%m-%dT%H:%M:%S%z')
local_datetime = utc_datetime.replace(tzinfo=pytz.utc)
local_datetime = local_datetime.astimezone(local_timezone)
data_dict['start_time'] = local_datetime.strftime("%m/%d/%Y, %H:%M:%S")
booked_not_checkin.append(data_dict)
return booked_not_checkin
@api.route("/send-reminder/line-walkin/", methods=["POST"])
class SendLineReminderWalkin(Resource):
citizen_schema = CitizenSchema()
office_schema = OfficeSchema()
walkinObj = WalkinDetail()
@jwt.has_one_of_roles([Role.internal_user.value])
@api_call_with_retry
def post(self):
try:
result = []
json_data = request.get_json()
previous_citizen_id = json_data.get('previous_citizen_id', False)
if previous_citizen_id:
previous_citizen = Citizen.query.filter_by(citizen_id=previous_citizen_id).first()
# get nth line
nth_line = self.get_nth_line(previous_citizen)
# get all in Q + Agenda panel
res_list = []
# result= all citizen in q
result = self.walkinObj.get_all_citizen_in_q(citizen = previous_citizen)
# process result
# am_on_true= means get all citizen in Q
booked_check_app, walkin_app = self.process_all_citizen_in_q(result)
# sorting-maintaing the order group
res_list = tuple(booked_check_app + walkin_app)
# get the nth object in checkedin and walkin list
# bool checks for both False and 0
nth_app = False
if nth_line:
if len(res_list) >= int(nth_line) and (int(nth_line) > 0):
nth_app = res_list[int(nth_line)-1]
if nth_app['citizen_id']:
citizen = Citizen.query.filter_by(citizen_id=nth_app['citizen_id']).first()
if (not (citizen.automatic_reminder_flag) or (citizen.automatic_reminder_flag == 0)):
office_obj = Office.find_by_id(citizen.office_id)
if citizen.notification_phone:
citizen = self.send_sms_reminder(citizen, office_obj)
citizen.automatic_reminder_flag = 1
if citizen.notification_email:
citizen = self.send_email_reminder(citizen, office_obj)
citizen.automatic_reminder_flag = 1
db.session.add(citizen)
db.session.commit()
result = self.citizen_schema.dump(previous_citizen)
return {'citizen': result,
'errors': self.citizen_schema.validate(previous_citizen)}, 200
except ValidationError as err:
return {'message': err.messages}, 422
def get_nth_line(self, citizen):
my_office = Office.query.filter_by(office_id=citizen.office_id).first()
my_office_data = self.office_schema.dump(my_office)
nth_line = False
if my_office_data:
nth_line = my_office_data.get('automatic_reminder_at', False)
return nth_line
def process_all_citizen_in_q(self, result):
booked_check_app = []
walkin_app = []
for each in result:
data_dict = {}
if bool(each.get('service_reqs', False)):
for i in each['service_reqs']:
served_period = sorted(i['periods'], key= lambda x:x['period_id'], reverse=True)[0]
if served_period:
if (not (served_period['time_end']) and (served_period['ps']['ps_name'] in ('Waiting', 'Invited'))):
not_booked_flag = False
data_dict = {}
data_dict['citizen_id'] = each.get('citizen_id', False)
data_dict['service_name'] = i['service']['parent']['service_name']
if (each.get('citizen_comments', '')):
if '|||' in each['citizen_comments']:
data_dict['flag'] = 'booked_app'
booked_check_app.append(data_dict)
data_dict = {}
break
else:
not_booked_flag = True
else:
not_booked_flag = True
if not_booked_flag and each.get('cs', False):
if each['cs'].get('cs_state_name', '') == 'Active':
data_dict['flag'] = 'walkin_app'
data_dict['created_at'] = each.get('created_at', '')
walkin_app.append(data_dict)
data_dict = {}
break
return booked_check_app, walkin_app
def send_sms_reminder(self, citizen, office_obj):
if (citizen.notification_phone):
sms_sent = False
validate_check = True
# code/function call to send sms notification,
if citizen.reminder_flag:
if (citizen.reminder_flag == 2):
validate_check = False
if validate_check:
sms_sent = send_walkin_reminder_sms(citizen, office_obj, request.headers['Authorization'].replace('Bearer ', ''))
if (sms_sent):
flag_value = 1
if citizen.reminder_flag == 1:
flag_value = 2
citizen.reminder_flag = flag_value
citizen.notification_sent_time = datetime.utcnow()
return citizen
def send_email_reminder(self, citizen, office_obj):
if (citizen.notification_email):
# code/function call to send first email notification,
email_sent = False
validate_check = True
if citizen.reminder_flag:
if (citizen.reminder_flag == 2):
validate_check = False
if validate_check:
email_sent = get_walkin_reminder_email_contents(citizen, office_obj)
if email_sent:
send_email(request.headers['Authorization'].replace('Bearer ', ''), *email_sent)
flag_value = 1
if citizen.reminder_flag == 1:
flag_value = 2
citizen.reminder_flag = flag_value
citizen.notification_sent_time = datetime.utcnow()
return citizen
@api.route("/smardboard/Q-details/waiting/<string:id>", methods=["GET"])
class SmartBoradQDetails(Resource):
citizen_schema = CitizenSchema()
office_schema = OfficeSchema()
walkinObj = WalkinDetail()
processObj = SendLineReminderWalkin()
@api_call_with_retry
def get(self, id):
try:
# get office details from url id
office = Office.query.filter_by(office_number=id).first()
if not office:
return {'message': 'office_number could not be found.'}, 400
res_list = []
if (office.currently_waiting == 1):
# result= all citizen in q
result = self.walkinObj.get_all_citizen_in_q(office = office)
# process result
booked_check_app, walkin_app = self.processObj.process_all_citizen_in_q(result)
# sorting-maintaing the order group
res_list = tuple(booked_check_app + walkin_app)
return {'citizen_in_q': res_list}, 200
return {}
except exc.SQLAlchemyError as e:
print(e)
return {'message': 'API is down'}, 500
@api.route("/smardboard/Q-details/upcoming/<string:id>", methods=["GET"])
class SmartBoradQDetails(Resource):
citizen_schema = CitizenSchema()
office_schema = OfficeSchema()
walkinObj = WalkinDetail()
processObj = SendLineReminderWalkin()
@api_call_with_retry
def get(self, id):
try:
# get office details from url id
office = Office.query.filter_by(office_number=id).first()
if not office:
return {'message': 'office_number could not be found.'}, 400
booked_not_checkin = []
if (office.currently_waiting == 1):
# office time zone
local_timezone = self.walkinObj.get_my_office_timezone(office = office)
# get all app from agenda panel
result_in_book = self.walkinObj.get_all_app_from_agenda_panel(office = office)
# processing agenda panel appointmnets:
booked_not_checkin = self.walkinObj.process_agenda_panel(result_in_book, local_timezone)
return {'booked_not_checkin': booked_not_checkin}, 200
return {}
except exc.SQLAlchemyError as e:
print(e)
return {'message': 'API is down'}, 500 | 48.709596 | 163 | 0.54373 | import pytz
from pprint import pprint
from datetime import datetime, timedelta
from flask import request, g
from flask_restx import Resource
from qsystem import api, api_call_with_retry, db, socketio, my_print, application
from app.models.theq import Citizen, CSR, Counter, Office, CitizenState, ServiceReq
from app.models.bookings import Appointment
from marshmallow import ValidationError
from app.schemas.theq import CitizenSchema, OfficeSchema
from app.schemas.bookings import AppointmentSchema
from sqlalchemy import exc
from app.utilities.snowplow import SnowPlow
from app.utilities.auth_util import Role, has_any_role
from app.auth.auth import jwt
from app.utilities.email import send_email, get_walkin_reminder_email_contents
from app.utilities.sms import send_walkin_reminder_sms
@api.route("/citizen/all-walkin/<string:id>/", methods=["GET"])
class WalkinDetail(Resource):
citizen_schema = CitizenSchema()
citizens_schema = CitizenSchema(many=True)
appointment_schema = AppointmentSchema(many=True)
office_schema = OfficeSchema()
def get(self, id):
try:
citizen = Citizen.query.filter_by(walkin_unique_id=id).join(CitizenState)\
.filter(CitizenState.cs_state_name == 'Active')\
.order_by(Citizen.citizen_id.desc()).first()
if citizen:
res_list = []
local_timezone = self.get_my_office_timezone(citizen = citizen)
am_on_hold = self.am_i_on_hold(citizen)
show_estimate = application.config.get('SHOW_ESTIMATE_TIME_WALKIN', False)
result = self.get_all_citizen_in_q(citizen = citizen)
booked_check_app, walkin_app = self.process_all_citizen_in_q(result, citizen, am_on_hold, local_timezone)
result_in_book = self.get_all_app_from_agenda_panel(citizen=citizen)
booked_not_checkin = self.process_agenda_panel(result_in_book, local_timezone)
res_list = tuple(booked_check_app + booked_not_checkin + walkin_app)
return {'citizen': res_list, 'show_estimate': show_estimate}, 200
return {}
except exc.SQLAlchemyError as e:
print(e)
return {'message': 'API is down'}, 500
def get_my_office_timezone(self, citizen=False, office=False):
office_id = False
local_timezone = False
if citizen:
office_id = citizen.office_id
if office:
office_id = office.office_id
if office_id:
my_office = Office.query.filter_by(office_id=office_id).first()
my_office_data = self.office_schema.dump(my_office)
if my_office_data:
my_time_zone = my_office_data['timezone']['timezone_name']
local_timezone = pytz.timezone(my_time_zone)
return local_timezone
def am_i_on_hold(self, citizen):
my_result = self.citizen_schema.dump(citizen)
am_on_hold = False
citizen_service_reqs = my_result.get('service_reqs', [])
for j in citizen_service_reqs:
my_served_period = sorted(j['periods'], key= lambda x:x['period_id'], reverse=True)[0]
if my_served_period:
if (my_served_period['ps']['ps_name'] == 'On hold'):
am_on_hold = True
return am_on_hold
def get_all_citizen_in_q(self, citizen=False, office=False):
office_id = False
result = []
if citizen:
office_id = citizen.office_id
if office:
office_id = office.office_id
if office_id:
all_citizen_in_q = Citizen.query.filter_by(office_id=office_id) \
.join(CitizenState)\
.filter(CitizenState.cs_state_name == 'Active')\
.order_by(Citizen.priority) \
.join(Citizen.service_reqs).all()
result = self.citizens_schema.dump(all_citizen_in_q)
return result
def process_all_citizen_in_q(self, result, citizen, am_on_hold, local_timezone):
booked_check_app = []
walkin_app = []
for each in result:
data_dict = {}
if bool(each.get('service_reqs', False)):
for i in each['service_reqs']:
served_period = sorted(i['periods'], key= lambda x:x['period_id'], reverse=True)[0]
if served_period:
if (not (served_period['time_end']) and (served_period['ps']['ps_name'] in ('Waiting', 'Invited'))):
not_booked_flag = False
data_dict = {}
data_dict['ticket_number'] = each.get('ticket_number', '')
data_dict['walkin_unique_id'] = each.get('walkin_unique_id', '')
if (each.get('citizen_comments', '')):
if '|||' in each['citizen_comments']:
data_dict['flag'] = 'booked_app'
booked_check_app.append(data_dict)
data_dict = {}
break
else:
not_booked_flag = True
else:
not_booked_flag = True
if not_booked_flag and each.get('cs', False):
if each['cs'].get('cs_state_name', '') == 'Active':
each_time_obj = datetime.strptime(each['start_time'], '%Y-%m-%dT%H:%M:%SZ')
local_datetime_start = each_time_obj.replace(tzinfo=pytz.utc).astimezone(local_timezone)
local_datetime_end = citizen.start_time.replace(tzinfo=pytz.utc).astimezone(local_timezone)
if am_on_hold:
data_dict['flag'] = 'walkin_app'
walkin_app.append(data_dict)
data_dict = {}
break
else:
if local_datetime_start <= local_datetime_end:
data_dict['flag'] = 'walkin_app'
walkin_app.append(data_dict)
data_dict = {}
break
return booked_check_app, walkin_app
def get_all_app_from_agenda_panel(self, citizen=False, office=False):
office_id = False
result_in_book = []
if citizen:
office_id = citizen.office_id
if office:
office_id = office.office_id
if office_id:
past_hour = datetime.utcnow() - timedelta(minutes=15)
future_hour = datetime.utcnow() + timedelta(minutes=15)
local_past = pytz.utc.localize(past_hour)
local_future = pytz.utc.localize(future_hour)
appointments = Appointment.query.filter_by(office_id=office_id)\
.filter(Appointment.start_time <= local_future)\
.filter(Appointment.start_time >= local_past)\
.filter(Appointment.checked_in_time == None)\
.order_by(Appointment.start_time)\
.all()
result_in_book = self.appointment_schema.dump(appointments)
return result_in_book
def process_agenda_panel(self, result_in_book, local_timezone):
booked_not_checkin = []
for app in result_in_book:
if not (app.get('is_draft', True)) and (app.get('blackout_flag', 'N') == 'N') and not (app.get('stat_flag', True)):
data_dict = {}
data_dict['flag'] = 'agenda_panel'
data_dict['start_time'] = app.get('start_time', '')
if data_dict['start_time'] and local_timezone:
if (len(data_dict['start_time']) >= 3):
if ':' in data_dict['start_time'][-3]:
data_dict['start_time'] = '{}{}'.format(data_dict['start_time'][:-3], data_dict['start_time'][-2:])
utc_datetime = datetime.strptime(data_dict['start_time'], '%Y-%m-%dT%H:%M:%S%z')
local_datetime = utc_datetime.replace(tzinfo=pytz.utc)
local_datetime = local_datetime.astimezone(local_timezone)
data_dict['start_time'] = local_datetime.strftime("%m/%d/%Y, %H:%M:%S")
booked_not_checkin.append(data_dict)
return booked_not_checkin
@api.route("/send-reminder/line-walkin/", methods=["POST"])
class SendLineReminderWalkin(Resource):
citizen_schema = CitizenSchema()
office_schema = OfficeSchema()
walkinObj = WalkinDetail()
@jwt.has_one_of_roles([Role.internal_user.value])
@api_call_with_retry
def post(self):
try:
result = []
json_data = request.get_json()
previous_citizen_id = json_data.get('previous_citizen_id', False)
if previous_citizen_id:
previous_citizen = Citizen.query.filter_by(citizen_id=previous_citizen_id).first()
nth_line = self.get_nth_line(previous_citizen)
res_list = []
result = self.walkinObj.get_all_citizen_in_q(citizen = previous_citizen)
booked_check_app, walkin_app = self.process_all_citizen_in_q(result)
res_list = tuple(booked_check_app + walkin_app)
nth_app = False
if nth_line:
if len(res_list) >= int(nth_line) and (int(nth_line) > 0):
nth_app = res_list[int(nth_line)-1]
if nth_app['citizen_id']:
citizen = Citizen.query.filter_by(citizen_id=nth_app['citizen_id']).first()
if (not (citizen.automatic_reminder_flag) or (citizen.automatic_reminder_flag == 0)):
office_obj = Office.find_by_id(citizen.office_id)
if citizen.notification_phone:
citizen = self.send_sms_reminder(citizen, office_obj)
citizen.automatic_reminder_flag = 1
if citizen.notification_email:
citizen = self.send_email_reminder(citizen, office_obj)
citizen.automatic_reminder_flag = 1
db.session.add(citizen)
db.session.commit()
result = self.citizen_schema.dump(previous_citizen)
return {'citizen': result,
'errors': self.citizen_schema.validate(previous_citizen)}, 200
except ValidationError as err:
return {'message': err.messages}, 422
def get_nth_line(self, citizen):
my_office = Office.query.filter_by(office_id=citizen.office_id).first()
my_office_data = self.office_schema.dump(my_office)
nth_line = False
if my_office_data:
nth_line = my_office_data.get('automatic_reminder_at', False)
return nth_line
def process_all_citizen_in_q(self, result):
booked_check_app = []
walkin_app = []
for each in result:
data_dict = {}
if bool(each.get('service_reqs', False)):
for i in each['service_reqs']:
served_period = sorted(i['periods'], key= lambda x:x['period_id'], reverse=True)[0]
if served_period:
if (not (served_period['time_end']) and (served_period['ps']['ps_name'] in ('Waiting', 'Invited'))):
not_booked_flag = False
data_dict = {}
data_dict['citizen_id'] = each.get('citizen_id', False)
data_dict['service_name'] = i['service']['parent']['service_name']
if (each.get('citizen_comments', '')):
if '|||' in each['citizen_comments']:
data_dict['flag'] = 'booked_app'
booked_check_app.append(data_dict)
data_dict = {}
break
else:
not_booked_flag = True
else:
not_booked_flag = True
if not_booked_flag and each.get('cs', False):
if each['cs'].get('cs_state_name', '') == 'Active':
data_dict['flag'] = 'walkin_app'
data_dict['created_at'] = each.get('created_at', '')
walkin_app.append(data_dict)
data_dict = {}
break
return booked_check_app, walkin_app
def send_sms_reminder(self, citizen, office_obj):
if (citizen.notification_phone):
sms_sent = False
validate_check = True
if citizen.reminder_flag:
if (citizen.reminder_flag == 2):
validate_check = False
if validate_check:
sms_sent = send_walkin_reminder_sms(citizen, office_obj, request.headers['Authorization'].replace('Bearer ', ''))
if (sms_sent):
flag_value = 1
if citizen.reminder_flag == 1:
flag_value = 2
citizen.reminder_flag = flag_value
citizen.notification_sent_time = datetime.utcnow()
return citizen
def send_email_reminder(self, citizen, office_obj):
if (citizen.notification_email):
email_sent = False
validate_check = True
if citizen.reminder_flag:
if (citizen.reminder_flag == 2):
validate_check = False
if validate_check:
email_sent = get_walkin_reminder_email_contents(citizen, office_obj)
if email_sent:
send_email(request.headers['Authorization'].replace('Bearer ', ''), *email_sent)
flag_value = 1
if citizen.reminder_flag == 1:
flag_value = 2
citizen.reminder_flag = flag_value
citizen.notification_sent_time = datetime.utcnow()
return citizen
@api.route("/smardboard/Q-details/waiting/<string:id>", methods=["GET"])
class SmartBoradQDetails(Resource):
citizen_schema = CitizenSchema()
office_schema = OfficeSchema()
walkinObj = WalkinDetail()
processObj = SendLineReminderWalkin()
@api_call_with_retry
def get(self, id):
try:
office = Office.query.filter_by(office_number=id).first()
if not office:
return {'message': 'office_number could not be found.'}, 400
res_list = []
if (office.currently_waiting == 1):
result = self.walkinObj.get_all_citizen_in_q(office = office)
booked_check_app, walkin_app = self.processObj.process_all_citizen_in_q(result)
res_list = tuple(booked_check_app + walkin_app)
return {'citizen_in_q': res_list}, 200
return {}
except exc.SQLAlchemyError as e:
print(e)
return {'message': 'API is down'}, 500
@api.route("/smardboard/Q-details/upcoming/<string:id>", methods=["GET"])
class SmartBoradQDetails(Resource):
citizen_schema = CitizenSchema()
office_schema = OfficeSchema()
walkinObj = WalkinDetail()
processObj = SendLineReminderWalkin()
@api_call_with_retry
def get(self, id):
try:
office = Office.query.filter_by(office_number=id).first()
if not office:
return {'message': 'office_number could not be found.'}, 400
booked_not_checkin = []
if (office.currently_waiting == 1):
local_timezone = self.walkinObj.get_my_office_timezone(office = office)
result_in_book = self.walkinObj.get_all_app_from_agenda_panel(office = office)
booked_not_checkin = self.walkinObj.process_agenda_panel(result_in_book, local_timezone)
return {'booked_not_checkin': booked_not_checkin}, 200
return {}
except exc.SQLAlchemyError as e:
print(e)
return {'message': 'API is down'}, 500 | true | true |
1c2ba781fe0dee311f64c8ce2ba3a983a60619d4 | 370 | py | Python | stacks/XIAOMATECH/1.0/services/INFLUXDB/package/scripts/service_check.py | tvorogme/dataops | acfa21df42a20768c004c6630a064f4e38e280b2 | [
"Apache-2.0"
] | 3 | 2019-08-13T01:44:16.000Z | 2019-12-10T04:05:56.000Z | stacks/XIAOMATECH/1.0/services/INFLUXDB/package/scripts/service_check.py | tvorogme/dataops | acfa21df42a20768c004c6630a064f4e38e280b2 | [
"Apache-2.0"
] | null | null | null | stacks/XIAOMATECH/1.0/services/INFLUXDB/package/scripts/service_check.py | tvorogme/dataops | acfa21df42a20768c004c6630a064f4e38e280b2 | [
"Apache-2.0"
] | 7 | 2019-05-29T17:35:25.000Z | 2021-12-04T07:55:10.000Z | from resource_management import *
from resource_management.libraries.script import Script
from resource_management.core.resources.system import Execute
class ServiceCheck(Script):
def service_check(self, env):
import params
env.set_params(params)
Execute('service influxdb status')
if __name__ == "__main__":
ServiceCheck().execute()
| 24.666667 | 61 | 0.745946 | from resource_management import *
from resource_management.libraries.script import Script
from resource_management.core.resources.system import Execute
class ServiceCheck(Script):
def service_check(self, env):
import params
env.set_params(params)
Execute('service influxdb status')
if __name__ == "__main__":
ServiceCheck().execute()
| true | true |
1c2ba9fb743c59f44b67814ab32a615a45a43d26 | 824 | py | Python | tests/reducers/test_setting_reducers.py | mlopezantequera/pytorch-metric-learning | 17fe941c5f8ff1177c577d94518bf01a8d035747 | [
"MIT"
] | null | null | null | tests/reducers/test_setting_reducers.py | mlopezantequera/pytorch-metric-learning | 17fe941c5f8ff1177c577d94518bf01a8d035747 | [
"MIT"
] | null | null | null | tests/reducers/test_setting_reducers.py | mlopezantequera/pytorch-metric-learning | 17fe941c5f8ff1177c577d94518bf01a8d035747 | [
"MIT"
] | null | null | null | import unittest
from pytorch_metric_learning.losses import ContrastiveLoss, TripletMarginLoss
from pytorch_metric_learning.reducers import (AvgNonZeroReducer, MeanReducer,
ThresholdReducer)
class TestSettingReducers(unittest.TestCase):
def test_setting_reducers(self):
for loss in [TripletMarginLoss, ContrastiveLoss]:
for reducer in [
ThresholdReducer(low=0),
MeanReducer(),
AvgNonZeroReducer(),
]:
L = loss(reducer=reducer)
if isinstance(L, TripletMarginLoss):
assert type(L.reducer) == type(reducer)
else:
for v in L.reducer.reducers.values():
assert type(v) == type(reducer)
| 37.454545 | 77 | 0.571602 | import unittest
from pytorch_metric_learning.losses import ContrastiveLoss, TripletMarginLoss
from pytorch_metric_learning.reducers import (AvgNonZeroReducer, MeanReducer,
ThresholdReducer)
class TestSettingReducers(unittest.TestCase):
def test_setting_reducers(self):
for loss in [TripletMarginLoss, ContrastiveLoss]:
for reducer in [
ThresholdReducer(low=0),
MeanReducer(),
AvgNonZeroReducer(),
]:
L = loss(reducer=reducer)
if isinstance(L, TripletMarginLoss):
assert type(L.reducer) == type(reducer)
else:
for v in L.reducer.reducers.values():
assert type(v) == type(reducer)
| true | true |
1c2baa35cd37cff6bc63bf7d8ff088a3dc1ef5a1 | 528 | py | Python | DAIN/my_package/SeparableConv/setup.py | mpriessner/VFIN | a027c02cc9e28a4db493358654dc5f1ef7928fe2 | [
"MIT"
] | 8 | 2021-11-03T20:21:35.000Z | 2021-12-06T14:53:13.000Z | DAIN/my_package/SeparableConv/setup.py | mpriessner/VFIN | a027c02cc9e28a4db493358654dc5f1ef7928fe2 | [
"MIT"
] | 3 | 2021-11-17T16:46:48.000Z | 2021-11-18T20:57:49.000Z | DAIN/my_package/SeparableConv/setup.py | mpriessner/VFIN | a027c02cc9e28a4db493358654dc5f1ef7928fe2 | [
"MIT"
] | 2 | 2021-12-03T13:10:11.000Z | 2021-12-20T11:06:25.000Z | import os
import json
from setuptools import setup, find_packages
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
import torch
with open('../../compiler_args.json') as f:
extra_compile_args = json.load(f)
setup(
name='separableconv_cuda',
ext_modules=[
CUDAExtension('separableconv_cuda', [
'separableconv_cuda.cc',
'separableconv_cuda_kernel.cu'
], extra_compile_args=extra_compile_args)
],
cmdclass={
'build_ext': BuildExtension
})
| 25.142857 | 67 | 0.691288 | import os
import json
from setuptools import setup, find_packages
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
import torch
with open('../../compiler_args.json') as f:
extra_compile_args = json.load(f)
setup(
name='separableconv_cuda',
ext_modules=[
CUDAExtension('separableconv_cuda', [
'separableconv_cuda.cc',
'separableconv_cuda_kernel.cu'
], extra_compile_args=extra_compile_args)
],
cmdclass={
'build_ext': BuildExtension
})
| true | true |
1c2bab093580a45c29e395e0ee2a8e16331e5f1d | 7,116 | py | Python | eodag/plugins/crunch/filter_overlap.py | sbrunato/eodag | 70aa45515b7b7c11326419abcf616979e7b6e024 | [
"Apache-2.0"
] | 149 | 2019-12-13T21:12:36.000Z | 2022-03-26T09:56:31.000Z | eodag/plugins/crunch/filter_overlap.py | sbrunato/eodag | 70aa45515b7b7c11326419abcf616979e7b6e024 | [
"Apache-2.0"
] | 200 | 2020-06-18T17:30:58.000Z | 2022-03-30T09:54:59.000Z | eodag/plugins/crunch/filter_overlap.py | sbrunato/eodag | 70aa45515b7b7c11326419abcf616979e7b6e024 | [
"Apache-2.0"
] | 23 | 2019-12-12T14:36:49.000Z | 2022-03-29T07:11:28.000Z | # -*- coding: utf-8 -*-
# Copyright 2021, CS GROUP - France, https://www.csgroup.eu/
#
# This file is part of EODAG project
# https://www.github.com/CS-SI/EODAG
#
# 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 logging
from eodag.plugins.crunch.base import Crunch
from eodag.utils import get_geometry_from_various
try:
from shapely.errors import TopologicalError
except ImportError:
from shapely.geos import TopologicalError
logger = logging.getLogger("eodag.plugins.crunch.filter_overlap")
class FilterOverlap(Crunch):
"""FilterOverlap cruncher
Filter products, retaining only those that are overlapping with the search_extent
:param config: Crunch configuration, may contain :
- `minimum_overlap` : minimal overlap percentage
- `contains` : True if product geometry contains the search area
- `intersects` : True if product geometry intersects the search area
- `within` : True if product geometry is within the search area
These configuration parameters are mutually exclusive.
:type config: dict
"""
def proceed(self, products, **search_params):
"""Execute crunch: Filter products, retaining only those that are overlapping with the search_extent
:param products: A list of products resulting from a search
:type products: list(:class:`~eodag.api.product._product.EOProduct`)
:param search_params: Search criteria that must contain `geometry`
:type search_params: dict
:returns: The filtered products
:rtype: list(:class:`~eodag.api.product._product.EOProduct`)
"""
logger.debug("Start filtering for overlapping products")
filtered = []
add_to_filtered = filtered.append
search_geom = get_geometry_from_various(**search_params)
if not search_geom:
logger.warning(
"geometry not found in cruncher arguments, filtering disabled."
)
return products
minimum_overlap = float(self.config.get("minimum_overlap", "0"))
contains = self.config.get("contains", False)
intersects = self.config.get("intersects", False)
within = self.config.get("within", False)
if contains and (within or intersects) or (within and intersects):
logger.warning(
"contains, intersects and within parameters are mutually exclusive"
)
return products
elif (
minimum_overlap > 0
and minimum_overlap < 100
and (contains or within or intersects)
):
logger.warning(
"minimum_overlap will be ignored because of contains/intersects/within usage"
)
elif not contains and not within and not intersects:
logger.debug("Minimum overlap is: {} %".format(minimum_overlap))
logger.debug("Initial requested extent area: %s", search_geom.area)
if search_geom.area == 0:
logger.debug(
"No product can overlap a requested extent that is not a polygon (i.e with area=0)"
)
else:
for product in products:
logger.debug("Uncovered extent area: %s", search_geom.area)
if product.search_intersection:
intersection = product.search_intersection
product_geometry = product.geometry
else: # Product geometry may be invalid
if not product.geometry.is_valid:
logger.debug(
"Trying our best to deal with invalid geometry on product: %r",
product,
)
product_geometry = product.geometry.buffer(0)
try:
intersection = search_geom.intersection(product_geometry)
except TopologicalError:
logger.debug(
"Product geometry still invalid. Overlap test restricted to containment"
)
if search_geom.contains(product_geometry):
logger.debug(
"Product %r overlaps the search extent. Adding it to filtered results"
)
add_to_filtered(product)
continue
else:
product_geometry = product.geometry
intersection = search_geom.intersection(product_geometry)
if (
(contains and product_geometry.contains(search_geom))
or (within and product_geometry.within(search_geom))
or (intersects and product_geometry.intersects(search_geom))
):
add_to_filtered(product)
continue
elif contains or within or intersects:
continue
ipos = (intersection.area / search_geom.area) * 100
ipop = (intersection.area / product_geometry.area) * 100
logger.debug(
"Intersection of product extent and search extent covers %f percent of the search extent "
"area",
ipos,
)
logger.debug(
"Intersection of product extent and search extent covers %f percent of the product extent "
"area",
ipop,
)
if any(
(
search_geom.contains(product.geometry),
ipos >= minimum_overlap,
ipop >= minimum_overlap,
)
):
logger.debug(
"Product %r overlaps the search extent by the specified constraint. Adding it to "
"filtered results",
product,
)
add_to_filtered(product)
else:
logger.debug(
"Product %r does not overlaps the search extent by the specified constraint. "
"Skipping it",
product,
)
logger.info("Finished filtering products. %s resulting products", len(filtered))
return filtered
| 42.610778 | 111 | 0.56113 |
import logging
from eodag.plugins.crunch.base import Crunch
from eodag.utils import get_geometry_from_various
try:
from shapely.errors import TopologicalError
except ImportError:
from shapely.geos import TopologicalError
logger = logging.getLogger("eodag.plugins.crunch.filter_overlap")
class FilterOverlap(Crunch):
def proceed(self, products, **search_params):
logger.debug("Start filtering for overlapping products")
filtered = []
add_to_filtered = filtered.append
search_geom = get_geometry_from_various(**search_params)
if not search_geom:
logger.warning(
"geometry not found in cruncher arguments, filtering disabled."
)
return products
minimum_overlap = float(self.config.get("minimum_overlap", "0"))
contains = self.config.get("contains", False)
intersects = self.config.get("intersects", False)
within = self.config.get("within", False)
if contains and (within or intersects) or (within and intersects):
logger.warning(
"contains, intersects and within parameters are mutually exclusive"
)
return products
elif (
minimum_overlap > 0
and minimum_overlap < 100
and (contains or within or intersects)
):
logger.warning(
"minimum_overlap will be ignored because of contains/intersects/within usage"
)
elif not contains and not within and not intersects:
logger.debug("Minimum overlap is: {} %".format(minimum_overlap))
logger.debug("Initial requested extent area: %s", search_geom.area)
if search_geom.area == 0:
logger.debug(
"No product can overlap a requested extent that is not a polygon (i.e with area=0)"
)
else:
for product in products:
logger.debug("Uncovered extent area: %s", search_geom.area)
if product.search_intersection:
intersection = product.search_intersection
product_geometry = product.geometry
else:
if not product.geometry.is_valid:
logger.debug(
"Trying our best to deal with invalid geometry on product: %r",
product,
)
product_geometry = product.geometry.buffer(0)
try:
intersection = search_geom.intersection(product_geometry)
except TopologicalError:
logger.debug(
"Product geometry still invalid. Overlap test restricted to containment"
)
if search_geom.contains(product_geometry):
logger.debug(
"Product %r overlaps the search extent. Adding it to filtered results"
)
add_to_filtered(product)
continue
else:
product_geometry = product.geometry
intersection = search_geom.intersection(product_geometry)
if (
(contains and product_geometry.contains(search_geom))
or (within and product_geometry.within(search_geom))
or (intersects and product_geometry.intersects(search_geom))
):
add_to_filtered(product)
continue
elif contains or within or intersects:
continue
ipos = (intersection.area / search_geom.area) * 100
ipop = (intersection.area / product_geometry.area) * 100
logger.debug(
"Intersection of product extent and search extent covers %f percent of the search extent "
"area",
ipos,
)
logger.debug(
"Intersection of product extent and search extent covers %f percent of the product extent "
"area",
ipop,
)
if any(
(
search_geom.contains(product.geometry),
ipos >= minimum_overlap,
ipop >= minimum_overlap,
)
):
logger.debug(
"Product %r overlaps the search extent by the specified constraint. Adding it to "
"filtered results",
product,
)
add_to_filtered(product)
else:
logger.debug(
"Product %r does not overlaps the search extent by the specified constraint. "
"Skipping it",
product,
)
logger.info("Finished filtering products. %s resulting products", len(filtered))
return filtered
| true | true |
1c2bab35007c0e16616799e219263ce48e7899b7 | 367 | py | Python | src/schnetpack/nn/activations.py | giadefa/schnetpack | 9dabc3b6e3b28deb2fb3743ea1857c46b055efbf | [
"MIT"
] | 450 | 2018-09-04T08:37:47.000Z | 2022-03-30T08:05:37.000Z | src/schnetpack/nn/activations.py | giadefa/schnetpack | 9dabc3b6e3b28deb2fb3743ea1857c46b055efbf | [
"MIT"
] | 239 | 2018-09-11T21:09:08.000Z | 2022-03-18T09:25:11.000Z | src/schnetpack/nn/activations.py | giadefa/schnetpack | 9dabc3b6e3b28deb2fb3743ea1857c46b055efbf | [
"MIT"
] | 166 | 2018-09-13T13:01:06.000Z | 2022-03-31T12:59:12.000Z | import numpy as np
from torch.nn import functional
def shifted_softplus(x):
r"""Compute shifted soft-plus activation function.
.. math::
y = \ln\left(1 + e^{-x}\right) - \ln(2)
Args:
x (torch.Tensor): input tensor.
Returns:
torch.Tensor: shifted soft-plus of input.
"""
return functional.softplus(x) - np.log(2.0)
| 19.315789 | 54 | 0.610354 | import numpy as np
from torch.nn import functional
def shifted_softplus(x):
return functional.softplus(x) - np.log(2.0)
| true | true |
1c2baba36a7a089cd7f46d3bf45a67d99c349331 | 757 | py | Python | datasets/cifar10.py | mtyhon/ckconv | 056ec93c039e8bcda89f07ff9fdece3e7373b0bf | [
"MIT"
] | 74 | 2021-02-04T14:28:49.000Z | 2022-03-23T16:12:18.000Z | datasets/cifar10.py | mtyhon/ckconv | 056ec93c039e8bcda89f07ff9fdece3e7373b0bf | [
"MIT"
] | 7 | 2021-02-28T03:29:12.000Z | 2022-02-16T14:33:06.000Z | datasets/cifar10.py | mtyhon/ckconv | 056ec93c039e8bcda89f07ff9fdece3e7373b0bf | [
"MIT"
] | 6 | 2021-02-12T14:43:15.000Z | 2021-08-11T02:42:31.000Z | from torchvision import datasets, transforms
class CIFAR10(datasets.CIFAR10): # TODO: Documentation
def __init__(
self,
partition: str,
**kwargs,
):
root = "./data"
transform = transforms.Compose(
[
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
]
)
if partition == "train":
train = True
elif partition == "test":
train = False
else:
raise NotImplementedError(
"The dataset partition {} does not exist".format(partition)
)
super().__init__(root=root, train=train, transform=transform, download=True)
| 27.035714 | 84 | 0.52576 | from torchvision import datasets, transforms
class CIFAR10(datasets.CIFAR10):
def __init__(
self,
partition: str,
**kwargs,
):
root = "./data"
transform = transforms.Compose(
[
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
]
)
if partition == "train":
train = True
elif partition == "test":
train = False
else:
raise NotImplementedError(
"The dataset partition {} does not exist".format(partition)
)
super().__init__(root=root, train=train, transform=transform, download=True)
| true | true |
1c2bac34ad8c76ff7ae97490b476c068a8bdcead | 5,000 | py | Python | docs/source/conf.py | remz1337/LGP | aac633fbd1305f699973c1bfe7db4603195f8dfa | [
"MIT"
] | 15 | 2017-05-12T13:20:38.000Z | 2021-09-27T05:09:37.000Z | docs/source/conf.py | remz1337/LGP | aac633fbd1305f699973c1bfe7db4603195f8dfa | [
"MIT"
] | 35 | 2017-04-20T04:57:45.000Z | 2022-03-20T05:34:33.000Z | docs/source/conf.py | remz1337/LGP | aac633fbd1305f699973c1bfe7db4603195f8dfa | [
"MIT"
] | 4 | 2018-11-02T00:35:33.000Z | 2020-09-29T00:59:32.000Z | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# LGP documentation build configuration file, created by
# sphinx-quickstart on Wed Apr 19 11:42:17 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.mathjax',
'sphinx.ext.githubpages'
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'LGP'
copyright = '2017, Jed Simson'
author = 'Jed Simson'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = ''
# The full version, including alpha/beta/rc tags.
release = ''
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = []
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
'description': 'A robust LGP implementation on the JVM using Kotlin.',
'github_user': 'JedS6391',
'github_repo': 'LGP',
'travis_button': True,
'fixed_sidebar': True,
'github_type': 'star',
'github_count': False
}
html_sidebars = {
'**': [
'about.html',
'globaltoc.html',
'searchbox.html'
]
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'LGPdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'LGP.tex', 'LGP Documentation',
'Jed Simson', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'lgp', 'LGP Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'LGP', 'LGP Documentation',
author, 'LGP', 'One line description of project.',
'Miscellaneous'),
]
| 28.571429 | 79 | 0.6698 |
extensions = [
'sphinx.ext.mathjax',
'sphinx.ext.githubpages'
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'LGP'
copyright = '2017, Jed Simson'
author = 'Jed Simson'
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = ''
# The full version, including alpha/beta/rc tags.
release = ''
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = []
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
'description': 'A robust LGP implementation on the JVM using Kotlin.',
'github_user': 'JedS6391',
'github_repo': 'LGP',
'travis_button': True,
'fixed_sidebar': True,
'github_type': 'star',
'github_count': False
}
html_sidebars = {
'**': [
'about.html',
'globaltoc.html',
'searchbox.html'
]
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'LGPdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'LGP.tex', 'LGP Documentation',
'Jed Simson', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'lgp', 'LGP Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'LGP', 'LGP Documentation',
author, 'LGP', 'One line description of project.',
'Miscellaneous'),
]
| true | true |
1c2bac51ebfee79ae18de2be4e3e8de544345b1d | 5,210 | py | Python | nodular_JJ/finite_sc/phase_diagrams/fxd_gam_gap.py | tbcole/majoranaJJ | dcf31f7786fa0a4874a940b7d8dcdd55f3921a46 | [
"MIT"
] | null | null | null | nodular_JJ/finite_sc/phase_diagrams/fxd_gam_gap.py | tbcole/majoranaJJ | dcf31f7786fa0a4874a940b7d8dcdd55f3921a46 | [
"MIT"
] | 2 | 2020-03-24T23:46:17.000Z | 2020-04-19T20:29:08.000Z | nodular_JJ/finite_sc/phase_diagrams/fxd_gam_gap.py | tbcole/majoranaJJ | dcf31f7786fa0a4874a940b7d8dcdd55f3921a46 | [
"MIT"
] | 3 | 2020-04-30T08:48:12.000Z | 2022-01-26T12:15:15.000Z | import sys
import time
import os
import gc
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from scipy.signal import argrelextrema
import scipy.linalg as LA
import scipy.sparse.linalg as spLA
import majoranaJJ.operators.sparse_operators as spop #sparse operators
from majoranaJJ.operators.potentials import Vjj #potential JJ
import majoranaJJ.lattice.nbrs as nb #neighbor arrays
import majoranaJJ.lattice.shapes as shps #lattice shapes
import majoranaJJ.modules.plots as plots #plotting functions
import majoranaJJ.modules.gamfinder as gamfinder
from majoranaJJ.modules.checkers import boundary_check as bc
import majoranaJJ.modules.checkers as check
###################################################
#Defining System
Nx = 3 #Number of lattice sites along x-direction
Ny = 360 #Number of lattice sites along y-direction
ax = 50 #lattice spacing in x-direction: [A]
ay = 50 #lattice spacing in y-direction: [A]
Wj = 10 #Junction region
cutx = 0 #width of nodule
cuty = 0 #height of nodule
Nx, Ny, cutx, cuty, Wj = check.junction_geometry_check(Nx, Ny, cutx, cuty, Wj)
print("Nx = {}, Ny = {}, cutx = {}, cuty = {}, Wj = {}".format(Nx, Ny, cutx, cuty, Wj))
Junc_width = Wj*ay*.10 #nm
SC_width = ((Ny - Wj)*ay*.10)/2 #nm
Nod_widthx = cutx*ax*.1 #nm
Nod_widthy = cuty*ay*.1 #nm
print("Nodule Width in x-direction = ", Nod_widthx, "(nm)")
print("Nodule Width in y-direction = ", Nod_widthy, "(nm)")
print("Junction Width = ", Junc_width, "(nm)")
print("Supercondicting Lead Width = ", SC_width, "(nm)")
###################################################
coor = shps.square(Nx, Ny) #square lattice
NN = nb.NN_sqr(coor)
NNb = nb.Bound_Arr(coor)
lat_size = coor.shape[0]
print("Lattice Size: ", lat_size)
Lx = (max(coor[:, 0]) - min(coor[:, 0]) + 1)*ax #Unit cell size in x-direction
Ly = (max(coor[:, 1]) - min(coor[:, 1]) + 1)*ay #Unit cell size in y-direction
###################################################
#Defining Hamiltonian parameters
gamx = 5
alpha = 300 #Spin-Orbit Coupling constant: [meV*A]
phi = np.pi #SC phase difference
delta = 1 #Superconducting Gap: [meV]
Vsc = 0 #SC potential: [meV]
Vj = 0 #Junction potential: [meV]
V = Vjj(coor, Wj = Wj, Vsc = Vsc, Vj = Vj, cutx = cutx, cuty = cuty)
mu_i = 0
mu_f = 50
res = 1
mu_steps = int((mu_f-mu_i)/res)
mu = np.linspace(mu_i, mu_f, mu_steps)
q_steps = 500
qx = np.linspace(0, np.pi/Lx, q_steps) #kx in the first Brillouin zone
k = 4
LE_Bands = np.zeros((qx.shape[0], mu.shape[0]))
###################################################
dirS = 'gap_data'
if not os.path.exists(dirS):
os.makedirs(dirS)
try:
PLOT = str(sys.argv[1])
except:
PLOT = 'F'
if PLOT != 'P':
for i in range(q_steps):
for j in range(mu.shape[0]):
print(q_steps-i, mu.shape[0]-j)
H = spop.HBDG(coor, ax, ay, NN, NNb=NNb, Wj=Wj, cutx=cutx, cuty=cuty, V=V, mu=mu[j], alpha=alpha, delta=delta, phi=phi, gamx=gamx, qx=qx[i]) #gives low energy basis
eigs, vecs = spLA.eigsh(H, k=k, sigma=0, which='LM')
idx_sort = np.argsort(eigs)
eigs = eigs[idx_sort]
LE_Bands[i, j] = eigs[int(k/2)]
gap = np.zeros((mu.shape[0]))
q_minima = []
for i in range(LE_Bands.shape[1]):
eig_min_idx = np.array(argrelextrema(LE_Bands[:, i], np.less)[0])
q_minima.append(qx[eig_min_idx])
gap[i] = min(LE_Bands[:, i])
q_minima = np.array(q_minima)
print(gap)
np.save("%s/gap Lx = %.1f Ly = %.1f Wsc = %.1f Wj = %.1f nodx = %.1f nody = %.1f Vj = %.1f Vsc = %.1f alpha = %.1f delta = %.2f phi = %.3f.npy" % (dirS, Lx*.1, Ly*.1, SC_width, Junc_width, Nod_widthx, Nod_widthy, Vj, Vsc, alpha, delta, phi), gap)
gc.collect()
sys.exit()
else:
gap = np.load("%s/gap Lx = %.1f Ly = %.1f Wsc = %.1f Wj = %.1f nodx = %.1f nody = %.1f Vj = %.1f Vsc = %.1f alpha = %.1f delta = %.2f phi = %.3f.npy" % (dirS, Lx*.1, Ly*.1, SC_width, Junc_width, Nod_widthx, Nod_widthy, Vj, Vsc, alpha, delta, phi))
#q_minima = np.load("%s/q_minima Lx = %.1f Ly = %.1f Wsc = %.1f Wj = %.1f nodx = %.1f nody = %.1f Vj = %.1f Vsc = %.1f alpha = %.1f delta = %.2f phi = %.3f.npy" % (dirS, Lx*.1, Ly*.1, SC_width, Junc_width, Nod_widthx, Nod_widthy, Vj, Vsc, alpha, delta, phi))
gap = gap/delta
plt.plot(mu, gap)
plt.xlabel(r'$\mu$ (meV)')
plt.ylabel(r'$E_{gap}/\Delta$ (meV)')
plt.xlim(mu_i, mu_f)
title = r"$\Gamma$ = %.1f $L_x$ = %.1f nm, $L_y$ = %.1f nm, $W_{sc}$ = %.1f nm, $W_j$ = %.1f nm, $nodule_x$ = %.1f nm, $nodule_y$ = %.1f nm, $V_j$ = %.1f meV, $V_{SC}$ = %.1f meV, $\phi$ = %.2f " % (gamx, Lx*.1, Ly*.1, SC_width, Junc_width, Nod_widthx, Nod_widthy, Vj, Vsc, phi)
#title = r"$L_x =$ {} nm, $L_y =$ {} nm, SC width = {} nm, $W_j =$ {} nm, $nodule_x = ${} nm, $nodule_y = ${} nm, $\alpha = $ {} meV*A, $\phi =$ {} ".format(Lx*.1, Ly*.1, SC_width, Junc_width, Nod_widthx, Nod_widthy, alpha, phi)
plt.title(title, loc = 'center', wrap = True)
plt.subplots_adjust(top=0.85)
plt.savefig('gap juncwidth = {} SCwidth = {} nodwidthx = {} nodwidthy = {} phi = {} Vj = {} Vsc = {}.png'.format(Junc_width, SC_width, Nod_widthx, Nod_widthy, delta, alpha, phi, Vj, Vsc))
plt.show()
sys.exit()
| 43.057851 | 282 | 0.604223 | import sys
import time
import os
import gc
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from scipy.signal import argrelextrema
import scipy.linalg as LA
import scipy.sparse.linalg as spLA
import majoranaJJ.operators.sparse_operators as spop
from majoranaJJ.operators.potentials import Vjj
import majoranaJJ.lattice.nbrs as nb
import majoranaJJ.lattice.shapes as shps
import majoranaJJ.modules.plots as plots
import majoranaJJ.modules.gamfinder as gamfinder
from majoranaJJ.modules.checkers import boundary_check as bc
import majoranaJJ.modules.checkers as check
| true | true |
1c2bac807284f98d90b280bb37eeb8993e2597bb | 6,381 | py | Python | jigsaw19/roberta_large3/train/train.py | GuanshuoXu/Jigsaw-Rate-Severity-of-Toxic-Comments | 84243994c70124d1a529bb6931f579f7d185d64c | [
"MIT"
] | 49 | 2022-02-08T21:34:37.000Z | 2022-03-31T17:31:45.000Z | jigsaw19/roberta_large3/train/train.py | xiaobenla/Jigsaw-Rate-Severity-of-Toxic-Comments | 84243994c70124d1a529bb6931f579f7d185d64c | [
"MIT"
] | 1 | 2022-03-21T13:48:01.000Z | 2022-03-21T13:48:01.000Z | jigsaw19/roberta_large3/train/train.py | xiaobenla/Jigsaw-Rate-Severity-of-Toxic-Comments | 84243994c70124d1a529bb6931f579f7d185d64c | [
"MIT"
] | 14 | 2022-02-08T21:34:39.000Z | 2022-03-01T00:44:18.000Z | import argparse
import numpy as np
import pandas as pd
import os
from tqdm import tqdm
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.distributed import DistributedSampler
import torch
import random
import pickle
from torch.cuda.amp import autocast, GradScaler
import time
from transformers import RobertaModel, RobertaPreTrainedModel, RobertaConfig, get_linear_schedule_with_warmup, RobertaTokenizerFast
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
class JRSDataset(Dataset):
def __init__(self, id_list, tokenizer, data_dict, max_len):
self.id_list=id_list
self.tokenizer=tokenizer
self.data_dict=data_dict
self.max_len=max_len
def __len__(self):
return len(self.id_list)
def __getitem__(self, index):
tokenized = self.tokenizer(text=self.data_dict[self.id_list[index]]['text'],
padding='max_length',
truncation=True,
max_length=self.max_len,
return_attention_mask=True,
return_token_type_ids=True,
return_tensors='pt')
target = self.data_dict[self.id_list[index]]['labels']
return tokenized['input_ids'].squeeze(), tokenized['attention_mask'].squeeze(), tokenized['token_type_ids'].squeeze(), target
class JRSModel(RobertaPreTrainedModel):
def __init__(self, config):
super(JRSModel, self).__init__(config)
self.roberta = RobertaModel(config)
self.classifier = nn.Linear(config.hidden_size, 7)
self.init_weights()
def forward(self, input_ids, attention_mask=None, token_type_ids=None):
outputs = self.roberta(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)['last_hidden_state']
embeddings = torch.mean(outputs, axis=1)
logits = self.classifier(embeddings)
return logits
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--local_rank", type=int, default=-1, help="local_rank for distributed training on gpus")
args = parser.parse_args()
torch.cuda.set_device(args.local_rank)
device = torch.device("cuda", args.local_rank)
torch.distributed.init_process_group(backend="nccl")
args.device = device
seed = 7365
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
# prepare input
import pickle
with open('../../splits/split1/train_id_list1.pickle', 'rb') as f:
id_list = pickle.load(f)
with open('../../splits/split1/data_dict.pickle', 'rb') as f:
data_dict = pickle.load(f)
print(len(id_list), len(data_dict))
# hyperparameters
learning_rate = 0.000025
max_len = 256
batch_size = 32
num_epoch = 1
model_path = "roberta-large"
# build model
if args.local_rank != 0:
torch.distributed.barrier()
config = RobertaConfig.from_pretrained(model_path)
config.hidden_dropout_prob = 0
config.attention_probs_dropout_prob = 0
tokenizer = RobertaTokenizerFast.from_pretrained(model_path)
model = JRSModel.from_pretrained(model_path, config=config)
if args.local_rank == 0:
torch.distributed.barrier()
model.to(args.device)
num_train_steps = int(len(id_list)/(batch_size*3)*num_epoch)
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=int(num_train_steps*0.1), num_training_steps=num_train_steps)
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True)
# training
train_datagen = JRSDataset(id_list, tokenizer, data_dict, max_len)
train_sampler = DistributedSampler(train_datagen)
train_generator = DataLoader(dataset=train_datagen,
sampler=train_sampler,
batch_size=batch_size,
num_workers=8,
pin_memory=True)
if args.local_rank == 0:
start_time = time.time()
scaler = GradScaler()
for ep in range(num_epoch):
losses = AverageMeter()
model.train()
for j, (batch_input_ids, batch_attention_mask, batch_token_type_ids, batch_target) in enumerate(train_generator):
batch_input_ids = batch_input_ids.to(args.device)
batch_attention_mask = batch_attention_mask.to(args.device)
batch_token_type_ids = batch_token_type_ids.to(args.device)
batch_target = torch.from_numpy(np.array(batch_target)).float().to(args.device)
with autocast():
logits = model(batch_input_ids, batch_attention_mask, batch_token_type_ids)
loss = nn.BCEWithLogitsLoss()(logits, batch_target)
losses.update(loss.item(), logits.size(0))
optimizer.zero_grad()
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
scheduler.step()
#if args.local_rank == 0:
# print('\r',end='',flush=True)
# message = '%s %5.1f %6.1f %0.8f | %0.3f |' % ("train",j/len(train_generator)+ep,ep,scheduler.get_lr()[0],losses.avg)
# print(message , end='',flush=True)
if args.local_rank == 0:
print('epoch: {}, train_loss: {}'.format(ep, losses.avg), flush=True)
if args.local_rank == 0:
out_dir = 'weights/'
if not os.path.exists(out_dir):
os.makedirs(out_dir)
torch.save(model.module.state_dict(), out_dir+'weights')
if args.local_rank == 0:
end_time = time.time()
print(end_time-start_time)
if __name__ == "__main__":
main()
| 38.209581 | 150 | 0.645197 | import argparse
import numpy as np
import pandas as pd
import os
from tqdm import tqdm
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.distributed import DistributedSampler
import torch
import random
import pickle
from torch.cuda.amp import autocast, GradScaler
import time
from transformers import RobertaModel, RobertaPreTrainedModel, RobertaConfig, get_linear_schedule_with_warmup, RobertaTokenizerFast
class AverageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
class JRSDataset(Dataset):
def __init__(self, id_list, tokenizer, data_dict, max_len):
self.id_list=id_list
self.tokenizer=tokenizer
self.data_dict=data_dict
self.max_len=max_len
def __len__(self):
return len(self.id_list)
def __getitem__(self, index):
tokenized = self.tokenizer(text=self.data_dict[self.id_list[index]]['text'],
padding='max_length',
truncation=True,
max_length=self.max_len,
return_attention_mask=True,
return_token_type_ids=True,
return_tensors='pt')
target = self.data_dict[self.id_list[index]]['labels']
return tokenized['input_ids'].squeeze(), tokenized['attention_mask'].squeeze(), tokenized['token_type_ids'].squeeze(), target
class JRSModel(RobertaPreTrainedModel):
def __init__(self, config):
super(JRSModel, self).__init__(config)
self.roberta = RobertaModel(config)
self.classifier = nn.Linear(config.hidden_size, 7)
self.init_weights()
def forward(self, input_ids, attention_mask=None, token_type_ids=None):
outputs = self.roberta(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)['last_hidden_state']
embeddings = torch.mean(outputs, axis=1)
logits = self.classifier(embeddings)
return logits
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--local_rank", type=int, default=-1, help="local_rank for distributed training on gpus")
args = parser.parse_args()
torch.cuda.set_device(args.local_rank)
device = torch.device("cuda", args.local_rank)
torch.distributed.init_process_group(backend="nccl")
args.device = device
seed = 7365
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
import pickle
with open('../../splits/split1/train_id_list1.pickle', 'rb') as f:
id_list = pickle.load(f)
with open('../../splits/split1/data_dict.pickle', 'rb') as f:
data_dict = pickle.load(f)
print(len(id_list), len(data_dict))
learning_rate = 0.000025
max_len = 256
batch_size = 32
num_epoch = 1
model_path = "roberta-large"
if args.local_rank != 0:
torch.distributed.barrier()
config = RobertaConfig.from_pretrained(model_path)
config.hidden_dropout_prob = 0
config.attention_probs_dropout_prob = 0
tokenizer = RobertaTokenizerFast.from_pretrained(model_path)
model = JRSModel.from_pretrained(model_path, config=config)
if args.local_rank == 0:
torch.distributed.barrier()
model.to(args.device)
num_train_steps = int(len(id_list)/(batch_size*3)*num_epoch)
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=int(num_train_steps*0.1), num_training_steps=num_train_steps)
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True)
train_datagen = JRSDataset(id_list, tokenizer, data_dict, max_len)
train_sampler = DistributedSampler(train_datagen)
train_generator = DataLoader(dataset=train_datagen,
sampler=train_sampler,
batch_size=batch_size,
num_workers=8,
pin_memory=True)
if args.local_rank == 0:
start_time = time.time()
scaler = GradScaler()
for ep in range(num_epoch):
losses = AverageMeter()
model.train()
for j, (batch_input_ids, batch_attention_mask, batch_token_type_ids, batch_target) in enumerate(train_generator):
batch_input_ids = batch_input_ids.to(args.device)
batch_attention_mask = batch_attention_mask.to(args.device)
batch_token_type_ids = batch_token_type_ids.to(args.device)
batch_target = torch.from_numpy(np.array(batch_target)).float().to(args.device)
with autocast():
logits = model(batch_input_ids, batch_attention_mask, batch_token_type_ids)
loss = nn.BCEWithLogitsLoss()(logits, batch_target)
losses.update(loss.item(), logits.size(0))
optimizer.zero_grad()
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
scheduler.step()
if args.local_rank == 0:
print('epoch: {}, train_loss: {}'.format(ep, losses.avg), flush=True)
if args.local_rank == 0:
out_dir = 'weights/'
if not os.path.exists(out_dir):
os.makedirs(out_dir)
torch.save(model.module.state_dict(), out_dir+'weights')
if args.local_rank == 0:
end_time = time.time()
print(end_time-start_time)
if __name__ == "__main__":
main()
| true | true |
1c2bacc2932662969a4085cb1c52e06980fd3539 | 2,395 | py | Python | ipinfo.py | abuelacantora/judas | 722f04ec44069b73600b80a99fa2d7fb1886b5a5 | [
"MIT"
] | null | null | null | ipinfo.py | abuelacantora/judas | 722f04ec44069b73600b80a99fa2d7fb1886b5a5 | [
"MIT"
] | null | null | null | ipinfo.py | abuelacantora/judas | 722f04ec44069b73600b80a99fa2d7fb1886b5a5 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# Gets info on IP address (IPv4 or IPv6) from http://ipinfo.io/
# Source: https://github.com/sanderjo/ipinfo.git
# GPL3
'''
Based on this public API from http://ipinfo.io/ :
$ curl http://ipinfo.io/31.21.30.159/json
{
"ip": "31.21.30.159",
"hostname": "No Hostname",
"city": "",
"region": "",
"country": "NL",
"loc": "52.3667,4.9000",
"org": "AS31615 T-mobile Netherlands bv."
}
'''
import json
import urllib
import re
baseurl = 'http://api.ipapi.com' # no HTTPS supported (at least: not without a plan)
def ispublic(ipaddress):
return not isprivate(ipaddress)
def isprivate(ipaddress):
if ipaddress.startswith("::ffff:"):
ipaddress=ipaddress.replace("::ffff:", "")
# IPv4 Regexp from https://stackoverflow.com/questions/30674845/
if re.search(r"^(?:10|127|172\.(?:1[6-9]|2[0-9]|3[01])|192\.168)\..*", ipaddress):
# Yes, so match, so a local or RFC1918 IPv4 address
return True
if ipaddress == "::1":
# Yes, IPv6 localhost
return True
return False
def getall(ipaddress, key):
url = '%s/%s?access_key=%s' % (baseurl, ipaddress, key)
try:
urlresult = urllib.urlopen(url)
jsonresult = urlresult.read() # get the JSON
parsedjson = json.loads(jsonresult) # put parsed JSON into dictionary
return parsedjson
except:
return None
def country_and_org(ipaddress):
allinfo = getall(ipaddress) # one lookup
try:
# FYI: the first word in allinfo['org'] is the ASN, which we skip
return allinfo['country'] + ' --- ' + allinfo['org'].split(' ', 1)[1]
except:
return ""
def country_and_org_as_list(ipaddress):
allinfo = getall(ipaddress) # one lookup
try:
# FYI: the first word in allinfo['org'] is the ASN, which we skip
return [ allinfo['country'], allinfo['org'].split(' ', 1)[1] ]
except:
return ['','']
if __name__ == '__main__':
# Some examples:
print(getall('31.21.30.159'))
print(country_and_org('31.21.30.159'))
print(getall('192.168.0.1'))
print(country_and_org('192.168.0.1'))
print(country_and_org('2a00:1450:4013:c01::64'))
print(country_and_org('::ffff:194.109.6.92'))
print(' --- '.join(country_and_org_as_list('31.21.30.159')))
print(' --- '.join(country_and_org_as_list('31.21.30.')))
| 25.210526 | 87 | 0.610438 |
import json
import urllib
import re
baseurl = 'http://api.ipapi.com'
def ispublic(ipaddress):
return not isprivate(ipaddress)
def isprivate(ipaddress):
if ipaddress.startswith("::ffff:"):
ipaddress=ipaddress.replace("::ffff:", "")
if re.search(r"^(?:10|127|172\.(?:1[6-9]|2[0-9]|3[01])|192\.168)\..*", ipaddress):
return True
if ipaddress == "::1":
return True
return False
def getall(ipaddress, key):
url = '%s/%s?access_key=%s' % (baseurl, ipaddress, key)
try:
urlresult = urllib.urlopen(url)
jsonresult = urlresult.read()
parsedjson = json.loads(jsonresult)
return parsedjson
except:
return None
def country_and_org(ipaddress):
allinfo = getall(ipaddress)
try:
return allinfo['country'] + ' --- ' + allinfo['org'].split(' ', 1)[1]
except:
return ""
def country_and_org_as_list(ipaddress):
allinfo = getall(ipaddress)
try:
return [ allinfo['country'], allinfo['org'].split(' ', 1)[1] ]
except:
return ['','']
if __name__ == '__main__':
print(getall('31.21.30.159'))
print(country_and_org('31.21.30.159'))
print(getall('192.168.0.1'))
print(country_and_org('192.168.0.1'))
print(country_and_org('2a00:1450:4013:c01::64'))
print(country_and_org('::ffff:194.109.6.92'))
print(' --- '.join(country_and_org_as_list('31.21.30.159')))
print(' --- '.join(country_and_org_as_list('31.21.30.')))
| true | true |
1c2bad54eb4e97edcefe58d45791dbff64e10082 | 627 | py | Python | solutions/007/007.py | vicaal/daily-coding-problem | 351436363575c303ceff56236f193e3c3c20fcd3 | [
"MIT"
] | null | null | null | solutions/007/007.py | vicaal/daily-coding-problem | 351436363575c303ceff56236f193e3c3c20fcd3 | [
"MIT"
] | null | null | null | solutions/007/007.py | vicaal/daily-coding-problem | 351436363575c303ceff56236f193e3c3c20fcd3 | [
"MIT"
] | null | null | null |
def valid_character(number):
return True if int(number) > 0 and int(number) < 27 else False
def solve(message):
if message == '':
return 1
else:
number_of_solutions = 0
if valid_character(message[:1]):
number_of_solutions += (solve(message[1:]))
if len(message) > 1 and valid_character(message[:2]):
number_of_solutions += (solve(message[2:]))
return number_of_solutions
assert solve('65') == 1
assert solve('23') == 2
assert solve('111') == 3
assert solve('1224') == 5
assert solve('2522') == 4
assert solve('2562') == 2
assert solve('2532') == 2
| 23.222222 | 66 | 0.61244 |
def valid_character(number):
return True if int(number) > 0 and int(number) < 27 else False
def solve(message):
if message == '':
return 1
else:
number_of_solutions = 0
if valid_character(message[:1]):
number_of_solutions += (solve(message[1:]))
if len(message) > 1 and valid_character(message[:2]):
number_of_solutions += (solve(message[2:]))
return number_of_solutions
assert solve('65') == 1
assert solve('23') == 2
assert solve('111') == 3
assert solve('1224') == 5
assert solve('2522') == 4
assert solve('2562') == 2
assert solve('2532') == 2
| true | true |
1c2bae9d0e78a12065a8ee588ab65cb01f497586 | 1,507 | py | Python | pv_vision/tools/im_move.py | hackingmaterials/pv_vision | a42be9b55da4a2384602bc456989cef1324edab1 | [
"BSD-3-Clause"
] | 12 | 2020-11-11T22:59:28.000Z | 2022-03-21T08:52:43.000Z | pv_vision/tools/im_move.py | hackingmaterials/pv_vision | a42be9b55da4a2384602bc456989cef1324edab1 | [
"BSD-3-Clause"
] | 4 | 2021-02-01T22:18:59.000Z | 2022-03-14T00:41:57.000Z | pv_vision/tools/im_move.py | hackingmaterials/pv_vision | a42be9b55da4a2384602bc456989cef1324edab1 | [
"BSD-3-Clause"
] | 3 | 2021-01-23T00:58:46.000Z | 2022-01-10T21:17:07.000Z | import csv
import os
import shutil
import argparse
from pathlib import Path
from tqdm import tqdm
def im_move(im_folder_path, csv_path, subfolders, parentfolder='classified_images', im_extension=None):
"""Move the source images into subfolders based on their categories.
Parameters
----------
im_folder_path: str or pathlib.PosixPath
The folder path of the original images.
csv_path: str or pathlib.PosixPath
The path of the csv file that indicates the category of each solar module.
The first column of the csv file should be the name of a module without filename extension
The second column should be its category which is the same in the subfolders.
subfolders: list of strings
The categories of the solar modules.
E.g. ['category1', 'category2', 'category3']
parentfolder: str
The parent folder name of subfolders
im_extension: str
The filename extension of the src images, e.g. '.png', '.jpg', etc.
"""
if not im_extension:
image = os.listdir(im_folder_path)[0]
im_extension = os.path.splitext(image)[-1]
folder = Path(parentfolder)
for subfolder in subfolders:
os.makedirs(folder/ subfolder, exist_ok=True)
with open(csv_path, 'r') as file:
data = [line.rstrip() for line in file]
for cell in tqdm(data):
name, label = cell.split(',')[0], cell.split(',')[1]
shutil.copy(im_folder_path/ (name + im_extension), folder/label)
| 32.76087 | 103 | 0.678832 | import csv
import os
import shutil
import argparse
from pathlib import Path
from tqdm import tqdm
def im_move(im_folder_path, csv_path, subfolders, parentfolder='classified_images', im_extension=None):
if not im_extension:
image = os.listdir(im_folder_path)[0]
im_extension = os.path.splitext(image)[-1]
folder = Path(parentfolder)
for subfolder in subfolders:
os.makedirs(folder/ subfolder, exist_ok=True)
with open(csv_path, 'r') as file:
data = [line.rstrip() for line in file]
for cell in tqdm(data):
name, label = cell.split(',')[0], cell.split(',')[1]
shutil.copy(im_folder_path/ (name + im_extension), folder/label)
| true | true |
1c2baf6a358cd9fd2d8127bad96dc8f8f8625f5a | 20,938 | py | Python | tests/standalone/run_all.py | lurid-bogey/Nuitka | 7eca8d66874e08f6d8472ad4e63255a08ad0c3c5 | [
"Apache-2.0"
] | null | null | null | tests/standalone/run_all.py | lurid-bogey/Nuitka | 7eca8d66874e08f6d8472ad4e63255a08ad0c3c5 | [
"Apache-2.0"
] | null | null | null | tests/standalone/run_all.py | lurid-bogey/Nuitka | 7eca8d66874e08f6d8472ad4e63255a08ad0c3c5 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# Copyright 2019, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Python test originally created or extracted from other peoples work. The
# parts from me are licensed as below. It is at least Free Software where
# it's copied from other people. In these cases, that will normally be
# indicated.
#
# 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.
#
""" Runner for standalone program tests of Nuitka.
These tests aim at showing that one specific module works in standalone
mode, trying to find issues with that packaging.
"""
import os
import sys
# Find nuitka package relative to us. The replacement is for POSIX python
# and Windows paths on command line.
sys.path.insert(
0,
os.path.normpath(
os.path.join(
os.path.dirname(os.path.abspath(__file__.replace("\\", os.sep))), "..", ".."
)
),
)
# isort:start
import subprocess
from nuitka.tools.testing.Common import (
compareWithCPython,
createSearchMode,
decideFilenameVersionSkip,
getPythonVendor,
getRuntimeTraceOfLoadedFiles,
hasModule,
my_print,
reportSkip,
setup,
)
from nuitka.tree.SourceReading import readSourceCodeFromFilename
from nuitka.utils.FileOperations import areSamePaths, removeDirectory
from nuitka.utils.Utils import getOS
# checks requirements needed to run each test module, according to the specified special comment
# special comments are in the following formats:
# "# nuitka-skip-unless-expression: expression to be evaluated"
# OR
# "# nuitka-skip-unless-imports: module1,module2,..."
def checkRequirements(filename):
for line in readSourceCodeFromFilename(None, filename).splitlines():
if line.startswith("# nuitka-skip-unless-"):
if line[21:33] == "expression: ":
expression = line[33:]
with open(os.devnull, "w") as devnull:
result = subprocess.call(
(
os.environ["PYTHON"],
"-c",
"import sys, os; sys.exit(not bool(%s))" % expression,
),
stdout=devnull,
stderr=subprocess.STDOUT,
)
if result != 0:
return (False, "Expression '%s' evaluated to false" % expression)
elif line[21:30] == "imports: ":
imports_needed = line[30:].rstrip().split(",")
for i in imports_needed:
if not hasModule(i):
return (
False,
i
+ " not installed for this Python version, but test needs it",
)
# default return value
return (True, "")
def displayError(dirname, filename):
assert dirname is None
my_print("Listing of dist folder:")
if os.name == "nt":
command = "dir /b /s /a:-D %s"
else:
command = "ls -Rla %s"
os.system(command % filename)
def main():
# Complex stuff, even more should become common code though.
# pylint: disable=too-many-branches,too-many-statements
python_version = setup(needs_io_encoding=True)
search_mode = createSearchMode()
for filename in sorted(os.listdir(".")):
if not filename.endswith(".py"):
continue
if not decideFilenameVersionSkip(filename):
continue
active = search_mode.consider(dirname=None, filename=filename)
if not active:
my_print("Skipping", filename)
continue
extra_flags = ["expect_success", "standalone", "remove_output"]
# skip each test if their respective requirements are not met
requirements_met, error_message = checkRequirements(filename)
if not requirements_met:
reportSkip(error_message, ".", filename)
continue
# catch error
elif filename == "Boto3Using.py":
reportSkip("boto3 test not fully working yet", ".", filename)
continue
elif "Idna" in filename:
# For the warnings of Python2.
if python_version.startswith("2"):
extra_flags.append("ignore_stderr")
elif filename == "CtypesUsing.py":
extra_flags.append("plugin_disable:pylint-warnings")
elif filename == "GtkUsing.py":
# Don't test on platforms not supported by current Debian testing, and
# which should be considered irrelevant by now.
if python_version.startswith("2.6"):
reportSkip("irrelevant Python version", ".", filename)
continue
# For the warnings.
extra_flags.append("ignore_warnings")
elif filename.startswith("Win"):
if os.name != "nt":
reportSkip("Windows only test", ".", filename)
continue
elif filename == "TkInterUsing.py":
if getOS() == "Darwin":
reportSkip("Not working macOS yet", ".", filename)
continue
# For the plug-in information.
extra_flags.append("ignore_infos")
extra_flags.append("plugin_enable:tk-inter")
elif filename == "FlaskUsing.py":
# For the warnings.
extra_flags.append("ignore_warnings")
# For enum plugin info
extra_flags.append("ignore_infos")
elif filename == "NumpyUsing.py":
# TODO: Disabled for now.
reportSkip("numpy.test not fully working yet", ".", filename)
continue
# extra_flags.append("plugin_enable:data-files")
elif filename == "PmwUsing.py":
extra_flags.append("plugin_enable:pmw-freezer")
elif filename == "OpenGLUsing.py":
# For the warnings.
extra_flags.append("ignore_warnings")
elif filename == "PasslibUsing.py":
# For the warnings.
extra_flags.append("ignore_warnings")
elif filename == "PySideUsing.py":
# TODO: Disabled due to lack of upstream support.
reportSkip("PySide not supported yet", ".", filename)
continue
if filename.startswith(("PySide", "PyQt")):
if python_version.startswith("2.6"):
reportSkip("irrelevant Python version", ".", filename)
continue
# For the plug-in information.
extra_flags.append("ignore_infos")
if getPythonVendor() != "Anaconda":
extra_flags.append("plugin_enable:qt-plugins")
# extra_flags.append("ignore_infos")
else:
# For the plug-in not used information.
extra_flags.append("ignore_warnings")
my_print("Consider output of recursively compiled program:", filename)
# First compare so we know the program behaves identical.
compareWithCPython(
dirname=None,
filename=filename,
extra_flags=extra_flags,
search_mode=search_mode,
needs_2to3=False,
on_error=displayError,
)
# Second check if glibc libraries haven't been accidentaly
# shipped with the standalone executable
found_glibc_libs = []
for dist_filename in os.listdir(os.path.join(filename[:-3] + ".dist")):
if os.path.basename(dist_filename).startswith(
(
"ld-linux-x86-64.so",
"libc.so.",
"libpthread.so.",
"libm.so.",
"libdl.so.",
"libBrokenLocale.so.",
"libSegFault.so",
"libanl.so.",
"libcidn.so.",
"libcrypt.so.",
"libmemusage.so",
"libmvec.so.",
"libnsl.so.",
"libnss_compat.so.",
"libnss_db.so.",
"libnss_dns.so.",
"libnss_files.so.",
"libnss_hesiod.so.",
"libnss_nis.so.",
"libnss_nisplus.so.",
"libpcprofile.so",
"libresolv.so.",
"librt.so.",
"libthread_db-1.0.so",
"libthread_db.so.",
"libutil.so.",
)
):
found_glibc_libs.append(dist_filename)
if found_glibc_libs:
my_print(
"Should not ship glibc libraries with the standalone executable (found %s)"
% found_glibc_libs
)
sys.exit(1)
binary_filename = os.path.join(
filename[:-3] + ".dist", filename[:-3] + (".exe" if os.name == "nt" else "")
)
# Then use "strace" on the result.
loaded_filenames = getRuntimeTraceOfLoadedFiles(binary_filename)
current_dir = os.path.normpath(os.getcwd())
current_dir = os.path.normcase(current_dir)
illegal_access = False
for loaded_filename in loaded_filenames:
loaded_filename = os.path.normpath(loaded_filename)
loaded_filename = os.path.normcase(loaded_filename)
loaded_basename = os.path.basename(loaded_filename)
if os.name == "nt":
if areSamePaths(
os.path.dirname(loaded_filename),
os.path.normpath(
os.path.join(os.environ["SYSTEMROOT"], "System32")
),
):
continue
if areSamePaths(
os.path.dirname(loaded_filename),
os.path.normpath(
os.path.join(os.environ["SYSTEMROOT"], "SysWOW64")
),
):
continue
if r"windows\winsxs" in loaded_filename:
continue
if loaded_filename.startswith(current_dir):
continue
if loaded_filename.startswith(os.path.abspath(current_dir)):
continue
if loaded_filename.startswith("/etc/"):
continue
if loaded_filename.startswith("/proc/") or loaded_filename == "/proc":
continue
if loaded_filename.startswith("/dev/"):
continue
if loaded_filename.startswith("/tmp/"):
continue
if loaded_filename.startswith("/run/"):
continue
if loaded_filename.startswith("/usr/lib/locale/"):
continue
if loaded_filename.startswith("/usr/share/locale/"):
continue
if loaded_filename.startswith("/usr/share/X11/locale/"):
continue
# Themes may of course be loaded.
if loaded_filename.startswith("/usr/share/themes"):
continue
if "gtk" in loaded_filename and "/engines/" in loaded_filename:
continue
if loaded_filename in (
"/usr",
"/usr/local",
"/usr/local/lib",
"/usr/share",
"/usr/local/share",
"/usr/lib64",
):
continue
# TCL/tk for tkinter for non-Windows is OK.
if loaded_filename.startswith(
(
"/usr/lib/tcltk/",
"/usr/share/tcltk/",
"/usr/lib/tcl/",
"/usr/lib64/tcl/",
)
):
continue
if loaded_filename in (
"/usr/lib/tcltk",
"/usr/share/tcltk",
"/usr/lib/tcl",
"/usr/lib64/tcl",
):
continue
if loaded_filename in (
"/lib",
"/lib64",
"/lib/sse2",
"/lib/tls",
"/lib64/tls",
"/usr/lib/sse2",
"/usr/lib/tls",
"/usr/lib64/tls",
):
continue
if loaded_filename in ("/usr/share/tcl8.6", "/usr/share/tcl8.5"):
continue
if loaded_filename in (
"/usr/share/tcl8.6/init.tcl",
"/usr/share/tcl8.5/init.tcl",
):
continue
if loaded_filename in (
"/usr/share/tcl8.6/encoding",
"/usr/share/tcl8.5/encoding",
):
continue
# System SSL config on Linux. TODO: Should this not be included and
# read from dist folder.
if loaded_basename == "openssl.cnf":
continue
# Taking these from system is harmless and desirable
if loaded_basename.startswith(("libz.so", "libgcc_s.so")):
continue
# System C libraries are to be expected.
if loaded_basename.startswith(
(
"ld-linux-x86-64.so",
"libc.so.",
"libpthread.so.",
"libm.so.",
"libdl.so.",
"libBrokenLocale.so.",
"libSegFault.so",
"libanl.so.",
"libcidn.so.",
"libcrypt.so.",
"libmemusage.so",
"libmvec.so.",
"libnsl.so.",
"libnss_compat.so.",
"libnss_db.so.",
"libnss_dns.so.",
"libnss_files.so.",
"libnss_hesiod.so.",
"libnss_nis.so.",
"libnss_nisplus.so.",
"libpcprofile.so",
"libresolv.so.",
"librt.so.",
"libthread_db-1.0.so",
"libthread_db.so.",
"libutil.so.",
)
):
continue
# Loaded by C library potentially for DNS lookups.
if loaded_basename.startswith(
(
"libnss_",
"libnsl",
# Some systems load a lot more, this is CentOS 7 on OBS
"libattr.so.",
"libbz2.so.",
"libcap.so.",
"libdw.so.",
"libelf.so.",
"liblzma.so.",
# Some systems load a lot more, this is Fedora 26 on OBS
"libselinux.so.",
"libpcre.so.",
# And this is Fedora 29 on OBS
"libblkid.so.",
"libmount.so.",
"libpcre2-8.so.",
)
):
continue
# Loaded by dtruss on macOS X.
if loaded_filename.startswith("/usr/lib/dtrace/"):
continue
# Loaded by cowbuilder and pbuilder on Debian
if loaded_basename == ".ilist":
continue
if "cowdancer" in loaded_filename:
continue
if "eatmydata" in loaded_filename:
continue
# Loading from home directories is OK too.
if (
loaded_filename.startswith("/home/")
or loaded_filename.startswith("/data/")
or loaded_filename.startswith("/root/")
or loaded_filename in ("/home", "/data", "/root")
):
continue
# For Debian builders, /build is OK too.
if loaded_filename.startswith("/build/") or loaded_filename == "/build":
continue
# TODO: Unclear, loading gconv from filesystem of installed system
# may be OK or not. I think it should be.
if loaded_basename == "gconv-modules.cache":
continue
if "/gconv/" in loaded_filename:
continue
if loaded_basename.startswith("libicu"):
continue
if loaded_filename.startswith("/usr/share/icu/"):
continue
# Loading from caches is OK.
if loaded_filename.startswith("/var/cache/"):
continue
# PySide accesses its directory.
if (
loaded_filename
== "/usr/lib/python" + python_version[:3] + "/dist-packages/PySide"
):
continue
# GTK accesses package directories only.
if (
loaded_filename
== "/usr/lib/python" + python_version[:3] + "/dist-packages/gtk-2.0/gtk"
):
continue
if (
loaded_filename
== "/usr/lib/python" + python_version[:3] + "/dist-packages/glib"
):
continue
if (
loaded_filename
== "/usr/lib/python" + python_version[:3] + "/dist-packages/gtk-2.0/gio"
):
continue
if (
loaded_filename
== "/usr/lib/python" + python_version[:3] + "/dist-packages/gobject"
):
continue
# PyQt5 seems to do this, but won't use contents then.
if loaded_filename in (
"/usr/lib/qt5/plugins",
"/usr/lib/qt5",
"/usr/lib64/qt5/plugins",
"/usr/lib64/qt5",
"/usr/lib/x86_64-linux-gnu/qt5/plugins",
"/usr/lib/x86_64-linux-gnu/qt5",
"/usr/lib/x86_64-linux-gnu",
"/usr/lib",
):
continue
# Can look at these.
if loaded_filename in ("/usr/bin/python3.2mu", "/usr/bin/python3"):
continue
# Current Python executable can actually be a symlink and
# the real executable which it points to will be on the
# loaded_filenames list. This is all fine, let's ignore it.
# Also, because the loaded_filename can be yet another symlink
# (this is weird, but it's true), let's better resolve its real
# path too.
if os.path.realpath(loaded_filename) == os.path.realpath(sys.executable):
continue
# Accessing SE-Linux is OK.
if loaded_filename in ("/sys/fs/selinux", "/selinux"):
continue
# Allow reading time zone info of local system.
if loaded_filename.startswith("/usr/share/zoneinfo/"):
continue
# The access to .pth files has no effect.
if loaded_filename.endswith(".pth"):
continue
# Looking at site-package dir alone is alone.
if loaded_filename.endswith(("site-packages", "dist-packages")):
continue
# QtNetwork insist on doing this it seems.
if loaded_basename.startswith(("libcrypto.so", "libssl.so")):
continue
# macOS uses these:
if loaded_basename in ("libcrypto.1.0.0.dylib", "libssl.1.0.0.dylib"):
continue
# MSVC run time DLLs, seem to sometimes come from system.
if loaded_basename.upper() in ("MSVCRT.DLL", "MSVCR90.DLL"):
continue
my_print("Should not access '%s'." % loaded_filename)
illegal_access = True
if illegal_access:
if os.name != "nt":
my_print("Listing of dist folder:")
os.system("ls -Rla %s" % filename[:-3] + ".dist")
my_print("strace:")
os.system("strace -s4096 -e file %s" % binary_filename)
search_mode.onErrorDetected(1)
removeDirectory(filename[:-3] + ".dist", ignore_errors=True)
if search_mode.abortIfExecuted():
break
search_mode.finish()
if __name__ == "__main__":
main()
| 34.4375 | 96 | 0.50406 |
# indicated.
#
# 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 os
import sys
# Find nuitka package relative to us. The replacement is for POSIX python
# and Windows paths on command line.
sys.path.insert(
0,
os.path.normpath(
os.path.join(
os.path.dirname(os.path.abspath(__file__.replace("\\", os.sep))), "..", ".."
)
),
)
# isort:start
import subprocess
from nuitka.tools.testing.Common import (
compareWithCPython,
createSearchMode,
decideFilenameVersionSkip,
getPythonVendor,
getRuntimeTraceOfLoadedFiles,
hasModule,
my_print,
reportSkip,
setup,
)
from nuitka.tree.SourceReading import readSourceCodeFromFilename
from nuitka.utils.FileOperations import areSamePaths, removeDirectory
from nuitka.utils.Utils import getOS
# checks requirements needed to run each test module, according to the specified special comment
# special comments are in the following formats:
# "# nuitka-skip-unless-expression: expression to be evaluated"
# OR
# "# nuitka-skip-unless-imports: module1,module2,..."
def checkRequirements(filename):
for line in readSourceCodeFromFilename(None, filename).splitlines():
if line.startswith("# nuitka-skip-unless-"):
if line[21:33] == "expression: ":
expression = line[33:]
with open(os.devnull, "w") as devnull:
result = subprocess.call(
(
os.environ["PYTHON"],
"-c",
"import sys, os; sys.exit(not bool(%s))" % expression,
),
stdout=devnull,
stderr=subprocess.STDOUT,
)
if result != 0:
return (False, "Expression '%s' evaluated to false" % expression)
elif line[21:30] == "imports: ":
imports_needed = line[30:].rstrip().split(",")
for i in imports_needed:
if not hasModule(i):
return (
False,
i
+ " not installed for this Python version, but test needs it",
)
# default return value
return (True, "")
def displayError(dirname, filename):
assert dirname is None
my_print("Listing of dist folder:")
if os.name == "nt":
command = "dir /b /s /a:-D %s"
else:
command = "ls -Rla %s"
os.system(command % filename)
def main():
# Complex stuff, even more should become common code though.
# pylint: disable=too-many-branches,too-many-statements
python_version = setup(needs_io_encoding=True)
search_mode = createSearchMode()
for filename in sorted(os.listdir(".")):
if not filename.endswith(".py"):
continue
if not decideFilenameVersionSkip(filename):
continue
active = search_mode.consider(dirname=None, filename=filename)
if not active:
my_print("Skipping", filename)
continue
extra_flags = ["expect_success", "standalone", "remove_output"]
# skip each test if their respective requirements are not met
requirements_met, error_message = checkRequirements(filename)
if not requirements_met:
reportSkip(error_message, ".", filename)
continue
# catch error
elif filename == "Boto3Using.py":
reportSkip("boto3 test not fully working yet", ".", filename)
continue
elif "Idna" in filename:
# For the warnings of Python2.
if python_version.startswith("2"):
extra_flags.append("ignore_stderr")
elif filename == "CtypesUsing.py":
extra_flags.append("plugin_disable:pylint-warnings")
elif filename == "GtkUsing.py":
# Don't test on platforms not supported by current Debian testing, and
if python_version.startswith("2.6"):
reportSkip("irrelevant Python version", ".", filename)
continue
extra_flags.append("ignore_warnings")
elif filename.startswith("Win"):
if os.name != "nt":
reportSkip("Windows only test", ".", filename)
continue
elif filename == "TkInterUsing.py":
if getOS() == "Darwin":
reportSkip("Not working macOS yet", ".", filename)
continue
extra_flags.append("ignore_infos")
extra_flags.append("plugin_enable:tk-inter")
elif filename == "FlaskUsing.py":
extra_flags.append("ignore_warnings")
extra_flags.append("ignore_infos")
elif filename == "NumpyUsing.py":
reportSkip("numpy.test not fully working yet", ".", filename)
continue
elif filename == "PmwUsing.py":
extra_flags.append("plugin_enable:pmw-freezer")
elif filename == "OpenGLUsing.py":
extra_flags.append("ignore_warnings")
elif filename == "PasslibUsing.py":
extra_flags.append("ignore_warnings")
elif filename == "PySideUsing.py":
reportSkip("PySide not supported yet", ".", filename)
continue
if filename.startswith(("PySide", "PyQt")):
if python_version.startswith("2.6"):
reportSkip("irrelevant Python version", ".", filename)
continue
extra_flags.append("ignore_infos")
if getPythonVendor() != "Anaconda":
extra_flags.append("plugin_enable:qt-plugins")
else:
extra_flags.append("ignore_warnings")
my_print("Consider output of recursively compiled program:", filename)
compareWithCPython(
dirname=None,
filename=filename,
extra_flags=extra_flags,
search_mode=search_mode,
needs_2to3=False,
on_error=displayError,
)
# shipped with the standalone executable
found_glibc_libs = []
for dist_filename in os.listdir(os.path.join(filename[:-3] + ".dist")):
if os.path.basename(dist_filename).startswith(
(
"ld-linux-x86-64.so",
"libc.so.",
"libpthread.so.",
"libm.so.",
"libdl.so.",
"libBrokenLocale.so.",
"libSegFault.so",
"libanl.so.",
"libcidn.so.",
"libcrypt.so.",
"libmemusage.so",
"libmvec.so.",
"libnsl.so.",
"libnss_compat.so.",
"libnss_db.so.",
"libnss_dns.so.",
"libnss_files.so.",
"libnss_hesiod.so.",
"libnss_nis.so.",
"libnss_nisplus.so.",
"libpcprofile.so",
"libresolv.so.",
"librt.so.",
"libthread_db-1.0.so",
"libthread_db.so.",
"libutil.so.",
)
):
found_glibc_libs.append(dist_filename)
if found_glibc_libs:
my_print(
"Should not ship glibc libraries with the standalone executable (found %s)"
% found_glibc_libs
)
sys.exit(1)
binary_filename = os.path.join(
filename[:-3] + ".dist", filename[:-3] + (".exe" if os.name == "nt" else "")
)
# Then use "strace" on the result.
loaded_filenames = getRuntimeTraceOfLoadedFiles(binary_filename)
current_dir = os.path.normpath(os.getcwd())
current_dir = os.path.normcase(current_dir)
illegal_access = False
for loaded_filename in loaded_filenames:
loaded_filename = os.path.normpath(loaded_filename)
loaded_filename = os.path.normcase(loaded_filename)
loaded_basename = os.path.basename(loaded_filename)
if os.name == "nt":
if areSamePaths(
os.path.dirname(loaded_filename),
os.path.normpath(
os.path.join(os.environ["SYSTEMROOT"], "System32")
),
):
continue
if areSamePaths(
os.path.dirname(loaded_filename),
os.path.normpath(
os.path.join(os.environ["SYSTEMROOT"], "SysWOW64")
),
):
continue
if r"windows\winsxs" in loaded_filename:
continue
if loaded_filename.startswith(current_dir):
continue
if loaded_filename.startswith(os.path.abspath(current_dir)):
continue
if loaded_filename.startswith("/etc/"):
continue
if loaded_filename.startswith("/proc/") or loaded_filename == "/proc":
continue
if loaded_filename.startswith("/dev/"):
continue
if loaded_filename.startswith("/tmp/"):
continue
if loaded_filename.startswith("/run/"):
continue
if loaded_filename.startswith("/usr/lib/locale/"):
continue
if loaded_filename.startswith("/usr/share/locale/"):
continue
if loaded_filename.startswith("/usr/share/X11/locale/"):
continue
# Themes may of course be loaded.
if loaded_filename.startswith("/usr/share/themes"):
continue
if "gtk" in loaded_filename and "/engines/" in loaded_filename:
continue
if loaded_filename in (
"/usr",
"/usr/local",
"/usr/local/lib",
"/usr/share",
"/usr/local/share",
"/usr/lib64",
):
continue
# TCL/tk for tkinter for non-Windows is OK.
if loaded_filename.startswith(
(
"/usr/lib/tcltk/",
"/usr/share/tcltk/",
"/usr/lib/tcl/",
"/usr/lib64/tcl/",
)
):
continue
if loaded_filename in (
"/usr/lib/tcltk",
"/usr/share/tcltk",
"/usr/lib/tcl",
"/usr/lib64/tcl",
):
continue
if loaded_filename in (
"/lib",
"/lib64",
"/lib/sse2",
"/lib/tls",
"/lib64/tls",
"/usr/lib/sse2",
"/usr/lib/tls",
"/usr/lib64/tls",
):
continue
if loaded_filename in ("/usr/share/tcl8.6", "/usr/share/tcl8.5"):
continue
if loaded_filename in (
"/usr/share/tcl8.6/init.tcl",
"/usr/share/tcl8.5/init.tcl",
):
continue
if loaded_filename in (
"/usr/share/tcl8.6/encoding",
"/usr/share/tcl8.5/encoding",
):
continue
# System SSL config on Linux. TODO: Should this not be included and
# read from dist folder.
if loaded_basename == "openssl.cnf":
continue
# Taking these from system is harmless and desirable
if loaded_basename.startswith(("libz.so", "libgcc_s.so")):
continue
# System C libraries are to be expected.
if loaded_basename.startswith(
(
"ld-linux-x86-64.so",
"libc.so.",
"libpthread.so.",
"libm.so.",
"libdl.so.",
"libBrokenLocale.so.",
"libSegFault.so",
"libanl.so.",
"libcidn.so.",
"libcrypt.so.",
"libmemusage.so",
"libmvec.so.",
"libnsl.so.",
"libnss_compat.so.",
"libnss_db.so.",
"libnss_dns.so.",
"libnss_files.so.",
"libnss_hesiod.so.",
"libnss_nis.so.",
"libnss_nisplus.so.",
"libpcprofile.so",
"libresolv.so.",
"librt.so.",
"libthread_db-1.0.so",
"libthread_db.so.",
"libutil.so.",
)
):
continue
# Loaded by C library potentially for DNS lookups.
if loaded_basename.startswith(
(
"libnss_",
"libnsl",
# Some systems load a lot more, this is CentOS 7 on OBS
"libattr.so.",
"libbz2.so.",
"libcap.so.",
"libdw.so.",
"libelf.so.",
"liblzma.so.",
# Some systems load a lot more, this is Fedora 26 on OBS
"libselinux.so.",
"libpcre.so.",
# And this is Fedora 29 on OBS
"libblkid.so.",
"libmount.so.",
"libpcre2-8.so.",
)
):
continue
# Loaded by dtruss on macOS X.
if loaded_filename.startswith("/usr/lib/dtrace/"):
continue
# Loaded by cowbuilder and pbuilder on Debian
if loaded_basename == ".ilist":
continue
if "cowdancer" in loaded_filename:
continue
if "eatmydata" in loaded_filename:
continue
# Loading from home directories is OK too.
if (
loaded_filename.startswith("/home/")
or loaded_filename.startswith("/data/")
or loaded_filename.startswith("/root/")
or loaded_filename in ("/home", "/data", "/root")
):
continue
# For Debian builders, /build is OK too.
if loaded_filename.startswith("/build/") or loaded_filename == "/build":
continue
# TODO: Unclear, loading gconv from filesystem of installed system
# may be OK or not. I think it should be.
if loaded_basename == "gconv-modules.cache":
continue
if "/gconv/" in loaded_filename:
continue
if loaded_basename.startswith("libicu"):
continue
if loaded_filename.startswith("/usr/share/icu/"):
continue
# Loading from caches is OK.
if loaded_filename.startswith("/var/cache/"):
continue
# PySide accesses its directory.
if (
loaded_filename
== "/usr/lib/python" + python_version[:3] + "/dist-packages/PySide"
):
continue
# GTK accesses package directories only.
if (
loaded_filename
== "/usr/lib/python" + python_version[:3] + "/dist-packages/gtk-2.0/gtk"
):
continue
if (
loaded_filename
== "/usr/lib/python" + python_version[:3] + "/dist-packages/glib"
):
continue
if (
loaded_filename
== "/usr/lib/python" + python_version[:3] + "/dist-packages/gtk-2.0/gio"
):
continue
if (
loaded_filename
== "/usr/lib/python" + python_version[:3] + "/dist-packages/gobject"
):
continue
# PyQt5 seems to do this, but won't use contents then.
if loaded_filename in (
"/usr/lib/qt5/plugins",
"/usr/lib/qt5",
"/usr/lib64/qt5/plugins",
"/usr/lib64/qt5",
"/usr/lib/x86_64-linux-gnu/qt5/plugins",
"/usr/lib/x86_64-linux-gnu/qt5",
"/usr/lib/x86_64-linux-gnu",
"/usr/lib",
):
continue
if loaded_filename in ("/usr/bin/python3.2mu", "/usr/bin/python3"):
continue
# Also, because the loaded_filename can be yet another symlink
# (this is weird, but it's true), let's better resolve its real
# path too.
if os.path.realpath(loaded_filename) == os.path.realpath(sys.executable):
continue
# Accessing SE-Linux is OK.
if loaded_filename in ("/sys/fs/selinux", "/selinux"):
continue
# Allow reading time zone info of local system.
if loaded_filename.startswith("/usr/share/zoneinfo/"):
continue
# The access to .pth files has no effect.
if loaded_filename.endswith(".pth"):
continue
# Looking at site-package dir alone is alone.
if loaded_filename.endswith(("site-packages", "dist-packages")):
continue
# QtNetwork insist on doing this it seems.
if loaded_basename.startswith(("libcrypto.so", "libssl.so")):
continue
# macOS uses these:
if loaded_basename in ("libcrypto.1.0.0.dylib", "libssl.1.0.0.dylib"):
continue
# MSVC run time DLLs, seem to sometimes come from system.
if loaded_basename.upper() in ("MSVCRT.DLL", "MSVCR90.DLL"):
continue
my_print("Should not access '%s'." % loaded_filename)
illegal_access = True
if illegal_access:
if os.name != "nt":
my_print("Listing of dist folder:")
os.system("ls -Rla %s" % filename[:-3] + ".dist")
my_print("strace:")
os.system("strace -s4096 -e file %s" % binary_filename)
search_mode.onErrorDetected(1)
removeDirectory(filename[:-3] + ".dist", ignore_errors=True)
if search_mode.abortIfExecuted():
break
search_mode.finish()
if __name__ == "__main__":
main()
| true | true |
1c2baf6f26f1c7e0daf213dfbbb84217a5ff2939 | 1,025 | py | Python | tests_app/tests/functional/routers/extended_default_router/tests.py | sahithi-rp/drf-extensions | 00712396be979aaa5a86246bee39284b5e5e8d71 | [
"MIT"
] | null | null | null | tests_app/tests/functional/routers/extended_default_router/tests.py | sahithi-rp/drf-extensions | 00712396be979aaa5a86246bee39284b5e5e8d71 | [
"MIT"
] | null | null | null | tests_app/tests/functional/routers/extended_default_router/tests.py | sahithi-rp/drf-extensions | 00712396be979aaa5a86246bee39284b5e5e8d71 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from django.test import override_settings
from django.urls import NoReverseMatch
from rest_framework_extensions.test import APITestCase
@override_settings(ROOT_URLCONF='tests_app.tests.functional.routers.extended_default_router.urls')
class ExtendedDefaultRouterTestBehaviour(APITestCase):
def test_index_page(self):
try:
response = self.client.get('/')
except NoReverseMatch:
issue = 'https://github.com/chibisov/drf-extensions/issues/14'
self.fail('DefaultRouter tries to reverse nested routes and breaks with error. NoReverseMatch should be '
'handled for nested routes. They must be excluded from index page. ' + issue)
self.assertEqual(response.status_code, 200)
expected = {
'users': 'http://testserver/users/',
'groups': 'http://testserver/groups/',
'permissions': 'http://testserver/permissions/',
}
self.assertEqual(response.data, expected)
| 39.423077 | 117 | 0.676098 |
from django.test import override_settings
from django.urls import NoReverseMatch
from rest_framework_extensions.test import APITestCase
@override_settings(ROOT_URLCONF='tests_app.tests.functional.routers.extended_default_router.urls')
class ExtendedDefaultRouterTestBehaviour(APITestCase):
def test_index_page(self):
try:
response = self.client.get('/')
except NoReverseMatch:
issue = 'https://github.com/chibisov/drf-extensions/issues/14'
self.fail('DefaultRouter tries to reverse nested routes and breaks with error. NoReverseMatch should be '
'handled for nested routes. They must be excluded from index page. ' + issue)
self.assertEqual(response.status_code, 200)
expected = {
'users': 'http://testserver/users/',
'groups': 'http://testserver/groups/',
'permissions': 'http://testserver/permissions/',
}
self.assertEqual(response.data, expected)
| true | true |
1c2baf708977f783b57c7c1667b3d161745384f8 | 2,577 | py | Python | VoiceAssistant/Project_Basic_struct/VoiceAssistant_main.py | TheRealMilesLee/Python | d145c848a7ba76e8e523e4fe06e2a0add7e2fae1 | [
"MIT"
] | 1 | 2018-12-05T11:04:47.000Z | 2018-12-05T11:04:47.000Z | VoiceAssistant/Project_Basic_struct/VoiceAssistant_main.py | MarkHooland/Python | d145c848a7ba76e8e523e4fe06e2a0add7e2fae1 | [
"MIT"
] | null | null | null | VoiceAssistant/Project_Basic_struct/VoiceAssistant_main.py | MarkHooland/Python | d145c848a7ba76e8e523e4fe06e2a0add7e2fae1 | [
"MIT"
] | null | null | null | from speakListen import *
from websiteWork import *
from textRead import *
from dictator import *
from menu import *
from speechtotext import *
from TextTospeech import *
def main():
start = 0
end = 0
if start == 0:
print("\nSay \"Hello Python\" to activate the Voice Assistant!")
start += 1
while True:
q = short_hear().lower()
if "close" in q:
greet("end")
exit(0)
if "hello python" in q:
greet("start")
print_menu()
while True:
query = hear().lower()
if "close" in query:
greet("end")
end += 1
return 0
elif "text to speech" in query:
tts()
time.sleep(4)
elif "search on google" in query or "search google" in query or "google" in query:
google_search()
time.sleep(10)
elif "search on wikipedia" in query or "search wikipedia" in query or "wikipedia" in query:
wiki_search()
time.sleep(10)
elif "word" in query:
ms_word()
time.sleep(5)
elif "book" in query:
pdf_read()
time.sleep(10)
elif "speech to text" in query:
big_text()
time.sleep(5)
else:
print("I could'nt understand what you just said!")
speak("I could'nt understand what you just said!")
print("\nDo you want to continue? if yes then say " + Fore.YELLOW + "\"YES\"" + Fore.WHITE + " else say " + Fore.YELLOW + "\"CLOSE PYTHON\"")
speak("Do you want to continue? if yes then say YES else say CLOSE PYTHON")
qry = hear().lower()
if "yes" in qry:
print_menu()
elif "close" in qry:
greet("end")
return 0
else:
speak("You didn't say a valid command. So I am continuing!")
continue
elif "close" in q:
return 0
else:
continue
main()
| 32.620253 | 158 | 0.407451 | from speakListen import *
from websiteWork import *
from textRead import *
from dictator import *
from menu import *
from speechtotext import *
from TextTospeech import *
def main():
start = 0
end = 0
if start == 0:
print("\nSay \"Hello Python\" to activate the Voice Assistant!")
start += 1
while True:
q = short_hear().lower()
if "close" in q:
greet("end")
exit(0)
if "hello python" in q:
greet("start")
print_menu()
while True:
query = hear().lower()
if "close" in query:
greet("end")
end += 1
return 0
elif "text to speech" in query:
tts()
time.sleep(4)
elif "search on google" in query or "search google" in query or "google" in query:
google_search()
time.sleep(10)
elif "search on wikipedia" in query or "search wikipedia" in query or "wikipedia" in query:
wiki_search()
time.sleep(10)
elif "word" in query:
ms_word()
time.sleep(5)
elif "book" in query:
pdf_read()
time.sleep(10)
elif "speech to text" in query:
big_text()
time.sleep(5)
else:
print("I could'nt understand what you just said!")
speak("I could'nt understand what you just said!")
print("\nDo you want to continue? if yes then say " + Fore.YELLOW + "\"YES\"" + Fore.WHITE + " else say " + Fore.YELLOW + "\"CLOSE PYTHON\"")
speak("Do you want to continue? if yes then say YES else say CLOSE PYTHON")
qry = hear().lower()
if "yes" in qry:
print_menu()
elif "close" in qry:
greet("end")
return 0
else:
speak("You didn't say a valid command. So I am continuing!")
continue
elif "close" in q:
return 0
else:
continue
main()
| true | true |
1c2bafbebe89cb5ab07084b754d3e2b0ca72021c | 4,004 | py | Python | tests/unit/clients/python/test_client.py | facebbook/jina | e8079af3d58f1de0f51f8aef6cdf1eb3d87a9873 | [
"Apache-2.0"
] | null | null | null | tests/unit/clients/python/test_client.py | facebbook/jina | e8079af3d58f1de0f51f8aef6cdf1eb3d87a9873 | [
"Apache-2.0"
] | 2 | 2021-02-15T01:40:38.000Z | 2021-02-15T02:00:21.000Z | tests/unit/clients/python/test_client.py | facebbook/jina | e8079af3d58f1de0f51f8aef6cdf1eb3d87a9873 | [
"Apache-2.0"
] | null | null | null | import os
import time
import pytest
import requests
from jina.clients import Client
from jina.clients.sugary_io import _input_files
from jina.excepts import BadClientInput
from jina.flow import Flow
from jina import helper
from jina.parsers import set_gateway_parser
from jina.peapods import Pea
from jina.proto.jina_pb2 import DocumentProto
cur_dir = os.path.dirname(os.path.abspath(__file__))
@pytest.fixture(scope='function')
def flow():
return Flow(rest_api=False).add()
@pytest.fixture(scope='function')
def flow_with_rest_api_enabled():
return Flow(rest_api=True).add()
@pytest.fixture(scope='function')
def test_img_1():
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAA2ElEQVR4nADIADf/AxWcWRUeCEeBO68T3u1qLWarHqMaxDnxhAEaLh0Ssu6ZGfnKcjP4CeDLoJok3o4aOPYAJocsjktZfo4Z7Q/WR1UTgppAAdguAhR+AUm9AnqRH2jgdBZ0R+kKxAFoAME32BL7fwQbcLzhw+dXMmY9BS9K8EarXyWLH8VYK1MACkxlLTY4Eh69XfjpROqjE7P0AeBx6DGmA8/lRRlTCmPkL196pC0aWBkVs2wyjqb/LABVYL8Xgeomjl3VtEMxAeaUrGvnIawVh/oBAAD///GwU6v3yCoVAAAAAElFTkSuQmCC'
@pytest.fixture(scope='function')
def test_img_2():
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAA2ElEQVR4nADIADf/AvdGjTZeOlQq07xSYPgJjlWRwfWEBx2+CgAVrPrP+O5ghhOa+a0cocoWnaMJFAsBuCQCgiJOKDBcIQTiLieOrPD/cp/6iZ/Iu4HqAh5dGzggIQVJI3WqTxwVTDjs5XJOy38AlgHoaKgY+xJEXeFTyR7FOfF7JNWjs3b8evQE6B2dTDvQZx3n3Rz6rgOtVlaZRLvR9geCAxuY3G+0mepEAhrTISES3bwPWYYi48OUrQOc//IaJeij9xZGGmDIG9kc73fNI7eA8VMBAAD//0SxXMMT90UdAAAAAElFTkSuQmCC'
@pytest.mark.parametrize(
'inputs', [iter([b'1234', b'45467']), iter([DocumentProto(), DocumentProto()])]
)
def test_check_input_success(inputs):
Client.check_input(inputs)
@pytest.mark.parametrize(
'inputs', [iter([list(), list(), [12, 2, 3]]), iter([set(), set()])]
)
def test_check_input_fail(inputs):
with pytest.raises(BadClientInput):
Client.check_input(inputs)
@pytest.mark.parametrize(
'port_expose, route, status_code',
[(helper.random_port(), '/status', 200), (helper.random_port(), '/api/ass', 405)],
)
def test_gateway_ready(port_expose, route, status_code):
p = set_gateway_parser().parse_args(
['--port-expose', str(port_expose), '--runtime-cls', 'RESTRuntime']
)
with Pea(p):
time.sleep(0.5)
a = requests.get(f'http://0.0.0.0:{p.port_expose}{route}')
assert a.status_code == status_code
def test_gateway_index(flow_with_rest_api_enabled, test_img_1, test_img_2):
with flow_with_rest_api_enabled:
time.sleep(0.5)
r = requests.post(
f'http://0.0.0.0:{flow_with_rest_api_enabled.port_expose}/api/index',
json={'data': [test_img_1, test_img_2]},
)
assert r.status_code == 200
resp = r.json()
assert 'index' in resp
assert len(resp['index']['docs']) == 2
assert resp['index']['docs'][0]['uri'] == test_img_1
@pytest.mark.parametrize('restful', [False, True])
def test_mime_type(restful):
f = Flow(restful=restful).add(uses='- !URI2Buffer {}')
def validate_mime_type(req):
for d in req.index.docs:
assert d.mime_type == 'text/x-python'
with f:
f.index(_input_files('*.py'), validate_mime_type)
@pytest.mark.parametrize('func_name', ['index', 'search'])
@pytest.mark.parametrize('restful', [False, True])
def test_client_ndjson(restful, mocker, func_name):
with Flow(restful=restful).add() as f, open(
os.path.join(cur_dir, 'docs.jsonlines')
) as fp:
mock = mocker.Mock()
getattr(f, f'{func_name}_ndjson')(fp, on_done=mock)
mock.assert_called_once()
@pytest.mark.parametrize('func_name', ['index', 'search'])
@pytest.mark.parametrize('restful', [False, True])
def test_client_csv(restful, mocker, func_name):
with Flow(restful=restful).add() as f, open(
os.path.join(cur_dir, 'docs.csv')
) as fp:
mock = mocker.Mock()
getattr(f, f'{func_name}_csv')(fp, on_done=mock)
mock.assert_called_once()
| 35.122807 | 399 | 0.724276 | import os
import time
import pytest
import requests
from jina.clients import Client
from jina.clients.sugary_io import _input_files
from jina.excepts import BadClientInput
from jina.flow import Flow
from jina import helper
from jina.parsers import set_gateway_parser
from jina.peapods import Pea
from jina.proto.jina_pb2 import DocumentProto
cur_dir = os.path.dirname(os.path.abspath(__file__))
@pytest.fixture(scope='function')
def flow():
return Flow(rest_api=False).add()
@pytest.fixture(scope='function')
def flow_with_rest_api_enabled():
return Flow(rest_api=True).add()
@pytest.fixture(scope='function')
def test_img_1():
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAA2ElEQVR4nADIADf/AxWcWRUeCEeBO68T3u1qLWarHqMaxDnxhAEaLh0Ssu6ZGfnKcjP4CeDLoJok3o4aOPYAJocsjktZfo4Z7Q/WR1UTgppAAdguAhR+AUm9AnqRH2jgdBZ0R+kKxAFoAME32BL7fwQbcLzhw+dXMmY9BS9K8EarXyWLH8VYK1MACkxlLTY4Eh69XfjpROqjE7P0AeBx6DGmA8/lRRlTCmPkL196pC0aWBkVs2wyjqb/LABVYL8Xgeomjl3VtEMxAeaUrGvnIawVh/oBAAD///GwU6v3yCoVAAAAAElFTkSuQmCC'
@pytest.fixture(scope='function')
def test_img_2():
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAA2ElEQVR4nADIADf/AvdGjTZeOlQq07xSYPgJjlWRwfWEBx2+CgAVrPrP+O5ghhOa+a0cocoWnaMJFAsBuCQCgiJOKDBcIQTiLieOrPD/cp/6iZ/Iu4HqAh5dGzggIQVJI3WqTxwVTDjs5XJOy38AlgHoaKgY+xJEXeFTyR7FOfF7JNWjs3b8evQE6B2dTDvQZx3n3Rz6rgOtVlaZRLvR9geCAxuY3G+0mepEAhrTISES3bwPWYYi48OUrQOc//IaJeij9xZGGmDIG9kc73fNI7eA8VMBAAD//0SxXMMT90UdAAAAAElFTkSuQmCC'
@pytest.mark.parametrize(
'inputs', [iter([b'1234', b'45467']), iter([DocumentProto(), DocumentProto()])]
)
def test_check_input_success(inputs):
Client.check_input(inputs)
@pytest.mark.parametrize(
'inputs', [iter([list(), list(), [12, 2, 3]]), iter([set(), set()])]
)
def test_check_input_fail(inputs):
with pytest.raises(BadClientInput):
Client.check_input(inputs)
@pytest.mark.parametrize(
'port_expose, route, status_code',
[(helper.random_port(), '/status', 200), (helper.random_port(), '/api/ass', 405)],
)
def test_gateway_ready(port_expose, route, status_code):
p = set_gateway_parser().parse_args(
['--port-expose', str(port_expose), '--runtime-cls', 'RESTRuntime']
)
with Pea(p):
time.sleep(0.5)
a = requests.get(f'http://0.0.0.0:{p.port_expose}{route}')
assert a.status_code == status_code
def test_gateway_index(flow_with_rest_api_enabled, test_img_1, test_img_2):
with flow_with_rest_api_enabled:
time.sleep(0.5)
r = requests.post(
f'http://0.0.0.0:{flow_with_rest_api_enabled.port_expose}/api/index',
json={'data': [test_img_1, test_img_2]},
)
assert r.status_code == 200
resp = r.json()
assert 'index' in resp
assert len(resp['index']['docs']) == 2
assert resp['index']['docs'][0]['uri'] == test_img_1
@pytest.mark.parametrize('restful', [False, True])
def test_mime_type(restful):
f = Flow(restful=restful).add(uses='- !URI2Buffer {}')
def validate_mime_type(req):
for d in req.index.docs:
assert d.mime_type == 'text/x-python'
with f:
f.index(_input_files('*.py'), validate_mime_type)
@pytest.mark.parametrize('func_name', ['index', 'search'])
@pytest.mark.parametrize('restful', [False, True])
def test_client_ndjson(restful, mocker, func_name):
with Flow(restful=restful).add() as f, open(
os.path.join(cur_dir, 'docs.jsonlines')
) as fp:
mock = mocker.Mock()
getattr(f, f'{func_name}_ndjson')(fp, on_done=mock)
mock.assert_called_once()
@pytest.mark.parametrize('func_name', ['index', 'search'])
@pytest.mark.parametrize('restful', [False, True])
def test_client_csv(restful, mocker, func_name):
with Flow(restful=restful).add() as f, open(
os.path.join(cur_dir, 'docs.csv')
) as fp:
mock = mocker.Mock()
getattr(f, f'{func_name}_csv')(fp, on_done=mock)
mock.assert_called_once()
| true | true |
1c2bafd39110a18198ed8febd96622814ea3167d | 4,565 | py | Python | Python/Host/easy_lidar.py | henrymidles/LidarBot | f67b5ed77671abad7267a86f425192fc6d5aad42 | [
"MIT"
] | null | null | null | Python/Host/easy_lidar.py | henrymidles/LidarBot | f67b5ed77671abad7267a86f425192fc6d5aad42 | [
"MIT"
] | null | null | null | Python/Host/easy_lidar.py | henrymidles/LidarBot | f67b5ed77671abad7267a86f425192fc6d5aad42 | [
"MIT"
] | null | null | null | import time
import random
import struct
import serial
class Lidar():
def __init__(self, port='/dev/ttyUSB0'):
self.lidar = None
self.port = port
self.baud = 128000
def start(self):
self.lidar = serial.Serial(self.port, self.baud)
def stop(self):
if self.lidar != None:
self.lidar.close()
self.lidar = None
def start_scan(self):
self.send_msg([0xA5, 0x60])
def send_msg(self, msg):
if self.lidar != None:
self.lidar.write(bytearray(msg))
def get_data_list(self):
if self.lidar != None:
while self.lidar.in_waiting == 0:
time.sleep(0.001)
return list(self.lidar.read(self.lidar.in_waiting))
else:
return None
def get_data_bytes(self):
if self.lidar != None:
while self.lidar.in_waiting == 0:
time.sleep(0.001)
return self.lidar.read(self.lidar.in_waiting)
else:
return None
if __name__ == "__main__":
lidar_s = serial.Serial('/dev/ttyUSB0', 128000)
send_msg(lidar_s, [0xA5, 0x00], 5)
send_msg(lidar_s, [0xA5, 0x65], 5)
send_msg(lidar_s, [0xA5, 0x00], 5)
send_msg(lidar_s, [0xA5, 0x65], 5)
send_msg(lidar_s, [0xA5, 0x92], 5)
timer = time.time() + 0.1
while time.time() < timer:
if lidar_s.in_waiting > 0:
print(lidar_s.read())
send_msg(lidar_s, [0xA5, 0x90], 5)
timer = time.time() + 0.1
while time.time() < timer:
if lidar_s.in_waiting > 0:
print(lidar_s.read())
send_msg(lidar_s, [0xA5, 0x60], 1)
timer = time.time() + 10
last_rx_time = time.time()
buff = b''
while time.time() < timer:
if lidar_s.in_waiting > 0:
newbs = list(lidar_s.read(lidar_s.in_waiting))
#print(newbs)
try:
idx = newbs.index(170)
idx2 = newbs.index(85)
idx3 = newbs.index(1)
if idx2 == idx+1 and idx3 == idx2+1:
rx_time = time.time()
print(rx_time - last_rx_time)
last_rx_time = rx_time
#print(f"{idx} , {idx2} , {idx3}")
except ValueError:
pass
# From: https://github.com/YDLIDAR/YDLidar-SDK/blob/master/core/common/ydlidar_protocol.h
#define LIDAR_CMD_STOP 0x65
#define LIDAR_CMD_SCAN 0x60
#define LIDAR_CMD_FORCE_SCAN 0x61
#define LIDAR_CMD_RESET 0x80
#define LIDAR_CMD_FORCE_STOP 0x00
#define LIDAR_CMD_GET_EAI 0x55
#define LIDAR_CMD_GET_DEVICE_INFO 0x90
#define LIDAR_CMD_GET_DEVICE_HEALTH 0x92
#define LIDAR_ANS_TYPE_DEVINFO 0x4
#define LIDAR_ANS_TYPE_DEVHEALTH 0x6
#define LIDAR_CMD_SYNC_BYTE 0xA5
#define LIDAR_CMDFLAG_HAS_PAYLOAD 0x80
#define LIDAR_ANS_SYNC_BYTE1 0xA5
#define LIDAR_ANS_SYNC_BYTE2 0x5A
#define LIDAR_ANS_TYPE_MEASUREMENT 0x81
#define LIDAR_RESP_MEASUREMENT_SYNCBIT (0x1<<0)
#define LIDAR_RESP_MEASUREMENT_QUALITY_SHIFT 2
#define LIDAR_RESP_MEASUREMENT_CHECKBIT (0x1<<0)
#define LIDAR_RESP_MEASUREMENT_ANGLE_SHIFT 1
#define LIDAR_RESP_MEASUREMENT_DISTANCE_SHIFT 2
#define LIDAR_RESP_MEASUREMENT_ANGLE_SAMPLE_SHIFT 8
#define LIDAR_CMD_RUN_POSITIVE 0x06
#define LIDAR_CMD_RUN_INVERSION 0x07
#define LIDAR_CMD_SET_AIMSPEED_ADDMIC 0x09
#define LIDAR_CMD_SET_AIMSPEED_DISMIC 0x0A
#define LIDAR_CMD_SET_AIMSPEED_ADD 0x0B
#define LIDAR_CMD_SET_AIMSPEED_DIS 0x0C
#define LIDAR_CMD_GET_AIMSPEED 0x0D
#define LIDAR_CMD_SET_SAMPLING_RATE 0xD0
#define LIDAR_CMD_GET_SAMPLING_RATE 0xD1
#define LIDAR_STATUS_OK 0x0
#define LIDAR_STATUS_WARNING 0x1
#define LIDAR_STATUS_ERROR 0x2
#define LIDAR_CMD_ENABLE_LOW_POWER 0x01
#define LIDAR_CMD_DISABLE_LOW_POWER 0x02
#define LIDAR_CMD_STATE_MODEL_MOTOR 0x05
#define LIDAR_CMD_ENABLE_CONST_FREQ 0x0E
#define LIDAR_CMD_DISABLE_CONST_FREQ 0x0F
#define LIDAR_CMD_GET_OFFSET_ANGLE 0x93
#define LIDAR_CMD_SAVE_SET_EXPOSURE 0x94
#define LIDAR_CMD_SET_LOW_EXPOSURE 0x95
#define LIDAR_CMD_ADD_EXPOSURE 0x96
#define LIDAR_CMD_DIS_EXPOSURE 0x97
#define LIDAR_CMD_SET_HEART_BEAT 0xD9 | 34.323308 | 89 | 0.614677 | import time
import random
import struct
import serial
class Lidar():
def __init__(self, port='/dev/ttyUSB0'):
self.lidar = None
self.port = port
self.baud = 128000
def start(self):
self.lidar = serial.Serial(self.port, self.baud)
def stop(self):
if self.lidar != None:
self.lidar.close()
self.lidar = None
def start_scan(self):
self.send_msg([0xA5, 0x60])
def send_msg(self, msg):
if self.lidar != None:
self.lidar.write(bytearray(msg))
def get_data_list(self):
if self.lidar != None:
while self.lidar.in_waiting == 0:
time.sleep(0.001)
return list(self.lidar.read(self.lidar.in_waiting))
else:
return None
def get_data_bytes(self):
if self.lidar != None:
while self.lidar.in_waiting == 0:
time.sleep(0.001)
return self.lidar.read(self.lidar.in_waiting)
else:
return None
if __name__ == "__main__":
lidar_s = serial.Serial('/dev/ttyUSB0', 128000)
send_msg(lidar_s, [0xA5, 0x00], 5)
send_msg(lidar_s, [0xA5, 0x65], 5)
send_msg(lidar_s, [0xA5, 0x00], 5)
send_msg(lidar_s, [0xA5, 0x65], 5)
send_msg(lidar_s, [0xA5, 0x92], 5)
timer = time.time() + 0.1
while time.time() < timer:
if lidar_s.in_waiting > 0:
print(lidar_s.read())
send_msg(lidar_s, [0xA5, 0x90], 5)
timer = time.time() + 0.1
while time.time() < timer:
if lidar_s.in_waiting > 0:
print(lidar_s.read())
send_msg(lidar_s, [0xA5, 0x60], 1)
timer = time.time() + 10
last_rx_time = time.time()
buff = b''
while time.time() < timer:
if lidar_s.in_waiting > 0:
newbs = list(lidar_s.read(lidar_s.in_waiting))
try:
idx = newbs.index(170)
idx2 = newbs.index(85)
idx3 = newbs.index(1)
if idx2 == idx+1 and idx3 == idx2+1:
rx_time = time.time()
print(rx_time - last_rx_time)
last_rx_time = rx_time
except ValueError:
pass
| true | true |
1c2bb138f1d57f3a7862052c16931f2e0822b233 | 704 | py | Python | breathe/path_handler.py | 2bndy5/breathe | d3022c1017ff44575b6cec7f017b68719d3e4480 | [
"BSD-3-Clause"
] | null | null | null | breathe/path_handler.py | 2bndy5/breathe | d3022c1017ff44575b6cec7f017b68719d3e4480 | [
"BSD-3-Clause"
] | null | null | null | breathe/path_handler.py | 2bndy5/breathe | d3022c1017ff44575b6cec7f017b68719d3e4480 | [
"BSD-3-Clause"
] | null | null | null | from sphinx.application import Sphinx
import os
def includes_directory(file_path: str):
# Check for backslash or forward slash as we don't know what platform we're on and sometimes
# the doxygen paths will have forward slash even on Windows.
return bool(file_path.count("\\")) or bool(file_path.count("/"))
def resolve_path(app: Sphinx, directory: str, filename: str):
"""Returns a full path to the filename in the given directory assuming that if the directory
path is relative, then it is relative to the conf.py directory.
"""
# os.path.join does the appropriate handling if _project_path is an absolute path
return os.path.join(app.confdir, directory, filename)
| 37.052632 | 96 | 0.738636 | from sphinx.application import Sphinx
import os
def includes_directory(file_path: str):
return bool(file_path.count("\\")) or bool(file_path.count("/"))
def resolve_path(app: Sphinx, directory: str, filename: str):
return os.path.join(app.confdir, directory, filename)
| true | true |
1c2bb18f2deebaaeae20a1d1afaae3aec8d4710f | 1,674 | py | Python | setup.py | xu183255/planetutils | 07554a4f7d2f30c8a3967d732997f5e1076205d0 | [
"MIT"
] | null | null | null | setup.py | xu183255/planetutils | 07554a4f7d2f30c8a3967d732997f5e1076205d0 | [
"MIT"
] | null | null | null | setup.py | xu183255/planetutils | 07554a4f7d2f30c8a3967d732997f5e1076205d0 | [
"MIT"
] | null | null | null | from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(name='interline-planetutils',
version='0.4.8',
description='Interline PlanetUtils',
long_description=long_description,
url='https://github.com/interline-io/planetutils',
author='Ian Rees',
author_email='ian@interline.io',
license='MIT',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
install_requires=['future', 'requests','boto3'], #, 'osmium'
tests_require=['nose'],
test_suite = 'nose.collector',
entry_points={
'console_scripts': [
'osm_planet_update=planetutils.osm_planet_update:main',
'osm_planet_extract=planetutils.osm_planet_extract:main',
'osm_planet_get_timestamp=planetutils.osm_planet_get_timestamp:main',
'osm_extract_download=planetutils.osm_extract_download:main',
'elevation_tile_download=planetutils.elevation_tile_download:main',
'elevation_tile_merge=planetutils.elevation_tile_merge:main',
'valhalla_tilepack_download=planetutils.tilepack_download:main',
'valhalla_tilepack_list=planetutils.tilepack_list:main'
],
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.7'
]
)
| 38.930233 | 81 | 0.685185 | from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(name='interline-planetutils',
version='0.4.8',
description='Interline PlanetUtils',
long_description=long_description,
url='https://github.com/interline-io/planetutils',
author='Ian Rees',
author_email='ian@interline.io',
license='MIT',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
install_requires=['future', 'requests','boto3'],
tests_require=['nose'],
test_suite = 'nose.collector',
entry_points={
'console_scripts': [
'osm_planet_update=planetutils.osm_planet_update:main',
'osm_planet_extract=planetutils.osm_planet_extract:main',
'osm_planet_get_timestamp=planetutils.osm_planet_get_timestamp:main',
'osm_extract_download=planetutils.osm_extract_download:main',
'elevation_tile_download=planetutils.elevation_tile_download:main',
'elevation_tile_merge=planetutils.elevation_tile_merge:main',
'valhalla_tilepack_download=planetutils.tilepack_download:main',
'valhalla_tilepack_list=planetutils.tilepack_list:main'
],
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.7'
]
)
| true | true |
1c2bb1fbe68365151ed8763afe3a628c2a484dba | 30,744 | py | Python | ignite/contrib/handlers/clearml_logger.py | rushabh-v/ignite | bfdcfa43108b37ef0423899941530744124aae67 | [
"BSD-3-Clause"
] | 1 | 2021-08-30T14:29:10.000Z | 2021-08-30T14:29:10.000Z | ignite/contrib/handlers/clearml_logger.py | rushabh-v/ignite | bfdcfa43108b37ef0423899941530744124aae67 | [
"BSD-3-Clause"
] | null | null | null | ignite/contrib/handlers/clearml_logger.py | rushabh-v/ignite | bfdcfa43108b37ef0423899941530744124aae67 | [
"BSD-3-Clause"
] | null | null | null | """ClearML logger and its helper handlers."""
import numbers
import os
import tempfile
import warnings
from collections import defaultdict
from datetime import datetime
from enum import Enum
from typing import Any, Callable, DefaultDict, List, Mapping, Optional, Tuple, Type, Union
import torch
from torch.nn import Module
from torch.optim import Optimizer
import ignite.distributed as idist
from ignite.contrib.handlers.base_logger import (
BaseLogger,
BaseOptimizerParamsHandler,
BaseOutputHandler,
BaseWeightsHistHandler,
BaseWeightsScalarHandler,
)
from ignite.engine import Engine, Events
from ignite.handlers import global_step_from_engine
from ignite.handlers.checkpoint import DiskSaver
__all__ = [
"ClearMLLogger",
"ClearMLSaver",
"OptimizerParamsHandler",
"OutputHandler",
"WeightsScalarHandler",
"WeightsHistHandler",
"GradsScalarHandler",
"GradsHistHandler",
"global_step_from_engine",
]
class ClearMLLogger(BaseLogger):
"""
`ClearML <https://github.com/allegroai/clearml>`_ handler to log metrics, text, model/optimizer parameters,
plots during training and validation.
Also supports model checkpoints logging and upload to the storage solution of your choice (i.e. ClearML File server,
S3 bucket etc.)
.. code-block:: bash
pip install clearml
clearml-init
Args:
project_name: The name of the project in which the experiment will be created. If the project
does not exist, it is created. If ``project_name`` is ``None``, the repository name is used. (Optional)
task_name: The name of Task (experiment). If ``task_name`` is ``None``, the Python experiment
script's file name is used. (Optional)
task_type: Optional. The task type. Valid values are:
- ``TaskTypes.training`` (Default)
- ``TaskTypes.train``
- ``TaskTypes.testing``
- ``TaskTypes.inference``
Examples:
.. code-block:: python
from ignite.contrib.handlers.clearml_logger import *
# Create a logger
clearml_logger = ClearMLLogger(
project_name="pytorch-ignite-integration",
task_name="cnn-mnist"
)
# Attach the logger to the trainer to log training loss at each iteration
clearml_logger.attach_output_handler(
trainer,
event_name=Events.ITERATION_COMPLETED,
tag="training",
output_transform=lambda loss: {"loss": loss}
)
# Attach the logger to the evaluator on the training dataset and log NLL, Accuracy metrics after each epoch
# We setup `global_step_transform=global_step_from_engine(trainer)` to take the epoch
# of the `trainer` instead of `train_evaluator`.
clearml_logger.attach_output_handler(
train_evaluator,
event_name=Events.EPOCH_COMPLETED,
tag="training",
metric_names=["nll", "accuracy"],
global_step_transform=global_step_from_engine(trainer),
)
# Attach the logger to the evaluator on the validation dataset and log NLL, Accuracy metrics after
# each epoch. We setup `global_step_transform=global_step_from_engine(trainer)` to take the epoch of the
# `trainer` instead of `evaluator`.
clearml_logger.attach_output_handler(
evaluator,
event_name=Events.EPOCH_COMPLETED,
tag="validation",
metric_names=["nll", "accuracy"],
global_step_transform=global_step_from_engine(trainer)),
)
# Attach the logger to the trainer to log optimizer's parameters, e.g. learning rate at each iteration
clearml_logger.attach_opt_params_handler(
trainer,
event_name=Events.ITERATION_STARTED,
optimizer=optimizer,
param_name='lr' # optional
)
# Attach the logger to the trainer to log model's weights norm after each iteration
clearml_logger.attach(
trainer,
event_name=Events.ITERATION_COMPLETED,
log_handler=WeightsScalarHandler(model)
)
"""
def __init__(self, *_: Any, **kwargs: Any):
try:
from clearml import Task
from clearml.binding.frameworks.tensorflow_bind import WeightsGradientHistHelper
except ImportError:
try:
# Backwards-compatibility for legacy Trains SDK
from trains import Task
from trains.binding.frameworks.tensorflow_bind import WeightsGradientHistHelper
except ImportError:
raise RuntimeError(
"This contrib module requires clearml to be installed. "
"You may install clearml using: \n pip install clearml \n"
)
experiment_kwargs = {k: v for k, v in kwargs.items() if k not in ("project_name", "task_name", "task_type")}
if self.bypass_mode():
warnings.warn("ClearMLSaver: running in bypass mode")
class _Stub(object):
def __call__(self, *_: Any, **__: Any) -> "_Stub":
return self
def __getattr__(self, attr: str) -> "_Stub":
if attr in ("name", "id"):
return "" # type: ignore[return-value]
return self
def __setattr__(self, attr: str, val: Any) -> None:
pass
self._task = _Stub()
else:
self._task = Task.init(
project_name=kwargs.get("project_name"),
task_name=kwargs.get("task_name"),
task_type=kwargs.get("task_type", Task.TaskTypes.training),
**experiment_kwargs,
)
self.clearml_logger = self._task.get_logger()
self.grad_helper = WeightsGradientHistHelper(logger=self.clearml_logger)
@classmethod
def set_bypass_mode(cls, bypass: bool) -> None:
"""
Will bypass all outside communication, and will drop all logs.
Should only be used in "standalone mode", when there is no access to the *clearml-server*.
Args:
bypass: If ``True``, all outside communication is skipped.
"""
setattr(cls, "_bypass", bypass)
@classmethod
def bypass_mode(cls) -> bool:
"""
Returns the bypass mode state.
Note:
`GITHUB_ACTIONS` env will automatically set bypass_mode to ``True``
unless overridden specifically with ``ClearMLLogger.set_bypass_mode(False)``.
Return:
If True, all outside communication is skipped.
"""
return getattr(cls, "_bypass", bool(os.environ.get("CI")))
def close(self) -> None:
self.clearml_logger.flush()
def _create_output_handler(self, *args: Any, **kwargs: Any) -> "OutputHandler":
return OutputHandler(*args, **kwargs)
def _create_opt_params_handler(self, *args: Any, **kwargs: Any) -> "OptimizerParamsHandler":
return OptimizerParamsHandler(*args, **kwargs)
class OutputHandler(BaseOutputHandler):
"""Helper handler to log engine's output and/or metrics
Examples:
.. code-block:: python
from ignite.contrib.handlers.clearml_logger import *
# Create a logger
clearml_logger = ClearMLLogger(
project_name="pytorch-ignite-integration",
task_name="cnn-mnist"
)
# Attach the logger to the evaluator on the validation dataset and log NLL, Accuracy metrics after
# each epoch. We setup `global_step_transform=global_step_from_engine(trainer)` to take the epoch
# of the `trainer`:
clearml_logger.attach(
evaluator,
log_handler=OutputHandler(
tag="validation",
metric_names=["nll", "accuracy"],
global_step_transform=global_step_from_engine(trainer)
),
event_name=Events.EPOCH_COMPLETED
)
# or equivalently
clearml_logger.attach_output_handler(
evaluator,
event_name=Events.EPOCH_COMPLETED,
tag="validation",
metric_names=["nll", "accuracy"],
global_step_transform=global_step_from_engine(trainer)
)
Another example, where model is evaluated every 500 iterations:
.. code-block:: python
from ignite.contrib.handlers.clearml_logger import *
@trainer.on(Events.ITERATION_COMPLETED(every=500))
def evaluate(engine):
evaluator.run(validation_set, max_epochs=1)
# Create a logger
clearml_logger = ClearMLLogger(
project_name="pytorch-ignite-integration",
task_name="cnn-mnist"
)
def global_step_transform(*args, **kwargs):
return trainer.state.iteration
# Attach the logger to the evaluator on the validation dataset and log NLL, Accuracy metrics after
# every 500 iterations. Since evaluator engine does not have access to the training iteration, we
# provide a global_step_transform to return the trainer.state.iteration for the global_step, each time
# evaluator metrics are plotted on ClearML.
clearml_logger.attach_output_handler(
evaluator,
event_name=Events.EPOCH_COMPLETED,
tag="validation",
metrics=["nll", "accuracy"],
global_step_transform=global_step_transform
)
Args:
tag: common title for all produced plots. For example, "training"
metric_names: list of metric names to plot or a string "all" to plot all available
metrics.
output_transform: output transform function to prepare `engine.state.output` as a number.
For example, `output_transform = lambda output: output`
This function can also return a dictionary, e.g `{"loss": loss1, "another_loss": loss2}` to label the plot
with corresponding keys.
global_step_transform: global step transform function to output a desired global step.
Input of the function is `(engine, event_name)`. Output of function should be an integer.
Default is None, global_step based on attached engine. If provided,
uses function output as global_step. To setup global step from another engine, please use
:meth:`~ignite.contrib.handlers.clearml_logger.global_step_from_engine`.
Note:
Example of `global_step_transform`:
.. code-block:: python
def global_step_transform(engine, event_name):
return engine.state.get_event_attrib_value(event_name)
"""
def __init__(
self,
tag: str,
metric_names: Optional[List[str]] = None,
output_transform: Optional[Callable] = None,
global_step_transform: Optional[Callable] = None,
):
super(OutputHandler, self).__init__(tag, metric_names, output_transform, global_step_transform)
def __call__(self, engine: Engine, logger: ClearMLLogger, event_name: Union[str, Events]) -> None:
if not isinstance(logger, ClearMLLogger):
raise RuntimeError("Handler OutputHandler works only with ClearMLLogger")
metrics = self._setup_output_metrics(engine)
global_step = self.global_step_transform(engine, event_name) # type: ignore[misc]
if not isinstance(global_step, int):
raise TypeError(
f"global_step must be int, got {type(global_step)}."
" Please check the output of global_step_transform."
)
for key, value in metrics.items():
if isinstance(value, numbers.Number) or isinstance(value, torch.Tensor) and value.ndimension() == 0:
logger.clearml_logger.report_scalar(title=self.tag, series=key, iteration=global_step, value=value)
elif isinstance(value, torch.Tensor) and value.ndimension() == 1:
for i, v in enumerate(value):
logger.clearml_logger.report_scalar(
title=f"{self.tag}/{key}", series=str(i), iteration=global_step, value=v.item()
)
else:
warnings.warn(f"ClearMLLogger output_handler can not log metrics value type {type(value)}")
class OptimizerParamsHandler(BaseOptimizerParamsHandler):
"""Helper handler to log optimizer parameters
Examples:
.. code-block:: python
from ignite.contrib.handlers.clearml_logger import *
# Create a logger
clearml_logger = ClearMLLogger(
project_name="pytorch-ignite-integration",
task_name="cnn-mnist"
)
# Attach the logger to the trainer to log optimizer's parameters, e.g. learning rate at each iteration
clearml_logger.attach(
trainer,
log_handler=OptimizerParamsHandler(optimizer),
event_name=Events.ITERATION_STARTED
)
# or equivalently
clearml_logger.attach_opt_params_handler(
trainer,
event_name=Events.ITERATION_STARTED,
optimizer=optimizer
)
Args:
optimizer: torch optimizer or any object with attribute ``param_groups``
as a sequence.
param_name: parameter name
tag: common title for all produced plots. For example, "generator"
"""
def __init__(self, optimizer: Optimizer, param_name: str = "lr", tag: Optional[str] = None):
super(OptimizerParamsHandler, self).__init__(optimizer, param_name, tag)
def __call__(self, engine: Engine, logger: ClearMLLogger, event_name: Union[str, Events]) -> None:
if not isinstance(logger, ClearMLLogger):
raise RuntimeError("Handler OptimizerParamsHandler works only with ClearMLLogger")
global_step = engine.state.get_event_attrib_value(event_name)
tag_prefix = f"{self.tag}/" if self.tag else ""
params = {
str(i): float(param_group[self.param_name]) for i, param_group in enumerate(self.optimizer.param_groups)
}
for k, v in params.items():
logger.clearml_logger.report_scalar(
title=f"{tag_prefix}{self.param_name}", series=k, value=v, iteration=global_step
)
class WeightsScalarHandler(BaseWeightsScalarHandler):
"""Helper handler to log model's weights as scalars.
Handler iterates over named parameters of the model, applies reduction function to each parameter
produce a scalar and then logs the scalar.
Examples:
.. code-block:: python
from ignite.contrib.handlers.clearml_logger import *
# Create a logger
clearml_logger = ClearMLLogger(
project_name="pytorch-ignite-integration",
task_name="cnn-mnist"
)
# Attach the logger to the trainer to log model's weights norm after each iteration
clearml_logger.attach(
trainer,
event_name=Events.ITERATION_COMPLETED,
log_handler=WeightsScalarHandler(model, reduction=torch.norm)
)
Args:
model: model to log weights
reduction: function to reduce parameters into scalar
tag: common title for all produced plots. For example, "generator"
"""
def __init__(self, model: Module, reduction: Callable = torch.norm, tag: Optional[str] = None):
super(WeightsScalarHandler, self).__init__(model, reduction, tag=tag)
def __call__(self, engine: Engine, logger: ClearMLLogger, event_name: Union[str, Events]) -> None:
if not isinstance(logger, ClearMLLogger):
raise RuntimeError("Handler WeightsScalarHandler works only with ClearMLLogger")
global_step = engine.state.get_event_attrib_value(event_name)
tag_prefix = f"{self.tag}/" if self.tag else ""
for name, p in self.model.named_parameters():
if p.grad is None:
continue
title_name, _, series_name = name.partition(".")
logger.clearml_logger.report_scalar(
title=f"{tag_prefix}weights_{self.reduction.__name__}/{title_name}",
series=series_name,
value=self.reduction(p.data),
iteration=global_step,
)
class WeightsHistHandler(BaseWeightsHistHandler):
"""Helper handler to log model's weights as histograms.
Examples:
.. code-block:: python
from ignite.contrib.handlers.clearml_logger import *
# Create a logger
clearml_logger = ClearMLLogger(
project_name="pytorch-ignite-integration",
task_name="cnn-mnist"
)
# Attach the logger to the trainer to log model's weights norm after each iteration
clearml_logger.attach(
trainer,
event_name=Events.ITERATION_COMPLETED,
log_handler=WeightsHistHandler(model)
)
Args:
model: model to log weights
tag: common title for all produced plots. For example, 'generator'
"""
def __init__(self, model: Module, tag: Optional[str] = None):
super(WeightsHistHandler, self).__init__(model, tag=tag)
def __call__(self, engine: Engine, logger: ClearMLLogger, event_name: Union[str, Events]) -> None:
if not isinstance(logger, ClearMLLogger):
raise RuntimeError("Handler 'WeightsHistHandler' works only with ClearMLLogger")
global_step = engine.state.get_event_attrib_value(event_name)
tag_prefix = f"{self.tag}/" if self.tag else ""
for name, p in self.model.named_parameters():
if p.grad is None:
continue
title_name, _, series_name = name.partition(".")
logger.grad_helper.add_histogram(
title=f"{tag_prefix}weights_{title_name}",
series=series_name,
step=global_step,
hist_data=p.grad.detach().cpu().numpy(),
)
class GradsScalarHandler(BaseWeightsScalarHandler):
"""Helper handler to log model's gradients as scalars.
Handler iterates over the gradients of named parameters of the model, applies reduction function to each parameter
produce a scalar and then logs the scalar.
Examples:
.. code-block:: python
from ignite.contrib.handlers.clearml_logger import *
# Create a logger
clearml_logger = ClearMLLogger(
project_name="pytorch-ignite-integration",
task_name="cnn-mnist"
)
# Attach the logger to the trainer to log model's weights norm after each iteration
clearml_logger.attach(
trainer,
event_name=Events.ITERATION_COMPLETED,
log_handler=GradsScalarHandler(model, reduction=torch.norm)
)
Args:
model: model to log weights
reduction: function to reduce parameters into scalar
tag: common title for all produced plots. For example, "generator"
"""
def __init__(self, model: Module, reduction: Callable = torch.norm, tag: Optional[str] = None):
super(GradsScalarHandler, self).__init__(model, reduction, tag=tag)
def __call__(self, engine: Engine, logger: ClearMLLogger, event_name: Union[str, Events]) -> None:
if not isinstance(logger, ClearMLLogger):
raise RuntimeError("Handler GradsScalarHandler works only with ClearMLLogger")
global_step = engine.state.get_event_attrib_value(event_name)
tag_prefix = f"{self.tag}/" if self.tag else ""
for name, p in self.model.named_parameters():
if p.grad is None:
continue
title_name, _, series_name = name.partition(".")
logger.clearml_logger.report_scalar(
title=f"{tag_prefix}grads_{self.reduction.__name__}/{title_name}",
series=series_name,
value=self.reduction(p.data),
iteration=global_step,
)
class GradsHistHandler(BaseWeightsHistHandler):
"""Helper handler to log model's gradients as histograms.
Examples:
.. code-block:: python
from ignite.contrib.handlers.clearml_logger import *
# Create a logger
clearml_logger = ClearMLLogger(
project_name="pytorch-ignite-integration",
task_name="cnn-mnist"
)
# Attach the logger to the trainer to log model's weights norm after each iteration
clearml_logger.attach(
trainer,
event_name=Events.ITERATION_COMPLETED,
log_handler=GradsHistHandler(model)
)
Args:
model: model to log weights
tag: common title for all produced plots. For example, 'generator'
"""
def __init__(self, model: Module, tag: Optional[str] = None):
super(GradsHistHandler, self).__init__(model, tag=tag)
def __call__(self, engine: Engine, logger: ClearMLLogger, event_name: Union[str, Events]) -> None:
if not isinstance(logger, ClearMLLogger):
raise RuntimeError("Handler 'GradsHistHandler' works only with ClearMLLogger")
global_step = engine.state.get_event_attrib_value(event_name)
tag_prefix = f"{self.tag}/" if self.tag else ""
for name, p in self.model.named_parameters():
if p.grad is None:
continue
title_name, _, series_name = name.partition(".")
logger.grad_helper.add_histogram(
title=f"{tag_prefix}grads_{title_name}",
series=series_name,
step=global_step,
hist_data=p.grad.detach().cpu().numpy(),
)
class ClearMLSaver(DiskSaver):
"""
Handler that saves input checkpoint as ClearML artifacts
Args:
logger: An instance of :class:`~ignite.contrib.handlers.clearml_logger.ClearMLLogger`,
ensuring a valid ClearML ``Task`` has been initialized. If not provided, and a ClearML Task
has not been manually initialized, a runtime error will be raised.
output_uri: The default location for output models and other artifacts uploaded by ClearML. For
more information, see ``clearml.Task.init``.
dirname: Directory path where the checkpoint will be saved. If not provided, a temporary
directory will be created.
Examples:
.. code-block:: python
from ignite.contrib.handlers.clearml_logger import *
from ignite.handlers import Checkpoint
clearml_logger = ClearMLLogger(
project_name="pytorch-ignite-integration",
task_name="cnn-mnist"
)
to_save = {"model": model}
handler = Checkpoint(
to_save,
ClearMLSaver(),
n_saved=1,
score_function=lambda e: 123,
score_name="acc",
filename_prefix="best",
global_step_transform=global_step_from_engine(trainer)
)
validation_evaluator.add_event_handler(Events.EVENT_COMPLETED, handler)
"""
def __init__(
self,
logger: Optional[ClearMLLogger] = None,
output_uri: Optional[str] = None,
dirname: Optional[str] = None,
*args: Any,
**kwargs: Any,
):
self._setup_check_clearml(logger, output_uri)
if not dirname:
dirname = ""
if idist.get_rank() == 0:
dirname = tempfile.mkdtemp(prefix=f"ignite_checkpoints_{datetime.now().strftime('%Y_%m_%d_%H_%M_%S_')}")
if idist.get_world_size() > 1:
dirname = idist.all_gather(dirname)[0] # type: ignore[index, assignment]
warnings.warn(f"ClearMLSaver created a temporary checkpoints directory: {dirname}")
idist.barrier()
# Let's set non-atomic tmp dir saving behaviour
if "atomic" not in kwargs:
kwargs["atomic"] = False
self._checkpoint_slots = defaultdict(list) # type: DefaultDict[Union[str, Tuple[str, str]], List[Any]]
super(ClearMLSaver, self).__init__(dirname=dirname, *args, **kwargs) # type: ignore[misc]
@idist.one_rank_only()
def _setup_check_clearml(self, logger: ClearMLLogger, output_uri: str) -> None:
try:
from clearml import Task
except ImportError:
try:
# Backwards-compatibility for legacy Trains SDK
from trains import Task
except ImportError:
raise RuntimeError(
"This contrib module requires clearml to be installed. "
"You may install clearml using: \n pip install clearml \n"
)
if logger and not isinstance(logger, ClearMLLogger):
raise TypeError("logger must be an instance of ClearMLLogger")
self._task = Task.current_task()
if not self._task:
raise RuntimeError(
"ClearMLSaver requires a ClearML Task to be initialized. "
"Please use the `logger` argument or call `clearml.Task.init()`."
)
if output_uri:
self._task.output_uri = output_uri
class _CallbacksContext:
def __init__(
self,
callback_type: Type[Enum],
slots: List,
checkpoint_key: str,
filename: str,
basename: str,
metadata: Optional[Mapping] = None,
) -> None:
self._callback_type = callback_type
self._slots = slots
self._checkpoint_key = str(checkpoint_key)
self._filename = filename
self._basename = basename
self._metadata = metadata
def pre_callback(self, action: str, model_info: Any) -> Any:
if action != self._callback_type.save: # type: ignore[attr-defined]
return model_info
try:
slot = self._slots.index(None)
self._slots[slot] = model_info.upload_filename
except ValueError:
self._slots.append(model_info.upload_filename)
slot = len(self._slots) - 1
model_info.upload_filename = f"{self._basename}_{slot}{os.path.splitext(self._filename)[1]}"
model_info.local_model_id = f"{self._checkpoint_key}:{model_info.upload_filename}"
return model_info
def post_callback(self, action: str, model_info: Any) -> Any:
if action != self._callback_type.save: # type: ignore[attr-defined]
return model_info
model_info.model.name = f"{model_info.task.name}: {self._filename}"
prefix = "Checkpoint Metadata: "
metadata_items = ", ".join(f"{k}={v}" for k, v in self._metadata.items()) if self._metadata else "none"
metadata = f"{prefix}{metadata_items}"
comment = "\n".join(
metadata if line.startswith(prefix) else line for line in (model_info.model.comment or "").split("\n")
)
if prefix not in comment:
comment += "\n" + metadata
model_info.model.comment = comment
return model_info
def __call__(self, checkpoint: Mapping, filename: str, metadata: Optional[Mapping] = None) -> None:
try:
from clearml import Model
from clearml.binding.frameworks import WeightsFileHandler
except ImportError:
try:
# Backwards-compatibility for legacy Trains SDK
from trains import Model
from trains.binding.frameworks import WeightsFileHandler
except ImportError:
raise RuntimeError(
"This contrib module requires clearml to be installed. "
"You may install clearml using: \n pip install clearml \n"
)
try:
basename = metadata["basename"] # type: ignore[index]
except (TypeError, KeyError):
warnings.warn("Checkpoint metadata missing or basename cannot be found")
basename = "checkpoint"
checkpoint_key = (self.dirname, basename)
cb_context = self._CallbacksContext(
callback_type=WeightsFileHandler.CallbackType,
slots=self._checkpoint_slots[checkpoint_key],
checkpoint_key=str(checkpoint_key),
filename=filename,
basename=basename,
metadata=metadata,
)
pre_cb_id = WeightsFileHandler.add_pre_callback(cb_context.pre_callback)
post_cb_id = WeightsFileHandler.add_post_callback(cb_context.post_callback)
try:
super(ClearMLSaver, self).__call__(checkpoint, filename, metadata)
finally:
WeightsFileHandler.remove_pre_callback(pre_cb_id)
WeightsFileHandler.remove_post_callback(post_cb_id)
@idist.one_rank_only()
def get_local_copy(self, filename: str) -> Optional[str]:
"""Get artifact local copy.
.. warning::
In distributed configuration this method should be called on rank 0 process.
Args:
filename: artifact name.
Returns:
a local path to a downloaded copy of the artifact
"""
artifact = self._task.artifacts.get(filename)
if artifact:
return artifact.get_local_copy()
self._task.get_logger().report_text(f"Can not find artifact {filename}")
return None
@idist.one_rank_only()
def remove(self, filename: str) -> None:
super(ClearMLSaver, self).remove(filename)
for slots in self._checkpoint_slots.values():
try:
slots[slots.index(filename)] = None
except ValueError:
pass
else:
break
| 37.538462 | 120 | 0.612217 | import numbers
import os
import tempfile
import warnings
from collections import defaultdict
from datetime import datetime
from enum import Enum
from typing import Any, Callable, DefaultDict, List, Mapping, Optional, Tuple, Type, Union
import torch
from torch.nn import Module
from torch.optim import Optimizer
import ignite.distributed as idist
from ignite.contrib.handlers.base_logger import (
BaseLogger,
BaseOptimizerParamsHandler,
BaseOutputHandler,
BaseWeightsHistHandler,
BaseWeightsScalarHandler,
)
from ignite.engine import Engine, Events
from ignite.handlers import global_step_from_engine
from ignite.handlers.checkpoint import DiskSaver
__all__ = [
"ClearMLLogger",
"ClearMLSaver",
"OptimizerParamsHandler",
"OutputHandler",
"WeightsScalarHandler",
"WeightsHistHandler",
"GradsScalarHandler",
"GradsHistHandler",
"global_step_from_engine",
]
class ClearMLLogger(BaseLogger):
def __init__(self, *_: Any, **kwargs: Any):
try:
from clearml import Task
from clearml.binding.frameworks.tensorflow_bind import WeightsGradientHistHelper
except ImportError:
try:
from trains import Task
from trains.binding.frameworks.tensorflow_bind import WeightsGradientHistHelper
except ImportError:
raise RuntimeError(
"This contrib module requires clearml to be installed. "
"You may install clearml using: \n pip install clearml \n"
)
experiment_kwargs = {k: v for k, v in kwargs.items() if k not in ("project_name", "task_name", "task_type")}
if self.bypass_mode():
warnings.warn("ClearMLSaver: running in bypass mode")
class _Stub(object):
def __call__(self, *_: Any, **__: Any) -> "_Stub":
return self
def __getattr__(self, attr: str) -> "_Stub":
if attr in ("name", "id"):
return ""
return self
def __setattr__(self, attr: str, val: Any) -> None:
pass
self._task = _Stub()
else:
self._task = Task.init(
project_name=kwargs.get("project_name"),
task_name=kwargs.get("task_name"),
task_type=kwargs.get("task_type", Task.TaskTypes.training),
**experiment_kwargs,
)
self.clearml_logger = self._task.get_logger()
self.grad_helper = WeightsGradientHistHelper(logger=self.clearml_logger)
@classmethod
def set_bypass_mode(cls, bypass: bool) -> None:
setattr(cls, "_bypass", bypass)
@classmethod
def bypass_mode(cls) -> bool:
return getattr(cls, "_bypass", bool(os.environ.get("CI")))
def close(self) -> None:
self.clearml_logger.flush()
def _create_output_handler(self, *args: Any, **kwargs: Any) -> "OutputHandler":
return OutputHandler(*args, **kwargs)
def _create_opt_params_handler(self, *args: Any, **kwargs: Any) -> "OptimizerParamsHandler":
return OptimizerParamsHandler(*args, **kwargs)
class OutputHandler(BaseOutputHandler):
def __init__(
self,
tag: str,
metric_names: Optional[List[str]] = None,
output_transform: Optional[Callable] = None,
global_step_transform: Optional[Callable] = None,
):
super(OutputHandler, self).__init__(tag, metric_names, output_transform, global_step_transform)
def __call__(self, engine: Engine, logger: ClearMLLogger, event_name: Union[str, Events]) -> None:
if not isinstance(logger, ClearMLLogger):
raise RuntimeError("Handler OutputHandler works only with ClearMLLogger")
metrics = self._setup_output_metrics(engine)
global_step = self.global_step_transform(engine, event_name)
if not isinstance(global_step, int):
raise TypeError(
f"global_step must be int, got {type(global_step)}."
" Please check the output of global_step_transform."
)
for key, value in metrics.items():
if isinstance(value, numbers.Number) or isinstance(value, torch.Tensor) and value.ndimension() == 0:
logger.clearml_logger.report_scalar(title=self.tag, series=key, iteration=global_step, value=value)
elif isinstance(value, torch.Tensor) and value.ndimension() == 1:
for i, v in enumerate(value):
logger.clearml_logger.report_scalar(
title=f"{self.tag}/{key}", series=str(i), iteration=global_step, value=v.item()
)
else:
warnings.warn(f"ClearMLLogger output_handler can not log metrics value type {type(value)}")
class OptimizerParamsHandler(BaseOptimizerParamsHandler):
def __init__(self, optimizer: Optimizer, param_name: str = "lr", tag: Optional[str] = None):
super(OptimizerParamsHandler, self).__init__(optimizer, param_name, tag)
def __call__(self, engine: Engine, logger: ClearMLLogger, event_name: Union[str, Events]) -> None:
if not isinstance(logger, ClearMLLogger):
raise RuntimeError("Handler OptimizerParamsHandler works only with ClearMLLogger")
global_step = engine.state.get_event_attrib_value(event_name)
tag_prefix = f"{self.tag}/" if self.tag else ""
params = {
str(i): float(param_group[self.param_name]) for i, param_group in enumerate(self.optimizer.param_groups)
}
for k, v in params.items():
logger.clearml_logger.report_scalar(
title=f"{tag_prefix}{self.param_name}", series=k, value=v, iteration=global_step
)
class WeightsScalarHandler(BaseWeightsScalarHandler):
def __init__(self, model: Module, reduction: Callable = torch.norm, tag: Optional[str] = None):
super(WeightsScalarHandler, self).__init__(model, reduction, tag=tag)
def __call__(self, engine: Engine, logger: ClearMLLogger, event_name: Union[str, Events]) -> None:
if not isinstance(logger, ClearMLLogger):
raise RuntimeError("Handler WeightsScalarHandler works only with ClearMLLogger")
global_step = engine.state.get_event_attrib_value(event_name)
tag_prefix = f"{self.tag}/" if self.tag else ""
for name, p in self.model.named_parameters():
if p.grad is None:
continue
title_name, _, series_name = name.partition(".")
logger.clearml_logger.report_scalar(
title=f"{tag_prefix}weights_{self.reduction.__name__}/{title_name}",
series=series_name,
value=self.reduction(p.data),
iteration=global_step,
)
class WeightsHistHandler(BaseWeightsHistHandler):
def __init__(self, model: Module, tag: Optional[str] = None):
super(WeightsHistHandler, self).__init__(model, tag=tag)
def __call__(self, engine: Engine, logger: ClearMLLogger, event_name: Union[str, Events]) -> None:
if not isinstance(logger, ClearMLLogger):
raise RuntimeError("Handler 'WeightsHistHandler' works only with ClearMLLogger")
global_step = engine.state.get_event_attrib_value(event_name)
tag_prefix = f"{self.tag}/" if self.tag else ""
for name, p in self.model.named_parameters():
if p.grad is None:
continue
title_name, _, series_name = name.partition(".")
logger.grad_helper.add_histogram(
title=f"{tag_prefix}weights_{title_name}",
series=series_name,
step=global_step,
hist_data=p.grad.detach().cpu().numpy(),
)
class GradsScalarHandler(BaseWeightsScalarHandler):
def __init__(self, model: Module, reduction: Callable = torch.norm, tag: Optional[str] = None):
super(GradsScalarHandler, self).__init__(model, reduction, tag=tag)
def __call__(self, engine: Engine, logger: ClearMLLogger, event_name: Union[str, Events]) -> None:
if not isinstance(logger, ClearMLLogger):
raise RuntimeError("Handler GradsScalarHandler works only with ClearMLLogger")
global_step = engine.state.get_event_attrib_value(event_name)
tag_prefix = f"{self.tag}/" if self.tag else ""
for name, p in self.model.named_parameters():
if p.grad is None:
continue
title_name, _, series_name = name.partition(".")
logger.clearml_logger.report_scalar(
title=f"{tag_prefix}grads_{self.reduction.__name__}/{title_name}",
series=series_name,
value=self.reduction(p.data),
iteration=global_step,
)
class GradsHistHandler(BaseWeightsHistHandler):
def __init__(self, model: Module, tag: Optional[str] = None):
super(GradsHistHandler, self).__init__(model, tag=tag)
def __call__(self, engine: Engine, logger: ClearMLLogger, event_name: Union[str, Events]) -> None:
if not isinstance(logger, ClearMLLogger):
raise RuntimeError("Handler 'GradsHistHandler' works only with ClearMLLogger")
global_step = engine.state.get_event_attrib_value(event_name)
tag_prefix = f"{self.tag}/" if self.tag else ""
for name, p in self.model.named_parameters():
if p.grad is None:
continue
title_name, _, series_name = name.partition(".")
logger.grad_helper.add_histogram(
title=f"{tag_prefix}grads_{title_name}",
series=series_name,
step=global_step,
hist_data=p.grad.detach().cpu().numpy(),
)
class ClearMLSaver(DiskSaver):
def __init__(
self,
logger: Optional[ClearMLLogger] = None,
output_uri: Optional[str] = None,
dirname: Optional[str] = None,
*args: Any,
**kwargs: Any,
):
self._setup_check_clearml(logger, output_uri)
if not dirname:
dirname = ""
if idist.get_rank() == 0:
dirname = tempfile.mkdtemp(prefix=f"ignite_checkpoints_{datetime.now().strftime('%Y_%m_%d_%H_%M_%S_')}")
if idist.get_world_size() > 1:
dirname = idist.all_gather(dirname)[0]
warnings.warn(f"ClearMLSaver created a temporary checkpoints directory: {dirname}")
idist.barrier()
if "atomic" not in kwargs:
kwargs["atomic"] = False
self._checkpoint_slots = defaultdict(list) # type: DefaultDict[Union[str, Tuple[str, str]], List[Any]]
super(ClearMLSaver, self).__init__(dirname=dirname, *args, **kwargs) # type: ignore[misc]
@idist.one_rank_only()
def _setup_check_clearml(self, logger: ClearMLLogger, output_uri: str) -> None:
try:
from clearml import Task
except ImportError:
try:
# Backwards-compatibility for legacy Trains SDK
from trains import Task
except ImportError:
raise RuntimeError(
"This contrib module requires clearml to be installed. "
"You may install clearml using: \n pip install clearml \n"
)
if logger and not isinstance(logger, ClearMLLogger):
raise TypeError("logger must be an instance of ClearMLLogger")
self._task = Task.current_task()
if not self._task:
raise RuntimeError(
"ClearMLSaver requires a ClearML Task to be initialized. "
"Please use the `logger` argument or call `clearml.Task.init()`."
)
if output_uri:
self._task.output_uri = output_uri
class _CallbacksContext:
def __init__(
self,
callback_type: Type[Enum],
slots: List,
checkpoint_key: str,
filename: str,
basename: str,
metadata: Optional[Mapping] = None,
) -> None:
self._callback_type = callback_type
self._slots = slots
self._checkpoint_key = str(checkpoint_key)
self._filename = filename
self._basename = basename
self._metadata = metadata
def pre_callback(self, action: str, model_info: Any) -> Any:
if action != self._callback_type.save: # type: ignore[attr-defined]
return model_info
try:
slot = self._slots.index(None)
self._slots[slot] = model_info.upload_filename
except ValueError:
self._slots.append(model_info.upload_filename)
slot = len(self._slots) - 1
model_info.upload_filename = f"{self._basename}_{slot}{os.path.splitext(self._filename)[1]}"
model_info.local_model_id = f"{self._checkpoint_key}:{model_info.upload_filename}"
return model_info
def post_callback(self, action: str, model_info: Any) -> Any:
if action != self._callback_type.save: # type: ignore[attr-defined]
return model_info
model_info.model.name = f"{model_info.task.name}: {self._filename}"
prefix = "Checkpoint Metadata: "
metadata_items = ", ".join(f"{k}={v}" for k, v in self._metadata.items()) if self._metadata else "none"
metadata = f"{prefix}{metadata_items}"
comment = "\n".join(
metadata if line.startswith(prefix) else line for line in (model_info.model.comment or "").split("\n")
)
if prefix not in comment:
comment += "\n" + metadata
model_info.model.comment = comment
return model_info
def __call__(self, checkpoint: Mapping, filename: str, metadata: Optional[Mapping] = None) -> None:
try:
from clearml import Model
from clearml.binding.frameworks import WeightsFileHandler
except ImportError:
try:
# Backwards-compatibility for legacy Trains SDK
from trains import Model
from trains.binding.frameworks import WeightsFileHandler
except ImportError:
raise RuntimeError(
"This contrib module requires clearml to be installed. "
"You may install clearml using: \n pip install clearml \n"
)
try:
basename = metadata["basename"] # type: ignore[index]
except (TypeError, KeyError):
warnings.warn("Checkpoint metadata missing or basename cannot be found")
basename = "checkpoint"
checkpoint_key = (self.dirname, basename)
cb_context = self._CallbacksContext(
callback_type=WeightsFileHandler.CallbackType,
slots=self._checkpoint_slots[checkpoint_key],
checkpoint_key=str(checkpoint_key),
filename=filename,
basename=basename,
metadata=metadata,
)
pre_cb_id = WeightsFileHandler.add_pre_callback(cb_context.pre_callback)
post_cb_id = WeightsFileHandler.add_post_callback(cb_context.post_callback)
try:
super(ClearMLSaver, self).__call__(checkpoint, filename, metadata)
finally:
WeightsFileHandler.remove_pre_callback(pre_cb_id)
WeightsFileHandler.remove_post_callback(post_cb_id)
@idist.one_rank_only()
def get_local_copy(self, filename: str) -> Optional[str]:
artifact = self._task.artifacts.get(filename)
if artifact:
return artifact.get_local_copy()
self._task.get_logger().report_text(f"Can not find artifact {filename}")
return None
@idist.one_rank_only()
def remove(self, filename: str) -> None:
super(ClearMLSaver, self).remove(filename)
for slots in self._checkpoint_slots.values():
try:
slots[slots.index(filename)] = None
except ValueError:
pass
else:
break
| true | true |
1c2bb21e9f8d5ea373a0cada2c3f86a2a57f2c62 | 163 | py | Python | examples/if_oneliner.py | personal-army-of-4o/nyanMigen | 205e114d47495a3c7c885556ffa0ebe386e9b9fc | [
"BSD-3-Clause"
] | 4 | 2021-02-26T17:20:44.000Z | 2021-04-15T07:41:31.000Z | examples/if_oneliner.py | personal-army-of-4o/nyanMigen | 205e114d47495a3c7c885556ffa0ebe386e9b9fc | [
"BSD-3-Clause"
] | 121 | 2021-02-18T07:24:22.000Z | 2021-07-19T14:24:51.000Z | examples/if_oneliner.py | personal-army-of-4o/nyanMigen | 205e114d47495a3c7c885556ffa0ebe386e9b9fc | [
"BSD-3-Clause"
] | null | null | null |
from nyanMigen import nyanify
@nyanify
class if_oneliner:
def elaborate(self, platform):
a = Signal()
b = Signal()
a = 1 if b else 0
| 16.3 | 34 | 0.595092 |
from nyanMigen import nyanify
@nyanify
class if_oneliner:
def elaborate(self, platform):
a = Signal()
b = Signal()
a = 1 if b else 0
| true | true |
1c2bb30ea4f7632e975191f0c33e42994bfeddb2 | 7,983 | py | Python | labtex/unit.py | CianLM/labtex | cb8233d762f62825c466fbdb050334f743847aaa | [
"MIT"
] | 4 | 2021-07-10T13:28:48.000Z | 2021-09-04T07:06:18.000Z | labtex/unit.py | CianLM/labtex | cb8233d762f62825c466fbdb050334f743847aaa | [
"MIT"
] | null | null | null | labtex/unit.py | CianLM/labtex | cb8233d762f62825c466fbdb050334f743847aaa | [
"MIT"
] | null | null | null | import re
from typing import Union
import math
# TODO
# MeasurementList type compatability
class Unit:
"SI Unit taking in a string."
def __init__(self,unitString: Union[str,dict]):
Unit.knownUnits = ['g','s','A','K','C','J','V','N','W','T','Pa','Hz','m']
Unit.prefixes = {'n':1e-9,'u':1e-6,'m':1e-3,'c':1e-2,'':1,'k':1e3,'M':1e6,'G':1e9}
# Given user string input, parse the units, prefixes and powers
if(type(unitString) == str):
self.units = dict.fromkeys(Unit.knownUnits)
for unit in self.units:
self.units[unit] = {'prefix':'','power':0}
self.parse( unitString.replace(' ','').replace('{','').replace('}','') )
# Used internally to construct a Unit from a dictionary of its units
else:
self.units = unitString
def __repr__(self):
unitoutput = []
for unit in Unit.knownUnits:
if (self.units[unit]['power'] != 0):
if(self.units[unit]['power'] != 1):
unitoutput.append(f"{self.units[unit]['prefix']}{unit}^{ self.units[unit]['power'] if self.units[unit]['power'] > 0 else '{' + str(self.units[unit]['power']) + '}'}")
else:
unitoutput.append(f"{self.units[unit]['prefix']}{unit}")
return " ".join(unitoutput)
def parse(self,unitString):
"Decompose string into its constituent SI units."
# Match a prefix
prefix = re.compile('([numckMG])')
# Match a known unit
unit = re.compile('([gsAKCJVNWTm]|(?:Pa)|(?:Hz))')
# Match a '^' followed optionally by '-' and then any number of digits
rgxpower = re.compile('(\^)(\-?)(\d+)')
i = 0
while i < len(unitString):
prefixmatch = prefix.match(unitString[i:])
prefixfound = prefixmatch is not None
unitmatch = unit.match(unitString[i+prefixfound:])
if (unitmatch is not None):
unitname = unitmatch.group(1)
powermatch = rgxpower.match(unitString[i+prefixfound+len(unitname):])
powerlength = powermatch.span()[1] if powermatch != None else 0
self.units[unitname] = {
'prefix': prefixmatch.group(1) if prefixfound else '',
'power': int(powermatch.group(2) + powermatch.group(3) if powermatch != None else 1)
}
i += prefixfound + len(unitname) + powerlength
# account for 'm' as a prefix match but no succeeding unit
elif (prefixfound):
unitmatch = unit.match(unitString[i:])
if(unitmatch is not None):
unitname = unitmatch.group(1)
powermatch = rgxpower.match(unitString[i+len(unitname):])
powerlength = powermatch.span()[1] if powermatch != None else 0
self.units[unitname] = {
'prefix': '',
'power': int(powermatch.group(2) + powermatch.group(3) if powermatch else 1)
}
i += len(unitname) + powerlength
else:
raise Exception(f"Error in unit parsing with unknown characters: {unitString[i:]}")
else:
raise Exception(f"Error in unit parsing with unknown characters: {unitString[i:]}")
@staticmethod
def unitless(self):
return all([ dim['power'] == 0 for dim in self.units.values() ])
@staticmethod
def singular(self): # only a single dimension has a non zero power
return sum([*map(lambda x: x['power'] != 0,self.units.values())]) == 1
@staticmethod
def singularunit(self):
if(Unit.singular(self)):
for unit in self.units.values():
if(unit["power"] != 0):
return unit
else:
return False
def __eq__(self,obj):
"Check if two Units are the same."
if (isinstance(obj,Unit)):
return all(self.units[unit] == obj.units[unit] for unit in Unit.knownUnits)
return False
def __mul__(self,obj):
"Multiply two Units."
if(isinstance(obj,Unit)):
newunits = {}
for unit in Unit.knownUnits:
if((self.units[unit]["power"] > 0) ^ (obj.units[unit]["power"] > 0) ):
newunits[unit] = {
"prefix": self.units[unit]["prefix"] + obj.units[unit]["prefix"],
"power": self.units[unit]["power"] + obj.units[unit]["power"]
}
elif(self.units[unit]["prefix"] == obj.units[unit]["prefix"]):
newunits[unit] = {
"prefix": self.units[unit]["prefix"] if self.units[unit]["power"] + obj.units[unit]["power"] != 0 else "",
"power": self.units[unit]["power"] + obj.units[unit]["power"]
}
else:
raise Exception("Measurements have different prefixes. Multiplication not supported.")
return Unit(newunits)
else:
# We require only a single dimension present otherwise we dont know which dimension to change the prefix of.
if(Unit.singular(self) and int(math.log10(obj)) == math.log10(obj)):
singularunit = Unit.singularunit(self)
multiplicativefactor = obj**(1/singularunit["power"])
if(Unit.prefixes[singularunit["prefix"]] * multiplicativefactor in Unit.prefixes.values()):
newunits = self.units.copy()
for unit in Unit.knownUnits:
if(self.units[unit] == singularunit):
# find the key that corresponds to this value
newunits[unit] = {
"prefix": list(Unit.prefixes.keys())[list(Unit.prefixes.values()).index(
Unit.prefixes[singularunit["prefix"]] * multiplicativefactor
)],
"power": self.units[unit]["power"]
}
return Unit(newunits)
return self
def __rmul__(self,obj):
return self.__mul__(obj)
def __truediv__(self,obj):
if(isinstance(obj,Unit)):
newunits = {}
for unit in Unit.knownUnits:
if(self.units[unit]["power"] > 0 ^ obj.units[unit]["power"] > 0 ):
newunits[unit] = {
"prefix": self.units[unit]["prefix"] + obj.units[unit]["power"],
"power": self.units[unit]["power"] - obj.units[unit]["power"]
}
elif(self.units[unit]["prefix"] == obj.units[unit]["prefix"]):
newunits[unit] = {
"prefix": self.units[unit]["prefix"] if self.units[unit]["power"] - obj.units[unit]["power"] != 0 else "",
"power": self.units[unit]["power"] - obj.units[unit]["power"]
}
else:
raise Exception("Measurements have different prefixes. Division not supported.")
return Unit(newunits)
else:
return self.__mul__(1/obj)
def __rtruediv__(self,obj):
newunits = {
unit: {
"prefix": self.units[unit]["prefix"],
"power": -self.units[unit]["power"]
} for unit in Unit.knownUnits
}
tmpUnit = Unit(newunits)
return tmpUnit.__mul__(obj)
def __pow__(self,obj):
newunits = {
unit: {
"prefix": self.units[unit]["prefix"],
"power": self.units[unit]["power"] * obj
} for unit in Unit.knownUnits
}
return Unit(newunits)
| 42.919355 | 186 | 0.507829 | import re
from typing import Union
import math
class Unit:
def __init__(self,unitString: Union[str,dict]):
Unit.knownUnits = ['g','s','A','K','C','J','V','N','W','T','Pa','Hz','m']
Unit.prefixes = {'n':1e-9,'u':1e-6,'m':1e-3,'c':1e-2,'':1,'k':1e3,'M':1e6,'G':1e9}
if(type(unitString) == str):
self.units = dict.fromkeys(Unit.knownUnits)
for unit in self.units:
self.units[unit] = {'prefix':'','power':0}
self.parse( unitString.replace(' ','').replace('{','').replace('}','') )
else:
self.units = unitString
def __repr__(self):
unitoutput = []
for unit in Unit.knownUnits:
if (self.units[unit]['power'] != 0):
if(self.units[unit]['power'] != 1):
unitoutput.append(f"{self.units[unit]['prefix']}{unit}^{ self.units[unit]['power'] if self.units[unit]['power'] > 0 else '{' + str(self.units[unit]['power']) + '}'}")
else:
unitoutput.append(f"{self.units[unit]['prefix']}{unit}")
return " ".join(unitoutput)
def parse(self,unitString):
prefix = re.compile('([numckMG])')
unit = re.compile('([gsAKCJVNWTm]|(?:Pa)|(?:Hz))')
rgxpower = re.compile('(\^)(\-?)(\d+)')
i = 0
while i < len(unitString):
prefixmatch = prefix.match(unitString[i:])
prefixfound = prefixmatch is not None
unitmatch = unit.match(unitString[i+prefixfound:])
if (unitmatch is not None):
unitname = unitmatch.group(1)
powermatch = rgxpower.match(unitString[i+prefixfound+len(unitname):])
powerlength = powermatch.span()[1] if powermatch != None else 0
self.units[unitname] = {
'prefix': prefixmatch.group(1) if prefixfound else '',
'power': int(powermatch.group(2) + powermatch.group(3) if powermatch != None else 1)
}
i += prefixfound + len(unitname) + powerlength
elif (prefixfound):
unitmatch = unit.match(unitString[i:])
if(unitmatch is not None):
unitname = unitmatch.group(1)
powermatch = rgxpower.match(unitString[i+len(unitname):])
powerlength = powermatch.span()[1] if powermatch != None else 0
self.units[unitname] = {
'prefix': '',
'power': int(powermatch.group(2) + powermatch.group(3) if powermatch else 1)
}
i += len(unitname) + powerlength
else:
raise Exception(f"Error in unit parsing with unknown characters: {unitString[i:]}")
else:
raise Exception(f"Error in unit parsing with unknown characters: {unitString[i:]}")
@staticmethod
def unitless(self):
return all([ dim['power'] == 0 for dim in self.units.values() ])
@staticmethod
def singular(self):
return sum([*map(lambda x: x['power'] != 0,self.units.values())]) == 1
@staticmethod
def singularunit(self):
if(Unit.singular(self)):
for unit in self.units.values():
if(unit["power"] != 0):
return unit
else:
return False
def __eq__(self,obj):
if (isinstance(obj,Unit)):
return all(self.units[unit] == obj.units[unit] for unit in Unit.knownUnits)
return False
def __mul__(self,obj):
if(isinstance(obj,Unit)):
newunits = {}
for unit in Unit.knownUnits:
if((self.units[unit]["power"] > 0) ^ (obj.units[unit]["power"] > 0) ):
newunits[unit] = {
"prefix": self.units[unit]["prefix"] + obj.units[unit]["prefix"],
"power": self.units[unit]["power"] + obj.units[unit]["power"]
}
elif(self.units[unit]["prefix"] == obj.units[unit]["prefix"]):
newunits[unit] = {
"prefix": self.units[unit]["prefix"] if self.units[unit]["power"] + obj.units[unit]["power"] != 0 else "",
"power": self.units[unit]["power"] + obj.units[unit]["power"]
}
else:
raise Exception("Measurements have different prefixes. Multiplication not supported.")
return Unit(newunits)
else:
if(Unit.singular(self) and int(math.log10(obj)) == math.log10(obj)):
singularunit = Unit.singularunit(self)
multiplicativefactor = obj**(1/singularunit["power"])
if(Unit.prefixes[singularunit["prefix"]] * multiplicativefactor in Unit.prefixes.values()):
newunits = self.units.copy()
for unit in Unit.knownUnits:
if(self.units[unit] == singularunit):
newunits[unit] = {
"prefix": list(Unit.prefixes.keys())[list(Unit.prefixes.values()).index(
Unit.prefixes[singularunit["prefix"]] * multiplicativefactor
)],
"power": self.units[unit]["power"]
}
return Unit(newunits)
return self
def __rmul__(self,obj):
return self.__mul__(obj)
def __truediv__(self,obj):
if(isinstance(obj,Unit)):
newunits = {}
for unit in Unit.knownUnits:
if(self.units[unit]["power"] > 0 ^ obj.units[unit]["power"] > 0 ):
newunits[unit] = {
"prefix": self.units[unit]["prefix"] + obj.units[unit]["power"],
"power": self.units[unit]["power"] - obj.units[unit]["power"]
}
elif(self.units[unit]["prefix"] == obj.units[unit]["prefix"]):
newunits[unit] = {
"prefix": self.units[unit]["prefix"] if self.units[unit]["power"] - obj.units[unit]["power"] != 0 else "",
"power": self.units[unit]["power"] - obj.units[unit]["power"]
}
else:
raise Exception("Measurements have different prefixes. Division not supported.")
return Unit(newunits)
else:
return self.__mul__(1/obj)
def __rtruediv__(self,obj):
newunits = {
unit: {
"prefix": self.units[unit]["prefix"],
"power": -self.units[unit]["power"]
} for unit in Unit.knownUnits
}
tmpUnit = Unit(newunits)
return tmpUnit.__mul__(obj)
def __pow__(self,obj):
newunits = {
unit: {
"prefix": self.units[unit]["prefix"],
"power": self.units[unit]["power"] * obj
} for unit in Unit.knownUnits
}
return Unit(newunits)
| true | true |
1c2bb33a3b8e73cc82ea9b94f589fefd41185f7c | 393 | py | Python | api/views.py | MosenzonTal/Cloudi | 65bb04c50584b02f909bf84d6323a9c6a02e819b | [
"FSFAP"
] | null | null | null | api/views.py | MosenzonTal/Cloudi | 65bb04c50584b02f909bf84d6323a9c6a02e819b | [
"FSFAP"
] | null | null | null | api/views.py | MosenzonTal/Cloudi | 65bb04c50584b02f909bf84d6323a9c6a02e819b | [
"FSFAP"
] | 1 | 2021-07-04T10:51:54.000Z | 2021-07-04T10:51:54.000Z | from rest_framework import viewsets
from cloudinis.models import ActivatedPolicy, Violation
from .serializers import *
class ActivatedPolicyView(viewsets.ModelViewSet):
queryset = ActivatedPolicy.objects.all()
serializer_class = ActivatedPolicySerializer
class ViolationView(viewsets.ModelViewSet):
queryset = Violation.objects.all()
serializer_class = ViolationSerializer
| 28.071429 | 55 | 0.814249 | from rest_framework import viewsets
from cloudinis.models import ActivatedPolicy, Violation
from .serializers import *
class ActivatedPolicyView(viewsets.ModelViewSet):
queryset = ActivatedPolicy.objects.all()
serializer_class = ActivatedPolicySerializer
class ViolationView(viewsets.ModelViewSet):
queryset = Violation.objects.all()
serializer_class = ViolationSerializer
| true | true |
1c2bb39539fa4821abad2e9a2b3c423d36ef5556 | 31,431 | py | Python | test-models/tf-models-r1.11/official/resnet/resnet_run_loop_hvd_imagenet_300.py | Shigangli/eager-SGD | d96905ae5c88ab65fb0c7aa064d7937ca131799f | [
"Apache-2.0"
] | 6 | 2020-06-04T07:14:11.000Z | 2021-09-24T05:50:24.000Z | test-models/tf-models-r1.11/official/resnet/resnet_run_loop_hvd_imagenet_300.py | Shigangli/eager-SGD | d96905ae5c88ab65fb0c7aa064d7937ca131799f | [
"Apache-2.0"
] | 1 | 2021-03-31T22:01:00.000Z | 2021-03-31T22:01:00.000Z | test-models/tf-models-r1.11/official/resnet/resnet_run_loop_hvd_imagenet_300.py | Shigangli/eager-SGD | d96905ae5c88ab65fb0c7aa064d7937ca131799f | [
"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.
# ==============================================================================
"""Contains utility and supporting functions for ResNet.
This module contains ResNet code which does not directly build layers. This
includes dataset management, hyperparameter and optimizer code, and argument
parsing. Code for defining the ResNet layers can be found in resnet_model.py.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import os
# pylint: disable=g-bad-import-order
from absl import flags
import tensorflow as tf
import time
import numpy as np
from official.resnet import resnet_model, lars_util
from official.utils.flags import core as flags_core
from official.utils.export import export
from official.utils.logs import hooks_helper
from official.utils.logs import logger
from official.utils.misc import distribution_utils
from official.utils.misc import model_helpers
# pylint: enable=g-bad-import-order
counter = 0
#try:
# from official.utils.opt_sgd_mpi import EagerSGDOptimizer
#except: # In case of import errors (ImportError, ModuleNotFoundError)
# EagerSGDOptimizer = None
################################################################################
# Functions for input processing.
################################################################################
def process_record_dataset(dataset, is_training, batch_size, shuffle_buffer,
parse_record_fn, preprocess_fn=None, num_epochs=1, num_gpus=None,
examples_per_epoch=None, batchaug_m=1, num_workers=1):
"""Given a Dataset with raw records, return an iterator over the records.
Args:
dataset: A Dataset representing raw records
is_training: A boolean denoting whether the input is for training.
batch_size: The number of samples per batch.
shuffle_buffer: The buffer size to use when shuffling records. A larger
value results in better randomness, but smaller values reduce startup
time and use less memory.
parse_record_fn: A function that takes a raw record and returns the
corresponding (image, label) pair.
num_epochs: The number of epochs to repeat the dataset.
num_gpus: The number of gpus used for training.
examples_per_epoch: The number of examples in an epoch.
Returns:
Dataset of (image, label) pairs ready for iteration.
"""
# We prefetch a batch at a time, This can help smooth out the time taken to
# load input files as we go through shuffling and processing.
dataset = dataset.prefetch(buffer_size=batch_size)
if is_training:
# Shuffle the records. Note that we shuffle before repeating to ensure
# that the shuffling respects epoch boundaries.
seed = None
if flags.FLAGS.shuffleaug > 1:
rank = 0
if flags.FLAGS.horovod:
from horovod import tensorflow as hvd
rank = hvd.rank()
seed = flags.FLAGS.baseseed + int(rank // flags.FLAGS.shuffleaug)
dataset = dataset.shuffle(buffer_size=shuffle_buffer, seed=seed)
# If we are training over multiple epochs before evaluating, repeat the
# dataset for the appropriate number of epochs.
dataset = dataset.repeat(num_epochs)
# Adapt epoch length to the number of workers
if is_training and num_workers > 1:
dataset = dataset.take(((examples_per_epoch * num_epochs) // batch_size // num_workers) * batch_size)
if is_training and num_gpus and examples_per_epoch:
total_examples = num_epochs * examples_per_epoch
# Force the number of batches to be divisible by the number of devices.
# This prevents some devices from receiving batches while others do not,
# which can lead to a lockup. This case will soon be handled directly by
# distribution strategies, at which point this .take() operation will no
# longer be needed.
total_batches = total_examples // batch_size // num_gpus * num_gpus
dataset.take(total_batches * batch_size)
# Parse the raw records into images and labels. Testing has shown that setting
# num_parallel_batches > 1 produces no improvement in throughput, since
# batch_size is almost always much greater than the number of CPU cores.
dataset = dataset.apply(
#tf.data.experimental.map_and_batch(
tf.contrib.data.map_and_batch(
lambda value: parse_record_fn(value, is_training, batchaug_m),
batch_size=batch_size // num_workers,
num_parallel_batches=1,
drop_remainder=True))
# Preprocess after batching
if preprocess_fn is not None:
dataset = dataset.map(lambda *args: preprocess_fn(args, is_training))
# Operations between the final prefetch and the get_next call to the iterator
# will happen synchronously during run time. We prefetch here again to
# background all of the above processing work and keep it out of the
# critical training path. Setting buffer_size to tf.contrib.data.AUTOTUNE
# allows DistributionStrategies to adjust how many batches to fetch based
# on how many devices are present.
dataset = dataset.prefetch(buffer_size=tf.contrib.data.AUTOTUNE)
return dataset
def get_synth_input_fn(height, width, num_channels, num_classes):
"""Returns an input function that returns a dataset with zeroes.
This is useful in debugging input pipeline performance, as it removes all
elements of file reading and image preprocessing.
Args:
height: Integer height that will be used to create a fake image tensor.
width: Integer width that will be used to create a fake image tensor.
num_channels: Integer depth that will be used to create a fake image tensor.
num_classes: Number of classes that should be represented in the fake labels
tensor
Returns:
An input_fn that can be used in place of a real one to return a dataset
that can be used for iteration.
"""
def input_fn(is_training, data_dir, batch_size, *args, **kwargs): # pylint: disable=unused-argument
return model_helpers.generate_synthetic_data(
input_shape=tf.TensorShape([batch_size, height, width, num_channels]),
input_dtype=tf.float32,
label_shape=tf.TensorShape([batch_size]),
label_dtype=tf.int32)
return input_fn
################################################################################
# Functions for running training/eval/validation loops for the model.
################################################################################
def learning_rate_with_decay(
batch_size, batch_denom, num_images, boundary_epochs, decay_rates,
base_lr=0.1, warmup=False):
"""Get a learning rate that decays step-wise as training progresses.
Args:
batch_size: the number of examples processed in each training batch.
batch_denom: this value will be used to scale the base learning rate.
`0.1 * batch size` is divided by this number, such that when
batch_denom == batch_size, the initial learning rate will be 0.1.
num_images: total number of images that will be used for training.
boundary_epochs: list of ints representing the epochs at which we
decay the learning rate.
decay_rates: list of floats representing the decay rates to be used
for scaling the learning rate. It should have one more element
than `boundary_epochs`, and all elements should have the same type.
base_lr: Initial learning rate scaled based on batch_denom.
warmup: Run a 5 epoch warmup to the initial lr.
Returns:
Returns a function that takes a single argument - the number of batches
trained so far (global_step)- and returns the learning rate to be used
for training the next batch.
"""
if flags.FLAGS.disablewarmup:
warmup = False
tf.logging.info('Disabled warmup')
initial_learning_rate = base_lr * batch_size / batch_denom
batches_per_epoch = num_images / batch_size
# Reduce the learning rate at certain epochs.
# CIFAR-10: divide by 10 at epoch 100, 150, and 200
# ImageNet: divide by 10 at epoch 30, 60, 80, and 90
boundaries = [int(batches_per_epoch * epoch) for epoch in boundary_epochs]
vals = [initial_learning_rate * decay for decay in decay_rates]
def learning_rate_fn(step):
"""Builds scaled learning rate function with 5 epoch warm up."""
global_step = step + flags.FLAGS.start_epoch
lr = tf.train.piecewise_constant(global_step, boundaries, vals)
if warmup:
warmup_steps = int(batches_per_epoch * 5)
# For warmup that begins at 0.1, add "base_lr + ..."
# - base_lr
warmup_lr = (
((initial_learning_rate * tf.cast(global_step, tf.float32)) / tf.cast(
warmup_steps, tf.float32)))
return tf.cond(global_step < warmup_steps, lambda: warmup_lr, lambda: lr)
return lr
return learning_rate_fn
def resnet_model_fn(features, labels, mode, model_class,
resnet_size, weight_decay, learning_rate_fn, batch_size, momentum,
data_format, resnet_version, loss_scale,
loss_filter_fn=None, dtype=resnet_model.DEFAULT_DTYPE,
fine_tune=False):
"""Shared functionality for different resnet model_fns.
Initializes the ResnetModel representing the model layers
and uses that model to build the necessary EstimatorSpecs for
the `mode` in question. For training, this means building losses,
the optimizer, and the train op that get passed into the EstimatorSpec.
For evaluation and prediction, the EstimatorSpec is returned without
a train op, but with the necessary parameters for the given mode.
Args:
features: tensor representing input images
labels: tensor representing class labels for all input images
mode: current estimator mode; should be one of
`tf.estimator.ModeKeys.TRAIN`, `EVALUATE`, `PREDICT`
model_class: a class representing a TensorFlow model that has a __call__
function. We assume here that this is a subclass of ResnetModel.
resnet_size: A single integer for the size of the ResNet model.
weight_decay: weight decay loss rate used to regularize learned variables.
learning_rate_fn: function that returns the current learning rate given
the current global_step
momentum: momentum term used for optimization
data_format: Input format ('channels_last', 'channels_first', or None).
If set to None, the format is dependent on whether a GPU is available.
resnet_version: Integer representing which version of the ResNet network to
use. See README for details. Valid values: [1, 2]
loss_scale: The factor to scale the loss for numerical stability. A detailed
summary is present in the arg parser help text.
loss_filter_fn: function that takes a string variable name and returns
True if the var should be included in loss calculation, and False
otherwise. If None, batch_normalization variables will be excluded
from the loss.
dtype: the TensorFlow dtype to use for calculations.
fine_tune: If True only train the dense layers(final layers).
Returns:
EstimatorSpec parameterized according to the input params and the
current mode.
"""
tf.logging.info('Final tensor: %s' % str(features))
#if mode == tf.estimator.ModeKeys.TRAIN:
# rank = 0
# if flags.FLAGS.horovod:
# from horovod import tensorflow as hvd
# rank = hvd.rank()
# features = tf.Print(features, [labels], 'LABELS from rank %d: ' % rank, summarize=200)
# features = tf.Print(features, [features], 'FEATURES from rank %d: ' % rank, summarize=200)
# Generate a summary node for the images
tf.summary.image('images', features, max_outputs=6)
features = tf.cast(features, dtype)
model = model_class(resnet_size, data_format, resnet_version=resnet_version,
dtype=dtype)
fs = features.get_shape()
global counter
counter = counter + 1
np.random.seed(counter)
def my_func(x):
if hvd.rank() == np.random.randint(hvd.size()) or hvd.rank() == np.random.randint(hvd.size()):
time.sleep(0.32)
return x
features = tf.py_func(my_func, [features], tf.float32)
features.set_shape(fs)
logits = model(features, mode == tf.estimator.ModeKeys.TRAIN)
# This acts as a no-op if the logits are already in fp32 (provided logits are
# not a SparseTensor). If dtype is is low precision, logits must be cast to
# fp32 for numerical stability.
logits = tf.cast(logits, tf.float32)
predictions = {
'classes': tf.argmax(logits, axis=1),
'probabilities': tf.nn.softmax(logits, name='softmax_tensor')
}
if mode == tf.estimator.ModeKeys.PREDICT:
# Return the predictions and the specification for serving a SavedModel
return tf.estimator.EstimatorSpec(
mode=mode,
predictions=predictions,
export_outputs={
'predict': tf.estimator.export.PredictOutput(predictions)
})
# Calculate loss, which includes softmax cross entropy and L2 regularization.
cross_entropy = tf.losses.sparse_softmax_cross_entropy(
logits=logits, labels=labels)
# Create a tensor named cross_entropy for logging purposes.
tf.identity(cross_entropy, name='cross_entropy')
tf.summary.scalar('cross_entropy', cross_entropy)
# If no loss_filter_fn is passed, assume we want the default behavior,
# which is that batch_normalization variables are excluded from loss.
def exclude_batch_norm(name):
return 'batch_normalization' not in name
loss_filter_fn = loss_filter_fn or exclude_batch_norm
if not flags.FLAGS.lars:
# Add weight decay to the loss.
l2_loss = weight_decay * tf.add_n(
# loss is computed using fp32 for numerical stability.
[tf.nn.l2_loss(tf.cast(v, tf.float32)) for v in tf.trainable_variables()
if loss_filter_fn(v.name)])
tf.summary.scalar('l2_loss', l2_loss)
loss = cross_entropy + l2_loss
else:
tf.summary.scalar('l2_loss', 0)
loss = cross_entropy
if mode == tf.estimator.ModeKeys.TRAIN:
global_step = tf.train.get_or_create_global_step()
learning_rate = learning_rate_fn(global_step)
# Create a tensor named learning_rate for logging purposes
tf.identity(learning_rate, name='learning_rate')
tf.summary.scalar('learning_rate', learning_rate)
# From imagenet_main.py
_NUM_TRAIN_IMAGES = 1281167
steps_per_epoch = _NUM_TRAIN_IMAGES // batch_size
current_epoch = (tf.cast(global_step, tf.float32) /
steps_per_epoch)
trainmode = 1
if flags.FLAGS.lars:
tf.logging.info('Using LARS')
optimizer = lars_util.init_lars_optimizer(current_epoch, batch_size, momentum,
weight_decay)
else:
optimizer = tf.train.MomentumOptimizer(
learning_rate=learning_rate,
momentum=momentum
)
if flags.FLAGS.horovod:
tf.logging.info('Enabling Horovod distributed optimizer')
from horovod import tensorflow as hvd
optimizer = hvd.DistributedOptimizer(optimizer)
#elif flags.FLAGS.solodance:
# from deep500.lv3.communication import CommunicationNetwork
# tf.logging.info('Enabling Deep500 distributed optimizer')
# comm = CommunicationNetwork()
# optimizer = EagerSGDOptimizer(optimizer, comm.size)
def _dense_grad_filter(gvs):
"""Only apply gradient updates to the final layer.
This function is used for fine tuning.
Args:
gvs: list of tuples with gradients and variable info
Returns:
filtered gradients so that only the dense layer remains
"""
return [(g, v) for g, v in gvs if 'dense' in v.name]
if loss_scale != 1:
# When computing fp16 gradients, often intermediate tensor values are
# so small, they underflow to 0. To avoid this, we multiply the loss by
# loss_scale to make these tensor values loss_scale times bigger.
scaled_grad_vars = optimizer.compute_gradients(loss * loss_scale)
if fine_tune:
scaled_grad_vars = _dense_grad_filter(scaled_grad_vars)
# Once the gradient computation is complete we can scale the gradients
# back to the correct scale before passing them to the optimizer.
unscaled_grad_vars = [(grad / loss_scale, var)
for grad, var in scaled_grad_vars]
minimize_op = optimizer.apply_gradients(unscaled_grad_vars, global_step)
else:
grad_vars = optimizer.compute_gradients(loss)
if fine_tune:
grad_vars = _dense_grad_filter(grad_vars)
minimize_op = optimizer.apply_gradients(grad_vars, global_step)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
train_op = tf.group(minimize_op, update_ops)
else:
# From imagenet_main.py
_NUM_VAL_IMAGES = 50000
steps_per_epoch = _NUM_VAL_IMAGES // batch_size
current_epoch = 0
trainmode = 0
train_op = None
accuracy = tf.metrics.accuracy(labels, predictions['classes'])
accuracy_top_5 = tf.metrics.mean(tf.nn.in_top_k(predictions=logits,
targets=labels,
k=5,
name='top_5_op'))
metrics = {'accuracy': accuracy,
'accuracy_top_5': accuracy_top_5}
# Create a tensor named train_accuracy for logging purposes
tf.identity(accuracy[1], name='train_accuracy')
tf.identity(accuracy_top_5[1], name='train_accuracy_top_5')
tf.summary.scalar('train_accuracy', accuracy[1])
tf.summary.scalar('train_accuracy_top_5', accuracy_top_5[1])
tf.identity(current_epoch, name='current_epoch')
tf.summary.scalar('current_epoch', current_epoch)
tf.identity(steps_per_epoch, name='steps_per_epoch')
tf.summary.scalar('steps_per_epoch', steps_per_epoch)
tf.identity(trainmode, name='trainmode')
tf.summary.scalar('trainmode', trainmode)
return tf.estimator.EstimatorSpec(
mode=mode,
predictions=predictions,
loss=loss,
train_op=train_op,
eval_metric_ops=metrics)
def resnet_main(
flags_obj, model_function, input_function, dataset_name, shape=None):
"""Shared main loop for ResNet Models.
Args:
flags_obj: An object containing parsed flags. See define_resnet_flags()
for details.
model_function: the function that instantiates the Model and builds the
ops for train/eval. This will be passed directly into the estimator.
input_function: the function that processes the dataset and returns a
dataset that the estimator can train on. This will be wrapped with
all the relevant flags for running and passed to estimator.
dataset_name: the name of the dataset for training and evaluation. This is
used for logging purpose.
shape: list of ints representing the shape of the images used for training.
This is only used if flags_obj.export_dir is passed.
"""
model_helpers.apply_clean(flags.FLAGS)
#if flags.FLAGS.horovod and flags.FLAGS.solodance:
# raise ValueError('Horovod and Deep500/Solodance flags are incompatible!')
exporter = True
num_workers = 1
pid = -1
if flags.FLAGS.horovod:
from horovod import tensorflow as hvd
hvd.init()
if hvd.rank() != 0:
exporter = False
tf.logging.set_verbosity(tf.logging.ERROR)
pid = hvd.rank()
num_workers = int(hvd.size() // flags.FLAGS.shuffleaug)
tf.logging.error('Horovod initialized, rank %d / %d' % (hvd.rank(), hvd.size()))
#elif flags.FLAGS.solodance:
# if EagerSGDOptimizer is None:
# raise ImportError('SoloDance could not be imported. Deep500 is required')
# from deep500.lv3.communication import CommunicationNetwork
# comm = CommunicationNetwork()
# pid = comm.rank
# if comm.rank != 0:
# exporter = False
# tf.logging.set_verbosity(tf.logging.ERROR)
# num_workers = int(comm.size // flags.FLAGS.shuffleaug)
# tf.logging.error('D500 communication initialized, rank %d / %d' % (comm.rank, comm.size))
#
# # Set joint random seed instead of broadcasting variables
# # TODO: Enable broadcasting
# if flags.FLAGS.baseseed > 0:
# tf.set_random_seed(flags.FLAGS.baseseed)
# Using the Winograd non-fused algorithms provides a small performance boost.
os.environ['TF_ENABLE_WINOGRAD_NONFUSED'] = '1'
# Create session config based on values of inter_op_parallelism_threads and
# intra_op_parallelism_threads. Note that we default to having
# allow_soft_placement = True, which is required for multi-GPU and not
# harmful for other modes.
session_config = tf.ConfigProto(
inter_op_parallelism_threads=flags_obj.inter_op_parallelism_threads,
intra_op_parallelism_threads=flags_obj.intra_op_parallelism_threads,
allow_soft_placement=True)
if flags_obj.horovod:
#session_config.gpu_options.allow_growth = True
session_config.gpu_options.visible_device_list = str(hvd.local_rank())
if flags_obj.xla:
session_config.graph_options.optimizer_options.global_jit_level = tf.OptimizerOptions.ON_1
distribution_strategy = distribution_utils.get_distribution_strategy(
flags_core.get_num_gpus(flags_obj), flags_obj.all_reduce_alg)
run_config = tf.estimator.RunConfig(
train_distribute=distribution_strategy,
session_config=session_config,
save_checkpoints_secs=60*60*24)
# initialize our model with all but the dense layer from pretrained resnet
if flags_obj.pretrained_model_checkpoint_path is not None:
warm_start_settings = tf.estimator.WarmStartSettings(
flags_obj.pretrained_model_checkpoint_path,
vars_to_warm_start='^(?!.*dense)')
else:
warm_start_settings = None
classifier = tf.estimator.Estimator(
model_fn=model_function,
#model_dir=flags_obj.model_dir if exporter else None,
#model_dir=flags_obj.model_dir,
model_dir=os.path.join(flags_obj.model_dir, str(pid)),
config=run_config,
warm_start_from=warm_start_settings, params={
'resnet_size': int(flags_obj.resnet_size),
'data_format': flags_obj.data_format,
'batch_size': flags_obj.batch_size * num_workers,
'resnet_version': int(flags_obj.resnet_version),
'loss_scale': flags_core.get_loss_scale(flags_obj),
'dtype': flags_core.get_tf_dtype(flags_obj),
'fine_tune': flags_obj.fine_tune
})
run_params = {
'batch_size': flags_obj.batch_size * num_workers,
'dtype': flags_core.get_tf_dtype(flags_obj),
'resnet_size': flags_obj.resnet_size,
'resnet_version': flags_obj.resnet_version,
'synthetic_data': flags_obj.use_synthetic_data,
'train_epochs': flags_obj.train_epochs,
}
if flags_obj.use_synthetic_data:
dataset_name = dataset_name + '-synthetic'
benchmark_logger = logger.get_benchmark_logger()
benchmark_logger.log_run_info('resnet', dataset_name, run_params,
test_id=flags_obj.benchmark_test_id)
def log_formatter(fields):
if not exporter:
return None
epoch = int(fields['current_epoch'])
progress = fields['current_epoch'] - epoch
# 'Time {dt:.3f}\t'
return str('{mode} - Epoch: [{epoch}][{step}/{steps_per_epoch}]\t'
'LR {lr:.4f}\t'
'Loss {loss:.4f}\t'
'Prec@1 {prec1:.3f}\t'
'Prec@5 {prec5:.3f}\t'
.format(mode='TRAINING' if fields['trainmode'] == 1 else 'EVALUATING',
epoch=epoch,
step=int(progress*fields['steps_per_epoch']),
steps_per_epoch=fields['steps_per_epoch'],
lr=fields['learning_rate'],
loss=fields['cross_entropy'],
prec1=(fields['train_accuracy'] * 100.0),
prec5=(fields['train_accuracy_top_5'] * 100.0)
))
train_hooks = hooks_helper.get_train_hooks(
flags_obj.hooks,
#model_dir=flags_obj.model_dir,
model_dir=os.path.join(flags_obj.model_dir, str(pid)),
batch_size=flags_obj.batch_size * num_workers,
every_n_iter=flags_obj.train_acc_steps,
tensors_to_log={x:x for x in [
'current_epoch',
'steps_per_epoch',
'trainmode',
'global_step',
'learning_rate',
'cross_entropy',
'train_accuracy',
'train_accuracy_top_5']},
formatter=log_formatter
)
if flags_obj.horovod:
train_hooks.append(hvd.BroadcastGlobalVariablesHook(0))
def input_fn_train(num_epochs):
return input_function(
is_training=True, data_dir=flags_obj.data_dir,
batch_size=num_workers * distribution_utils.per_device_batch_size(
flags_obj.batch_size, flags_core.get_num_gpus(flags_obj)),
num_epochs=num_epochs,
num_gpus=flags_core.get_num_gpus(flags_obj),
batchaug_m=flags_obj.batchaug,
num_workers=num_workers)
def input_fn_eval():
return input_function(
is_training=False, data_dir=flags_obj.data_dir,
batch_size=distribution_utils.per_device_batch_size(
flags_obj.batch_size, flags_core.get_num_gpus(flags_obj)),
num_epochs=1, batchaug_m=1, num_workers=1)
if flags_obj.eval_only or not flags_obj.train_epochs:
# If --eval_only is set, perform a single loop with zero train epochs.
schedule, n_loops = [0], 1
else:
# Compute the number of times to loop while training. All but the last
# pass will train for `epochs_between_evals` epochs, while the last will
# train for the number needed to reach `training_epochs`. For instance if
# train_epochs = 25 and epochs_between_evals = 10
# schedule will be set to [10, 10, 5]. That is to say, the loop will:
# Train for 10 epochs and then evaluate.
# Train for another 10 epochs and then evaluate.
# Train for a final 5 epochs (to reach 25 epochs) and then evaluate.
n_loops = math.ceil(flags_obj.train_epochs / flags_obj.epochs_between_evals)
schedule = [flags_obj.epochs_between_evals for _ in range(int(n_loops))]
schedule[-1] = flags_obj.train_epochs - sum(schedule[:-1]) # over counting.
for cycle_index, num_train_epochs in enumerate(schedule):
tf.logging.info('Starting cycle: %d/%d', cycle_index, int(n_loops))
if num_train_epochs:
classifier.train(input_fn=lambda: input_fn_train(num_train_epochs),
hooks=train_hooks, max_steps=flags_obj.max_train_steps)
tf.logging.info('Starting to evaluate.')
# flags_obj.max_train_steps is generally associated with testing and
# profiling. As a result it is frequently called with synthetic data, which
# will iterate forever. Passing steps=flags_obj.max_train_steps allows the
# eval (which is generally unimportant in those circumstances) to terminate.
# Note that eval will run for max_train_steps each loop, regardless of the
# global_step count.
eval_results = classifier.evaluate(input_fn=input_fn_eval,
steps=flags_obj.max_train_steps)
benchmark_logger.log_evaluation_result(eval_results)
if model_helpers.past_stop_threshold(
flags_obj.stop_threshold, eval_results['accuracy']):
break
if flags_obj.export_dir is not None and exporter:
# Exports a saved model for the given classifier.
input_receiver_fn = export.build_tensor_serving_input_receiver_fn(
shape, batch_size=flags_obj.batch_size * num_workers)
classifier.export_savedmodel(flags_obj.export_dir, input_receiver_fn)
def define_resnet_flags(resnet_size_choices=None):
"""Add flags and validators for ResNet."""
flags_core.define_base()
flags_core.define_performance(num_parallel_calls=False)
flags_core.define_image()
flags_core.define_benchmark()
flags.adopt_module_key_flags(flags_core)
flags.DEFINE_integer(name='batchaug', short_name='aug', default=1,
help='Number of duplicates per image for batch augmentation')
flags.DEFINE_integer(name='shuffleaug', short_name='saug', default=1,
help='Number of duplicates per image for batch augmentation')
flags.DEFINE_integer(name='baseseed', short_name='bse', default=1234,
help='Base random seed')
flags.DEFINE_integer(name='regime', short_name='fr', default=0,
help='Use a certain LR schedule (0-2, higher is faster)')
flags.DEFINE_float(name='lrmult', short_name='lrm', default=1.0,
help=('Base learning rate multiplier.'))
flags.DEFINE_bool(name='disablewarmup', short_name='dwu', default=False,
help='Disable warmup')
flags.DEFINE_integer(name='start_epoch', short_name='sep', default=0,
help='Epoch to start from (LR schedule)')
flags.DEFINE_bool(name='horovod', short_name='hvd', default=False,
help='Use Horovod for distributed training')
#flags.DEFINE_bool(name='solodance', short_name='solo', default=False,
# help='Use Deep500/SoloDance for distributed training')
flags.DEFINE_bool(name='xla', short_name='xla', default=False,
help='Use XLA for acceleration')
flags.DEFINE_bool(name='lars', short_name='lars', default=False,
help='Use LARS in training')
flags.DEFINE_float(name='poly_rate', short_name='lpr', default=0.0,
help=('Set LARS/Poly learning rate.'))
flags.DEFINE_integer(name='train_acc_steps', short_name='tas', default=10,
help='Number of steps between train accuracy printouts')
flags.DEFINE_enum(
name='resnet_version', short_name='rv', default='2',
enum_values=['1', '2'],
help=flags_core.help_wrap(
'Version of ResNet. (1 or 2) See README.md for details.'))
flags.DEFINE_bool(
name='fine_tune', short_name='ft', default=False,
help=flags_core.help_wrap(
'If True do not train any parameters except for the final layer.'))
flags.DEFINE_string(
name='pretrained_model_checkpoint_path', short_name='pmcp', default=None,
help=flags_core.help_wrap(
'If not None initialize all the network except the final layer with '
'these values'))
flags.DEFINE_boolean(
name="eval_only", default=False,
help=flags_core.help_wrap('Skip training and only perform evaluation on '
'the latest checkpoint.'))
choice_kwargs = dict(
name='resnet_size', short_name='rs', default='50',
help=flags_core.help_wrap('The size of the ResNet model to use.'))
if resnet_size_choices is None:
flags.DEFINE_string(**choice_kwargs)
else:
flags.DEFINE_enum(enum_values=resnet_size_choices, **choice_kwargs)
| 41.520476 | 105 | 0.698101 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import os
from absl import flags
import tensorflow as tf
import time
import numpy as np
from official.resnet import resnet_model, lars_util
from official.utils.flags import core as flags_core
from official.utils.export import export
from official.utils.logs import hooks_helper
from official.utils.logs import logger
from official.utils.misc import distribution_utils
from official.utils.misc import model_helpers
counter = 0
h_size, flags_core.get_num_gpus(flags_obj)),
num_epochs=num_epochs,
num_gpus=flags_core.get_num_gpus(flags_obj),
batchaug_m=flags_obj.batchaug,
num_workers=num_workers)
def input_fn_eval():
return input_function(
is_training=False, data_dir=flags_obj.data_dir,
batch_size=distribution_utils.per_device_batch_size(
flags_obj.batch_size, flags_core.get_num_gpus(flags_obj)),
num_epochs=1, batchaug_m=1, num_workers=1)
if flags_obj.eval_only or not flags_obj.train_epochs:
schedule, n_loops = [0], 1
else:
n_loops = math.ceil(flags_obj.train_epochs / flags_obj.epochs_between_evals)
schedule = [flags_obj.epochs_between_evals for _ in range(int(n_loops))]
schedule[-1] = flags_obj.train_epochs - sum(schedule[:-1])
for cycle_index, num_train_epochs in enumerate(schedule):
tf.logging.info('Starting cycle: %d/%d', cycle_index, int(n_loops))
if num_train_epochs:
classifier.train(input_fn=lambda: input_fn_train(num_train_epochs),
hooks=train_hooks, max_steps=flags_obj.max_train_steps)
tf.logging.info('Starting to evaluate.')
eval_results = classifier.evaluate(input_fn=input_fn_eval,
steps=flags_obj.max_train_steps)
benchmark_logger.log_evaluation_result(eval_results)
if model_helpers.past_stop_threshold(
flags_obj.stop_threshold, eval_results['accuracy']):
break
if flags_obj.export_dir is not None and exporter:
input_receiver_fn = export.build_tensor_serving_input_receiver_fn(
shape, batch_size=flags_obj.batch_size * num_workers)
classifier.export_savedmodel(flags_obj.export_dir, input_receiver_fn)
def define_resnet_flags(resnet_size_choices=None):
flags_core.define_base()
flags_core.define_performance(num_parallel_calls=False)
flags_core.define_image()
flags_core.define_benchmark()
flags.adopt_module_key_flags(flags_core)
flags.DEFINE_integer(name='batchaug', short_name='aug', default=1,
help='Number of duplicates per image for batch augmentation')
flags.DEFINE_integer(name='shuffleaug', short_name='saug', default=1,
help='Number of duplicates per image for batch augmentation')
flags.DEFINE_integer(name='baseseed', short_name='bse', default=1234,
help='Base random seed')
flags.DEFINE_integer(name='regime', short_name='fr', default=0,
help='Use a certain LR schedule (0-2, higher is faster)')
flags.DEFINE_float(name='lrmult', short_name='lrm', default=1.0,
help=('Base learning rate multiplier.'))
flags.DEFINE_bool(name='disablewarmup', short_name='dwu', default=False,
help='Disable warmup')
flags.DEFINE_integer(name='start_epoch', short_name='sep', default=0,
help='Epoch to start from (LR schedule)')
flags.DEFINE_bool(name='horovod', short_name='hvd', default=False,
help='Use Horovod for distributed training')
flags.DEFINE_bool(name='xla', short_name='xla', default=False,
help='Use XLA for acceleration')
flags.DEFINE_bool(name='lars', short_name='lars', default=False,
help='Use LARS in training')
flags.DEFINE_float(name='poly_rate', short_name='lpr', default=0.0,
help=('Set LARS/Poly learning rate.'))
flags.DEFINE_integer(name='train_acc_steps', short_name='tas', default=10,
help='Number of steps between train accuracy printouts')
flags.DEFINE_enum(
name='resnet_version', short_name='rv', default='2',
enum_values=['1', '2'],
help=flags_core.help_wrap(
'Version of ResNet. (1 or 2) See README.md for details.'))
flags.DEFINE_bool(
name='fine_tune', short_name='ft', default=False,
help=flags_core.help_wrap(
'If True do not train any parameters except for the final layer.'))
flags.DEFINE_string(
name='pretrained_model_checkpoint_path', short_name='pmcp', default=None,
help=flags_core.help_wrap(
'If not None initialize all the network except the final layer with '
'these values'))
flags.DEFINE_boolean(
name="eval_only", default=False,
help=flags_core.help_wrap('Skip training and only perform evaluation on '
'the latest checkpoint.'))
choice_kwargs = dict(
name='resnet_size', short_name='rs', default='50',
help=flags_core.help_wrap('The size of the ResNet model to use.'))
if resnet_size_choices is None:
flags.DEFINE_string(**choice_kwargs)
else:
flags.DEFINE_enum(enum_values=resnet_size_choices, **choice_kwargs)
| true | true |
1c2bb485d101f7ef12bd988d60f030b89e99a2d2 | 3,508 | py | Python | sphinx_copybutton/__init__.py | pradyunsg/sphinx-copybutton | bdfc41e933582040c7e88a7c751a9558f2161d8c | [
"MIT"
] | 3 | 2020-04-25T19:31:27.000Z | 2020-04-27T14:53:46.000Z | sphinx_copybutton/__init__.py | pradyunsg/sphinx-copybutton | bdfc41e933582040c7e88a7c751a9558f2161d8c | [
"MIT"
] | 3 | 2020-04-21T22:46:51.000Z | 2020-04-23T22:37:53.000Z | sphinx_copybutton/__init__.py | pradyunsg/sphinx-copybutton | bdfc41e933582040c7e88a7c751a9558f2161d8c | [
"MIT"
] | 1 | 2020-04-23T22:14:31.000Z | 2020-04-23T22:14:31.000Z | """A small sphinx extension to add "copy" buttons to code blocks."""
from pathlib import Path
from sphinx.util import logging
__version__ = "0.5.0"
logger = logging.getLogger(__name__)
def scb_static_path(app):
app.config.html_static_path.append(
str(Path(__file__).parent.joinpath("_static").absolute())
)
def add_to_context(app, config):
# Update the global context
config.html_context.update(
{"copybutton_prompt_text": config.copybutton_prompt_text}
)
config.html_context.update(
{"copybutton_prompt_is_regexp": config.copybutton_prompt_is_regexp}
)
config.html_context.update(
{"copybutton_only_copy_prompt_lines": config.copybutton_only_copy_prompt_lines}
)
config.html_context.update(
{"copybutton_remove_prompts": config.copybutton_remove_prompts}
)
config.html_context.update(
{"copybutton_copy_empty_lines": config.copybutton_copy_empty_lines}
)
config.html_context.update(
{
"copybutton_line_continuation_character": (
config.copybutton_line_continuation_character
)
}
)
config.html_context.update(
{"copybutton_here_doc_delimiter": config.copybutton_here_doc_delimiter}
)
# Old image path deprecation
# REMOVE after next release
if config.copybutton_image_path:
path = Path(app.srcdir) / config.copybutton_image_path
logger.warning("copybutton_image_path is deprecated, use copybutton_image_svg")
if not path.exists():
raise ValueError("copybutton_img_path does not exist")
if not path.suffix == ".svg":
raise ValueError("copybutton_img_path must be an SVG")
config.copybutton_image_svg = path.read_text()
config.html_context.update({"copybutton_image_svg": config.copybutton_image_svg})
config.html_context.update({"copybutton_selector": config.copybutton_selector})
config.html_context.update(
{
"copybutton_format_func": Path(__file__)
.parent.joinpath("_static", "copybutton_funcs.js")
.read_text()
.replace("export function", "function")
}
)
def setup(app):
logger.verbose("Adding copy buttons to code blocks...")
# Add our static path
app.connect("builder-inited", scb_static_path)
# configuration for this tool
app.add_config_value("copybutton_prompt_text", "", "html")
app.add_config_value("copybutton_prompt_is_regexp", False, "html")
app.add_config_value("copybutton_only_copy_prompt_lines", True, "html")
app.add_config_value("copybutton_remove_prompts", True, "html")
app.add_config_value("copybutton_copy_empty_lines", True, "html")
app.add_config_value("copybutton_line_continuation_character", "", "html")
app.add_config_value("copybutton_here_doc_delimiter", "", "html")
app.add_config_value("copybutton_image_svg", "", "html")
app.add_config_value("copybutton_selector", "div.highlight pre", "html")
# DEPRECATE THIS AFTER THE NEXT RELEASE
app.add_config_value("copybutton_image_path", "", "html")
# Add configuration value to the template
app.connect("config-inited", add_to_context)
# Add relevant code to headers
app.add_css_file("copybutton.css")
app.add_js_file("clipboard.min.js")
app.add_js_file("copybutton.js")
return {
"version": __version__,
"parallel_read_safe": True,
"parallel_write_safe": True,
}
| 35.434343 | 87 | 0.698689 | from pathlib import Path
from sphinx.util import logging
__version__ = "0.5.0"
logger = logging.getLogger(__name__)
def scb_static_path(app):
app.config.html_static_path.append(
str(Path(__file__).parent.joinpath("_static").absolute())
)
def add_to_context(app, config):
config.html_context.update(
{"copybutton_prompt_text": config.copybutton_prompt_text}
)
config.html_context.update(
{"copybutton_prompt_is_regexp": config.copybutton_prompt_is_regexp}
)
config.html_context.update(
{"copybutton_only_copy_prompt_lines": config.copybutton_only_copy_prompt_lines}
)
config.html_context.update(
{"copybutton_remove_prompts": config.copybutton_remove_prompts}
)
config.html_context.update(
{"copybutton_copy_empty_lines": config.copybutton_copy_empty_lines}
)
config.html_context.update(
{
"copybutton_line_continuation_character": (
config.copybutton_line_continuation_character
)
}
)
config.html_context.update(
{"copybutton_here_doc_delimiter": config.copybutton_here_doc_delimiter}
)
if config.copybutton_image_path:
path = Path(app.srcdir) / config.copybutton_image_path
logger.warning("copybutton_image_path is deprecated, use copybutton_image_svg")
if not path.exists():
raise ValueError("copybutton_img_path does not exist")
if not path.suffix == ".svg":
raise ValueError("copybutton_img_path must be an SVG")
config.copybutton_image_svg = path.read_text()
config.html_context.update({"copybutton_image_svg": config.copybutton_image_svg})
config.html_context.update({"copybutton_selector": config.copybutton_selector})
config.html_context.update(
{
"copybutton_format_func": Path(__file__)
.parent.joinpath("_static", "copybutton_funcs.js")
.read_text()
.replace("export function", "function")
}
)
def setup(app):
logger.verbose("Adding copy buttons to code blocks...")
app.connect("builder-inited", scb_static_path)
app.add_config_value("copybutton_prompt_text", "", "html")
app.add_config_value("copybutton_prompt_is_regexp", False, "html")
app.add_config_value("copybutton_only_copy_prompt_lines", True, "html")
app.add_config_value("copybutton_remove_prompts", True, "html")
app.add_config_value("copybutton_copy_empty_lines", True, "html")
app.add_config_value("copybutton_line_continuation_character", "", "html")
app.add_config_value("copybutton_here_doc_delimiter", "", "html")
app.add_config_value("copybutton_image_svg", "", "html")
app.add_config_value("copybutton_selector", "div.highlight pre", "html")
app.add_config_value("copybutton_image_path", "", "html")
app.connect("config-inited", add_to_context)
app.add_css_file("copybutton.css")
app.add_js_file("clipboard.min.js")
app.add_js_file("copybutton.js")
return {
"version": __version__,
"parallel_read_safe": True,
"parallel_write_safe": True,
}
| true | true |
1c2bb53468dda3156f8e214524049297c4e53b9c | 21,752 | py | Python | zerver/tests/test_presence.py | umairwaheed/zulip | 25a71853da7f51582caddca0a0bcd680f029ada3 | [
"Apache-2.0"
] | 1 | 2021-11-26T04:49:14.000Z | 2021-11-26T04:49:14.000Z | zerver/tests/test_presence.py | umairwaheed/zulip | 25a71853da7f51582caddca0a0bcd680f029ada3 | [
"Apache-2.0"
] | 2 | 2017-06-19T04:40:37.000Z | 2017-06-27T06:58:11.000Z | zerver/tests/test_presence.py | umairwaheed/zulip | 25a71853da7f51582caddca0a0bcd680f029ada3 | [
"Apache-2.0"
] | 2 | 2017-03-30T14:33:59.000Z | 2021-06-17T17:04:58.000Z | # -*- coding: utf-8 -*-
from datetime import timedelta
from django.http import HttpResponse
from django.test import override_settings
from django.utils.timezone import now as timezone_now
from mock import mock
from typing import Any, Dict
from zerver.lib.actions import do_deactivate_user
from zerver.lib.statistics import seconds_usage_between
from zerver.lib.test_helpers import (
make_client,
queries_captured,
)
from zerver.lib.test_classes import (
ZulipTestCase,
)
from zerver.lib.timestamp import datetime_to_timestamp
from zerver.models import (
email_to_domain,
Client,
PushDeviceToken,
UserActivity,
UserActivityInterval,
UserProfile,
UserPresence,
flush_per_request_caches,
get_realm,
)
import datetime
class ActivityTest(ZulipTestCase):
def test_activity(self) -> None:
self.login(self.example_email("hamlet"))
client, _ = Client.objects.get_or_create(name='website')
query = '/json/users/me/pointer'
last_visit = timezone_now()
count = 150
for activity_user_profile in UserProfile.objects.all():
UserActivity.objects.get_or_create(
user_profile=activity_user_profile,
client=client,
query=query,
count=count,
last_visit=last_visit
)
# Fails when not staff
result = self.client_get('/activity')
self.assertEqual(result.status_code, 302)
user_profile = self.example_user("hamlet")
user_profile.is_staff = True
user_profile.save()
flush_per_request_caches()
with queries_captured() as queries:
result = self.client_get('/activity')
self.assertEqual(result.status_code, 200)
self.assert_length(queries, 13)
flush_per_request_caches()
with queries_captured() as queries:
result = self.client_get('/realm_activity/zulip/')
self.assertEqual(result.status_code, 200)
self.assert_length(queries, 9)
flush_per_request_caches()
with queries_captured() as queries:
result = self.client_get('/user_activity/iago@zulip.com/')
self.assertEqual(result.status_code, 200)
self.assert_length(queries, 5)
class TestClientModel(ZulipTestCase):
def test_client_stringification(self) -> None:
'''
This test is designed to cover __str__ method for Client.
'''
client = make_client('some_client')
self.assertEqual(str(client), '<Client: some_client>')
class UserPresenceModelTests(ZulipTestCase):
def test_date_logic(self) -> None:
UserPresence.objects.all().delete()
user_profile = self.example_user('hamlet')
email = user_profile.email
presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id)
self.assertEqual(len(presence_dct), 0)
self.login(email)
result = self.client_post("/json/users/me/presence", {'status': 'active'})
self.assert_json_success(result)
presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id)
self.assertEqual(len(presence_dct), 1)
self.assertEqual(presence_dct[email]['website']['status'], 'active')
def back_date(num_weeks: int) -> None:
user_presence = UserPresence.objects.filter(user_profile=user_profile)[0]
user_presence.timestamp = timezone_now() - datetime.timedelta(weeks=num_weeks)
user_presence.save()
# Simulate the presence being a week old first. Nothing should change.
back_date(num_weeks=1)
presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id)
self.assertEqual(len(presence_dct), 1)
# If the UserPresence row is three weeks old, we ignore it.
back_date(num_weeks=3)
presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id)
self.assertEqual(len(presence_dct), 0)
def test_push_tokens(self) -> None:
UserPresence.objects.all().delete()
user_profile = self.example_user('hamlet')
email = user_profile.email
self.login(email)
result = self.client_post("/json/users/me/presence", {'status': 'active'})
self.assert_json_success(result)
def pushable() -> bool:
presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id)
self.assertEqual(len(presence_dct), 1)
return presence_dct[email]['website']['pushable']
self.assertFalse(pushable())
user_profile.enable_offline_push_notifications = True
user_profile.save()
self.assertFalse(pushable())
PushDeviceToken.objects.create(
user=user_profile,
kind=PushDeviceToken.APNS
)
self.assertTrue(pushable())
class UserPresenceTests(ZulipTestCase):
def test_invalid_presence(self) -> None:
email = self.example_email("hamlet")
self.login(email)
result = self.client_post("/json/users/me/presence", {'status': 'foo'})
self.assert_json_error(result, 'Invalid status: foo')
def test_set_idle(self) -> None:
email = self.example_email("hamlet")
self.login(email)
client = 'website'
result = self.client_post("/json/users/me/presence", {'status': 'idle'})
self.assert_json_success(result)
json = result.json()
self.assertEqual(json['presences'][email][client]['status'], 'idle')
self.assertIn('timestamp', json['presences'][email][client])
self.assertIsInstance(json['presences'][email][client]['timestamp'], int)
self.assertEqual(list(json['presences'].keys()), [self.example_email("hamlet")])
timestamp = json['presences'][email][client]['timestamp']
email = self.example_email("othello")
self.login(email)
result = self.client_post("/json/users/me/presence", {'status': 'idle'})
json = result.json()
self.assertEqual(json['presences'][email][client]['status'], 'idle')
self.assertEqual(json['presences'][self.example_email("hamlet")][client]['status'], 'idle')
self.assertEqual(sorted(json['presences'].keys()), [self.example_email("hamlet"), self.example_email("othello")])
newer_timestamp = json['presences'][email][client]['timestamp']
self.assertGreaterEqual(newer_timestamp, timestamp)
def test_set_active(self) -> None:
self.login(self.example_email("hamlet"))
client = 'website'
result = self.client_post("/json/users/me/presence", {'status': 'idle'})
self.assert_json_success(result)
self.assertEqual(result.json()['presences'][self.example_email("hamlet")][client]['status'], 'idle')
email = self.example_email("othello")
self.login(self.example_email("othello"))
result = self.client_post("/json/users/me/presence", {'status': 'idle'})
self.assert_json_success(result)
json = result.json()
self.assertEqual(json['presences'][email][client]['status'], 'idle')
self.assertEqual(json['presences'][self.example_email("hamlet")][client]['status'], 'idle')
result = self.client_post("/json/users/me/presence", {'status': 'active'})
self.assert_json_success(result)
json = result.json()
self.assertEqual(json['presences'][email][client]['status'], 'active')
self.assertEqual(json['presences'][self.example_email("hamlet")][client]['status'], 'idle')
def test_new_user_input(self) -> None:
"""Mostly a test for UserActivityInterval"""
user_profile = self.example_user("hamlet")
self.login(self.example_email("hamlet"))
self.assertEqual(UserActivityInterval.objects.filter(user_profile=user_profile).count(), 0)
time_zero = timezone_now().replace(microsecond=0)
with mock.patch('zerver.views.presence.timezone_now', return_value=time_zero):
result = self.client_post("/json/users/me/presence", {'status': 'active',
'new_user_input': 'true'})
self.assert_json_success(result)
self.assertEqual(UserActivityInterval.objects.filter(user_profile=user_profile).count(), 1)
interval = UserActivityInterval.objects.get(user_profile=user_profile)
self.assertEqual(interval.start, time_zero)
self.assertEqual(interval.end, time_zero + UserActivityInterval.MIN_INTERVAL_LENGTH)
second_time = time_zero + timedelta(seconds=600)
# Extent the interval
with mock.patch('zerver.views.presence.timezone_now', return_value=second_time):
result = self.client_post("/json/users/me/presence", {'status': 'active',
'new_user_input': 'true'})
self.assert_json_success(result)
self.assertEqual(UserActivityInterval.objects.filter(user_profile=user_profile).count(), 1)
interval = UserActivityInterval.objects.get(user_profile=user_profile)
self.assertEqual(interval.start, time_zero)
self.assertEqual(interval.end, second_time + UserActivityInterval.MIN_INTERVAL_LENGTH)
third_time = time_zero + timedelta(seconds=6000)
with mock.patch('zerver.views.presence.timezone_now', return_value=third_time):
result = self.client_post("/json/users/me/presence", {'status': 'active',
'new_user_input': 'true'})
self.assert_json_success(result)
self.assertEqual(UserActivityInterval.objects.filter(user_profile=user_profile).count(), 2)
interval = UserActivityInterval.objects.filter(user_profile=user_profile).order_by('start')[0]
self.assertEqual(interval.start, time_zero)
self.assertEqual(interval.end, second_time + UserActivityInterval.MIN_INTERVAL_LENGTH)
interval = UserActivityInterval.objects.filter(user_profile=user_profile).order_by('start')[1]
self.assertEqual(interval.start, third_time)
self.assertEqual(interval.end, third_time + UserActivityInterval.MIN_INTERVAL_LENGTH)
self.assertEqual(
seconds_usage_between(
user_profile, time_zero, third_time).total_seconds(),
1500)
self.assertEqual(
seconds_usage_between(
user_profile, time_zero, third_time+timedelta(seconds=10)).total_seconds(),
1510)
self.assertEqual(
seconds_usage_between(
user_profile, time_zero, third_time+timedelta(seconds=1000)).total_seconds(),
2400)
self.assertEqual(
seconds_usage_between(
user_profile, time_zero, third_time - timedelta(seconds=100)).total_seconds(),
1500)
self.assertEqual(
seconds_usage_between(
user_profile, time_zero + timedelta(seconds=100),
third_time - timedelta(seconds=100)).total_seconds(),
1400)
self.assertEqual(
seconds_usage_between(
user_profile, time_zero + timedelta(seconds=1200),
third_time - timedelta(seconds=100)).total_seconds(),
300)
# Now test /activity with actual data
user_profile.is_staff = True
user_profile.save()
result = self.client_get('/activity')
self.assertEqual(result.status_code, 200)
def test_filter_presence_idle_user_ids(self) -> None:
user_profile = self.example_user("hamlet")
from zerver.lib.actions import filter_presence_idle_user_ids
self.login(self.example_email("hamlet"))
self.assertEqual(filter_presence_idle_user_ids({user_profile.id}), [user_profile.id])
self.client_post("/json/users/me/presence", {'status': 'idle'})
self.assertEqual(filter_presence_idle_user_ids({user_profile.id}), [user_profile.id])
self.client_post("/json/users/me/presence", {'status': 'active'})
self.assertEqual(filter_presence_idle_user_ids({user_profile.id}), [])
def test_no_mit(self) -> None:
"""Zephyr mirror realms such as MIT never get a list of users"""
self.login(self.mit_email("espuser"), realm=get_realm("zephyr"))
result = self.client_post("/json/users/me/presence", {'status': 'idle'},
subdomain="zephyr")
self.assert_json_success(result)
self.assertEqual(result.json()['presences'], {})
def test_mirror_presence(self) -> None:
"""Zephyr mirror realms find out the status of their mirror bot"""
user_profile = self.mit_user('espuser')
email = user_profile.email
self.login(email, realm=user_profile.realm)
def post_presence() -> Dict[str, Any]:
result = self.client_post("/json/users/me/presence", {'status': 'idle'},
subdomain="zephyr")
self.assert_json_success(result)
json = result.json()
return json
json = post_presence()
self.assertEqual(json['zephyr_mirror_active'], False)
self._simulate_mirror_activity_for_user(user_profile)
json = post_presence()
self.assertEqual(json['zephyr_mirror_active'], True)
def _simulate_mirror_activity_for_user(self, user_profile: UserProfile) -> None:
last_visit = timezone_now()
client = make_client('zephyr_mirror')
UserActivity.objects.get_or_create(
user_profile=user_profile,
client=client,
query='get_events_backend',
count=2,
last_visit=last_visit
)
def test_same_realm(self) -> None:
self.login(self.mit_email("espuser"), realm=get_realm("zephyr"))
self.client_post("/json/users/me/presence", {'status': 'idle'},
subdomain="zephyr")
self.logout()
# Ensure we don't see hamlet@zulip.com information leakage
self.login(self.example_email("hamlet"))
result = self.client_post("/json/users/me/presence", {'status': 'idle'})
self.assert_json_success(result)
json = result.json()
self.assertEqual(json['presences'][self.example_email("hamlet")]["website"]['status'], 'idle')
# We only want @zulip.com emails
for email in json['presences'].keys():
self.assertEqual(email_to_domain(email), 'zulip.com')
class SingleUserPresenceTests(ZulipTestCase):
def test_single_user_get(self) -> None:
# First, we setup the test with some data
email = self.example_email("othello")
self.login(self.example_email("othello"))
result = self.client_post("/json/users/me/presence", {'status': 'active'})
result = self.client_post("/json/users/me/presence", {'status': 'active'},
HTTP_USER_AGENT="ZulipDesktop/1.0")
result = self.api_post(email, "/api/v1/users/me/presence", {'status': 'idle'},
HTTP_USER_AGENT="ZulipAndroid/1.0")
self.assert_json_success(result)
# Check some error conditions
result = self.client_get("/json/users/nonexistence@zulip.com/presence")
self.assert_json_error(result, "No such user")
result = self.client_get("/json/users/cordelia@zulip.com/presence")
self.assert_json_error(result, "No presence data for cordelia@zulip.com")
do_deactivate_user(self.example_user('cordelia'))
result = self.client_get("/json/users/cordelia@zulip.com/presence")
self.assert_json_error(result, "No such user")
result = self.client_get("/json/users/new-user-bot@zulip.com/presence")
self.assert_json_error(result, "Presence is not supported for bot users.")
self.login(self.mit_email("sipbtest"), realm=get_realm("zephyr"))
result = self.client_get("/json/users/othello@zulip.com/presence",
subdomain="zephyr")
self.assert_json_error(result, "No such user")
# Then, we check everything works
self.login(self.example_email("hamlet"))
result = self.client_get("/json/users/othello@zulip.com/presence")
result_dict = result.json()
self.assertEqual(
set(result_dict['presence'].keys()),
{"ZulipAndroid", "website", "aggregated"})
self.assertEqual(set(result_dict['presence']['website'].keys()), {"status", "timestamp"})
def test_ping_only(self) -> None:
self.login(self.example_email("othello"))
req = dict(
status='active',
ping_only='true',
)
result = self.client_post("/json/users/me/presence", req)
self.assertEqual(result.json()['msg'], '')
class UserPresenceAggregationTests(ZulipTestCase):
def _send_presence_for_aggregated_tests(self, email: str, status: str,
validate_time: datetime.datetime) -> Dict[str, Dict[str, Any]]:
self.login(email)
timezone_util = 'zerver.views.presence.timezone_now'
with mock.patch(timezone_util, return_value=validate_time - datetime.timedelta(seconds=5)):
self.client_post("/json/users/me/presence", {'status': status})
with mock.patch(timezone_util, return_value=validate_time - datetime.timedelta(seconds=2)):
self.api_post(email, "/api/v1/users/me/presence", {'status': status},
HTTP_USER_AGENT="ZulipAndroid/1.0")
with mock.patch(timezone_util, return_value=validate_time - datetime.timedelta(seconds=7)):
latest_result = self.api_post(email, "/api/v1/users/me/presence", {'status': status},
HTTP_USER_AGENT="ZulipIOS/1.0")
latest_result_dict = latest_result.json()
self.assertDictEqual(
latest_result_dict['presences'][email]['aggregated'],
{
'status': status,
'timestamp': datetime_to_timestamp(validate_time - datetime.timedelta(seconds=2)),
'client': 'ZulipAndroid'
}
)
result = self.client_get("/json/users/%s/presence" % (email,))
return result.json()
def test_aggregated_info(self) -> None:
email = self.example_email("othello")
validate_time = timezone_now()
self._send_presence_for_aggregated_tests(str(self.example_email("othello")), 'active', validate_time)
with mock.patch('zerver.views.presence.timezone_now',
return_value=validate_time - datetime.timedelta(seconds=1)):
result = self.api_post(email, "/api/v1/users/me/presence", {'status': 'active'},
HTTP_USER_AGENT="ZulipTestDev/1.0")
result_dict = result.json()
self.assertDictEqual(
result_dict['presences'][email]['aggregated'],
{
'status': 'active',
'timestamp': datetime_to_timestamp(validate_time - datetime.timedelta(seconds=1)),
'client': 'ZulipTestDev'
}
)
def test_aggregated_presense_active(self) -> None:
validate_time = timezone_now()
result_dict = self._send_presence_for_aggregated_tests(str(self.example_email("othello")), 'active',
validate_time)
self.assertDictEqual(
result_dict['presence']['aggregated'],
{
"status": "active",
"timestamp": datetime_to_timestamp(validate_time - datetime.timedelta(seconds=2))
}
)
def test_aggregated_presense_idle(self) -> None:
validate_time = timezone_now()
result_dict = self._send_presence_for_aggregated_tests(str(self.example_email("othello")), 'idle',
validate_time)
self.assertDictEqual(
result_dict['presence']['aggregated'],
{
"status": "idle",
"timestamp": datetime_to_timestamp(validate_time - datetime.timedelta(seconds=2))
}
)
def test_aggregated_presense_mixed(self) -> None:
email = self.example_email("othello")
self.login(email)
validate_time = timezone_now()
with mock.patch('zerver.views.presence.timezone_now',
return_value=validate_time - datetime.timedelta(seconds=3)):
self.api_post(email, "/api/v1/users/me/presence", {'status': 'active'},
HTTP_USER_AGENT="ZulipTestDev/1.0")
result_dict = self._send_presence_for_aggregated_tests(str(email), 'idle', validate_time)
self.assertDictEqual(
result_dict['presence']['aggregated'],
{
"status": "idle",
"timestamp": datetime_to_timestamp(validate_time - datetime.timedelta(seconds=2))
}
)
def test_aggregated_presense_offline(self) -> None:
email = self.example_email("othello")
self.login(email)
validate_time = timezone_now()
with self.settings(OFFLINE_THRESHOLD_SECS=1):
result_dict = self._send_presence_for_aggregated_tests(str(email), 'idle', validate_time)
self.assertDictEqual(
result_dict['presence']['aggregated'],
{
"status": "offline",
"timestamp": datetime_to_timestamp(validate_time - datetime.timedelta(seconds=2))
}
)
| 44.57377 | 121 | 0.634884 |
from datetime import timedelta
from django.http import HttpResponse
from django.test import override_settings
from django.utils.timezone import now as timezone_now
from mock import mock
from typing import Any, Dict
from zerver.lib.actions import do_deactivate_user
from zerver.lib.statistics import seconds_usage_between
from zerver.lib.test_helpers import (
make_client,
queries_captured,
)
from zerver.lib.test_classes import (
ZulipTestCase,
)
from zerver.lib.timestamp import datetime_to_timestamp
from zerver.models import (
email_to_domain,
Client,
PushDeviceToken,
UserActivity,
UserActivityInterval,
UserProfile,
UserPresence,
flush_per_request_caches,
get_realm,
)
import datetime
class ActivityTest(ZulipTestCase):
def test_activity(self) -> None:
self.login(self.example_email("hamlet"))
client, _ = Client.objects.get_or_create(name='website')
query = '/json/users/me/pointer'
last_visit = timezone_now()
count = 150
for activity_user_profile in UserProfile.objects.all():
UserActivity.objects.get_or_create(
user_profile=activity_user_profile,
client=client,
query=query,
count=count,
last_visit=last_visit
)
result = self.client_get('/activity')
self.assertEqual(result.status_code, 302)
user_profile = self.example_user("hamlet")
user_profile.is_staff = True
user_profile.save()
flush_per_request_caches()
with queries_captured() as queries:
result = self.client_get('/activity')
self.assertEqual(result.status_code, 200)
self.assert_length(queries, 13)
flush_per_request_caches()
with queries_captured() as queries:
result = self.client_get('/realm_activity/zulip/')
self.assertEqual(result.status_code, 200)
self.assert_length(queries, 9)
flush_per_request_caches()
with queries_captured() as queries:
result = self.client_get('/user_activity/iago@zulip.com/')
self.assertEqual(result.status_code, 200)
self.assert_length(queries, 5)
class TestClientModel(ZulipTestCase):
def test_client_stringification(self) -> None:
client = make_client('some_client')
self.assertEqual(str(client), '<Client: some_client>')
class UserPresenceModelTests(ZulipTestCase):
def test_date_logic(self) -> None:
UserPresence.objects.all().delete()
user_profile = self.example_user('hamlet')
email = user_profile.email
presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id)
self.assertEqual(len(presence_dct), 0)
self.login(email)
result = self.client_post("/json/users/me/presence", {'status': 'active'})
self.assert_json_success(result)
presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id)
self.assertEqual(len(presence_dct), 1)
self.assertEqual(presence_dct[email]['website']['status'], 'active')
def back_date(num_weeks: int) -> None:
user_presence = UserPresence.objects.filter(user_profile=user_profile)[0]
user_presence.timestamp = timezone_now() - datetime.timedelta(weeks=num_weeks)
user_presence.save()
back_date(num_weeks=1)
presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id)
self.assertEqual(len(presence_dct), 1)
back_date(num_weeks=3)
presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id)
self.assertEqual(len(presence_dct), 0)
def test_push_tokens(self) -> None:
UserPresence.objects.all().delete()
user_profile = self.example_user('hamlet')
email = user_profile.email
self.login(email)
result = self.client_post("/json/users/me/presence", {'status': 'active'})
self.assert_json_success(result)
def pushable() -> bool:
presence_dct = UserPresence.get_status_dict_by_realm(user_profile.realm_id)
self.assertEqual(len(presence_dct), 1)
return presence_dct[email]['website']['pushable']
self.assertFalse(pushable())
user_profile.enable_offline_push_notifications = True
user_profile.save()
self.assertFalse(pushable())
PushDeviceToken.objects.create(
user=user_profile,
kind=PushDeviceToken.APNS
)
self.assertTrue(pushable())
class UserPresenceTests(ZulipTestCase):
def test_invalid_presence(self) -> None:
email = self.example_email("hamlet")
self.login(email)
result = self.client_post("/json/users/me/presence", {'status': 'foo'})
self.assert_json_error(result, 'Invalid status: foo')
def test_set_idle(self) -> None:
email = self.example_email("hamlet")
self.login(email)
client = 'website'
result = self.client_post("/json/users/me/presence", {'status': 'idle'})
self.assert_json_success(result)
json = result.json()
self.assertEqual(json['presences'][email][client]['status'], 'idle')
self.assertIn('timestamp', json['presences'][email][client])
self.assertIsInstance(json['presences'][email][client]['timestamp'], int)
self.assertEqual(list(json['presences'].keys()), [self.example_email("hamlet")])
timestamp = json['presences'][email][client]['timestamp']
email = self.example_email("othello")
self.login(email)
result = self.client_post("/json/users/me/presence", {'status': 'idle'})
json = result.json()
self.assertEqual(json['presences'][email][client]['status'], 'idle')
self.assertEqual(json['presences'][self.example_email("hamlet")][client]['status'], 'idle')
self.assertEqual(sorted(json['presences'].keys()), [self.example_email("hamlet"), self.example_email("othello")])
newer_timestamp = json['presences'][email][client]['timestamp']
self.assertGreaterEqual(newer_timestamp, timestamp)
def test_set_active(self) -> None:
self.login(self.example_email("hamlet"))
client = 'website'
result = self.client_post("/json/users/me/presence", {'status': 'idle'})
self.assert_json_success(result)
self.assertEqual(result.json()['presences'][self.example_email("hamlet")][client]['status'], 'idle')
email = self.example_email("othello")
self.login(self.example_email("othello"))
result = self.client_post("/json/users/me/presence", {'status': 'idle'})
self.assert_json_success(result)
json = result.json()
self.assertEqual(json['presences'][email][client]['status'], 'idle')
self.assertEqual(json['presences'][self.example_email("hamlet")][client]['status'], 'idle')
result = self.client_post("/json/users/me/presence", {'status': 'active'})
self.assert_json_success(result)
json = result.json()
self.assertEqual(json['presences'][email][client]['status'], 'active')
self.assertEqual(json['presences'][self.example_email("hamlet")][client]['status'], 'idle')
def test_new_user_input(self) -> None:
user_profile = self.example_user("hamlet")
self.login(self.example_email("hamlet"))
self.assertEqual(UserActivityInterval.objects.filter(user_profile=user_profile).count(), 0)
time_zero = timezone_now().replace(microsecond=0)
with mock.patch('zerver.views.presence.timezone_now', return_value=time_zero):
result = self.client_post("/json/users/me/presence", {'status': 'active',
'new_user_input': 'true'})
self.assert_json_success(result)
self.assertEqual(UserActivityInterval.objects.filter(user_profile=user_profile).count(), 1)
interval = UserActivityInterval.objects.get(user_profile=user_profile)
self.assertEqual(interval.start, time_zero)
self.assertEqual(interval.end, time_zero + UserActivityInterval.MIN_INTERVAL_LENGTH)
second_time = time_zero + timedelta(seconds=600)
with mock.patch('zerver.views.presence.timezone_now', return_value=second_time):
result = self.client_post("/json/users/me/presence", {'status': 'active',
'new_user_input': 'true'})
self.assert_json_success(result)
self.assertEqual(UserActivityInterval.objects.filter(user_profile=user_profile).count(), 1)
interval = UserActivityInterval.objects.get(user_profile=user_profile)
self.assertEqual(interval.start, time_zero)
self.assertEqual(interval.end, second_time + UserActivityInterval.MIN_INTERVAL_LENGTH)
third_time = time_zero + timedelta(seconds=6000)
with mock.patch('zerver.views.presence.timezone_now', return_value=third_time):
result = self.client_post("/json/users/me/presence", {'status': 'active',
'new_user_input': 'true'})
self.assert_json_success(result)
self.assertEqual(UserActivityInterval.objects.filter(user_profile=user_profile).count(), 2)
interval = UserActivityInterval.objects.filter(user_profile=user_profile).order_by('start')[0]
self.assertEqual(interval.start, time_zero)
self.assertEqual(interval.end, second_time + UserActivityInterval.MIN_INTERVAL_LENGTH)
interval = UserActivityInterval.objects.filter(user_profile=user_profile).order_by('start')[1]
self.assertEqual(interval.start, third_time)
self.assertEqual(interval.end, third_time + UserActivityInterval.MIN_INTERVAL_LENGTH)
self.assertEqual(
seconds_usage_between(
user_profile, time_zero, third_time).total_seconds(),
1500)
self.assertEqual(
seconds_usage_between(
user_profile, time_zero, third_time+timedelta(seconds=10)).total_seconds(),
1510)
self.assertEqual(
seconds_usage_between(
user_profile, time_zero, third_time+timedelta(seconds=1000)).total_seconds(),
2400)
self.assertEqual(
seconds_usage_between(
user_profile, time_zero, third_time - timedelta(seconds=100)).total_seconds(),
1500)
self.assertEqual(
seconds_usage_between(
user_profile, time_zero + timedelta(seconds=100),
third_time - timedelta(seconds=100)).total_seconds(),
1400)
self.assertEqual(
seconds_usage_between(
user_profile, time_zero + timedelta(seconds=1200),
third_time - timedelta(seconds=100)).total_seconds(),
300)
user_profile.is_staff = True
user_profile.save()
result = self.client_get('/activity')
self.assertEqual(result.status_code, 200)
def test_filter_presence_idle_user_ids(self) -> None:
user_profile = self.example_user("hamlet")
from zerver.lib.actions import filter_presence_idle_user_ids
self.login(self.example_email("hamlet"))
self.assertEqual(filter_presence_idle_user_ids({user_profile.id}), [user_profile.id])
self.client_post("/json/users/me/presence", {'status': 'idle'})
self.assertEqual(filter_presence_idle_user_ids({user_profile.id}), [user_profile.id])
self.client_post("/json/users/me/presence", {'status': 'active'})
self.assertEqual(filter_presence_idle_user_ids({user_profile.id}), [])
def test_no_mit(self) -> None:
self.login(self.mit_email("espuser"), realm=get_realm("zephyr"))
result = self.client_post("/json/users/me/presence", {'status': 'idle'},
subdomain="zephyr")
self.assert_json_success(result)
self.assertEqual(result.json()['presences'], {})
def test_mirror_presence(self) -> None:
user_profile = self.mit_user('espuser')
email = user_profile.email
self.login(email, realm=user_profile.realm)
def post_presence() -> Dict[str, Any]:
result = self.client_post("/json/users/me/presence", {'status': 'idle'},
subdomain="zephyr")
self.assert_json_success(result)
json = result.json()
return json
json = post_presence()
self.assertEqual(json['zephyr_mirror_active'], False)
self._simulate_mirror_activity_for_user(user_profile)
json = post_presence()
self.assertEqual(json['zephyr_mirror_active'], True)
def _simulate_mirror_activity_for_user(self, user_profile: UserProfile) -> None:
last_visit = timezone_now()
client = make_client('zephyr_mirror')
UserActivity.objects.get_or_create(
user_profile=user_profile,
client=client,
query='get_events_backend',
count=2,
last_visit=last_visit
)
def test_same_realm(self) -> None:
self.login(self.mit_email("espuser"), realm=get_realm("zephyr"))
self.client_post("/json/users/me/presence", {'status': 'idle'},
subdomain="zephyr")
self.logout()
self.login(self.example_email("hamlet"))
result = self.client_post("/json/users/me/presence", {'status': 'idle'})
self.assert_json_success(result)
json = result.json()
self.assertEqual(json['presences'][self.example_email("hamlet")]["website"]['status'], 'idle')
# We only want @zulip.com emails
for email in json['presences'].keys():
self.assertEqual(email_to_domain(email), 'zulip.com')
class SingleUserPresenceTests(ZulipTestCase):
def test_single_user_get(self) -> None:
# First, we setup the test with some data
email = self.example_email("othello")
self.login(self.example_email("othello"))
result = self.client_post("/json/users/me/presence", {'status': 'active'})
result = self.client_post("/json/users/me/presence", {'status': 'active'},
HTTP_USER_AGENT="ZulipDesktop/1.0")
result = self.api_post(email, "/api/v1/users/me/presence", {'status': 'idle'},
HTTP_USER_AGENT="ZulipAndroid/1.0")
self.assert_json_success(result)
# Check some error conditions
result = self.client_get("/json/users/nonexistence@zulip.com/presence")
self.assert_json_error(result, "No such user")
result = self.client_get("/json/users/cordelia@zulip.com/presence")
self.assert_json_error(result, "No presence data for cordelia@zulip.com")
do_deactivate_user(self.example_user('cordelia'))
result = self.client_get("/json/users/cordelia@zulip.com/presence")
self.assert_json_error(result, "No such user")
result = self.client_get("/json/users/new-user-bot@zulip.com/presence")
self.assert_json_error(result, "Presence is not supported for bot users.")
self.login(self.mit_email("sipbtest"), realm=get_realm("zephyr"))
result = self.client_get("/json/users/othello@zulip.com/presence",
subdomain="zephyr")
self.assert_json_error(result, "No such user")
# Then, we check everything works
self.login(self.example_email("hamlet"))
result = self.client_get("/json/users/othello@zulip.com/presence")
result_dict = result.json()
self.assertEqual(
set(result_dict['presence'].keys()),
{"ZulipAndroid", "website", "aggregated"})
self.assertEqual(set(result_dict['presence']['website'].keys()), {"status", "timestamp"})
def test_ping_only(self) -> None:
self.login(self.example_email("othello"))
req = dict(
status='active',
ping_only='true',
)
result = self.client_post("/json/users/me/presence", req)
self.assertEqual(result.json()['msg'], '')
class UserPresenceAggregationTests(ZulipTestCase):
def _send_presence_for_aggregated_tests(self, email: str, status: str,
validate_time: datetime.datetime) -> Dict[str, Dict[str, Any]]:
self.login(email)
timezone_util = 'zerver.views.presence.timezone_now'
with mock.patch(timezone_util, return_value=validate_time - datetime.timedelta(seconds=5)):
self.client_post("/json/users/me/presence", {'status': status})
with mock.patch(timezone_util, return_value=validate_time - datetime.timedelta(seconds=2)):
self.api_post(email, "/api/v1/users/me/presence", {'status': status},
HTTP_USER_AGENT="ZulipAndroid/1.0")
with mock.patch(timezone_util, return_value=validate_time - datetime.timedelta(seconds=7)):
latest_result = self.api_post(email, "/api/v1/users/me/presence", {'status': status},
HTTP_USER_AGENT="ZulipIOS/1.0")
latest_result_dict = latest_result.json()
self.assertDictEqual(
latest_result_dict['presences'][email]['aggregated'],
{
'status': status,
'timestamp': datetime_to_timestamp(validate_time - datetime.timedelta(seconds=2)),
'client': 'ZulipAndroid'
}
)
result = self.client_get("/json/users/%s/presence" % (email,))
return result.json()
def test_aggregated_info(self) -> None:
email = self.example_email("othello")
validate_time = timezone_now()
self._send_presence_for_aggregated_tests(str(self.example_email("othello")), 'active', validate_time)
with mock.patch('zerver.views.presence.timezone_now',
return_value=validate_time - datetime.timedelta(seconds=1)):
result = self.api_post(email, "/api/v1/users/me/presence", {'status': 'active'},
HTTP_USER_AGENT="ZulipTestDev/1.0")
result_dict = result.json()
self.assertDictEqual(
result_dict['presences'][email]['aggregated'],
{
'status': 'active',
'timestamp': datetime_to_timestamp(validate_time - datetime.timedelta(seconds=1)),
'client': 'ZulipTestDev'
}
)
def test_aggregated_presense_active(self) -> None:
validate_time = timezone_now()
result_dict = self._send_presence_for_aggregated_tests(str(self.example_email("othello")), 'active',
validate_time)
self.assertDictEqual(
result_dict['presence']['aggregated'],
{
"status": "active",
"timestamp": datetime_to_timestamp(validate_time - datetime.timedelta(seconds=2))
}
)
def test_aggregated_presense_idle(self) -> None:
validate_time = timezone_now()
result_dict = self._send_presence_for_aggregated_tests(str(self.example_email("othello")), 'idle',
validate_time)
self.assertDictEqual(
result_dict['presence']['aggregated'],
{
"status": "idle",
"timestamp": datetime_to_timestamp(validate_time - datetime.timedelta(seconds=2))
}
)
def test_aggregated_presense_mixed(self) -> None:
email = self.example_email("othello")
self.login(email)
validate_time = timezone_now()
with mock.patch('zerver.views.presence.timezone_now',
return_value=validate_time - datetime.timedelta(seconds=3)):
self.api_post(email, "/api/v1/users/me/presence", {'status': 'active'},
HTTP_USER_AGENT="ZulipTestDev/1.0")
result_dict = self._send_presence_for_aggregated_tests(str(email), 'idle', validate_time)
self.assertDictEqual(
result_dict['presence']['aggregated'],
{
"status": "idle",
"timestamp": datetime_to_timestamp(validate_time - datetime.timedelta(seconds=2))
}
)
def test_aggregated_presense_offline(self) -> None:
email = self.example_email("othello")
self.login(email)
validate_time = timezone_now()
with self.settings(OFFLINE_THRESHOLD_SECS=1):
result_dict = self._send_presence_for_aggregated_tests(str(email), 'idle', validate_time)
self.assertDictEqual(
result_dict['presence']['aggregated'],
{
"status": "offline",
"timestamp": datetime_to_timestamp(validate_time - datetime.timedelta(seconds=2))
}
)
| true | true |
1c2bb5b0e721c62019d5c1c9ee7c7982aa312788 | 10,522 | py | Python | esmvaltool/diag_scripts/aerosols/diagnostics_burden.py | RCHG/ESMValTool | c6458c72777f22b52b2dcde73749a47e407b77f0 | [
"Apache-2.0"
] | null | null | null | esmvaltool/diag_scripts/aerosols/diagnostics_burden.py | RCHG/ESMValTool | c6458c72777f22b52b2dcde73749a47e407b77f0 | [
"Apache-2.0"
] | null | null | null | esmvaltool/diag_scripts/aerosols/diagnostics_burden.py | RCHG/ESMValTool | c6458c72777f22b52b2dcde73749a47e407b77f0 | [
"Apache-2.0"
] | null | null | null | """
Diagnostics to estimate aerosols burden analysis.
Author: Ramiro Checa-Garcia (LSCE-IPSL)
rcheca@lsce.ipsl.fr
Method:
- It estimates global mean values and create time series
with monthly and yearly time resolution.
Variables:
- emidust, emisoa, emiss etc to estimate emission flux
- drydust, drysoa, etc to estimate dry deposition flux
Outputs:
- Single values or time series.
"""
import os
import numpy as np
import matplotlib
# use this everytime you import matplotlib
# modules; some machines dont have graphical interface (X)
matplotlib.use('Agg') # noqa
import iris
import matplotlib.pyplot as plt
from esmvaltool.diag_scripts.shared import run_diagnostic
from esmvaltool.preprocessor._area_pp import area_average
from esmvaltool.diag_scripts.shared import (group_metadata, run_diagnostic,
select_metadata, sorted_metadata)
import logging
logger = logging.getLogger(os.path.basename(__file__))
## Specific modules needed by this diagnostic ----------------------------
import pandas as pd
from tabulate import tabulate
from pprint import pformat
#import xarray as xr
#daxr = xr.DataArray.from_iris(newcube)
def _get_my_files(cfg):
"""Put files in dicts of datasets and return them."""
files_dict = {}
for filename, attributes in cfg['input_data'].items():
base_file = os.path.basename(filename)
dataset = base_file.split('_')[1]
files_dict[dataset] = {}
files_dict[dataset]['file'] = filename
if 'fx_files' in attributes:
for fx_var in attributes['fx_files']:
files_dict[dataset][fx_var] = attributes['fx_files'][fx_var]
return files_dict
def _get_my_infos(cfg):
"""Put files in dicts of datasets and return them."""
info_dict = {}
for filename, attributes in cfg['input_data'].items():
base_file = os.path.basename(filename)
dataset = base_file.split('_')[1]
info_dict[dataset] = {}
info_dict[dataset]['units'] = attributes['units']
info_dict[dataset]['short_name'] = attributes['short_name']
if 'fx_files' in attributes:
for fx_var in attributes['fx_files']:
info_dict[dataset][fx_var] = attributes['fx_files'][fx_var]
return info_dict
def main(cfg):
"""Compute the global specie emissions for each input dataset."""
'''
# Get a description of the preprocessed data that we will use as input.
input_data = cfg['input_data'].values()
grouped_input_data = group_metadata(input_data, 'standard_name', sort='dataset')
logger.info( "Example of how to group and sort input data by standard_name:"
"\n%s", pformat(grouped_input_data))
# Example of how to loop over variables/datasets in alphabetical order
for standard_name in grouped_input_data:
logger.info("Processing variable %s", standard_name)
for attributes in grouped_input_data[standard_name]:
logger.info("Processing dataset %s", attributes['dataset'])
filename = attributes['filename']
logger.info("Loading %s", filename)
name = os.path.splitext(os.path.basename(filename))[0] + '_mean'
logger.info("Name %s", name)
'''
global_emisions(cfg)
return
def global_emisions(cfg):
my_files_dict = _get_my_files(cfg)
my_infos_dict = _get_my_infos(cfg)
input_data = cfg['input_data'].values()
print(my_infos_dict)
grouped_input_data = group_metadata(
input_data, 'standard_name', sort='dataset')
logger.info(
"Example of how to group and sort input data by standard_name:"
"\n%s", pformat(grouped_input_data))
# Example of how to loop over variables/datasets in alphabetical order
for standard_name in grouped_input_data:
logger.info("Processing variable %s", standard_name)
for attributes in grouped_input_data[standard_name]:
logger.info("Processing dataset %s", attributes['dataset'])
filename = attributes['filename']
logger.info("Loading %s", filename)
fname = os.path.splitext(os.path.basename(filename))[0] + '_mean'
fname = fname.replace(attributes['dataset'],'COMPARISON')
logger.info("Name %s", fname)
varname = attributes['short_name']
logger.info("Units %s", attributes['units'])
# Iterates through preprocessed model data to create multi-datasets tables
gemissions_m = {}
for key, value in my_files_dict.items():
cube = iris.load_cube(value['file'])
cube.coord('latitude').guess_bounds()
cube.coord('longitude').guess_bounds()
# Creates a new temporal cube with the global mean area values
cube_area = iris.analysis.cartography.area_weights(cube)
newcube = cube.collapsed(['longitude', 'latitude'], iris.analysis.SUM,
weights=cube_area)
# IMPORTANT ---------------------------------------------------------
# here we could provide a time series and seasons and sampled monthly
tbounds = newcube.coord('time').bounds
wbounds = [y[1]-y[0] for y in tbounds]
# we assume here time units of hours but variable in sec-1 ----------
if my_infos_dict[key]['units']=='kg m-2 s-1':
stime = np.array(wbounds)*24*60*60
fdata = np.array([ a*b/1.e9 for a, b in zip(stime,newcube.data)])
time = newcube.coord('time')
atime = time.units.num2date(time.points)
gemissions_m[key]=fdata
gemissions_m['Date']=atime
else:
exit()
globalemi_mon = pd.DataFrame(gemissions_m)
globalemi_mon = globalemi_mon.set_index('Date')
globalemi_yrs = globalemi_mon.resample("Y").sum()
if cfg.get('table'):
path_table_mon = os.path.join(
cfg['table_dir'],
fname + '_mon.' + cfg['table_output_file_type'],
)
path_table_yrs = os.path.join(
cfg['table_dir'],
fname + '_yrs.' + cfg['table_output_file_type'],
)
path_table_des = os.path.join(
cfg['table_dir'],
fname + '_des.' + cfg['table_output_file_type'],
)
if cfg['output_file_type']!='md':
month_tb = tabulate(globalemi_mon, headers='keys', tablefmt='psql')
years_tb = tabulate(globalemi_yrs, headers='keys', tablefmt='psql')
month_de = tabulate(globalemi_mon.describe(), headers='keys', tablefmt='psql')
years_de = tabulate(globalemi_yrs.describe(), headers='keys', tablefmt='psql')
if cfg['output_file_type']!='tex':
month_tb = tabulate(globalemi_mon, headers='keys', tablefmt='latex')
years_tb = tabulate(globalemi_yrs, headers='keys', tablefmt='latex')
month_de = tabulate(globalemi_mon.describe(), headers='keys', tablefmt='latex')
years_de = tabulate(globalemi_yrs.describe(), headers='keys', tablefmt='latex')
if cfg['table']['monthly']==True:
with open(path_table_mon, 'w') as tablef:
tablef.write(month_tb)
if cfg['table']['yearly']==True:
with open(path_table_yrs, 'w') as tablef:
tablef.write(years_tb)
if cfg['table']['summary']==True:
with open(path_table_des, 'w') as tablef:
tablef.write(month_de)
tablef.write(years_de)
if cfg.get('plot'):
path_plot_mon = os.path.join(
cfg['plot_dir'],
fname + '_mon.' + cfg['output_file_type'],
)
path_plot_yrs = os.path.join(
cfg['plot_dir'],
fname + '_yrs.' + cfg['output_file_type'],
)
if cfg['plot']['monthly']==True:
globalemi_mon.plot(figsize=(12,4), legend=True)
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.90), facecolor=None, edgecolor=None, frameon=False)
plt.title('Comparison of global monthly '+varname)
plt.ylabel(varname + ' [Tg month-1]')
plt.subplots_adjust(right=0.7)
plt.savefig(path_plot_mon)
if cfg['plot']['yearly']==True:
globalemi_yrs.plot(figsize=(12,4), legend=True)
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.90), facecolor=None, edgecolor=None, frameon=False)
plt.title('Comparison of global yearly '+varname)
plt.ylabel(varname +' [Tg yr-1]')
plt.subplots_adjust(right=0.7)
plt.savefig(path_plot_yrs)
#plt.plot(newcube.coord('time'), fdata)
#plt.show()
# Dado un intervalo de tiempo largo es deseable que saque:
# median and mean sobre todos los anos
# median and mean sobre todos los meses
# extremos -> dar year y mes
# pdfs
# time series
# mean seasonal values
# anomalies
#
# here we have to ascertain the number of seconds per month and then use this
# to create a yearly value, or a monthly value.
return
def plot_time_series(cfg):
"""
Example of personal diagnostic function.
Arguments:
run - dictionary of data files
Returns:
string; makes some time-series plots
"""
# local path for e.g. plots: user input
root_dir = '/group_workspaces/jasmin2/cmip6_prep/' # edit as per need
out_path = 'esmvaltool_users/valeriu/' # edit as per need
local_path = os.path.join(root_dir, out_path)
# get the files (simple case, one-variable only)
my_files_dict = _get_my_files(cfg)
# iterate through preprocessed model data
for key, value in my_files_dict.items():
cube = iris.load_cube(value['file'])
area_avg_cube = area_average(cube, 'latitude', 'longitude')
plt.plot(area_avg_cube.data[:, 0], label=key)
plt.xlabel('Time (months)')
plt.ylabel(cube.standard_name)
plt.title('Time series at ground level')
plt.tight_layout()
plt.grid()
plt.legend()
png_name = 'Time_series_' + key + '.png'
plt.savefig(os.path.join(local_path, png_name))
plt.close()
return 'I made some plots!'
if __name__ == '__main__':
with run_diagnostic() as config:
main(config)
| 37.049296 | 116 | 0.614332 |
import os
import numpy as np
import matplotlib
matplotlib.use('Agg')
import iris
import matplotlib.pyplot as plt
from esmvaltool.diag_scripts.shared import run_diagnostic
from esmvaltool.preprocessor._area_pp import area_average
from esmvaltool.diag_scripts.shared import (group_metadata, run_diagnostic,
select_metadata, sorted_metadata)
import logging
logger = logging.getLogger(os.path.basename(__file__))
ormat
def _get_my_files(cfg):
files_dict = {}
for filename, attributes in cfg['input_data'].items():
base_file = os.path.basename(filename)
dataset = base_file.split('_')[1]
files_dict[dataset] = {}
files_dict[dataset]['file'] = filename
if 'fx_files' in attributes:
for fx_var in attributes['fx_files']:
files_dict[dataset][fx_var] = attributes['fx_files'][fx_var]
return files_dict
def _get_my_infos(cfg):
info_dict = {}
for filename, attributes in cfg['input_data'].items():
base_file = os.path.basename(filename)
dataset = base_file.split('_')[1]
info_dict[dataset] = {}
info_dict[dataset]['units'] = attributes['units']
info_dict[dataset]['short_name'] = attributes['short_name']
if 'fx_files' in attributes:
for fx_var in attributes['fx_files']:
info_dict[dataset][fx_var] = attributes['fx_files'][fx_var]
return info_dict
def main(cfg):
global_emisions(cfg)
return
def global_emisions(cfg):
my_files_dict = _get_my_files(cfg)
my_infos_dict = _get_my_infos(cfg)
input_data = cfg['input_data'].values()
print(my_infos_dict)
grouped_input_data = group_metadata(
input_data, 'standard_name', sort='dataset')
logger.info(
"Example of how to group and sort input data by standard_name:"
"\n%s", pformat(grouped_input_data))
for standard_name in grouped_input_data:
logger.info("Processing variable %s", standard_name)
for attributes in grouped_input_data[standard_name]:
logger.info("Processing dataset %s", attributes['dataset'])
filename = attributes['filename']
logger.info("Loading %s", filename)
fname = os.path.splitext(os.path.basename(filename))[0] + '_mean'
fname = fname.replace(attributes['dataset'],'COMPARISON')
logger.info("Name %s", fname)
varname = attributes['short_name']
logger.info("Units %s", attributes['units'])
gemissions_m = {}
for key, value in my_files_dict.items():
cube = iris.load_cube(value['file'])
cube.coord('latitude').guess_bounds()
cube.coord('longitude').guess_bounds()
cube_area = iris.analysis.cartography.area_weights(cube)
newcube = cube.collapsed(['longitude', 'latitude'], iris.analysis.SUM,
weights=cube_area)
tbounds = newcube.coord('time').bounds
wbounds = [y[1]-y[0] for y in tbounds]
if my_infos_dict[key]['units']=='kg m-2 s-1':
stime = np.array(wbounds)*24*60*60
fdata = np.array([ a*b/1.e9 for a, b in zip(stime,newcube.data)])
time = newcube.coord('time')
atime = time.units.num2date(time.points)
gemissions_m[key]=fdata
gemissions_m['Date']=atime
else:
exit()
globalemi_mon = pd.DataFrame(gemissions_m)
globalemi_mon = globalemi_mon.set_index('Date')
globalemi_yrs = globalemi_mon.resample("Y").sum()
if cfg.get('table'):
path_table_mon = os.path.join(
cfg['table_dir'],
fname + '_mon.' + cfg['table_output_file_type'],
)
path_table_yrs = os.path.join(
cfg['table_dir'],
fname + '_yrs.' + cfg['table_output_file_type'],
)
path_table_des = os.path.join(
cfg['table_dir'],
fname + '_des.' + cfg['table_output_file_type'],
)
if cfg['output_file_type']!='md':
month_tb = tabulate(globalemi_mon, headers='keys', tablefmt='psql')
years_tb = tabulate(globalemi_yrs, headers='keys', tablefmt='psql')
month_de = tabulate(globalemi_mon.describe(), headers='keys', tablefmt='psql')
years_de = tabulate(globalemi_yrs.describe(), headers='keys', tablefmt='psql')
if cfg['output_file_type']!='tex':
month_tb = tabulate(globalemi_mon, headers='keys', tablefmt='latex')
years_tb = tabulate(globalemi_yrs, headers='keys', tablefmt='latex')
month_de = tabulate(globalemi_mon.describe(), headers='keys', tablefmt='latex')
years_de = tabulate(globalemi_yrs.describe(), headers='keys', tablefmt='latex')
if cfg['table']['monthly']==True:
with open(path_table_mon, 'w') as tablef:
tablef.write(month_tb)
if cfg['table']['yearly']==True:
with open(path_table_yrs, 'w') as tablef:
tablef.write(years_tb)
if cfg['table']['summary']==True:
with open(path_table_des, 'w') as tablef:
tablef.write(month_de)
tablef.write(years_de)
if cfg.get('plot'):
path_plot_mon = os.path.join(
cfg['plot_dir'],
fname + '_mon.' + cfg['output_file_type'],
)
path_plot_yrs = os.path.join(
cfg['plot_dir'],
fname + '_yrs.' + cfg['output_file_type'],
)
if cfg['plot']['monthly']==True:
globalemi_mon.plot(figsize=(12,4), legend=True)
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.90), facecolor=None, edgecolor=None, frameon=False)
plt.title('Comparison of global monthly '+varname)
plt.ylabel(varname + ' [Tg month-1]')
plt.subplots_adjust(right=0.7)
plt.savefig(path_plot_mon)
if cfg['plot']['yearly']==True:
globalemi_yrs.plot(figsize=(12,4), legend=True)
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.90), facecolor=None, edgecolor=None, frameon=False)
plt.title('Comparison of global yearly '+varname)
plt.ylabel(varname +' [Tg yr-1]')
plt.subplots_adjust(right=0.7)
plt.savefig(path_plot_yrs)
return
def plot_time_series(cfg):
root_dir = '/group_workspaces/jasmin2/cmip6_prep/'
out_path = 'esmvaltool_users/valeriu/'
local_path = os.path.join(root_dir, out_path)
my_files_dict = _get_my_files(cfg)
for key, value in my_files_dict.items():
cube = iris.load_cube(value['file'])
area_avg_cube = area_average(cube, 'latitude', 'longitude')
plt.plot(area_avg_cube.data[:, 0], label=key)
plt.xlabel('Time (months)')
plt.ylabel(cube.standard_name)
plt.title('Time series at ground level')
plt.tight_layout()
plt.grid()
plt.legend()
png_name = 'Time_series_' + key + '.png'
plt.savefig(os.path.join(local_path, png_name))
plt.close()
return 'I made some plots!'
if __name__ == '__main__':
with run_diagnostic() as config:
main(config)
| true | true |
1c2bb7e242a344b192039843a26470b232e4eb61 | 12,935 | py | Python | Material/CityTowerProblem/CODE/TowerPlanning.py | pragneshrana/NumericalOptimization | 28ea55840ed95262bc39c0896acee9e54cc375c2 | [
"MIT"
] | null | null | null | Material/CityTowerProblem/CODE/TowerPlanning.py | pragneshrana/NumericalOptimization | 28ea55840ed95262bc39c0896acee9e54cc375c2 | [
"MIT"
] | null | null | null | Material/CityTowerProblem/CODE/TowerPlanning.py | pragneshrana/NumericalOptimization | 28ea55840ed95262bc39c0896acee9e54cc375c2 | [
"MIT"
] | null | null | null | #calling libraries
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
from scipy.spatial import Voronoi, voronoi_plot_2d
import random
import pandas as pd
import sys
import os
from datetime import date
import time
class TowerPlanning():
def __init__(self,dim,main_cities,total_population,min_c,max_c,budget,RequiredRegions,NeighborsToCover,CostPerEach,PopulationData=None):
self.dim = dim
self.main_cities = main_cities
self.total_population = total_population
self.min_c = min_c
self.max_c = max_c
self.budget = budget
self.RequiredRegions = RequiredRegions
self.PopulationData = PopulationData
self.Usedbudget = None
self.CoveredRegion = None
self.NeighborsToCover = NeighborsToCover
self.CostPerEach = CostPerEach
#creating Directory
try:
os.mkdir('./result/')
except FileExistsError:
pass
try:
os.mkdir('./result/'+str(self.RequiredRegions)+'/')
except FileExistsError:
pass
try:
os.mknod('./result/'+str(self.RequiredRegions)+'/ResultSummary.txt')
except FileExistsError:
pass
self.f = open('./result/'+str(self.RequiredRegions)+'/ResultSummary.txt',"w")
self.f.write('\n\n\n'+str(date.today()))
#Creating Folder
try:
os.mknod('Result.csv')
except FileExistsError:
pass
def GeneratePopulation(self,):
'''
This method will generate the random population for simulation
'''
# Define area of
def random_population():
random.seed(30)
return [random.randint(self.min_c, self.max_c) for _ in range(self.dim)]
#Generating clusters
from sklearn.datasets import make_blobs
'''
70% of the population is assumed to generate cluster of population
30% of population is scattered for business or store or other purpose
'''
#70%
main_population, y = make_blobs(n_samples=int(self.total_population*0.7),cluster_std= (self.max_c - self.min_c), centers=self.main_cities, center_box=(self.min_c, self.max_c) ,n_features=self.dim,random_state=41)
#30%
other_population = np.zeros((int(0.3*total_population),self.dim))
for i in range(len(other_population)):
other_population[i] = random_population()
#Visualization of population generation
plt.scatter(main_population[:,0], main_population[:,1], marker = '.',color="red", s=10, label="City People")
plt.scatter(other_population[:,0],other_population[:,1], marker = '.' , color="green", s=10, label="Scattered/Temporary People")
# plt.show()
self.PopulationData = np.concatenate((main_population, other_population))
def GenerateClusters(self,):
'''
This method will generate clusters
'''
from sklearn.cluster import KMeans
from sklearn.cluster import DBSCAN
import sklearn
# silhouette_score_values= []
# NumberOfClusters=range(2,30)
# for i in NumberOfClusters:
# classifier=KMeans(i,init='k-means++', n_init=10, max_iter=300, tol=0.0001, verbose=0, random_state=None, copy_x=True)
# classifier.fit(population_data)
# labels= classifier.predict(population_data)
# print("Number Of Clusters:")
# print(i)
# print("Silhouette score value")
# print(sklearn.metrics.silhouette_score(population_data,labels ,metric='euclidean', sample_size=None, random_state=None))
# silhouette_score_values.append(sklearn.metrics.silhouette_score(population_data,labels ,metric='euclidean', sample_size=None, random_state=None))
# plt.plot(NumberOfClusters, silhouette_score_values)
# plt.title("Silhouette score values vs Numbers of Clusters ")
# plt.show()
# self.RequiredRegions=NumberOfClusters[silhouette_score_values.index(max(silhouette_score_values))]
# print("Optimal number of components is:")
# print(self.RequiredRegions)
##Kmeans
kmeans = KMeans(n_clusters=self.RequiredRegions, init='k-means++', max_iter=100, n_init=1, verbose=0, random_state=3425).fit(self.PopulationData)
cluster_label = kmeans.labels_
region_centers = kmeans.cluster_centers_
return cluster_label, region_centers
def ResultPlot(self,FinalNodes,region_centers):
plt.clf()
self.VoronoiDiagram(region_centers)
plt.scatter(self.PopulationData[:,0],self.PopulationData[:,1], marker = '.' , color="green", s=10, label="Scattered/Temporary People")
for i in range(len(FinalNodes)):
plt.scatter(FinalNodes[i][0],FinalNodes[i][1],marker = 'x' , color="red",label="TowerLocation"+str(i))
plt.text(FinalNodes[i][0]+0.25,FinalNodes[i][1]+0.25,str(i), fontsize=15)
# plt.ylim(self.min_c, self.max_c)
# plt.xlim(self.min_c,self.max_c)
plt.savefig('./result/'+str(self.RequiredRegions)+'/FinalResult.jpg')
plt.show()
def CellTowerProblem(self,AllocatedFacilityData,RegionWisePopulation):
'''
This method will solve cell tower problem using gurobi library
'''
import gurobipy as gp
from gurobipy import GRB
# tested with Gurobi v9.0.0 and Python 3.7.0
Populationkey = [*range(0,len(self.PopulationData))]
PopulationDict = dict(zip(Populationkey,RegionWisePopulation))
regions, population = gp.multidict(PopulationDict)
# # Parameters
# regions, population = gp.multidict({
# 0: 523, 1: 690, 2: 420,
# 3: 1010, 4: 1200, 5: 850,
# 6: 400, 7: 1008, 8: 950
# })
#Calculating Cost of each tower
'''
Summation of total population covered in all region
'''
cost = []
for i in range(len(AllocatedFacilityData)):
TempCost = 0
sum = 0
RegionsOccupiedByVertex = AllocatedFacilityData.iloc[i,1:]
for j in range(self.NeighborsToCover):
sum += RegionWisePopulation[RegionsOccupiedByVertex[j]]
cost.append(sum + self.CostPerEach)
RegionKey = [*range(0,len(AllocatedFacilityData))]
RegionValue = []
coverageData = []
for i in range(len(AllocatedFacilityData)):
coverageData = [list(AllocatedFacilityData.iloc[i,1:])]
coverageData.append(cost[i])
RegionValue.append(coverageData)
RegionDict = dict(zip(RegionKey,RegionValue))
# print('RegionDict: ', RegionDict)
# sites, coverage, cost = gp.multidict({
# 0: [[0,1,5], 42],
# 1: [[0,7,8], 61],
# 2: [[2,3,4,6], 52],
# 3: [[2,5,6], 55],
# 4: [[0,2,6,7,8], 48],
# 5: [[3,4,8], 92]
# })
sites, coverage, cost = gp.multidict(RegionDict)
# MIP model formulation
m = gp.Model("cell_tower")
# m = gp.Model()
build = m.addVars(len(sites), vtype=GRB.BINARY, name="Build")
is_covered = m.addVars(len(regions), vtype=GRB.BINARY, name="Is_covered")
m.addConstrs((gp.quicksum(build[t] for t in sites if r in coverage[t]) >= is_covered[r]
for r in regions), name="Build2cover")
m.addConstr(build.prod(cost) <= self.budget, name="budget")
m.setObjective(is_covered.prod(population), GRB.MAXIMIZE)
m.optimize()
# display optimal values of decision variables
LocationFound = []
for tower in build.keys():
if (abs(build[tower].x) > 1e-6):
print(f"\n Build a cell tower at location Tower {tower}.")
self.f.write("\n Build a cell tower at location Tower "+str(tower))
LocationFound.append(tower)
# Percentage of the population covered by the cell towers built is computed as follows.
total_population = 0
for region in range(len(regions)):
total_population += population[region]
self.CoveredRegion = round(100*m.objVal/total_population, 2)
print(f"\n The population coverage associated to the cell towers build plan is: {self.CoveredRegion} %")
self.f.write("\n The population coverage associated to the cell towers build plan is: "+str(self.CoveredRegion))
# Percentage of budget consumed to build cell towers
total_cost = 0
for tower in range(len(sites)):
if (abs(build[tower].x) > 0.5):
total_cost += cost[tower]*int(build[tower].x)
try:
self.Usedbudget = round(100*total_cost/budget, 2)
except:
return 0,0
print(f"\n The percentage of budget consumed associated to the cell towers build plan is: {self.Usedbudget} %")
self.f.write("\n The percentage of budget consumed associated to the cell towers build plan is: "+str(self.Usedbudget))
return LocationFound
def VoronoiDiagram(self,centers):
'''
This method will generate voronoi diagram
'''
from scipy.spatial import Voronoi, voronoi_plot_2d
vor = Voronoi(centers)
voronoi_plot_2d(vor)
vertices = vor.vertices #coord of voronoi vertices
# ind_reg = vor.regions #indices of voronoi vertices
# print('ind_reg: ', ind_reg)
# ind_redig_verti = vor.ridge_vertices #indices of voronoi vertices forming ridge
# print('ind_redig_verti: ', ind_redig_verti)
# ind_ver_poi = vor.ridge_points #indices of each voronoi between which each voronoi lies
# print('ind_ver_poi: ', ind_ver_poi)
# return vertices
def DistBtnCentroidNNeighbor(self,region_centers):
'''
This method will find nearest three centroid from the vertex
return : methos will return
'''
headers = ['RegionCenter']
for i in range(self.NeighborsToCover):
headers.append('NeighborCenter'+str(i))
dataframe = pd.DataFrame([],dtype=int)
for i in range(len(region_centers)): #find nearest centroid from all
data_array = np.array([i])
measured_dist = []
for j in range(len(region_centers)):
measured_dist.append(self.CalculateEuclidianDist(region_centers[i],region_centers[j]))
data_array = np.concatenate((data_array,np.argsort(measured_dist)[1:self.NeighborsToCover+1]))
dataframe = dataframe.append(pd.Series(list(data_array)),ignore_index=True)
dataframe = dataframe.astype('int64', copy=False)
dataframe.columns = headers
return dataframe
def CalculateEuclidianDist(self,array1,array2):
'''
This method will calculate euclidian distance
'''
dist = np.linalg.norm((array1-array2))
return dist
def FindFinalNode(self,region_centers,IndexOfNodesToBuild,AllocatedFacilityData):
FinalNodes = []
for i in range(len(IndexOfNodesToBuild)):
temp_nodes = []
for j in range(self.NeighborsToCover+1):
temp_nodes.append(region_centers[AllocatedFacilityData.iloc[IndexOfNodesToBuild[i],:][j]])
FinalNodes.append(sum(temp_nodes) / len(temp_nodes))
return FinalNodes
def Simulate(self,):
population_label , region_centers = self.GenerateClusters()
#voronoi diagram
self.VoronoiDiagram(region_centers)
#finding nearest centroid from each vertex
AllocatedFacilityData = self.DistBtnCentroidNNeighbor(region_centers)
#Writing center on graph plot
for i in range(len(region_centers)):
plt.text(region_centers[i][0],region_centers[i][1],str(i), fontsize=15)
# #writing vertex on plot
# for i in range(len(vertices)):
# plt.text(vertices[i][0],vertices[i][1],str(i), fontsize=15)
#Visualization population Regions
regional_data = [] #clusterwise data
RegionWisePopulation = [] #clusterwise population count
unique_label = np.unique(population_label)
for i in range(len(unique_label)):
temp_data = []
for j in range(len(self.PopulationData)):
if(population_label[j] == unique_label[i]):
temp_data.append(list(self.PopulationData[j,:]))
temp_data = np.array(temp_data)
RegionWisePopulation.append(len(temp_data))
regional_data.append(temp_data)
color = "#%06x" % random.randint(0, 0xFFFFFF)
plt.scatter(temp_data[:,0],temp_data[:,1],c=color,marker='.',label='cluster'+str(i))
plt.savefig('./result/'+str(self.RequiredRegions)+'/Regions.jpg')
plt.show()
#optimizing
start = time.time()
IndexOfNodesToBuild = self.CellTowerProblem(AllocatedFacilityData,RegionWisePopulation)
end = time.time()
ElapsedTime = end - start
FinalNodes = self.FindFinalNode(region_centers,IndexOfNodesToBuild,AllocatedFacilityData)
self.ResultPlot(FinalNodes,region_centers)
self.f.close()
return self.Usedbudget, self.CoveredRegion ,ElapsedTime
if __name__ == "__main__":
#For Population
dim = 2 #dimension
main_cities = 5 #to generate data points
headers = ['Regions','Coverage','Budget','Execution Time']
if(sys.argv[1].isnumeric()):
RequiredRegions = int(sys.argv[1]) #to generate clusters
print('RequiredRegions: ', RequiredRegions)
else:
print('Pass Integer')
exit()
#############################
####### Input ###########
#############################
## Parameters
total_population = 130000
NeighborsToCover = 3
CostPerEach = 3000000
budget = 1000000 * RequiredRegions #lakhs#Budget 12013000 +
#area
min_c = 100
max_c = 200
#############################
#############################
TP = TowerPlanning(dim,main_cities,total_population,min_c,max_c,budget,int(RequiredRegions),NeighborsToCover,CostPerEach)
TP.GeneratePopulation()
try:
result = pd.read_csv('Result.csv')
except pd.errors.EmptyDataError :
result = pd.DataFrame([],columns=headers)
# coverage , budget = Simulate(population,self.NeighborsToCover,budget,8)
coverage , budget , ElapsedTime = TP.Simulate()
append_data = [int(RequiredRegions),coverage,budget,ElapsedTime]
resu = pd.DataFrame([append_data],columns=headers)
result = pd.concat([result,resu])
result.to_csv('Result.csv',index=False)
plt.close('all')
| 33.861257 | 214 | 0.716351 |
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
from scipy.spatial import Voronoi, voronoi_plot_2d
import random
import pandas as pd
import sys
import os
from datetime import date
import time
class TowerPlanning():
def __init__(self,dim,main_cities,total_population,min_c,max_c,budget,RequiredRegions,NeighborsToCover,CostPerEach,PopulationData=None):
self.dim = dim
self.main_cities = main_cities
self.total_population = total_population
self.min_c = min_c
self.max_c = max_c
self.budget = budget
self.RequiredRegions = RequiredRegions
self.PopulationData = PopulationData
self.Usedbudget = None
self.CoveredRegion = None
self.NeighborsToCover = NeighborsToCover
self.CostPerEach = CostPerEach
try:
os.mkdir('./result/')
except FileExistsError:
pass
try:
os.mkdir('./result/'+str(self.RequiredRegions)+'/')
except FileExistsError:
pass
try:
os.mknod('./result/'+str(self.RequiredRegions)+'/ResultSummary.txt')
except FileExistsError:
pass
self.f = open('./result/'+str(self.RequiredRegions)+'/ResultSummary.txt',"w")
self.f.write('\n\n\n'+str(date.today()))
try:
os.mknod('Result.csv')
except FileExistsError:
pass
def GeneratePopulation(self,):
def random_population():
random.seed(30)
return [random.randint(self.min_c, self.max_c) for _ in range(self.dim)]
from sklearn.datasets import make_blobs
main_population, y = make_blobs(n_samples=int(self.total_population*0.7),cluster_std= (self.max_c - self.min_c), centers=self.main_cities, center_box=(self.min_c, self.max_c) ,n_features=self.dim,random_state=41)
other_population = np.zeros((int(0.3*total_population),self.dim))
for i in range(len(other_population)):
other_population[i] = random_population()
plt.scatter(main_population[:,0], main_population[:,1], marker = '.',color="red", s=10, label="City People")
plt.scatter(other_population[:,0],other_population[:,1], marker = '.' , color="green", s=10, label="Scattered/Temporary People")
self.PopulationData = np.concatenate((main_population, other_population))
def GenerateClusters(self,):
from sklearn.cluster import KMeans
from sklearn.cluster import DBSCAN
import sklearn
ns = KMeans(n_clusters=self.RequiredRegions, init='k-means++', max_iter=100, n_init=1, verbose=0, random_state=3425).fit(self.PopulationData)
cluster_label = kmeans.labels_
region_centers = kmeans.cluster_centers_
return cluster_label, region_centers
def ResultPlot(self,FinalNodes,region_centers):
plt.clf()
self.VoronoiDiagram(region_centers)
plt.scatter(self.PopulationData[:,0],self.PopulationData[:,1], marker = '.' , color="green", s=10, label="Scattered/Temporary People")
for i in range(len(FinalNodes)):
plt.scatter(FinalNodes[i][0],FinalNodes[i][1],marker = 'x' , color="red",label="TowerLocation"+str(i))
plt.text(FinalNodes[i][0]+0.25,FinalNodes[i][1]+0.25,str(i), fontsize=15)
plt.savefig('./result/'+str(self.RequiredRegions)+'/FinalResult.jpg')
plt.show()
def CellTowerProblem(self,AllocatedFacilityData,RegionWisePopulation):
import gurobipy as gp
from gurobipy import GRB
Populationkey = [*range(0,len(self.PopulationData))]
PopulationDict = dict(zip(Populationkey,RegionWisePopulation))
regions, population = gp.multidict(PopulationDict)
cost = []
for i in range(len(AllocatedFacilityData)):
TempCost = 0
sum = 0
RegionsOccupiedByVertex = AllocatedFacilityData.iloc[i,1:]
for j in range(self.NeighborsToCover):
sum += RegionWisePopulation[RegionsOccupiedByVertex[j]]
cost.append(sum + self.CostPerEach)
RegionKey = [*range(0,len(AllocatedFacilityData))]
RegionValue = []
coverageData = []
for i in range(len(AllocatedFacilityData)):
coverageData = [list(AllocatedFacilityData.iloc[i,1:])]
coverageData.append(cost[i])
RegionValue.append(coverageData)
RegionDict = dict(zip(RegionKey,RegionValue))
sites, coverage, cost = gp.multidict(RegionDict)
m = gp.Model("cell_tower")
build = m.addVars(len(sites), vtype=GRB.BINARY, name="Build")
is_covered = m.addVars(len(regions), vtype=GRB.BINARY, name="Is_covered")
m.addConstrs((gp.quicksum(build[t] for t in sites if r in coverage[t]) >= is_covered[r]
for r in regions), name="Build2cover")
m.addConstr(build.prod(cost) <= self.budget, name="budget")
m.setObjective(is_covered.prod(population), GRB.MAXIMIZE)
m.optimize()
LocationFound = []
for tower in build.keys():
if (abs(build[tower].x) > 1e-6):
print(f"\n Build a cell tower at location Tower {tower}.")
self.f.write("\n Build a cell tower at location Tower "+str(tower))
LocationFound.append(tower)
total_population = 0
for region in range(len(regions)):
total_population += population[region]
self.CoveredRegion = round(100*m.objVal/total_population, 2)
print(f"\n The population coverage associated to the cell towers build plan is: {self.CoveredRegion} %")
self.f.write("\n The population coverage associated to the cell towers build plan is: "+str(self.CoveredRegion))
total_cost = 0
for tower in range(len(sites)):
if (abs(build[tower].x) > 0.5):
total_cost += cost[tower]*int(build[tower].x)
try:
self.Usedbudget = round(100*total_cost/budget, 2)
except:
return 0,0
print(f"\n The percentage of budget consumed associated to the cell towers build plan is: {self.Usedbudget} %")
self.f.write("\n The percentage of budget consumed associated to the cell towers build plan is: "+str(self.Usedbudget))
return LocationFound
def VoronoiDiagram(self,centers):
from scipy.spatial import Voronoi, voronoi_plot_2d
vor = Voronoi(centers)
voronoi_plot_2d(vor)
vertices = vor.vertices
ghborsToCover):
headers.append('NeighborCenter'+str(i))
dataframe = pd.DataFrame([],dtype=int)
for i in range(len(region_centers)):
data_array = np.array([i])
measured_dist = []
for j in range(len(region_centers)):
measured_dist.append(self.CalculateEuclidianDist(region_centers[i],region_centers[j]))
data_array = np.concatenate((data_array,np.argsort(measured_dist)[1:self.NeighborsToCover+1]))
dataframe = dataframe.append(pd.Series(list(data_array)),ignore_index=True)
dataframe = dataframe.astype('int64', copy=False)
dataframe.columns = headers
return dataframe
def CalculateEuclidianDist(self,array1,array2):
dist = np.linalg.norm((array1-array2))
return dist
def FindFinalNode(self,region_centers,IndexOfNodesToBuild,AllocatedFacilityData):
FinalNodes = []
for i in range(len(IndexOfNodesToBuild)):
temp_nodes = []
for j in range(self.NeighborsToCover+1):
temp_nodes.append(region_centers[AllocatedFacilityData.iloc[IndexOfNodesToBuild[i],:][j]])
FinalNodes.append(sum(temp_nodes) / len(temp_nodes))
return FinalNodes
def Simulate(self,):
population_label , region_centers = self.GenerateClusters()
self.VoronoiDiagram(region_centers)
AllocatedFacilityData = self.DistBtnCentroidNNeighbor(region_centers)
for i in range(len(region_centers)):
plt.text(region_centers[i][0],region_centers[i][1],str(i), fontsize=15)
ata = []
RegionWisePopulation = []
unique_label = np.unique(population_label)
for i in range(len(unique_label)):
temp_data = []
for j in range(len(self.PopulationData)):
if(population_label[j] == unique_label[i]):
temp_data.append(list(self.PopulationData[j,:]))
temp_data = np.array(temp_data)
RegionWisePopulation.append(len(temp_data))
regional_data.append(temp_data)
color = "#%06x" % random.randint(0, 0xFFFFFF)
plt.scatter(temp_data[:,0],temp_data[:,1],c=color,marker='.',label='cluster'+str(i))
plt.savefig('./result/'+str(self.RequiredRegions)+'/Regions.jpg')
plt.show()
start = time.time()
IndexOfNodesToBuild = self.CellTowerProblem(AllocatedFacilityData,RegionWisePopulation)
end = time.time()
ElapsedTime = end - start
FinalNodes = self.FindFinalNode(region_centers,IndexOfNodesToBuild,AllocatedFacilityData)
self.ResultPlot(FinalNodes,region_centers)
self.f.close()
return self.Usedbudget, self.CoveredRegion ,ElapsedTime
if __name__ == "__main__":
dim = 2
main_cities = 5
headers = ['Regions','Coverage','Budget','Execution Time']
if(sys.argv[1].isnumeric()):
RequiredRegions = int(sys.argv[1])
print('RequiredRegions: ', RequiredRegions)
else:
print('Pass Integer')
exit()
| true | true |
1c2bb89713d56d2561fb50de42b707d4de73ea39 | 12,543 | py | Python | cea/bigmacc/wesbrook_DH_single.py | justinfmccarty/CityEnergyAnalyst_bigmacc | a7f2d6085e83730bdc4bcb2321e1613070372027 | [
"MIT"
] | null | null | null | cea/bigmacc/wesbrook_DH_single.py | justinfmccarty/CityEnergyAnalyst_bigmacc | a7f2d6085e83730bdc4bcb2321e1613070372027 | [
"MIT"
] | null | null | null | cea/bigmacc/wesbrook_DH_single.py | justinfmccarty/CityEnergyAnalyst_bigmacc | a7f2d6085e83730bdc4bcb2321e1613070372027 | [
"MIT"
] | null | null | null | """
Wesbrook has a DH system fed first by heat pumps using waste and alst by NG peaking boilers. This script takes the
demand calculated by the CEA and reinterprets it for this system, outputting the results directly into the CEA
demand files.
"""
import pandas as pd
import time
import logging
logging.getLogger('numba').setLevel(logging.WARNING)
from itertools import repeat
import cea.utilities.parallel
import cea.config
import cea.utilities
import cea.inputlocator
import cea.demand.demand_main
import cea.resources.radiation_daysim.radiation_main
import cea.bigmacc.bigmacc_rules
import cea.datamanagement.archetypes_mapper
import cea.datamanagement.data_initializer
import cea.analysis.costs.system_costs
import cea.analysis.lca.main
import cea.utilities.dbf
__author__ = "Justin McCarty"
__copyright__ = ""
__credits__ = ["Justin McCarty"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = ""
__email__ = ""
__status__ = ""
def demand_source(locator, bldg, resource):
# Qhs_sys_kWh, Qww_sys_kWh
hourly_results = locator.get_demand_results_file(bldg, 'csv')
df_demand = pd.read_csv(hourly_results)
return df_demand[resource].rename(bldg)
def breakup_use(df, config):
df = df.loc["total"]
df = df.transpose()
df.index = pd.date_range(start=f'1/1/{config.emissions.year_to_calculate}', periods=8760, freq='H')
return df
def district_buildings(locator):
supply_hs_df = pd.read_excel(locator.get_database_supply_assemblies(), sheet_name='HEATING')
supply_dhw_df = pd.read_excel(locator.get_database_supply_assemblies(), sheet_name='HOT_WATER')
hs_codes = supply_hs_df[supply_hs_df['feedstock'] == 'DISTRICT']['code'].to_list()
dhw_codes = supply_dhw_df[supply_dhw_df['feedstock'] == 'DISTRICT']['code'].to_list()
supply_df = cea.utilities.dbf.dbf_to_dataframe(locator.get_building_supply(), index='Name')
def get_build_list(codes, supply_type):
if supply_type in codes:
return 'Yes'
else:
return 'No'
supply_df['hs_keep'] = supply_df.apply(lambda x: get_build_list(hs_codes, x['type_hs']), axis=1)
on_DH_hs = supply_df[supply_df['hs_keep'] == 'Yes']['Name'].to_list()
supply_df['dhw_keep'] = supply_df.apply(lambda x: get_build_list(dhw_codes, x['type_dhw']), axis=1)
on_DH_dhw = supply_df[supply_df['dhw_keep'] == 'Yes']['Name'].to_list()
return on_DH_hs, on_DH_dhw
def ng(total, hplim):
if total > hplim:
return total - hplim
else:
return 0
def hp(total, ng_demand):
if ng_demand > 0:
return total - ng_demand
else:
return total
def hp1(hp_demand, trlim):
if hp_demand >= trlim:
return trlim
else:
return hp_demand
def hp2(hp_demand, hp1_demand, trlim):
if hp1_demand < trlim:
return 0
else:
return hp_demand - trlim
def calc_district_demand(df):
months = list(range(1, 13, 1))
triumf_max = [5, 3.5, 5, 9, 9, 9.5, 11, 10.5, 9.5, 9, 8, 6.5]
hp_max = [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
district = ((557900 + 75900) / 1078800)
triumf_district = [round(i * district * 1000, 2) for i in triumf_max]
hp_district = [round(i * district * 1000, 2) for i in hp_max]
triumf_limit = dict(zip(months, triumf_district))
hp_limit = dict(zip(months, hp_district))
df['tr_limit'] = df.index.month.map(triumf_limit)
df['hp_limit'] = df.index.month.map(hp_limit)
df['ng_demand'] = df.apply(lambda x: ng(x['total'], x['hp_limit']), axis=1)
df['hp_demand'] = df.apply(lambda x: hp(x['total'], x['ng_demand']), axis=1)
df['hp1_demand'] = df.apply(lambda x: hp1(x['hp_demand'], x['tr_limit']), axis=1)
df['hp2_demand'] = df.apply(lambda x: hp2(x['hp_demand'], x['hp1_demand'], x['tr_limit']), axis=1)
df['ng_source_demand'] = df['ng_demand'] / 0.95
df['hp1_source_demand'] = df['hp1_demand'] / 3.4
df['hp2_source_demand'] = df['hp2_demand'] / 2.7
df['hp_source_demand'] = df['hp1_source_demand'] + df['hp2_source_demand']
return df[['ng_source_demand', 'hp_source_demand']]
def recalc_DH(config):
# TODO By splitting up DHW and HS the overall demand on the system is minimized
# TODO rewrite so the district heat and district hot water can run independentely
locator = cea.inputlocator.InputLocator(config.scenario)
on_DH_hs, on_DH_dhw = district_buildings(locator)
while (len(on_DH_hs) == 0 or len(on_DH_dhw) == 0):
print('wrong')
break
heat_df = pd.DataFrame()
print(' - - - Gathering space heating...')
for bldg in on_DH_hs:
heat_df = heat_df.append(demand_source(locator, bldg, 'Qhs_sys_kWh'))
heat_df['Name'] = heat_df.index
dhw_df = pd.DataFrame()
print(' - - - Gathering DHW...')
for bldg in on_DH_dhw:
dhw_df = dhw_df.append(demand_source(locator, bldg, 'Qww_sys_kWh'))
dhw_df['Name'] = dhw_df.index
demand_df = pd.concat([heat_df, dhw_df], ignore_index=True).groupby(['Name'], as_index=False).sum()
demand_df = demand_df.set_index(demand_df['Name'], drop=True)
del demand_df['Name']
demand_df.loc["total"] = demand_df.sum()
heat_df.loc["total"] = heat_df.sum()
del heat_df['Name']
dhw_df.loc["total"] = dhw_df.sum()
del dhw_df['Name']
def calc_share(demand, total):
return demand / total
print(' - - - Calculating share of district heat load...')
heat_df_share = heat_df.apply(lambda x: calc_share(x, heat_df.loc['total']), axis=1)
dhw_df_share = dhw_df.apply(lambda x: calc_share(x, dhw_df.loc['total']), axis=1)
demand_DH_heat = pd.DataFrame(breakup_use(heat_df, config))
demand_DH_dhw = pd.DataFrame(breakup_use(dhw_df, config))
demand_DH_heat = calc_district_demand(demand_DH_heat)
demand_DH_dhw = calc_district_demand(demand_DH_dhw)
hp_dhw = demand_DH_dhw['hp_source_demand'].reset_index(drop=True).transpose() * dhw_df_share
hp_heat = demand_DH_heat['hp_source_demand'].reset_index(drop=True).transpose() * heat_df_share
ng_dhw = demand_DH_dhw['ng_source_demand'].reset_index(drop=True).transpose() * dhw_df_share
ng_heat = demand_DH_heat['ng_source_demand'].reset_index(drop=True).transpose() * heat_df_share
all_bldgs = on_DH_hs + list(set(on_DH_dhw) - set(on_DH_hs))
if on_DH_hs == on_DH_dhw:
print(' - - - Changing results for all bldgs...')
for bldg in all_bldgs:
# open bldg demand file and replace _ww_kWh with following
hourly_results = locator.get_demand_results_file(bldg, 'csv')
df_demand = pd.read_csv(hourly_results)
df_demand['GRID_hs_kWh'] = hp_heat.loc[bldg]
df_demand['E_hs_kWh'] = hp_heat.loc[bldg]
df_demand['NG_hs_kWh'] = ng_heat.loc[bldg]
df_demand['DH_hs_kWh'] = 0
df_demand['GRID_ww_kWh'] = hp_dhw.loc[bldg]
df_demand['E_ww_kWh'] = hp_heat.loc[bldg]
df_demand['NG_ww_kWh'] = ng_dhw.loc[bldg]
df_demand['DH_ww_kWh'] = 0
df_demand['GRID_kWh'] = df_demand[['GRID_a_kWh', 'GRID_l_kWh', 'GRID_v_kWh', 'GRID_ve_kWh','GRID_data_kWh',
'GRID_pro_kWh', 'GRID_aux_kWh', 'GRID_ww_kWh','GRID_hs_kWh',
'GRID_cs_kWh', 'GRID_cdata_kWh', 'GRID_cre_kWh']].sum(axis=1)
df_demand['E_sys_kWh'] = df_demand[['Eal_kWh', 'Ea_kWh', 'El_kWh', 'Ev_kWh', 'Eve_kWh', 'Edata_kWh',
'Epro_kWh', 'Eaux_kWh', 'E_ww_kWh', 'E_hs_kWh', 'E_cs_kWh',
'E_cre_kWh', 'E_cdata_kWh']].sum(axis=1)
df_demand.to_csv(hourly_results)
else:
for bldg in on_DH_hs:
# open bldg demand file and replace _ww_kWh with following
print(' - - - Resetting results for all district heat buildings...')
hourly_results = locator.get_demand_results_file(bldg, 'csv')
df_demand = pd.read_csv(hourly_results)
df_demand['GRID_hs_kWh'] = hp_heat.loc[bldg]
df_demand['E_hs_kWh'] = hp_heat.loc[bldg]
df_demand['NG_hs_kWh'] = ng_heat.loc[bldg]
df_demand['DH_hs_kWh'] = 0
df_demand.to_csv(hourly_results)
for bldg in on_DH_dhw:
# open bldg demand file and replace _ww_kWh with following
print(' - - - Resetting results for district hot water bldgs...')
hourly_results = locator.get_demand_results_file(bldg, 'csv')
df_demand = pd.read_csv(hourly_results)
df_demand['GRID_ww_kWh'] = hp_dhw.loc[bldg]
df_demand['E_ww_kWh'] = hp_dhw.loc[bldg]
df_demand['NG_ww_kWh'] = ng_dhw.loc[bldg]
df_demand['DH_ww_kWh'] = 0
df_demand.to_csv(hourly_results)
for bldg in all_bldgs:
hourly_results = locator.get_demand_results_file(bldg, 'csv')
df_demand = pd.read_csv(hourly_results)
df_demand['GRID_kWh'] = df_demand[['GRID_a_kWh','GRID_l_kWh','GRID_v_kWh','GRID_ve_kWh','GRID_data_kWh',
'GRID_pro_kWh','GRID_aux_kWh','GRID_ww_kWh','GRID_hs_kWh',
'GRID_cs_kWh','GRID_cdata_kWh','GRID_cre_kWh']].sum(axis=1)
df_demand['E_sys_kWh'] = df_demand[['Eal_kWh', 'Ea_kWh', 'El_kWh', 'Ev_kWh', 'Eve_kWh', 'Edata_kWh',
'Epro_kWh', 'Eaux_kWh', 'E_ww_kWh', 'E_hs_kWh', 'E_cs_kWh',
'E_cre_kWh', 'E_cdata_kWh']].sum(axis=1)
df_demand.to_csv(hourly_results)
return print(' - District heating recalculated!')
def rewrite_to_csv(config):
"""
Used to rewrite the annual results per building after calculating
the district heating supply.
"""
locator = cea.inputlocator.InputLocator(config.scenario)
df_ann = pd.read_csv(locator.get_total_demand('csv'), index_col='Name')
print(' - Rewriting annual results following recalculation.')
for bldg in df_ann.index.to_list():
hourly_results = locator.get_demand_results_file(bldg, 'csv')
df_hourly = pd.read_csv(hourly_results, index_col='DATE')
df_ann.loc[bldg,'GRID_MWhyr'] = df_hourly['GRID_kWh'].sum() / 1000
df_ann.loc[bldg,'E_sys_MWhyr'] = df_hourly['E_sys_kWh'].sum() / 1000
df_ann.loc[bldg,'PV_MWhyr'] = df_hourly['PV_kWh'].sum() / 1000
df_ann.loc[bldg,'NG_hs_MWhyr'] = df_hourly['NG_hs_kWh'].sum() / 1000
df_ann.loc[bldg,'NG_ww_MWhyr'] = df_hourly['NG_ww_kWh'].sum() / 1000
df_ann.loc[bldg,'GRID_hs_MWhyr'] = df_hourly['GRID_hs_kWh'].sum() / 1000
df_ann.loc[bldg,'GRID_ww_MWhyr'] = df_hourly['GRID_ww_kWh'].sum() / 1000
df_ann.loc[bldg,'E_hs_MWhyr'] = df_hourly['E_hs_kWh'].sum() / 1000
df_ann.loc[bldg,'E_ww_MWhyr'] = df_hourly['E_ww_kWh'].sum() / 1000
df_ann.loc[bldg,'DH_hs_MWhyr'] = 0
df_ann.loc[bldg,'DH_ww_MWhyr'] = 0
df_ann.loc[bldg,'DH_hs0_kW'] = 0
df_ann.loc[bldg,'DH_ww0_kW'] = 0
df_ann.loc[bldg,'GRID_hs0_kW'] = df_hourly['GRID_hs_kWh'].max()
df_ann.loc[bldg,'E_hs0_kW'] = df_hourly['E_hs_kWh'].max()
df_ann.loc[bldg,'NG_hs0_kW'] = df_hourly['NG_hs_kWh'].max()
df_ann.loc[bldg,'GRID_ww0_kW'] = df_hourly['GRID_ww_kWh'].max()
df_ann.loc[bldg,'E_ww0_kW'] = df_hourly['E_ww_kWh'].max()
df_ann.loc[bldg,'NG_ww0_kW'] = df_hourly['NG_ww_kWh'].max()
df_ann['GRID0_kW'] = df_ann[['GRID_a0_kW', 'GRID_l0_kW', 'GRID_v0_kW', 'GRID_ve0_kW', 'GRID_data0_kW',
'GRID_pro0_kW', 'GRID_aux0_kW', 'GRID_ww0_kW', 'GRID_hs0_kW',
'GRID_cs0_kW', 'GRID_cdata0_kW', 'GRID_cre0_kW']].sum(axis=1)
df_ann['E_sys0_kW'] = df_ann[['Eal0_kW', 'Ea0_kW', 'El0_kW', 'Ev0_kW', 'Eve0_kW', 'Edata0_kW',
'Epro0_kW', 'Eaux0_kW', 'E_ww0_kW', 'E_hs0_kW', 'E_cs0_kW',
'E_cre0_kW', 'E_cdata0_kW']].sum(axis=1)
df_ann.to_csv(locator.get_total_demand('csv'), index=True, float_format='%.3f', na_rep=0)
return print(' - Annual results rewritten!')
def main(config):
recalc_DH(config)
rewrite_to_csv(config)
return print(' - District heating dealt with!')
if __name__ == '__main__':
t1 = time.perf_counter()
main(cea.config.Configuration())
time_end = time.perf_counter() - t1
print(time_end)
| 42.375 | 119 | 0.640836 |
import pandas as pd
import time
import logging
logging.getLogger('numba').setLevel(logging.WARNING)
from itertools import repeat
import cea.utilities.parallel
import cea.config
import cea.utilities
import cea.inputlocator
import cea.demand.demand_main
import cea.resources.radiation_daysim.radiation_main
import cea.bigmacc.bigmacc_rules
import cea.datamanagement.archetypes_mapper
import cea.datamanagement.data_initializer
import cea.analysis.costs.system_costs
import cea.analysis.lca.main
import cea.utilities.dbf
__author__ = "Justin McCarty"
__copyright__ = ""
__credits__ = ["Justin McCarty"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = ""
__email__ = ""
__status__ = ""
def demand_source(locator, bldg, resource):
hourly_results = locator.get_demand_results_file(bldg, 'csv')
df_demand = pd.read_csv(hourly_results)
return df_demand[resource].rename(bldg)
def breakup_use(df, config):
df = df.loc["total"]
df = df.transpose()
df.index = pd.date_range(start=f'1/1/{config.emissions.year_to_calculate}', periods=8760, freq='H')
return df
def district_buildings(locator):
supply_hs_df = pd.read_excel(locator.get_database_supply_assemblies(), sheet_name='HEATING')
supply_dhw_df = pd.read_excel(locator.get_database_supply_assemblies(), sheet_name='HOT_WATER')
hs_codes = supply_hs_df[supply_hs_df['feedstock'] == 'DISTRICT']['code'].to_list()
dhw_codes = supply_dhw_df[supply_dhw_df['feedstock'] == 'DISTRICT']['code'].to_list()
supply_df = cea.utilities.dbf.dbf_to_dataframe(locator.get_building_supply(), index='Name')
def get_build_list(codes, supply_type):
if supply_type in codes:
return 'Yes'
else:
return 'No'
supply_df['hs_keep'] = supply_df.apply(lambda x: get_build_list(hs_codes, x['type_hs']), axis=1)
on_DH_hs = supply_df[supply_df['hs_keep'] == 'Yes']['Name'].to_list()
supply_df['dhw_keep'] = supply_df.apply(lambda x: get_build_list(dhw_codes, x['type_dhw']), axis=1)
on_DH_dhw = supply_df[supply_df['dhw_keep'] == 'Yes']['Name'].to_list()
return on_DH_hs, on_DH_dhw
def ng(total, hplim):
if total > hplim:
return total - hplim
else:
return 0
def hp(total, ng_demand):
if ng_demand > 0:
return total - ng_demand
else:
return total
def hp1(hp_demand, trlim):
if hp_demand >= trlim:
return trlim
else:
return hp_demand
def hp2(hp_demand, hp1_demand, trlim):
if hp1_demand < trlim:
return 0
else:
return hp_demand - trlim
def calc_district_demand(df):
months = list(range(1, 13, 1))
triumf_max = [5, 3.5, 5, 9, 9, 9.5, 11, 10.5, 9.5, 9, 8, 6.5]
hp_max = [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
district = ((557900 + 75900) / 1078800)
triumf_district = [round(i * district * 1000, 2) for i in triumf_max]
hp_district = [round(i * district * 1000, 2) for i in hp_max]
triumf_limit = dict(zip(months, triumf_district))
hp_limit = dict(zip(months, hp_district))
df['tr_limit'] = df.index.month.map(triumf_limit)
df['hp_limit'] = df.index.month.map(hp_limit)
df['ng_demand'] = df.apply(lambda x: ng(x['total'], x['hp_limit']), axis=1)
df['hp_demand'] = df.apply(lambda x: hp(x['total'], x['ng_demand']), axis=1)
df['hp1_demand'] = df.apply(lambda x: hp1(x['hp_demand'], x['tr_limit']), axis=1)
df['hp2_demand'] = df.apply(lambda x: hp2(x['hp_demand'], x['hp1_demand'], x['tr_limit']), axis=1)
df['ng_source_demand'] = df['ng_demand'] / 0.95
df['hp1_source_demand'] = df['hp1_demand'] / 3.4
df['hp2_source_demand'] = df['hp2_demand'] / 2.7
df['hp_source_demand'] = df['hp1_source_demand'] + df['hp2_source_demand']
return df[['ng_source_demand', 'hp_source_demand']]
def recalc_DH(config):
locator = cea.inputlocator.InputLocator(config.scenario)
on_DH_hs, on_DH_dhw = district_buildings(locator)
while (len(on_DH_hs) == 0 or len(on_DH_dhw) == 0):
print('wrong')
break
heat_df = pd.DataFrame()
print(' - - - Gathering space heating...')
for bldg in on_DH_hs:
heat_df = heat_df.append(demand_source(locator, bldg, 'Qhs_sys_kWh'))
heat_df['Name'] = heat_df.index
dhw_df = pd.DataFrame()
print(' - - - Gathering DHW...')
for bldg in on_DH_dhw:
dhw_df = dhw_df.append(demand_source(locator, bldg, 'Qww_sys_kWh'))
dhw_df['Name'] = dhw_df.index
demand_df = pd.concat([heat_df, dhw_df], ignore_index=True).groupby(['Name'], as_index=False).sum()
demand_df = demand_df.set_index(demand_df['Name'], drop=True)
del demand_df['Name']
demand_df.loc["total"] = demand_df.sum()
heat_df.loc["total"] = heat_df.sum()
del heat_df['Name']
dhw_df.loc["total"] = dhw_df.sum()
del dhw_df['Name']
def calc_share(demand, total):
return demand / total
print(' - - - Calculating share of district heat load...')
heat_df_share = heat_df.apply(lambda x: calc_share(x, heat_df.loc['total']), axis=1)
dhw_df_share = dhw_df.apply(lambda x: calc_share(x, dhw_df.loc['total']), axis=1)
demand_DH_heat = pd.DataFrame(breakup_use(heat_df, config))
demand_DH_dhw = pd.DataFrame(breakup_use(dhw_df, config))
demand_DH_heat = calc_district_demand(demand_DH_heat)
demand_DH_dhw = calc_district_demand(demand_DH_dhw)
hp_dhw = demand_DH_dhw['hp_source_demand'].reset_index(drop=True).transpose() * dhw_df_share
hp_heat = demand_DH_heat['hp_source_demand'].reset_index(drop=True).transpose() * heat_df_share
ng_dhw = demand_DH_dhw['ng_source_demand'].reset_index(drop=True).transpose() * dhw_df_share
ng_heat = demand_DH_heat['ng_source_demand'].reset_index(drop=True).transpose() * heat_df_share
all_bldgs = on_DH_hs + list(set(on_DH_dhw) - set(on_DH_hs))
if on_DH_hs == on_DH_dhw:
print(' - - - Changing results for all bldgs...')
for bldg in all_bldgs:
hourly_results = locator.get_demand_results_file(bldg, 'csv')
df_demand = pd.read_csv(hourly_results)
df_demand['GRID_hs_kWh'] = hp_heat.loc[bldg]
df_demand['E_hs_kWh'] = hp_heat.loc[bldg]
df_demand['NG_hs_kWh'] = ng_heat.loc[bldg]
df_demand['DH_hs_kWh'] = 0
df_demand['GRID_ww_kWh'] = hp_dhw.loc[bldg]
df_demand['E_ww_kWh'] = hp_heat.loc[bldg]
df_demand['NG_ww_kWh'] = ng_dhw.loc[bldg]
df_demand['DH_ww_kWh'] = 0
df_demand['GRID_kWh'] = df_demand[['GRID_a_kWh', 'GRID_l_kWh', 'GRID_v_kWh', 'GRID_ve_kWh','GRID_data_kWh',
'GRID_pro_kWh', 'GRID_aux_kWh', 'GRID_ww_kWh','GRID_hs_kWh',
'GRID_cs_kWh', 'GRID_cdata_kWh', 'GRID_cre_kWh']].sum(axis=1)
df_demand['E_sys_kWh'] = df_demand[['Eal_kWh', 'Ea_kWh', 'El_kWh', 'Ev_kWh', 'Eve_kWh', 'Edata_kWh',
'Epro_kWh', 'Eaux_kWh', 'E_ww_kWh', 'E_hs_kWh', 'E_cs_kWh',
'E_cre_kWh', 'E_cdata_kWh']].sum(axis=1)
df_demand.to_csv(hourly_results)
else:
for bldg in on_DH_hs:
print(' - - - Resetting results for all district heat buildings...')
hourly_results = locator.get_demand_results_file(bldg, 'csv')
df_demand = pd.read_csv(hourly_results)
df_demand['GRID_hs_kWh'] = hp_heat.loc[bldg]
df_demand['E_hs_kWh'] = hp_heat.loc[bldg]
df_demand['NG_hs_kWh'] = ng_heat.loc[bldg]
df_demand['DH_hs_kWh'] = 0
df_demand.to_csv(hourly_results)
for bldg in on_DH_dhw:
print(' - - - Resetting results for district hot water bldgs...')
hourly_results = locator.get_demand_results_file(bldg, 'csv')
df_demand = pd.read_csv(hourly_results)
df_demand['GRID_ww_kWh'] = hp_dhw.loc[bldg]
df_demand['E_ww_kWh'] = hp_dhw.loc[bldg]
df_demand['NG_ww_kWh'] = ng_dhw.loc[bldg]
df_demand['DH_ww_kWh'] = 0
df_demand.to_csv(hourly_results)
for bldg in all_bldgs:
hourly_results = locator.get_demand_results_file(bldg, 'csv')
df_demand = pd.read_csv(hourly_results)
df_demand['GRID_kWh'] = df_demand[['GRID_a_kWh','GRID_l_kWh','GRID_v_kWh','GRID_ve_kWh','GRID_data_kWh',
'GRID_pro_kWh','GRID_aux_kWh','GRID_ww_kWh','GRID_hs_kWh',
'GRID_cs_kWh','GRID_cdata_kWh','GRID_cre_kWh']].sum(axis=1)
df_demand['E_sys_kWh'] = df_demand[['Eal_kWh', 'Ea_kWh', 'El_kWh', 'Ev_kWh', 'Eve_kWh', 'Edata_kWh',
'Epro_kWh', 'Eaux_kWh', 'E_ww_kWh', 'E_hs_kWh', 'E_cs_kWh',
'E_cre_kWh', 'E_cdata_kWh']].sum(axis=1)
df_demand.to_csv(hourly_results)
return print(' - District heating recalculated!')
def rewrite_to_csv(config):
locator = cea.inputlocator.InputLocator(config.scenario)
df_ann = pd.read_csv(locator.get_total_demand('csv'), index_col='Name')
print(' - Rewriting annual results following recalculation.')
for bldg in df_ann.index.to_list():
hourly_results = locator.get_demand_results_file(bldg, 'csv')
df_hourly = pd.read_csv(hourly_results, index_col='DATE')
df_ann.loc[bldg,'GRID_MWhyr'] = df_hourly['GRID_kWh'].sum() / 1000
df_ann.loc[bldg,'E_sys_MWhyr'] = df_hourly['E_sys_kWh'].sum() / 1000
df_ann.loc[bldg,'PV_MWhyr'] = df_hourly['PV_kWh'].sum() / 1000
df_ann.loc[bldg,'NG_hs_MWhyr'] = df_hourly['NG_hs_kWh'].sum() / 1000
df_ann.loc[bldg,'NG_ww_MWhyr'] = df_hourly['NG_ww_kWh'].sum() / 1000
df_ann.loc[bldg,'GRID_hs_MWhyr'] = df_hourly['GRID_hs_kWh'].sum() / 1000
df_ann.loc[bldg,'GRID_ww_MWhyr'] = df_hourly['GRID_ww_kWh'].sum() / 1000
df_ann.loc[bldg,'E_hs_MWhyr'] = df_hourly['E_hs_kWh'].sum() / 1000
df_ann.loc[bldg,'E_ww_MWhyr'] = df_hourly['E_ww_kWh'].sum() / 1000
df_ann.loc[bldg,'DH_hs_MWhyr'] = 0
df_ann.loc[bldg,'DH_ww_MWhyr'] = 0
df_ann.loc[bldg,'DH_hs0_kW'] = 0
df_ann.loc[bldg,'DH_ww0_kW'] = 0
df_ann.loc[bldg,'GRID_hs0_kW'] = df_hourly['GRID_hs_kWh'].max()
df_ann.loc[bldg,'E_hs0_kW'] = df_hourly['E_hs_kWh'].max()
df_ann.loc[bldg,'NG_hs0_kW'] = df_hourly['NG_hs_kWh'].max()
df_ann.loc[bldg,'GRID_ww0_kW'] = df_hourly['GRID_ww_kWh'].max()
df_ann.loc[bldg,'E_ww0_kW'] = df_hourly['E_ww_kWh'].max()
df_ann.loc[bldg,'NG_ww0_kW'] = df_hourly['NG_ww_kWh'].max()
df_ann['GRID0_kW'] = df_ann[['GRID_a0_kW', 'GRID_l0_kW', 'GRID_v0_kW', 'GRID_ve0_kW', 'GRID_data0_kW',
'GRID_pro0_kW', 'GRID_aux0_kW', 'GRID_ww0_kW', 'GRID_hs0_kW',
'GRID_cs0_kW', 'GRID_cdata0_kW', 'GRID_cre0_kW']].sum(axis=1)
df_ann['E_sys0_kW'] = df_ann[['Eal0_kW', 'Ea0_kW', 'El0_kW', 'Ev0_kW', 'Eve0_kW', 'Edata0_kW',
'Epro0_kW', 'Eaux0_kW', 'E_ww0_kW', 'E_hs0_kW', 'E_cs0_kW',
'E_cre0_kW', 'E_cdata0_kW']].sum(axis=1)
df_ann.to_csv(locator.get_total_demand('csv'), index=True, float_format='%.3f', na_rep=0)
return print(' - Annual results rewritten!')
def main(config):
recalc_DH(config)
rewrite_to_csv(config)
return print(' - District heating dealt with!')
if __name__ == '__main__':
t1 = time.perf_counter()
main(cea.config.Configuration())
time_end = time.perf_counter() - t1
print(time_end)
| true | true |
1c2bb8a3a99295fae2abd825d2b16e03dfeccb98 | 13,691 | py | Python | short-read-mngs/idseq-dag/idseq_dag/steps/run_validate_input.py | chanzuckerberg/idseq-workflows | b1e7c91e5d9f0d9a05f97f240211fcc16d33225b | [
"MIT"
] | 30 | 2020-05-23T21:23:38.000Z | 2022-03-24T17:18:47.000Z | short-read-mngs/idseq-dag/idseq_dag/steps/run_validate_input.py | grunwaldlab/idseq-workflows | cacfaa02f014ba06b8fb69e62911ab7fd5d88d9a | [
"MIT"
] | 65 | 2020-05-27T14:21:26.000Z | 2021-11-18T17:58:56.000Z | short-read-mngs/idseq-dag/idseq_dag/steps/run_validate_input.py | grunwaldlab/idseq-workflows | cacfaa02f014ba06b8fb69e62911ab7fd5d88d9a | [
"MIT"
] | 12 | 2020-08-24T12:00:28.000Z | 2022-02-03T08:28:02.000Z | import json
import os
from idseq_dag.engine.pipeline_step import PipelineStep
from idseq_dag.exceptions import InvalidFileFormatError, InsufficientReadsError
import idseq_dag.util.command as command
import idseq_dag.util.command_patterns as command_patterns
import idseq_dag.util.count as count
import idseq_dag.util.validate_constants as vc
import idseq_dag.util.s3 as s3
class PipelineStepRunValidateInput(PipelineStep):
""" Validates that the input files are .fastq format and truncates to 75 million fragments
(specifically, 75 million reads for single-end libraries or 150 million reads for paired-end libraries).
The validation process counts the number of sequences that fall in specified length buckets, which will
inform the parameters used downstream for initial host removal by STAR.
"""
def run(self):
# Setup
input_files = self.input_files_local[0][0:2]
num_inputs = len(input_files)
assert num_inputs in [1, 2], 'Invalid number of input files'
output_files = self.output_files_local()[1:3]
summary_file = self.output_files_local()[0]
max_fragments = self.additional_attributes["truncate_fragments_to"]
file_ext = self.additional_attributes.get("file_ext")
assert file_ext in ['fastq', 'fasta'], 'Invalid file extension'
is_fastq = file_ext == 'fastq'
try:
for i in range(num_inputs):
input_file = input_files[i]
splited_input_file_name, splited_input_file_ext = os.path.splitext(input_file)
num_lines = self.calc_max_num_lines(is_fastq, max_fragments)
# unzip if .gz file
if splited_input_file_ext == '.gz':
input_files[i] = splited_input_file_name
try:
# test if a valid gzip file
command.execute(
command_patterns.SingleCommand(
cmd="gzip",
args=[
"-t",
input_file
]
)
)
# then decompress it
command.execute(
command_patterns.ShellScriptCommand(
script=r'''gzip -dc "${input_file}" | cut -c -"$[max_line_length+1]" | head -n "${num_lines}" | sed -e 's/\r$//' | awk -f "${awk_script_file}" -v max_line_length="${max_line_length}" > "${output_file}";''',
named_args={
"input_file": input_file,
"awk_script_file": command.get_resource_filename("scripts/fastq-fasta-line-validation.awk"),
"max_line_length": vc.MAX_LINE_LENGTH,
"num_lines": num_lines,
"output_file": splited_input_file_name
}
)
)
except:
raise InvalidFileFormatError("Invalid fastq/fasta/gzip file")
else:
# Validate and truncate the input file to keep behavior consistent with gz input files
try:
tmp_file = splited_input_file_name + ".tmp"
command.execute(
command_patterns.ShellScriptCommand(
script=r'''cat "${input_file}" | cut -c -"$[max_line_length+1]" | head -n "${num_lines}" | sed -e 's/\r$//' | awk -f "${awk_script_file}" -v max_line_length="${max_line_length}" > "${output_file}";''',
named_args={
"input_file": input_file,
"awk_script_file": command.get_resource_filename("scripts/fastq-fasta-line-validation.awk"),
"max_line_length": vc.MAX_LINE_LENGTH,
"num_lines": num_lines,
"output_file": tmp_file
}
)
)
input_files[i] = tmp_file
except:
raise InvalidFileFormatError("Invalid fastq/fasta file")
# keep a dictionary of the distribution of read lengths in the files
self.summary_dict = {vc.BUCKET_TOO_SHORT: 0,
vc.BUCKET_NORMAL: 0,
vc.BUCKET_LONG: 0,
vc.BUCKET_TOO_LONG: 0}
# add a total reads output as source of truth (if filtering changes)
self.total_output_reads = 0
quick_check_passed = \
self.quick_check_file(input_files[0], is_fastq) and \
(num_inputs == 1 or self.quick_check_file(input_files[1], is_fastq))
all_fragments = []
for infile, outfile in zip(input_files, output_files):
if quick_check_passed:
num_fragments = self.truncate_file(infile, outfile, is_fastq, max_fragments)
else:
num_fragments = self._full_check_and_truncate_file(infile, outfile, is_fastq, max_fragments, num_inputs)
all_fragments.append(num_fragments)
if len(all_fragments) == 2 and abs(all_fragments[1] - all_fragments[0]) > 1000:
raise InvalidFileFormatError("Paired input files need to contain the same number of reads")
with open(summary_file, 'w') as summary_f:
json.dump(self.summary_dict, summary_f)
except Exception as e:
with open(summary_file, 'w') as summary_f:
json.dump({'Validation error': str(e)}, summary_f)
s3_path = self.s3_path(summary_file)
s3.upload_with_retries(summary_file, s3_path)
raise e
return
# quick_check_file returns:
# True if the first 100 fragments all have the same length of reads and
# are well-formated single-line FASTA / FASTQ entries.
#
# False if the entries are not formatted simply or the read lengths are not
# all identical or if there is another possibly recoverable error
#
# Throws an exception in the case of an unrecoverable abnormality
def quick_check_file(self, file, is_fastq, max_fragments_to_check=100):
num_fragments = 0
fragment_length = 0
with open(file, 'r', encoding='utf-8') as input_f:
while True:
num_fragments += 1
if num_fragments > max_fragments_to_check:
break
identifier_l = input_f.readline()
if len(identifier_l) == 0: # EOF
if num_fragments == 1:
raise InsufficientReadsError("The input file contains 0 reads")
break
read_l = input_f.readline()
if len(read_l) == 0: # unexpected EOF
raise InvalidFileFormatError("Invalid input file")
if is_fastq:
identifier2_l = input_f.readline()
if len(identifier2_l) == 0:
raise InvalidFileFormatError("Invalid FASTQ file")
quality_l = input_f.readline()
if len(quality_l) == 0:
raise InvalidFileFormatError("Invalid FASTQ file")
if is_fastq:
if identifier_l[0] != '@' or identifier2_l[0] != '+':
# may be FASTQ file with multi-line reads, requires full check
return False
else:
if identifier_l[0] != '>':
# may be FASTA file with multi-line reads, requires full check
return False
if fragment_length == 0:
fragment_length = len(read_l)
if fragment_length < vc.READ_LEN_CUTOFF_LOW or fragment_length > vc.READ_LEN_CUTOFF_MID:
# non-standard fragment lengths require more detailed examination
return False
if fragment_length != len(read_l) or (is_fastq and fragment_length != len(quality_l)):
# file does not meet "quick check" requirements since fragments/quality
# scores are not all of same length
return False
return True
def calc_max_num_lines(self, is_fastq, max_fragments):
if is_fastq:
num_lines = max_fragments * 4
else:
num_lines = max_fragments * 2
return num_lines
def truncate_file(self, infile, outfile, is_fastq, max_fragments):
num_lines = self.calc_max_num_lines(is_fastq, max_fragments)
command.execute(
command_patterns.ShellScriptCommand(
script=r'''head -n "${num_lines}" "${infile}" > "${outfile}";''',
named_args={
'num_lines': num_lines,
'infile': infile,
'outfile': outfile
}
)
)
num_fragments = count.reads(outfile)
self.summary_dict[vc.BUCKET_NORMAL] += num_fragments
self.total_output_reads += num_fragments
return num_fragments
# _full_check_and_truncate_file does an exhaustive check of the input file, up to
# max_fragments, and reformats the output to conform to what the rest of the
# computational pipeline expects (single-line reads of max-length 10,000). After
# viewing max_fragments reads or encountering EOF, the function returns.
#
# Throws an exception in the case of an unrecoverable abnormality
def _full_check_and_truncate_file(self, infile, outfile, is_fastq, max_fragments, num_inputs):
num_fragments = 0
with open(infile, 'r', encoding='utf-8') as input_f, open(outfile, 'w') as output_f:
next_line = input_f.readline()
while True:
num_fragments += 1
if num_fragments > max_fragments:
break
identifier_l = next_line
if len(identifier_l) == 0: # EOF
break
read_l = input_f.readline()
if len(read_l) == 0:
raise InvalidFileFormatError("Invalid input file")
read_l = read_l.rstrip()
next_line = input_f.readline()
while len(next_line) > 0 and next_line[0] not in ['>', '@', '+']:
read_l += next_line.rstrip()
next_line = input_f.readline()
if is_fastq:
identifier2_l = next_line
if len(identifier2_l) == 0:
raise InvalidFileFormatError("Invalid FASTQ file")
quality_l = input_f.readline()
if len(quality_l) == 0:
raise InvalidFileFormatError("Invalid FASTQ file")
quality_l = quality_l.rstrip()
next_line = input_f.readline()
while len(next_line) > 0 and next_line[0] not in ['>', '@', '+']:
quality_l += next_line.rstrip()
next_line = input_f.readline()
if is_fastq:
if identifier_l[0] != '@':
raise InvalidFileFormatError("Invalid FASTQ file")
if identifier2_l[0] != '+':
raise InvalidFileFormatError("Invalid FASTQ file")
else:
if identifier_l[0] != '>':
raise InvalidFileFormatError("Invalid FASTA file")
# At this point, identifier_l and identifier2_l end in a newline and
# read_l and quality_l do not end in a newline
read_len = len(read_l)
# Force read and quality lengths to be identical, either by padding quality
# with the last quality score or truncating quality score
if is_fastq:
if read_len > len(quality_l):
quality_l += (quality_l[-1] * (read_len - len(quality_l)))
elif read_len < len(quality_l):
quality_l = quality_l[0:read_len]
if read_len < vc.READ_LEN_CUTOFF_LOW:
self.summary_dict[vc.BUCKET_TOO_SHORT] += 1
elif read_len < vc.READ_LEN_CUTOFF_MID:
self.summary_dict[vc.BUCKET_NORMAL] += 1
elif read_len < vc.READ_LEN_CUTOFF_HIGH:
self.summary_dict[vc.BUCKET_LONG] += 1
else:
self.summary_dict[vc.BUCKET_TOO_LONG] += 1
read_l = read_l[0:vc.READ_LEN_CUTOFF_HIGH]
if is_fastq:
quality_l = quality_l[0:vc.READ_LEN_CUTOFF_HIGH]
self.total_output_reads += 1
output_f.write(identifier_l + read_l + "\n")
if is_fastq:
output_f.write(identifier2_l + quality_l + "\n")
return num_fragments
def count_reads(self):
self.should_count_reads = True
self.counts_dict[self.name] = self.total_output_reads
| 46.253378 | 238 | 0.536119 | import json
import os
from idseq_dag.engine.pipeline_step import PipelineStep
from idseq_dag.exceptions import InvalidFileFormatError, InsufficientReadsError
import idseq_dag.util.command as command
import idseq_dag.util.command_patterns as command_patterns
import idseq_dag.util.count as count
import idseq_dag.util.validate_constants as vc
import idseq_dag.util.s3 as s3
class PipelineStepRunValidateInput(PipelineStep):
def run(self):
input_files = self.input_files_local[0][0:2]
num_inputs = len(input_files)
assert num_inputs in [1, 2], 'Invalid number of input files'
output_files = self.output_files_local()[1:3]
summary_file = self.output_files_local()[0]
max_fragments = self.additional_attributes["truncate_fragments_to"]
file_ext = self.additional_attributes.get("file_ext")
assert file_ext in ['fastq', 'fasta'], 'Invalid file extension'
is_fastq = file_ext == 'fastq'
try:
for i in range(num_inputs):
input_file = input_files[i]
splited_input_file_name, splited_input_file_ext = os.path.splitext(input_file)
num_lines = self.calc_max_num_lines(is_fastq, max_fragments)
if splited_input_file_ext == '.gz':
input_files[i] = splited_input_file_name
try:
command.execute(
command_patterns.SingleCommand(
cmd="gzip",
args=[
"-t",
input_file
]
)
)
command.execute(
command_patterns.ShellScriptCommand(
script=r'''gzip -dc "${input_file}" | cut -c -"$[max_line_length+1]" | head -n "${num_lines}" | sed -e 's/\r$//' | awk -f "${awk_script_file}" -v max_line_length="${max_line_length}" > "${output_file}";''',
named_args={
"input_file": input_file,
"awk_script_file": command.get_resource_filename("scripts/fastq-fasta-line-validation.awk"),
"max_line_length": vc.MAX_LINE_LENGTH,
"num_lines": num_lines,
"output_file": splited_input_file_name
}
)
)
except:
raise InvalidFileFormatError("Invalid fastq/fasta/gzip file")
else:
try:
tmp_file = splited_input_file_name + ".tmp"
command.execute(
command_patterns.ShellScriptCommand(
script=r'''cat "${input_file}" | cut -c -"$[max_line_length+1]" | head -n "${num_lines}" | sed -e 's/\r$//' | awk -f "${awk_script_file}" -v max_line_length="${max_line_length}" > "${output_file}";''',
named_args={
"input_file": input_file,
"awk_script_file": command.get_resource_filename("scripts/fastq-fasta-line-validation.awk"),
"max_line_length": vc.MAX_LINE_LENGTH,
"num_lines": num_lines,
"output_file": tmp_file
}
)
)
input_files[i] = tmp_file
except:
raise InvalidFileFormatError("Invalid fastq/fasta file")
self.summary_dict = {vc.BUCKET_TOO_SHORT: 0,
vc.BUCKET_NORMAL: 0,
vc.BUCKET_LONG: 0,
vc.BUCKET_TOO_LONG: 0}
self.total_output_reads = 0
quick_check_passed = \
self.quick_check_file(input_files[0], is_fastq) and \
(num_inputs == 1 or self.quick_check_file(input_files[1], is_fastq))
all_fragments = []
for infile, outfile in zip(input_files, output_files):
if quick_check_passed:
num_fragments = self.truncate_file(infile, outfile, is_fastq, max_fragments)
else:
num_fragments = self._full_check_and_truncate_file(infile, outfile, is_fastq, max_fragments, num_inputs)
all_fragments.append(num_fragments)
if len(all_fragments) == 2 and abs(all_fragments[1] - all_fragments[0]) > 1000:
raise InvalidFileFormatError("Paired input files need to contain the same number of reads")
with open(summary_file, 'w') as summary_f:
json.dump(self.summary_dict, summary_f)
except Exception as e:
with open(summary_file, 'w') as summary_f:
json.dump({'Validation error': str(e)}, summary_f)
s3_path = self.s3_path(summary_file)
s3.upload_with_retries(summary_file, s3_path)
raise e
return
def quick_check_file(self, file, is_fastq, max_fragments_to_check=100):
num_fragments = 0
fragment_length = 0
with open(file, 'r', encoding='utf-8') as input_f:
while True:
num_fragments += 1
if num_fragments > max_fragments_to_check:
break
identifier_l = input_f.readline()
if len(identifier_l) == 0:
if num_fragments == 1:
raise InsufficientReadsError("The input file contains 0 reads")
break
read_l = input_f.readline()
if len(read_l) == 0:
raise InvalidFileFormatError("Invalid input file")
if is_fastq:
identifier2_l = input_f.readline()
if len(identifier2_l) == 0:
raise InvalidFileFormatError("Invalid FASTQ file")
quality_l = input_f.readline()
if len(quality_l) == 0:
raise InvalidFileFormatError("Invalid FASTQ file")
if is_fastq:
if identifier_l[0] != '@' or identifier2_l[0] != '+':
return False
else:
if identifier_l[0] != '>':
return False
if fragment_length == 0:
fragment_length = len(read_l)
if fragment_length < vc.READ_LEN_CUTOFF_LOW or fragment_length > vc.READ_LEN_CUTOFF_MID:
return False
if fragment_length != len(read_l) or (is_fastq and fragment_length != len(quality_l)):
return False
return True
def calc_max_num_lines(self, is_fastq, max_fragments):
if is_fastq:
num_lines = max_fragments * 4
else:
num_lines = max_fragments * 2
return num_lines
def truncate_file(self, infile, outfile, is_fastq, max_fragments):
num_lines = self.calc_max_num_lines(is_fastq, max_fragments)
command.execute(
command_patterns.ShellScriptCommand(
script=r'''head -n "${num_lines}" "${infile}" > "${outfile}";''',
named_args={
'num_lines': num_lines,
'infile': infile,
'outfile': outfile
}
)
)
num_fragments = count.reads(outfile)
self.summary_dict[vc.BUCKET_NORMAL] += num_fragments
self.total_output_reads += num_fragments
return num_fragments
def _full_check_and_truncate_file(self, infile, outfile, is_fastq, max_fragments, num_inputs):
num_fragments = 0
with open(infile, 'r', encoding='utf-8') as input_f, open(outfile, 'w') as output_f:
next_line = input_f.readline()
while True:
num_fragments += 1
if num_fragments > max_fragments:
break
identifier_l = next_line
if len(identifier_l) == 0:
break
read_l = input_f.readline()
if len(read_l) == 0:
raise InvalidFileFormatError("Invalid input file")
read_l = read_l.rstrip()
next_line = input_f.readline()
while len(next_line) > 0 and next_line[0] not in ['>', '@', '+']:
read_l += next_line.rstrip()
next_line = input_f.readline()
if is_fastq:
identifier2_l = next_line
if len(identifier2_l) == 0:
raise InvalidFileFormatError("Invalid FASTQ file")
quality_l = input_f.readline()
if len(quality_l) == 0:
raise InvalidFileFormatError("Invalid FASTQ file")
quality_l = quality_l.rstrip()
next_line = input_f.readline()
while len(next_line) > 0 and next_line[0] not in ['>', '@', '+']:
quality_l += next_line.rstrip()
next_line = input_f.readline()
if is_fastq:
if identifier_l[0] != '@':
raise InvalidFileFormatError("Invalid FASTQ file")
if identifier2_l[0] != '+':
raise InvalidFileFormatError("Invalid FASTQ file")
else:
if identifier_l[0] != '>':
raise InvalidFileFormatError("Invalid FASTA file")
read_len = len(read_l)
if is_fastq:
if read_len > len(quality_l):
quality_l += (quality_l[-1] * (read_len - len(quality_l)))
elif read_len < len(quality_l):
quality_l = quality_l[0:read_len]
if read_len < vc.READ_LEN_CUTOFF_LOW:
self.summary_dict[vc.BUCKET_TOO_SHORT] += 1
elif read_len < vc.READ_LEN_CUTOFF_MID:
self.summary_dict[vc.BUCKET_NORMAL] += 1
elif read_len < vc.READ_LEN_CUTOFF_HIGH:
self.summary_dict[vc.BUCKET_LONG] += 1
else:
self.summary_dict[vc.BUCKET_TOO_LONG] += 1
read_l = read_l[0:vc.READ_LEN_CUTOFF_HIGH]
if is_fastq:
quality_l = quality_l[0:vc.READ_LEN_CUTOFF_HIGH]
self.total_output_reads += 1
output_f.write(identifier_l + read_l + "\n")
if is_fastq:
output_f.write(identifier2_l + quality_l + "\n")
return num_fragments
def count_reads(self):
self.should_count_reads = True
self.counts_dict[self.name] = self.total_output_reads
| true | true |
1c2bb8a98c077606cc899d45686c3cf5e5870630 | 321 | py | Python | settings_prod.py | pryny/django_shop_alex | 3c04aab7573734a82a969ec152c3986ed240ab8d | [
"Apache-2.0"
] | null | null | null | settings_prod.py | pryny/django_shop_alex | 3c04aab7573734a82a969ec152c3986ed240ab8d | [
"Apache-2.0"
] | null | null | null | settings_prod.py | pryny/django_shop_alex | 3c04aab7573734a82a969ec152c3986ed240ab8d | [
"Apache-2.0"
] | null | null | null | DEBUG = False
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'db1',
'USER': 'alex',
'PASSWORD': 'asdewqr1',
'HOST': 'localhost', # Set to empty string for localhost.
'PORT': '', # Set to empty string for default.
}
} | 26.75 | 62 | 0.566978 | DEBUG = False
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'db1',
'USER': 'alex',
'PASSWORD': 'asdewqr1',
'HOST': 'localhost',
'PORT': '',
}
} | true | true |
1c2bb8b70e8aee984db365fa62cfda1a098c013c | 1,121 | py | Python | manipulateWindowExample.py | KevinRohn/py-window-manipulation | ec4cfb4d3baa027071bd1dc111278e75a9b784a3 | [
"MIT"
] | null | null | null | manipulateWindowExample.py | KevinRohn/py-window-manipulation | ec4cfb4d3baa027071bd1dc111278e75a9b784a3 | [
"MIT"
] | null | null | null | manipulateWindowExample.py | KevinRohn/py-window-manipulation | ec4cfb4d3baa027071bd1dc111278e75a9b784a3 | [
"MIT"
] | null | null | null | import sys, os
sys.path.append(os.getcwd()+ r"\modules")
import WMM
import time
import subprocess
w = WMM.WindowManipulationManager()
def startProgram(programm="", args=""):
subprocess.Popen(programm+"" + args+ "")
def renameWindow(title=""):
w.set_window_title(title)
def findWindow():
if w.find_window_wildcard(".*Micro*"):
return True
def moveWindow(move=None,monitor=0):
if w.prepare_style_build():
w.style_builder(resizable=False,sysmenu=False,minimizebox=False,maximizebox=False,closeable=False,border=False,titlebar=False,sizebox=False,taskbarIcon=True)
w.set_defined_style()
w.remove_menubar()
w.set_foreground()
if move is not None:
if move:
try:
monitorInfo = w.get_info_for_monitor(monitor)
w.move_window_to_pos(monitorInfo['Monitor'])
except:
print("no Monitor found")
else:
w.set_FullScreen()
startProgram("http://<IP>")
time.sleep(5)
if findWindow():
renameWindow("New Title")
time.sleep(5)
moveWindow(move=True,monitor=0) | 26.069767 | 165 | 0.648528 | import sys, os
sys.path.append(os.getcwd()+ r"\modules")
import WMM
import time
import subprocess
w = WMM.WindowManipulationManager()
def startProgram(programm="", args=""):
subprocess.Popen(programm+"" + args+ "")
def renameWindow(title=""):
w.set_window_title(title)
def findWindow():
if w.find_window_wildcard(".*Micro*"):
return True
def moveWindow(move=None,monitor=0):
if w.prepare_style_build():
w.style_builder(resizable=False,sysmenu=False,minimizebox=False,maximizebox=False,closeable=False,border=False,titlebar=False,sizebox=False,taskbarIcon=True)
w.set_defined_style()
w.remove_menubar()
w.set_foreground()
if move is not None:
if move:
try:
monitorInfo = w.get_info_for_monitor(monitor)
w.move_window_to_pos(monitorInfo['Monitor'])
except:
print("no Monitor found")
else:
w.set_FullScreen()
startProgram("http://<IP>")
time.sleep(5)
if findWindow():
renameWindow("New Title")
time.sleep(5)
moveWindow(move=True,monitor=0) | true | true |
1c2bb8c955cb5b0c1b40aa00ae5b9ae97aab9bbe | 2,617 | py | Python | setup.py | One-sixth/imageio-ffmpeg | 888dace44a2160395cd88c577d542fe820086aa0 | [
"BSD-2-Clause"
] | null | null | null | setup.py | One-sixth/imageio-ffmpeg | 888dace44a2160395cd88c577d542fe820086aa0 | [
"BSD-2-Clause"
] | null | null | null | setup.py | One-sixth/imageio-ffmpeg | 888dace44a2160395cd88c577d542fe820086aa0 | [
"BSD-2-Clause"
] | null | null | null | """
Setup script for imageio-ffmpeg.
"""
import os
import sys
from setuptools import setup
this_dir = os.path.dirname(os.path.abspath(__file__))
# Get version
sys.path.insert(0, os.path.join(this_dir, "imageio_ffmpeg"))
try:
from _definitions import __version__
finally:
sys.path.pop(0)
# Disallow releasing via setup.py
if "upload" in sys.argv:
raise RuntimeError("Running setup.py upload is not the proper release procedure!")
# If making a source dist, clear the binaries directory
if "sdist" in sys.argv:
target_dir = os.path.abspath(os.path.join(this_dir, "imageio_ffmpeg", "binaries"))
for fname in os.listdir(target_dir):
if fname != "README.md":
os.remove(os.path.join(target_dir, fname))
long_description = """
FFMPEG wrapper for Python.
Note that the platform-specific wheels contain the binary executable
of ffmpeg, which makes this package around 60 MiB in size.
I guess that's the cost for being able to read/write video files.
For Linux users: the above is not the case when installing via your
Linux package manager (if that is possible), because this package would
simply depend on ffmpeg in that case.
""".lstrip()
setup(
name="imageio-ffmpeg",
version=__version__,
author="imageio contributors",
author_email="almar.klein@gmail.com",
license="(new) BSD",
url="https://github.com/imageio/imageio-ffmpeg",
download_url="http://pypi.python.org/pypi/imageio-ffmpeg",
keywords="video ffmpeg",
description="FFMPEG wrapper for Python",
long_description=long_description,
platforms="any",
provides=["imageio_ffmpeg"],
python_requires=">=3.4",
setup_requires=["pip>19"],
install_requires=[], # todo: maybe numpy
packages=["imageio_ffmpeg"],
package_dir={"imageio_ffmpeg": "imageio_ffmpeg"},
package_data={"imageio_ffmpeg": ["binaries/*.*"]},
include_package_data=True,
zip_safe=False,
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Science/Research",
"Intended Audience :: Education",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
],
)
| 31.154762 | 86 | 0.677111 |
import os
import sys
from setuptools import setup
this_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(this_dir, "imageio_ffmpeg"))
try:
from _definitions import __version__
finally:
sys.path.pop(0)
if "upload" in sys.argv:
raise RuntimeError("Running setup.py upload is not the proper release procedure!")
if "sdist" in sys.argv:
target_dir = os.path.abspath(os.path.join(this_dir, "imageio_ffmpeg", "binaries"))
for fname in os.listdir(target_dir):
if fname != "README.md":
os.remove(os.path.join(target_dir, fname))
long_description = """
FFMPEG wrapper for Python.
Note that the platform-specific wheels contain the binary executable
of ffmpeg, which makes this package around 60 MiB in size.
I guess that's the cost for being able to read/write video files.
For Linux users: the above is not the case when installing via your
Linux package manager (if that is possible), because this package would
simply depend on ffmpeg in that case.
""".lstrip()
setup(
name="imageio-ffmpeg",
version=__version__,
author="imageio contributors",
author_email="almar.klein@gmail.com",
license="(new) BSD",
url="https://github.com/imageio/imageio-ffmpeg",
download_url="http://pypi.python.org/pypi/imageio-ffmpeg",
keywords="video ffmpeg",
description="FFMPEG wrapper for Python",
long_description=long_description,
platforms="any",
provides=["imageio_ffmpeg"],
python_requires=">=3.4",
setup_requires=["pip>19"],
install_requires=[], # todo: maybe numpy
packages=["imageio_ffmpeg"],
package_dir={"imageio_ffmpeg": "imageio_ffmpeg"},
package_data={"imageio_ffmpeg": ["binaries/*.*"]},
include_package_data=True,
zip_safe=False,
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Science/Research",
"Intended Audience :: Education",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
],
)
| true | true |
1c2bb9375a496db093a5e79a34e5b401bf3621e7 | 1,514 | py | Python | sourcecode/src/vx/pgff/Access.py | Jarol0709/GFF | 2817ef97434c1e2c0c96cdbf48617d5a38c01e01 | [
"MIT"
] | 1 | 2021-01-23T14:22:03.000Z | 2021-01-23T14:22:03.000Z | sourcecode/src/vx/pgff/Access.py | Jarol0709/GFF | 2817ef97434c1e2c0c96cdbf48617d5a38c01e01 | [
"MIT"
] | null | null | null | sourcecode/src/vx/pgff/Access.py | Jarol0709/GFF | 2817ef97434c1e2c0c96cdbf48617d5a38c01e01 | [
"MIT"
] | 3 | 2021-02-22T17:30:19.000Z | 2021-08-03T03:19:29.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Ivar Vargas Belizario
# Copyright (c) 2020
# E-mail: ivar@usp.br
import tornado.ioloop
import tornado.web
import tornado.httpserver
import ujson
import bcrypt
from vx.pgff.Settings import *
from vx.pgff.BaseHandler import *
from vx.pgff.User import *
from vx.com.py.database.MongoDB import *
class Login(BaseHandler):
def get(self):
if Settings.MULIUSER==1:
self.render("login.html")
else:
self.redirect("./")
return
def post(self):
op = int(self.get_argument('option'))
re = User.login( self.get_argument('user'),
self.get_argument('password') );
if len(re)==1:
for r in re:
uid = str(r['_id'])
#uid = ""+uid+"".decode("utf-8")
self.set_secure_cookie("user", uid)
self.set_secure_cookie("email", r['email'])
#print("r['adminid']",r['adminid']);
self.set_secure_cookie("adminid", str(r['adminid']))
#self.set_secure_cookie("user", uid, expires_days=1)
#self.set_secure_cookie("email", r['email'], expires_days=1)
self.redirect("./")
return
else:
self.redirect("./login")
return
return
class Logout(BaseHandler):
def get(self):
self.clear_cookie('user')
self.clear_cookie('email')
self.redirect("./")
| 24.419355 | 76 | 0.548217 |
import tornado.ioloop
import tornado.web
import tornado.httpserver
import ujson
import bcrypt
from vx.pgff.Settings import *
from vx.pgff.BaseHandler import *
from vx.pgff.User import *
from vx.com.py.database.MongoDB import *
class Login(BaseHandler):
def get(self):
if Settings.MULIUSER==1:
self.render("login.html")
else:
self.redirect("./")
return
def post(self):
op = int(self.get_argument('option'))
re = User.login( self.get_argument('user'),
self.get_argument('password') );
if len(re)==1:
for r in re:
uid = str(r['_id'])
self.set_secure_cookie("user", uid)
self.set_secure_cookie("email", r['email'])
self.set_secure_cookie("adminid", str(r['adminid']))
self.redirect("./")
return
else:
self.redirect("./login")
return
return
class Logout(BaseHandler):
def get(self):
self.clear_cookie('user')
self.clear_cookie('email')
self.redirect("./")
| true | true |
1c2bb941a4ed9df0e80487cc0c96e709d64f5ad3 | 4,579 | py | Python | generator/interact_server.py | AbrahamSanders/SIMIE | 5c3ed41307627c11df3ce2297f5f5369b4b01b79 | [
"MIT"
] | 5 | 2021-02-10T03:43:10.000Z | 2021-06-15T18:02:26.000Z | generator/interact_server.py | AbrahamSanders/SIMIE | 5c3ed41307627c11df3ce2297f5f5369b4b01b79 | [
"MIT"
] | 4 | 2021-02-13T21:58:00.000Z | 2021-05-04T01:23:26.000Z | generator/interact_server.py | AbrahamSanders/SIMIE | 5c3ed41307627c11df3ce2297f5f5369b4b01b79 | [
"MIT"
] | null | null | null | from transformers import AutoModelForCausalLM, AutoTokenizer
from flask import Flask, abort, send_from_directory
from flask_restful import Resource, Api, reqparse
import argparse
import uuid
import numpy as np
import torch
from interact import generate
from identities import Identities
parser = argparse.ArgumentParser("Run the interaction server")
parser.add_argument("--modelpath", default="models/gpt2-xl-dialog-narrative", required=False,
help="Path to the Huggingface Transformers GPT-2 model to load. (default: %(default)s)")
parser.add_argument("--force-cpu", action="store_true", required=False,
help="Force the device to cpu even if a supported GPU is present.")
parser.add_argument("--prompt-narrative-prob", type=float, default=0.2, required=False,
help="Probability that the model will get prompted to generate narrative at each turn. (default: %(default)s)")
parser.add_argument("--max-input-tokens", type=int, default=350, required=False,
help="Maximum number of tokens to use as input. Dialog history gets trimmed from the back to accommodate this. (default: %(default)s)")
parser.add_argument("--print-raw", action="store_true", required=False,
help="Print the raw model input and output for debugging purposes.")
parser.add_argument("--speaker-tracking", action="store_true", required=False,
help="Enable speaker tracking through narrative prompts.")
parser.add_argument("--num-beams", type=int, default=6, required=False,
help="Number of beams to use for beam search generation.")
parser.add_argument("--show-beams", action="store_true", required=False,
help="Print all beams when using beam search generation.")
parser.add_argument("--port", "-p", default="8080", required=False, type=int, help="Port to run server on.")
args = parser.parse_args()
print()
print("Running with arguments:")
print(args)
print()
# load the model and tokenizer
tokenizer = AutoTokenizer.from_pretrained(args.modelpath)
model = AutoModelForCausalLM.from_pretrained(args.modelpath)
if args.force_cpu:
device = torch.device("cpu")
else:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
if device == "cuda":
model = model.half()
model.to(device)
model.eval()
identities = Identities()
narrative_token = tokenizer.additional_special_tokens[0]
sessions = {}
app = Flask(__name__)
api = Api(app)
class Session(Resource):
def post(self):
session_id = uuid.uuid4().hex
sessions[session_id] = []
return session_id
class Interaction(Resource):
def __init__(self):
self.reqparser = reqparse.RequestParser()
self.reqparser.add_argument("user_input", type=str, location="json", required=True)
self.reqparser.add_argument("session_id", type=str, location="json", required=True)
#batch_reqparser.add_argument("max_len", type=int, default=60, required=False)
#batch_reqparser.add_argument("num_beams", type=int, default=4, required=False)
#batch_reqparser.add_argument("temperature", type=float, default=1.0, required=False)
def post(self):
reqargs = self.reqparser.parse_args()
user_input = reqargs["user_input"]
session_id = reqargs["session_id"]
#max_len = reqargs["max_len"]
#num_beams = reqargs["num_beams"]
#temperature = reqargs["temperature"]
if session_id not in sessions:
abort(404)
return
dialog_history = sessions[session_id]
responses = []
if bool(np.random.binomial(1, args.prompt_narrative_prob)):
results = generate(args, model, device, tokenizer, dialog_history, identities, user_input, prompt_narrative=True)
else:
results = generate(args, model, device, tokenizer, dialog_history, identities, user_input)
responses.extend(results)
#If a narrative is generated, generate a follow-up dialog response.
if dialog_history[-1].startswith(narrative_token):
results = generate(args, model, device, tokenizer, dialog_history, identities, prompt_dialog=True)
responses.extend(results)
return responses
class UI(Resource):
def get(self):
return send_from_directory(".", "chat_ui.html")
api.add_resource(Session, "/session")
api.add_resource(Interaction, "/interaction")
api.add_resource(UI, "/chat_ui/")
app.run(debug=False, port=args.port, host="0.0.0.0") | 42.009174 | 155 | 0.694475 | from transformers import AutoModelForCausalLM, AutoTokenizer
from flask import Flask, abort, send_from_directory
from flask_restful import Resource, Api, reqparse
import argparse
import uuid
import numpy as np
import torch
from interact import generate
from identities import Identities
parser = argparse.ArgumentParser("Run the interaction server")
parser.add_argument("--modelpath", default="models/gpt2-xl-dialog-narrative", required=False,
help="Path to the Huggingface Transformers GPT-2 model to load. (default: %(default)s)")
parser.add_argument("--force-cpu", action="store_true", required=False,
help="Force the device to cpu even if a supported GPU is present.")
parser.add_argument("--prompt-narrative-prob", type=float, default=0.2, required=False,
help="Probability that the model will get prompted to generate narrative at each turn. (default: %(default)s)")
parser.add_argument("--max-input-tokens", type=int, default=350, required=False,
help="Maximum number of tokens to use as input. Dialog history gets trimmed from the back to accommodate this. (default: %(default)s)")
parser.add_argument("--print-raw", action="store_true", required=False,
help="Print the raw model input and output for debugging purposes.")
parser.add_argument("--speaker-tracking", action="store_true", required=False,
help="Enable speaker tracking through narrative prompts.")
parser.add_argument("--num-beams", type=int, default=6, required=False,
help="Number of beams to use for beam search generation.")
parser.add_argument("--show-beams", action="store_true", required=False,
help="Print all beams when using beam search generation.")
parser.add_argument("--port", "-p", default="8080", required=False, type=int, help="Port to run server on.")
args = parser.parse_args()
print()
print("Running with arguments:")
print(args)
print()
tokenizer = AutoTokenizer.from_pretrained(args.modelpath)
model = AutoModelForCausalLM.from_pretrained(args.modelpath)
if args.force_cpu:
device = torch.device("cpu")
else:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
if device == "cuda":
model = model.half()
model.to(device)
model.eval()
identities = Identities()
narrative_token = tokenizer.additional_special_tokens[0]
sessions = {}
app = Flask(__name__)
api = Api(app)
class Session(Resource):
def post(self):
session_id = uuid.uuid4().hex
sessions[session_id] = []
return session_id
class Interaction(Resource):
def __init__(self):
self.reqparser = reqparse.RequestParser()
self.reqparser.add_argument("user_input", type=str, location="json", required=True)
self.reqparser.add_argument("session_id", type=str, location="json", required=True)
def post(self):
reqargs = self.reqparser.parse_args()
user_input = reqargs["user_input"]
session_id = reqargs["session_id"]
if session_id not in sessions:
abort(404)
return
dialog_history = sessions[session_id]
responses = []
if bool(np.random.binomial(1, args.prompt_narrative_prob)):
results = generate(args, model, device, tokenizer, dialog_history, identities, user_input, prompt_narrative=True)
else:
results = generate(args, model, device, tokenizer, dialog_history, identities, user_input)
responses.extend(results)
if dialog_history[-1].startswith(narrative_token):
results = generate(args, model, device, tokenizer, dialog_history, identities, prompt_dialog=True)
responses.extend(results)
return responses
class UI(Resource):
def get(self):
return send_from_directory(".", "chat_ui.html")
api.add_resource(Session, "/session")
api.add_resource(Interaction, "/interaction")
api.add_resource(UI, "/chat_ui/")
app.run(debug=False, port=args.port, host="0.0.0.0") | true | true |
1c2bb9cd9c55edaa99b3d19fa83399689105d278 | 5,661 | py | Python | pypy/objspace/std/callmethod.py | nanjekyejoannah/pypy | e80079fe13c29eda7b2a6b4cd4557051f975a2d9 | [
"Apache-2.0",
"OpenSSL"
] | 381 | 2018-08-18T03:37:22.000Z | 2022-02-06T23:57:36.000Z | pypy/objspace/std/callmethod.py | nanjekyejoannah/pypy | e80079fe13c29eda7b2a6b4cd4557051f975a2d9 | [
"Apache-2.0",
"OpenSSL"
] | 16 | 2018-09-22T18:12:47.000Z | 2022-02-22T20:03:59.000Z | pypy/objspace/std/callmethod.py | nanjekyejoannah/pypy | e80079fe13c29eda7b2a6b4cd4557051f975a2d9 | [
"Apache-2.0",
"OpenSSL"
] | 55 | 2015-08-16T02:41:30.000Z | 2022-03-20T20:33:35.000Z | """
Two bytecodes to speed up method calls. Here is how a method call looks
like: (on the left, without the new bytecodes; on the right, with them)
<push self> <push self>
LOAD_ATTR name LOOKUP_METHOD name
<push arg 0> <push arg 0>
... ...
<push arg n-1> <push arg n-1>
CALL_FUNCTION n CALL_METHOD n
"""
from pypy.interpreter import function
from rpython.rlib import jit
from pypy.objspace.std.mapdict import LOOKUP_METHOD_mapdict, \
LOOKUP_METHOD_mapdict_fill_cache_method
# This module exports two extra methods for StdObjSpaceFrame implementing
# the LOOKUP_METHOD and CALL_METHOD opcodes in an efficient way, as well
# as a version of space.call_method() that uses the same approach.
# See pypy.objspace.std.objspace for where these functions are used from.
def LOOKUP_METHOD(f, nameindex, *ignored):
from pypy.objspace.std.typeobject import MutableCell
# stack before after
# -------------- --fast-method----fallback-case------------
#
# w_object None
# w_object => w_function w_boundmethod_or_whatever
# (more stuff) (more stuff) (more stuff)
#
space = f.space
w_obj = f.popvalue()
if not jit.we_are_jitted():
# mapdict has an extra-fast version of this function
if LOOKUP_METHOD_mapdict(f, nameindex, w_obj):
return
w_name = f.getname_w(nameindex)
w_value = None
w_type = space.type(w_obj)
if w_type.has_object_getattribute():
name = space.text_w(w_name)
# bit of a mess to use these internal functions, but it allows the
# mapdict caching below to work without an additional lookup
version_tag = w_type.version_tag()
if version_tag is None:
_, w_descr = w_type._lookup_where(name)
w_descr_cell = None
else:
_, w_descr_cell = w_type._pure_lookup_where_with_method_cache(
name, version_tag)
w_descr = w_descr_cell
if isinstance(w_descr, MutableCell):
w_descr = w_descr.unwrap_cell(space)
if w_descr is None:
# this handles directly the common case
# module.function(args..)
w_value = w_obj.getdictvalue(space, name)
# xxx we could also use the mapdict cache in that case, probably
else:
typ = type(w_descr)
if typ is function.Function or typ is function.FunctionWithFixedCode:
w_value = w_obj.getdictvalue(space, name)
if w_value is None:
# fast method path: a function object in the class,
# nothing in the instance
f.pushvalue(w_descr)
f.pushvalue(w_obj)
if not jit.we_are_jitted():
# let mapdict cache stuff
LOOKUP_METHOD_mapdict_fill_cache_method(
space, f.getcode(), name, nameindex, w_obj, w_type,
w_descr_cell)
return
if w_value is None:
w_value = space.getattr(w_obj, w_name)
f.pushvalue(w_value)
f.pushvalue_none()
@jit.unroll_safe
def CALL_METHOD(f, oparg, *ignored):
# opargs contains the arg, and kwarg count, excluding the implicit 'self'
n_args = oparg & 0xff
n_kwargs = (oparg >> 8) & 0xff
w_self = f.peekvalue_maybe_none(n_args + (2 * n_kwargs))
n = n_args + (w_self is not None)
if not n_kwargs:
w_callable = f.peekvalue(n_args + (2 * n_kwargs) + 1)
try:
w_result = f.space.call_valuestack(
w_callable, n, f, methodcall=w_self is not None)
finally:
f.dropvalues(n_args + 2)
else:
keywords = [None] * n_kwargs
keywords_w = [None] * n_kwargs
while True:
n_kwargs -= 1
if n_kwargs < 0:
break
w_value = f.popvalue()
w_key = f.popvalue()
key = f.space.text_w(w_key)
keywords[n_kwargs] = key
keywords_w[n_kwargs] = w_value
arguments = f.popvalues(n) # includes w_self if it is not None
args = f.argument_factory(
arguments, keywords, keywords_w, None, None,
methodcall=w_self is not None)
if w_self is None:
f.popvalue_maybe_none() # removes w_self, which is None
w_callable = f.popvalue()
if f.get_is_being_profiled() and function.is_builtin_code(w_callable):
w_result = f.space.call_args_and_c_profile(f, w_callable, args)
else:
w_result = f.space.call_args(w_callable, args)
f.pushvalue(w_result)
def call_method_opt(space, w_obj, methname, *arg_w):
"""An optimized version of space.call_method()
based on the same principle as above.
"""
w_type = space.type(w_obj)
if w_type.has_object_getattribute():
w_descr = space.lookup(w_obj, methname)
typ = type(w_descr)
if typ is function.Function or typ is function.FunctionWithFixedCode:
w_value = w_obj.getdictvalue(space, methname)
if w_value is None:
# fast method path: a function object in the class,
# nothing in the instance
return space.call_function(w_descr, w_obj, *arg_w)
w_name = space.newtext(methname)
w_meth = space.getattr(w_obj, w_name)
return space.call_function(w_meth, *arg_w)
| 39.3125 | 81 | 0.592122 |
from pypy.interpreter import function
from rpython.rlib import jit
from pypy.objspace.std.mapdict import LOOKUP_METHOD_mapdict, \
LOOKUP_METHOD_mapdict_fill_cache_method
def LOOKUP_METHOD(f, nameindex, *ignored):
from pypy.objspace.std.typeobject import MutableCell
space = f.space
w_obj = f.popvalue()
if not jit.we_are_jitted():
if LOOKUP_METHOD_mapdict(f, nameindex, w_obj):
return
w_name = f.getname_w(nameindex)
w_value = None
w_type = space.type(w_obj)
if w_type.has_object_getattribute():
name = space.text_w(w_name)
version_tag = w_type.version_tag()
if version_tag is None:
_, w_descr = w_type._lookup_where(name)
w_descr_cell = None
else:
_, w_descr_cell = w_type._pure_lookup_where_with_method_cache(
name, version_tag)
w_descr = w_descr_cell
if isinstance(w_descr, MutableCell):
w_descr = w_descr.unwrap_cell(space)
if w_descr is None:
w_value = w_obj.getdictvalue(space, name)
else:
typ = type(w_descr)
if typ is function.Function or typ is function.FunctionWithFixedCode:
w_value = w_obj.getdictvalue(space, name)
if w_value is None:
f.pushvalue(w_descr)
f.pushvalue(w_obj)
if not jit.we_are_jitted():
LOOKUP_METHOD_mapdict_fill_cache_method(
space, f.getcode(), name, nameindex, w_obj, w_type,
w_descr_cell)
return
if w_value is None:
w_value = space.getattr(w_obj, w_name)
f.pushvalue(w_value)
f.pushvalue_none()
@jit.unroll_safe
def CALL_METHOD(f, oparg, *ignored):
n_args = oparg & 0xff
n_kwargs = (oparg >> 8) & 0xff
w_self = f.peekvalue_maybe_none(n_args + (2 * n_kwargs))
n = n_args + (w_self is not None)
if not n_kwargs:
w_callable = f.peekvalue(n_args + (2 * n_kwargs) + 1)
try:
w_result = f.space.call_valuestack(
w_callable, n, f, methodcall=w_self is not None)
finally:
f.dropvalues(n_args + 2)
else:
keywords = [None] * n_kwargs
keywords_w = [None] * n_kwargs
while True:
n_kwargs -= 1
if n_kwargs < 0:
break
w_value = f.popvalue()
w_key = f.popvalue()
key = f.space.text_w(w_key)
keywords[n_kwargs] = key
keywords_w[n_kwargs] = w_value
arguments = f.popvalues(n)
args = f.argument_factory(
arguments, keywords, keywords_w, None, None,
methodcall=w_self is not None)
if w_self is None:
f.popvalue_maybe_none()
w_callable = f.popvalue()
if f.get_is_being_profiled() and function.is_builtin_code(w_callable):
w_result = f.space.call_args_and_c_profile(f, w_callable, args)
else:
w_result = f.space.call_args(w_callable, args)
f.pushvalue(w_result)
def call_method_opt(space, w_obj, methname, *arg_w):
w_type = space.type(w_obj)
if w_type.has_object_getattribute():
w_descr = space.lookup(w_obj, methname)
typ = type(w_descr)
if typ is function.Function or typ is function.FunctionWithFixedCode:
w_value = w_obj.getdictvalue(space, methname)
if w_value is None:
return space.call_function(w_descr, w_obj, *arg_w)
w_name = space.newtext(methname)
w_meth = space.getattr(w_obj, w_name)
return space.call_function(w_meth, *arg_w)
| true | true |
1c2bbc46fb79ba1730324fa391dfec2a9e71fecd | 540 | py | Python | manage.py | heolin123/funcrowd | 20167783de208394c09ed0429a5f02ec6dd79c42 | [
"MIT"
] | null | null | null | manage.py | heolin123/funcrowd | 20167783de208394c09ed0429a5f02ec6dd79c42 | [
"MIT"
] | 11 | 2019-11-12T23:26:45.000Z | 2021-06-10T17:37:23.000Z | manage.py | heolin123/funcrowd | 20167783de208394c09ed0429a5f02ec6dd79c42 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "funcrowd.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
| 33.75 | 73 | 0.687037 |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "funcrowd.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
| true | true |
1c2bbd9182ee7fdf9900b481d7b484a821b2ea31 | 10,016 | py | Python | app/main/routes.py | ktroach/cmp-1 | df3bc2d22532fe61173353b41709347f066a7ad5 | [
"MIT"
] | null | null | null | app/main/routes.py | ktroach/cmp-1 | df3bc2d22532fe61173353b41709347f066a7ad5 | [
"MIT"
] | null | null | null | app/main/routes.py | ktroach/cmp-1 | df3bc2d22532fe61173353b41709347f066a7ad5 | [
"MIT"
] | null | null | null | from datetime import datetime
from flask import render_template, flash, redirect, url_for, request, g, \
jsonify, current_app
from flask_login import current_user, login_required
from flask_babel import _, get_locale
from guess_language import guess_language
from app import db
from app.main.forms import EditProfileForm, PostForm, SearchForm, MessageForm, NewApplicantForm
from app.models import User, Post, Message, Notification, ApplicantForm
from app.translate import translate
from app.main import bp
import logging
logging.basicConfig(filename='./logs/routes.log',level=logging.DEBUG)
# @bp.route('/new_applicant', methods=['GET', 'POST'])
# def new_applicant_personal_info():
# form = NewApplicantForm_Personal_Info()
# if form.validate_on_submit():
# applicant_form = ApplicantForm(
# first_name=form.first_name.data,
# last_name=form.last_name.data,
# email=form.email.data
# )
# # db.session.add(applicant_form)
# # db.session.commit()
# # flash(_('Your changes have been saved.'))
# return redirect(url_for('main.index'))
# return render_template('new_applicant.html', title=_('New Applicant'),
# form=form)
@bp.route('/new_applicant', methods=['GET', 'POST'])
def new_applicant():
form = NewApplicantForm()
if form.validate_on_submit():
new_applicant_form = ApplicantForm(
first_name=form.first_name.data,
last_name=form.last_name.data,
email=form.email.data
)
db.session.add(new_applicant_form)
db.session.commit()
flash(_('Your changes have been saved.'))
logging.debug('new_applicant >>> new_applicant_form.id: %s', new_applicant_form.id)
return redirect(url_for('main.index', new_applicant_id=new_applicant_form.id))
return render_template('new_applicant.html', title=_('New Applicant'), form=form)
@bp.before_app_request
def before_request():
if current_user.is_authenticated:
current_user.last_seen = datetime.utcnow()
db.session.commit()
g.search_form = SearchForm()
g.locale = str(get_locale())
@bp.route('/', methods=['GET', 'POST'])
@bp.route('/index', methods=['GET', 'POST'])
@login_required
def index():
new_applicant_id = request.args.get('new_applicant_id', 1, type=int)
logging.debug('main.index >>> new_applicant_id: %s', new_applicant_id)
form = PostForm()
if form.validate_on_submit():
language = guess_language(form.post.data)
if language == 'UNKNOWN' or len(language) > 5:
language = ''
post = Post(body=form.post.data, author=current_user,
language=language)
db.session.add(post)
db.session.commit()
flash(_('Your post is now live!'))
return redirect(url_for('main.index'))
page = request.args.get('page', 1, type=int)
posts = current_user.followed_posts().paginate(
page, current_app.config['POSTS_PER_PAGE'], False)
next_url = url_for('main.index', page=posts.next_num) \
if posts.has_next else None
prev_url = url_for('main.index', page=posts.prev_num) \
if posts.has_prev else None
return render_template('index.html', title=_('Home'), form=form,
posts=posts.items, next_url=next_url,
prev_url=prev_url)
@bp.route('/explore')
@login_required
def explore():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(Post.timestamp.desc()).paginate(
page, current_app.config['POSTS_PER_PAGE'], False)
next_url = url_for('main.explore', page=posts.next_num) \
if posts.has_next else None
prev_url = url_for('main.explore', page=posts.prev_num) \
if posts.has_prev else None
return render_template('index.html', title=_('Explore'),
posts=posts.items, next_url=next_url,
prev_url=prev_url)
@bp.route('/user/<username>')
@login_required
def user(username):
user = User.query.filter_by(username=username).first_or_404()
page = request.args.get('page', 1, type=int)
posts = user.posts.order_by(Post.timestamp.desc()).paginate(
page, current_app.config['POSTS_PER_PAGE'], False)
next_url = url_for('main.user', username=user.username,
page=posts.next_num) if posts.has_next else None
prev_url = url_for('main.user', username=user.username,
page=posts.prev_num) if posts.has_prev else None
return render_template('user.html', user=user, posts=posts.items,
next_url=next_url, prev_url=prev_url)
@bp.route('/user/<username>/popup')
@login_required
def user_popup(username):
user = User.query.filter_by(username=username).first_or_404()
return render_template('user_popup.html', user=user)
@bp.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
form = EditProfileForm(current_user.username)
if form.validate_on_submit():
current_user.username = form.username.data
current_user.about_me = form.about_me.data
db.session.commit()
flash(_('Your changes have been saved.'))
return redirect(url_for('main.edit_profile'))
elif request.method == 'GET':
form.username.data = current_user.username
form.about_me.data = current_user.about_me
return render_template('edit_profile.html', title=_('Edit Profile'),
form=form)
@bp.route('/follow/<username>')
@login_required
def follow(username):
user = User.query.filter_by(username=username).first()
if user is None:
flash(_('User %(username)s not found.', username=username))
return redirect(url_for('main.index'))
if user == current_user:
flash(_('You cannot follow yourself!'))
return redirect(url_for('main.user', username=username))
current_user.follow(user)
db.session.commit()
flash(_('You are following %(username)s!', username=username))
return redirect(url_for('main.user', username=username))
@bp.route('/unfollow/<username>')
@login_required
def unfollow(username):
user = User.query.filter_by(username=username).first()
if user is None:
flash(_('User %(username)s not found.', username=username))
return redirect(url_for('main.index'))
if user == current_user:
flash(_('You cannot unfollow yourself!'))
return redirect(url_for('main.user', username=username))
current_user.unfollow(user)
db.session.commit()
flash(_('You are not following %(username)s.', username=username))
return redirect(url_for('main.user', username=username))
@bp.route('/translate', methods=['POST'])
@login_required
def translate_text():
return jsonify({'text': translate(request.form['text'],
request.form['source_language'],
request.form['dest_language'])})
@bp.route('/search')
@login_required
def search():
if not g.search_form.validate():
return redirect(url_for('main.explore'))
page = request.args.get('page', 1, type=int)
posts, total = Post.search(g.search_form.q.data, page,
current_app.config['POSTS_PER_PAGE'])
next_url = url_for('main.search', q=g.search_form.q.data, page=page + 1) \
if total > page * current_app.config['POSTS_PER_PAGE'] else None
prev_url = url_for('main.search', q=g.search_form.q.data, page=page - 1) \
if page > 1 else None
return render_template('search.html', title=_('Search'), posts=posts,
next_url=next_url, prev_url=prev_url)
@bp.route('/send_message/<recipient>', methods=['GET', 'POST'])
@login_required
def send_message(recipient):
user = User.query.filter_by(username=recipient).first_or_404()
form = MessageForm()
if form.validate_on_submit():
msg = Message(author=current_user, recipient=user,
body=form.message.data)
db.session.add(msg)
user.add_notification('unread_message_count', user.new_messages())
db.session.commit()
flash(_('Your message has been sent.'))
return redirect(url_for('main.user', username=recipient))
return render_template('send_message.html', title=_('Send Message'),
form=form, recipient=recipient)
@bp.route('/messages')
@login_required
def messages():
current_user.last_message_read_time = datetime.utcnow()
current_user.add_notification('unread_message_count', 0)
db.session.commit()
page = request.args.get('page', 1, type=int)
messages = current_user.messages_received.order_by(
Message.timestamp.desc()).paginate(
page, current_app.config['POSTS_PER_PAGE'], False)
next_url = url_for('main.messages', page=messages.next_num) \
if messages.has_next else None
prev_url = url_for('main.messages', page=messages.prev_num) \
if messages.has_prev else None
return render_template('messages.html', messages=messages.items,
next_url=next_url, prev_url=prev_url)
@bp.route('/export_posts')
@login_required
def export_posts():
if current_user.get_task_in_progress('export_posts'):
flash(_('An export task is currently in progress'))
else:
current_user.launch_task('export_posts', _('Exporting posts...'))
db.session.commit()
return redirect(url_for('main.user', username=current_user.username))
@bp.route('/notifications')
@login_required
def notifications():
since = request.args.get('since', 0.0, type=float)
notifications = current_user.notifications.filter(
Notification.timestamp > since).order_by(Notification.timestamp.asc())
return jsonify([{
'name': n.name,
'data': n.get_data(),
'timestamp': n.timestamp
} for n in notifications])
| 39.125 | 95 | 0.660843 | from datetime import datetime
from flask import render_template, flash, redirect, url_for, request, g, \
jsonify, current_app
from flask_login import current_user, login_required
from flask_babel import _, get_locale
from guess_language import guess_language
from app import db
from app.main.forms import EditProfileForm, PostForm, SearchForm, MessageForm, NewApplicantForm
from app.models import User, Post, Message, Notification, ApplicantForm
from app.translate import translate
from app.main import bp
import logging
logging.basicConfig(filename='./logs/routes.log',level=logging.DEBUG)
pplicantForm()
if form.validate_on_submit():
new_applicant_form = ApplicantForm(
first_name=form.first_name.data,
last_name=form.last_name.data,
email=form.email.data
)
db.session.add(new_applicant_form)
db.session.commit()
flash(_('Your changes have been saved.'))
logging.debug('new_applicant >>> new_applicant_form.id: %s', new_applicant_form.id)
return redirect(url_for('main.index', new_applicant_id=new_applicant_form.id))
return render_template('new_applicant.html', title=_('New Applicant'), form=form)
@bp.before_app_request
def before_request():
if current_user.is_authenticated:
current_user.last_seen = datetime.utcnow()
db.session.commit()
g.search_form = SearchForm()
g.locale = str(get_locale())
@bp.route('/', methods=['GET', 'POST'])
@bp.route('/index', methods=['GET', 'POST'])
@login_required
def index():
new_applicant_id = request.args.get('new_applicant_id', 1, type=int)
logging.debug('main.index >>> new_applicant_id: %s', new_applicant_id)
form = PostForm()
if form.validate_on_submit():
language = guess_language(form.post.data)
if language == 'UNKNOWN' or len(language) > 5:
language = ''
post = Post(body=form.post.data, author=current_user,
language=language)
db.session.add(post)
db.session.commit()
flash(_('Your post is now live!'))
return redirect(url_for('main.index'))
page = request.args.get('page', 1, type=int)
posts = current_user.followed_posts().paginate(
page, current_app.config['POSTS_PER_PAGE'], False)
next_url = url_for('main.index', page=posts.next_num) \
if posts.has_next else None
prev_url = url_for('main.index', page=posts.prev_num) \
if posts.has_prev else None
return render_template('index.html', title=_('Home'), form=form,
posts=posts.items, next_url=next_url,
prev_url=prev_url)
@bp.route('/explore')
@login_required
def explore():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(Post.timestamp.desc()).paginate(
page, current_app.config['POSTS_PER_PAGE'], False)
next_url = url_for('main.explore', page=posts.next_num) \
if posts.has_next else None
prev_url = url_for('main.explore', page=posts.prev_num) \
if posts.has_prev else None
return render_template('index.html', title=_('Explore'),
posts=posts.items, next_url=next_url,
prev_url=prev_url)
@bp.route('/user/<username>')
@login_required
def user(username):
user = User.query.filter_by(username=username).first_or_404()
page = request.args.get('page', 1, type=int)
posts = user.posts.order_by(Post.timestamp.desc()).paginate(
page, current_app.config['POSTS_PER_PAGE'], False)
next_url = url_for('main.user', username=user.username,
page=posts.next_num) if posts.has_next else None
prev_url = url_for('main.user', username=user.username,
page=posts.prev_num) if posts.has_prev else None
return render_template('user.html', user=user, posts=posts.items,
next_url=next_url, prev_url=prev_url)
@bp.route('/user/<username>/popup')
@login_required
def user_popup(username):
user = User.query.filter_by(username=username).first_or_404()
return render_template('user_popup.html', user=user)
@bp.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
form = EditProfileForm(current_user.username)
if form.validate_on_submit():
current_user.username = form.username.data
current_user.about_me = form.about_me.data
db.session.commit()
flash(_('Your changes have been saved.'))
return redirect(url_for('main.edit_profile'))
elif request.method == 'GET':
form.username.data = current_user.username
form.about_me.data = current_user.about_me
return render_template('edit_profile.html', title=_('Edit Profile'),
form=form)
@bp.route('/follow/<username>')
@login_required
def follow(username):
user = User.query.filter_by(username=username).first()
if user is None:
flash(_('User %(username)s not found.', username=username))
return redirect(url_for('main.index'))
if user == current_user:
flash(_('You cannot follow yourself!'))
return redirect(url_for('main.user', username=username))
current_user.follow(user)
db.session.commit()
flash(_('You are following %(username)s!', username=username))
return redirect(url_for('main.user', username=username))
@bp.route('/unfollow/<username>')
@login_required
def unfollow(username):
user = User.query.filter_by(username=username).first()
if user is None:
flash(_('User %(username)s not found.', username=username))
return redirect(url_for('main.index'))
if user == current_user:
flash(_('You cannot unfollow yourself!'))
return redirect(url_for('main.user', username=username))
current_user.unfollow(user)
db.session.commit()
flash(_('You are not following %(username)s.', username=username))
return redirect(url_for('main.user', username=username))
@bp.route('/translate', methods=['POST'])
@login_required
def translate_text():
return jsonify({'text': translate(request.form['text'],
request.form['source_language'],
request.form['dest_language'])})
@bp.route('/search')
@login_required
def search():
if not g.search_form.validate():
return redirect(url_for('main.explore'))
page = request.args.get('page', 1, type=int)
posts, total = Post.search(g.search_form.q.data, page,
current_app.config['POSTS_PER_PAGE'])
next_url = url_for('main.search', q=g.search_form.q.data, page=page + 1) \
if total > page * current_app.config['POSTS_PER_PAGE'] else None
prev_url = url_for('main.search', q=g.search_form.q.data, page=page - 1) \
if page > 1 else None
return render_template('search.html', title=_('Search'), posts=posts,
next_url=next_url, prev_url=prev_url)
@bp.route('/send_message/<recipient>', methods=['GET', 'POST'])
@login_required
def send_message(recipient):
user = User.query.filter_by(username=recipient).first_or_404()
form = MessageForm()
if form.validate_on_submit():
msg = Message(author=current_user, recipient=user,
body=form.message.data)
db.session.add(msg)
user.add_notification('unread_message_count', user.new_messages())
db.session.commit()
flash(_('Your message has been sent.'))
return redirect(url_for('main.user', username=recipient))
return render_template('send_message.html', title=_('Send Message'),
form=form, recipient=recipient)
@bp.route('/messages')
@login_required
def messages():
current_user.last_message_read_time = datetime.utcnow()
current_user.add_notification('unread_message_count', 0)
db.session.commit()
page = request.args.get('page', 1, type=int)
messages = current_user.messages_received.order_by(
Message.timestamp.desc()).paginate(
page, current_app.config['POSTS_PER_PAGE'], False)
next_url = url_for('main.messages', page=messages.next_num) \
if messages.has_next else None
prev_url = url_for('main.messages', page=messages.prev_num) \
if messages.has_prev else None
return render_template('messages.html', messages=messages.items,
next_url=next_url, prev_url=prev_url)
@bp.route('/export_posts')
@login_required
def export_posts():
if current_user.get_task_in_progress('export_posts'):
flash(_('An export task is currently in progress'))
else:
current_user.launch_task('export_posts', _('Exporting posts...'))
db.session.commit()
return redirect(url_for('main.user', username=current_user.username))
@bp.route('/notifications')
@login_required
def notifications():
since = request.args.get('since', 0.0, type=float)
notifications = current_user.notifications.filter(
Notification.timestamp > since).order_by(Notification.timestamp.asc())
return jsonify([{
'name': n.name,
'data': n.get_data(),
'timestamp': n.timestamp
} for n in notifications])
| true | true |
1c2bbfca17c2a5d7769a1f7e84a006cad6f8c519 | 9,393 | py | Python | dj_rql/drf/compat.py | maxipavlovic/django-rql | 53ece0cb44759310cc144193229bc0d9f16be831 | [
"Apache-2.0"
] | null | null | null | dj_rql/drf/compat.py | maxipavlovic/django-rql | 53ece0cb44759310cc144193229bc0d9f16be831 | [
"Apache-2.0"
] | null | null | null | dj_rql/drf/compat.py | maxipavlovic/django-rql | 53ece0cb44759310cc144193229bc0d9f16be831 | [
"Apache-2.0"
] | 1 | 2021-12-07T13:30:52.000Z | 2021-12-07T13:30:52.000Z | #
# Copyright © 2021 Ingram Micro Inc. All rights reserved.
#
from collections import Counter
from dj_rql.constants import (
ComparisonOperators as CO,
DjangoLookups as DJL,
FilterTypes,
RQL_ANY_SYMBOL,
RQL_FALSE,
RQL_LIMIT_PARAM,
RQL_NULL,
RQL_OFFSET_PARAM,
RQL_ORDERING_OPERATOR,
RQL_TRUE,
SearchOperators as SO,
)
from dj_rql.drf._utils import get_query
from dj_rql.drf.backend import RQLFilterBackend
from dj_rql.exceptions import RQLFilterParsingError
class CompatibilityRQLFilterBackend(RQLFilterBackend):
"""
If there is necessity to apply RQL filters to a production API, which was working on other
filter backend (without raising API version number or losing compatibility), this base
compatibility DRF backend must be inherited from.
"""
@classmethod
def get_query(cls, filter_instance, request, view):
try:
query_string = cls.modify_initial_query(filter_instance, request, get_query(request))
if not cls.is_old_syntax(filter_instance, request, query_string):
return query_string
else:
return cls.get_rql_query(filter_instance, request, query_string)
except Exception:
raise RQLFilterParsingError()
@classmethod
def modify_initial_query(cls, filter_instance, request, query_string):
return query_string
@classmethod
def is_old_syntax(cls, filter_instance, request, query_string):
raise NotImplementedError
@classmethod
def get_rql_query(cls, filter_instance, request, query_string):
raise NotImplementedError
class DjangoFiltersRQLFilterBackend(CompatibilityRQLFilterBackend):
"""
DRF Backend, that automatically converts Django Filter specific queries to correct RQL queries.
IMPORTANT NOTES:
* `;` separation is context-based;
* MultipleChoiceFilter works by OR logic in RQL.
Currently NOT SUPPORTED:
* range fields and filters;
* regex and iregex conversion;
* OrderingFilter;
* ?&& syntax in queries;
* etc.
"""
RESERVED_ORDERING_WORDS = {'order_by', 'ordering'}
_POSSIBLE_DF_LOOKUPS = DJL.all()
_RQL_COMPARISON_OPERATORS = {CO.EQ, CO.NE, CO.LE, CO.GE, CO.LT, CO.GT}
_IMPOSSIBLE_PROP_SYMBOLS = {'(', ',', ')', ' ', "'", '"'}
@classmethod
def is_old_syntax(cls, filter_instance, request, query_string):
if not query_string.strip():
return False
if query_string[-1] == '&':
return True
qp_all_filters = set()
qp_old_filters = set()
query_params = request.query_params
for filter_name in query_params.keys():
result = cls._filter_has_old_syntax(filter_name, query_params)
if result is not None:
return result
qp_all_filters.add(filter_name)
if cls._is_old_style_filter(filter_name):
lookup = cls._get_filter_and_lookup(filter_name)[-1]
if lookup in (DJL.REGEX, DJL.I_REGEX):
cls._conversion_error()
qp_old_filters.add(filter_name)
if not qp_all_filters.isdisjoint(cls.RESERVED_ORDERING_WORDS):
return True
if not qp_old_filters:
return False
if not qp_old_filters - cls._get_filters_similar_to_old_syntax(filter_instance):
return False
return True
@classmethod
def _filter_has_old_syntax(cls, filter_name, query_params):
has_select = not cls._is_select_in_filter(filter_name)
if has_select and (not set(Counter(filter_name)).isdisjoint(cls._IMPOSSIBLE_PROP_SYMBOLS)):
return False
return cls._filter_value_has_old_syntax(filter_name, query_params, has_select)
@classmethod
def _filter_value_has_old_syntax(cls, filter_name, query_params, has_select):
for v in query_params.getlist(filter_name):
if has_select and not v:
return True
if v in ('True', 'False'):
return True
is_old = cls._filter_value_has_old_syntax_by_special_chars(v)
if is_old is not None:
return is_old
@classmethod
def _filter_value_has_old_syntax_by_special_chars(cls, value):
vc = Counter(value)
no_quotes = not (vc.get('"', 0) > 1 or vc.get("'", 0) > 1)
if vc.get(' ') and no_quotes:
return True
number_of_eqs = vc.get('=', 0)
if number_of_eqs >= 1 and vc.get('(', 0) == 0 and vc.get(';'):
return True
if number_of_eqs and no_quotes:
return False
if len(value) > 2 and value[2] == '=' and value[:2] in cls._RQL_COMPARISON_OPERATORS:
return False
@classmethod
def get_rql_query(cls, filter_instance, request, query_string):
filter_value_pairs = []
for filter_name in request.query_params.keys():
if cls._is_select_in_filter(filter_name):
filter_value_pairs.append(filter_name)
continue
one_filter_value_pairs = []
for value in request.query_params.getlist(filter_name):
name_value_pair = cls._get_one_filter_value_pair(
filter_instance, filter_name, value,
)
if name_value_pair is not None:
one_filter_value_pairs.append(name_value_pair)
if one_filter_value_pairs:
filter_value_pairs.append('&'.join(one_filter_value_pairs))
return '&'.join(filter_value_pairs) if filter_value_pairs else ''
@classmethod
def _get_one_filter_value_pair(cls, filter_instance, filter_name, value):
if not value:
return
if filter_name in (RQL_LIMIT_PARAM, RQL_OFFSET_PARAM):
return '{0}={1}'.format(filter_name, value)
if filter_name in cls.RESERVED_ORDERING_WORDS:
return '{0}({1})'.format(RQL_ORDERING_OPERATOR, value)
f_item = filter_instance.get_filter_base_item(filter_name)
is_nc_item = f_item and (not f_item.get('custom', False))
if is_nc_item and FilterTypes.field_filter_type(f_item['field']) == FilterTypes.BOOLEAN:
value = cls._convert_bool_value(value)
if not cls._is_old_style_filter(filter_name):
return '{0}={1}'.format(filter_name, cls._add_quotes_to_value(value))
return cls._convert_filter_to_rql(filter_name, value)
@staticmethod
def _is_select_in_filter(filter_name):
return 'select(' in filter_name
@classmethod
def _convert_filter_to_rql(cls, filter_name, value):
filter_base, lookup = cls._get_filter_and_lookup(filter_name)
if lookup == DJL.IN:
return 'in({0},({1}))'.format(
filter_base, ','.join(cls._add_quotes_to_value(v) for v in value.split(',') if v),
)
if lookup == DJL.NULL:
operator = CO.EQ if cls._convert_bool_value(value) == 'true' else CO.NE
return '{0}={1}={2}'.format(filter_base, operator, RQL_NULL)
if lookup in (DJL.GT, DJL.GTE, DJL.LT, DJL.LTE):
if lookup == DJL.GTE:
operator = CO.GE
elif lookup == DJL.LTE:
operator = CO.LE
else:
operator = lookup
return '{0}={1}={2}'.format(filter_base, operator, value)
operator = SO.I_LIKE if lookup[0] == 'i' else SO.LIKE
lookups = (DJL.CONTAINS, DJL.I_CONTAINS, DJL.ENDSWITH, DJL.I_ENDSWITH)
if lookup in lookups and value[0] != RQL_ANY_SYMBOL:
value = RQL_ANY_SYMBOL + value
lookups = (DJL.CONTAINS, DJL.I_CONTAINS, DJL.STARTSWITH, DJL.I_STARTSWITH)
if lookup in lookups and value[-1] != RQL_ANY_SYMBOL:
value += RQL_ANY_SYMBOL
return '{0}({1},{2})'.format(operator, filter_base, cls._add_quotes_to_value(value))
@classmethod
def _convert_bool_value(cls, value):
if value in ('True', 'true', '1'):
return RQL_TRUE
elif value in ('False', 'false', '0'):
return RQL_FALSE
cls._conversion_error()
@classmethod
def _add_quotes_to_value(cls, value):
for quote in ('"', "'"):
if quote not in value:
return '{q}{0}{q}'.format(value, q=quote)
cls._conversion_error()
@staticmethod
def _conversion_error():
raise RQLFilterParsingError()
@classmethod
def _get_filters_similar_to_old_syntax(cls, filter_instance):
old_syntax_filters = getattr(filter_instance, 'old_syntax_filters', None)
if old_syntax_filters:
return old_syntax_filters
similar_to_old_syntax_filters = set()
for filter_name in filter_instance.filters.keys():
if cls._is_old_style_filter(filter_name):
similar_to_old_syntax_filters.add(filter_name)
filter_instance.old_syntax_filters = similar_to_old_syntax_filters
return similar_to_old_syntax_filters
@classmethod
def _is_old_style_filter(cls, filter_name):
return cls._get_filter_and_lookup(filter_name)[-1] in cls._POSSIBLE_DF_LOOKUPS
@classmethod
def _get_filter_and_lookup(cls, filter_name):
return filter_name.rsplit('__', 1)
| 34.156364 | 99 | 0.6425 |
from collections import Counter
from dj_rql.constants import (
ComparisonOperators as CO,
DjangoLookups as DJL,
FilterTypes,
RQL_ANY_SYMBOL,
RQL_FALSE,
RQL_LIMIT_PARAM,
RQL_NULL,
RQL_OFFSET_PARAM,
RQL_ORDERING_OPERATOR,
RQL_TRUE,
SearchOperators as SO,
)
from dj_rql.drf._utils import get_query
from dj_rql.drf.backend import RQLFilterBackend
from dj_rql.exceptions import RQLFilterParsingError
class CompatibilityRQLFilterBackend(RQLFilterBackend):
@classmethod
def get_query(cls, filter_instance, request, view):
try:
query_string = cls.modify_initial_query(filter_instance, request, get_query(request))
if not cls.is_old_syntax(filter_instance, request, query_string):
return query_string
else:
return cls.get_rql_query(filter_instance, request, query_string)
except Exception:
raise RQLFilterParsingError()
@classmethod
def modify_initial_query(cls, filter_instance, request, query_string):
return query_string
@classmethod
def is_old_syntax(cls, filter_instance, request, query_string):
raise NotImplementedError
@classmethod
def get_rql_query(cls, filter_instance, request, query_string):
raise NotImplementedError
class DjangoFiltersRQLFilterBackend(CompatibilityRQLFilterBackend):
RESERVED_ORDERING_WORDS = {'order_by', 'ordering'}
_POSSIBLE_DF_LOOKUPS = DJL.all()
_RQL_COMPARISON_OPERATORS = {CO.EQ, CO.NE, CO.LE, CO.GE, CO.LT, CO.GT}
_IMPOSSIBLE_PROP_SYMBOLS = {'(', ',', ')', ' ', "'", '"'}
@classmethod
def is_old_syntax(cls, filter_instance, request, query_string):
if not query_string.strip():
return False
if query_string[-1] == '&':
return True
qp_all_filters = set()
qp_old_filters = set()
query_params = request.query_params
for filter_name in query_params.keys():
result = cls._filter_has_old_syntax(filter_name, query_params)
if result is not None:
return result
qp_all_filters.add(filter_name)
if cls._is_old_style_filter(filter_name):
lookup = cls._get_filter_and_lookup(filter_name)[-1]
if lookup in (DJL.REGEX, DJL.I_REGEX):
cls._conversion_error()
qp_old_filters.add(filter_name)
if not qp_all_filters.isdisjoint(cls.RESERVED_ORDERING_WORDS):
return True
if not qp_old_filters:
return False
if not qp_old_filters - cls._get_filters_similar_to_old_syntax(filter_instance):
return False
return True
@classmethod
def _filter_has_old_syntax(cls, filter_name, query_params):
has_select = not cls._is_select_in_filter(filter_name)
if has_select and (not set(Counter(filter_name)).isdisjoint(cls._IMPOSSIBLE_PROP_SYMBOLS)):
return False
return cls._filter_value_has_old_syntax(filter_name, query_params, has_select)
@classmethod
def _filter_value_has_old_syntax(cls, filter_name, query_params, has_select):
for v in query_params.getlist(filter_name):
if has_select and not v:
return True
if v in ('True', 'False'):
return True
is_old = cls._filter_value_has_old_syntax_by_special_chars(v)
if is_old is not None:
return is_old
@classmethod
def _filter_value_has_old_syntax_by_special_chars(cls, value):
vc = Counter(value)
no_quotes = not (vc.get('"', 0) > 1 or vc.get("'", 0) > 1)
if vc.get(' ') and no_quotes:
return True
number_of_eqs = vc.get('=', 0)
if number_of_eqs >= 1 and vc.get('(', 0) == 0 and vc.get(';'):
return True
if number_of_eqs and no_quotes:
return False
if len(value) > 2 and value[2] == '=' and value[:2] in cls._RQL_COMPARISON_OPERATORS:
return False
@classmethod
def get_rql_query(cls, filter_instance, request, query_string):
filter_value_pairs = []
for filter_name in request.query_params.keys():
if cls._is_select_in_filter(filter_name):
filter_value_pairs.append(filter_name)
continue
one_filter_value_pairs = []
for value in request.query_params.getlist(filter_name):
name_value_pair = cls._get_one_filter_value_pair(
filter_instance, filter_name, value,
)
if name_value_pair is not None:
one_filter_value_pairs.append(name_value_pair)
if one_filter_value_pairs:
filter_value_pairs.append('&'.join(one_filter_value_pairs))
return '&'.join(filter_value_pairs) if filter_value_pairs else ''
@classmethod
def _get_one_filter_value_pair(cls, filter_instance, filter_name, value):
if not value:
return
if filter_name in (RQL_LIMIT_PARAM, RQL_OFFSET_PARAM):
return '{0}={1}'.format(filter_name, value)
if filter_name in cls.RESERVED_ORDERING_WORDS:
return '{0}({1})'.format(RQL_ORDERING_OPERATOR, value)
f_item = filter_instance.get_filter_base_item(filter_name)
is_nc_item = f_item and (not f_item.get('custom', False))
if is_nc_item and FilterTypes.field_filter_type(f_item['field']) == FilterTypes.BOOLEAN:
value = cls._convert_bool_value(value)
if not cls._is_old_style_filter(filter_name):
return '{0}={1}'.format(filter_name, cls._add_quotes_to_value(value))
return cls._convert_filter_to_rql(filter_name, value)
@staticmethod
def _is_select_in_filter(filter_name):
return 'select(' in filter_name
@classmethod
def _convert_filter_to_rql(cls, filter_name, value):
filter_base, lookup = cls._get_filter_and_lookup(filter_name)
if lookup == DJL.IN:
return 'in({0},({1}))'.format(
filter_base, ','.join(cls._add_quotes_to_value(v) for v in value.split(',') if v),
)
if lookup == DJL.NULL:
operator = CO.EQ if cls._convert_bool_value(value) == 'true' else CO.NE
return '{0}={1}={2}'.format(filter_base, operator, RQL_NULL)
if lookup in (DJL.GT, DJL.GTE, DJL.LT, DJL.LTE):
if lookup == DJL.GTE:
operator = CO.GE
elif lookup == DJL.LTE:
operator = CO.LE
else:
operator = lookup
return '{0}={1}={2}'.format(filter_base, operator, value)
operator = SO.I_LIKE if lookup[0] == 'i' else SO.LIKE
lookups = (DJL.CONTAINS, DJL.I_CONTAINS, DJL.ENDSWITH, DJL.I_ENDSWITH)
if lookup in lookups and value[0] != RQL_ANY_SYMBOL:
value = RQL_ANY_SYMBOL + value
lookups = (DJL.CONTAINS, DJL.I_CONTAINS, DJL.STARTSWITH, DJL.I_STARTSWITH)
if lookup in lookups and value[-1] != RQL_ANY_SYMBOL:
value += RQL_ANY_SYMBOL
return '{0}({1},{2})'.format(operator, filter_base, cls._add_quotes_to_value(value))
@classmethod
def _convert_bool_value(cls, value):
if value in ('True', 'true', '1'):
return RQL_TRUE
elif value in ('False', 'false', '0'):
return RQL_FALSE
cls._conversion_error()
@classmethod
def _add_quotes_to_value(cls, value):
for quote in ('"', "'"):
if quote not in value:
return '{q}{0}{q}'.format(value, q=quote)
cls._conversion_error()
@staticmethod
def _conversion_error():
raise RQLFilterParsingError()
@classmethod
def _get_filters_similar_to_old_syntax(cls, filter_instance):
old_syntax_filters = getattr(filter_instance, 'old_syntax_filters', None)
if old_syntax_filters:
return old_syntax_filters
similar_to_old_syntax_filters = set()
for filter_name in filter_instance.filters.keys():
if cls._is_old_style_filter(filter_name):
similar_to_old_syntax_filters.add(filter_name)
filter_instance.old_syntax_filters = similar_to_old_syntax_filters
return similar_to_old_syntax_filters
@classmethod
def _is_old_style_filter(cls, filter_name):
return cls._get_filter_and_lookup(filter_name)[-1] in cls._POSSIBLE_DF_LOOKUPS
@classmethod
def _get_filter_and_lookup(cls, filter_name):
return filter_name.rsplit('__', 1)
| true | true |
1c2bbfcab211315e2f9579e4af1707db3698248f | 927 | py | Python | dinofw/utils/api.py | thenetcircle/dino-service | 90f90e0b21ba920506dc8fc44caf69d5bed9fb6a | [
"MIT"
] | null | null | null | dinofw/utils/api.py | thenetcircle/dino-service | 90f90e0b21ba920506dc8fc44caf69d5bed9fb6a | [
"MIT"
] | 4 | 2021-05-24T04:31:34.000Z | 2021-06-28T03:38:56.000Z | dinofw/utils/api.py | thenetcircle/dino-service | 90f90e0b21ba920506dc8fc44caf69d5bed9fb6a | [
"MIT"
] | null | null | null | import inspect
from fastapi import HTTPException
from fastapi import status
from loguru import logger
from dinofw.utils import environ
from dinofw.utils.config import ErrorCodes
# dependency
def get_db():
db = environ.env.SessionLocal()
try:
yield db
finally:
db.close()
def log_error_and_raise_unknown(exc_info, e):
func_name = inspect.currentframe().f_back.f_code.co_name
logger.error(f"{func_name}: {str(e)}")
logger.exception(e)
environ.env.capture_exception(exc_info)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"{ErrorCodes.UNKNOWN_ERROR}: {str(e)}",
)
def log_error_and_raise_known(error_code, exc_info, e):
details = f"{error_code}: {e.message}"
logger.error(details)
environ.env.capture_exception(exc_info)
raise HTTPException(
status_code=error_code,
detail=details,
)
| 23.769231 | 60 | 0.710895 | import inspect
from fastapi import HTTPException
from fastapi import status
from loguru import logger
from dinofw.utils import environ
from dinofw.utils.config import ErrorCodes
def get_db():
db = environ.env.SessionLocal()
try:
yield db
finally:
db.close()
def log_error_and_raise_unknown(exc_info, e):
func_name = inspect.currentframe().f_back.f_code.co_name
logger.error(f"{func_name}: {str(e)}")
logger.exception(e)
environ.env.capture_exception(exc_info)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"{ErrorCodes.UNKNOWN_ERROR}: {str(e)}",
)
def log_error_and_raise_known(error_code, exc_info, e):
details = f"{error_code}: {e.message}"
logger.error(details)
environ.env.capture_exception(exc_info)
raise HTTPException(
status_code=error_code,
detail=details,
)
| true | true |
1c2bc09f1d0f689171edfa743b927e6341b11021 | 15,580 | py | Python | uds/uds_config_tool/FunctionCreation/DiagnosticSessionControlMethodFactory.py | J3rome/python-uds | fe0f7a9505cb7b87f693ab736d713d7871dff288 | [
"MIT"
] | null | null | null | uds/uds_config_tool/FunctionCreation/DiagnosticSessionControlMethodFactory.py | J3rome/python-uds | fe0f7a9505cb7b87f693ab736d713d7871dff288 | [
"MIT"
] | null | null | null | uds/uds_config_tool/FunctionCreation/DiagnosticSessionControlMethodFactory.py | J3rome/python-uds | fe0f7a9505cb7b87f693ab736d713d7871dff288 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
__author__ = "Richard Clubb"
__copyrights__ = "Copyright 2018, the python-uds project"
__credits__ = ["Richard Clubb"]
__license__ = "MIT"
__maintainer__ = "Richard Clubb"
__email__ = "richard.clubb@embeduk.com"
__status__ = "Development"
import xml.etree.ElementTree as ET
from .. import DecodeFunctions
import sys
from .iServiceMethodFactory import IServiceMethodFactory
SUPPRESS_RESPONSE_BIT = 0x80
requestFuncTemplate = str("def {0}(suppressResponse=False):\n"
" sessionType = {2}\n"
" suppressBit = {3} if suppressResponse else 0x00\n"
" sessionType[0] += suppressBit\n"
" return {1} + sessionType")
# Note: we do not need to cater for response suppression checking as nothing to check if response is suppressed - always unsuppressed
checkFunctionTemplate = str("def {0}(input):\n"
" serviceIdExpected = {1}\n"
" sessionTypeExpected = {2}\n"
" serviceId = DecodeFunctions.buildIntFromList(input[{3}:{4}])\n"
" sessionType = DecodeFunctions.buildIntFromList(input[{5}:{6}])\n"
" if(len(input) != {7}): raise Exception(\"Total length returned not as expected. Expected: {7}; Got {{0}}\".format(len(input)))\n"
" if(serviceId != serviceIdExpected): raise Exception(\"Service Id Received not expected. Expected {{0}}; Got {{1}} \".format(serviceIdExpected, serviceId))\n"
" if(sessionType != sessionTypeExpected): raise Exception(\"Session Type Received not as expected. Expected: {{0}}; Got {{1}}\".format(sessionTypeExpected, sessionType))")
negativeResponseFuncTemplate = str("def {0}(input):\n"
" {1}")
# Note: we do not need to cater for response suppression checking as nothing to check if response is suppressed - always unsuppressed
encodePositiveResponseFuncTemplate = str("def {0}(input):\n"
" result = {{}}\n"
" {1}\n"
" return result")
class DiagnosticSessionControlMethodFactory(IServiceMethodFactory):
##
# @brief method to create the request function for the service element
@staticmethod
def create_requestFunction(diagServiceElement, xmlElements):
# Some services are present in the ODX in both response and send only versions (with the same short name, so one will overwrite the other).
# Avoiding the overwrite by ignoring the send-only versions, i.e. these are identical other than postivie response details being missing.
try:
if diagServiceElement.attrib['TRANSMISSION-MODE'] == 'SEND-ONLY':
return None
except:
pass
serviceId = 0
sessionType = 0
shortName = "request_{0}".format(diagServiceElement.find('SHORT-NAME').text)
requestElement = xmlElements[diagServiceElement.find('REQUEST-REF').attrib['ID-REF']]
paramsElement = requestElement.find('PARAMS')
encodeFunctions = []
encodeFunction = "None"
for param in paramsElement:
semantic = None
try:
semantic = param.attrib['SEMANTIC']
except AttributeError:
pass
if(semantic == 'SERVICE-ID'):
serviceId = [int(param.find('CODED-VALUE').text)]
elif(semantic == 'SUBFUNCTION'):
sessionType = [int(param.find('CODED-VALUE').text)]
if sessionType[0] >= SUPPRESS_RESPONSE_BIT:
pass
#raise ValueError("Diagnostic Session Control:session type exceeds maximum value (received {0})".format(sessionType[0]))
funcString = requestFuncTemplate.format(shortName,
serviceId,
sessionType,
SUPPRESS_RESPONSE_BIT)
exec(funcString)
return locals()[shortName]
##
# @brief method to create the function to check the positive response for validity
@staticmethod
def create_checkPositiveResponseFunction(diagServiceElement, xmlElements):
# Some services are present in the ODX in both response and send only versions (with the same short name, so one will overwrite the other).
# Avoiding the overwrite by ignoring the send-only versions, i.e. these are identical other than postivie response details being missing.
try:
if diagServiceElement.attrib['TRANSMISSION-MODE'] == 'SEND-ONLY':
return None
except:
pass
responseId = 0
sessionType = 0
responseIdStart = 0
responseIdEnd = 0
sessionTypeStart = 0
sessionTypeEnd = 0
shortName = "request_{0}".format(diagServiceElement.find('SHORT-NAME').text)
checkFunctionName = "check_{0}".format(shortName)
positiveResponseElement = xmlElements[(diagServiceElement.find('POS-RESPONSE-REFS')).find('POS-RESPONSE-REF').attrib['ID-REF']]
paramsElement = positiveResponseElement.find('PARAMS')
totalLength = 0
paramCnt = 0
for param in paramsElement:
try:
semantic = None
try:
semantic = param.attrib['SEMANTIC']
except AttributeError:
pass
startByte = int(param.find('BYTE-POSITION').text)
if(semantic == 'SERVICE-ID'):
responseId = int(param.find('CODED-VALUE').text)
bitLength = int((param.find('DIAG-CODED-TYPE')).find('BIT-LENGTH').text)
listLength = int(bitLength / 8)
responseIdStart = startByte
responseIdEnd = startByte + listLength
totalLength += listLength
elif(semantic == 'SUBFUNCTION'):
sessionType = int(param.find('CODED-VALUE').text)
bitLength = int((param.find('DIAG-CODED-TYPE')).find('BIT-LENGTH').text)
listLength = int(bitLength / 8)
sessionTypeStart = startByte
sessionTypeEnd = startByte + listLength
totalLength += listLength
elif(semantic == 'DATA'):
dataObjectElement = xmlElements[(param.find('DOP-REF')).attrib['ID-REF']]
if(dataObjectElement.tag == "DATA-OBJECT-PROP"):
start = int(param.find('BYTE-POSITION').text)
bitLength = int(dataObjectElement.find('DIAG-CODED-TYPE').find('BIT-LENGTH').text)
listLength = int(bitLength/8)
totalLength += listLength
elif(dataObjectElement.tag == "STRUCTURE"):
start = int(param.find('BYTE-POSITION').text)
listLength = int(dataObjectElement.find('BYTE-SIZE').text)
totalLength += listLength
else:
pass
else:
pass
except:
#print(sys.exc_info())
pass
checkFunctionString = checkFunctionTemplate.format(checkFunctionName, # 0
responseId, # 1
sessionType, # 2
responseIdStart, # 3
responseIdEnd, # 4
sessionTypeStart, # 5
sessionTypeEnd, # 6
totalLength) # 7
exec(checkFunctionString)
return locals()[checkFunctionName]
##
# @brief method to encode the positive response from the raw type to it physical representation
@staticmethod
def create_encodePositiveResponseFunction(diagServiceElement, xmlElements):
# Some services are present in the ODX in both response and send only versions (with the same short name, so one will overwrite the other).
# Avoiding the overwrite by ignoring the send-only versions, i.e. these are identical other than postivie response details being missing.
try:
if diagServiceElement.attrib['TRANSMISSION-MODE'] == 'SEND-ONLY':
return None
except:
pass
# The values in the response are SID, diagnosticSessionType, and session parameters. Checking is handled in the check function,
# so must be present and ok. This function is only required to return the diagnosticSessionType, and session parameters.
positiveResponseElement = xmlElements[(diagServiceElement.find('POS-RESPONSE-REFS')).find('POS-RESPONSE-REF').attrib['ID-REF']]
shortName = diagServiceElement.find('SHORT-NAME').text
encodePositiveResponseFunctionName = "encode_{0}".format(shortName)
params = positiveResponseElement.find('PARAMS')
encodeFunctions = []
for param in params:
try:
semantic = None
try:
semantic = param.attrib['SEMANTIC']
except AttributeError:
pass
if semantic == 'SUBFUNCTION':
longName = param.find('LONG-NAME').text
bytePosition = int(param.find('BYTE-POSITION').text)
bitLength = int(param.find('DIAG-CODED-TYPE').find('BIT-LENGTH').text)
listLength = int(bitLength / 8)
endPosition = bytePosition + listLength
encodingType = param.find('DIAG-CODED-TYPE').attrib['BASE-DATA-TYPE']
if(encodingType) == "A_ASCIISTRING":
functionString = "DecodeFunctions.intListToString(input[{0}:{1}], None)".format(bytePosition,
endPosition)
else:
functionString = "input[{1}:{2}]".format(longName,
bytePosition,
endPosition)
encodeFunctions.append("result['{0}'] = {1}".format(longName,
functionString))
if semantic == 'DATA':
dataObjectElement = xmlElements[(param.find('DOP-REF')).attrib['ID-REF']]
longName = param.find('LONG-NAME').text
bytePosition = int(param.find('BYTE-POSITION').text)
bitLength = int(dataObjectElement.find('DIAG-CODED-TYPE').find('BIT-LENGTH').text)
listLength = int(bitLength / 8)
endPosition = bytePosition + listLength
encodingType = dataObjectElement.find('DIAG-CODED-TYPE').attrib['BASE-DATA-TYPE']
if(encodingType) == "A_ASCIISTRING":
functionString = "DecodeFunctions.intListToString(input[{0}:{1}], None)".format(bytePosition,
endPosition)
elif(encodingType == "A_UINT32"):
functionString = "input[{1}:{2}]".format(longName,
bytePosition,
endPosition)
else:
functionString = "input[{1}:{2}]".format(longName,
bytePosition,
endPosition)
encodeFunctions.append("result['{0}'] = {1}".format(longName,
functionString))
except:
pass
encodeFunctionString = encodePositiveResponseFuncTemplate.format(encodePositiveResponseFunctionName,
"\n ".join(encodeFunctions))
exec(encodeFunctionString)
return locals()[encodePositiveResponseFunctionName]
##
# @brief method to create the negative response function for the service element
@staticmethod
def create_checkNegativeResponseFunction(diagServiceElement, xmlElements):
# Some services are present in the ODX in both response and send only versions (with the same short name, so one will overwrite the other).
# Avoiding the overwrite by ignoring the send-only versions, i.e. these are identical other than postivie response details being missing.
try:
if diagServiceElement.attrib['TRANSMISSION-MODE'] == 'SEND-ONLY':
return None
except:
pass
shortName = diagServiceElement.find('SHORT-NAME').text
check_negativeResponseFunctionName = "check_negResponse_{0}".format(shortName)
negativeResponsesElement = diagServiceElement.find('NEG-RESPONSE-REFS')
negativeResponseChecks = []
for negativeResponse in negativeResponsesElement:
negativeResponseRef = xmlElements[negativeResponse.attrib['ID-REF']]
negativeResponseParams = negativeResponseRef.find('PARAMS')
for param in negativeResponseParams:
semantic = None
try:
semantic = param.attrib['SEMANTIC']
except:
semantic = None
if semantic == 'SERVICE-ID':
serviceId = param.find('CODED-VALUE').text
start = int(param.find('BYTE-POSITION').text)
diagCodedType = param.find('DIAG-CODED-TYPE')
bitLength = int((param.find('DIAG-CODED-TYPE')).find('BIT-LENGTH').text)
listLength = int(bitLength/8)
end = start + listLength
checkString = "if input[{0}:{1}] == [{2}]: raise Exception(\"Detected negative response: {{0}}\".format(str([hex(n) for n in input])))".format(start,
end,
serviceId)
negativeResponseChecks.append(checkString)
pass
pass
negativeResponseFunctionString = negativeResponseFuncTemplate.format(check_negativeResponseFunctionName,
"\n....".join(negativeResponseChecks))
exec(negativeResponseFunctionString)
return locals()[check_negativeResponseFunctionName]
| 50.096463 | 202 | 0.525417 |
__author__ = "Richard Clubb"
__copyrights__ = "Copyright 2018, the python-uds project"
__credits__ = ["Richard Clubb"]
__license__ = "MIT"
__maintainer__ = "Richard Clubb"
__email__ = "richard.clubb@embeduk.com"
__status__ = "Development"
import xml.etree.ElementTree as ET
from .. import DecodeFunctions
import sys
from .iServiceMethodFactory import IServiceMethodFactory
SUPPRESS_RESPONSE_BIT = 0x80
requestFuncTemplate = str("def {0}(suppressResponse=False):\n"
" sessionType = {2}\n"
" suppressBit = {3} if suppressResponse else 0x00\n"
" sessionType[0] += suppressBit\n"
" return {1} + sessionType")
checkFunctionTemplate = str("def {0}(input):\n"
" serviceIdExpected = {1}\n"
" sessionTypeExpected = {2}\n"
" serviceId = DecodeFunctions.buildIntFromList(input[{3}:{4}])\n"
" sessionType = DecodeFunctions.buildIntFromList(input[{5}:{6}])\n"
" if(len(input) != {7}): raise Exception(\"Total length returned not as expected. Expected: {7}; Got {{0}}\".format(len(input)))\n"
" if(serviceId != serviceIdExpected): raise Exception(\"Service Id Received not expected. Expected {{0}}; Got {{1}} \".format(serviceIdExpected, serviceId))\n"
" if(sessionType != sessionTypeExpected): raise Exception(\"Session Type Received not as expected. Expected: {{0}}; Got {{1}}\".format(sessionTypeExpected, sessionType))")
negativeResponseFuncTemplate = str("def {0}(input):\n"
" {1}")
encodePositiveResponseFuncTemplate = str("def {0}(input):\n"
" result = {{}}\n"
" {1}\n"
" return result")
class DiagnosticSessionControlMethodFactory(IServiceMethodFactory):
@staticmethod
def create_requestFunction(diagServiceElement, xmlElements):
try:
if diagServiceElement.attrib['TRANSMISSION-MODE'] == 'SEND-ONLY':
return None
except:
pass
serviceId = 0
sessionType = 0
shortName = "request_{0}".format(diagServiceElement.find('SHORT-NAME').text)
requestElement = xmlElements[diagServiceElement.find('REQUEST-REF').attrib['ID-REF']]
paramsElement = requestElement.find('PARAMS')
encodeFunctions = []
encodeFunction = "None"
for param in paramsElement:
semantic = None
try:
semantic = param.attrib['SEMANTIC']
except AttributeError:
pass
if(semantic == 'SERVICE-ID'):
serviceId = [int(param.find('CODED-VALUE').text)]
elif(semantic == 'SUBFUNCTION'):
sessionType = [int(param.find('CODED-VALUE').text)]
if sessionType[0] >= SUPPRESS_RESPONSE_BIT:
pass
funcString = requestFuncTemplate.format(shortName,
serviceId,
sessionType,
SUPPRESS_RESPONSE_BIT)
exec(funcString)
return locals()[shortName]
@staticmethod
def create_checkPositiveResponseFunction(diagServiceElement, xmlElements):
try:
if diagServiceElement.attrib['TRANSMISSION-MODE'] == 'SEND-ONLY':
return None
except:
pass
responseId = 0
sessionType = 0
responseIdStart = 0
responseIdEnd = 0
sessionTypeStart = 0
sessionTypeEnd = 0
shortName = "request_{0}".format(diagServiceElement.find('SHORT-NAME').text)
checkFunctionName = "check_{0}".format(shortName)
positiveResponseElement = xmlElements[(diagServiceElement.find('POS-RESPONSE-REFS')).find('POS-RESPONSE-REF').attrib['ID-REF']]
paramsElement = positiveResponseElement.find('PARAMS')
totalLength = 0
paramCnt = 0
for param in paramsElement:
try:
semantic = None
try:
semantic = param.attrib['SEMANTIC']
except AttributeError:
pass
startByte = int(param.find('BYTE-POSITION').text)
if(semantic == 'SERVICE-ID'):
responseId = int(param.find('CODED-VALUE').text)
bitLength = int((param.find('DIAG-CODED-TYPE')).find('BIT-LENGTH').text)
listLength = int(bitLength / 8)
responseIdStart = startByte
responseIdEnd = startByte + listLength
totalLength += listLength
elif(semantic == 'SUBFUNCTION'):
sessionType = int(param.find('CODED-VALUE').text)
bitLength = int((param.find('DIAG-CODED-TYPE')).find('BIT-LENGTH').text)
listLength = int(bitLength / 8)
sessionTypeStart = startByte
sessionTypeEnd = startByte + listLength
totalLength += listLength
elif(semantic == 'DATA'):
dataObjectElement = xmlElements[(param.find('DOP-REF')).attrib['ID-REF']]
if(dataObjectElement.tag == "DATA-OBJECT-PROP"):
start = int(param.find('BYTE-POSITION').text)
bitLength = int(dataObjectElement.find('DIAG-CODED-TYPE').find('BIT-LENGTH').text)
listLength = int(bitLength/8)
totalLength += listLength
elif(dataObjectElement.tag == "STRUCTURE"):
start = int(param.find('BYTE-POSITION').text)
listLength = int(dataObjectElement.find('BYTE-SIZE').text)
totalLength += listLength
else:
pass
else:
pass
except:
pass
checkFunctionString = checkFunctionTemplate.format(checkFunctionName,
responseId,
sessionType,
responseIdStart,
responseIdEnd,
sessionTypeStart,
sessionTypeEnd,
totalLength)
exec(checkFunctionString)
return locals()[checkFunctionName]
@staticmethod
def create_encodePositiveResponseFunction(diagServiceElement, xmlElements):
try:
if diagServiceElement.attrib['TRANSMISSION-MODE'] == 'SEND-ONLY':
return None
except:
pass
positiveResponseElement = xmlElements[(diagServiceElement.find('POS-RESPONSE-REFS')).find('POS-RESPONSE-REF').attrib['ID-REF']]
shortName = diagServiceElement.find('SHORT-NAME').text
encodePositiveResponseFunctionName = "encode_{0}".format(shortName)
params = positiveResponseElement.find('PARAMS')
encodeFunctions = []
for param in params:
try:
semantic = None
try:
semantic = param.attrib['SEMANTIC']
except AttributeError:
pass
if semantic == 'SUBFUNCTION':
longName = param.find('LONG-NAME').text
bytePosition = int(param.find('BYTE-POSITION').text)
bitLength = int(param.find('DIAG-CODED-TYPE').find('BIT-LENGTH').text)
listLength = int(bitLength / 8)
endPosition = bytePosition + listLength
encodingType = param.find('DIAG-CODED-TYPE').attrib['BASE-DATA-TYPE']
if(encodingType) == "A_ASCIISTRING":
functionString = "DecodeFunctions.intListToString(input[{0}:{1}], None)".format(bytePosition,
endPosition)
else:
functionString = "input[{1}:{2}]".format(longName,
bytePosition,
endPosition)
encodeFunctions.append("result['{0}'] = {1}".format(longName,
functionString))
if semantic == 'DATA':
dataObjectElement = xmlElements[(param.find('DOP-REF')).attrib['ID-REF']]
longName = param.find('LONG-NAME').text
bytePosition = int(param.find('BYTE-POSITION').text)
bitLength = int(dataObjectElement.find('DIAG-CODED-TYPE').find('BIT-LENGTH').text)
listLength = int(bitLength / 8)
endPosition = bytePosition + listLength
encodingType = dataObjectElement.find('DIAG-CODED-TYPE').attrib['BASE-DATA-TYPE']
if(encodingType) == "A_ASCIISTRING":
functionString = "DecodeFunctions.intListToString(input[{0}:{1}], None)".format(bytePosition,
endPosition)
elif(encodingType == "A_UINT32"):
functionString = "input[{1}:{2}]".format(longName,
bytePosition,
endPosition)
else:
functionString = "input[{1}:{2}]".format(longName,
bytePosition,
endPosition)
encodeFunctions.append("result['{0}'] = {1}".format(longName,
functionString))
except:
pass
encodeFunctionString = encodePositiveResponseFuncTemplate.format(encodePositiveResponseFunctionName,
"\n ".join(encodeFunctions))
exec(encodeFunctionString)
return locals()[encodePositiveResponseFunctionName]
@staticmethod
def create_checkNegativeResponseFunction(diagServiceElement, xmlElements):
try:
if diagServiceElement.attrib['TRANSMISSION-MODE'] == 'SEND-ONLY':
return None
except:
pass
shortName = diagServiceElement.find('SHORT-NAME').text
check_negativeResponseFunctionName = "check_negResponse_{0}".format(shortName)
negativeResponsesElement = diagServiceElement.find('NEG-RESPONSE-REFS')
negativeResponseChecks = []
for negativeResponse in negativeResponsesElement:
negativeResponseRef = xmlElements[negativeResponse.attrib['ID-REF']]
negativeResponseParams = negativeResponseRef.find('PARAMS')
for param in negativeResponseParams:
semantic = None
try:
semantic = param.attrib['SEMANTIC']
except:
semantic = None
if semantic == 'SERVICE-ID':
serviceId = param.find('CODED-VALUE').text
start = int(param.find('BYTE-POSITION').text)
diagCodedType = param.find('DIAG-CODED-TYPE')
bitLength = int((param.find('DIAG-CODED-TYPE')).find('BIT-LENGTH').text)
listLength = int(bitLength/8)
end = start + listLength
checkString = "if input[{0}:{1}] == [{2}]: raise Exception(\"Detected negative response: {{0}}\".format(str([hex(n) for n in input])))".format(start,
end,
serviceId)
negativeResponseChecks.append(checkString)
pass
pass
negativeResponseFunctionString = negativeResponseFuncTemplate.format(check_negativeResponseFunctionName,
"\n....".join(negativeResponseChecks))
exec(negativeResponseFunctionString)
return locals()[check_negativeResponseFunctionName]
| true | true |
1c2bc12eec7806707ac9c57a5277267fb7cd156d | 12,142 | py | Python | Code/scripts/SimCLR/SimCLR_DSAD_scripts.py | antoine-spahr/X-ray-Anomaly-Detection | 850b6195d6290a50eee865b4d5a66f5db5260e8f | [
"MIT"
] | 2 | 2020-10-12T08:25:13.000Z | 2021-08-16T08:43:43.000Z | Code/scripts/SimCLR/SimCLR_DSAD_scripts.py | antoine-spahr/X-ray-Anomaly-Detection | 850b6195d6290a50eee865b4d5a66f5db5260e8f | [
"MIT"
] | null | null | null | Code/scripts/SimCLR/SimCLR_DSAD_scripts.py | antoine-spahr/X-ray-Anomaly-Detection | 850b6195d6290a50eee865b4d5a66f5db5260e8f | [
"MIT"
] | 1 | 2020-06-17T07:40:17.000Z | 2020-06-17T07:40:17.000Z | import torch
import torch.cuda
import logging
import numpy as np
import pandas as pd
import random
from datetime import datetime
import os
import sys
sys.path.append('../../')
import click
from src.datasets.MURADataset import MURA_TrainValidTestSplitter, MURA_Dataset, MURADataset_SimCLR
from src.models.SimCLR_DSAD import SimCLR_DSAD
from src.models.networks.SimCLR_network import SimCLR_net
from src.utils.utils import summary_string
from src.utils.Config import Config
@click.command()
@click.argument('config_path', type=click.Path(exists=True))
def main(config_path):
"""
Train a DSAD on the MURA dataset using a SimCLR pretraining.
"""
# Load config file
cfg = Config(settings=None)
cfg.load_config(config_path)
# Get path to output
OUTPUT_PATH = cfg.settings['PATH']['OUTPUT'] + cfg.settings['Experiment_Name'] + datetime.today().strftime('%Y_%m_%d_%Hh%M')+'/'
# make output dir
if not os.path.isdir(OUTPUT_PATH+'models/'): os.makedirs(OUTPUT_PATH+'model/', exist_ok=True)
if not os.path.isdir(OUTPUT_PATH+'results/'): os.makedirs(OUTPUT_PATH+'results/', exist_ok=True)
if not os.path.isdir(OUTPUT_PATH+'logs/'): os.makedirs(OUTPUT_PATH+'logs/', exist_ok=True)
for seed_i, seed in enumerate(cfg.settings['seeds']):
############################### Set Up #################################
# initialize logger
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
try:
logger.handlers[1].stream.close()
logger.removeHandler(logger.handlers[1])
except IndexError:
pass
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')
log_file = OUTPUT_PATH + 'logs/' + f'log_{seed_i+1}.txt'
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# print path
logger.info(f"Log file : {log_file}")
logger.info(f"Data path : {cfg.settings['PATH']['DATA']}")
logger.info(f"Outputs path : {OUTPUT_PATH}" + "\n")
# Set seed
if seed != -1:
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
logger.info(f"Set seed {seed_i+1:02}/{len(cfg.settings['seeds']):02} to {seed}")
# set number of thread
if cfg.settings['n_thread'] > 0:
torch.set_num_threads(cfg.settings['n_thread'])
# check if GPU available
cfg.settings['device'] = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
# Print technical info in logger
logger.info(f"Device : {cfg.settings['device']}")
logger.info(f"Number of thread : {cfg.settings['n_thread']}")
############################### Split Data #############################
# Load data informations
df_info = pd.read_csv(cfg.settings['PATH']['DATA_INFO'])
df_info = df_info.drop(df_info.columns[0], axis=1)
# remove low contrast images (all black)
df_info = df_info[df_info.low_contrast == 0]
# Train Validation Test Split
spliter = MURA_TrainValidTestSplitter(df_info, train_frac=cfg.settings['Split']['train_frac'],
ratio_known_normal=cfg.settings['Split']['known_normal'],
ratio_known_abnormal=cfg.settings['Split']['known_abnormal'],
random_state=42)
spliter.split_data(verbose=False)
train_df = spliter.get_subset('train')
valid_df = spliter.get_subset('valid')
test_df = spliter.get_subset('test')
# print info to logger
for key, value in cfg.settings['Split'].items():
logger.info(f"Split param {key} : {value}")
logger.info("Split Summary \n" + str(spliter.print_stat(returnTable=True)))
############################# Build Model #############################
# make networks
net_CLR = SimCLR_net(MLP_Neurons_layer=cfg.settings['SimCLR']['MLP_head'])
net_CLR = net_CLR.to(cfg.settings['device'])
net_DSAD = SimCLR_net(MLP_Neurons_layer=cfg.settings['DSAD']['MLP_head'])
net_DSAD = net_DSAD.to(cfg.settings['device'])
# print network architecture
net_architecture = summary_string(net_CLR, (1, cfg.settings['Split']['img_size'], cfg.settings['Split']['img_size']),
batch_size=cfg.settings['SimCLR']['batch_size'], device=str(cfg.settings['device']))
logger.info("SimCLR net architecture: \n" + net_architecture + '\n')
net_architecture = summary_string(net_DSAD, (1, cfg.settings['Split']['img_size'], cfg.settings['Split']['img_size']),
batch_size=cfg.settings['DSAD']['batch_size'], device=str(cfg.settings['device']))
logger.info("DSAD net architecture: \n" + net_architecture + '\n')
# make model
clr_DSAD = SimCLR_DSAD(net_CLR, net_DSAD, tau=cfg.settings['SimCLR']['tau'],
eta=cfg.settings['DSAD']['eta'])
############################# Train SimCLR #############################
# make datasets
train_dataset_CLR = MURADataset_SimCLR(train_df, data_path=cfg.settings['PATH']['DATA'],
output_size=cfg.settings['Split']['img_size'], mask_img=True)
valid_dataset_CLR = MURADataset_SimCLR(valid_df, data_path=cfg.settings['PATH']['DATA'],
output_size=cfg.settings['Split']['img_size'], mask_img=True)
test_dataset_CLR = MURADataset_SimCLR(test_df, data_path=cfg.settings['PATH']['DATA'],
output_size=cfg.settings['Split']['img_size'], mask_img=True)
logger.info("SimCLR Online preprocessing pipeline : \n" + str(train_dataset_CLR.transform) + "\n")
# Load model if required
if cfg.settings['SimCLR']['model_path_to_load']:
clr_DSAD.load_repr_net(cfg.settings['SimCLR']['model_path_to_load'], map_location=cfg.settings['device'])
logger.info(f"SimCLR Model Loaded from {cfg.settings['SimCLR']['model_path_to_load']}" + "\n")
# print Train parameters
for key, value in cfg.settings['SimCLR'].items():
logger.info(f"SimCLR {key} : {value}")
# Train SimCLR
clr_DSAD.train_SimCLR(train_dataset_CLR, valid_dataset=None,
n_epoch=cfg.settings['SimCLR']['n_epoch'],
batch_size=cfg.settings['SimCLR']['batch_size'],
lr=cfg.settings['SimCLR']['lr'],
weight_decay=cfg.settings['SimCLR']['weight_decay'],
lr_milestones=cfg.settings['SimCLR']['lr_milestone'],
n_job_dataloader=cfg.settings['SimCLR']['num_worker'],
device=cfg.settings['device'],
print_batch_progress=cfg.settings['print_batch_progress'])
# Evaluate SimCLR to get embeddings
clr_DSAD.evaluate_SimCLR(valid_dataset_CLR, batch_size=cfg.settings['SimCLR']['batch_size'],
n_job_dataloader=cfg.settings['SimCLR']['num_worker'],
device=cfg.settings['device'],
print_batch_progress=cfg.settings['print_batch_progress'],
set='valid')
clr_DSAD.evaluate_SimCLR(test_dataset_CLR, batch_size=cfg.settings['SimCLR']['batch_size'],
n_job_dataloader=cfg.settings['SimCLR']['num_worker'],
device=cfg.settings['device'],
print_batch_progress=cfg.settings['print_batch_progress'],
set='test')
# save repr net
clr_DSAD.save_repr_net(OUTPUT_PATH + f'model/SimCLR_net_{seed_i+1}.pt')
logger.info("SimCLR model saved at " + OUTPUT_PATH + f"model/SimCLR_net_{seed_i+1}.pt")
# save Results
clr_DSAD.save_results(OUTPUT_PATH + f'results/results_{seed_i+1}.json')
logger.info("Results saved at " + OUTPUT_PATH + f"results/results_{seed_i+1}.json")
######################## Transfer Encoder Weight #######################
clr_DSAD.transfer_encoder()
############################## Train DSAD ##############################
# make dataset
train_dataset_AD = MURA_Dataset(train_df, data_path=cfg.settings['PATH']['DATA'], load_mask=True,
load_semilabels=True, output_size=cfg.settings['Split']['img_size'])
valid_dataset_AD = MURA_Dataset(valid_df, data_path=cfg.settings['PATH']['DATA'], load_mask=True,
load_semilabels=True, output_size=cfg.settings['Split']['img_size'])
test_dataset_AD = MURA_Dataset(test_df, data_path=cfg.settings['PATH']['DATA'], load_mask=True,
load_semilabels=True, output_size=cfg.settings['Split']['img_size'])
logger.info("DSAD Online preprocessing pipeline : \n" + str(train_dataset_AD.transform) + "\n")
# Load model if required
if cfg.settings['DSAD']['model_path_to_load']:
clr_DSAD.load_AD(cfg.settings['DSAD']['model_path_to_load'], map_location=cfg.settings['device'])
logger.info(f"DSAD Model Loaded from {cfg.settings['DSAD']['model_path_to_load']} \n")
# print Train parameters
for key, value in cfg.settings['DSAD'].items():
logger.info(f"DSAD {key} : {value}")
# Train DSAD
clr_DSAD.train_AD(train_dataset_AD, valid_dataset=valid_dataset_AD,
n_epoch=cfg.settings['DSAD']['n_epoch'],
batch_size=cfg.settings['DSAD']['batch_size'],
lr=cfg.settings['DSAD']['lr'],
weight_decay=cfg.settings['DSAD']['weight_decay'],
lr_milestone=cfg.settings['DSAD']['lr_milestone'],
n_job_dataloader=cfg.settings['DSAD']['num_worker'],
device=cfg.settings['device'],
print_batch_progress=cfg.settings['print_batch_progress'])
logger.info('--- Validation')
clr_DSAD.evaluate_AD(valid_dataset_AD, batch_size=cfg.settings['DSAD']['batch_size'],
n_job_dataloader=cfg.settings['DSAD']['num_worker'],
device=cfg.settings['device'],
print_batch_progress=cfg.settings['print_batch_progress'],
set='valid')
logger.info('--- Test')
clr_DSAD.evaluate_AD(test_dataset_AD, batch_size=cfg.settings['DSAD']['batch_size'],
n_job_dataloader=cfg.settings['DSAD']['num_worker'],
device=cfg.settings['device'],
print_batch_progress=cfg.settings['print_batch_progress'],
set='test')
# save DSAD
clr_DSAD.save_AD(OUTPUT_PATH + f'model/DSAD_{seed_i+1}.pt')
logger.info("model saved at " + OUTPUT_PATH + f"model/DSAD_{seed_i+1}.pt")
########################## Save Results ################################
# save Results
clr_DSAD.save_results(OUTPUT_PATH + f'results/results_{seed_i+1}.json')
logger.info("Results saved at " + OUTPUT_PATH + f"results/results_{seed_i+1}.json")
# save config file
cfg.settings['device'] = str(cfg.settings['device'])
cfg.save_config(OUTPUT_PATH + 'config.json')
logger.info("Config saved at " + OUTPUT_PATH + "config.json")
if __name__ == '__main__':
main()
| 51.888889 | 132 | 0.580053 | import torch
import torch.cuda
import logging
import numpy as np
import pandas as pd
import random
from datetime import datetime
import os
import sys
sys.path.append('../../')
import click
from src.datasets.MURADataset import MURA_TrainValidTestSplitter, MURA_Dataset, MURADataset_SimCLR
from src.models.SimCLR_DSAD import SimCLR_DSAD
from src.models.networks.SimCLR_network import SimCLR_net
from src.utils.utils import summary_string
from src.utils.Config import Config
@click.command()
@click.argument('config_path', type=click.Path(exists=True))
def main(config_path):
cfg = Config(settings=None)
cfg.load_config(config_path)
OUTPUT_PATH = cfg.settings['PATH']['OUTPUT'] + cfg.settings['Experiment_Name'] + datetime.today().strftime('%Y_%m_%d_%Hh%M')+'/'
if not os.path.isdir(OUTPUT_PATH+'models/'): os.makedirs(OUTPUT_PATH+'model/', exist_ok=True)
if not os.path.isdir(OUTPUT_PATH+'results/'): os.makedirs(OUTPUT_PATH+'results/', exist_ok=True)
if not os.path.isdir(OUTPUT_PATH+'logs/'): os.makedirs(OUTPUT_PATH+'logs/', exist_ok=True)
for seed_i, seed in enumerate(cfg.settings['seeds']):
| true | true |
1c2bc1508689c277c7d35f6f54288d95419839a0 | 8,586 | py | Python | examples/example_network_expressroutecircuits.py | zikalino/AzurePythonExamples | 23f9c173f0736f4e7ff66dde0402ef88da4ccc8f | [
"MIT"
] | 1 | 2020-09-04T14:38:13.000Z | 2020-09-04T14:38:13.000Z | examples/example_network_expressroutecircuits.py | zikalino/AzurePythonExamples | 23f9c173f0736f4e7ff66dde0402ef88da4ccc8f | [
"MIT"
] | null | null | null | examples/example_network_expressroutecircuits.py | zikalino/AzurePythonExamples | 23f9c173f0736f4e7ff66dde0402ef88da4ccc8f | [
"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 os
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.resource import ResourceManagementClient
from azure.common.credentials import ServicePrincipalCredentials
#--------------------------------------------------------------------------
# credentials from environment
#--------------------------------------------------------------------------
SUBSCRIPTION_ID = os.environ['AZURE_SUBSCRIPTION_ID']
TENANT_ID = os.environ['AZURE_TENANT']
CLIENT_ID = os.environ['AZURE_CLIENT_ID']
CLIENT_SECRET = os.environ['AZURE_SECRET']
#--------------------------------------------------------------------------
# variables
#--------------------------------------------------------------------------
AZURE_LOCATION = 'eastus'
RESOURCE_GROUP = "myResourceGroup"
CIRCUIT_NAME = "myCircuit"
PEERING_NAME = "AzurePrivatePeering"
EXPRESS_ROUTE_PORT_NAME = "myExpressRoutePort"
DEVICE_PATH = "myDevicePath"
#--------------------------------------------------------------------------
# management clients
#--------------------------------------------------------------------------
credentials = ServicePrincipalCredentials(
client_id=CLIENT_ID,
secret=CLIENT_SECRET,
tenant=TENANT_ID
)
mgmt_client = NetworkManagementClient(credentials, SUBSCRIPTION_ID)
resource_client = ResourceManagementClient(credentials, SUBSCRIPTION_ID)
#--------------------------------------------------------------------------
# resource group (prerequisite)
#--------------------------------------------------------------------------
print("Creating Resource Group")
resource_client.resource_groups.create_or_update(resource_group_name=RESOURCE_GROUP, parameters={ 'location': AZURE_LOCATION })
#--------------------------------------------------------------------------
# /ExpressRouteCircuits/put/Create ExpressRouteCircuit[put]
#--------------------------------------------------------------------------
print("Create ExpressRouteCircuit")
BODY = {
"sku": {
"name": "Standard_MeteredData",
"tier": "Standard",
"family": "MeteredData"
},
"location": AZURE_LOCATION,
"authorizations": [],
"peerings": [],
"allow_classic_operations": False,
"service_provider_properties": {
"service_provider_name": "Equinix",
"peering_location": "Silicon Valley",
"bandwidth_in_mbps": "200"
}
}
result = mgmt_client.express_route_circuits.create_or_update(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME, parameters=BODY)
result = result.result()
#--------------------------------------------------------------------------
# /ExpressRouteCircuitPeerings/put/Create ExpressRouteCircuit Peerings[put]
#--------------------------------------------------------------------------
print("Create ExpressRouteCircuit Peerings")
BODY = {
"peer_asn": "200",
"primary_peer_address_prefix": "192.168.16.252/30",
"secondary_peer_address_prefix": "192.168.18.252/30",
"vlan_id": "200"
}
result = mgmt_client.express_route_circuit_peerings.create_or_update(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME, peering_name=PEERING_NAME, peering_parameters=BODY)
result = result.result()
#--------------------------------------------------------------------------
# Disabled as express route port can't be created
# /ExpressRouteCircuits/put/Create ExpressRouteCircuit on ExpressRoutePort[put]
#--------------------------------------------------------------------------
print("Create ExpressRouteCircuit on ExpressRoutePort")
BODY = {
"location": AZURE_LOCATION,
"sku": {
"name": "Premium_MeteredData",
"tier": "Premium",
"family": "MeteredData"
},
"express_route_port": {
"id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Network/expressRoutePorts/" + EXPRESS_ROUTE_PORT_NAME
},
"bandwidth_in_gbps": "10"
}
# result = mgmt_client.express_route_circuits.create_or_update(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME, parameters=BODY)
# result = result.result()
#--------------------------------------------------------------------------
# /ExpressRouteCircuits/get/Get ExpressRoute Circuit Peering Traffic Stats[get]
#--------------------------------------------------------------------------
print("Get ExpressRoute Circuit Peering Traffic Stats")
result = mgmt_client.express_route_circuits.get_peering_stats(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME, peering_name=PEERING_NAME)
#--------------------------------------------------------------------------
# /ExpressRouteCircuits/get/Get ExpressRoute Circuit Traffic Stats[get]
#--------------------------------------------------------------------------
print("Get ExpressRoute Circuit Traffic Stats")
result = mgmt_client.express_route_circuits.get_stats(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME)
#--------------------------------------------------------------------------
# /ExpressRouteCircuits/get/Get ExpressRouteCircuit[get]
#--------------------------------------------------------------------------
print("Get ExpressRouteCircuit")
result = mgmt_client.express_route_circuits.get(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME)
#--------------------------------------------------------------------------
# /ExpressRouteCircuits/get/List ExpressRouteCircuits in a resource group[get]
#--------------------------------------------------------------------------
print("List ExpressRouteCircuits in a resource group")
result = mgmt_client.express_route_circuits.list(resource_group_name=RESOURCE_GROUP)
#--------------------------------------------------------------------------
# /ExpressRouteCircuits/get/List ExpressRouteCircuits in a subscription[get]
#--------------------------------------------------------------------------
print("List ExpressRouteCircuits in a subscription")
result = mgmt_client.express_route_circuits.list_all()
#--------------------------------------------------------------------------
# Disabled - not sure what device path should be
# /ExpressRouteCircuits/post/List Route Table Summary[post]
#--------------------------------------------------------------------------
print("List Route Table Summary")
# result = mgmt_client.express_route_circuits.list_routes_table_summary(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME, peering_name=PEERING_NAME, device_path=DEVICE_PATH)
# result = result.result()
#--------------------------------------------------------------------------
# Disabled - not sure what device path should be
# /ExpressRouteCircuits/post/List Route Tables[post]
#--------------------------------------------------------------------------
print("List Route Tables")
# result = mgmt_client.express_route_circuits.list_routes_table(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME, peering_name=PEERING_NAME, device_path=DEVICE_PATH)
# result = result.result()
#--------------------------------------------------------------------------
# Disabled - not sure what device path should be
# /ExpressRouteCircuits/post/List ARP Table[post]
#--------------------------------------------------------------------------
print("List ARP Table")
# result = mgmt_client.express_route_circuits.list_arp_table(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME, peering_name=PEERING_NAME, device_path=DEVICE_PATH)
# result = result.result()
#--------------------------------------------------------------------------
# /ExpressRouteCircuits/patch/Update Express Route Circuit Tags[patch]
#--------------------------------------------------------------------------
print("Update Express Route Circuit Tags")
TAGS = {
"tag1": "value1",
"tag2": "value2"
}
result = mgmt_client.express_route_circuits.update_tags(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME, tags=TAGS)
#--------------------------------------------------------------------------
# Azure Error: AnotherOperationInProgress
# /ExpressRouteCircuits/delete/Delete ExpressRouteCircuit[delete]
#--------------------------------------------------------------------------
print("Delete ExpressRouteCircuit")
# result = mgmt_client.express_route_circuits.delete(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME)
# result = result.result()
| 44.95288 | 186 | 0.548684 |
import os
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.resource import ResourceManagementClient
from azure.common.credentials import ServicePrincipalCredentials
SUBSCRIPTION_ID = os.environ['AZURE_SUBSCRIPTION_ID']
TENANT_ID = os.environ['AZURE_TENANT']
CLIENT_ID = os.environ['AZURE_CLIENT_ID']
CLIENT_SECRET = os.environ['AZURE_SECRET']
AZURE_LOCATION = 'eastus'
RESOURCE_GROUP = "myResourceGroup"
CIRCUIT_NAME = "myCircuit"
PEERING_NAME = "AzurePrivatePeering"
EXPRESS_ROUTE_PORT_NAME = "myExpressRoutePort"
DEVICE_PATH = "myDevicePath"
credentials = ServicePrincipalCredentials(
client_id=CLIENT_ID,
secret=CLIENT_SECRET,
tenant=TENANT_ID
)
mgmt_client = NetworkManagementClient(credentials, SUBSCRIPTION_ID)
resource_client = ResourceManagementClient(credentials, SUBSCRIPTION_ID)
print("Creating Resource Group")
resource_client.resource_groups.create_or_update(resource_group_name=RESOURCE_GROUP, parameters={ 'location': AZURE_LOCATION })
print("Create ExpressRouteCircuit")
BODY = {
"sku": {
"name": "Standard_MeteredData",
"tier": "Standard",
"family": "MeteredData"
},
"location": AZURE_LOCATION,
"authorizations": [],
"peerings": [],
"allow_classic_operations": False,
"service_provider_properties": {
"service_provider_name": "Equinix",
"peering_location": "Silicon Valley",
"bandwidth_in_mbps": "200"
}
}
result = mgmt_client.express_route_circuits.create_or_update(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME, parameters=BODY)
result = result.result()
print("Create ExpressRouteCircuit Peerings")
BODY = {
"peer_asn": "200",
"primary_peer_address_prefix": "192.168.16.252/30",
"secondary_peer_address_prefix": "192.168.18.252/30",
"vlan_id": "200"
}
result = mgmt_client.express_route_circuit_peerings.create_or_update(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME, peering_name=PEERING_NAME, peering_parameters=BODY)
result = result.result()
# /ExpressRouteCircuits/put/Create ExpressRouteCircuit on ExpressRoutePort[put]
#--------------------------------------------------------------------------
print("Create ExpressRouteCircuit on ExpressRoutePort")
BODY = {
"location": AZURE_LOCATION,
"sku": {
"name": "Premium_MeteredData",
"tier": "Premium",
"family": "MeteredData"
},
"express_route_port": {
"id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Network/expressRoutePorts/" + EXPRESS_ROUTE_PORT_NAME
},
"bandwidth_in_gbps": "10"
}
# result = mgmt_client.express_route_circuits.create_or_update(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME, parameters=BODY)
# result = result.result()
#--------------------------------------------------------------------------
# /ExpressRouteCircuits/get/Get ExpressRoute Circuit Peering Traffic Stats[get]
#--------------------------------------------------------------------------
print("Get ExpressRoute Circuit Peering Traffic Stats")
result = mgmt_client.express_route_circuits.get_peering_stats(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME, peering_name=PEERING_NAME)
#--------------------------------------------------------------------------
# /ExpressRouteCircuits/get/Get ExpressRoute Circuit Traffic Stats[get]
#--------------------------------------------------------------------------
print("Get ExpressRoute Circuit Traffic Stats")
result = mgmt_client.express_route_circuits.get_stats(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME)
#--------------------------------------------------------------------------
# /ExpressRouteCircuits/get/Get ExpressRouteCircuit[get]
#--------------------------------------------------------------------------
print("Get ExpressRouteCircuit")
result = mgmt_client.express_route_circuits.get(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME)
#--------------------------------------------------------------------------
# /ExpressRouteCircuits/get/List ExpressRouteCircuits in a resource group[get]
#--------------------------------------------------------------------------
print("List ExpressRouteCircuits in a resource group")
result = mgmt_client.express_route_circuits.list(resource_group_name=RESOURCE_GROUP)
#--------------------------------------------------------------------------
# /ExpressRouteCircuits/get/List ExpressRouteCircuits in a subscription[get]
#--------------------------------------------------------------------------
print("List ExpressRouteCircuits in a subscription")
result = mgmt_client.express_route_circuits.list_all()
#--------------------------------------------------------------------------
# Disabled - not sure what device path should be
# /ExpressRouteCircuits/post/List Route Table Summary[post]
#--------------------------------------------------------------------------
print("List Route Table Summary")
# result = mgmt_client.express_route_circuits.list_routes_table_summary(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME, peering_name=PEERING_NAME, device_path=DEVICE_PATH)
# result = result.result()
#--------------------------------------------------------------------------
# Disabled - not sure what device path should be
# /ExpressRouteCircuits/post/List Route Tables[post]
#--------------------------------------------------------------------------
print("List Route Tables")
# result = mgmt_client.express_route_circuits.list_routes_table(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME, peering_name=PEERING_NAME, device_path=DEVICE_PATH)
# result = result.result()
#--------------------------------------------------------------------------
# Disabled - not sure what device path should be
# /ExpressRouteCircuits/post/List ARP Table[post]
#--------------------------------------------------------------------------
print("List ARP Table")
# result = mgmt_client.express_route_circuits.list_arp_table(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME, peering_name=PEERING_NAME, device_path=DEVICE_PATH)
# result = result.result()
#--------------------------------------------------------------------------
# /ExpressRouteCircuits/patch/Update Express Route Circuit Tags[patch]
#--------------------------------------------------------------------------
print("Update Express Route Circuit Tags")
TAGS = {
"tag1": "value1",
"tag2": "value2"
}
result = mgmt_client.express_route_circuits.update_tags(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME, tags=TAGS)
#--------------------------------------------------------------------------
# Azure Error: AnotherOperationInProgress
# /ExpressRouteCircuits/delete/Delete ExpressRouteCircuit[delete]
#--------------------------------------------------------------------------
print("Delete ExpressRouteCircuit")
# result = mgmt_client.express_route_circuits.delete(resource_group_name=RESOURCE_GROUP, circuit_name=CIRCUIT_NAME)
# result = result.result()
| true | true |
1c2bc1ce0f7b96e0e21029da273c24947ff3b10f | 655 | py | Python | Lecture/Kapitel 9 - Seite 230 - Einsatzbereit mit TensorFlow.py | PhilippMatthes/tensorflow-playground | b5fee6e5f5044dc5cbcd54529d559388a3df7813 | [
"MIT"
] | null | null | null | Lecture/Kapitel 9 - Seite 230 - Einsatzbereit mit TensorFlow.py | PhilippMatthes/tensorflow-playground | b5fee6e5f5044dc5cbcd54529d559388a3df7813 | [
"MIT"
] | null | null | null | Lecture/Kapitel 9 - Seite 230 - Einsatzbereit mit TensorFlow.py | PhilippMatthes/tensorflow-playground | b5fee6e5f5044dc5cbcd54529d559388a3df7813 | [
"MIT"
] | null | null | null | import tensorflow as tf
x = tf.Variable(3, name="x")
y = tf.Variable(4, name="y")
f = x * x * y + y + 2
with tf.Session() as sess:
x.initializer.run()
y.initializer.run()
result1 = f.eval()
init = tf.global_variables_initializer()
with tf.Session() as sess:
init.run()
result2 = f.eval()
print(result1, result2)
x1 = tf.Variable(1)
print(x1.graph is tf.get_default_graph())
graph = tf.Graph()
with graph.as_default():
x2 = tf.Variable(2)
print(x2.graph is tf.get_default_graph())
print(x2.graph is graph)
w = tf.constant(3)
x = w + 2
y = x + 5
z = x * 3
with tf.Session() as sess:
print(y.eval())
print(z.eval())
| 17.236842 | 41 | 0.632061 | import tensorflow as tf
x = tf.Variable(3, name="x")
y = tf.Variable(4, name="y")
f = x * x * y + y + 2
with tf.Session() as sess:
x.initializer.run()
y.initializer.run()
result1 = f.eval()
init = tf.global_variables_initializer()
with tf.Session() as sess:
init.run()
result2 = f.eval()
print(result1, result2)
x1 = tf.Variable(1)
print(x1.graph is tf.get_default_graph())
graph = tf.Graph()
with graph.as_default():
x2 = tf.Variable(2)
print(x2.graph is tf.get_default_graph())
print(x2.graph is graph)
w = tf.constant(3)
x = w + 2
y = x + 5
z = x * 3
with tf.Session() as sess:
print(y.eval())
print(z.eval())
| true | true |
1c2bc1e4c4d14eabfd6f1d197618b21ae3dcb4be | 1,823 | py | Python | software/patterns/texture.py | mayhem/led-chandelier | 899caa8d81e6aac6e954f78b4f5b4ab101bf5257 | [
"MIT"
] | 2 | 2018-09-20T08:36:11.000Z | 2019-08-25T20:06:11.000Z | software/patterns/texture.py | mayhem/led-chandelier | 899caa8d81e6aac6e954f78b4f5b4ab101bf5257 | [
"MIT"
] | null | null | null | software/patterns/texture.py | mayhem/led-chandelier | 899caa8d81e6aac6e954f78b4f5b4ab101bf5257 | [
"MIT"
] | 1 | 2020-12-12T18:21:18.000Z | 2020-12-12T18:21:18.000Z | #!/usr/bin/env python3
import os
import sys
import math
from colorsys import hsv_to_rgb
from hippietrap.hippietrap import HippieTrap, ALL, NUM_NODES
from hippietrap.pattern import PatternBase, run_pattern
from time import sleep, time
from random import random
from hippietrap.geometry import HippieTrapGeometry
from hippietrap.color import Color
geo = HippieTrapGeometry()
class TexturePattern(PatternBase):
PERIOD = 850
name = "texture"
def __init__(self, trap):
super(PatternBase, self).__init__()
self.trap = trap
self.z_factor = .02
self.xy_factor = .01
def circle (self, x, y):
return (int)(self.z_factor * (x * x + y * y))
def circle2 (self, x, y):
return (int)(self.z_factor * (3 * x * x + y * y))
def anticircle (self, x, y):
return (int)(self.z_factor * (x * x - y * y))
def xyfun (self, x, y):
return (int)(self.z_factor * (x * x + self.xy_factor * x * y + y * y))
def x3y3 (self, x, y):
return (int)(self.z_factor * (x * x * x + y * y * y))
def x4y4 (self, x, y):
return (int)(self.z_factor * (x * x * x * x + y * y * y * y))
def x3y3_xy (self, x, y):
try:
return (int)(self.z_factor * (x * x * x + y * y * y) / (x * y))
except:
return 0
def pattern(self):
bottles = geo.calculate_bottle_locations()
self.trap.send_entropy()
scale = 0
while True:
for bottle, coord in enumerate(bottles):
z = self.circle(coord[0], coord[1])
y = self.circle2(coord[0], coord[1])
self.trap.set_color(bottle + 1, Color(z % 255, 0 , y % 255))
if self.stop_thread:
break
scale += .01
self.z_factor += .0005
| 26.808824 | 78 | 0.560614 |
import os
import sys
import math
from colorsys import hsv_to_rgb
from hippietrap.hippietrap import HippieTrap, ALL, NUM_NODES
from hippietrap.pattern import PatternBase, run_pattern
from time import sleep, time
from random import random
from hippietrap.geometry import HippieTrapGeometry
from hippietrap.color import Color
geo = HippieTrapGeometry()
class TexturePattern(PatternBase):
PERIOD = 850
name = "texture"
def __init__(self, trap):
super(PatternBase, self).__init__()
self.trap = trap
self.z_factor = .02
self.xy_factor = .01
def circle (self, x, y):
return (int)(self.z_factor * (x * x + y * y))
def circle2 (self, x, y):
return (int)(self.z_factor * (3 * x * x + y * y))
def anticircle (self, x, y):
return (int)(self.z_factor * (x * x - y * y))
def xyfun (self, x, y):
return (int)(self.z_factor * (x * x + self.xy_factor * x * y + y * y))
def x3y3 (self, x, y):
return (int)(self.z_factor * (x * x * x + y * y * y))
def x4y4 (self, x, y):
return (int)(self.z_factor * (x * x * x * x + y * y * y * y))
def x3y3_xy (self, x, y):
try:
return (int)(self.z_factor * (x * x * x + y * y * y) / (x * y))
except:
return 0
def pattern(self):
bottles = geo.calculate_bottle_locations()
self.trap.send_entropy()
scale = 0
while True:
for bottle, coord in enumerate(bottles):
z = self.circle(coord[0], coord[1])
y = self.circle2(coord[0], coord[1])
self.trap.set_color(bottle + 1, Color(z % 255, 0 , y % 255))
if self.stop_thread:
break
scale += .01
self.z_factor += .0005
| true | true |
1c2bc29b7f66439e368f4f8ee380cb0e9f1b345d | 92,659 | py | Python | python/ccxt/async_support/wavesexchange.py | StatyMcStats/ccxt | a464ecb0c9aba1945a7ef6e558939cce8ce6c47e | [
"MIT"
] | null | null | null | python/ccxt/async_support/wavesexchange.py | StatyMcStats/ccxt | a464ecb0c9aba1945a7ef6e558939cce8ce6c47e | [
"MIT"
] | null | null | null | python/ccxt/async_support/wavesexchange.py | StatyMcStats/ccxt | a464ecb0c9aba1945a7ef6e558939cce8ce6c47e | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import AccountSuspended
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import DuplicateOrderId
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.precise import Precise
class wavesexchange(Exchange):
def describe(self):
return self.deep_extend(super(wavesexchange, self).describe(), {
'id': 'wavesexchange',
'name': 'Waves.Exchange',
'countries': ['CH'], # Switzerland
'certified': True,
'pro': False,
'has': {
'CORS': None,
'spot': True,
'margin': False,
'swap': False,
'future': False,
'option': False,
'addMargin': False,
'cancelOrder': True,
'createMarketOrder': True,
'createOrder': True,
'createReduceOnlyOrder': False,
'fetchBalance': True,
'fetchBorrowRate': False,
'fetchBorrowRateHistories': False,
'fetchBorrowRateHistory': False,
'fetchBorrowRates': False,
'fetchBorrowRatesPerSymbol': False,
'fetchClosedOrders': True,
'fetchDepositAddress': True,
'fetchFundingHistory': False,
'fetchFundingRate': False,
'fetchFundingRateHistory': False,
'fetchFundingRates': False,
'fetchIndexOHLCV': False,
'fetchLeverage': False,
'fetchLeverageTiers': False,
'fetchMarkets': True,
'fetchMarkOHLCV': False,
'fetchMyTrades': True,
'fetchOHLCV': True,
'fetchOpenOrders': True,
'fetchOrder': True,
'fetchOrderBook': True,
'fetchOrders': True,
'fetchPosition': False,
'fetchPositions': False,
'fetchPositionsRisk': False,
'fetchPremiumIndexOHLCV': False,
'fetchTicker': True,
'fetchTrades': True,
'fetchTransfer': False,
'fetchTransfers': False,
'reduceMargin': False,
'setLeverage': False,
'setMarginMode': False,
'setPositionMode': False,
'signIn': True,
'transfer': False,
'withdraw': True,
},
'timeframes': {
'1m': '1m',
'5m': '5m',
'15m': '15m',
'30m': '30m',
'1h': '1h',
'2h': '2h',
'3h': '3h',
'4h': '4h',
'6h': '6h',
'12h': '12h',
'1d': '1d',
'1w': '1w',
'1M': '1M',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/84547058-5fb27d80-ad0b-11ea-8711-78ac8b3c7f31.jpg',
'test': {
'matcher': 'https://matcher-testnet.waves.exchange',
'node': 'https://nodes-testnet.wavesnodes.com',
'public': 'https://api-testnet.wavesplatform.com/v0',
'private': 'https://api-testnet.waves.exchange/v1',
'forward': 'https://testnet.waves.exchange/api/v1/forward/matcher',
'market': 'https://testnet.waves.exchange/api/v1/forward/marketdata/api/v1',
},
'api': {
'matcher': 'https://matcher.waves.exchange',
'node': 'https://nodes.waves.exchange',
'public': 'https://api.wavesplatform.com/v0',
'private': 'https://api.waves.exchange/v1',
'forward': 'https://waves.exchange/api/v1/forward/matcher',
'market': 'https://waves.exchange/api/v1/forward/marketdata/api/v1',
},
'doc': 'https://docs.waves.exchange',
'www': 'https://waves.exchange',
},
'api': {
'matcher': {
'get': [
'matcher',
'matcher/settings',
'matcher/settings/rates',
'matcher/balance/reserved/{publicKey}',
'matcher/debug/allSnashotOffsets',
'matcher/debug/currentOffset',
'matcher/debug/lastOffset',
'matcher/debug/oldestSnapshotOffset',
'matcher/orderbook',
'matcher/orderbook/{amountAsset}/{priceAsset}',
'matcher/orderbook/{baseId}/{quoteId}/publicKey/{publicKey}',
'matcher/orderbook/{baseId}/{quoteId}/{orderId}',
'matcher/orderbook/{baseId}/{quoteId}/info',
'matcher/orderbook/{baseId}/{quoteId}/status',
'matcher/orderbook/{baseId}/{quoteId}/tradeableBalance/{address}',
'matcher/orderbook/{publicKey}',
'matcher/orderbook/{publicKey}/{orderId}',
'matcher/orders/{address}',
'matcher/orders/{address}/{orderId}',
'matcher/transactions/{orderId}',
],
'post': [
'matcher/orderbook',
'matcher/orderbook/market',
'matcher/orderbook/cancel',
'matcher/orderbook/{baseId}/{quoteId}/cancel',
'matcher/orderbook/{amountAsset}/{priceAsset}/calculateFee',
'matcher/debug/saveSnapshots',
'matcher/orders/{address}/cancel',
'matcher/orders/cancel/{orderId}',
],
'delete': [
'matcher/orderbook/{baseId}/{quoteId}',
'matcher/settings/rates/{assetId}',
],
'put': [
'matcher/settings/rates/{assetId}',
],
},
'node': {
'get': [
'addresses',
'addresses/balance/{address}',
'addresses/balance/{address}/{confirmations}',
'addresses/balance/details/{address}',
'addresses/data/{address}',
'addresses/data/{address}/{key}',
'addresses/effectiveBalance/{address}',
'addresses/effectiveBalance/{address}/{confirmations}',
'addresses/publicKey/{publicKey}',
'addresses/scriptInfo/{address}',
'addresses/scriptInfo/{address}/meta',
'addresses/seed/{address}',
'addresses/seq/{from}/{to}',
'addresses/validate/{address}',
'alias/by-address/{address}',
'alias/by-alias/{alias}',
'assets/{assetId}/distribution/{height}/{limit}',
'assets/balance/{address}',
'assets/balance/{address}/{assetId}',
'assets/details/{assetId}',
'assets/nft/{address}/limit/{limit}',
'blockchain/rewards',
'blockchain/rewards/height',
'blocks/address/{address}/{from}/{to}/',
'blocks/at/{height}',
'blocks/delay/{signature}/{blockNum}',
'blocks/first',
'blocks/headers/last',
'blocks/headers/seq/{from}/{to}',
'blocks/height',
'blocks/height/{signature}',
'blocks/last',
'blocks/seq/{from}/{to}',
'blocks/signature/{signature}',
'consensus/algo',
'consensus/basetarget',
'consensus/basetarget/{blockId}',
'consensus/{generatingbalance}/address',
'consensus/generationsignature',
'consensus/generationsignature/{blockId}',
'debug/balances/history/{address}',
'debug/blocks/{howMany}',
'debug/configInfo',
'debug/historyInfo',
'debug/info',
'debug/minerInfo',
'debug/portfolios/{address}',
'debug/state',
'debug/stateChanges/address/{address}',
'debug/stateChanges/info/{id}',
'debug/stateWaves/{height}',
'leasing/active/{address}',
'node/state',
'node/version',
'peers/all',
'peers/blacklisted',
'peers/connected',
'peers/suspended',
'transactions/address/{address}/limit/{limit}',
'transactions/info/{id}',
'transactions/status',
'transactions/unconfirmed',
'transactions/unconfirmed/info/{id}',
'transactions/unconfirmed/size',
'utils/seed',
'utils/seed/{length}',
'utils/time',
'wallet/seed',
],
'post': [
'addresses',
'addresses/data/{address}',
'addresses/sign/{address}',
'addresses/signText/{address}',
'addresses/verify/{address}',
'addresses/verifyText/{address}',
'debug/blacklist',
'debug/print',
'debug/rollback',
'debug/validate',
'node/stop',
'peers/clearblacklist',
'peers/connect',
'transactions/broadcast',
'transactions/calculateFee',
'tranasctions/sign',
'transactions/sign/{signerAddress}',
'tranasctions/status',
'utils/hash/fast',
'utils/hash/secure',
'utils/script/compileCode',
'utils/script/compileWithImports',
'utils/script/decompile',
'utils/script/estimate',
'utils/sign/{privateKey}',
'utils/transactionsSerialize',
],
'delete': [
'addresses/{address}',
'debug/rollback-to/{signature}',
],
},
'public': {
'get': [
'assets',
'pairs',
'candles/{baseId}/{quoteId}',
'transactions/exchange',
],
},
'private': {
'get': [
'deposit/addresses/{currency}',
'deposit/addresses/{currency}/{platform}',
'platforms',
'deposit/currencies',
'withdraw/currencies',
'withdraw/addresses/{currency}/{address}',
],
'post': [
'oauth2/token',
],
},
'forward': {
'get': [
'matcher/orders/{address}', # can't get the orders endpoint to work with the matcher api
'matcher/orders/{address}/{orderId}',
],
'post': [
'matcher/orders/{wavesAddress}/cancel',
],
},
'market': {
'get': [
'tickers',
],
},
},
'currencies': {
'WX': {'id': 'EMAMLxDnv3xiz8RXg8Btj33jcEw3wLczL3JKYYmuubpc', 'numericId': None, 'code': 'WX', 'precision': 8},
},
'options': {
'allowedCandles': 1440,
'accessToken': None,
'createMarketBuyOrderRequiresPrice': True,
'matcherPublicKey': None,
'quotes': None,
'createOrderDefaultExpiry': 2419200000, # 60 * 60 * 24 * 28 * 1000
'wavesAddress': None,
'withdrawFeeUSDN': 7420,
'withdrawFeeWAVES': 100000,
'wavesPrecision': 8,
'messagePrefix': 'W', # W for production, T for testnet
'networks': {
'ERC20': 'ETH',
'BEP20': 'BSC',
},
'reverseNetworks': {
'ETH': 'ERC20',
'BSC': 'BEP20',
},
},
'commonCurrencies': {
'EGG': 'Waves Ducks',
},
'requiresEddsa': True,
'exceptions': {
'3147270': InsufficientFunds, # https://github.com/wavesplatform/matcher/wiki/List-of-all-errors
'112': InsufficientFunds,
'4': ExchangeError,
'13': ExchangeNotAvailable,
'14': ExchangeNotAvailable,
'3145733': AccountSuspended,
'3148040': DuplicateOrderId,
'3148801': AuthenticationError,
'9440512': AuthenticationError,
'9440771': BadSymbol,
'9441026': InvalidOrder,
'9441282': InvalidOrder,
'9441286': InvalidOrder,
'9441295': InvalidOrder,
'9441540': InvalidOrder,
'9441542': InvalidOrder,
'106954752': AuthenticationError,
'106954769': AuthenticationError,
'106957828': AuthenticationError,
'106960131': AuthenticationError,
'106981137': AuthenticationError,
'9437193': OrderNotFound,
'1048577': BadRequest,
'1051904': AuthenticationError,
},
})
def set_sandbox_mode(self, enabled):
self.options['messagePrefix'] = 'T' if enabled else 'W'
return super(wavesexchange, self).set_sandbox_mode(enabled)
async def get_fees_for_asset(self, symbol, side, amount, price, params={}):
await self.load_markets()
market = self.market(symbol)
amount = self.amount_to_precision(symbol, amount)
price = self.price_to_precision(symbol, price)
request = self.extend({
'amountAsset': market['baseId'],
'priceAsset': market['quoteId'],
'orderType': side,
'amount': amount,
'price': price,
}, params)
return await self.matcherPostMatcherOrderbookAmountAssetPriceAssetCalculateFee(request)
async def calculate_fee(self, symbol, type, side, amount, price, takerOrMaker='taker', params={}):
response = await self.get_fees_for_asset(symbol, side, amount, price)
# {
# "base":{
# "feeAssetId":"WAVES",
# "matcherFee":"1000000"
# },
# "discount":{
# "feeAssetId":"EMAMLxDnv3xiz8RXg8Btj33jcEw3wLczL3JKYYmuubpc",
# "matcherFee":"4077612"
# }
# }
isDiscountFee = self.safe_value(params, 'isDiscountFee', False)
mode = None
if isDiscountFee:
mode = self.safe_value(response, 'discount')
else:
mode = self.safe_value(response, 'base')
matcherFee = self.safe_string(mode, 'matcherFee')
feeAssetId = self.safe_string(mode, 'feeAssetId')
feeAsset = self.safe_currency_code(feeAssetId)
adjustedMatcherFee = self.currency_from_precision(feeAsset, matcherFee)
amountAsString = self.number_to_string(amount)
priceAsString = self.number_to_string(price)
feeCost = self.fee_to_precision(symbol, self.parse_number(adjustedMatcherFee))
feeRate = Precise.string_div(adjustedMatcherFee, Precise.string_mul(amountAsString, priceAsString))
return {
'type': takerOrMaker,
'currency': feeAsset,
'rate': self.parse_number(feeRate),
'cost': self.parse_number(feeCost),
}
async def get_quotes(self):
quotes = self.safe_value(self.options, 'quotes')
if quotes:
return quotes
else:
# currencies can have any name because you can create you own token
# as a result someone can create a fake token called BTC
# we use self mapping to determine the real tokens
# https://docs.waves.exchange/en/waves-matcher/matcher-api#asset-pair
response = await self.matcherGetMatcherSettings()
# {
# "orderVersions": [
# 1,
# 2,
# 3
# ],
# "success": True,
# "matcherPublicKey": "9cpfKN9suPNvfeUNphzxXMjcnn974eme8ZhWUjaktzU5",
# "orderFee": {
# "dynamic": {
# "baseFee": 300000,
# "rates": {
# "34N9YcEETLWn93qYQ64EsP1x89tSruJU44RrEMSXXEPJ": 1.22639597,
# "62LyMjcr2DtiyF5yVXFhoQ2q414VPPJXjsNYp72SuDCH": 0.00989643,
# "HZk1mbfuJpmxU1Fs4AX5MWLVYtctsNcg6e2C6VKqK8zk": 0.0395674,
# "8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS": 0.00018814,
# "4LHHvYGNKJUg5hj65aGD5vgScvCBmLpdRFtjokvCjSL8": 26.19721262,
# "474jTeYx2r2Va35794tCScAXWJG9hU2HcgxzMowaZUnu": 0.00752978,
# "DG2xFkPdDwKUoBkzGAhQtLpSGzfXLiCYPEzeKH2Ad24p": 1.84575,
# "B3uGHFRpSUuGEDWjqB9LWWxafQj8VTvpMucEyoxzws5H": 0.02330273,
# "zMFqXuoyrn5w17PFurTqxB7GsS71fp9dfk6XFwxbPCy": 0.00721412,
# "5WvPKSJXzVE2orvbkJ8wsQmmQKqTv9sGBPksV4adViw3": 0.02659103,
# "WAVES": 1,
# "BrjUWjndUanm5VsJkbUip8VRYy6LWJePtxya3FNv4TQa": 0.03433583
# }
# }
# },
# "networkByte": 87,
# "matcherVersion": "2.1.3.5",
# "status": "SimpleResponse",
# "priceAssets": [
# "Ft8X1v1LTa1ABafufpaCWyVj8KkaxUWE6xBhW6sNFJck",
# "DG2xFkPdDwKUoBkzGAhQtLpSGzfXLiCYPEzeKH2Ad24p",
# "34N9YcEETLWn93qYQ64EsP1x89tSruJU44RrEMSXXEPJ",
# "Gtb1WRznfchDnTh37ezoDTJ4wcoKaRsKqKjJjy7nm2zU",
# "2mX5DzVKWrAJw8iwdJnV2qtoeVG9h5nTDpTqC1wb1WEN",
# "8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS",
# "WAVES",
# "474jTeYx2r2Va35794tCScAXWJG9hU2HcgxzMowaZUnu",
# "zMFqXuoyrn5w17PFurTqxB7GsS71fp9dfk6XFwxbPCy",
# "62LyMjcr2DtiyF5yVXFhoQ2q414VPPJXjsNYp72SuDCH",
# "HZk1mbfuJpmxU1Fs4AX5MWLVYtctsNcg6e2C6VKqK8zk",
# "B3uGHFRpSUuGEDWjqB9LWWxafQj8VTvpMucEyoxzws5H",
# "5WvPKSJXzVE2orvbkJ8wsQmmQKqTv9sGBPksV4adViw3",
# "BrjUWjndUanm5VsJkbUip8VRYy6LWJePtxya3FNv4TQa",
# "4LHHvYGNKJUg5hj65aGD5vgScvCBmLpdRFtjokvCjSL8"
# ]
# }
quotes = {}
priceAssets = self.safe_value(response, 'priceAssets')
for i in range(0, len(priceAssets)):
quotes[priceAssets[i]] = True
self.options['quotes'] = quotes
return quotes
async def fetch_markets(self, params={}):
response = await self.marketGetTickers()
#
# [
# {
# "symbol": "WAVES/BTC",
# "amountAssetID": "WAVES",
# "amountAssetName": "Waves",
# "amountAssetDecimals": 8,
# "amountAssetTotalSupply": "106908766.00000000",
# "amountAssetMaxSupply": "106908766.00000000",
# "amountAssetCirculatingSupply": "106908766.00000000",
# "priceAssetID": "8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS",
# "priceAssetName": "WBTC",
# "priceAssetDecimals": 8,
# "priceAssetTotalSupply": "20999999.96007507",
# "priceAssetMaxSupply": "20999999.96007507",
# "priceAssetCirculatingSupply": "20999999.66019601",
# "24h_open": "0.00032688",
# "24h_high": "0.00033508",
# "24h_low": "0.00032443",
# "24h_close": "0.00032806",
# "24h_vwap": "0.00032988",
# "24h_volume": "42349.69440104",
# "24h_priceVolume": "13.97037207",
# "timestamp":1640232379124
# }
# ...
# ]
#
result = []
for i in range(0, len(response)):
entry = response[i]
baseId = self.safe_string(entry, 'amountAssetID')
quoteId = self.safe_string(entry, 'priceAssetID')
id = baseId + '/' + quoteId
marketId = self.safe_string(entry, 'symbol')
base, quote = marketId.split('/')
base = self.safe_currency_code(base)
quote = self.safe_currency_code(quote)
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': None,
'baseId': baseId,
'quoteId': quoteId,
'settleId': None,
'type': 'spot',
'spot': True,
'margin': False,
'swap': False,
'future': False,
'option': False,
'active': None,
'contract': False,
'linear': None,
'inverse': None,
'contractSize': None,
'expiry': None,
'expiryDatetime': None,
'strike': None,
'optionType': None,
'precision': {
'amount': self.safe_integer(entry, 'amountAssetDecimals'),
'price': self.safe_integer(entry, 'priceAssetDecimals'),
},
'limits': {
'leverage': {
'min': None,
'max': None,
},
'amount': {
'min': None,
'max': None,
},
'price': {
'min': None,
'max': None,
},
'cost': {
'min': None,
'max': None,
},
},
'info': entry,
})
return result
async def fetch_order_book(self, symbol, limit=None, params={}):
await self.load_markets()
market = self.market(symbol)
request = self.extend({
'amountAsset': market['baseId'],
'priceAsset': market['quoteId'],
}, params)
response = await self.matcherGetMatcherOrderbookAmountAssetPriceAsset(request)
timestamp = self.safe_integer(response, 'timestamp')
bids = self.parse_order_book_side(self.safe_value(response, 'bids'), market, limit)
asks = self.parse_order_book_side(self.safe_value(response, 'asks'), market, limit)
return {
'symbol': symbol,
'bids': bids,
'asks': asks,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'nonce': None,
}
def parse_order_book_side(self, bookSide, market=None, limit=None):
precision = market['precision']
wavesPrecision = self.safe_integer(self.options, 'wavesPrecision', 8)
amountPrecision = math.pow(10, precision['amount'])
difference = precision['amount'] - precision['price']
pricePrecision = math.pow(10, wavesPrecision - difference)
result = []
for i in range(0, len(bookSide)):
entry = bookSide[i]
price = self.safe_integer(entry, 'price', 0) / pricePrecision
amount = self.safe_integer(entry, 'amount', 0) / amountPrecision
if (limit is not None) and (i > limit):
break
result.append([price, amount])
return result
def check_required_keys(self):
if self.apiKey is None:
raise AuthenticationError(self.id + ' requires apiKey credential')
if self.secret is None:
raise AuthenticationError(self.id + ' requires secret credential')
apiKeyBytes = None
secretKeyBytes = None
try:
apiKeyBytes = self.base58_to_binary(self.apiKey)
except Exception as e:
raise AuthenticationError(self.id + ' apiKey must be a base58 encoded public key')
try:
secretKeyBytes = self.base58_to_binary(self.secret)
except Exception as e:
raise AuthenticationError(self.id + ' secret must be a base58 encoded private key')
hexApiKeyBytes = self.binary_to_base16(apiKeyBytes)
hexSecretKeyBytes = self.binary_to_base16(secretKeyBytes)
if len(hexApiKeyBytes) != 64:
raise AuthenticationError(self.id + ' apiKey must be a base58 encoded public key')
if len(hexSecretKeyBytes) != 64:
raise AuthenticationError(self.id + ' secret must be a base58 encoded private key')
def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
query = self.omit(params, self.extract_params(path))
isCancelOrder = path == 'matcher/orders/{wavesAddress}/cancel'
path = self.implode_params(path, params)
url = self.urls['api'][api] + '/' + path
queryString = self.urlencode_with_array_repeat(query)
if (api == 'private') or (api == 'forward'):
headers = {
'Accept': 'application/json',
}
accessToken = self.safe_string(self.options, 'accessToken')
if accessToken:
headers['Authorization'] = 'Bearer ' + accessToken
if method == 'POST':
headers['content-type'] = 'application/json'
else:
headers['content-type'] = 'application/x-www-form-urlencoded'
if isCancelOrder:
body = self.json([query['orderId']])
queryString = ''
if len(queryString) > 0:
url += '?' + queryString
elif api == 'matcher':
if method == 'POST':
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
body = self.json(query)
else:
headers = query
else:
if method == 'POST':
headers = {
'content-type': 'application/json',
}
body = self.json(query)
else:
headers = {
'content-type': 'application/x-www-form-urlencoded',
}
if len(queryString) > 0:
url += '?' + queryString
return {'url': url, 'method': method, 'body': body, 'headers': headers}
async def sign_in(self, params={}):
if not self.safe_string(self.options, 'accessToken'):
prefix = 'ffffff01'
expiresDelta = 60 * 60 * 24 * 7
seconds = self.sum(self.seconds(), expiresDelta)
seconds = str(seconds)
clientId = 'waves.exchange'
# W for production, T for testnet
defaultMessagePrefix = self.safe_string(self.options, 'messagePrefix', 'W')
message = defaultMessagePrefix + ':' + clientId + ':' + seconds
messageHex = self.binary_to_base16(self.encode(message))
payload = prefix + messageHex
hexKey = self.binary_to_base16(self.base58_to_binary(self.secret))
signature = self.eddsa(payload, hexKey, 'ed25519')
request = {
'grant_type': 'password',
'scope': 'general',
'username': self.apiKey,
'password': seconds + ':' + signature,
'client_id': clientId,
}
response = await self.privatePostOauth2Token(request)
# {access_token: 'eyJhbGciOXJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzaWciOiJiaTZiMVhMQlo0M1Q4QmRTSlVSejJBZGlQdVlpaFZQYVhhVjc4ZGVIOEpTM3M3NUdSeEU1VkZVOE5LRUI0UXViNkFHaUhpVFpuZ3pzcnhXdExUclRvZTgiLCJhIjoiM1A4VnpMU2EyM0VXNUNWY2tIYlY3ZDVCb043NWZGMWhoRkgiLCJuYiI6IlciLCJ1c2VyX25hbWUiOiJBSFhuOG5CQTRTZkxRRjdoTFFpU24xNmt4eWVoaml6QkdXMVRkcm1TWjFnRiIsInNjb3BlIjpbImdlbmVyYWwiXSwibHQiOjYwNDc5OSwicGsiOiJBSFhuOG5CQTRTZkxRRjdoTFFpU24xNmt4eWVoaml6QkdXMVRkcm1TWjFnRiIsImV4cCI6MTU5MTk3NTA1NywiZXhwMCI6MTU5MTk3NTA1NywianRpIjoiN2JhOTUxMTMtOGI2MS00NjEzLTlkZmYtNTEwYTc0NjlkOWI5IiwiY2lkIjoid2F2ZXMuZXhjaGFuZ2UifQ.B-XwexBnUAzbWknVN68RKT0ZP5w6Qk1SKJ8usL3OIwDEzCUUX9PjW-5TQHmiCRcA4oft8lqXEiCwEoNfsblCo_jTpRo518a1vZkIbHQk0-13Dm1K5ewGxfxAwBk0g49odcbKdjl64TN1yM_PO1VtLVuiTeZP-XF-S42Uj-7fcO-r7AulyQLuTE0uo-Qdep8HDCk47rduZwtJOmhFbCCnSgnLYvKWy3CVTeldsR77qxUY-vy8q9McqeP7Id-_MWnsob8vWXpkeJxaEsw1Fke1dxApJaJam09VU8EB3ZJWpkT7V8PdafIrQGeexx3jhKKxo7rRb4hDV8kfpVoCgkvFan',
# token_type: 'bearer',
# refresh_token: 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzaWciOiJiaTZiMVhMQlo0M1Q4QmRTSlVSejJBZGlQdVlpaFZQYVhhVjc4ZGVIOEpTM3M3NUdSeEU1VkZVOE5LRUI0UXViNkFHaUhpVFpuZ3pzcnhXdExUclRvZTgiLCJhIjoiM1A4VnpMU2EyM0VXNUNWY2tIYlY3ZDVCb043NWZGMWhoRkgiLCJuYiI6IlciLCJ1c2VyX25hbWUiOiJBSFhuOG5CQTRTZkxRRjdoTFFpU24xNmt4eWVoaml6QkdXMVRkcm1TWjFnRiIsInNjb3BlIjpbImdlbmVyYWwiXSwiYXRpIjoiN2JhOTUxMTMtOGI2MS00NjEzLTlkZmYtNTEwYTc0NjlkXWI5IiwibHQiOjYwNDc5OSwicGsiOiJBSFhuOG5CQTRTZkxRRjdoTFFpU24xNmt4eWVoaml6QkdXMVRkcm1TWjFnRiIsImV4cCI6MTU5Mzk2MjI1OCwiZXhwMCI6MTU5MTk3NTA1NywianRpIjoiM2MzZWRlMTktNjI5My00MTNlLWJmMWUtZTRlZDZlYzUzZTgzIiwiY2lkIjoid2F2ZXMuZXhjaGFuZ2UifQ.gD1Qj0jfqayfZpBvNY0t3ccMyK5hdbT7dY-_5L6LxwV0Knan4ndEtvygxlTOczmJUKtnA4T1r5GBFgNMZTvtViKZIbqZNysEg2OY8UxwDaF4VPeGJLg_QXEnn8wBeBQdyMafh9UQdwD2ci7x-saM4tOAGmncAygfTDxy80201gwDhfAkAGerb9kL00oWzSJScldxu--pNLDBUEHZt52MSEel10HGrzvZkkvvSh67vcQo5TOGb5KG6nh65UdJCwr41AVz4fbQPP-N2Nkxqy0TE_bqVzZxExXgvcS8TS0Z82T3ijJa_ct7B9wblpylBnvmyj3VycUzufD6uy8MUGq32D',
# expires_in: 604798,
# scope: 'general'}
self.options['accessToken'] = self.safe_string(response, 'access_token')
return self.options['accessToken']
def parse_ticker(self, ticker, market=None):
#
# {
# "__type":"pair",
# "data":{
# "firstPrice":0.00012512,
# "lastPrice":0.00012441,
# "low":0.00012167,
# "high":0.00012768,
# "weightedAveragePrice":0.000124710697407246,
# "volume":209554.26356614,
# "quoteVolume":26.1336583539951,
# "volumeWaves":209554.26356614,
# "txsCount":6655
# },
# "amountAsset":"WAVES",
# "priceAsset":"8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS"
# }
#
timestamp = None
baseId = self.safe_string(ticker, 'amountAsset')
quoteId = self.safe_string(ticker, 'priceAsset')
symbol = None
if (baseId is not None) and (quoteId is not None):
marketId = baseId + '/' + quoteId
if marketId in self.markets_by_id:
market = self.markets_by_id[marketId]
else:
base = self.safe_currency_code(baseId)
quote = self.safe_currency_code(quoteId)
symbol = base + '/' + quote
if (symbol is None) and (market is not None):
symbol = market['symbol']
data = self.safe_value(ticker, 'data', {})
last = self.safe_string(data, 'lastPrice')
low = self.safe_string(data, 'low')
high = self.safe_string(data, 'high')
vwap = self.safe_string(data, 'weightedAveragePrice')
baseVolume = self.safe_string(data, 'volume')
quoteVolume = self.safe_string(data, 'quoteVolume')
open = self.safe_string(data, 'firstPrice')
return self.safe_ticker({
'symbol': symbol,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': high,
'low': low,
'bid': None,
'bidVolume': None,
'ask': None,
'askVolume': None,
'vwap': vwap,
'open': open,
'close': last,
'last': last,
'previousClose': None,
'change': None,
'percentage': None,
'average': None,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
}, market, False)
async def fetch_ticker(self, symbol, params={}):
await self.load_markets()
market = self.market(symbol)
request = {
'pairs': market['id'],
}
response = await self.publicGetPairs(self.extend(request, params))
#
# {
# "__type":"list",
# "data":[
# {
# "__type":"pair",
# "data":{
# "firstPrice":0.00012512,
# "lastPrice":0.00012441,
# "low":0.00012167,
# "high":0.00012768,
# "weightedAveragePrice":0.000124710697407246,
# "volume":209554.26356614,
# "quoteVolume":26.1336583539951,
# "volumeWaves":209554.26356614,
# "txsCount":6655
# },
# "amountAsset":"WAVES",
# "priceAsset":"8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS"
# }
# ]
# }
#
data = self.safe_value(response, 'data', [])
ticker = self.safe_value(data, 0, {})
return self.parse_ticker(ticker, market)
async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
await self.load_markets()
market = self.market(symbol)
request = {
'baseId': market['baseId'],
'quoteId': market['quoteId'],
'interval': self.timeframes[timeframe],
}
allowedCandles = self.safe_integer(self.options, 'allowedCandles', 1440)
if limit is None:
limit = allowedCandles
limit = min(allowedCandles, limit)
duration = self.parse_timeframe(timeframe) * 1000
if since is None:
durationRoundedTimestamp = int(self.milliseconds() / duration) * duration
delta = (limit - 1) * duration
timeStart = durationRoundedTimestamp - delta
request['timeStart'] = str(timeStart)
else:
request['timeStart'] = str(since)
timeEnd = self.sum(since, duration * limit)
request['timeEnd'] = str(timeEnd)
response = await self.publicGetCandlesBaseIdQuoteId(self.extend(request, params))
#
# {
# "__type": "list",
# "data": [
# {
# "__type": "candle",
# "data": {
# "time": "2020-06-09T14:47:00.000Z",
# "open": 0.0250385,
# "close": 0.0250385,
# "high": 0.0250385,
# "low": 0.0250385,
# "volume": 0.01033012,
# "quoteVolume": 0.00025865,
# "weightedAveragePrice": 0.0250385,
# "maxHeight": 2099399,
# "txsCount": 5,
# "timeClose": "2020-06-09T14:47:59.999Z"
# }
# }
# ]
# }
#
data = self.safe_value(response, 'data', [])
result = self.parse_ohlcvs(data, market, timeframe, since, limit)
result = self.filter_future_candles(result)
lastClose = None
length = len(result)
for i in range(0, len(result)):
j = length - i - 1
entry = result[j]
open = entry[1]
if open is None:
entry[1] = lastClose
entry[2] = lastClose
entry[3] = lastClose
entry[4] = lastClose
result[j] = entry
lastClose = entry[4]
return result
def filter_future_candles(self, ohlcvs):
result = []
timestamp = self.milliseconds()
for i in range(0, len(ohlcvs)):
if ohlcvs[i][0] > timestamp:
# stop when getting data from the future
break
result.append(ohlcvs[i])
return result
def parse_ohlcv(self, ohlcv, market=None):
#
# {
# __type: 'candle',
# data: {
# time: '2020-06-05T20:46:00.000Z',
# open: 240.573975,
# close: 240.573975,
# high: 240.573975,
# low: 240.573975,
# volume: 0.01278413,
# quoteVolume: 3.075528,
# weightedAveragePrice: 240.573975,
# maxHeight: 2093895,
# txsCount: 5,
# timeClose: '2020-06-05T20:46:59.999Z'
# }
# }
#
data = self.safe_value(ohlcv, 'data', {})
return [
self.parse8601(self.safe_string(data, 'time')),
self.safe_number(data, 'open'),
self.safe_number(data, 'high'),
self.safe_number(data, 'low'),
self.safe_number(data, 'close'),
self.safe_number(data, 'volume', 0),
]
async def fetch_deposit_address(self, code, params={}):
await self.sign_in()
networks = self.safe_value(self.options, 'networks', {})
rawNetwork = self.safe_string_upper(params, 'network')
network = self.safe_string(networks, rawNetwork, rawNetwork)
params = self.omit(params, ['network'])
supportedCurrencies = await self.privateGetPlatforms()
#
# {
# "type": "list",
# "page_info": {
# "has_next_page": False,
# "last_cursor": null
# },
# "items": [
# {
# "type": "platform",
# "id": "ETH",
# "name": "Ethereum",
# "currencies": [
# "BAG",
# "BNT",
# "CRV",
# "EGG",
# "ETH",
# "EURN",
# "FL",
# "NSBT",
# "USDAP",
# "USDC",
# "USDFL",
# "USDN",
# "USDT",
# "WAVES"
# ]
# }
# ]
# }
#
currencies = {}
networksByCurrency = {}
items = self.safe_value(supportedCurrencies, 'items', [])
for i in range(0, len(items)):
entry = items[i]
currencyId = self.safe_string(entry, 'id')
innerCurrencies = self.safe_value(entry, 'currencies', [])
for j in range(0, len(innerCurrencies)):
currencyCode = self.safe_string(innerCurrencies, j)
currencies[currencyCode] = True
if not (currencyCode in networksByCurrency):
networksByCurrency[currencyCode] = {}
networksByCurrency[currencyCode][currencyId] = True
if not (code in currencies):
codes = list(currencies.keys())
raise ExchangeError(self.id + ' fetch ' + code + ' deposit address not supported. Currency code must be one of ' + ', '.join(codes))
response = None
if network is None:
request = {
'currency': code,
}
response = await self.privateGetDepositAddressesCurrency(self.extend(request, params))
else:
supportedNetworks = networksByCurrency[code]
if not (network in supportedNetworks):
supportedNetworkKeys = list(supportedNetworks.keys())
raise ExchangeError(self.id + ' ' + network + ' network ' + code + ' deposit address not supported. Network must be one of ' + ', '.join(supportedNetworkKeys))
if network == 'WAVES':
request = {
'publicKey': self.apiKey,
}
response = await self.nodeGetAddressesPublicKeyPublicKey(self.extend(request, request))
address = self.safe_string(response, 'address')
return {
'address': address,
'code': code,
'network': network,
'tag': None,
'info': response,
}
else:
request = {
'currency': code,
'platform': network,
}
response = await self.privateGetDepositAddressesCurrencyPlatform(self.extend(request, params))
#
# {
# "type": "deposit_addresses",
# "currency": {
# "type": "deposit_currency",
# "id": "ERGO",
# "waves_asset_id": "5dJj4Hn9t2Ve3tRpNGirUHy4yBK6qdJRAJYV21yPPuGz",
# "platform_id": "BSC",
# "decimals": 9,
# "status": "active",
# "allowed_amount": {
# "min": 0.001,
# "max": 100000
# },
# "fees": {
# "flat": 0,
# "rate": 0
# }
# },
# "deposit_addresses": [
# "9fRAAQjF8Yqg7qicQCL884zjimsRnuwsSavsM1rUdDaoG8mThku"
# ]
# }
currency = self.safe_value(response, 'currency')
networkId = self.safe_string(currency, 'platform_id')
reverseNetworks = self.safe_value(self.options, 'reverseNetworks', {})
unifiedNetwork = self.safe_string(reverseNetworks, networkId, networkId)
addresses = self.safe_value(response, 'deposit_addresses')
address = self.safe_string(addresses, 0)
return {
'address': address,
'code': code,
'tag': None,
'network': unifiedNetwork,
'info': response,
}
async def get_matcher_public_key(self):
# self method returns a single string
matcherPublicKey = self.safe_string(self.options, 'matcherPublicKey')
if matcherPublicKey:
return matcherPublicKey
else:
response = await self.matcherGetMatcher()
# remove trailing quotes from string response
self.options['matcherPublicKey'] = response[1:len(response) - 1]
return self.options['matcherPublicKey']
def get_asset_bytes(self, currencyId):
if currencyId == 'WAVES':
return self.number_to_be(0, 1)
else:
return self.binary_concat(self.number_to_be(1, 1), self.base58_to_binary(currencyId))
def get_asset_id(self, currencyId):
if currencyId == 'WAVES':
return ''
return currencyId
def price_to_precision(self, symbol, price):
market = self.markets[symbol]
wavesPrecision = self.safe_integer(self.options, 'wavesPrecision', 8)
difference = market['precision']['amount'] - market['precision']['price']
return int(float(self.to_precision(price, wavesPrecision - difference)))
def amount_to_precision(self, symbol, amount):
return int(float(self.to_precision(amount, self.markets[symbol]['precision']['amount'])))
def currency_to_precision(self, code, amount):
return int(float(self.to_precision(amount, self.currencies[code]['precision'])))
def from_precision(self, amount, scale):
if amount is None:
return None
precise = Precise(amount)
precise.decimals = precise.decimals + scale
precise.reduce()
return str(precise)
def to_precision(self, amount, scale):
amountString = str(amount)
precise = Precise(amountString)
precise.decimals = precise.decimals - scale
precise.reduce()
return str(precise)
def currency_from_precision(self, currency, amount):
scale = self.currencies[currency]['precision']
return self.from_precision(amount, scale)
def price_from_precision(self, symbol, price):
market = self.markets[symbol]
wavesPrecision = self.safe_integer(self.options, 'wavesPrecision', 8)
scale = wavesPrecision - market['precision']['amount'] + market['precision']['price']
return self.from_precision(price, scale)
def safe_get_dynamic(self, settings):
orderFee = self.safe_value(settings, 'orderFee')
if 'dynamic' in orderFee:
return self.safe_value(orderFee, 'dynamic')
else:
return self.safe_value(orderFee['composite']['default'], 'dynamic')
def safe_get_rates(self, dynamic):
rates = self.safe_value(dynamic, 'rates')
if rates is None:
return {'WAVES': 1}
return rates
async def create_order(self, symbol, type, side, amount, price=None, params={}):
self.check_required_dependencies()
self.check_required_keys()
await self.load_markets()
market = self.market(symbol)
matcherPublicKey = await self.get_matcher_public_key()
amountAsset = self.get_asset_id(market['baseId'])
priceAsset = self.get_asset_id(market['quoteId'])
isMarketOrder = (type == 'market')
if (isMarketOrder) and (price is None):
raise InvalidOrder(self.id + ' createOrder() requires a price argument for ' + type + ' orders to determine the max price for buy and the min price for sell')
orderType = 0 if (side == 'buy') else 1
timestamp = self.milliseconds()
defaultExpiryDelta = self.safe_integer(self.options, 'createOrderDefaultExpiry', 2419200000)
expiration = self.sum(timestamp, defaultExpiryDelta)
matcherFees = await self.get_fees_for_asset(symbol, side, amount, price)
# {
# "base":{
# "feeAssetId":"WAVES", # varies depending on the trading pair
# "matcherFee":"1000000"
# },
# "discount":{
# "feeAssetId":"EMAMLxDnv3xiz8RXg8Btj33jcEw3wLczL3JKYYmuubpc",
# "matcherFee":"4077612"
# }
# }
base = self.safe_value(matcherFees, 'base')
baseFeeAssetId = self.safe_string(base, 'feeAssetId')
baseFeeAsset = self.safe_currency_code(baseFeeAssetId)
baseMatcherFee = self.safe_string(base, 'matcherFee')
discount = self.safe_value(matcherFees, 'discount')
discountFeeAssetId = self.safe_string(discount, 'feeAssetId')
discountFeeAsset = self.safe_currency_code(discountFeeAssetId)
discountMatcherFee = self.safe_string(discount, 'matcherFee')
matcherFeeAssetId = None
matcherFee = None
# check first if user supplied asset fee is valid
if ('feeAsset' in params) or ('feeAsset' in self.options):
feeAsset = self.safe_string(params, 'feeAsset', self.safe_string(self.options, 'feeAsset'))
feeCurrency = self.currency(feeAsset)
matcherFeeAssetId = self.safe_string(feeCurrency, 'id')
balances = await self.fetch_balance()
if matcherFeeAssetId is not None:
if baseFeeAssetId != matcherFeeAssetId and discountFeeAssetId != matcherFeeAssetId:
raise InvalidOrder(self.id + ' asset fee must be ' + baseFeeAsset + ' or ' + discountFeeAsset)
matcherFeeAsset = self.safe_currency_code(matcherFeeAssetId)
rawMatcherFee = baseMatcherFee if (matcherFeeAssetId == baseFeeAssetId) else discountMatcherFee
floatMatcherFee = float(self.currency_from_precision(matcherFeeAsset, rawMatcherFee))
if (matcherFeeAsset in balances) and (balances[matcherFeeAsset]['free'] >= floatMatcherFee):
matcherFee = int(rawMatcherFee)
else:
raise InsufficientFunds(self.id + ' not enough funds of the selected asset fee')
if matcherFeeAssetId is None:
# try to the pay the fee using the base first then discount asset
floatBaseMatcherFee = float(self.currency_from_precision(baseFeeAsset, baseMatcherFee))
if (baseFeeAsset in balances) and (balances[baseFeeAsset]['free'] >= floatBaseMatcherFee):
matcherFeeAssetId = baseFeeAssetId
matcherFee = int(baseMatcherFee)
else:
floatDiscountMatcherFee = float(self.currency_from_precision(discountFeeAsset, discountMatcherFee))
if (discountFeeAsset in balances) and (balances[discountFeeAsset]['free'] >= floatDiscountMatcherFee):
matcherFeeAssetId = discountFeeAssetId
matcherFee = int(discountMatcherFee)
if matcherFeeAssetId is None:
raise InsufficientFunds(self.id + ' not enough funds on none of the eligible asset fees')
amount = self.amount_to_precision(symbol, amount)
price = self.price_to_precision(symbol, price)
byteArray = [
self.number_to_be(3, 1),
self.base58_to_binary(self.apiKey),
self.base58_to_binary(matcherPublicKey),
self.get_asset_bytes(market['baseId']),
self.get_asset_bytes(market['quoteId']),
self.number_to_be(orderType, 1),
self.number_to_be(price, 8),
self.number_to_be(amount, 8),
self.number_to_be(timestamp, 8),
self.number_to_be(expiration, 8),
self.number_to_be(matcherFee, 8),
self.get_asset_bytes(matcherFeeAssetId),
]
binary = self.binary_concat_array(byteArray)
signature = self.eddsa(self.binary_to_base16(binary), self.binary_to_base16(self.base58_to_binary(self.secret)), 'ed25519')
assetPair = {
'amountAsset': amountAsset,
'priceAsset': priceAsset,
}
body = {
'senderPublicKey': self.apiKey,
'matcherPublicKey': matcherPublicKey,
'assetPair': assetPair,
'orderType': side,
'price': price,
'amount': amount,
'timestamp': timestamp,
'expiration': expiration,
'matcherFee': int(matcherFee),
'signature': signature,
'version': 3,
}
if matcherFeeAssetId != 'WAVES':
body['matcherFeeAssetId'] = matcherFeeAssetId
#
# {
# "success":true,
# "message":{
# "version":3,
# "id":"GK5ox4RfLJFtqjQsCbDmvCya8ZhFVEUQDtF4yYuAJ6C7",
# "sender":"3P8VzLSa23EW5CVckHbV7d5BoN75fF1hhFH",
# "senderPublicKey":"AHXn8nBA4SfLQF7hLQiSn16kxyehjizBGW1TdrmSZ1gF",
# "matcherPublicKey":"9cpfKN9suPNvfeUNphzxXMjcnn974eme8ZhWUjaktzU5",
# "assetPair":{
# "amountAsset":"C1iWsKGqLwjHUndiQ7iXpdmPum9PeCDFfyXBdJJosDRS",
# "priceAsset":"WAVES"
# },
# "orderType":"buy",
# "amount":110874978,
# "price":514397851,
# "timestamp":1650473255988,
# "expiration":1652892455988,
# "matcherFee":7074571,
# "matcherFeeAssetId":"Atqv59EYzjFGuitKVnMRk6H8FukjoV3ktPorbEys25on",
# "signature":"5Vgs6mbdZJv5Ce9mdobT6fppXr6bKn5WVDbzP6mGG5jMB5jgcA2eSScwctgvY5SwPm9n1bctAAKuXtLcdHjNNie8",
# "proofs":["5Vgs6mbdZJv5Ce9mdobT6fppXr6bKn5WVDbzP6mGG5jMB5jgcA2eSScwctgvY5SwPm9n1bctAAKuXtLcdHjNNie8"]
# },
# "status":"OrderAccepted"
# }
#
if isMarketOrder:
response = await self.matcherPostMatcherOrderbookMarket(body)
value = self.safe_value(response, 'message')
return self.parse_order(value, market)
else:
response = await self.matcherPostMatcherOrderbook(body)
value = self.safe_value(response, 'message')
return self.parse_order(value, market)
async def cancel_order(self, id, symbol=None, params={}):
self.check_required_dependencies()
self.check_required_keys()
await self.sign_in()
wavesAddress = await self.get_waves_address()
response = await self.forwardPostMatcherOrdersWavesAddressCancel({
'wavesAddress': wavesAddress,
'orderId': id,
})
# {
# "success":true,
# "message":[[{"orderId":"EBpJeGM36KKFz5gTJAUKDBm89V8wqxKipSFBdU35AN3c","success":true,"status":"OrderCanceled"}]],
# "status":"BatchCancelCompleted"
# }
message = self.safe_value(response, 'message')
firstMessage = self.safe_value(message, 0)
firstOrder = self.safe_value(firstMessage, 0)
returnedId = self.safe_string(firstOrder, 'orderId')
return {
'info': response,
'id': returnedId,
'clientOrderId': None,
'timestamp': None,
'datetime': None,
'lastTradeTimestamp': None,
'symbol': symbol,
'type': None,
'side': None,
'price': None,
'amount': None,
'cost': None,
'average': None,
'filled': None,
'remaining': None,
'status': None,
'fee': None,
'trades': None,
}
async def fetch_order(self, id, symbol=None, params={}):
self.check_required_dependencies()
self.check_required_keys()
await self.load_markets()
market = None
if symbol is not None:
market = self.market(symbol)
timestamp = self.milliseconds()
byteArray = [
self.base58_to_binary(self.apiKey),
self.number_to_be(timestamp, 8),
]
binary = self.binary_concat_array(byteArray)
hexSecret = self.binary_to_base16(self.base58_to_binary(self.secret))
signature = self.eddsa(self.binary_to_base16(binary), hexSecret, 'ed25519')
request = {
'Timestamp': str(timestamp),
'Signature': signature,
'publicKey': self.apiKey,
'orderId': id,
}
response = await self.matcherGetMatcherOrderbookPublicKeyOrderId(self.extend(request, params))
return self.parse_order(response, market)
async def fetch_orders(self, symbol=None, since=None, limit=None, params={}):
self.check_required_dependencies()
self.check_required_keys()
if symbol is None:
raise ArgumentsRequired(self.id + ' fetchOrders() requires symbol argument')
await self.load_markets()
market = self.market(symbol)
timestamp = self.milliseconds()
byteArray = [
self.base58_to_binary(self.apiKey),
self.number_to_be(timestamp, 8),
]
binary = self.binary_concat_array(byteArray)
hexSecret = self.binary_to_base16(self.base58_to_binary(self.secret))
signature = self.eddsa(self.binary_to_base16(binary), hexSecret, 'ed25519')
request = {
'Accept': 'application/json',
'Timestamp': str(timestamp),
'Signature': signature,
'publicKey': self.apiKey,
'baseId': market['baseId'],
'quoteId': market['quoteId'],
}
response = await self.matcherGetMatcherOrderbookBaseIdQuoteIdPublicKeyPublicKey(self.extend(request, params))
# [{id: '3KicDeWayY2mdrRoYdCkP3gUAoUZUNT1AA6GAtWuPLfa',
# type: 'sell',
# orderType: 'limit',
# amount: 1,
# fee: 300000,
# price: 100000000,
# timestamp: 1591651254076,
# filled: 0,
# filledFee: 0,
# feeAsset: 'WAVES',
# status: 'Accepted',
# assetPair:
# {amountAsset: null,
# priceAsset: '8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS'},
# avgWeighedPrice: 0}, ...]
return self.parse_orders(response, market, since, limit)
async def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
await self.load_markets()
await self.sign_in()
market = None
if symbol is not None:
market = self.market(symbol)
address = await self.get_waves_address()
request = {
'address': address,
'activeOnly': True,
}
response = await self.forwardGetMatcherOrdersAddress(request)
return self.parse_orders(response, market, since, limit)
async def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):
await self.load_markets()
await self.sign_in()
market = None
if symbol is not None:
market = self.market(symbol)
address = await self.get_waves_address()
request = {
'address': address,
'closedOnly': True,
}
response = await self.forwardGetMatcherOrdersAddress(request)
# [
# {
# "id": "9aXcxvXai73jbAm7tQNnqaQ2PwUjdmWuyjvRTKAHsw4f",
# "type": "buy",
# "orderType": "limit",
# "amount": 23738330,
# "fee": 300000,
# "price": 3828348334,
# "timestamp": 1591926905636,
# "filled": 23738330,
# "filledFee": 300000,
# "feeAsset": "WAVES",
# "status": "Filled",
# "assetPair": {
# "amountAsset": "HZk1mbfuJpmxU1Fs4AX5MWLVYtctsNcg6e2C6VKqK8zk",
# "priceAsset": null
# },
# "avgWeighedPrice": 3828348334
# }, ...
# ]
return self.parse_orders(response, market, since, limit)
def parse_order_status(self, status):
statuses = {
'Cancelled': 'canceled',
'Accepted': 'open',
'Filled': 'closed',
'PartiallyFilled': 'open',
}
return self.safe_string(statuses, status, status)
def get_symbol_from_asset_pair(self, assetPair):
# a blank string or null can indicate WAVES
baseId = self.safe_string(assetPair, 'amountAsset', 'WAVES')
quoteId = self.safe_string(assetPair, 'priceAsset', 'WAVES')
return self.safe_currency_code(baseId) + '/' + self.safe_currency_code(quoteId)
def parse_order(self, order, market=None):
#
# createOrder
#
# {
# 'version': 3,
# 'id': 'BshyeHXDfJmTnjTdBYt371jD4yWaT3JTP6KpjpsiZepS',
# 'sender': '3P8VzLSa23EW5CVckHbV7d5BoN75fF1hhFH',
# 'senderPublicKey': 'AHXn8nBA4SfLQF7hLQiSn16kxyehjizBGW1TdrmSZ1gF',
# 'matcherPublicKey': '9cpfKN9suPNvfeUNphzxXMjcnn974eme8ZhWUjaktzU5',
# 'assetPair': {
# 'amountAsset': '474jTeYx2r2Va35794tCScAXWJG9hU2HcgxzMowaZUnu',
# 'priceAsset': 'DG2xFkPdDwKUoBkzGAhQtLpSGzfXLiCYPEzeKH2Ad24p',
# },
# 'orderType': 'buy',
# 'amount': 10000,
# 'price': 400000000,
# 'timestamp': 1599848586891,
# 'expiration': 1602267786891,
# 'matcherFee': 3008,
# 'matcherFeeAssetId': '474jTeYx2r2Va35794tCScAXWJG9hU2HcgxzMowaZUnu',
# 'signature': '3D2h8ubrhuWkXbVn4qJ3dvjmZQxLoRNfjTqb9uNpnLxUuwm4fGW2qGH6yKFe2SQPrcbgkS3bDVe7SNtMuatEJ7qy',
# 'proofs': [
# '3D2h8ubrhuWkXbVn4qJ3dvjmZQxLoRNfjTqb9uNpnLxUuwm4fGW2qGH6yKFe2SQPrcbgkS3bDVe7SNtMuatEJ7qy',
# ],
# }
#
#
# fetchOrder, fetchOrders, fetchOpenOrders, fetchClosedOrders
#
# {
# id: '81D9uKk2NfmZzfG7uaJsDtxqWFbJXZmjYvrL88h15fk8',
# type: 'buy',
# orderType: 'limit',
# amount: 30000000000,
# filled: 0,
# price: 1000000,
# fee: 300000,
# filledFee: 0,
# feeAsset: 'WAVES',
# timestamp: 1594303779322,
# status: 'Cancelled',
# assetPair: {
# amountAsset: '474jTeYx2r2Va35794tCScAXWJG9hU2HcgxzMowaZUnu',
# priceAsset: 'WAVES'
# },
# avgWeighedPrice: 0,
# version: 3,
# totalExecutedPriceAssets: 0, # in fetchOpenOrder/s
# }
#
timestamp = self.safe_integer(order, 'timestamp')
side = self.safe_string_2(order, 'type', 'orderType')
type = 'limit'
if 'type' in order:
# fetchOrders
type = self.safe_string(order, 'orderType', type)
id = self.safe_string(order, 'id')
filledString = self.safe_string(order, 'filled')
priceString = self.safe_string(order, 'price')
amountString = self.safe_string(order, 'amount')
assetPair = self.safe_value(order, 'assetPair')
symbol = None
if assetPair is not None:
symbol = self.get_symbol_from_asset_pair(assetPair)
elif market is not None:
symbol = market['symbol']
amountCurrency = self.safe_currency_code(self.safe_string(assetPair, 'amountAsset', 'WAVES'))
price = self.price_from_precision(symbol, priceString)
amount = self.currency_from_precision(amountCurrency, amountString)
filled = self.currency_from_precision(amountCurrency, filledString)
average = self.price_from_precision(symbol, self.safe_string(order, 'avgWeighedPrice'))
status = self.parse_order_status(self.safe_string(order, 'status'))
fee = None
if 'type' in order:
currency = self.safe_currency_code(self.safe_string(order, 'feeAsset'))
fee = {
'currency': currency,
'fee': self.parse_number(self.currency_from_precision(currency, self.safe_string(order, 'filledFee'))),
}
else:
currency = self.safe_currency_code(self.safe_string(order, 'matcherFeeAssetId', 'WAVES'))
fee = {
'currency': currency,
'fee': self.parse_number(self.currency_from_precision(currency, self.safe_string(order, 'matcherFee'))),
}
return self.safe_order({
'info': order,
'id': id,
'clientOrderId': None,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'lastTradeTimestamp': None,
'symbol': symbol,
'type': type,
'timeInForce': None,
'postOnly': None,
'side': side,
'price': price,
'stopPrice': None,
'amount': amount,
'cost': None,
'average': average,
'filled': filled,
'remaining': None,
'status': status,
'fee': fee,
'trades': None,
}, market)
async def get_waves_address(self):
cachedAddreess = self.safe_string(self.options, 'wavesAddress')
if cachedAddreess is None:
request = {
'publicKey': self.apiKey,
}
response = await self.nodeGetAddressesPublicKeyPublicKey(request)
self.options['wavesAddress'] = self.safe_string(response, 'address')
return self.options['wavesAddress']
else:
return cachedAddreess
async def fetch_balance(self, params={}):
# makes a lot of different requests to get all the data
# in particular:
# fetchMarkets, getWavesAddress,
# getTotalBalance(doesn't include waves), getReservedBalance(doesn't include waves)
# getReservedBalance(includes WAVES)
# I couldn't find another way to get all the data
self.check_required_dependencies()
self.check_required_keys()
await self.load_markets()
wavesAddress = await self.get_waves_address()
request = {
'address': wavesAddress,
}
totalBalance = await self.nodeGetAssetsBalanceAddress(request)
# {
# "address": "3P8VzLSa23EW5CVckHbV7d5BoN75fF1hhFH",
# "balances": [
# {
# "assetId": "DG2xFkPdDwKUoBkzGAhQtLpSGzfXLiCYPEzeKH2Ad24p",
# "balance": 1177200,
# "reissuable": False,
# "minSponsoredAssetFee": 7420,
# "sponsorBalance": 47492147189709,
# "quantity": 999999999775381400,
# "issueTransaction": {
# "senderPublicKey": "BRnVwSVctnV8pge5vRpsJdWnkjWEJspFb6QvrmZvu3Ht",
# "quantity": 1000000000000000000,
# "fee": 100400000,
# "description": "Neutrino USD",
# "type": 3,
# "version": 2,
# "reissuable": False,
# "script": null,
# "sender": "3PC9BfRwJWWiw9AREE2B3eWzCks3CYtg4yo",
# "feeAssetId": null,
# "chainId": 87,
# "proofs": [
# "3HNpbVkgP69NWSeb9hGYauiQDaXrRXh3tXFzNsGwsAAXnFrA29SYGbLtziW9JLpXEq7qW1uytv5Fnm5XTUMB2BxU"
# ],
# "assetId": "DG2xFkPdDwKUoBkzGAhQtLpSGzfXLiCYPEzeKH2Ad24p",
# "decimals": 6,
# "name": "USD-N",
# "id": "DG2xFkPdDwKUoBkzGAhQtLpSGzfXLiCYPEzeKH2Ad24p",
# "timestamp": 1574429393962
# }
# }
# ]
# }
balances = self.safe_value(totalBalance, 'balances')
result = {}
timestamp = None
assetIds = []
nonStandardBalances = []
for i in range(0, len(balances)):
entry = balances[i]
entryTimestamp = self.safe_integer(entry, 'timestamp')
timestamp = entryTimestamp if (timestamp is None) else max(timestamp, entryTimestamp)
issueTransaction = self.safe_value(entry, 'issueTransaction')
currencyId = self.safe_string(entry, 'assetId')
balance = self.safe_string(entry, 'balance')
if issueTransaction is None:
assetIds.append(currencyId)
nonStandardBalances.append(balance)
continue
decimals = self.safe_integer(issueTransaction, 'decimals')
code = None
if currencyId in self.currencies_by_id:
code = self.safe_currency_code(currencyId)
result[code] = self.account()
result[code]['total'] = self.from_precision(balance, decimals)
nonStandardAssets = len(assetIds)
if nonStandardAssets:
request = {
'ids': assetIds,
}
response = await self.publicGetAssets(request)
data = self.safe_value(response, 'data')
for i in range(0, len(data)):
entry = data[i]
balance = nonStandardBalances[i]
inner = self.safe_value(entry, 'data')
decimals = self.safe_integer(inner, 'precision')
ticker = self.safe_string(inner, 'ticker')
code = self.safe_currency_code(ticker)
result[code] = self.account()
result[code]['total'] = self.from_precision(balance, decimals)
currentTimestamp = self.milliseconds()
byteArray = [
self.base58_to_binary(self.apiKey),
self.number_to_be(currentTimestamp, 8),
]
binary = self.binary_concat_array(byteArray)
hexSecret = self.binary_to_base16(self.base58_to_binary(self.secret))
signature = self.eddsa(self.binary_to_base16(binary), hexSecret, 'ed25519')
matcherRequest = {
'publicKey': self.apiKey,
'signature': signature,
'timestamp': str(currentTimestamp),
}
reservedBalance = await self.matcherGetMatcherBalanceReservedPublicKey(matcherRequest)
# {WAVES: 200300000}
reservedKeys = list(reservedBalance.keys())
for i in range(0, len(reservedKeys)):
currencyId = reservedKeys[i]
code = self.safe_currency_code(currencyId)
if not (code in result):
result[code] = self.account()
amount = self.safe_string(reservedBalance, currencyId)
if code in self.currencies:
result[code]['used'] = self.currency_from_precision(code, amount)
else:
result[code]['used'] = amount
wavesRequest = {
'address': wavesAddress,
}
wavesTotal = await self.nodeGetAddressesBalanceAddress(wavesRequest)
# {
# "address": "3P8VzLSa23EW5CVckHbV7d5BoN75fF1hhFH",
# "confirmations": 0,
# "balance": 909085978
# }
result['WAVES'] = self.safe_value(result, 'WAVES', {})
result['WAVES']['total'] = self.currency_from_precision('WAVES', self.safe_string(wavesTotal, 'balance'))
codes = list(result.keys())
for i in range(0, len(codes)):
code = codes[i]
if self.safe_value(result[code], 'used') is None:
result[code]['used'] = '0'
result['timestamp'] = timestamp
result['datetime'] = self.iso8601(timestamp)
return self.safe_balance(result)
async def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
await self.load_markets()
market = self.market(symbol)
address = await self.get_waves_address()
request = {
'sender': address,
'amountAsset': market['baseId'],
'priceAsset': market['quoteId'],
}
response = await self.publicGetTransactionsExchange(request)
data = self.safe_value(response, 'data')
#
# {
# "__type":"list",
# "isLastPage":true,
# "lastCursor":"MzA2MjQ0MzAwMDI5OjpkZXNj",
# "data": [
# {
# "__type":"transaction",
# "data": {
# "id":"GbjPqco2wRP5QSrY5LimFrUyJaM535K9nhK5zaQ7J7Tx",
# "timestamp":"2022-04-06T19:56:31.479Z",
# "height":3062443,
# "type":7,
# "version":2,
# "proofs":[
# "57mYrANw61eiArCTv2eYwzXm71jYC2KpZ5AeM9zHEstuRaYSAWSuSE7njAJYJu8zap6DMCm3nzqc6es3wQFDpRCN"
# ],
# "fee":0.003,
# "applicationStatus":"succeeded",
# "sender":"3PEjHv3JGjcWNpYEEkif2w8NXV4kbhnoGgu",
# "senderPublicKey":"9cpfKN9suPNvfeUNphzxXMjcnn974eme8ZhWUjaktzU5",
# "buyMatcherFee":0,
# "sellMatcherFee":0.00141728,
# "price":215.7431,
# "amount":0.09,
# "order1": {
# "id":"49qiuQj5frdZ6zpTCEpMuKPMAh1EimwXpXWB4BeCw33h",
# "senderPublicKey":"CjUfoH3dsDZsf5UuAjqqzpWHXgvKzBZpVG9YixF7L48K",
# "matcherPublicKey":"9cpfKN9suPNvfeUNphzxXMjcnn974eme8ZhWUjaktzU5",
# "assetPair": {
# "amountAsset":"7TMu26hAs7B2oW6c5sfx45KSZT7GQA3TZNYuCav8Dcqt",
# "priceAsset":"DG2xFkPdDwKUoBkzGAhQtLpSGzfXLiCYPEzeKH2Ad24p"
# },
# "orderType":"buy",
# "price":215.7431,
# "sender":"3PR9WmaHV5ueVw2Wr9xsiCG3t4ySXzkkGLy",
# "amount":0.36265477,
# "timestamp":"2022-04-06T19:55:06.832Z",
# "expiration":"2022-05-05T19:55:06.832Z",
# "matcherFee":3.000334,
# "signature":"2rBWhdeuRJNpQfXfTFtcR8x8Lpic8FUHPdLML9uxABRUuxe48YRJcZxbncwWAh9LWFCEUZiztv7RZBZfGMWfFxTs",
# "matcherFeeAssetId":"DG2xFkPdDwKUoBkzGAhQtLpSGzfXLiCYPEzeKH2Ad24p"
# },
# "order2": {
# "id":"AkxiJqCuv6wm8K41TUSgFNwShZMnCbMDT78MqrcWpQ53",
# "senderPublicKey":"72o7qNKyne5hthB1Ww6famE7uHrk5vTVB2ZfUMBEqL3Y",
# "matcherPublicKey":"9cpfKN9suPNvfeUNphzxXMjcnn974eme8ZhWUjaktzU5",
# "assetPair": {
# "amountAsset":"7TMu26hAs7B2oW6c5sfx45KSZT7GQA3TZNYuCav8Dcqt",
# "priceAsset":"DG2xFkPdDwKUoBkzGAhQtLpSGzfXLiCYPEzeKH2Ad24p"
# },
# "orderType":"sell",
# "price":210,
# "sender":"3P3CzbjGgiqEyUBeKZYfgZtyaZfMG8fjoUD",
# "amount":0.09,
# "timestamp":"2022-04-06T19:56:18.535Z",
# "expiration":"2022-05-04T19:56:18.535Z",
# "matcherFee":0.00141728,
# "signature":"5BZCjYn6QzVkMXBFDBnzcAUBdCZqhq9hQfRXFHfLUQCsbis4zeriw4sUqLa1BZRT2isC6iY4Z4HtekikPqZ461PT",
# "matcherFeeAssetId":"7TMu26hAs7B2oW6c5sfx45KSZT7GQA3TZNYuCav8Dcqt"
# }
# }
# },...
# ]
# }
#
return self.parse_trades(data, market, since, limit)
async def fetch_trades(self, symbol, since=None, limit=None, params={}):
await self.load_markets()
market = self.market(symbol)
request = {
'amountAsset': market['baseId'],
'priceAsset': market['quoteId'],
}
if limit is not None:
request['limit'] = limit
if since is not None:
request['timeStart'] = since
response = await self.publicGetTransactionsExchange(request)
data = self.safe_value(response, 'data')
#
# {
# "__type":"list",
# "isLastPage":false,
# "lastCursor":"MzA2MjM2MTAwMDU0OjpkZXNj",
# "data": [
# {
# "__type":"transaction",
# "data": {
# "id":"F42WsvSsyEzvpPLFjVhQKkSNuopooP4zMkjSUs47NeML",
# "timestamp":"2022-04-06T18:39:49.145Z",
# "height":3062361,
# "type":7,
# "version":2,
# "proofs": [
# "39iJv82kFi4pyuBxYeZpP45NXXjbrCXdVsHPAAvj32UMLmTXLjMTfV43PcmZDSAuS93HKSDo1aKJrin8UvkeE9Bs"
# ],
# "fee":0.003,
# "applicationStatus":"succeeded",
# "sender":"3PEjHv3JGjcWNpYEEkif2w8NXV4kbhnoGgu",
# "senderPublicKey":"9cpfKN9suPNvfeUNphzxXMjcnn974eme8ZhWUjaktzU5",
# "buyMatcherFee":0.02314421,
# "sellMatcherFee":0,
# "price":217.3893,
# "amount":0.34523025,
# "order1": {
# "id":"HkM36PHGaeeZdDKT1mYgZXhaU9PRZ54RZiJc2K4YMT3Q",
# "senderPublicKey":"7wYCaDcc6GX1Jx2uS7QgLHBypBKvrezTS1HfiW6Xe4Bk",
# "matcherPublicKey":"9cpfKN9suPNvfeUNphzxXMjcnn974eme8ZhWUjaktzU5",
# "assetPair": {
# "amountAsset":"7TMu26hAs7B2oW6c5sfx45KSZT7GQA3TZNYuCav8Dcqt",
# "priceAsset":"DG2xFkPdDwKUoBkzGAhQtLpSGzfXLiCYPEzeKH2Ad24p"
# },
# "orderType":"buy",
# "price":225.2693,
# "sender":"3PLPc8f4DGYaF9C9bwJ2uVmHqRv3NCjg5VQ",
# "amount":2.529,
# "timestamp":"2022-04-06T18:39:48.796Z",
# "expiration":"2022-05-05T18:39:48.796Z",
# "matcherFee":0.17584444,
# "signature":"2yQfJoomv86evQDw36fg1uiRkHvPDZtRp3qvxqTBWPvz4JLTHGQtEHJF5NGTvym6U93CtgNprngzmD9ecHBjxf6U",
# "matcherFeeAssetId":"Atqv59EYzjFGuitKVnMRk6H8FukjoV3ktPorbEys25on"
# },
# "order2": {
# "id":"F7HKmeuzwWdk3wKitHLnVx5MuD4wBWPpphQ8kUGx4tT9",
# "senderPublicKey":"CjUfoH3dsDZsf5UuAjqqzpWHXgvKzBZpVG9YixF7L48K",
# "matcherPublicKey":"9cpfKN9suPNvfeUNphzxXMjcnn974eme8ZhWUjaktzU5",
# "assetPair": {
# "amountAsset":"7TMu26hAs7B2oW6c5sfx45KSZT7GQA3TZNYuCav8Dcqt",
# "priceAsset":"DG2xFkPdDwKUoBkzGAhQtLpSGzfXLiCYPEzeKH2Ad24p"
# },
# "orderType":"sell",
# "price":217.3893,
# "sender":"3PR9WmaHV5ueVw2Wr9xsiCG3t4ySXzkkGLy",
# "amount":0.35767793,
# "timestamp":"2022-04-06T18:32:01.390Z",
# "expiration":"2022-05-05T18:32:01.390Z",
# "matcherFee":0.0139168,
# "signature":"34HgWVLPgeYWkiSvAc5ChVepGTYDQDug2dMTSincs6idEyoM7AtaZuH3mqQ5RJG2fcxxH2QSB723Qq3dgLQwQmKf",
# "matcherFeeAssetId":"7TMu26hAs7B2oW6c5sfx45KSZT7GQA3TZNYuCav8Dcqt"
# }
# }
# }, ...
# ]
# }
#
return self.parse_trades(data, market, since, limit)
def parse_trade(self, trade, market=None):
#
# {__type: 'transaction',
# data:
# {id: 'HSdruioHqvYHeyn9hhyoHdRWPB2bFA8ujeCPZMK6992c',
# timestamp: '2020-06-09T19:34:51.897Z',
# height: 2099684,
# type: 7,
# version: 2,
# proofs:
# ['26teDHERQgwjjHqEn4REcDotNG8M21xjou3X42XuDuCvrRkQo6aPyrswByH3UrkWG8v27ZAaVNzoxDg4teNcLtde'],
# fee: 0.003,
# sender: '3PEjHv3JGjcWNpYEEkif2w8NXV4kbhnoGgu',
# senderPublicKey: '9cpfKN9suPNvfeUNphzxXMjcnn974eme8ZhWUjaktzU5',
# buyMatcherFee: 0.00299999,
# sellMatcherFee: 0.00299999,
# price: 0.00012003,
# amount: 60.80421562,
# order1:
# {id: 'CBRwP3ar4oMvvpUiGyfxc1syh41488SDi2GkrjuBDegv',
# senderPublicKey: 'DBXSHBz96NFsMu7xh4fi2eT9ZnyxefAHXsMxUayzgC6a',
# matcherPublicKey: '9cpfKN9suPNvfeUNphzxXMjcnn974eme8ZhWUjaktzU5',
# assetPair: [Object],
# orderType: 'buy',
# price: 0.00012003,
# sender: '3PJfFRgVuJ47UY4ckb74EGzEBzkHXtmG1LA',
# amount: 60.80424773,
# timestamp: '2020-06-09T19:34:51.885Z',
# expiration: '2020-06-10T12:31:31.885Z',
# matcherFee: 0.003,
# signature: '4cA3ZAb3XAEEXaFG7caqpto5TRbpR5PkhZpxoNQZ9ZReNvjuJQs5a3THnumv7rcqmVUiVtuHAgk2f67ANcqtKyJ8',
# matcherFeeAssetId: null},
# order2:
# {id: 'CHJSLQ6dfSPs6gu2mAegrMUcRiDEDqaj2GKfvptMjS3M',
# senderPublicKey: '3RUC4NGFZm9H8VJhSSjJyFLdiE42qNiUagDcZPwjgDf8',
# matcherPublicKey: '9cpfKN9suPNvfeUNphzxXMjcnn974eme8ZhWUjaktzU5',
# assetPair: [Object],
# orderType: 'sell',
# price: 0.00012003,
# sender: '3P9vKoQpMZtaSkHKpNh977YY9ZPzTuntLAq',
# amount: 60.80424773,
# timestamp: '2020-06-09T19:34:51.887Z',
# expiration: '2020-06-10T12:31:31.887Z',
# matcherFee: 0.003,
# signature: '3SFyrcqzou2ddZyNisnLYaGhLt5qRjKxH8Nw3s4T5U7CEKGX9DDo8dS27RgThPVGbYF1rYET1FwrWoQ2UFZ6SMTR',
# matcherFeeAssetId: null}}}
#
data = self.safe_value(trade, 'data')
datetime = self.safe_string(data, 'timestamp')
timestamp = self.parse8601(datetime)
id = self.safe_string(data, 'id')
priceString = self.safe_string(data, 'price')
amountString = self.safe_string(data, 'amount')
order1 = self.safe_value(data, 'order1')
order2 = self.safe_value(data, 'order2')
order = None
# order2 arrived after order1
if self.safe_string(order1, 'senderPublicKey') == self.apiKey:
order = order1
else:
order = order2
symbol = None
assetPair = self.safe_value(order, 'assetPair')
if assetPair is not None:
symbol = self.get_symbol_from_asset_pair(assetPair)
elif market is not None:
symbol = market['symbol']
side = self.safe_string(order, 'orderType')
orderId = self.safe_string(order, 'id')
fee = {
'cost': self.safe_string(order, 'matcherFee'),
'currency': self.safe_currency_code(self.safe_string(order, 'matcherFeeAssetId', 'WAVES')),
}
return self.safe_trade({
'info': trade,
'timestamp': timestamp,
'datetime': datetime,
'symbol': symbol,
'id': id,
'order': orderId,
'type': None,
'side': side,
'takerOrMaker': None,
'price': priceString,
'amount': amountString,
'cost': None,
'fee': fee,
}, market)
def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody):
errorCode = self.safe_string(response, 'error')
success = self.safe_value(response, 'success', True)
Exception = self.safe_value(self.exceptions, errorCode)
if Exception is not None:
message = self.safe_string(response, 'message')
raise Exception(self.id + ' ' + message)
message = self.safe_string(response, 'message')
if message == 'Validation Error':
raise BadRequest(self.id + ' ' + body)
if not success:
raise ExchangeError(self.id + ' ' + body)
async def withdraw(self, code, amount, address, tag=None, params={}):
tag, params = self.handle_withdraw_tag_and_params(tag, params)
# currently only works for BTC and WAVES
if code != 'WAVES':
supportedCurrencies = await self.privateGetWithdrawCurrencies()
currencies = {}
items = self.safe_value(supportedCurrencies, 'items', [])
for i in range(0, len(items)):
entry = items[i]
currencyCode = self.safe_string(entry, 'id')
currencies[currencyCode] = True
if not (code in currencies):
codes = list(currencies.keys())
raise ExchangeError(self.id + ' fetch ' + code + ' withdrawals are not supported. Currency code must be one of ' + str(codes))
await self.load_markets()
hexChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
set = {}
for i in range(0, len(hexChars)):
key = hexChars[i]
set[key] = True
isErc20 = True
noPrefix = self.remove0x_prefix(address)
lower = noPrefix.lower()
for i in range(0, len(lower)):
character = lower[i]
if not (character in set):
isErc20 = False
break
await self.sign_in()
proxyAddress = None
if code == 'WAVES' and not isErc20:
proxyAddress = address
else:
withdrawAddressRequest = {
'address': address,
'currency': code,
}
withdrawAddress = await self.privateGetWithdrawAddressesCurrencyAddress(withdrawAddressRequest)
currency = self.safe_value(withdrawAddress, 'currency')
allowedAmount = self.safe_value(currency, 'allowed_amount')
minimum = self.safe_number(allowedAmount, 'min')
if amount <= minimum:
raise BadRequest(self.id + ' ' + code + ' withdraw failed, amount ' + str(amount) + ' must be greater than the minimum allowed amount of ' + str(minimum))
# {
# "type": "withdrawal_addresses",
# "currency": {
# "type": "withdrawal_currency",
# "id": "BTC",
# "waves_asset_id": "8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS",
# "decimals": 8,
# "status": "active",
# "allowed_amount": {
# "min": 0.001,
# "max": 20
# },
# "fees": {
# "flat": 0.001,
# "rate": 0
# }
# },
# "proxy_addresses": [
# "3P3qqmkiLwNHB7x1FeoE8bvkRtULwGpo9ga"
# ]
# }
proxyAddresses = self.safe_value(withdrawAddress, 'proxy_addresses', [])
proxyAddress = self.safe_string(proxyAddresses, 0)
fee = self.safe_integer(self.options, 'withdrawFeeWAVES', 100000) # 0.001 WAVES
feeAssetId = 'WAVES'
type = 4 # transfer
version = 2
amountInteger = self.currency_to_precision(code, amount)
currency = self.currency(code)
timestamp = self.milliseconds()
byteArray = [
self.number_to_be(4, 1),
self.number_to_be(2, 1),
self.base58_to_binary(self.apiKey),
self.get_asset_bytes(currency['id']),
self.get_asset_bytes(feeAssetId),
self.number_to_be(timestamp, 8),
self.number_to_be(amountInteger, 8),
self.number_to_be(fee, 8),
self.base58_to_binary(proxyAddress),
self.number_to_be(0, 2),
]
binary = self.binary_concat_array(byteArray)
hexSecret = self.binary_to_base16(self.base58_to_binary(self.secret))
signature = self.eddsa(self.binary_to_base16(binary), hexSecret, 'ed25519')
request = {
'senderPublicKey': self.apiKey,
'amount': amountInteger,
'fee': fee,
'type': type,
'version': version,
'attachment': '',
'feeAssetId': self.get_asset_id(feeAssetId),
'proofs': [
signature,
],
'assetId': self.get_asset_id(currency['id']),
'recipient': proxyAddress,
'timestamp': timestamp,
'signature': signature,
}
result = await self.nodePostTransactionsBroadcast(request)
#
# {
# "id": "string",
# "signature": "string",
# "fee": 0,
# "timestamp": 1460678400000,
# "recipient": "3P274YB5qseSE9DTTL3bpSjosZrYBPDpJ8k",
# "amount": 0
# }
#
return self.parse_transaction(result, currency)
def parse_transaction(self, transaction, currency=None):
#
# withdraw
#
# {
# "id": "string",
# "signature": "string",
# "fee": 0,
# "timestamp": 1460678400000,
# "recipient": "3P274YB5qseSE9DTTL3bpSjosZrYBPDpJ8k",
# "amount": 0
# }
#
currency = self.safe_currency(None, currency)
return {
'id': None,
'txid': None,
'timestamp': None,
'datetime': None,
'network': None,
'addressFrom': None,
'address': None,
'addressTo': None,
'amount': None,
'type': None,
'currency': currency['code'],
'status': None,
'updated': None,
'tagFrom': None,
'tag': None,
'tagTo': None,
'comment': None,
'fee': None,
'info': transaction,
}
| 44.892926 | 1,000 | 0.516161 |
rt.base.exchange import Exchange
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import AccountSuspended
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import DuplicateOrderId
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.precise import Precise
class wavesexchange(Exchange):
def describe(self):
return self.deep_extend(super(wavesexchange, self).describe(), {
'id': 'wavesexchange',
'name': 'Waves.Exchange',
'countries': ['CH'],
'certified': True,
'pro': False,
'has': {
'CORS': None,
'spot': True,
'margin': False,
'swap': False,
'future': False,
'option': False,
'addMargin': False,
'cancelOrder': True,
'createMarketOrder': True,
'createOrder': True,
'createReduceOnlyOrder': False,
'fetchBalance': True,
'fetchBorrowRate': False,
'fetchBorrowRateHistories': False,
'fetchBorrowRateHistory': False,
'fetchBorrowRates': False,
'fetchBorrowRatesPerSymbol': False,
'fetchClosedOrders': True,
'fetchDepositAddress': True,
'fetchFundingHistory': False,
'fetchFundingRate': False,
'fetchFundingRateHistory': False,
'fetchFundingRates': False,
'fetchIndexOHLCV': False,
'fetchLeverage': False,
'fetchLeverageTiers': False,
'fetchMarkets': True,
'fetchMarkOHLCV': False,
'fetchMyTrades': True,
'fetchOHLCV': True,
'fetchOpenOrders': True,
'fetchOrder': True,
'fetchOrderBook': True,
'fetchOrders': True,
'fetchPosition': False,
'fetchPositions': False,
'fetchPositionsRisk': False,
'fetchPremiumIndexOHLCV': False,
'fetchTicker': True,
'fetchTrades': True,
'fetchTransfer': False,
'fetchTransfers': False,
'reduceMargin': False,
'setLeverage': False,
'setMarginMode': False,
'setPositionMode': False,
'signIn': True,
'transfer': False,
'withdraw': True,
},
'timeframes': {
'1m': '1m',
'5m': '5m',
'15m': '15m',
'30m': '30m',
'1h': '1h',
'2h': '2h',
'3h': '3h',
'4h': '4h',
'6h': '6h',
'12h': '12h',
'1d': '1d',
'1w': '1w',
'1M': '1M',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/84547058-5fb27d80-ad0b-11ea-8711-78ac8b3c7f31.jpg',
'test': {
'matcher': 'https://matcher-testnet.waves.exchange',
'node': 'https://nodes-testnet.wavesnodes.com',
'public': 'https://api-testnet.wavesplatform.com/v0',
'private': 'https://api-testnet.waves.exchange/v1',
'forward': 'https://testnet.waves.exchange/api/v1/forward/matcher',
'market': 'https://testnet.waves.exchange/api/v1/forward/marketdata/api/v1',
},
'api': {
'matcher': 'https://matcher.waves.exchange',
'node': 'https://nodes.waves.exchange',
'public': 'https://api.wavesplatform.com/v0',
'private': 'https://api.waves.exchange/v1',
'forward': 'https://waves.exchange/api/v1/forward/matcher',
'market': 'https://waves.exchange/api/v1/forward/marketdata/api/v1',
},
'doc': 'https://docs.waves.exchange',
'www': 'https://waves.exchange',
},
'api': {
'matcher': {
'get': [
'matcher',
'matcher/settings',
'matcher/settings/rates',
'matcher/balance/reserved/{publicKey}',
'matcher/debug/allSnashotOffsets',
'matcher/debug/currentOffset',
'matcher/debug/lastOffset',
'matcher/debug/oldestSnapshotOffset',
'matcher/orderbook',
'matcher/orderbook/{amountAsset}/{priceAsset}',
'matcher/orderbook/{baseId}/{quoteId}/publicKey/{publicKey}',
'matcher/orderbook/{baseId}/{quoteId}/{orderId}',
'matcher/orderbook/{baseId}/{quoteId}/info',
'matcher/orderbook/{baseId}/{quoteId}/status',
'matcher/orderbook/{baseId}/{quoteId}/tradeableBalance/{address}',
'matcher/orderbook/{publicKey}',
'matcher/orderbook/{publicKey}/{orderId}',
'matcher/orders/{address}',
'matcher/orders/{address}/{orderId}',
'matcher/transactions/{orderId}',
],
'post': [
'matcher/orderbook',
'matcher/orderbook/market',
'matcher/orderbook/cancel',
'matcher/orderbook/{baseId}/{quoteId}/cancel',
'matcher/orderbook/{amountAsset}/{priceAsset}/calculateFee',
'matcher/debug/saveSnapshots',
'matcher/orders/{address}/cancel',
'matcher/orders/cancel/{orderId}',
],
'delete': [
'matcher/orderbook/{baseId}/{quoteId}',
'matcher/settings/rates/{assetId}',
],
'put': [
'matcher/settings/rates/{assetId}',
],
},
'node': {
'get': [
'addresses',
'addresses/balance/{address}',
'addresses/balance/{address}/{confirmations}',
'addresses/balance/details/{address}',
'addresses/data/{address}',
'addresses/data/{address}/{key}',
'addresses/effectiveBalance/{address}',
'addresses/effectiveBalance/{address}/{confirmations}',
'addresses/publicKey/{publicKey}',
'addresses/scriptInfo/{address}',
'addresses/scriptInfo/{address}/meta',
'addresses/seed/{address}',
'addresses/seq/{from}/{to}',
'addresses/validate/{address}',
'alias/by-address/{address}',
'alias/by-alias/{alias}',
'assets/{assetId}/distribution/{height}/{limit}',
'assets/balance/{address}',
'assets/balance/{address}/{assetId}',
'assets/details/{assetId}',
'assets/nft/{address}/limit/{limit}',
'blockchain/rewards',
'blockchain/rewards/height',
'blocks/address/{address}/{from}/{to}/',
'blocks/at/{height}',
'blocks/delay/{signature}/{blockNum}',
'blocks/first',
'blocks/headers/last',
'blocks/headers/seq/{from}/{to}',
'blocks/height',
'blocks/height/{signature}',
'blocks/last',
'blocks/seq/{from}/{to}',
'blocks/signature/{signature}',
'consensus/algo',
'consensus/basetarget',
'consensus/basetarget/{blockId}',
'consensus/{generatingbalance}/address',
'consensus/generationsignature',
'consensus/generationsignature/{blockId}',
'debug/balances/history/{address}',
'debug/blocks/{howMany}',
'debug/configInfo',
'debug/historyInfo',
'debug/info',
'debug/minerInfo',
'debug/portfolios/{address}',
'debug/state',
'debug/stateChanges/address/{address}',
'debug/stateChanges/info/{id}',
'debug/stateWaves/{height}',
'leasing/active/{address}',
'node/state',
'node/version',
'peers/all',
'peers/blacklisted',
'peers/connected',
'peers/suspended',
'transactions/address/{address}/limit/{limit}',
'transactions/info/{id}',
'transactions/status',
'transactions/unconfirmed',
'transactions/unconfirmed/info/{id}',
'transactions/unconfirmed/size',
'utils/seed',
'utils/seed/{length}',
'utils/time',
'wallet/seed',
],
'post': [
'addresses',
'addresses/data/{address}',
'addresses/sign/{address}',
'addresses/signText/{address}',
'addresses/verify/{address}',
'addresses/verifyText/{address}',
'debug/blacklist',
'debug/print',
'debug/rollback',
'debug/validate',
'node/stop',
'peers/clearblacklist',
'peers/connect',
'transactions/broadcast',
'transactions/calculateFee',
'tranasctions/sign',
'transactions/sign/{signerAddress}',
'tranasctions/status',
'utils/hash/fast',
'utils/hash/secure',
'utils/script/compileCode',
'utils/script/compileWithImports',
'utils/script/decompile',
'utils/script/estimate',
'utils/sign/{privateKey}',
'utils/transactionsSerialize',
],
'delete': [
'addresses/{address}',
'debug/rollback-to/{signature}',
],
},
'public': {
'get': [
'assets',
'pairs',
'candles/{baseId}/{quoteId}',
'transactions/exchange',
],
},
'private': {
'get': [
'deposit/addresses/{currency}',
'deposit/addresses/{currency}/{platform}',
'platforms',
'deposit/currencies',
'withdraw/currencies',
'withdraw/addresses/{currency}/{address}',
],
'post': [
'oauth2/token',
],
},
'forward': {
'get': [
'matcher/orders/{address}',
'matcher/orders/{address}/{orderId}',
],
'post': [
'matcher/orders/{wavesAddress}/cancel',
],
},
'market': {
'get': [
'tickers',
],
},
},
'currencies': {
'WX': {'id': 'EMAMLxDnv3xiz8RXg8Btj33jcEw3wLczL3JKYYmuubpc', 'numericId': None, 'code': 'WX', 'precision': 8},
},
'options': {
'allowedCandles': 1440,
'accessToken': None,
'createMarketBuyOrderRequiresPrice': True,
'matcherPublicKey': None,
'quotes': None,
'createOrderDefaultExpiry': 2419200000, # 60 * 60 * 24 * 28 * 1000
'wavesAddress': None,
'withdrawFeeUSDN': 7420,
'withdrawFeeWAVES': 100000,
'wavesPrecision': 8,
'messagePrefix': 'W', # W for production, T for testnet
'networks': {
'ERC20': 'ETH',
'BEP20': 'BSC',
},
'reverseNetworks': {
'ETH': 'ERC20',
'BSC': 'BEP20',
},
},
'commonCurrencies': {
'EGG': 'Waves Ducks',
},
'requiresEddsa': True,
'exceptions': {
'3147270': InsufficientFunds, # https://github.com/wavesplatform/matcher/wiki/List-of-all-errors
'112': InsufficientFunds,
'4': ExchangeError,
'13': ExchangeNotAvailable,
'14': ExchangeNotAvailable,
'3145733': AccountSuspended,
'3148040': DuplicateOrderId,
'3148801': AuthenticationError,
'9440512': AuthenticationError,
'9440771': BadSymbol,
'9441026': InvalidOrder,
'9441282': InvalidOrder,
'9441286': InvalidOrder,
'9441295': InvalidOrder,
'9441540': InvalidOrder,
'9441542': InvalidOrder,
'106954752': AuthenticationError,
'106954769': AuthenticationError,
'106957828': AuthenticationError,
'106960131': AuthenticationError,
'106981137': AuthenticationError,
'9437193': OrderNotFound,
'1048577': BadRequest,
'1051904': AuthenticationError,
},
})
def set_sandbox_mode(self, enabled):
self.options['messagePrefix'] = 'T' if enabled else 'W'
return super(wavesexchange, self).set_sandbox_mode(enabled)
async def get_fees_for_asset(self, symbol, side, amount, price, params={}):
await self.load_markets()
market = self.market(symbol)
amount = self.amount_to_precision(symbol, amount)
price = self.price_to_precision(symbol, price)
request = self.extend({
'amountAsset': market['baseId'],
'priceAsset': market['quoteId'],
'orderType': side,
'amount': amount,
'price': price,
}, params)
return await self.matcherPostMatcherOrderbookAmountAssetPriceAssetCalculateFee(request)
async def calculate_fee(self, symbol, type, side, amount, price, takerOrMaker='taker', params={}):
response = await self.get_fees_for_asset(symbol, side, amount, price)
# {
# "base":{
# "feeAssetId":"WAVES",
# "matcherFee":"1000000"
# },
# "discount":{
# "feeAssetId":"EMAMLxDnv3xiz8RXg8Btj33jcEw3wLczL3JKYYmuubpc",
# "matcherFee":"4077612"
# }
# }
isDiscountFee = self.safe_value(params, 'isDiscountFee', False)
mode = None
if isDiscountFee:
mode = self.safe_value(response, 'discount')
else:
mode = self.safe_value(response, 'base')
matcherFee = self.safe_string(mode, 'matcherFee')
feeAssetId = self.safe_string(mode, 'feeAssetId')
feeAsset = self.safe_currency_code(feeAssetId)
adjustedMatcherFee = self.currency_from_precision(feeAsset, matcherFee)
amountAsString = self.number_to_string(amount)
priceAsString = self.number_to_string(price)
feeCost = self.fee_to_precision(symbol, self.parse_number(adjustedMatcherFee))
feeRate = Precise.string_div(adjustedMatcherFee, Precise.string_mul(amountAsString, priceAsString))
return {
'type': takerOrMaker,
'currency': feeAsset,
'rate': self.parse_number(feeRate),
'cost': self.parse_number(feeCost),
}
async def get_quotes(self):
quotes = self.safe_value(self.options, 'quotes')
if quotes:
return quotes
else:
# currencies can have any name because you can create you own token
# as a result someone can create a fake token called BTC
# we use self mapping to determine the real tokens
# https://docs.waves.exchange/en/waves-matcher/matcher-api#asset-pair
response = await self.matcherGetMatcherSettings()
# {
# "orderVersions": [
# 1,
# 2,
# 3
# ],
# "success": True,
# "matcherPublicKey": "9cpfKN9suPNvfeUNphzxXMjcnn974eme8ZhWUjaktzU5",
# "orderFee": {
# "dynamic": {
# "baseFee": 300000,
# "rates": {
# "34N9YcEETLWn93qYQ64EsP1x89tSruJU44RrEMSXXEPJ": 1.22639597,
# "62LyMjcr2DtiyF5yVXFhoQ2q414VPPJXjsNYp72SuDCH": 0.00989643,
# "HZk1mbfuJpmxU1Fs4AX5MWLVYtctsNcg6e2C6VKqK8zk": 0.0395674,
# "8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS": 0.00018814,
# "4LHHvYGNKJUg5hj65aGD5vgScvCBmLpdRFtjokvCjSL8": 26.19721262,
# "474jTeYx2r2Va35794tCScAXWJG9hU2HcgxzMowaZUnu": 0.00752978,
# "DG2xFkPdDwKUoBkzGAhQtLpSGzfXLiCYPEzeKH2Ad24p": 1.84575,
# "B3uGHFRpSUuGEDWjqB9LWWxafQj8VTvpMucEyoxzws5H": 0.02330273,
# "zMFqXuoyrn5w17PFurTqxB7GsS71fp9dfk6XFwxbPCy": 0.00721412,
# "5WvPKSJXzVE2orvbkJ8wsQmmQKqTv9sGBPksV4adViw3": 0.02659103,
# "WAVES": 1,
# "BrjUWjndUanm5VsJkbUip8VRYy6LWJePtxya3FNv4TQa": 0.03433583
# }
# }
# },
# "networkByte": 87,
# "matcherVersion": "2.1.3.5",
# "status": "SimpleResponse",
# "priceAssets": [
# "Ft8X1v1LTa1ABafufpaCWyVj8KkaxUWE6xBhW6sNFJck",
# "DG2xFkPdDwKUoBkzGAhQtLpSGzfXLiCYPEzeKH2Ad24p",
# "34N9YcEETLWn93qYQ64EsP1x89tSruJU44RrEMSXXEPJ",
# "Gtb1WRznfchDnTh37ezoDTJ4wcoKaRsKqKjJjy7nm2zU",
# "2mX5DzVKWrAJw8iwdJnV2qtoeVG9h5nTDpTqC1wb1WEN",
# "8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS",
# "WAVES",
# "474jTeYx2r2Va35794tCScAXWJG9hU2HcgxzMowaZUnu",
# "zMFqXuoyrn5w17PFurTqxB7GsS71fp9dfk6XFwxbPCy",
# "62LyMjcr2DtiyF5yVXFhoQ2q414VPPJXjsNYp72SuDCH",
# "HZk1mbfuJpmxU1Fs4AX5MWLVYtctsNcg6e2C6VKqK8zk",
# "B3uGHFRpSUuGEDWjqB9LWWxafQj8VTvpMucEyoxzws5H",
# "5WvPKSJXzVE2orvbkJ8wsQmmQKqTv9sGBPksV4adViw3",
# "BrjUWjndUanm5VsJkbUip8VRYy6LWJePtxya3FNv4TQa",
# "4LHHvYGNKJUg5hj65aGD5vgScvCBmLpdRFtjokvCjSL8"
# ]
# }
quotes = {}
priceAssets = self.safe_value(response, 'priceAssets')
for i in range(0, len(priceAssets)):
quotes[priceAssets[i]] = True
self.options['quotes'] = quotes
return quotes
async def fetch_markets(self, params={}):
response = await self.marketGetTickers()
#
# [
# {
# "symbol": "WAVES/BTC",
# "amountAssetID": "WAVES",
# "amountAssetName": "Waves",
# "amountAssetDecimals": 8,
# "amountAssetTotalSupply": "106908766.00000000",
# "amountAssetMaxSupply": "106908766.00000000",
# "amountAssetCirculatingSupply": "106908766.00000000",
# "priceAssetID": "8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS",
# "priceAssetName": "WBTC",
# "priceAssetDecimals": 8,
# "priceAssetTotalSupply": "20999999.96007507",
# "priceAssetMaxSupply": "20999999.96007507",
# "priceAssetCirculatingSupply": "20999999.66019601",
# "24h_open": "0.00032688",
# "24h_high": "0.00033508",
# "24h_low": "0.00032443",
# "24h_close": "0.00032806",
# "24h_vwap": "0.00032988",
# "24h_volume": "42349.69440104",
# "24h_priceVolume": "13.97037207",
# "timestamp":1640232379124
# }
# ...
# ]
#
result = []
for i in range(0, len(response)):
entry = response[i]
baseId = self.safe_string(entry, 'amountAssetID')
quoteId = self.safe_string(entry, 'priceAssetID')
id = baseId + '/' + quoteId
marketId = self.safe_string(entry, 'symbol')
base, quote = marketId.split('/')
base = self.safe_currency_code(base)
quote = self.safe_currency_code(quote)
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': None,
'baseId': baseId,
'quoteId': quoteId,
'settleId': None,
'type': 'spot',
'spot': True,
'margin': False,
'swap': False,
'future': False,
'option': False,
'active': None,
'contract': False,
'linear': None,
'inverse': None,
'contractSize': None,
'expiry': None,
'expiryDatetime': None,
'strike': None,
'optionType': None,
'precision': {
'amount': self.safe_integer(entry, 'amountAssetDecimals'),
'price': self.safe_integer(entry, 'priceAssetDecimals'),
},
'limits': {
'leverage': {
'min': None,
'max': None,
},
'amount': {
'min': None,
'max': None,
},
'price': {
'min': None,
'max': None,
},
'cost': {
'min': None,
'max': None,
},
},
'info': entry,
})
return result
async def fetch_order_book(self, symbol, limit=None, params={}):
await self.load_markets()
market = self.market(symbol)
request = self.extend({
'amountAsset': market['baseId'],
'priceAsset': market['quoteId'],
}, params)
response = await self.matcherGetMatcherOrderbookAmountAssetPriceAsset(request)
timestamp = self.safe_integer(response, 'timestamp')
bids = self.parse_order_book_side(self.safe_value(response, 'bids'), market, limit)
asks = self.parse_order_book_side(self.safe_value(response, 'asks'), market, limit)
return {
'symbol': symbol,
'bids': bids,
'asks': asks,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'nonce': None,
}
def parse_order_book_side(self, bookSide, market=None, limit=None):
precision = market['precision']
wavesPrecision = self.safe_integer(self.options, 'wavesPrecision', 8)
amountPrecision = math.pow(10, precision['amount'])
difference = precision['amount'] - precision['price']
pricePrecision = math.pow(10, wavesPrecision - difference)
result = []
for i in range(0, len(bookSide)):
entry = bookSide[i]
price = self.safe_integer(entry, 'price', 0) / pricePrecision
amount = self.safe_integer(entry, 'amount', 0) / amountPrecision
if (limit is not None) and (i > limit):
break
result.append([price, amount])
return result
def check_required_keys(self):
if self.apiKey is None:
raise AuthenticationError(self.id + ' requires apiKey credential')
if self.secret is None:
raise AuthenticationError(self.id + ' requires secret credential')
apiKeyBytes = None
secretKeyBytes = None
try:
apiKeyBytes = self.base58_to_binary(self.apiKey)
except Exception as e:
raise AuthenticationError(self.id + ' apiKey must be a base58 encoded public key')
try:
secretKeyBytes = self.base58_to_binary(self.secret)
except Exception as e:
raise AuthenticationError(self.id + ' secret must be a base58 encoded private key')
hexApiKeyBytes = self.binary_to_base16(apiKeyBytes)
hexSecretKeyBytes = self.binary_to_base16(secretKeyBytes)
if len(hexApiKeyBytes) != 64:
raise AuthenticationError(self.id + ' apiKey must be a base58 encoded public key')
if len(hexSecretKeyBytes) != 64:
raise AuthenticationError(self.id + ' secret must be a base58 encoded private key')
def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
query = self.omit(params, self.extract_params(path))
isCancelOrder = path == 'matcher/orders/{wavesAddress}/cancel'
path = self.implode_params(path, params)
url = self.urls['api'][api] + '/' + path
queryString = self.urlencode_with_array_repeat(query)
if (api == 'private') or (api == 'forward'):
headers = {
'Accept': 'application/json',
}
accessToken = self.safe_string(self.options, 'accessToken')
if accessToken:
headers['Authorization'] = 'Bearer ' + accessToken
if method == 'POST':
headers['content-type'] = 'application/json'
else:
headers['content-type'] = 'application/x-www-form-urlencoded'
if isCancelOrder:
body = self.json([query['orderId']])
queryString = ''
if len(queryString) > 0:
url += '?' + queryString
elif api == 'matcher':
if method == 'POST':
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
body = self.json(query)
else:
headers = query
else:
if method == 'POST':
headers = {
'content-type': 'application/json',
}
body = self.json(query)
else:
headers = {
'content-type': 'application/x-www-form-urlencoded',
}
if len(queryString) > 0:
url += '?' + queryString
return {'url': url, 'method': method, 'body': body, 'headers': headers}
async def sign_in(self, params={}):
if not self.safe_string(self.options, 'accessToken'):
prefix = 'ffffff01'
expiresDelta = 60 * 60 * 24 * 7
seconds = self.sum(self.seconds(), expiresDelta)
seconds = str(seconds)
clientId = 'waves.exchange'
# W for production, T for testnet
defaultMessagePrefix = self.safe_string(self.options, 'messagePrefix', 'W')
message = defaultMessagePrefix + ':' + clientId + ':' + seconds
messageHex = self.binary_to_base16(self.encode(message))
payload = prefix + messageHex
hexKey = self.binary_to_base16(self.base58_to_binary(self.secret))
signature = self.eddsa(payload, hexKey, 'ed25519')
request = {
'grant_type': 'password',
'scope': 'general',
'username': self.apiKey,
'password': seconds + ':' + signature,
'client_id': clientId,
}
response = await self.privatePostOauth2Token(request)
# {access_token: 'eyJhbGciOXJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzaWciOiJiaTZiMVhMQlo0M1Q4QmRTSlVSejJBZGlQdVlpaFZQYVhhVjc4ZGVIOEpTM3M3NUdSeEU1VkZVOE5LRUI0UXViNkFHaUhpVFpuZ3pzcnhXdExUclRvZTgiLCJhIjoiM1A4VnpMU2EyM0VXNUNWY2tIYlY3ZDVCb043NWZGMWhoRkgiLCJuYiI6IlciLCJ1c2VyX25hbWUiOiJBSFhuOG5CQTRTZkxRRjdoTFFpU24xNmt4eWVoaml6QkdXMVRkcm1TWjFnRiIsInNjb3BlIjpbImdlbmVyYWwiXSwibHQiOjYwNDc5OSwicGsiOiJBSFhuOG5CQTRTZkxRRjdoTFFpU24xNmt4eWVoaml6QkdXMVRkcm1TWjFnRiIsImV4cCI6MTU5MTk3NTA1NywiZXhwMCI6MTU5MTk3NTA1NywianRpIjoiN2JhOTUxMTMtOGI2MS00NjEzLTlkZmYtNTEwYTc0NjlkOWI5IiwiY2lkIjoid2F2ZXMuZXhjaGFuZ2UifQ.B-XwexBnUAzbWknVN68RKT0ZP5w6Qk1SKJ8usL3OIwDEzCUUX9PjW-5TQHmiCRcA4oft8lqXEiCwEoNfsblCo_jTpRo518a1vZkIbHQk0-13Dm1K5ewGxfxAwBk0g49odcbKdjl64TN1yM_PO1VtLVuiTeZP-XF-S42Uj-7fcO-r7AulyQLuTE0uo-Qdep8HDCk47rduZwtJOmhFbCCnSgnLYvKWy3CVTeldsR77qxUY-vy8q9McqeP7Id-_MWnsob8vWXpkeJxaEsw1Fke1dxApJaJam09VU8EB3ZJWpkT7V8PdafIrQGeexx3jhKKxo7rRb4hDV8kfpVoCgkvFan',
# token_type: 'bearer',
# refresh_token: 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzaWciOiJiaTZiMVhMQlo0M1Q4QmRTSlVSejJBZGlQdVlpaFZQYVhhVjc4ZGVIOEpTM3M3NUdSeEU1VkZVOE5LRUI0UXViNkFHaUhpVFpuZ3pzcnhXdExUclRvZTgiLCJhIjoiM1A4VnpMU2EyM0VXNUNWY2tIYlY3ZDVCb043NWZGMWhoRkgiLCJuYiI6IlciLCJ1c2VyX25hbWUiOiJBSFhuOG5CQTRTZkxRRjdoTFFpU24xNmt4eWVoaml6QkdXMVRkcm1TWjFnRiIsInNjb3BlIjpbImdlbmVyYWwiXSwiYXRpIjoiN2JhOTUxMTMtOGI2MS00NjEzLTlkZmYtNTEwYTc0NjlkXWI5IiwibHQiOjYwNDc5OSwicGsiOiJBSFhuOG5CQTRTZkxRRjdoTFFpU24xNmt4eWVoaml6QkdXMVRkcm1TWjFnRiIsImV4cCI6MTU5Mzk2MjI1OCwiZXhwMCI6MTU5MTk3NTA1NywianRpIjoiM2MzZWRlMTktNjI5My00MTNlLWJmMWUtZTRlZDZlYzUzZTgzIiwiY2lkIjoid2F2ZXMuZXhjaGFuZ2UifQ.gD1Qj0jfqayfZpBvNY0t3ccMyK5hdbT7dY-_5L6LxwV0Knan4ndEtvygxlTOczmJUKtnA4T1r5GBFgNMZTvtViKZIbqZNysEg2OY8UxwDaF4VPeGJLg_QXEnn8wBeBQdyMafh9UQdwD2ci7x-saM4tOAGmncAygfTDxy80201gwDhfAkAGerb9kL00oWzSJScldxu--pNLDBUEHZt52MSEel10HGrzvZkkvvSh67vcQo5TOGb5KG6nh65UdJCwr41AVz4fbQPP-N2Nkxqy0TE_bqVzZxExXgvcS8TS0Z82T3ijJa_ct7B9wblpylBnvmyj3VycUzufD6uy8MUGq32D',
# expires_in: 604798,
# scope: 'general'}
self.options['accessToken'] = self.safe_string(response, 'access_token')
return self.options['accessToken']
def parse_ticker(self, ticker, market=None):
#
# {
# "__type":"pair",
# "data":{
# "firstPrice":0.00012512,
# "lastPrice":0.00012441,
# "low":0.00012167,
# "high":0.00012768,
# "weightedAveragePrice":0.000124710697407246,
# "volume":209554.26356614,
# "quoteVolume":26.1336583539951,
# "volumeWaves":209554.26356614,
# "txsCount":6655
# },
# "amountAsset":"WAVES",
# "priceAsset":"8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS"
# }
#
timestamp = None
baseId = self.safe_string(ticker, 'amountAsset')
quoteId = self.safe_string(ticker, 'priceAsset')
symbol = None
if (baseId is not None) and (quoteId is not None):
marketId = baseId + '/' + quoteId
if marketId in self.markets_by_id:
market = self.markets_by_id[marketId]
else:
base = self.safe_currency_code(baseId)
quote = self.safe_currency_code(quoteId)
symbol = base + '/' + quote
if (symbol is None) and (market is not None):
symbol = market['symbol']
data = self.safe_value(ticker, 'data', {})
last = self.safe_string(data, 'lastPrice')
low = self.safe_string(data, 'low')
high = self.safe_string(data, 'high')
vwap = self.safe_string(data, 'weightedAveragePrice')
baseVolume = self.safe_string(data, 'volume')
quoteVolume = self.safe_string(data, 'quoteVolume')
open = self.safe_string(data, 'firstPrice')
return self.safe_ticker({
'symbol': symbol,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': high,
'low': low,
'bid': None,
'bidVolume': None,
'ask': None,
'askVolume': None,
'vwap': vwap,
'open': open,
'close': last,
'last': last,
'previousClose': None,
'change': None,
'percentage': None,
'average': None,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
}, market, False)
async def fetch_ticker(self, symbol, params={}):
await self.load_markets()
market = self.market(symbol)
request = {
'pairs': market['id'],
}
response = await self.publicGetPairs(self.extend(request, params))
#
# {
# "__type":"list",
# "data":[
# {
# "__type":"pair",
# "data":{
# "firstPrice":0.00012512,
# "lastPrice":0.00012441,
# "low":0.00012167,
# "high":0.00012768,
# "weightedAveragePrice":0.000124710697407246,
# "volume":209554.26356614,
# "quoteVolume":26.1336583539951,
# "volumeWaves":209554.26356614,
# "txsCount":6655
# },
# "amountAsset":"WAVES",
# "priceAsset":"8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS"
# }
# ]
# }
#
data = self.safe_value(response, 'data', [])
ticker = self.safe_value(data, 0, {})
return self.parse_ticker(ticker, market)
async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
await self.load_markets()
market = self.market(symbol)
request = {
'baseId': market['baseId'],
'quoteId': market['quoteId'],
'interval': self.timeframes[timeframe],
}
allowedCandles = self.safe_integer(self.options, 'allowedCandles', 1440)
if limit is None:
limit = allowedCandles
limit = min(allowedCandles, limit)
duration = self.parse_timeframe(timeframe) * 1000
if since is None:
durationRoundedTimestamp = int(self.milliseconds() / duration) * duration
delta = (limit - 1) * duration
timeStart = durationRoundedTimestamp - delta
request['timeStart'] = str(timeStart)
else:
request['timeStart'] = str(since)
timeEnd = self.sum(since, duration * limit)
request['timeEnd'] = str(timeEnd)
response = await self.publicGetCandlesBaseIdQuoteId(self.extend(request, params))
#
# {
# "__type": "list",
# "data": [
# {
# "__type": "candle",
# "data": {
# "time": "2020-06-09T14:47:00.000Z",
# "open": 0.0250385,
# "close": 0.0250385,
# "high": 0.0250385,
# "low": 0.0250385,
# "volume": 0.01033012,
# "quoteVolume": 0.00025865,
# "weightedAveragePrice": 0.0250385,
# "maxHeight": 2099399,
# "txsCount": 5,
# "timeClose": "2020-06-09T14:47:59.999Z"
# }
# }
# ]
# }
#
data = self.safe_value(response, 'data', [])
result = self.parse_ohlcvs(data, market, timeframe, since, limit)
result = self.filter_future_candles(result)
lastClose = None
length = len(result)
for i in range(0, len(result)):
j = length - i - 1
entry = result[j]
open = entry[1]
if open is None:
entry[1] = lastClose
entry[2] = lastClose
entry[3] = lastClose
entry[4] = lastClose
result[j] = entry
lastClose = entry[4]
return result
def filter_future_candles(self, ohlcvs):
result = []
timestamp = self.milliseconds()
for i in range(0, len(ohlcvs)):
if ohlcvs[i][0] > timestamp:
# stop when getting data from the future
break
result.append(ohlcvs[i])
return result
def parse_ohlcv(self, ohlcv, market=None):
#
# {
# __type: 'candle',
# data: {
# time: '2020-06-05T20:46:00.000Z',
# open: 240.573975,
# close: 240.573975,
# high: 240.573975,
# low: 240.573975,
# volume: 0.01278413,
# quoteVolume: 3.075528,
# weightedAveragePrice: 240.573975,
# maxHeight: 2093895,
# txsCount: 5,
# timeClose: '2020-06-05T20:46:59.999Z'
# }
# }
#
data = self.safe_value(ohlcv, 'data', {})
return [
self.parse8601(self.safe_string(data, 'time')),
self.safe_number(data, 'open'),
self.safe_number(data, 'high'),
self.safe_number(data, 'low'),
self.safe_number(data, 'close'),
self.safe_number(data, 'volume', 0),
]
async def fetch_deposit_address(self, code, params={}):
await self.sign_in()
networks = self.safe_value(self.options, 'networks', {})
rawNetwork = self.safe_string_upper(params, 'network')
network = self.safe_string(networks, rawNetwork, rawNetwork)
params = self.omit(params, ['network'])
supportedCurrencies = await self.privateGetPlatforms()
#
# {
# "type": "list",
# "page_info": {
# "has_next_page": False,
# "last_cursor": null
# },
# "items": [
# {
# "type": "platform",
# "id": "ETH",
# "name": "Ethereum",
# "currencies": [
# "BAG",
# "BNT",
# "CRV",
# "EGG",
# "ETH",
# "EURN",
# "FL",
# "NSBT",
# "USDAP",
# "USDC",
# "USDFL",
# "USDN",
# "USDT",
# "WAVES"
# ]
# }
# ]
# }
#
currencies = {}
networksByCurrency = {}
items = self.safe_value(supportedCurrencies, 'items', [])
for i in range(0, len(items)):
entry = items[i]
currencyId = self.safe_string(entry, 'id')
innerCurrencies = self.safe_value(entry, 'currencies', [])
for j in range(0, len(innerCurrencies)):
currencyCode = self.safe_string(innerCurrencies, j)
currencies[currencyCode] = True
if not (currencyCode in networksByCurrency):
networksByCurrency[currencyCode] = {}
networksByCurrency[currencyCode][currencyId] = True
if not (code in currencies):
codes = list(currencies.keys())
raise ExchangeError(self.id + ' fetch ' + code + ' deposit address not supported. Currency code must be one of ' + ', '.join(codes))
response = None
if network is None:
request = {
'currency': code,
}
response = await self.privateGetDepositAddressesCurrency(self.extend(request, params))
else:
supportedNetworks = networksByCurrency[code]
if not (network in supportedNetworks):
supportedNetworkKeys = list(supportedNetworks.keys())
raise ExchangeError(self.id + ' ' + network + ' network ' + code + ' deposit address not supported. Network must be one of ' + ', '.join(supportedNetworkKeys))
if network == 'WAVES':
request = {
'publicKey': self.apiKey,
}
response = await self.nodeGetAddressesPublicKeyPublicKey(self.extend(request, request))
address = self.safe_string(response, 'address')
return {
'address': address,
'code': code,
'network': network,
'tag': None,
'info': response,
}
else:
request = {
'currency': code,
'platform': network,
}
response = await self.privateGetDepositAddressesCurrencyPlatform(self.extend(request, params))
#
# {
# "type": "deposit_addresses",
# "currency": {
# "type": "deposit_currency",
# "id": "ERGO",
# "waves_asset_id": "5dJj4Hn9t2Ve3tRpNGirUHy4yBK6qdJRAJYV21yPPuGz",
# "platform_id": "BSC",
# "decimals": 9,
# "status": "active",
# "allowed_amount": {
# "min": 0.001,
# "max": 100000
# },
# "fees": {
# "flat": 0,
# "rate": 0
# }
# },
# "deposit_addresses": [
# "9fRAAQjF8Yqg7qicQCL884zjimsRnuwsSavsM1rUdDaoG8mThku"
# ]
# }
currency = self.safe_value(response, 'currency')
networkId = self.safe_string(currency, 'platform_id')
reverseNetworks = self.safe_value(self.options, 'reverseNetworks', {})
unifiedNetwork = self.safe_string(reverseNetworks, networkId, networkId)
addresses = self.safe_value(response, 'deposit_addresses')
address = self.safe_string(addresses, 0)
return {
'address': address,
'code': code,
'tag': None,
'network': unifiedNetwork,
'info': response,
}
async def get_matcher_public_key(self):
# self method returns a single string
matcherPublicKey = self.safe_string(self.options, 'matcherPublicKey')
if matcherPublicKey:
return matcherPublicKey
else:
response = await self.matcherGetMatcher()
# remove trailing quotes from string response
self.options['matcherPublicKey'] = response[1:len(response) - 1]
return self.options['matcherPublicKey']
def get_asset_bytes(self, currencyId):
if currencyId == 'WAVES':
return self.number_to_be(0, 1)
else:
return self.binary_concat(self.number_to_be(1, 1), self.base58_to_binary(currencyId))
def get_asset_id(self, currencyId):
if currencyId == 'WAVES':
return ''
return currencyId
def price_to_precision(self, symbol, price):
market = self.markets[symbol]
wavesPrecision = self.safe_integer(self.options, 'wavesPrecision', 8)
difference = market['precision']['amount'] - market['precision']['price']
return int(float(self.to_precision(price, wavesPrecision - difference)))
def amount_to_precision(self, symbol, amount):
return int(float(self.to_precision(amount, self.markets[symbol]['precision']['amount'])))
def currency_to_precision(self, code, amount):
return int(float(self.to_precision(amount, self.currencies[code]['precision'])))
def from_precision(self, amount, scale):
if amount is None:
return None
precise = Precise(amount)
precise.decimals = precise.decimals + scale
precise.reduce()
return str(precise)
def to_precision(self, amount, scale):
amountString = str(amount)
precise = Precise(amountString)
precise.decimals = precise.decimals - scale
precise.reduce()
return str(precise)
def currency_from_precision(self, currency, amount):
scale = self.currencies[currency]['precision']
return self.from_precision(amount, scale)
def price_from_precision(self, symbol, price):
market = self.markets[symbol]
wavesPrecision = self.safe_integer(self.options, 'wavesPrecision', 8)
scale = wavesPrecision - market['precision']['amount'] + market['precision']['price']
return self.from_precision(price, scale)
def safe_get_dynamic(self, settings):
orderFee = self.safe_value(settings, 'orderFee')
if 'dynamic' in orderFee:
return self.safe_value(orderFee, 'dynamic')
else:
return self.safe_value(orderFee['composite']['default'], 'dynamic')
def safe_get_rates(self, dynamic):
rates = self.safe_value(dynamic, 'rates')
if rates is None:
return {'WAVES': 1}
return rates
async def create_order(self, symbol, type, side, amount, price=None, params={}):
self.check_required_dependencies()
self.check_required_keys()
await self.load_markets()
market = self.market(symbol)
matcherPublicKey = await self.get_matcher_public_key()
amountAsset = self.get_asset_id(market['baseId'])
priceAsset = self.get_asset_id(market['quoteId'])
isMarketOrder = (type == 'market')
if (isMarketOrder) and (price is None):
raise InvalidOrder(self.id + ' createOrder() requires a price argument for ' + type + ' orders to determine the max price for buy and the min price for sell')
orderType = 0 if (side == 'buy') else 1
timestamp = self.milliseconds()
defaultExpiryDelta = self.safe_integer(self.options, 'createOrderDefaultExpiry', 2419200000)
expiration = self.sum(timestamp, defaultExpiryDelta)
matcherFees = await self.get_fees_for_asset(symbol, side, amount, price)
# {
# "base":{
# "feeAssetId":"WAVES", # varies depending on the trading pair
# "matcherFee":"1000000"
# },
# "discount":{
# "feeAssetId":"EMAMLxDnv3xiz8RXg8Btj33jcEw3wLczL3JKYYmuubpc",
# "matcherFee":"4077612"
# }
# }
base = self.safe_value(matcherFees, 'base')
baseFeeAssetId = self.safe_string(base, 'feeAssetId')
baseFeeAsset = self.safe_currency_code(baseFeeAssetId)
baseMatcherFee = self.safe_string(base, 'matcherFee')
discount = self.safe_value(matcherFees, 'discount')
discountFeeAssetId = self.safe_string(discount, 'feeAssetId')
discountFeeAsset = self.safe_currency_code(discountFeeAssetId)
discountMatcherFee = self.safe_string(discount, 'matcherFee')
matcherFeeAssetId = None
matcherFee = None
# check first if user supplied asset fee is valid
if ('feeAsset' in params) or ('feeAsset' in self.options):
feeAsset = self.safe_string(params, 'feeAsset', self.safe_string(self.options, 'feeAsset'))
feeCurrency = self.currency(feeAsset)
matcherFeeAssetId = self.safe_string(feeCurrency, 'id')
balances = await self.fetch_balance()
if matcherFeeAssetId is not None:
if baseFeeAssetId != matcherFeeAssetId and discountFeeAssetId != matcherFeeAssetId:
raise InvalidOrder(self.id + ' asset fee must be ' + baseFeeAsset + ' or ' + discountFeeAsset)
matcherFeeAsset = self.safe_currency_code(matcherFeeAssetId)
rawMatcherFee = baseMatcherFee if (matcherFeeAssetId == baseFeeAssetId) else discountMatcherFee
floatMatcherFee = float(self.currency_from_precision(matcherFeeAsset, rawMatcherFee))
if (matcherFeeAsset in balances) and (balances[matcherFeeAsset]['free'] >= floatMatcherFee):
matcherFee = int(rawMatcherFee)
else:
raise InsufficientFunds(self.id + ' not enough funds of the selected asset fee')
if matcherFeeAssetId is None:
# try to the pay the fee using the base first then discount asset
floatBaseMatcherFee = float(self.currency_from_precision(baseFeeAsset, baseMatcherFee))
if (baseFeeAsset in balances) and (balances[baseFeeAsset]['free'] >= floatBaseMatcherFee):
matcherFeeAssetId = baseFeeAssetId
matcherFee = int(baseMatcherFee)
else:
floatDiscountMatcherFee = float(self.currency_from_precision(discountFeeAsset, discountMatcherFee))
if (discountFeeAsset in balances) and (balances[discountFeeAsset]['free'] >= floatDiscountMatcherFee):
matcherFeeAssetId = discountFeeAssetId
matcherFee = int(discountMatcherFee)
if matcherFeeAssetId is None:
raise InsufficientFunds(self.id + ' not enough funds on none of the eligible asset fees')
amount = self.amount_to_precision(symbol, amount)
price = self.price_to_precision(symbol, price)
byteArray = [
self.number_to_be(3, 1),
self.base58_to_binary(self.apiKey),
self.base58_to_binary(matcherPublicKey),
self.get_asset_bytes(market['baseId']),
self.get_asset_bytes(market['quoteId']),
self.number_to_be(orderType, 1),
self.number_to_be(price, 8),
self.number_to_be(amount, 8),
self.number_to_be(timestamp, 8),
self.number_to_be(expiration, 8),
self.number_to_be(matcherFee, 8),
self.get_asset_bytes(matcherFeeAssetId),
]
binary = self.binary_concat_array(byteArray)
signature = self.eddsa(self.binary_to_base16(binary), self.binary_to_base16(self.base58_to_binary(self.secret)), 'ed25519')
assetPair = {
'amountAsset': amountAsset,
'priceAsset': priceAsset,
}
body = {
'senderPublicKey': self.apiKey,
'matcherPublicKey': matcherPublicKey,
'assetPair': assetPair,
'orderType': side,
'price': price,
'amount': amount,
'timestamp': timestamp,
'expiration': expiration,
'matcherFee': int(matcherFee),
'signature': signature,
'version': 3,
}
if matcherFeeAssetId != 'WAVES':
body['matcherFeeAssetId'] = matcherFeeAssetId
#
# {
# "success":true,
# "message":{
# "version":3,
# "id":"GK5ox4RfLJFtqjQsCbDmvCya8ZhFVEUQDtF4yYuAJ6C7",
# "sender":"3P8VzLSa23EW5CVckHbV7d5BoN75fF1hhFH",
# "senderPublicKey":"AHXn8nBA4SfLQF7hLQiSn16kxyehjizBGW1TdrmSZ1gF",
# "matcherPublicKey":"9cpfKN9suPNvfeUNphzxXMjcnn974eme8ZhWUjaktzU5",
# "assetPair":{
# "amountAsset":"C1iWsKGqLwjHUndiQ7iXpdmPum9PeCDFfyXBdJJosDRS",
# "priceAsset":"WAVES"
# },
# "orderType":"buy",
# "amount":110874978,
# "price":514397851,
# "timestamp":1650473255988,
# "expiration":1652892455988,
# "matcherFee":7074571,
# "matcherFeeAssetId":"Atqv59EYzjFGuitKVnMRk6H8FukjoV3ktPorbEys25on",
# "signature":"5Vgs6mbdZJv5Ce9mdobT6fppXr6bKn5WVDbzP6mGG5jMB5jgcA2eSScwctgvY5SwPm9n1bctAAKuXtLcdHjNNie8",
# "proofs":["5Vgs6mbdZJv5Ce9mdobT6fppXr6bKn5WVDbzP6mGG5jMB5jgcA2eSScwctgvY5SwPm9n1bctAAKuXtLcdHjNNie8"]
# },
# "status":"OrderAccepted"
# }
#
if isMarketOrder:
response = await self.matcherPostMatcherOrderbookMarket(body)
value = self.safe_value(response, 'message')
return self.parse_order(value, market)
else:
response = await self.matcherPostMatcherOrderbook(body)
value = self.safe_value(response, 'message')
return self.parse_order(value, market)
async def cancel_order(self, id, symbol=None, params={}):
self.check_required_dependencies()
self.check_required_keys()
await self.sign_in()
wavesAddress = await self.get_waves_address()
response = await self.forwardPostMatcherOrdersWavesAddressCancel({
'wavesAddress': wavesAddress,
'orderId': id,
})
# {
# "success":true,
# "message":[[{"orderId":"EBpJeGM36KKFz5gTJAUKDBm89V8wqxKipSFBdU35AN3c","success":true,"status":"OrderCanceled"}]],
# "status":"BatchCancelCompleted"
# }
message = self.safe_value(response, 'message')
firstMessage = self.safe_value(message, 0)
firstOrder = self.safe_value(firstMessage, 0)
returnedId = self.safe_string(firstOrder, 'orderId')
return {
'info': response,
'id': returnedId,
'clientOrderId': None,
'timestamp': None,
'datetime': None,
'lastTradeTimestamp': None,
'symbol': symbol,
'type': None,
'side': None,
'price': None,
'amount': None,
'cost': None,
'average': None,
'filled': None,
'remaining': None,
'status': None,
'fee': None,
'trades': None,
}
async def fetch_order(self, id, symbol=None, params={}):
self.check_required_dependencies()
self.check_required_keys()
await self.load_markets()
market = None
if symbol is not None:
market = self.market(symbol)
timestamp = self.milliseconds()
byteArray = [
self.base58_to_binary(self.apiKey),
self.number_to_be(timestamp, 8),
]
binary = self.binary_concat_array(byteArray)
hexSecret = self.binary_to_base16(self.base58_to_binary(self.secret))
signature = self.eddsa(self.binary_to_base16(binary), hexSecret, 'ed25519')
request = {
'Timestamp': str(timestamp),
'Signature': signature,
'publicKey': self.apiKey,
'orderId': id,
}
response = await self.matcherGetMatcherOrderbookPublicKeyOrderId(self.extend(request, params))
return self.parse_order(response, market)
async def fetch_orders(self, symbol=None, since=None, limit=None, params={}):
self.check_required_dependencies()
self.check_required_keys()
if symbol is None:
raise ArgumentsRequired(self.id + ' fetchOrders() requires symbol argument')
await self.load_markets()
market = self.market(symbol)
timestamp = self.milliseconds()
byteArray = [
self.base58_to_binary(self.apiKey),
self.number_to_be(timestamp, 8),
]
binary = self.binary_concat_array(byteArray)
hexSecret = self.binary_to_base16(self.base58_to_binary(self.secret))
signature = self.eddsa(self.binary_to_base16(binary), hexSecret, 'ed25519')
request = {
'Accept': 'application/json',
'Timestamp': str(timestamp),
'Signature': signature,
'publicKey': self.apiKey,
'baseId': market['baseId'],
'quoteId': market['quoteId'],
}
response = await self.matcherGetMatcherOrderbookBaseIdQuoteIdPublicKeyPublicKey(self.extend(request, params))
# [{id: '3KicDeWayY2mdrRoYdCkP3gUAoUZUNT1AA6GAtWuPLfa',
# type: 'sell',
# orderType: 'limit',
# amount: 1,
# fee: 300000,
# price: 100000000,
# timestamp: 1591651254076,
# filled: 0,
# filledFee: 0,
# feeAsset: 'WAVES',
# status: 'Accepted',
# assetPair:
# {amountAsset: null,
# priceAsset: '8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS'},
# avgWeighedPrice: 0}, ...]
return self.parse_orders(response, market, since, limit)
async def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
await self.load_markets()
await self.sign_in()
market = None
if symbol is not None:
market = self.market(symbol)
address = await self.get_waves_address()
request = {
'address': address,
'activeOnly': True,
}
response = await self.forwardGetMatcherOrdersAddress(request)
return self.parse_orders(response, market, since, limit)
async def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):
await self.load_markets()
await self.sign_in()
market = None
if symbol is not None:
market = self.market(symbol)
address = await self.get_waves_address()
request = {
'address': address,
'closedOnly': True,
}
response = await self.forwardGetMatcherOrdersAddress(request)
# [
# {
# "id": "9aXcxvXai73jbAm7tQNnqaQ2PwUjdmWuyjvRTKAHsw4f",
# "type": "buy",
# "orderType": "limit",
# "amount": 23738330,
# "fee": 300000,
# "price": 3828348334,
# "timestamp": 1591926905636,
# "filled": 23738330,
# "filledFee": 300000,
# "feeAsset": "WAVES",
# "status": "Filled",
# "assetPair": {
# "amountAsset": "HZk1mbfuJpmxU1Fs4AX5MWLVYtctsNcg6e2C6VKqK8zk",
# "priceAsset": null
# },
# "avgWeighedPrice": 3828348334
# }, ...
# ]
return self.parse_orders(response, market, since, limit)
def parse_order_status(self, status):
statuses = {
'Cancelled': 'canceled',
'Accepted': 'open',
'Filled': 'closed',
'PartiallyFilled': 'open',
}
return self.safe_string(statuses, status, status)
def get_symbol_from_asset_pair(self, assetPair):
# a blank string or null can indicate WAVES
baseId = self.safe_string(assetPair, 'amountAsset', 'WAVES')
quoteId = self.safe_string(assetPair, 'priceAsset', 'WAVES')
return self.safe_currency_code(baseId) + '/' + self.safe_currency_code(quoteId)
def parse_order(self, order, market=None):
#
# createOrder
#
# {
# 'version': 3,
# 'id': 'BshyeHXDfJmTnjTdBYt371jD4yWaT3JTP6KpjpsiZepS',
# 'sender': '3P8VzLSa23EW5CVckHbV7d5BoN75fF1hhFH',
# 'senderPublicKey': 'AHXn8nBA4SfLQF7hLQiSn16kxyehjizBGW1TdrmSZ1gF',
# 'matcherPublicKey': '9cpfKN9suPNvfeUNphzxXMjcnn974eme8ZhWUjaktzU5',
# 'assetPair': {
# 'amountAsset': '474jTeYx2r2Va35794tCScAXWJG9hU2HcgxzMowaZUnu',
# 'priceAsset': 'DG2xFkPdDwKUoBkzGAhQtLpSGzfXLiCYPEzeKH2Ad24p',
# },
# 'orderType': 'buy',
# 'amount': 10000,
# 'price': 400000000,
# 'timestamp': 1599848586891,
# 'expiration': 1602267786891,
# 'matcherFee': 3008,
# 'matcherFeeAssetId': '474jTeYx2r2Va35794tCScAXWJG9hU2HcgxzMowaZUnu',
# 'signature': '3D2h8ubrhuWkXbVn4qJ3dvjmZQxLoRNfjTqb9uNpnLxUuwm4fGW2qGH6yKFe2SQPrcbgkS3bDVe7SNtMuatEJ7qy',
# 'proofs': [
# '3D2h8ubrhuWkXbVn4qJ3dvjmZQxLoRNfjTqb9uNpnLxUuwm4fGW2qGH6yKFe2SQPrcbgkS3bDVe7SNtMuatEJ7qy',
# ],
# }
#
#
# fetchOrder, fetchOrders, fetchOpenOrders, fetchClosedOrders
#
# {
# id: '81D9uKk2NfmZzfG7uaJsDtxqWFbJXZmjYvrL88h15fk8',
# type: 'buy',
# orderType: 'limit',
# amount: 30000000000,
# filled: 0,
# price: 1000000,
# fee: 300000,
# filledFee: 0,
# feeAsset: 'WAVES',
# timestamp: 1594303779322,
# status: 'Cancelled',
# assetPair: {
# amountAsset: '474jTeYx2r2Va35794tCScAXWJG9hU2HcgxzMowaZUnu',
# priceAsset: 'WAVES'
# },
# avgWeighedPrice: 0,
# version: 3,
# totalExecutedPriceAssets: 0, # in fetchOpenOrder/s
# }
#
timestamp = self.safe_integer(order, 'timestamp')
side = self.safe_string_2(order, 'type', 'orderType')
type = 'limit'
if 'type' in order:
# fetchOrders
type = self.safe_string(order, 'orderType', type)
id = self.safe_string(order, 'id')
filledString = self.safe_string(order, 'filled')
priceString = self.safe_string(order, 'price')
amountString = self.safe_string(order, 'amount')
assetPair = self.safe_value(order, 'assetPair')
symbol = None
if assetPair is not None:
symbol = self.get_symbol_from_asset_pair(assetPair)
elif market is not None:
symbol = market['symbol']
amountCurrency = self.safe_currency_code(self.safe_string(assetPair, 'amountAsset', 'WAVES'))
price = self.price_from_precision(symbol, priceString)
amount = self.currency_from_precision(amountCurrency, amountString)
filled = self.currency_from_precision(amountCurrency, filledString)
average = self.price_from_precision(symbol, self.safe_string(order, 'avgWeighedPrice'))
status = self.parse_order_status(self.safe_string(order, 'status'))
fee = None
if 'type' in order:
currency = self.safe_currency_code(self.safe_string(order, 'feeAsset'))
fee = {
'currency': currency,
'fee': self.parse_number(self.currency_from_precision(currency, self.safe_string(order, 'filledFee'))),
}
else:
currency = self.safe_currency_code(self.safe_string(order, 'matcherFeeAssetId', 'WAVES'))
fee = {
'currency': currency,
'fee': self.parse_number(self.currency_from_precision(currency, self.safe_string(order, 'matcherFee'))),
}
return self.safe_order({
'info': order,
'id': id,
'clientOrderId': None,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'lastTradeTimestamp': None,
'symbol': symbol,
'type': type,
'timeInForce': None,
'postOnly': None,
'side': side,
'price': price,
'stopPrice': None,
'amount': amount,
'cost': None,
'average': average,
'filled': filled,
'remaining': None,
'status': status,
'fee': fee,
'trades': None,
}, market)
async def get_waves_address(self):
cachedAddreess = self.safe_string(self.options, 'wavesAddress')
if cachedAddreess is None:
request = {
'publicKey': self.apiKey,
}
response = await self.nodeGetAddressesPublicKeyPublicKey(request)
self.options['wavesAddress'] = self.safe_string(response, 'address')
return self.options['wavesAddress']
else:
return cachedAddreess
async def fetch_balance(self, params={}):
# makes a lot of different requests to get all the data
# in particular:
# fetchMarkets, getWavesAddress,
# getTotalBalance(doesn't include waves), getReservedBalance(doesn't include waves)
# getReservedBalance(includes WAVES)
# I couldn't find another way to get all the data
self.check_required_dependencies()
self.check_required_keys()
await self.load_markets()
wavesAddress = await self.get_waves_address()
request = {
'address': wavesAddress,
}
totalBalance = await self.nodeGetAssetsBalanceAddress(request)
balances = self.safe_value(totalBalance, 'balances')
result = {}
timestamp = None
assetIds = []
nonStandardBalances = []
for i in range(0, len(balances)):
entry = balances[i]
entryTimestamp = self.safe_integer(entry, 'timestamp')
timestamp = entryTimestamp if (timestamp is None) else max(timestamp, entryTimestamp)
issueTransaction = self.safe_value(entry, 'issueTransaction')
currencyId = self.safe_string(entry, 'assetId')
balance = self.safe_string(entry, 'balance')
if issueTransaction is None:
assetIds.append(currencyId)
nonStandardBalances.append(balance)
continue
decimals = self.safe_integer(issueTransaction, 'decimals')
code = None
if currencyId in self.currencies_by_id:
code = self.safe_currency_code(currencyId)
result[code] = self.account()
result[code]['total'] = self.from_precision(balance, decimals)
nonStandardAssets = len(assetIds)
if nonStandardAssets:
request = {
'ids': assetIds,
}
response = await self.publicGetAssets(request)
data = self.safe_value(response, 'data')
for i in range(0, len(data)):
entry = data[i]
balance = nonStandardBalances[i]
inner = self.safe_value(entry, 'data')
decimals = self.safe_integer(inner, 'precision')
ticker = self.safe_string(inner, 'ticker')
code = self.safe_currency_code(ticker)
result[code] = self.account()
result[code]['total'] = self.from_precision(balance, decimals)
currentTimestamp = self.milliseconds()
byteArray = [
self.base58_to_binary(self.apiKey),
self.number_to_be(currentTimestamp, 8),
]
binary = self.binary_concat_array(byteArray)
hexSecret = self.binary_to_base16(self.base58_to_binary(self.secret))
signature = self.eddsa(self.binary_to_base16(binary), hexSecret, 'ed25519')
matcherRequest = {
'publicKey': self.apiKey,
'signature': signature,
'timestamp': str(currentTimestamp),
}
reservedBalance = await self.matcherGetMatcherBalanceReservedPublicKey(matcherRequest)
reservedKeys = list(reservedBalance.keys())
for i in range(0, len(reservedKeys)):
currencyId = reservedKeys[i]
code = self.safe_currency_code(currencyId)
if not (code in result):
result[code] = self.account()
amount = self.safe_string(reservedBalance, currencyId)
if code in self.currencies:
result[code]['used'] = self.currency_from_precision(code, amount)
else:
result[code]['used'] = amount
wavesRequest = {
'address': wavesAddress,
}
wavesTotal = await self.nodeGetAddressesBalanceAddress(wavesRequest)
result['WAVES'] = self.safe_value(result, 'WAVES', {})
result['WAVES']['total'] = self.currency_from_precision('WAVES', self.safe_string(wavesTotal, 'balance'))
codes = list(result.keys())
for i in range(0, len(codes)):
code = codes[i]
if self.safe_value(result[code], 'used') is None:
result[code]['used'] = '0'
result['timestamp'] = timestamp
result['datetime'] = self.iso8601(timestamp)
return self.safe_balance(result)
async def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
await self.load_markets()
market = self.market(symbol)
address = await self.get_waves_address()
request = {
'sender': address,
'amountAsset': market['baseId'],
'priceAsset': market['quoteId'],
}
response = await self.publicGetTransactionsExchange(request)
data = self.safe_value(response, 'data')
return self.parse_trades(data, market, since, limit)
async def fetch_trades(self, symbol, since=None, limit=None, params={}):
await self.load_markets()
market = self.market(symbol)
request = {
'amountAsset': market['baseId'],
'priceAsset': market['quoteId'],
}
if limit is not None:
request['limit'] = limit
if since is not None:
request['timeStart'] = since
response = await self.publicGetTransactionsExchange(request)
data = self.safe_value(response, 'data')
return self.parse_trades(data, market, since, limit)
def parse_trade(self, trade, market=None):
data = self.safe_value(trade, 'data')
datetime = self.safe_string(data, 'timestamp')
timestamp = self.parse8601(datetime)
id = self.safe_string(data, 'id')
priceString = self.safe_string(data, 'price')
amountString = self.safe_string(data, 'amount')
order1 = self.safe_value(data, 'order1')
order2 = self.safe_value(data, 'order2')
order = None
if self.safe_string(order1, 'senderPublicKey') == self.apiKey:
order = order1
else:
order = order2
symbol = None
assetPair = self.safe_value(order, 'assetPair')
if assetPair is not None:
symbol = self.get_symbol_from_asset_pair(assetPair)
elif market is not None:
symbol = market['symbol']
side = self.safe_string(order, 'orderType')
orderId = self.safe_string(order, 'id')
fee = {
'cost': self.safe_string(order, 'matcherFee'),
'currency': self.safe_currency_code(self.safe_string(order, 'matcherFeeAssetId', 'WAVES')),
}
return self.safe_trade({
'info': trade,
'timestamp': timestamp,
'datetime': datetime,
'symbol': symbol,
'id': id,
'order': orderId,
'type': None,
'side': side,
'takerOrMaker': None,
'price': priceString,
'amount': amountString,
'cost': None,
'fee': fee,
}, market)
def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody):
errorCode = self.safe_string(response, 'error')
success = self.safe_value(response, 'success', True)
Exception = self.safe_value(self.exceptions, errorCode)
if Exception is not None:
message = self.safe_string(response, 'message')
raise Exception(self.id + ' ' + message)
message = self.safe_string(response, 'message')
if message == 'Validation Error':
raise BadRequest(self.id + ' ' + body)
if not success:
raise ExchangeError(self.id + ' ' + body)
async def withdraw(self, code, amount, address, tag=None, params={}):
tag, params = self.handle_withdraw_tag_and_params(tag, params)
if code != 'WAVES':
supportedCurrencies = await self.privateGetWithdrawCurrencies()
currencies = {}
items = self.safe_value(supportedCurrencies, 'items', [])
for i in range(0, len(items)):
entry = items[i]
currencyCode = self.safe_string(entry, 'id')
currencies[currencyCode] = True
if not (code in currencies):
codes = list(currencies.keys())
raise ExchangeError(self.id + ' fetch ' + code + ' withdrawals are not supported. Currency code must be one of ' + str(codes))
await self.load_markets()
hexChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
set = {}
for i in range(0, len(hexChars)):
key = hexChars[i]
set[key] = True
isErc20 = True
noPrefix = self.remove0x_prefix(address)
lower = noPrefix.lower()
for i in range(0, len(lower)):
character = lower[i]
if not (character in set):
isErc20 = False
break
await self.sign_in()
proxyAddress = None
if code == 'WAVES' and not isErc20:
proxyAddress = address
else:
withdrawAddressRequest = {
'address': address,
'currency': code,
}
withdrawAddress = await self.privateGetWithdrawAddressesCurrencyAddress(withdrawAddressRequest)
currency = self.safe_value(withdrawAddress, 'currency')
allowedAmount = self.safe_value(currency, 'allowed_amount')
minimum = self.safe_number(allowedAmount, 'min')
if amount <= minimum:
raise BadRequest(self.id + ' ' + code + ' withdraw failed, amount ' + str(amount) + ' must be greater than the minimum allowed amount of ' + str(minimum))
proxyAddresses = self.safe_value(withdrawAddress, 'proxy_addresses', [])
proxyAddress = self.safe_string(proxyAddresses, 0)
fee = self.safe_integer(self.options, 'withdrawFeeWAVES', 100000)
feeAssetId = 'WAVES'
type = 4
version = 2
amountInteger = self.currency_to_precision(code, amount)
currency = self.currency(code)
timestamp = self.milliseconds()
byteArray = [
self.number_to_be(4, 1),
self.number_to_be(2, 1),
self.base58_to_binary(self.apiKey),
self.get_asset_bytes(currency['id']),
self.get_asset_bytes(feeAssetId),
self.number_to_be(timestamp, 8),
self.number_to_be(amountInteger, 8),
self.number_to_be(fee, 8),
self.base58_to_binary(proxyAddress),
self.number_to_be(0, 2),
]
binary = self.binary_concat_array(byteArray)
hexSecret = self.binary_to_base16(self.base58_to_binary(self.secret))
signature = self.eddsa(self.binary_to_base16(binary), hexSecret, 'ed25519')
request = {
'senderPublicKey': self.apiKey,
'amount': amountInteger,
'fee': fee,
'type': type,
'version': version,
'attachment': '',
'feeAssetId': self.get_asset_id(feeAssetId),
'proofs': [
signature,
],
'assetId': self.get_asset_id(currency['id']),
'recipient': proxyAddress,
'timestamp': timestamp,
'signature': signature,
}
result = await self.nodePostTransactionsBroadcast(request)
return self.parse_transaction(result, currency)
def parse_transaction(self, transaction, currency=None):
currency = self.safe_currency(None, currency)
return {
'id': None,
'txid': None,
'timestamp': None,
'datetime': None,
'network': None,
'addressFrom': None,
'address': None,
'addressTo': None,
'amount': None,
'type': None,
'currency': currency['code'],
'status': None,
'updated': None,
'tagFrom': None,
'tag': None,
'tagTo': None,
'comment': None,
'fee': None,
'info': transaction,
}
| true | true |
1c2bc3a25d7069e9289c2b367bcecdf522ac1c1a | 3,427 | py | Python | huaweicloud-sdk-dcs/huaweicloudsdkdcs/v2/model/update_password_request.py | wuchen-huawei/huaweicloud-sdk-python-v3 | 3683d703f4320edb2b8516f36f16d485cff08fc2 | [
"Apache-2.0"
] | 1 | 2021-11-03T07:54:50.000Z | 2021-11-03T07:54:50.000Z | huaweicloud-sdk-dcs/huaweicloudsdkdcs/v2/model/update_password_request.py | wuchen-huawei/huaweicloud-sdk-python-v3 | 3683d703f4320edb2b8516f36f16d485cff08fc2 | [
"Apache-2.0"
] | null | null | null | huaweicloud-sdk-dcs/huaweicloudsdkdcs/v2/model/update_password_request.py | wuchen-huawei/huaweicloud-sdk-python-v3 | 3683d703f4320edb2b8516f36f16d485cff08fc2 | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
import pprint
import re
import six
class UpdatePasswordRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'instance_id': 'str',
'body': 'ModifyInstancePasswordBody'
}
attribute_map = {
'instance_id': 'instance_id',
'body': 'body'
}
def __init__(self, instance_id=None, body=None):
"""UpdatePasswordRequest - a model defined in huaweicloud sdk"""
self._instance_id = None
self._body = None
self.discriminator = None
self.instance_id = instance_id
if body is not None:
self.body = body
@property
def instance_id(self):
"""Gets the instance_id of this UpdatePasswordRequest.
实例ID。
:return: The instance_id of this UpdatePasswordRequest.
:rtype: str
"""
return self._instance_id
@instance_id.setter
def instance_id(self, instance_id):
"""Sets the instance_id of this UpdatePasswordRequest.
实例ID。
:param instance_id: The instance_id of this UpdatePasswordRequest.
:type: str
"""
self._instance_id = instance_id
@property
def body(self):
"""Gets the body of this UpdatePasswordRequest.
:return: The body of this UpdatePasswordRequest.
:rtype: ModifyInstancePasswordBody
"""
return self._body
@body.setter
def body(self, body):
"""Sets the body of this UpdatePasswordRequest.
:param body: The body of this UpdatePasswordRequest.
:type: ModifyInstancePasswordBody
"""
self._body = body
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, UpdatePasswordRequest):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 25.385185 | 74 | 0.553254 |
import pprint
import re
import six
class UpdatePasswordRequest:
sensitive_list = []
openapi_types = {
'instance_id': 'str',
'body': 'ModifyInstancePasswordBody'
}
attribute_map = {
'instance_id': 'instance_id',
'body': 'body'
}
def __init__(self, instance_id=None, body=None):
self._instance_id = None
self._body = None
self.discriminator = None
self.instance_id = instance_id
if body is not None:
self.body = body
@property
def instance_id(self):
return self._instance_id
@instance_id.setter
def instance_id(self, instance_id):
self._instance_id = instance_id
@property
def body(self):
return self._body
@body.setter
def body(self, body):
self._body = body
def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
return pprint.pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
if not isinstance(other, UpdatePasswordRequest):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
1c2bc44d4ae2e40e2df2e5a7fd7b06e1b26b0809 | 1,693 | py | Python | NASA SPACEAPPS CHALLENGE/Solution/Software part/Astronomical Data and Python Libraries/Astropy/astropy-1.1.2/astropy/constants/__init__.py | sahirsharma/Martian | 062e9b47849512863c16713811f347ad7e121b56 | [
"MIT"
] | null | null | null | NASA SPACEAPPS CHALLENGE/Solution/Software part/Astronomical Data and Python Libraries/Astropy/astropy-1.1.2/astropy/constants/__init__.py | sahirsharma/Martian | 062e9b47849512863c16713811f347ad7e121b56 | [
"MIT"
] | null | null | null | NASA SPACEAPPS CHALLENGE/Solution/Software part/Astronomical Data and Python Libraries/Astropy/astropy-1.1.2/astropy/constants/__init__.py | sahirsharma/Martian | 062e9b47849512863c16713811f347ad7e121b56 | [
"MIT"
] | null | null | null | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Contains astronomical and physical constants for use in Astropy or other
places.
A typical use case might be::
>>> from astropy.constants import c, m_e
>>> # ... define the mass of something you want the rest energy of as m ...
>>> m = m_e
>>> E = m * c**2
>>> E.to('MeV') # doctest: +FLOAT_CMP
<Quantity 0.510998927603161 MeV>
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import itertools
# Hack to make circular imports with units work
try:
from .. import units
del units
except ImportError:
pass
from .constant import Constant, EMConstant
from . import si
from . import cgs
# for updating the constants module docstring
_lines = [
'The following constants are available:\n',
'========== ============== ================ =========================',
' Name Value Unit Description',
'========== ============== ================ =========================',
]
for _nm, _c in itertools.chain(sorted(vars(si).items()),
sorted(vars(cgs).items())):
if isinstance(_c, Constant) and _c.abbrev not in locals():
locals()[_c.abbrev] = _c.__class__(_c.abbrev, _c.name, _c.value,
_c._unit_string, _c.uncertainty,
_c.reference)
_lines.append('{0:^10} {1:^14.9g} {2:^16} {3}'.format(
_c.abbrev, _c.value, _c._unit_string, _c.name))
_lines.append(_lines[1])
if __doc__ is not None:
__doc__ += '\n'.join(_lines)
del _lines, _nm, _c
| 30.232143 | 79 | 0.550502 |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import itertools
try:
from .. import units
del units
except ImportError:
pass
from .constant import Constant, EMConstant
from . import si
from . import cgs
_lines = [
'The following constants are available:\n',
'========== ============== ================ =========================',
' Name Value Unit Description',
'========== ============== ================ =========================',
]
for _nm, _c in itertools.chain(sorted(vars(si).items()),
sorted(vars(cgs).items())):
if isinstance(_c, Constant) and _c.abbrev not in locals():
locals()[_c.abbrev] = _c.__class__(_c.abbrev, _c.name, _c.value,
_c._unit_string, _c.uncertainty,
_c.reference)
_lines.append('{0:^10} {1:^14.9g} {2:^16} {3}'.format(
_c.abbrev, _c.value, _c._unit_string, _c.name))
_lines.append(_lines[1])
if __doc__ is not None:
__doc__ += '\n'.join(_lines)
del _lines, _nm, _c
| true | true |
1c2bc56c431a8930996709b573d3ff160e8b2b3d | 738 | py | Python | ros_sandbox/catkin_ws/src/beginner/scripts/listener.py | kjgonzalez/codefiles | b86f25182d1b5553a331f8721dd06b51fa157c3e | [
"MIT"
] | null | null | null | ros_sandbox/catkin_ws/src/beginner/scripts/listener.py | kjgonzalez/codefiles | b86f25182d1b5553a331f8721dd06b51fa157c3e | [
"MIT"
] | 10 | 2019-10-01T20:48:15.000Z | 2020-04-14T18:21:09.000Z | ros_sandbox/catkin_ws/src/beginner/scripts/listener.py | kjgonzalez/codefiles | b86f25182d1b5553a331f8721dd06b51fa157c3e | [
"MIT"
] | null | null | null | #!/usr/bin/env python
'''
see talker.py for more information
'''
import rospy
from std_msgs.msg import String
def callback(data):
rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
def listener():
# In ROS, nodes are uniquely named. If two nodes with the same
# name are launched, the previous one is kicked off. The
# anonymous=True flag means that rospy will choose a unique
# name for our 'listener' node so that multiple listeners can
# run simultaneously.
rospy.init_node('listener', anonymous=True)
rospy.Subscriber("chatter", String, callback)
# spin() simply keeps python from exiting until this node is stopped
rospy.spin()
if __name__ == '__main__':
listener()
| 26.357143 | 72 | 0.699187 |
import rospy
from std_msgs.msg import String
def callback(data):
rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
def listener():
rospy.init_node('listener', anonymous=True)
rospy.Subscriber("chatter", String, callback)
rospy.spin()
if __name__ == '__main__':
listener()
| true | true |
1c2bc5a344893c7237a4fdc6553393d6f0ff80f8 | 4,724 | py | Python | datasets/kor_hate/kor_hate.py | WojciechKusa/datasets | 1406a04c3e911cec2680d8bc513653e0cafcaaa4 | [
"Apache-2.0"
] | 10,608 | 2020-09-10T15:47:50.000Z | 2022-03-31T22:51:47.000Z | datasets/kor_hate/kor_hate.py | realChainLife/datasets | 98261e8b0b7be4dbaaa71ae188b950f7fbe51bbd | [
"Apache-2.0"
] | 2,396 | 2020-09-10T14:55:31.000Z | 2022-03-31T19:41:04.000Z | datasets/kor_hate/kor_hate.py | realChainLife/datasets | 98261e8b0b7be4dbaaa71ae188b950f7fbe51bbd | [
"Apache-2.0"
] | 1,530 | 2020-09-10T21:43:10.000Z | 2022-03-31T01:59:12.000Z | # coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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.
"""Korean HateSpeech Dataset"""
import csv
import datasets
_CITATION = """\
@inproceedings{moon-etal-2020-beep,
title = "{BEEP}! {K}orean Corpus of Online News Comments for Toxic Speech Detection",
author = "Moon, Jihyung and
Cho, Won Ik and
Lee, Junbum",
booktitle = "Proceedings of the Eighth International Workshop on Natural Language Processing for Social Media",
month = jul,
year = "2020",
address = "Online",
publisher = "Association for Computational Linguistics",
url = "https://www.aclweb.org/anthology/2020.socialnlp-1.4",
pages = "25--31",
abstract = "Toxic comments in online platforms are an unavoidable social issue under the cloak of anonymity. Hate speech detection has been actively done for languages such as English, German, or Italian, where manually labeled corpus has been released. In this work, we first present 9.4K manually labeled entertainment news comments for identifying Korean toxic speech, collected from a widely used online news platform in Korea. The comments are annotated regarding social bias and hate speech since both aspects are correlated. The inter-annotator agreement Krippendorff{'}s alpha score is 0.492 and 0.496, respectively. We provide benchmarks using CharCNN, BiLSTM, and BERT, where BERT achieves the highest score on all tasks. The models generally display better performance on bias identification, since the hate speech detection is a more subjective issue. Additionally, when BERT is trained with bias label for hate speech detection, the prediction score increases, implying that bias and hate are intertwined. We make our dataset publicly available and open competitions with the corpus and benchmarks.",
}
"""
_DESCRIPTION = """\
Human-annotated Korean corpus collected from a popular domestic entertainment news aggregation platform
for toxic speech detection. Comments are annotated for gender bias, social bias and hate speech.
"""
_HOMEPAGE = "https://github.com/kocohub/korean-hate-speech"
_LICENSE = "Creative Commons"
_TRAIN_DOWNLOAD_URL = "https://raw.githubusercontent.com/kocohub/korean-hate-speech/master/labeled/train.tsv"
_TEST_DOWNLOAD_URL = "https://raw.githubusercontent.com/kocohub/korean-hate-speech/master/labeled/dev.tsv"
class KorHate(datasets.GeneratorBasedBuilder):
"""Korean Corpus of Online News Comments for Toxic Speech Detection"""
VERSION = datasets.Version("1.1.0")
def _info(self):
features = datasets.Features(
{
"comments": datasets.Value("string"),
"contain_gender_bias": datasets.features.ClassLabel(names=["False", "True"]),
"bias": datasets.features.ClassLabel(names=["none", "gender", "others"]),
"hate": datasets.features.ClassLabel(names=["hate", "offensive", "none"]),
}
)
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
supervised_keys=None,
homepage=_HOMEPAGE,
license=_LICENSE,
citation=_CITATION,
)
def _split_generators(self, dl_manager):
train_path = dl_manager.download_and_extract(_TRAIN_DOWNLOAD_URL)
test_path = dl_manager.download_and_extract(_TEST_DOWNLOAD_URL)
return [
datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": train_path}),
datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": test_path}),
]
def _generate_examples(self, filepath):
"""Generate Korean HateSpeech examples"""
with open(filepath, encoding="utf-8") as tsv_file:
tsv_reader = csv.DictReader(tsv_file, delimiter="\t", quoting=csv.QUOTE_NONE)
for id_, row in enumerate(tsv_reader):
yield id_, {
"comments": row["comments"],
"contain_gender_bias": row["contain_gender_bias"],
"bias": row["bias"],
"hate": row["hate"],
}
| 48.204082 | 1,117 | 0.703006 |
import csv
import datasets
_CITATION = """\
@inproceedings{moon-etal-2020-beep,
title = "{BEEP}! {K}orean Corpus of Online News Comments for Toxic Speech Detection",
author = "Moon, Jihyung and
Cho, Won Ik and
Lee, Junbum",
booktitle = "Proceedings of the Eighth International Workshop on Natural Language Processing for Social Media",
month = jul,
year = "2020",
address = "Online",
publisher = "Association for Computational Linguistics",
url = "https://www.aclweb.org/anthology/2020.socialnlp-1.4",
pages = "25--31",
abstract = "Toxic comments in online platforms are an unavoidable social issue under the cloak of anonymity. Hate speech detection has been actively done for languages such as English, German, or Italian, where manually labeled corpus has been released. In this work, we first present 9.4K manually labeled entertainment news comments for identifying Korean toxic speech, collected from a widely used online news platform in Korea. The comments are annotated regarding social bias and hate speech since both aspects are correlated. The inter-annotator agreement Krippendorff{'}s alpha score is 0.492 and 0.496, respectively. We provide benchmarks using CharCNN, BiLSTM, and BERT, where BERT achieves the highest score on all tasks. The models generally display better performance on bias identification, since the hate speech detection is a more subjective issue. Additionally, when BERT is trained with bias label for hate speech detection, the prediction score increases, implying that bias and hate are intertwined. We make our dataset publicly available and open competitions with the corpus and benchmarks.",
}
"""
_DESCRIPTION = """\
Human-annotated Korean corpus collected from a popular domestic entertainment news aggregation platform
for toxic speech detection. Comments are annotated for gender bias, social bias and hate speech.
"""
_HOMEPAGE = "https://github.com/kocohub/korean-hate-speech"
_LICENSE = "Creative Commons"
_TRAIN_DOWNLOAD_URL = "https://raw.githubusercontent.com/kocohub/korean-hate-speech/master/labeled/train.tsv"
_TEST_DOWNLOAD_URL = "https://raw.githubusercontent.com/kocohub/korean-hate-speech/master/labeled/dev.tsv"
class KorHate(datasets.GeneratorBasedBuilder):
VERSION = datasets.Version("1.1.0")
def _info(self):
features = datasets.Features(
{
"comments": datasets.Value("string"),
"contain_gender_bias": datasets.features.ClassLabel(names=["False", "True"]),
"bias": datasets.features.ClassLabel(names=["none", "gender", "others"]),
"hate": datasets.features.ClassLabel(names=["hate", "offensive", "none"]),
}
)
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
supervised_keys=None,
homepage=_HOMEPAGE,
license=_LICENSE,
citation=_CITATION,
)
def _split_generators(self, dl_manager):
train_path = dl_manager.download_and_extract(_TRAIN_DOWNLOAD_URL)
test_path = dl_manager.download_and_extract(_TEST_DOWNLOAD_URL)
return [
datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": train_path}),
datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": test_path}),
]
def _generate_examples(self, filepath):
with open(filepath, encoding="utf-8") as tsv_file:
tsv_reader = csv.DictReader(tsv_file, delimiter="\t", quoting=csv.QUOTE_NONE)
for id_, row in enumerate(tsv_reader):
yield id_, {
"comments": row["comments"],
"contain_gender_bias": row["contain_gender_bias"],
"bias": row["bias"],
"hate": row["hate"],
}
| true | true |
1c2bc5c356dac5e51b277bd6d832c1e32cf63e8b | 4,300 | py | Python | test/cut/test_cut_merge_supervisions.py | rosrad/lhotse | 177ce3a6b963d4ac56a87843a0130ccfc74b3a57 | [
"Apache-2.0"
] | 353 | 2020-10-31T10:38:51.000Z | 2022-03-30T05:22:52.000Z | test/cut/test_cut_merge_supervisions.py | rosrad/lhotse | 177ce3a6b963d4ac56a87843a0130ccfc74b3a57 | [
"Apache-2.0"
] | 353 | 2020-10-27T23:25:12.000Z | 2022-03-31T22:16:05.000Z | test/cut/test_cut_merge_supervisions.py | rosrad/lhotse | 177ce3a6b963d4ac56a87843a0130ccfc74b3a57 | [
"Apache-2.0"
] | 66 | 2020-11-01T06:08:08.000Z | 2022-03-29T02:03:07.000Z | from lhotse import CutSet
from lhotse.cut import PaddingCut
from lhotse.testing.dummies import DummyManifest, dummy_cut, dummy_supervision
def test_mono_cut_merge_supervisions():
cut = dummy_cut(
0,
duration=10,
supervisions=[
dummy_supervision(0, start=1, duration=2),
dummy_supervision(1, start=5, duration=3),
],
)
assert len(cut.supervisions) == 2
mcut = cut.merge_supervisions()
# original not modified
assert len(cut.supervisions) == 2
assert len(mcut.supervisions) == 1
s = mcut.supervisions[0]
assert s.id == "cat#dummy-segment-0000#dummy-segment-0001"
assert s.recording_id == "dummy-recording-0000" # not changed
assert s.recording_id == cut.supervisions[0].recording_id
assert s.start == 1
assert s.end == 8
assert s.duration == 7
assert s.channel == 0
assert s.text == "irrelevant irrelevant"
assert s.language == "cat#irrelevant#irrelevant"
assert s.speaker == "cat#irrelevant#irrelevant"
assert s.gender == "cat#irrelevant#irrelevant"
assert s.custom is not None
assert s.custom["custom_field"] == "cat#irrelevant#irrelevant"
def test_mono_cut_merge_supervisions_identity():
cut = dummy_cut(0, supervisions=[dummy_supervision(0)])
mcut = cut.merge_supervisions()
assert cut == mcut
def test_mono_cut_merge_supervisions_no_supervisions():
cut = dummy_cut(0, supervisions=[])
mcut = cut.merge_supervisions()
assert cut == mcut
def test_mono_cut_merge_supervisions_empty_fields():
cut = dummy_cut(
0,
duration=2,
supervisions=[dummy_supervision(0), dummy_supervision(1, start=1)],
)
# set the fields to None to check if the merged spvn also has None
cut.supervisions[0].speaker = None
cut.supervisions[1].speaker = None
mcut = cut.merge_supervisions()
assert mcut.supervisions[0].speaker is None
def test_mono_cut_merge_supervisions_custom_merge_fn():
cut = dummy_cut(
0,
duration=2,
supervisions=[dummy_supervision(0), dummy_supervision(1, start=1)],
)
# Note: in tests, by default there exists one custom field called "custom_field"
# we add custom field "a" and define a different merging behavior for it.
cut.supervisions[0].custom["a"] = 20
cut.supervisions[1].custom["a"] = -13
mcut = cut.merge_supervisions(
custom_merge_fn=lambda k, vs: sum(vs) if k == "a" else None
)
assert isinstance(mcut.supervisions[0].custom, dict)
assert mcut.supervisions[0].custom["a"] == 7
# "dummy_supervision" object has a "custom_field" set by default
assert mcut.supervisions[0].custom["custom_field"] is None
def test_padding_cut_merge_supervisions():
cut = PaddingCut("x", 1, 16000, 0)
mcut = cut.merge_supervisions()
assert cut == mcut
def test_mixed_cut_merge_supervisions():
cut0 = dummy_cut(0, supervisions=[dummy_supervision(0)])
cut1 = dummy_cut(1, supervisions=[dummy_supervision(1)])
# overlapping supervisions -- note that we don't do anything smart for them.
mixed = cut0.mix(cut1, offset_other_by=0.5)
assert len(mixed.supervisions) == 2
mcut = mixed.merge_supervisions()
# original not modified
assert len(mixed.supervisions) == 2
assert len(mcut.supervisions) == 1
s = mcut.supervisions[0]
assert s.id == "cat#dummy-segment-0000#dummy-segment-0001"
assert s.recording_id == "cat#dummy-recording-0000#dummy-recording-0001"
assert s.start == 0
assert s.end == 1.5
assert s.duration == 1.5
assert s.channel == -1
assert s.text == "irrelevant irrelevant"
assert s.language == "cat#irrelevant#irrelevant"
assert s.speaker == "cat#irrelevant#irrelevant"
assert s.gender == "cat#irrelevant#irrelevant"
assert s.custom is not None
assert s.custom["custom_field"] == "cat#irrelevant#irrelevant"
def test_mixed_cut_merge_supervisions_identity():
cut = dummy_cut(0, supervisions=[dummy_supervision(0)])
cut = cut.append(cut.drop_supervisions())
mcut = cut.merge_supervisions()
assert cut == mcut
def test_cut_set_merge_supervisions():
cuts = DummyManifest(CutSet, begin_id=0, end_id=2)
mcuts = cuts.merge_supervisions()
assert cuts == mcuts
| 33.59375 | 84 | 0.68907 | from lhotse import CutSet
from lhotse.cut import PaddingCut
from lhotse.testing.dummies import DummyManifest, dummy_cut, dummy_supervision
def test_mono_cut_merge_supervisions():
cut = dummy_cut(
0,
duration=10,
supervisions=[
dummy_supervision(0, start=1, duration=2),
dummy_supervision(1, start=5, duration=3),
],
)
assert len(cut.supervisions) == 2
mcut = cut.merge_supervisions()
assert len(cut.supervisions) == 2
assert len(mcut.supervisions) == 1
s = mcut.supervisions[0]
assert s.id == "cat#dummy-segment-0000#dummy-segment-0001"
assert s.recording_id == "dummy-recording-0000"
assert s.recording_id == cut.supervisions[0].recording_id
assert s.start == 1
assert s.end == 8
assert s.duration == 7
assert s.channel == 0
assert s.text == "irrelevant irrelevant"
assert s.language == "cat#irrelevant#irrelevant"
assert s.speaker == "cat#irrelevant#irrelevant"
assert s.gender == "cat#irrelevant#irrelevant"
assert s.custom is not None
assert s.custom["custom_field"] == "cat#irrelevant#irrelevant"
def test_mono_cut_merge_supervisions_identity():
cut = dummy_cut(0, supervisions=[dummy_supervision(0)])
mcut = cut.merge_supervisions()
assert cut == mcut
def test_mono_cut_merge_supervisions_no_supervisions():
cut = dummy_cut(0, supervisions=[])
mcut = cut.merge_supervisions()
assert cut == mcut
def test_mono_cut_merge_supervisions_empty_fields():
cut = dummy_cut(
0,
duration=2,
supervisions=[dummy_supervision(0), dummy_supervision(1, start=1)],
)
cut.supervisions[0].speaker = None
cut.supervisions[1].speaker = None
mcut = cut.merge_supervisions()
assert mcut.supervisions[0].speaker is None
def test_mono_cut_merge_supervisions_custom_merge_fn():
cut = dummy_cut(
0,
duration=2,
supervisions=[dummy_supervision(0), dummy_supervision(1, start=1)],
)
cut.supervisions[0].custom["a"] = 20
cut.supervisions[1].custom["a"] = -13
mcut = cut.merge_supervisions(
custom_merge_fn=lambda k, vs: sum(vs) if k == "a" else None
)
assert isinstance(mcut.supervisions[0].custom, dict)
assert mcut.supervisions[0].custom["a"] == 7
assert mcut.supervisions[0].custom["custom_field"] is None
def test_padding_cut_merge_supervisions():
cut = PaddingCut("x", 1, 16000, 0)
mcut = cut.merge_supervisions()
assert cut == mcut
def test_mixed_cut_merge_supervisions():
cut0 = dummy_cut(0, supervisions=[dummy_supervision(0)])
cut1 = dummy_cut(1, supervisions=[dummy_supervision(1)])
mixed = cut0.mix(cut1, offset_other_by=0.5)
assert len(mixed.supervisions) == 2
mcut = mixed.merge_supervisions()
# original not modified
assert len(mixed.supervisions) == 2
assert len(mcut.supervisions) == 1
s = mcut.supervisions[0]
assert s.id == "cat#dummy-segment-0000#dummy-segment-0001"
assert s.recording_id == "cat#dummy-recording-0000#dummy-recording-0001"
assert s.start == 0
assert s.end == 1.5
assert s.duration == 1.5
assert s.channel == -1
assert s.text == "irrelevant irrelevant"
assert s.language == "cat#irrelevant#irrelevant"
assert s.speaker == "cat#irrelevant#irrelevant"
assert s.gender == "cat#irrelevant#irrelevant"
assert s.custom is not None
assert s.custom["custom_field"] == "cat#irrelevant#irrelevant"
def test_mixed_cut_merge_supervisions_identity():
cut = dummy_cut(0, supervisions=[dummy_supervision(0)])
cut = cut.append(cut.drop_supervisions())
mcut = cut.merge_supervisions()
assert cut == mcut
def test_cut_set_merge_supervisions():
cuts = DummyManifest(CutSet, begin_id=0, end_id=2)
mcuts = cuts.merge_supervisions()
assert cuts == mcuts
| true | true |
1c2bc6587696105dda1accbc0708f3301279c001 | 27,780 | py | Python | javsdt/JavbusYouma.py | wineast/javsdt | 5cdcee19e7c1bfade46f8e5a933693c68bcceb63 | [
"MIT"
] | 7 | 2021-06-09T07:16:17.000Z | 2022-03-01T05:32:20.000Z | javsdt/JavbusYouma.py | wineast/javsdt | 5cdcee19e7c1bfade46f8e5a933693c68bcceb63 | [
"MIT"
] | null | null | null | javsdt/JavbusYouma.py | wineast/javsdt | 5cdcee19e7c1bfade46f8e5a933693c68bcceb63 | [
"MIT"
] | 1 | 2021-06-05T10:10:22.000Z | 2021-06-05T10:10:22.000Z | # -*- coding:utf-8 -*-
import os, re
from shutil import copyfile
from traceback import format_exc
########################################################################################################################
from Class.Settings import Settings
from Class.JavFile import JavFile
from Functions.Status import judge_exist_nfo, judge_exist_extra_folders, count_num_videos
from Functions.User import choose_directory
from Functions.Record import record_start, record_fail, record_warn
from Functions.Process import perfect_dict_data
from Functions.Standard import rename_mp4, rename_folder, classify_files, classify_folder
from Functions.XML import replace_xml, replace_xml_win
from Functions.Process import judge_exist_subtitle
from Functions.Picture import check_picture, add_watermark_subtitle
from Functions.Requests.Download import download_pic
from Functions.Genre import better_dict_genre
# ################################################## 不同 ##########################################################
from Functions.Process import judge_exist_divulge
from Functions.Status import check_actors
from Functions.Car import find_car_bus, list_suren_car
from Functions.Standard import collect_sculpture
from Functions.Baidu import translate
from Functions.Picture import add_watermark_divulge, crop_poster_youma
from Functions.Requests.JavbusReq import get_bus_html
from Functions.Requests.ArzonReq import steal_arzon_cookies, find_plot_arzon
# main开始
print('1、避开21:00-1:00,访问javbus和arzon很慢。\n'
'2、若一直打不开javbus,请在ini中更新防屏蔽网址\n')
# 读取配置文件,这个ini文件用来给用户设置
print('正在读取ini中的设置...', end='')
try:
settings = Settings('有码')
except:
settings = None
print(format_exc())
print('\n无法读取ini文件,请修改它为正确格式,或者打开“【ini】重新创建ini.exe”创建全新的ini!')
os.system('pause')
print('\n读取ini文件成功!\n')
# 路径分隔符:当前系统的路径分隔符 windows是“\”,linux和mac是“/”
sep = os.sep
# 检查头像:如果需要为kodi整理头像,先检查演员头像ini、头像文件夹是否存在。
check_actors(settings.bool_sculpture)
# 局部代理:哪些站点需要代理。
proxy_library, proxy_bus, proxy_321, proxy_db, proxy_arzon, proxy_dmm = settings.get_proxy()
# arzon通行证:如果需要在nfo中写入日语简介,需要先获得合法的arzon网站的cookie,用于通过成人验证。
cookie_arzon = steal_arzon_cookies(proxy_arzon) if settings.bool_plot and settings.bool_nfo else {}
# javbus网址 https://www.buscdn.work/
url_bus = settings.get_url_bus()
# 选择简繁中文以及百度翻译账户:需要简体中文还是繁体中文,影响影片特征和简介。
to_language, tran_id, tran_sk = settings.get_translate_account()
# 信息字典:存放影片信息,用于给用户自定义各种命名。
dict_data = {'车牌': 'ABC-123',
'车牌前缀': 'ABC',
'标题': '有码标题',
'完整标题': '完整有码标题',
'导演': '有码导演',
'片商': '有码片商',
'评分': '0',
'片长': '0',
'系列': '有码系列',
'发行年月日': '1970-01-01', '发行年份': '1970', '月': '01', '日': '01',
'首个演员': '有码演员', '全部演员': '有码演员',
'空格': ' ',
'\\': sep, '/': sep, # 文件路径分隔符
'是否中字': '',
'是否流出': '',
'影片类型': settings.av_type(),
'视频': 'ABC-123', # 当前及未来的视频文件名,不带ext
'原文件名': 'ABC-123', '原文件夹名': 'ABC-123', }
# nfo中title的写法。
list_name_nfo_title = settings.formula_name_nfo_title()
# 额外将哪些元素放入特征中
list_extra_genres = settings.list_extra_genre()
# 重命名视频的格式
list_name_video = settings.formula_rename_video()
# 重命名文件夹的格式
list_name_folder = settings.formula_rename_folder()
# fanart的格式
list_name_fanart = settings.formula_name_fanart()
# poster的格式
list_name_poster = settings.formula_name_poster()
# 视频文件名包含哪些多余的字母数字,需要无视
list_surplus_words_in_filename = settings.list_surplus_word_in_filename('有码')
# 文件名包含哪些特殊含义的文字,判断是否中字
list_subtitle_words_in_filename = settings.list_subtitle_word_in_filename()
# 文件名包含哪些特殊含义的文字,判断是否是无码流出片
list_divulge_words_in_filename = settings.list_divulge_word_in_filename()
# 素人番号:得到事先设置的素人番号,让程序能跳过它们
list_suren_cars = list_suren_car()
# 需要扫描的文件的类型
tuple_video_types = settings.tuple_video_type()
# 完善dict_data,如果用户自定义了一些文字,不在元素中,需要将它们添加进dict_data;list_classify_basis,归类标准,归类目标文件夹的组成公式。
dict_data, list_classify_basis = perfect_dict_data(list_extra_genres, list_name_video, list_name_folder, list_name_nfo_title, list_name_fanart, list_name_poster, settings.custom_classify_basis(), dict_data)
# 优化特征的字典
dict_genre = better_dict_genre('Javbus有码', to_language)
# 用户输入“回车”就继续选择文件夹整理
input_start_key = ''
while input_start_key == '':
# 用户:选择需要整理的文件夹
print('请选择要整理的文件夹:', end='')
root_choose = choose_directory()
print(root_choose)
# 日志:在txt中记录一下用户的这次操作,在某个时间选择了某个文件夹
record_start(root_choose)
# 归类:用户自定义的归类根目录,如果不需要归类则为空
root_classify = settings.check_classify_root(root_choose, sep)
# 计数:失败次数及进度
num_fail = 0 # 已经或可能导致致命错误,比如整理未完成,同车牌有不同视频
num_warn = 0 # 对整理结果不致命的问题,比如找不到简介
num_all_videos = count_num_videos(root_choose, tuple_video_types) # 所选文件夹总共有多少个视频文件
num_current = 0 # 当前视频的编号
print('...文件扫描开始...如果时间过长...请避开夜晚高峰期...\n')
# root【当前根目录】 dirs【子文件夹】 files【文件】,root是str,后两个是list
for root, dirs, files in os.walk(root_choose):
# 什么文件都没有
if not files:
continue
# 当前root是已归类的目录,无需处理
if '归类完成' in root.replace(root_choose, ''):
continue
# 跳过已存在nfo的文件夹,判断这一层文件夹中有没有nfo
if settings.bool_skip and judge_exist_nfo(files):
continue
# 对这一层文件夹进行评估,有多少视频,有多少同车牌视频,是不是独立文件夹
list_jav_struct = [] # 存放:需要整理的jav的结构体
dict_car_pref = {} # 存放:每一车牌的集数, 例如{'abp-123': 1, avop-789': 2}是指 abp-123只有一集,avop-789有cd1、cd2
num_videos_include = 0 # 计数:当前文件夹中视频的数量,可能有视频不是jav
dict_subtitle_files = {} # 存放:jav的字幕文件和车牌对应关系 {'c:\a\abc_123.srt': 'abc-123'}
# 判断文件是不是字幕文件,放入dict_subtitle_files中
for file_raw in files:
file_temp = file_raw.upper()
if file_temp.endswith(('.SRT', '.VTT', '.ASS', '.SSA', '.SUB', '.SMI',)):
# 当前模式不处理FC2
if 'FC2' in file_temp:
continue
# 去除用户设置的、干扰车牌的文字
for word in list_surplus_words_in_filename:
file_temp = file_temp.replace(word, '')
# 得到字幕文件名中的车牌
subtitle_car = find_car_bus(file_temp, list_suren_cars)
# 将该字幕文件和其中的车牌对应到dict_subtitle_files中
if subtitle_car:
dict_subtitle_files[file_raw] = subtitle_car
# print(dict_subtitle_files)
# 判断文件是不是视频,放入list_jav_struct中
for file_raw in files:
file_temp = file_raw.upper()
if file_temp.endswith(tuple_video_types) and not file_temp.startswith('.'):
num_videos_include += 1
num_current += 1
if 'FC2' in file_temp:
continue
for word in list_surplus_words_in_filename:
file_temp = file_temp.replace(word, '')
# 得到视频中的车牌
car = find_car_bus(file_temp, list_suren_cars)
if car:
try:
dict_car_pref[car] += 1 # 已经有这个车牌了,加一集cd
except KeyError:
dict_car_pref[car] = 1 # 这个新车牌有了第一集
# 这个车牌在dict_subtitle_files中,有它的字幕。
if car in dict_subtitle_files.values():
subtitle_file = list(dict_subtitle_files.keys())[list(dict_subtitle_files.values()).index(car)]
del dict_subtitle_files[subtitle_file]
else:
subtitle_file = ''
# 将该jav的各种属性打包好,包括原文件名带扩展名、所在文件夹路径、第几集、所属字幕文件名
jav_struct = JavFile(file_raw, root, car, dict_car_pref[car], subtitle_file, num_current)
list_jav_struct.append(jav_struct)
else:
print('>>无法处理:', root.replace(root_choose, '') + sep + file_raw)
# 判定影片所在文件夹是否是独立文件夹,独立文件夹是指该文件夹仅用来存放该影片,而不是大杂烩文件夹
# 这一层文件夹下有jav
if dict_car_pref:
# 当前文件夹下,车牌不止一个;还有其他非jav视频;有其他文件夹,除了演员头像文件夹“.actors”和额外剧照文件夹“extrafanart”;
if len(dict_car_pref) > 1 or num_videos_include > len(list_jav_struct) or judge_exist_extra_folders(dirs):
bool_separate_folder = False # 不是独立的文件夹
else:
bool_separate_folder = True # 这一层文件夹是这部jav的独立文件夹
else:
continue
# 开始处理每一部jav
for jav in list_jav_struct:
# 告诉用户进度
print('>> [' + str(jav.number) + '/' + str(num_all_videos) + ']:', jav.name)
print(' >发现车牌:', jav.car)
# 判断是否有中字的特征,条件有三满足其一即可:1有外挂字幕 2文件名中含有“-C”之类的字眼 3旧的nfo中已经记录了它的中字特征
if jav.subtitle:
bool_subtitle = True # 判定成功
dict_data['是否中字'] = settings.custom_subtitle_expression # '是否中字'这一命名元素被激活
else:
bool_subtitle = judge_exist_subtitle(root, jav.name_no_ext, list_subtitle_words_in_filename)
dict_data['是否中字'] = settings.custom_subtitle_expression if bool_subtitle else ''
# 判断是否是无码流出的作品,同理
bool_divulge = judge_exist_divulge(root, jav.name_no_ext, list_divulge_words_in_filename)
dict_data['是否流出'] = settings.custom_divulge_expression if bool_divulge else ''
# 影片的相对于所选文件夹的路径,用于报错
path_relative = sep + jav.path.replace(root_choose, '')
# 获取nfo信息的javbus网页
try:
# 用户指定了网址,则直接得到jav所在网址
if '公交车' in jav.name:
url_appointg = re.search(r'公交车(.+?)\.', jav.name)
if str(url_appointg) != 'None':
url_on_web = url_bus + url_appointg.group(1)
else:
num_fail += 1
record_fail(' >第' + str(num_fail) + '个失败!你指定的javbus网址有错误:' + path_relative + '\n')
continue # 【退出对该jav的整理】
# 用户没有指定网址,则去搜索
else:
url_search_web = url_bus + 'search/' + jav.car + '&type=1&parent=ce'
print(' >搜索车牌:', url_search_web)
# 得到javbus搜索网页html
html_web = get_bus_html(url_search_web, proxy_bus)
# 尝试找movie-box
list_search_results = re.findall(r'movie-box" href="(.+?)">', html_web) # 匹配处理“标题”
if list_search_results: # 搜索页面有结果
# print(list_search_results)
# print(' >正在核查搜索结果...')
jav_pref = jav.car.split('-')[0] # 匹配车牌的前缀字母
jav_suf = jav.car.split('-')[-1].lstrip('0') # 当前车牌的后缀数字 去除多余的0
list_fit_results = [] # 存放,车牌符合的结果
for i in list_search_results:
url_end = i.split('/')[-1].upper()
url_suf = re.search(r'[-_](\d+)', url_end).group(1).lstrip('0') # 匹配box上影片url,车牌的后缀数字,去除多余的0
if jav_suf == url_suf: # 数字相同
url_pref = re.search(r'([A-Z0-9]+)[-_]', url_end).group(1).upper() # 匹配处理url所带车牌前面的字母“n”
if jav_pref == url_pref: # 数字相同的基础下,字母也相同,即可能车牌相同
list_fit_results.append(i)
# 有码搜索的结果一个都匹配不上
if not list_fit_results:
num_fail += 1
record_fail(' >第' + str(
num_fail) + '个失败!javbus有码找不到该车牌的信息:' + jav.car + ',' + path_relative + '\n')
continue # 【跳出对该jav的整理】
# 默认用第一个搜索结果
url_on_web = list_fit_results[0]
if len(list_fit_results) > 1:
num_fail += 1
record_fail(' >第' + str(
num_fail) + '个警告!javbus搜索到同车牌的不同视频:' + jav.car + ',' + path_relative + '\n')
# 找不到box
else:
num_fail += 1
record_fail(' >第' + str(
num_fail) + '个失败!javbus有码找不到该车牌的信息:' + jav.car + ',' + path_relative + '\n')
continue # 【跳出对该jav的整理】
# 经过上面的三种情况,可能找到了jav在bus上的网页链接url_on_web
print(' >获取信息:', url_on_web)
# 得到最终的jav所在网页
html_web = get_bus_html(url_on_web, proxy_bus)
# 开始匹配信息
# 有大部分信息的html_web
html_web = re.search(r'(h3>[\s\S]*?)磁力連結投稿', html_web, re.DOTALL).group(1)
# 标题
title = re.search(r'h3>(.+?)</h3', html_web, re.DOTALL).group(1) # javbus上的标题可能占两行
# 去除xml文档和windows路径不允许的特殊字符 &<> \/:*?"<>|
title = replace_xml_win(title)
print(' >影片标题:', title)
# 正则匹配 影片信息 开始!
# title的开头是车牌号,想要后面的纯标题
car_titleg = re.search(r'(.+?) (.+)', title)
# 车牌号
dict_data['车牌'] = car = car_titleg.group(1)
dict_data['车牌前缀'] = car.split('-')[0]
# 给用户重命名用的标题是“短标题”,nfo中是“完整标题”,但用户在ini中只用写“标题”
title_only = car_titleg.group(2)
# DVD封面cover
coverg = re.search(r'bigImage" href="(.+?)">', html_web) # 封面图片的正则对象
if str(coverg) != 'None':
url_cover = url_bus + coverg.group(1)
else:
url_cover = ''
# 发行日期
premieredg = re.search(r'發行日期:</span> (.+?)</p>', html_web)
if str(premieredg) != 'None':
dict_data['发行年月日'] = time_premiered = premieredg.group(1)
dict_data['发行年份'] = time_premiered[0:4]
dict_data['月'] = time_premiered[5:7]
dict_data['日'] = time_premiered[8:10]
else:
dict_data['发行年月日'] = time_premiered = '1970-01-01'
dict_data['发行年份'] = '1970'
dict_data['月'] = '01'
dict_data['日'] = '01'
# 片长 <td><span class="text">150</span> 分钟</td>
runtimeg = re.search(r'長度:</span> (.+?)分鐘</p>', html_web)
if str(runtimeg) != 'None':
dict_data['片长'] = runtimeg.group(1)
else:
dict_data['片长'] = '0'
# 导演
directorg = re.search(r'導演:</span> <a href=".+?">(.+?)<', html_web)
if str(directorg) != 'None':
dict_data['导演'] = replace_xml_win(directorg.group(1))
else:
dict_data['导演'] = '有码导演'
# 片商 制作商
studiog = re.search(r'製作商:</span> <a href=".+?">(.+?)</a>', html_web)
if str(studiog) != 'None':
dict_data['片商'] = studio = replace_xml_win(studiog.group(1))
else:
dict_data['片商'] = '有码片商'
studio = ''
# 系列:</span> <a href="https://www.cdnbus.work/series/kpl">悪質シロウトナンパ</a>
seriesg = re.search(r'系列:</span> <a href=".+?">(.+?)</a>', html_web) # 封面图片的正则对象
if str(seriesg) != 'None':
dict_data['系列'] = series = seriesg.group(1).replace(sep, '#')
else:
dict_data['系列'] = '有码系列'
series = ''
# 演员们 和 # 第一个演员
actors = re.findall(r'star/.+?"><img src=.+?" title="(.+?)">', html_web)
if actors:
if len(actors) > 7:
dict_data['全部演员'] = ' '.join(actors[:7])
else:
dict_data['全部演员'] = ' '.join(actors)
dict_data['首个演员'] = actors[0]
# 有些用户需要删去 标题 末尾可能存在的 演员姓名
if settings.bool_strip_actors and title_only.endswith(dict_data['全部演员']):
title_only = title_only[:-len(dict_data['全部演员'])].rstrip()
else:
actors = ['有码演员']
dict_data['首个演员'] = dict_data['全部演员'] = '有码演员'
# 处理影片的标题过长
dict_data['完整标题'] = title_only
if len(title_only) > settings.int_title_len:
dict_data['标题'] = title_only[:settings.int_title_len]
else:
dict_data['标题'] = title_only
# 特点
genres = re.findall(r'genre"><a href=".+?">(.+?)</a></span>', html_web)
if bool_subtitle: # 有“中字“,加上特征”中文字幕”
genres.append('中文字幕')
if bool_divulge: # 是流出无码片,加上特征'无码流出'
genres.append('无码流出')
try:
genres = [dict_genre[i] for i in genres if dict_genre[i] != '删除']
except KeyError as error:
num_fail += 1
record_fail(' >第' + str(num_fail) + '个失败!发现新的特征需要添加至【特征对照表】:' + str(error) + '\n')
continue
# print(genres)
# arzon的简介 #########################################################
# 去arzon找简介
if settings.bool_nfo and settings.bool_plot and jav.episode == 1:
plot, status_arzon, acook = find_plot_arzon(car, cookie_arzon, proxy_arzon)
if status_arzon == 0:
pass
elif status_arzon == 1:
num_warn += 1
record_warn(' >第' + str(num_warn) + '个失败!找不到简介,尽管arzon上有搜索结果:' + path_relative + '\n')
else:
num_warn += 1
record_warn(' >第' + str(num_warn) + '个失败!找不到简介,影片被arzon下架:' + path_relative + '\n')
# 需要翻译简介
if settings.bool_tran:
plot = translate(tran_id, tran_sk, plot, to_language)
if plot.startswith('【百度'):
num_fail += 1
record_fail(' >第' + str(num_fail) + '个失败!翻译简介失败:' + path_relative + '\n')
# 去除xml文档不允许的特殊字符 &<> \/:*?"<>|
plot = replace_xml(plot)
# print(plot)
else:
plot = ''
#######################################################################
dict_data['视频'] = dict_data['原文件名'] = jav.name # dict_data['视频'],先定义为原文件名,即将发生变化。
# 是CD1还是CDn?
num_all_episodes = dict_car_pref[jav.car] # 该车牌总共多少集
if num_all_episodes > 1:
str_cd = '-cd' + str(jav.episode)
else:
str_cd = ''
# 1重命名视频【相同】
try:
dict_data, jav, num_temp = rename_mp4(jav, num_fail, settings, dict_data, list_name_video,
path_relative, str_cd)
num_fail = num_temp
except FileExistsError:
num_fail += 1
continue
# 2 归类影片【相同】只针对视频文件和字幕文件。注意:第2操作和下面(第3操作+第7操作)互斥,只能执行第2操作或(第3操作+第7操作),归类影片是针对“文件”还是“文件夹”。
try:
jav, num_temp = classify_files(jav, num_fail, settings, dict_data, list_classify_basis,
root_classify)
num_fail = num_temp
except FileExistsError:
num_fail += 1
continue
# 3重命名文件夹【相同】如果是针对“文件”归类,这一步会被跳过。 因为用户只需要归类视频文件,不需要管文件夹。
try:
jav, num_temp = rename_folder(jav, num_fail, settings, dict_data, list_name_folder,
bool_separate_folder, num_all_episodes)
num_fail = num_temp
except FileExistsError:
num_fail += 1
continue
# 更新一下path_relative
path_relative = sep + jav.path.replace(root_choose, '') # 影片的相对于所选文件夹的路径,用于报错
# 4写入nfo【独特】
if settings.bool_nfo:
if settings.bool_cd_only:
path_nfo = jav.root + sep + jav.name_no_ext.replace(str_cd, '') + '.nfo'
else:
path_nfo = jav.root + sep + jav.name_no_ext + '.nfo'
title_in_nfo = ''
for i in list_name_nfo_title:
title_in_nfo += dict_data[i] # nfo中tilte的写法
# 开始写入nfo,这nfo格式是参考的kodi的nfo
f = open(path_nfo, 'w', encoding="utf-8")
f.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>\n"
"<movie>\n"
" <plot>" + plot + "</plot>\n"
" <title>" + title_in_nfo + "</title>\n"
" <originaltitle>" + title + "</originaltitle>\n"
" <director>" + dict_data['导演'] + "</director>\n"
" <year>" + dict_data['发行年份'] + "</year>\n"
" <mpaa>NC-17</mpaa>\n"
" <customrating>NC-17</customrating>\n"
" <countrycode>JP</countrycode>\n"
" <premiered>" + time_premiered + "</premiered>\n"
" <release>" + time_premiered + "</release>\n"
" <runtime>" + dict_data['片长'] + "</runtime>\n"
" <country>日本</country>\n"
" <studio>" + studio + "</studio>\n"
" <id>" + car + "</id>\n"
" <num>" + car + "</num>\n"
" <set>" + series + "</set>\n") # emby不管set系列,kodi可以
# 需要将特征写入genre
if settings.bool_genre:
for i in genres:
f.write(" <genre>" + i + "</genre>\n")
if settings.bool_write_series and series:
f.write(" <genre>系列:" + series + "</genre>\n")
if settings.bool_write_studio and studio:
f.write(" <genre>片商:" + studio + "</genre>\n")
if list_extra_genres:
for i in list_extra_genres:
f.write(" <genre>" + dict_data[i] + "</genre>\n")
# 需要将特征写入tag
if settings.bool_tag:
for i in genres:
f.write(" <tag>" + i + "</tag>\n")
if settings.bool_write_series and series:
f.write(" <tag>系列:" + series + "</tag>\n")
if settings.bool_write_studio and studio:
f.write(" <tag>片商:" + studio + "</tag>\n")
if list_extra_genres:
for i in list_extra_genres:
f.write(" <tag>" + dict_data[i] + "</tag>\n")
# 写入演员
for i in actors:
f.write(" <actor>\n <name>" + i + "</name>\n <type>Actor</type>\n </actor>\n")
f.write("</movie>\n")
f.close()
print(' >nfo收集完成')
# 5需要两张封面图片【独特】
if settings.bool_jpg:
# fanart和poster路径
path_fanart = jav.root + sep
path_poster = jav.root + sep
for i in list_name_fanart:
path_fanart += dict_data[i]
for i in list_name_poster:
path_poster += dict_data[i]
# print(path_fanart)
# kodi只需要一份图片,图片路径唯一
if settings.bool_cd_only:
path_fanart = path_fanart.replace(str_cd, '')
path_poster = path_poster.replace(str_cd, '')
# emby需要多份,现在不是第一集,直接复制第一集的图片
elif jav.episode != 1:
try:
copyfile(path_fanart.replace(str_cd, '-cd1'), path_fanart)
print(' >fanart.jpg复制成功')
copyfile(path_poster.replace(str_cd, '-cd1'), path_poster)
print(' >poster.jpg复制成功')
except FileNotFoundError:
pass
# kodi或者emby需要的第一份图片
if check_picture(path_fanart):
# print(' >已有fanart.jpg')
pass
else:
# 下载封面
print(' >从javbus下载封面:', url_cover)
try:
download_pic(url_cover, path_fanart, proxy_bus)
print(' >fanart.jpg下载成功')
except:
num_fail += 1
record_fail(' >第' + str(
num_fail) + '个失败!下载fanart.jpg失败:' + url_cover + ',' + path_relative + '\n')
continue # 退出对该jav的整理
# 裁剪生成 poster
if check_picture(path_poster):
# print(' >已有poster.jpg')
pass
else:
crop_poster_youma(path_fanart, path_poster)
# 需要加上条纹
if settings.bool_watermark_subtitle and bool_subtitle:
add_watermark_subtitle(path_poster)
if settings.bool_watermark_divulge and bool_divulge:
add_watermark_divulge(path_poster)
# 6收集演员头像【相同】
if settings.bool_sculpture and jav.episode == 1:
if actors[0] == '有码演员':
print(' >未知演员,无法收集头像')
else:
collect_sculpture(actors, jav.root)
# 7归类影片,针对文件夹【相同】
try:
num_temp = classify_folder(jav, num_fail, settings, dict_data, list_classify_basis, root_classify,
root, bool_separate_folder, num_all_episodes)
num_fail = num_temp
except FileExistsError:
num_fail += 1
continue
except:
num_fail += 1
record_fail(' >第' + str(num_fail) + '个失败!发生错误,如一直在该影片报错请截图并联系作者:' + path_relative + '\n' + format_exc() + '\n')
continue # 【退出对该jav的整理】
# 完结撒花
print('\n当前文件夹完成,', end='')
if num_fail > 0:
print('失败', num_fail, '个! ', root_choose, '\n')
line = -1
with open('【可删除】失败记录.txt', 'r', encoding="utf-8") as f:
content = list(f)
while 1:
if content[line].startswith('已'):
break
line -= 1
for i in range(line+1, 0):
print(content[i], end='')
print('\n“【可删除】失败记录.txt”已记录错误\n')
else:
print(' “0”失败! ', root_choose, '\n')
if num_warn > 0:
print('“警告信息.txt”还记录了', num_warn, '个警告信息!\n')
# os.system('pause')
input_start_key = input('回车继续选择文件夹整理:')
| 47.568493 | 206 | 0.487869 |
import os, re
from shutil import copyfile
from traceback import format_exc
pan> <a href=".+?">(.+?)<', html_web)
if str(directorg) != 'None':
dict_data['导演'] = replace_xml_win(directorg.group(1))
else:
dict_data['导演'] = '有码导演'
# 片商 制作商
studiog = re.search(r'製作商:</span> <a href=".+?">(.+?)</a>', html_web)
if str(studiog) != 'None':
dict_data['片商'] = studio = replace_xml_win(studiog.group(1))
else:
dict_data['片商'] = '有码片商'
studio = ''
# 系列:</span> <a href="https://www.cdnbus.work/series/kpl">悪質シロウトナンパ</a>
seriesg = re.search(r'系列:</span> <a href=".+?">(.+?)</a>', html_web) # 封面图片的正则对象
if str(seriesg) != 'None':
dict_data['系列'] = series = seriesg.group(1).replace(sep, '#')
else:
dict_data['系列'] = '有码系列'
series = ''
# 演员们 和 # 第一个演员
actors = re.findall(r'star/.+?"><img src=.+?" title="(.+?)">', html_web)
if actors:
if len(actors) > 7:
dict_data['全部演员'] = ' '.join(actors[:7])
else:
dict_data['全部演员'] = ' '.join(actors)
dict_data['首个演员'] = actors[0]
# 有些用户需要删去 标题 末尾可能存在的 演员姓名
if settings.bool_strip_actors and title_only.endswith(dict_data['全部演员']):
title_only = title_only[:-len(dict_data['全部演员'])].rstrip()
else:
actors = ['有码演员']
dict_data['首个演员'] = dict_data['全部演员'] = '有码演员'
# 处理影片的标题过长
dict_data['完整标题'] = title_only
if len(title_only) > settings.int_title_len:
dict_data['标题'] = title_only[:settings.int_title_len]
else:
dict_data['标题'] = title_only
# 特点
genres = re.findall(r'genre"><a href=".+?">(.+?)</a></span>', html_web)
if bool_subtitle: # 有“中字“,加上特征”中文字幕”
genres.append('中文字幕')
if bool_divulge: # 是流出无码片,加上特征'无码流出'
genres.append('无码流出')
try:
genres = [dict_genre[i] for i in genres if dict_genre[i] != '删除']
except KeyError as error:
num_fail += 1
record_fail(' >第' + str(num_fail) + '个失败!发现新的特征需要添加至【特征对照表】:' + str(error) + '\n')
continue
# print(genres)
# arzon的简介 #########################################################
# 去arzon找简介
if settings.bool_nfo and settings.bool_plot and jav.episode == 1:
plot, status_arzon, acook = find_plot_arzon(car, cookie_arzon, proxy_arzon)
if status_arzon == 0:
pass
elif status_arzon == 1:
num_warn += 1
record_warn(' >第' + str(num_warn) + '个失败!找不到简介,尽管arzon上有搜索结果:' + path_relative + '\n')
else:
num_warn += 1
record_warn(' >第' + str(num_warn) + '个失败!找不到简介,影片被arzon下架:' + path_relative + '\n')
# 需要翻译简介
if settings.bool_tran:
plot = translate(tran_id, tran_sk, plot, to_language)
if plot.startswith('【百度'):
num_fail += 1
record_fail(' >第' + str(num_fail) + '个失败!翻译简介失败:' + path_relative + '\n')
# 去除xml文档不允许的特殊字符 &<> \/:*?"<>|
plot = replace_xml(plot)
# print(plot)
else:
plot = ''
#######################################################################
dict_data['视频'] = dict_data['原文件名'] = jav.name # dict_data['视频'],先定义为原文件名,即将发生变化。
# 是CD1还是CDn?
num_all_episodes = dict_car_pref[jav.car] # 该车牌总共多少集
if num_all_episodes > 1:
str_cd = '-cd' + str(jav.episode)
else:
str_cd = ''
# 1重命名视频【相同】
try:
dict_data, jav, num_temp = rename_mp4(jav, num_fail, settings, dict_data, list_name_video,
path_relative, str_cd)
num_fail = num_temp
except FileExistsError:
num_fail += 1
continue
# 2 归类影片【相同】只针对视频文件和字幕文件。注意:第2操作和下面(第3操作+第7操作)互斥,只能执行第2操作或(第3操作+第7操作),归类影片是针对“文件”还是“文件夹”。
try:
jav, num_temp = classify_files(jav, num_fail, settings, dict_data, list_classify_basis,
root_classify)
num_fail = num_temp
except FileExistsError:
num_fail += 1
continue
# 3重命名文件夹【相同】如果是针对“文件”归类,这一步会被跳过。 因为用户只需要归类视频文件,不需要管文件夹。
try:
jav, num_temp = rename_folder(jav, num_fail, settings, dict_data, list_name_folder,
bool_separate_folder, num_all_episodes)
num_fail = num_temp
except FileExistsError:
num_fail += 1
continue
# 更新一下path_relative
path_relative = sep + jav.path.replace(root_choose, '') # 影片的相对于所选文件夹的路径,用于报错
# 4写入nfo【独特】
if settings.bool_nfo:
if settings.bool_cd_only:
path_nfo = jav.root + sep + jav.name_no_ext.replace(str_cd, '') + '.nfo'
else:
path_nfo = jav.root + sep + jav.name_no_ext + '.nfo'
title_in_nfo = ''
for i in list_name_nfo_title:
title_in_nfo += dict_data[i] # nfo中tilte的写法
# 开始写入nfo,这nfo格式是参考的kodi的nfo
f = open(path_nfo, 'w', encoding="utf-8")
f.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>\n"
"<movie>\n"
" <plot>" + plot + "</plot>\n"
" <title>" + title_in_nfo + "</title>\n"
" <originaltitle>" + title + "</originaltitle>\n"
" <director>" + dict_data['导演'] + "</director>\n"
" <year>" + dict_data['发行年份'] + "</year>\n"
" <mpaa>NC-17</mpaa>\n"
" <customrating>NC-17</customrating>\n"
" <countrycode>JP</countrycode>\n"
" <premiered>" + time_premiered + "</premiered>\n"
" <release>" + time_premiered + "</release>\n"
" <runtime>" + dict_data['片长'] + "</runtime>\n"
" <country>日本</country>\n"
" <studio>" + studio + "</studio>\n"
" <id>" + car + "</id>\n"
" <num>" + car + "</num>\n"
" <set>" + series + "</set>\n") # emby不管set系列,kodi可以
# 需要将特征写入genre
if settings.bool_genre:
for i in genres:
f.write(" <genre>" + i + "</genre>\n")
if settings.bool_write_series and series:
f.write(" <genre>系列:" + series + "</genre>\n")
if settings.bool_write_studio and studio:
f.write(" <genre>片商:" + studio + "</genre>\n")
if list_extra_genres:
for i in list_extra_genres:
f.write(" <genre>" + dict_data[i] + "</genre>\n")
# 需要将特征写入tag
if settings.bool_tag:
for i in genres:
f.write(" <tag>" + i + "</tag>\n")
if settings.bool_write_series and series:
f.write(" <tag>系列:" + series + "</tag>\n")
if settings.bool_write_studio and studio:
f.write(" <tag>片商:" + studio + "</tag>\n")
if list_extra_genres:
for i in list_extra_genres:
f.write(" <tag>" + dict_data[i] + "</tag>\n")
# 写入演员
for i in actors:
f.write(" <actor>\n <name>" + i + "</name>\n <type>Actor</type>\n </actor>\n")
f.write("</movie>\n")
f.close()
print(' >nfo收集完成')
# 5需要两张封面图片【独特】
if settings.bool_jpg:
# fanart和poster路径
path_fanart = jav.root + sep
path_poster = jav.root + sep
for i in list_name_fanart:
path_fanart += dict_data[i]
for i in list_name_poster:
path_poster += dict_data[i]
# print(path_fanart)
# kodi只需要一份图片,图片路径唯一
if settings.bool_cd_only:
path_fanart = path_fanart.replace(str_cd, '')
path_poster = path_poster.replace(str_cd, '')
# emby需要多份,现在不是第一集,直接复制第一集的图片
elif jav.episode != 1:
try:
copyfile(path_fanart.replace(str_cd, '-cd1'), path_fanart)
print(' >fanart.jpg复制成功')
copyfile(path_poster.replace(str_cd, '-cd1'), path_poster)
print(' >poster.jpg复制成功')
except FileNotFoundError:
pass
# kodi或者emby需要的第一份图片
if check_picture(path_fanart):
# print(' >已有fanart.jpg')
pass
else:
# 下载封面
print(' >从javbus下载封面:', url_cover)
try:
download_pic(url_cover, path_fanart, proxy_bus)
print(' >fanart.jpg下载成功')
except:
num_fail += 1
record_fail(' >第' + str(
num_fail) + '个失败!下载fanart.jpg失败:' + url_cover + ',' + path_relative + '\n')
continue # 退出对该jav的整理
# 裁剪生成 poster
if check_picture(path_poster):
# print(' >已有poster.jpg')
pass
else:
crop_poster_youma(path_fanart, path_poster)
# 需要加上条纹
if settings.bool_watermark_subtitle and bool_subtitle:
add_watermark_subtitle(path_poster)
if settings.bool_watermark_divulge and bool_divulge:
add_watermark_divulge(path_poster)
# 6收集演员头像【相同】
if settings.bool_sculpture and jav.episode == 1:
if actors[0] == '有码演员':
print(' >未知演员,无法收集头像')
else:
collect_sculpture(actors, jav.root)
# 7归类影片,针对文件夹【相同】
try:
num_temp = classify_folder(jav, num_fail, settings, dict_data, list_classify_basis, root_classify,
root, bool_separate_folder, num_all_episodes)
num_fail = num_temp
except FileExistsError:
num_fail += 1
continue
except:
num_fail += 1
record_fail(' >第' + str(num_fail) + '个失败!发生错误,如一直在该影片报错请截图并联系作者:' + path_relative + '\n' + format_exc() + '\n')
continue # 【退出对该jav的整理】
# 完结撒花
print('\n当前文件夹完成,', end='')
if num_fail > 0:
print('失败', num_fail, '个! ', root_choose, '\n')
line = -1
with open('【可删除】失败记录.txt', 'r', encoding="utf-8") as f:
content = list(f)
while 1:
if content[line].startswith('已'):
break
line -= 1
for i in range(line+1, 0):
print(content[i], end='')
print('\n“【可删除】失败记录.txt”已记录错误\n')
else:
print(' “0”失败! ', root_choose, '\n')
if num_warn > 0:
print('“警告信息.txt”还记录了', num_warn, '个警告信息!\n')
# os.system('pause')
input_start_key = input('回车继续选择文件夹整理:')
| true | true |
1c2bc749f187c7eed4b2e52f2d167111094537a8 | 32,080 | py | Python | test/nn/test_multiple_module_flipsrotations.py | QUVA-Lab/escnn | 59ed6b96f61f8616f87b3f25aa2f8abdb6f1a882 | [
"BSD-3-Clause"
] | 4 | 2022-03-16T22:51:39.000Z | 2022-03-18T18:45:49.000Z | test/nn/test_multiple_module_flipsrotations.py | QUVA-Lab/escnn | 59ed6b96f61f8616f87b3f25aa2f8abdb6f1a882 | [
"BSD-3-Clause"
] | null | null | null | test/nn/test_multiple_module_flipsrotations.py | QUVA-Lab/escnn | 59ed6b96f61f8616f87b3f25aa2f8abdb6f1a882 | [
"BSD-3-Clause"
] | null | null | null | import unittest
from unittest import TestCase
from escnn.nn import *
from escnn.gspaces import *
import torch
import random
batchnormalizations = [
([('regular_bnorm', 'pointwise')], InnerBatchNorm),
([('g_bnorm', 'norm')], GNormBatchNorm),
([('norm_bnorm', 'norm')], NormBatchNorm),
([('indnorm_bnorm', 'induced_norm')], InducedNormBatchNorm),
]
allbatchnormalizations = []
for bn, _ in batchnormalizations:
allbatchnormalizations += bn
poolings = [
([('regular_mpool', 'pointwise')], PointwiseMaxPool),
([('norm_mpool', 'norm')], NormMaxPool),
]
allpoolings = []
for pl, _ in poolings:
allpoolings += pl
nonlinearities = [
([('p_relu', 'pointwise')], PointwiseNonLinearity),
([('p_sigmoid', 'pointwise')], PointwiseNonLinearity),
([('p_tanh', 'pointwise')], PointwiseNonLinearity),
([('c_relu', 'concatenated')], ConcatenatedNonLinearity),
([('c_sigmoid', 'concatenated')], ConcatenatedNonLinearity),
([('c_tanh', 'concatenated')], ConcatenatedNonLinearity),
([('n_relu', 'norm')], NormNonLinearity),
([('n_sigmoid', 'norm')], NormNonLinearity),
([('vectorfield', 'vectorfield')], VectorFieldNonLinearity),
([('gate', 'gate'), ('gated', 'gated')], GatedNonLinearity2),
]
allnonlinearities = []
for nl, _ in nonlinearities:
allnonlinearities += nl
convolutions = [
([('conv2d', 'any')], R2Conv),
]
allconvolutions = []
for cl, _ in convolutions:
allconvolutions += cl
allfunctions = allbatchnormalizations + allpoolings + allnonlinearities + allconvolutions
class TestNonLinearitiesFlipRotations(TestCase):
def test_dihedral_multiples_nonlinearities_sorted(self):
N = 8
g = flipRot2dOnR2(N)
reprs = []
labels = []
modules = []
gated = 0
for blocks, module in nonlinearities:
# print(blocks)
for name, type in blocks:
if name != 'gate':
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
if name == 'gated':
gated += 1
reprs = [g.trivial_repr] * gated + reprs
labels = ['gate'] * gated + labels
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in nonlinearities:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, function=blocks[0][0]), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.check_equivariance(full_space_action=False)
def test_dihedral_multiples_poolings_sorted(self):
N = 8
g = flipRot2dOnR2(N)
reprs = []
labels = []
modules = []
kernel = (3, 3)
for blocks, module in poolings:
# print(blocks)
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in poolings:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, kernel_size=kernel), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.check_equivariance(full_space_action=False)
def test_dihedral_multiples_batchnorm_sorted(self):
N = 8
g = flipRot2dOnR2(N)
M = N // 2
for m in range(M // 2 + 1):
g.induced_repr((0, M), g.fibergroup.subgroup((0, M))[0].irrep(1, m))
reprs = []
labels = []
modules = []
for blocks, module in batchnormalizations:
if module not in [NormBatchNorm, InducedNormBatchNorm]:
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
for r in g.representations.values():
if not r.contains_trivial():
for blocks, module in batchnormalizations:
if module == NormBatchNorm:
for name, type in blocks:
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
elif module == InducedNormBatchNorm:
for name, type in blocks:
if any(snl.startswith(type) for snl in r.supported_nonlinearities):
reprs.append(r)
labels.append(name)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in batchnormalizations:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.train()
b, c, h, w = 4, r.size, 30, 30
for i in range(20):
x = GeometricTensor(torch.randn(b, c, h, w), r)
nnl(x)
nnl.eval()
nnl.check_equivariance(full_space_action=False)
def test_dihedral_multiples_nonlinearities_shuffled(self):
N = 8
g = flipRot2dOnR2(N)
reprs = []
labels = []
modules = []
gated = 0
for blocks, module in nonlinearities:
# print(blocks)
for name, type in blocks:
if name != 'gate':
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
if name == 'gated':
gated += 1
reprs = [g.trivial_repr] * gated + reprs
labels = ['gate'] * gated + labels
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in nonlinearities:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, function=blocks[0][0]), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.check_equivariance(full_space_action=False)
def test_dihedral_multiples_poolings_shuffled(self):
N = 8
g = flipRot2dOnR2(N)
reprs = []
labels = []
modules = []
kernel = (3, 3)
for blocks, module in poolings:
# print(blocks)
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in poolings:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, kernel_size=kernel), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.check_equivariance(full_space_action=False)
def test_dihedral_multiples_batchnorm_shuffled(self):
N = 8
g = flipRot2dOnR2(N)
M = N // 2
for m in range(M // 2 + 1):
g.induced_repr((0, M), g.fibergroup.subgroup((0, M))[0].irrep(1, m))
reprs = []
labels = []
modules = []
for blocks, module in batchnormalizations:
if module not in [NormBatchNorm, InducedNormBatchNorm]:
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
for r in g.representations.values():
if not r.contains_trivial():
for blocks, module in batchnormalizations:
if module == NormBatchNorm:
for name, type in blocks:
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
elif module == InducedNormBatchNorm:
for name, type in blocks:
if any(snl.startswith(type) for snl in r.supported_nonlinearities):
reprs.append(r)
labels.append(name)
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in batchnormalizations:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.train()
b, c, h, w = 4, r.size, 30, 30
for i in range(20):
x = GeometricTensor(torch.randn(b, c, h, w), r)
nnl(x)
nnl.eval()
nnl.check_equivariance(full_space_action=False)
def test_dihedral_multiples_nonlinearities_sort(self):
N = 8
g = flipRot2dOnR2(N)
reprs = []
labels = []
modules = []
gated = 0
for blocks, module in nonlinearities:
# print(blocks)
for i in range(3):
for name, type in blocks:
if name != 'gate':
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
if name == 'gated':
gated += 1
reprs = [g.trivial_repr] * gated + reprs
labels = ['gate'] * gated + labels
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in nonlinearities:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, function=blocks[0][0]), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=True)
nnl.check_equivariance(full_space_action=False)
def test_dihedral_multiples_poolings_sort(self):
N = 8
g = flipRot2dOnR2(N)
reprs = []
labels = []
modules = []
kernel = (3, 3)
for blocks, module in poolings:
# print(blocks)
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in poolings:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, kernel_size=kernel), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=True)
nnl.check_equivariance(full_space_action=False)
def test_dihedral_multiples_batchnorm_sort(self):
N = 8
g = flipRot2dOnR2(N)
M = N // 2
for m in range(M // 2 + 1):
g.induced_repr((0, M), g.fibergroup.subgroup((0, M))[0].irrep(1, m))
reprs = []
labels = []
modules = []
for blocks, module in batchnormalizations:
if module not in [NormBatchNorm, InducedNormBatchNorm]:
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
for r in g.representations.values():
if not r.contains_trivial():
for blocks, module in batchnormalizations:
if module == NormBatchNorm:
for name, type in blocks:
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
elif module == InducedNormBatchNorm:
for name, type in blocks:
if any(snl.startswith(type) for snl in r.supported_nonlinearities):
reprs.append(r)
labels.append(name)
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in batchnormalizations:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=True)
nnl.train()
b, c, h, w = 4, r.size, 30, 30
for i in range(20):
x = GeometricTensor(torch.randn(b, c, h, w), r)
nnl(x)
nnl.eval()
nnl.check_equivariance(full_space_action=False)
def test_o2_multiples_nonlinearities_sorted(self):
N = 8
g = flipRot2dOnR2(-1, N)
reprs = []
labels = []
modules = []
gated = 0
for blocks, module in nonlinearities:
# print(blocks)
for name, type in blocks:
if name != 'gate':
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
if name == 'gated':
gated += 1
reprs = [g.trivial_repr] * gated + reprs
labels = ['gate'] * gated + labels
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in nonlinearities:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, function=blocks[0][0]), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.check_equivariance(full_space_action=False)
def test_o2_multiples_poolings_sorted(self):
N = 8
g = flipRot2dOnR2(-1, N)
reprs = []
labels = []
modules = []
kernel = (3, 3)
for blocks, module in poolings:
# print(blocks)
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in poolings:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, kernel_size=kernel), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.check_equivariance(full_space_action=False)
def test_o2_multiples_batchnorm_sorted(self):
N = 8
g = flipRot2dOnR2(-1, N)
for m in range(5):
g.induced_repr((None, -1), g.fibergroup.subgroup((None, -1))[0].irrep(m))
reprs = []
labels = []
modules = []
for blocks, module in batchnormalizations:
if module not in [NormBatchNorm, InducedNormBatchNorm]:
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
for r in g.representations.values():
if not r.contains_trivial():
for blocks, module in batchnormalizations:
if module == NormBatchNorm:
for name, type in blocks:
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
elif module == InducedNormBatchNorm:
for name, type in blocks:
if any(snl.startswith(type) for snl in r.supported_nonlinearities):
reprs.append(r)
labels.append(name)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in batchnormalizations:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.train()
b, c, h, w = 4, r.size, 30, 30
for i in range(20):
x = GeometricTensor(torch.randn(b, c, h, w), r)
nnl(x)
nnl.eval()
nnl.check_equivariance(full_space_action=False)
def test_o2_multiples_nonlinearities_shuffled(self):
N = 8
g = flipRot2dOnR2(-1, N)
reprs = []
labels = []
modules = []
gated = 0
for blocks, module in nonlinearities:
# print(blocks)
for name, type in blocks:
if name != 'gate':
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
if name == 'gated':
gated += 1
reprs = [g.trivial_repr] * gated + reprs
labels = ['gate'] * gated + labels
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in nonlinearities:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, function=blocks[0][0]), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.check_equivariance(full_space_action=False)
def test_o2_multiples_poolings_shuffled(self):
N = 8
g = flipRot2dOnR2(-1, N)
reprs = []
labels = []
modules = []
kernel = (3, 3)
for blocks, module in poolings:
# print(blocks)
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in poolings:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, kernel_size=kernel), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.check_equivariance(full_space_action=False)
def test_o2_multiples_batchnorm_shuffled(self):
N = 8
g = flipRot2dOnR2(-1, N)
for m in range(5):
g.induced_repr((None, -1), g.fibergroup.subgroup((None, -1))[0].irrep(m))
reprs = []
labels = []
modules = []
for blocks, module in batchnormalizations:
if module not in [NormBatchNorm, InducedNormBatchNorm]:
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
for r in g.representations.values():
if not r.contains_trivial():
for blocks, module in batchnormalizations:
if module == NormBatchNorm:
for name, type in blocks:
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
elif module == InducedNormBatchNorm:
for name, type in blocks:
if any(snl.startswith(type) for snl in r.supported_nonlinearities):
reprs.append(r)
labels.append(name)
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in batchnormalizations:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.train()
b, c, h, w = 4, r.size, 30, 30
for i in range(20):
x = GeometricTensor(torch.randn(b, c, h, w), r)
nnl(x)
nnl.eval()
nnl.check_equivariance(full_space_action=False)
def test_o2_multiples_nonlinearities_sort(self):
N = 8
g = flipRot2dOnR2(-1, N)
reprs = []
labels = []
modules = []
gated = 0
for blocks, module in nonlinearities:
# print(blocks)
for i in range(3):
for name, type in blocks:
if name != 'gate':
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
if name == 'gated':
gated += 1
reprs = [g.trivial_repr] * gated + reprs
labels = ['gate'] * gated + labels
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in nonlinearities:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, function=blocks[0][0]), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=True)
nnl.check_equivariance(full_space_action=False)
def test_o2_multiples_poolings_sort(self):
N = 8
g = flipRot2dOnR2(-1, N)
reprs = []
labels = []
modules = []
kernel = (3, 3)
for blocks, module in poolings:
# print(blocks)
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in poolings:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, kernel_size=kernel), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=True)
nnl.check_equivariance(full_space_action=False)
def test_o2_multiples_batchnorm_sort(self):
N = 8
g = flipRot2dOnR2(-1, N)
for m in range(5):
g.induced_repr((None, -1), g.fibergroup.subgroup((None, -1))[0].irrep(m))
reprs = []
labels = []
modules = []
for blocks, module in batchnormalizations:
if module not in [NormBatchNorm, InducedNormBatchNorm]:
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
for r in g.representations.values():
if not r.contains_trivial():
for blocks, module in batchnormalizations:
if module == NormBatchNorm:
for name, type in blocks:
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
elif module == InducedNormBatchNorm:
for name, type in blocks:
if any(snl.startswith(type) for snl in r.supported_nonlinearities):
reprs.append(r)
labels.append(name)
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in batchnormalizations:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=True)
nnl.train()
b, c, h, w = 4, r.size, 30, 30
for i in range(20):
x = GeometricTensor(torch.randn(b, c, h, w), r)
nnl(x)
nnl.eval()
nnl.check_equivariance(full_space_action=False)
if __name__ == '__main__':
unittest.main()
| 32.970195 | 95 | 0.470854 | import unittest
from unittest import TestCase
from escnn.nn import *
from escnn.gspaces import *
import torch
import random
batchnormalizations = [
([('regular_bnorm', 'pointwise')], InnerBatchNorm),
([('g_bnorm', 'norm')], GNormBatchNorm),
([('norm_bnorm', 'norm')], NormBatchNorm),
([('indnorm_bnorm', 'induced_norm')], InducedNormBatchNorm),
]
allbatchnormalizations = []
for bn, _ in batchnormalizations:
allbatchnormalizations += bn
poolings = [
([('regular_mpool', 'pointwise')], PointwiseMaxPool),
([('norm_mpool', 'norm')], NormMaxPool),
]
allpoolings = []
for pl, _ in poolings:
allpoolings += pl
nonlinearities = [
([('p_relu', 'pointwise')], PointwiseNonLinearity),
([('p_sigmoid', 'pointwise')], PointwiseNonLinearity),
([('p_tanh', 'pointwise')], PointwiseNonLinearity),
([('c_relu', 'concatenated')], ConcatenatedNonLinearity),
([('c_sigmoid', 'concatenated')], ConcatenatedNonLinearity),
([('c_tanh', 'concatenated')], ConcatenatedNonLinearity),
([('n_relu', 'norm')], NormNonLinearity),
([('n_sigmoid', 'norm')], NormNonLinearity),
([('vectorfield', 'vectorfield')], VectorFieldNonLinearity),
([('gate', 'gate'), ('gated', 'gated')], GatedNonLinearity2),
]
allnonlinearities = []
for nl, _ in nonlinearities:
allnonlinearities += nl
convolutions = [
([('conv2d', 'any')], R2Conv),
]
allconvolutions = []
for cl, _ in convolutions:
allconvolutions += cl
allfunctions = allbatchnormalizations + allpoolings + allnonlinearities + allconvolutions
class TestNonLinearitiesFlipRotations(TestCase):
def test_dihedral_multiples_nonlinearities_sorted(self):
N = 8
g = flipRot2dOnR2(N)
reprs = []
labels = []
modules = []
gated = 0
for blocks, module in nonlinearities:
for name, type in blocks:
if name != 'gate':
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
if name == 'gated':
gated += 1
reprs = [g.trivial_repr] * gated + reprs
labels = ['gate'] * gated + labels
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in nonlinearities:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, function=blocks[0][0]), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.check_equivariance(full_space_action=False)
def test_dihedral_multiples_poolings_sorted(self):
N = 8
g = flipRot2dOnR2(N)
reprs = []
labels = []
modules = []
kernel = (3, 3)
for blocks, module in poolings:
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in poolings:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, kernel_size=kernel), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.check_equivariance(full_space_action=False)
def test_dihedral_multiples_batchnorm_sorted(self):
N = 8
g = flipRot2dOnR2(N)
M = N // 2
for m in range(M // 2 + 1):
g.induced_repr((0, M), g.fibergroup.subgroup((0, M))[0].irrep(1, m))
reprs = []
labels = []
modules = []
for blocks, module in batchnormalizations:
if module not in [NormBatchNorm, InducedNormBatchNorm]:
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
for r in g.representations.values():
if not r.contains_trivial():
for blocks, module in batchnormalizations:
if module == NormBatchNorm:
for name, type in blocks:
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
elif module == InducedNormBatchNorm:
for name, type in blocks:
if any(snl.startswith(type) for snl in r.supported_nonlinearities):
reprs.append(r)
labels.append(name)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in batchnormalizations:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.train()
b, c, h, w = 4, r.size, 30, 30
for i in range(20):
x = GeometricTensor(torch.randn(b, c, h, w), r)
nnl(x)
nnl.eval()
nnl.check_equivariance(full_space_action=False)
def test_dihedral_multiples_nonlinearities_shuffled(self):
N = 8
g = flipRot2dOnR2(N)
reprs = []
labels = []
modules = []
gated = 0
for blocks, module in nonlinearities:
for name, type in blocks:
if name != 'gate':
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
if name == 'gated':
gated += 1
reprs = [g.trivial_repr] * gated + reprs
labels = ['gate'] * gated + labels
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in nonlinearities:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, function=blocks[0][0]), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.check_equivariance(full_space_action=False)
def test_dihedral_multiples_poolings_shuffled(self):
N = 8
g = flipRot2dOnR2(N)
reprs = []
labels = []
modules = []
kernel = (3, 3)
for blocks, module in poolings:
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in poolings:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, kernel_size=kernel), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.check_equivariance(full_space_action=False)
def test_dihedral_multiples_batchnorm_shuffled(self):
N = 8
g = flipRot2dOnR2(N)
M = N // 2
for m in range(M // 2 + 1):
g.induced_repr((0, M), g.fibergroup.subgroup((0, M))[0].irrep(1, m))
reprs = []
labels = []
modules = []
for blocks, module in batchnormalizations:
if module not in [NormBatchNorm, InducedNormBatchNorm]:
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
for r in g.representations.values():
if not r.contains_trivial():
for blocks, module in batchnormalizations:
if module == NormBatchNorm:
for name, type in blocks:
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
elif module == InducedNormBatchNorm:
for name, type in blocks:
if any(snl.startswith(type) for snl in r.supported_nonlinearities):
reprs.append(r)
labels.append(name)
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in batchnormalizations:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.train()
b, c, h, w = 4, r.size, 30, 30
for i in range(20):
x = GeometricTensor(torch.randn(b, c, h, w), r)
nnl(x)
nnl.eval()
nnl.check_equivariance(full_space_action=False)
def test_dihedral_multiples_nonlinearities_sort(self):
N = 8
g = flipRot2dOnR2(N)
reprs = []
labels = []
modules = []
gated = 0
for blocks, module in nonlinearities:
for i in range(3):
for name, type in blocks:
if name != 'gate':
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
if name == 'gated':
gated += 1
reprs = [g.trivial_repr] * gated + reprs
labels = ['gate'] * gated + labels
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in nonlinearities:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, function=blocks[0][0]), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=True)
nnl.check_equivariance(full_space_action=False)
def test_dihedral_multiples_poolings_sort(self):
N = 8
g = flipRot2dOnR2(N)
reprs = []
labels = []
modules = []
kernel = (3, 3)
for blocks, module in poolings:
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in poolings:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, kernel_size=kernel), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=True)
nnl.check_equivariance(full_space_action=False)
def test_dihedral_multiples_batchnorm_sort(self):
N = 8
g = flipRot2dOnR2(N)
M = N // 2
for m in range(M // 2 + 1):
g.induced_repr((0, M), g.fibergroup.subgroup((0, M))[0].irrep(1, m))
reprs = []
labels = []
modules = []
for blocks, module in batchnormalizations:
if module not in [NormBatchNorm, InducedNormBatchNorm]:
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
for r in g.representations.values():
if not r.contains_trivial():
for blocks, module in batchnormalizations:
if module == NormBatchNorm:
for name, type in blocks:
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
elif module == InducedNormBatchNorm:
for name, type in blocks:
if any(snl.startswith(type) for snl in r.supported_nonlinearities):
reprs.append(r)
labels.append(name)
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in batchnormalizations:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=True)
nnl.train()
b, c, h, w = 4, r.size, 30, 30
for i in range(20):
x = GeometricTensor(torch.randn(b, c, h, w), r)
nnl(x)
nnl.eval()
nnl.check_equivariance(full_space_action=False)
def test_o2_multiples_nonlinearities_sorted(self):
N = 8
g = flipRot2dOnR2(-1, N)
reprs = []
labels = []
modules = []
gated = 0
for blocks, module in nonlinearities:
for name, type in blocks:
if name != 'gate':
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
if name == 'gated':
gated += 1
reprs = [g.trivial_repr] * gated + reprs
labels = ['gate'] * gated + labels
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in nonlinearities:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, function=blocks[0][0]), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.check_equivariance(full_space_action=False)
def test_o2_multiples_poolings_sorted(self):
N = 8
g = flipRot2dOnR2(-1, N)
reprs = []
labels = []
modules = []
kernel = (3, 3)
for blocks, module in poolings:
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in poolings:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, kernel_size=kernel), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.check_equivariance(full_space_action=False)
def test_o2_multiples_batchnorm_sorted(self):
N = 8
g = flipRot2dOnR2(-1, N)
for m in range(5):
g.induced_repr((None, -1), g.fibergroup.subgroup((None, -1))[0].irrep(m))
reprs = []
labels = []
modules = []
for blocks, module in batchnormalizations:
if module not in [NormBatchNorm, InducedNormBatchNorm]:
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
for r in g.representations.values():
if not r.contains_trivial():
for blocks, module in batchnormalizations:
if module == NormBatchNorm:
for name, type in blocks:
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
elif module == InducedNormBatchNorm:
for name, type in blocks:
if any(snl.startswith(type) for snl in r.supported_nonlinearities):
reprs.append(r)
labels.append(name)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in batchnormalizations:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.train()
b, c, h, w = 4, r.size, 30, 30
for i in range(20):
x = GeometricTensor(torch.randn(b, c, h, w), r)
nnl(x)
nnl.eval()
nnl.check_equivariance(full_space_action=False)
def test_o2_multiples_nonlinearities_shuffled(self):
N = 8
g = flipRot2dOnR2(-1, N)
reprs = []
labels = []
modules = []
gated = 0
for blocks, module in nonlinearities:
for name, type in blocks:
if name != 'gate':
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
if name == 'gated':
gated += 1
reprs = [g.trivial_repr] * gated + reprs
labels = ['gate'] * gated + labels
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in nonlinearities:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, function=blocks[0][0]), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.check_equivariance(full_space_action=False)
def test_o2_multiples_poolings_shuffled(self):
N = 8
g = flipRot2dOnR2(-1, N)
reprs = []
labels = []
modules = []
kernel = (3, 3)
for blocks, module in poolings:
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in poolings:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, kernel_size=kernel), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.check_equivariance(full_space_action=False)
def test_o2_multiples_batchnorm_shuffled(self):
N = 8
g = flipRot2dOnR2(-1, N)
for m in range(5):
g.induced_repr((None, -1), g.fibergroup.subgroup((None, -1))[0].irrep(m))
reprs = []
labels = []
modules = []
for blocks, module in batchnormalizations:
if module not in [NormBatchNorm, InducedNormBatchNorm]:
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
for r in g.representations.values():
if not r.contains_trivial():
for blocks, module in batchnormalizations:
if module == NormBatchNorm:
for name, type in blocks:
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
elif module == InducedNormBatchNorm:
for name, type in blocks:
if any(snl.startswith(type) for snl in r.supported_nonlinearities):
reprs.append(r)
labels.append(name)
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in batchnormalizations:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=False)
nnl.train()
b, c, h, w = 4, r.size, 30, 30
for i in range(20):
x = GeometricTensor(torch.randn(b, c, h, w), r)
nnl(x)
nnl.eval()
nnl.check_equivariance(full_space_action=False)
def test_o2_multiples_nonlinearities_sort(self):
N = 8
g = flipRot2dOnR2(-1, N)
reprs = []
labels = []
modules = []
gated = 0
for blocks, module in nonlinearities:
for i in range(3):
for name, type in blocks:
if name != 'gate':
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
if name == 'gated':
gated += 1
reprs = [g.trivial_repr] * gated + reprs
labels = ['gate'] * gated + labels
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in nonlinearities:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, function=blocks[0][0]), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=True)
nnl.check_equivariance(full_space_action=False)
def test_o2_multiples_poolings_sort(self):
N = 8
g = flipRot2dOnR2(-1, N)
reprs = []
labels = []
modules = []
kernel = (3, 3)
for blocks, module in poolings:
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in poolings:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr, kernel_size=kernel), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=True)
nnl.check_equivariance(full_space_action=False)
def test_o2_multiples_batchnorm_sort(self):
N = 8
g = flipRot2dOnR2(-1, N)
for m in range(5):
g.induced_repr((None, -1), g.fibergroup.subgroup((None, -1))[0].irrep(m))
reprs = []
labels = []
modules = []
for blocks, module in batchnormalizations:
if module not in [NormBatchNorm, InducedNormBatchNorm]:
for name, type in blocks:
for r in g.representations.values():
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
for r in g.representations.values():
if not r.contains_trivial():
for blocks, module in batchnormalizations:
if module == NormBatchNorm:
for name, type in blocks:
if type in r.supported_nonlinearities:
reprs.append(r)
labels.append(name)
elif module == InducedNormBatchNorm:
for name, type in blocks:
if any(snl.startswith(type) for snl in r.supported_nonlinearities):
reprs.append(r)
labels.append(name)
t = list(zip(reprs, labels))
random.shuffle(t)
reprs, labels = zip(*t)
r = FieldType(g, reprs)
reprs_dict = r.group_by_labels(labels)
for blocks, module in batchnormalizations:
if all(l in reprs_dict for l, _ in blocks):
repr = tuple(reprs_dict[l] for l, _ in blocks)
if len(repr) == 1:
repr = repr[0]
lbs = [l for l, _ in blocks]
if len(lbs) == 1:
lbs = lbs[0]
modules.append((module(repr), lbs))
nnl = MultipleModule(r, labels, modules, reshuffle=True)
nnl.train()
b, c, h, w = 4, r.size, 30, 30
for i in range(20):
x = GeometricTensor(torch.randn(b, c, h, w), r)
nnl(x)
nnl.eval()
nnl.check_equivariance(full_space_action=False)
if __name__ == '__main__':
unittest.main()
| true | true |
1c2bc7eb173349f47a557a2b19dac248efb80629 | 10,472 | py | Python | zs3/tools.py | vaynelau/zs3-modified | da48567cb30e60dbe7827f56ec48f1a0098cd94a | [
"Apache-2.0"
] | null | null | null | zs3/tools.py | vaynelau/zs3-modified | da48567cb30e60dbe7827f56ec48f1a0098cd94a | [
"Apache-2.0"
] | null | null | null | zs3/tools.py | vaynelau/zs3-modified | da48567cb30e60dbe7827f56ec48f1a0098cd94a | [
"Apache-2.0"
] | null | null | null | import os
import sys
import yaml
import random
import pickle
import cv2
import numpy as np
import torch
import torch.nn.functional as F
class MeaninglessError(BaseException):
pass
class Const_Scheduler():
def __init__(self, step_n='step1'):
assert (step_n in ['step1', 'step2', 'self_training'])
self.step_n = step_n
pass
def now(self):
return self.step_n
def step(self):
pass
class Step_Scheduler():
def __init__(self, interval_step1, interval_step2, first='step2'):
assert (first in ['step1', 'step2'])
assert (interval_step1 > 0 and interval_step2 > 0)
self.interval_step1 = int(interval_step1)
self.interval_step2 = int(interval_step2)
self.first = first
self.now_step = 0
def now(self):
assert (self.now_step in range(self.interval_step1 + self.interval_step2))
if self.first == 'step2':
if self.now_step < self.interval_step2:
return 'step2'
else:
return 'step1'
else:
if self.now_step < self.interval_step1:
return 'step1'
else:
return 'step2'
def step(self):
self.now_step += 1
if self.now_step == self.interval_step1 + self.interval_step2:
self.now_step = 0
class logWritter():
def __init__(self, log_file):
self.logs = log_file
if not os.path.exists(log_file):
os.mknod(log_file)
def write(self, strs):
assert (type(strs) == str)
with open(self.logs, 'a') as f:
f.write(strs + '\n')
class RandomImageSampler(torch.utils.data.Sampler):
"""
Samples classes randomly, then returns images corresponding to those classes.
"""
def __init__(self, seenset, novelset):
self.data_index = []
for v in seenset:
self.data_index.append([v, 0])
for v, i in novelset:
self.data_index.append([v, i + 1])
def __iter__(self):
return iter([self.data_index[i] for i in np.random.permutation(len(self.data_index))])
def __len__(self):
return len(self.data_index)
def construct_gt_st(resized_gt_st, sorted_indices, config):
indices_select = sorted_indices[:, :, :, :config['top_p']] # retain category indices with top_p prediction scores
indices_select_pos = torch.full(indices_select.shape, config['ignore_index']).long()
indices_select_neg = torch.full(indices_select.shape, -config['ignore_index']).long()
indices_repeat = torch.LongTensor(range(config['top_p'])).repeat(indices_select.shape[0], indices_select.shape[1],
indices_select.shape[2], 1)
p0 = torch.where(indices_select >= config['dis']['out_dim_cls'] - config['num_unseen'] - 1, indices_select,
indices_select_pos).long()
p1 = torch.where(indices_select < config['dis']['out_dim_cls'] - 1, indices_select, indices_select_neg).long()
p2 = torch.where(p0 == p1, indices_select, indices_select_pos).long()
p3 = torch.where(p0 == p1, indices_repeat, indices_select_pos).long()
p4 = torch.argmin(p3, dim=3).long()
accumulated = config['top_p'] * torch.LongTensor(range(p2.shape[0] * p2.shape[1] * p2.shape[2]))
p5 = p4.view(-1) + accumulated
p6 = p2.view(-1)[p5].view(resized_gt_st.shape)
gt_new = torch.where(resized_gt_st == config['ignore_index'], p6, resized_gt_st).long()
return gt_new
def resize_target(target, size):
new_target = np.zeros((target.shape[0], size, size), np.int32)
for i, t in enumerate(target.cpu().numpy()):
new_target[i, ...] = cv2.resize(t, (size,) * 2, interpolation=cv2.INTER_NEAREST)
return torch.from_numpy(new_target).long()
def get_config(config):
with open(config, 'r') as stream:
return yaml.load(stream, Loader=yaml.FullLoader)
def get_embedding(dataset_path):
class_emb = np.concatenate([pickle.load(open(dataset_path / 'word_vectors/fasttext.pkl', "rb")),
pickle.load(open(dataset_path / 'word_vectors/word2vec.pkl', "rb"))], axis=1)
class_emb = F.normalize(torch.tensor(class_emb, dtype=torch.float32), p=2, dim=1)
print("Class embedding map normalized!")
return class_emb
def get_split(cfg):
dataset_path = os.path.join(cfg['datadir'], cfg['dataset'])
train = np.load(dataset_path + '/split/train_list.npy')
val = np.load(dataset_path + '/split/test_list.npy')
seen_classes = np.load(dataset_path + '/split/seen_cls.npy').astype(np.int32)
novel_classes = np.load(dataset_path + '/split/novel_cls.npy').astype(np.int32)
# if cfg['dataset'] == 'cocostuff':
# seen_classes += 1
# novel_classes += 1
seen_novel_classes = np.concatenate((seen_classes, novel_classes), axis=0)
all_labels = np.genfromtxt(dataset_path + '/labels_refined.txt', delimiter='\t', usecols=1, dtype='str')
# if cfg['dataset'] == 'cocostuff':
# all_labels = np.insert(all_labels, 0, 'background')
visible_classes = seen_classes
visible_classes_test = seen_novel_classes
novelset, seenset = [], range(train.shape[0])
sampler = RandomImageSampler(seenset, novelset)
if cfg['dataset'] == 'cocostuff':
cls_map = np.array([cfg['ignore_index']] * (cfg['ignore_index'] + 1)).astype(np.int32)
for i, n in enumerate(list(seen_classes)):
cls_map[n] = n
cls_map_test = np.array([cfg['ignore_index']] * (cfg['ignore_index'] + 1)).astype(np.int32)
for i, n in enumerate(list(seen_novel_classes)):
cls_map_test[n] = n
else:
cls_map = np.array([cfg['ignore_index']] * (cfg['ignore_index'] + 1)).astype(np.int32)
for i, n in enumerate(list(seen_classes)):
cls_map[n] = n - 1
cls_map_test = np.array([cfg['ignore_index']] * (cfg['ignore_index'] + 1)).astype(np.int32)
for i, n in enumerate(list(seen_novel_classes)):
cls_map_test[n] = n - 1
visibility_mask = {}
visibility_mask[0] = cls_map.copy()
for i, n in enumerate(list(novel_classes)):
visibility_mask[i + 1] = cls_map.copy()
visibility_mask[i + 1][n] = seen_classes.shape[0] + i
# print('seen_classes', seen_classes)
# print('novel_classes', novel_classes)
# print('all_labels', all_labels)
# print('visible_classes', visible_classes)
# print('visible_classes_test', visible_classes_test)
# print('visibility_mask[0]', visibility_mask[0])
# print('train', train[:10], len(train))
# print('val', val[:10], len(val))
return seen_classes, novel_classes, all_labels, visible_classes, visible_classes_test, train, val, sampler, visibility_mask, cls_map, cls_map_test
def _fast_hist(label_true, label_pred, n_class):
mask = (label_true >= 0) & (label_true < n_class)
hist = np.bincount(
n_class * label_true[mask].astype(int) + label_pred[mask],
minlength=n_class ** 2,
).reshape(n_class, n_class)
return hist
def scores(label_trues, label_preds, n_class):
hist = np.zeros((n_class, n_class))
for lt, lp in zip(label_trues, label_preds):
if (lt.size > 0):
hist += _fast_hist(lt.flatten(), lp.flatten(), n_class)
acc = np.diag(hist).sum() / hist.sum()
acc_cls = np.diag(hist) / hist.sum(axis=1)
acc_cls = np.nanmean(acc_cls)
iu = np.diag(hist) / (hist.sum(axis=1) + hist.sum(axis=0) - np.diag(hist))
mean_iu = np.nanmean(iu)
freq = hist.sum(axis=1) / hist.sum()
fwavacc = (freq[freq > 0] * iu[freq > 0]).sum()
cls_iu = dict(zip(range(n_class), iu))
return {
"Overall Acc": acc,
"Mean Acc": acc_cls,
"FreqW Acc": fwavacc,
"Mean IoU": mean_iu,
}, cls_iu
def scores_gzsl(label_trues, label_preds, n_class, seen_cls, unseen_cls):
hist = np.zeros((n_class, n_class))
for lt, lp in zip(label_trues, label_preds):
if (lt.size > 0):
hist += _fast_hist(lt.flatten(), lp.flatten(), n_class)
with np.errstate(divide='ignore', invalid='ignore'):
acc = np.diag(hist).sum() / hist.sum()
seen_acc = np.diag(hist)[seen_cls].sum() / hist[seen_cls].sum()
unseen_acc = np.diag(hist)[unseen_cls].sum() / hist[unseen_cls].sum()
h_acc = 2. / (1. / seen_acc + 1. / unseen_acc)
if np.isnan(h_acc):
h_acc = 0
acc_cls = np.diag(hist) / hist.sum(axis=1)
seen_acc_cls = np.diag(hist)[seen_cls] / hist.sum(axis=1)[seen_cls]
unseen_acc_cls = np.diag(hist)[unseen_cls] / hist.sum(axis=1)[unseen_cls]
acc_cls = np.nanmean(acc_cls)
seen_acc_cls = np.nanmean(seen_acc_cls)
unseen_acc_cls = np.nanmean(unseen_acc_cls)
h_acc_cls = 2. / (1. / seen_acc_cls + 1. / unseen_acc_cls)
if np.isnan(h_acc_cls):
h_acc_cls = 0
iu = np.diag(hist) / (hist.sum(axis=1) + hist.sum(axis=0) - np.diag(hist))
mean_iu = np.nanmean(iu)
seen_mean_iu = np.nanmean(iu[seen_cls])
unseen_mean_iu = np.nanmean(iu[unseen_cls])
h_mean_iu = 2. / (1. / seen_mean_iu + 1. / unseen_mean_iu)
if np.isnan(h_mean_iu):
h_mean_iu = 0
freq = hist.sum(axis=1) / hist.sum()
fwavacc = (freq * iu)
fwavacc[np.isnan(fwavacc)] = 0
seen_fwavacc = fwavacc[seen_cls].sum()
unseen_fwavacc = fwavacc[unseen_cls].sum()
h_fwavacc = 2. / (1. / seen_fwavacc + 1. / unseen_fwavacc)
if np.isnan(h_fwavacc):
h_fwavacc = 0
fwavacc = fwavacc.sum()
cls_iu = dict(zip(range(n_class), iu))
return {
"Overall Acc": acc,
"Overall Acc Seen": seen_acc,
"Overall Acc Unseen": unseen_acc,
"Overall Acc Harmonic": h_acc,
"Mean Acc": acc_cls,
"Mean Acc Seen": seen_acc_cls,
"Mean Acc Unseen": unseen_acc_cls,
"Mean Acc Harmonic": h_acc_cls,
"FreqW Acc": fwavacc,
"FreqW Acc Seen": seen_fwavacc,
"FreqW Acc Unseen": unseen_fwavacc,
"FreqW Acc Harmonic": h_fwavacc,
"Mean IoU": mean_iu,
"Mean IoU Seen": seen_mean_iu,
"Mean IoU Unseen": unseen_mean_iu,
"Mean IoU Harmonic": h_mean_iu,
}, cls_iu | 38.929368 | 150 | 0.612777 | import os
import sys
import yaml
import random
import pickle
import cv2
import numpy as np
import torch
import torch.nn.functional as F
class MeaninglessError(BaseException):
pass
class Const_Scheduler():
def __init__(self, step_n='step1'):
assert (step_n in ['step1', 'step2', 'self_training'])
self.step_n = step_n
pass
def now(self):
return self.step_n
def step(self):
pass
class Step_Scheduler():
def __init__(self, interval_step1, interval_step2, first='step2'):
assert (first in ['step1', 'step2'])
assert (interval_step1 > 0 and interval_step2 > 0)
self.interval_step1 = int(interval_step1)
self.interval_step2 = int(interval_step2)
self.first = first
self.now_step = 0
def now(self):
assert (self.now_step in range(self.interval_step1 + self.interval_step2))
if self.first == 'step2':
if self.now_step < self.interval_step2:
return 'step2'
else:
return 'step1'
else:
if self.now_step < self.interval_step1:
return 'step1'
else:
return 'step2'
def step(self):
self.now_step += 1
if self.now_step == self.interval_step1 + self.interval_step2:
self.now_step = 0
class logWritter():
def __init__(self, log_file):
self.logs = log_file
if not os.path.exists(log_file):
os.mknod(log_file)
def write(self, strs):
assert (type(strs) == str)
with open(self.logs, 'a') as f:
f.write(strs + '\n')
class RandomImageSampler(torch.utils.data.Sampler):
def __init__(self, seenset, novelset):
self.data_index = []
for v in seenset:
self.data_index.append([v, 0])
for v, i in novelset:
self.data_index.append([v, i + 1])
def __iter__(self):
return iter([self.data_index[i] for i in np.random.permutation(len(self.data_index))])
def __len__(self):
return len(self.data_index)
def construct_gt_st(resized_gt_st, sorted_indices, config):
indices_select = sorted_indices[:, :, :, :config['top_p']]
indices_select_pos = torch.full(indices_select.shape, config['ignore_index']).long()
indices_select_neg = torch.full(indices_select.shape, -config['ignore_index']).long()
indices_repeat = torch.LongTensor(range(config['top_p'])).repeat(indices_select.shape[0], indices_select.shape[1],
indices_select.shape[2], 1)
p0 = torch.where(indices_select >= config['dis']['out_dim_cls'] - config['num_unseen'] - 1, indices_select,
indices_select_pos).long()
p1 = torch.where(indices_select < config['dis']['out_dim_cls'] - 1, indices_select, indices_select_neg).long()
p2 = torch.where(p0 == p1, indices_select, indices_select_pos).long()
p3 = torch.where(p0 == p1, indices_repeat, indices_select_pos).long()
p4 = torch.argmin(p3, dim=3).long()
accumulated = config['top_p'] * torch.LongTensor(range(p2.shape[0] * p2.shape[1] * p2.shape[2]))
p5 = p4.view(-1) + accumulated
p6 = p2.view(-1)[p5].view(resized_gt_st.shape)
gt_new = torch.where(resized_gt_st == config['ignore_index'], p6, resized_gt_st).long()
return gt_new
def resize_target(target, size):
new_target = np.zeros((target.shape[0], size, size), np.int32)
for i, t in enumerate(target.cpu().numpy()):
new_target[i, ...] = cv2.resize(t, (size,) * 2, interpolation=cv2.INTER_NEAREST)
return torch.from_numpy(new_target).long()
def get_config(config):
with open(config, 'r') as stream:
return yaml.load(stream, Loader=yaml.FullLoader)
def get_embedding(dataset_path):
class_emb = np.concatenate([pickle.load(open(dataset_path / 'word_vectors/fasttext.pkl', "rb")),
pickle.load(open(dataset_path / 'word_vectors/word2vec.pkl', "rb"))], axis=1)
class_emb = F.normalize(torch.tensor(class_emb, dtype=torch.float32), p=2, dim=1)
print("Class embedding map normalized!")
return class_emb
def get_split(cfg):
dataset_path = os.path.join(cfg['datadir'], cfg['dataset'])
train = np.load(dataset_path + '/split/train_list.npy')
val = np.load(dataset_path + '/split/test_list.npy')
seen_classes = np.load(dataset_path + '/split/seen_cls.npy').astype(np.int32)
novel_classes = np.load(dataset_path + '/split/novel_cls.npy').astype(np.int32)
seen_novel_classes = np.concatenate((seen_classes, novel_classes), axis=0)
all_labels = np.genfromtxt(dataset_path + '/labels_refined.txt', delimiter='\t', usecols=1, dtype='str')
visible_classes = seen_classes
visible_classes_test = seen_novel_classes
novelset, seenset = [], range(train.shape[0])
sampler = RandomImageSampler(seenset, novelset)
if cfg['dataset'] == 'cocostuff':
cls_map = np.array([cfg['ignore_index']] * (cfg['ignore_index'] + 1)).astype(np.int32)
for i, n in enumerate(list(seen_classes)):
cls_map[n] = n
cls_map_test = np.array([cfg['ignore_index']] * (cfg['ignore_index'] + 1)).astype(np.int32)
for i, n in enumerate(list(seen_novel_classes)):
cls_map_test[n] = n
else:
cls_map = np.array([cfg['ignore_index']] * (cfg['ignore_index'] + 1)).astype(np.int32)
for i, n in enumerate(list(seen_classes)):
cls_map[n] = n - 1
cls_map_test = np.array([cfg['ignore_index']] * (cfg['ignore_index'] + 1)).astype(np.int32)
for i, n in enumerate(list(seen_novel_classes)):
cls_map_test[n] = n - 1
visibility_mask = {}
visibility_mask[0] = cls_map.copy()
for i, n in enumerate(list(novel_classes)):
visibility_mask[i + 1] = cls_map.copy()
visibility_mask[i + 1][n] = seen_classes.shape[0] + i
return seen_classes, novel_classes, all_labels, visible_classes, visible_classes_test, train, val, sampler, visibility_mask, cls_map, cls_map_test
def _fast_hist(label_true, label_pred, n_class):
mask = (label_true >= 0) & (label_true < n_class)
hist = np.bincount(
n_class * label_true[mask].astype(int) + label_pred[mask],
minlength=n_class ** 2,
).reshape(n_class, n_class)
return hist
def scores(label_trues, label_preds, n_class):
hist = np.zeros((n_class, n_class))
for lt, lp in zip(label_trues, label_preds):
if (lt.size > 0):
hist += _fast_hist(lt.flatten(), lp.flatten(), n_class)
acc = np.diag(hist).sum() / hist.sum()
acc_cls = np.diag(hist) / hist.sum(axis=1)
acc_cls = np.nanmean(acc_cls)
iu = np.diag(hist) / (hist.sum(axis=1) + hist.sum(axis=0) - np.diag(hist))
mean_iu = np.nanmean(iu)
freq = hist.sum(axis=1) / hist.sum()
fwavacc = (freq[freq > 0] * iu[freq > 0]).sum()
cls_iu = dict(zip(range(n_class), iu))
return {
"Overall Acc": acc,
"Mean Acc": acc_cls,
"FreqW Acc": fwavacc,
"Mean IoU": mean_iu,
}, cls_iu
def scores_gzsl(label_trues, label_preds, n_class, seen_cls, unseen_cls):
hist = np.zeros((n_class, n_class))
for lt, lp in zip(label_trues, label_preds):
if (lt.size > 0):
hist += _fast_hist(lt.flatten(), lp.flatten(), n_class)
with np.errstate(divide='ignore', invalid='ignore'):
acc = np.diag(hist).sum() / hist.sum()
seen_acc = np.diag(hist)[seen_cls].sum() / hist[seen_cls].sum()
unseen_acc = np.diag(hist)[unseen_cls].sum() / hist[unseen_cls].sum()
h_acc = 2. / (1. / seen_acc + 1. / unseen_acc)
if np.isnan(h_acc):
h_acc = 0
acc_cls = np.diag(hist) / hist.sum(axis=1)
seen_acc_cls = np.diag(hist)[seen_cls] / hist.sum(axis=1)[seen_cls]
unseen_acc_cls = np.diag(hist)[unseen_cls] / hist.sum(axis=1)[unseen_cls]
acc_cls = np.nanmean(acc_cls)
seen_acc_cls = np.nanmean(seen_acc_cls)
unseen_acc_cls = np.nanmean(unseen_acc_cls)
h_acc_cls = 2. / (1. / seen_acc_cls + 1. / unseen_acc_cls)
if np.isnan(h_acc_cls):
h_acc_cls = 0
iu = np.diag(hist) / (hist.sum(axis=1) + hist.sum(axis=0) - np.diag(hist))
mean_iu = np.nanmean(iu)
seen_mean_iu = np.nanmean(iu[seen_cls])
unseen_mean_iu = np.nanmean(iu[unseen_cls])
h_mean_iu = 2. / (1. / seen_mean_iu + 1. / unseen_mean_iu)
if np.isnan(h_mean_iu):
h_mean_iu = 0
freq = hist.sum(axis=1) / hist.sum()
fwavacc = (freq * iu)
fwavacc[np.isnan(fwavacc)] = 0
seen_fwavacc = fwavacc[seen_cls].sum()
unseen_fwavacc = fwavacc[unseen_cls].sum()
h_fwavacc = 2. / (1. / seen_fwavacc + 1. / unseen_fwavacc)
if np.isnan(h_fwavacc):
h_fwavacc = 0
fwavacc = fwavacc.sum()
cls_iu = dict(zip(range(n_class), iu))
return {
"Overall Acc": acc,
"Overall Acc Seen": seen_acc,
"Overall Acc Unseen": unseen_acc,
"Overall Acc Harmonic": h_acc,
"Mean Acc": acc_cls,
"Mean Acc Seen": seen_acc_cls,
"Mean Acc Unseen": unseen_acc_cls,
"Mean Acc Harmonic": h_acc_cls,
"FreqW Acc": fwavacc,
"FreqW Acc Seen": seen_fwavacc,
"FreqW Acc Unseen": unseen_fwavacc,
"FreqW Acc Harmonic": h_fwavacc,
"Mean IoU": mean_iu,
"Mean IoU Seen": seen_mean_iu,
"Mean IoU Unseen": unseen_mean_iu,
"Mean IoU Harmonic": h_mean_iu,
}, cls_iu | true | true |
1c2bc8edf67c70d66eaf4332f8ec9bfdbb7cfc35 | 2,023 | py | Python | gui/mlin.py | pocar/mlin | d7d37a9f20a22a94a23b31a8b281c6c10dda178e | [
"MIT"
] | null | null | null | gui/mlin.py | pocar/mlin | d7d37a9f20a22a94a23b31a8b281c6c10dda178e | [
"MIT"
] | null | null | null | gui/mlin.py | pocar/mlin | d7d37a9f20a22a94a23b31a8b281c6c10dda178e | [
"MIT"
] | null | null | null | #!/usr/bin/python
'''
Created on 5. avg. 2012
@author: anton
'''
import pygame
from pygame.locals import *
from igralnadeska import IgralnaDeska
from gradniki import *
velikostZaslona = [640, 480]
bela = (255, 255, 255)
crna = (0, 0, 0 )
svetlo_siva = (230, 230, 230)
temno_siva = (80, 80, 80)
def main():
pygame.init() #@UndefinedVariable
deska = IgralnaDeska(Rect((0,0),(velikostZaslona[0],velikostZaslona[1]-60)))
statusnaVrstica = StatusnaVrstica(Rect([0, velikostZaslona[1]-25, velikostZaslona[0], 25]))
novaIgra = Gumb(Rect([0, velikostZaslona[1]-57, velikostZaslona[0]//3, 30]), "Nova igra")
# for i in range(24):
# deska.polje[i].zeton = 1 + (i % 2)
# print("{0} -> {1}".format(i,deska.polje[i].center))
zaslon = pygame.display.set_mode(velikostZaslona)
pygame.display.set_caption("Mlin")
clock = pygame.time.Clock()
done = False
while done == False:
# event handling
for event in pygame.event.get(): # User did something
if event.type == MOUSEBUTTONDOWN: #@UndefinedVariable
if deska.konecIgre == False:
deska.klikDol(event)
novaIgra.klikDol(event)
elif event.type == MOUSEBUTTONUP: #@UndefinedVariable
if deska.konecIgre == False:
deska.klikGor(event)
novaIgra.klikGor(event)
elif event.type == QUIT: # If user clicked close @UndefinedVariable
done=True # Flag that we are done so we exit this loop
# posodobitev stanja gradnikov
statusnaVrstica.status(deska.status())
# izrisovanje
zaslon.fill(bela)
deska.izrisiDesko(zaslon)
statusnaVrstica.izrisi(zaslon)
novaIgra.izrisi(zaslon)
# izpiši status
# update the zaslon
pygame.display.flip()
# wait till next frame
clock.tick(30)
pygame.quit() #@UndefinedVariable
if __name__ == '__main__':
main() | 29.75 | 95 | 0.605042 |
import pygame
from pygame.locals import *
from igralnadeska import IgralnaDeska
from gradniki import *
velikostZaslona = [640, 480]
bela = (255, 255, 255)
crna = (0, 0, 0 )
svetlo_siva = (230, 230, 230)
temno_siva = (80, 80, 80)
def main():
pygame.init()
deska = IgralnaDeska(Rect((0,0),(velikostZaslona[0],velikostZaslona[1]-60)))
statusnaVrstica = StatusnaVrstica(Rect([0, velikostZaslona[1]-25, velikostZaslona[0], 25]))
novaIgra = Gumb(Rect([0, velikostZaslona[1]-57, velikostZaslona[0]//3, 30]), "Nova igra")
zaslon = pygame.display.set_mode(velikostZaslona)
pygame.display.set_caption("Mlin")
clock = pygame.time.Clock()
done = False
while done == False:
for event in pygame.event.get():
if event.type == MOUSEBUTTONDOWN:
if deska.konecIgre == False:
deska.klikDol(event)
novaIgra.klikDol(event)
elif event.type == MOUSEBUTTONUP:
if deska.konecIgre == False:
deska.klikGor(event)
novaIgra.klikGor(event)
elif event.type == QUIT:
done=True
statusnaVrstica.status(deska.status())
zaslon.fill(bela)
deska.izrisiDesko(zaslon)
statusnaVrstica.izrisi(zaslon)
novaIgra.izrisi(zaslon)
pygame.display.flip()
clock.tick(30)
pygame.quit()
if __name__ == '__main__':
main() | true | true |
1c2bc9966a7a60e8e1fd981ceb1dafd7a6ab7d6e | 1,927 | py | Python | tools/mytools/ARIA/src/py/aria/FloatFile.py | fmareuil/Galaxy_test_pasteur | 6f84fb0fc52e3e7dd358623b5da5354c66e16a5f | [
"CC-BY-3.0"
] | null | null | null | tools/mytools/ARIA/src/py/aria/FloatFile.py | fmareuil/Galaxy_test_pasteur | 6f84fb0fc52e3e7dd358623b5da5354c66e16a5f | [
"CC-BY-3.0"
] | null | null | null | tools/mytools/ARIA/src/py/aria/FloatFile.py | fmareuil/Galaxy_test_pasteur | 6f84fb0fc52e3e7dd358623b5da5354c66e16a5f | [
"CC-BY-3.0"
] | null | null | null | """
ARIA -- Ambiguous Restraints for Iterative Assignment
A software for automated NOE assignment
Version 2.3
Copyright (C) Benjamin Bardiaux, Michael Habeck, Therese Malliavin,
Wolfgang Rieping, and Michael Nilges
All rights reserved.
NO WARRANTY. This software package is provided 'as is' without warranty of
any kind, expressed or implied, including, but not limited to the implied
warranties of merchantability and fitness for a particular purpose or
a warranty of non-infringement.
Distribution of substantively modified versions of this module is
prohibited without the explicit permission of the copyright holders.
$Author: bardiaux $
$Revision: 1.1.1.1 $
$Date: 2010/03/23 15:27:24 $
"""
from aria.ariabase import AriaBaseClass as _AriaBaseClass
class FloatFile(_AriaBaseClass):
def parse(self, file):
from aria.tools import string_to_segid
import re
atom = 'segid "(?P<segid%(i)d>.*)" and ' + \
'resid (?P<residue%(i)d>[0-9]+).*and ' + \
'name (?P<atom%(i)d>H[A-Z0-9]+)'
line = 'REVE.*\(\(.*%s.*\).*OR.*\(.*%s.*\)\)' \
% (atom % {'i': 1}, atom % {'i': 2})
regex = re.compile(line)
table = regex.findall(open(file).read())
swapped_atoms = {}
for row in table:
row = [x.strip() for x in row]
row = [f(x) for f, x in zip([str, int, str, str, int, str], row)]
row[0] = string_to_segid(row[0])
row[3] = string_to_segid(row[3])
key = tuple(row[:3])
value = tuple(row[3:])
if swapped_atoms.has_key(key):
m = 'Inconsistency: atom "%s" swapped twice.' % str(key)
self.error(ValueError, m)
swapped_atoms[key] = value
return swapped_atoms
| 26.763889 | 77 | 0.567722 |
from aria.ariabase import AriaBaseClass as _AriaBaseClass
class FloatFile(_AriaBaseClass):
def parse(self, file):
from aria.tools import string_to_segid
import re
atom = 'segid "(?P<segid%(i)d>.*)" and ' + \
'resid (?P<residue%(i)d>[0-9]+).*and ' + \
'name (?P<atom%(i)d>H[A-Z0-9]+)'
line = 'REVE.*\(\(.*%s.*\).*OR.*\(.*%s.*\)\)' \
% (atom % {'i': 1}, atom % {'i': 2})
regex = re.compile(line)
table = regex.findall(open(file).read())
swapped_atoms = {}
for row in table:
row = [x.strip() for x in row]
row = [f(x) for f, x in zip([str, int, str, str, int, str], row)]
row[0] = string_to_segid(row[0])
row[3] = string_to_segid(row[3])
key = tuple(row[:3])
value = tuple(row[3:])
if swapped_atoms.has_key(key):
m = 'Inconsistency: atom "%s" swapped twice.' % str(key)
self.error(ValueError, m)
swapped_atoms[key] = value
return swapped_atoms
| true | true |
1c2bca30ebc3205d10e58a5c3f4df4a6a073fa28 | 41,448 | py | Python | tests/test_tuya.py | Thomas55555/zha-device-handlers | 16c76d85dbb7bb71ae38cf37a46e9665e25a5fcc | [
"Apache-2.0"
] | null | null | null | tests/test_tuya.py | Thomas55555/zha-device-handlers | 16c76d85dbb7bb71ae38cf37a46e9665e25a5fcc | [
"Apache-2.0"
] | null | null | null | tests/test_tuya.py | Thomas55555/zha-device-handlers | 16c76d85dbb7bb71ae38cf37a46e9665e25a5fcc | [
"Apache-2.0"
] | null | null | null | """Tests for Tuya quirks."""
import asyncio
import datetime
from unittest import mock
import pytest
from zigpy.profiles import zha
from zigpy.quirks import CustomDevice, get_device
import zigpy.types as t
from zigpy.zcl import foundation
from zhaquirks.const import (
DEVICE_TYPE,
ENDPOINTS,
INPUT_CLUSTERS,
MODELS_INFO,
OFF,
ON,
OUTPUT_CLUSTERS,
PROFILE_ID,
ZONE_STATE,
)
from zhaquirks.tuya import Data, TuyaManufClusterAttributes
import zhaquirks.tuya.electric_heating
import zhaquirks.tuya.motion
import zhaquirks.tuya.siren
import zhaquirks.tuya.ts0042
import zhaquirks.tuya.ts0043
import zhaquirks.tuya.valve
from tests.common import ClusterListener
ZCL_TUYA_SET_TIME_REQUEST = b"\tp\x24\x00\00"
ZCL_TUYA_MOTION = b"\tL\x01\x00\x05\x03\x04\x00\x01\x02"
ZCL_TUYA_SWITCH_ON = b"\tQ\x02\x006\x01\x01\x00\x01\x01"
ZCL_TUYA_SWITCH_OFF = b"\tQ\x02\x006\x01\x01\x00\x01\x00"
ZCL_TUYA_ATTRIBUTE_617_TO_179 = b"\tp\x02\x00\x02i\x02\x00\x04\x00\x00\x00\xb3"
ZCL_TUYA_SIREN_TEMPERATURE = ZCL_TUYA_ATTRIBUTE_617_TO_179
ZCL_TUYA_SIREN_HUMIDITY = b"\tp\x02\x00\x02j\x02\x00\x04\x00\x00\x00U"
ZCL_TUYA_SIREN_ON = b"\t\t\x02\x00\x04h\x01\x00\x01\x01"
ZCL_TUYA_SIREN_OFF = b"\t\t\x02\x00\x04h\x01\x00\x01\x00"
ZCL_TUYA_VALVE_TEMPERATURE = b"\tp\x02\x00\x02\x03\x02\x00\x04\x00\x00\x00\xb3"
ZCL_TUYA_VALVE_TARGET_TEMP = b"\t3\x01\x03\x05\x02\x02\x00\x04\x00\x00\x002"
ZCL_TUYA_VALVE_OFF = b"\t2\x01\x03\x04\x04\x04\x00\x01\x00"
ZCL_TUYA_VALVE_SCHEDULE = b"\t2\x01\x03\x04\x04\x04\x00\x01\x01"
ZCL_TUYA_VALVE_MANUAL = b"\t2\x01\x03\x04\x04\x04\x00\x01\x02"
ZCL_TUYA_VALVE_COMFORT = b"\t2\x01\x03\x04\x04\x04\x00\x01\x03"
ZCL_TUYA_VALVE_ECO = b"\t2\x01\x03\x04\x04\x04\x00\x01\x04"
ZCL_TUYA_VALVE_BOOST = b"\t2\x01\x03\x04\x04\x04\x00\x01\x05"
ZCL_TUYA_VALVE_COMPLEX = b"\t2\x01\x03\x04\x04\x04\x00\x01\x06"
ZCL_TUYA_VALVE_WINDOW_DETECTION = b"\tp\x02\x00\x02\x68\x00\x00\x03\x01\x10\x05"
ZCL_TUYA_VALVE_WORKDAY_SCHEDULE = b"\tp\x02\x00\x02\x70\x00\x00\x12\x06\x00\x14\x08\x00\x0F\x0B\x1E\x0F\x0C\x1E\x0F\x11\x1E\x14\x16\x00\x0F"
ZCL_TUYA_VALVE_WEEKEND_SCHEDULE = b"\tp\x02\x00\x02\x71\x00\x00\x12\x06\x00\x14\x08\x00\x0F\x0B\x1E\x0F\x0C\x1E\x0F\x11\x1E\x14\x16\x00\x0F"
ZCL_TUYA_VALVE_STATE_50 = b"\t2\x01\x03\x04\x6D\x02\x00\x04\x00\x00\x00\x32"
ZCL_TUYA_VALVE_CHILD_LOCK_ON = b"\t2\x01\x03\x04\x07\x01\x00\x01\x01"
ZCL_TUYA_VALVE_AUTO_LOCK_ON = b"\t2\x01\x03\x04\x74\x01\x00\x01\x01"
ZCL_TUYA_VALVE_BATTERY_LOW = b"\t2\x01\x03\x04\x6E\x01\x00\x01\x01"
ZCL_TUYA_EHEAT_TEMPERATURE = b"\tp\x02\x00\x02\x18\x02\x00\x04\x00\x00\x00\xb3"
ZCL_TUYA_EHEAT_TARGET_TEMP = b"\t3\x01\x03\x05\x10\x02\x00\x04\x00\x00\x00\x15"
class NewDatetime(datetime.datetime):
"""Override for datetime functions."""
@classmethod
def now(cls):
"""Return testvalue."""
return cls(1970, 1, 1, 1, 0, 0)
@classmethod
def utcnow(cls):
"""Return testvalue."""
return cls(1970, 1, 1, 2, 0, 0)
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.motion.TuyaMotion,))
async def test_motion(zigpy_device_from_quirk, quirk):
"""Test tuya motion sensor."""
motion_dev = zigpy_device_from_quirk(quirk)
motion_cluster = motion_dev.endpoints[1].ias_zone
motion_listener = ClusterListener(motion_cluster)
tuya_cluster = motion_dev.endpoints[1].tuya_manufacturer
# send motion on Tuya manufacturer specific cluster
hdr, args = tuya_cluster.deserialize(ZCL_TUYA_MOTION)
with mock.patch.object(motion_cluster, "reset_s", 0):
tuya_cluster.handle_message(hdr, args)
assert len(motion_listener.cluster_commands) == 1
assert len(motion_listener.attribute_updates) == 1
assert motion_listener.cluster_commands[0][1] == ZONE_STATE
assert motion_listener.cluster_commands[0][2][0] == ON
await asyncio.gather(asyncio.sleep(0), asyncio.sleep(0), asyncio.sleep(0))
assert len(motion_listener.cluster_commands) == 2
assert motion_listener.cluster_commands[1][1] == ZONE_STATE
assert motion_listener.cluster_commands[1][2][0] == OFF
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.singleswitch.TuyaSingleSwitch,))
async def test_singleswitch_state_report(zigpy_device_from_quirk, quirk):
"""Test tuya single switch."""
switch_dev = zigpy_device_from_quirk(quirk)
switch_cluster = switch_dev.endpoints[1].on_off
switch_listener = ClusterListener(switch_cluster)
tuya_cluster = switch_dev.endpoints[1].tuya_manufacturer
hdr, args = tuya_cluster.deserialize(ZCL_TUYA_SWITCH_ON)
tuya_cluster.handle_message(hdr, args)
hdr, args = tuya_cluster.deserialize(ZCL_TUYA_SWITCH_OFF)
tuya_cluster.handle_message(hdr, args)
assert len(switch_listener.cluster_commands) == 0
assert len(switch_listener.attribute_updates) == 2
assert switch_listener.attribute_updates[0][0] == 0x0000
assert switch_listener.attribute_updates[0][1] == ON
assert switch_listener.attribute_updates[1][0] == 0x0000
assert switch_listener.attribute_updates[1][1] == OFF
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.singleswitch.TuyaSingleSwitch,))
async def test_singleswitch_requests(zigpy_device_from_quirk, quirk):
"""Test tuya single switch."""
switch_dev = zigpy_device_from_quirk(quirk)
switch_cluster = switch_dev.endpoints[1].on_off
tuya_cluster = switch_dev.endpoints[1].tuya_manufacturer
with mock.patch.object(
tuya_cluster.endpoint, "request", return_value=foundation.Status.SUCCESS
) as m1:
status = switch_cluster.command(0x0000)
m1.assert_called_with(
61184,
1,
b"\x01\x01\x00\x00\x00\x01\x01\x00\x01\x00",
expect_reply=True,
command_id=0,
)
assert status == 0
status = switch_cluster.command(0x0001)
m1.assert_called_with(
61184,
2,
b"\x01\x02\x00\x00\x00\x01\x01\x00\x01\x01",
expect_reply=True,
command_id=0,
)
assert status == 0
status = switch_cluster.command(0x0002)
assert status == foundation.Status.UNSUP_CLUSTER_COMMAND
async def test_tuya_data_conversion():
"""Test tuya conversion from Data to ztype and reverse."""
assert Data([4, 0, 0, 1, 39]).to_value(t.uint32_t) == 295
assert Data([4, 0, 0, 0, 220]).to_value(t.uint32_t) == 220
assert Data([4, 255, 255, 255, 236]).to_value(t.int32s) == -20
assert Data.from_value(t.uint32_t(295)) == [4, 0, 0, 1, 39]
assert Data.from_value(t.uint32_t(220)) == [4, 0, 0, 0, 220]
assert Data.from_value(t.int32s(-20)) == [4, 255, 255, 255, 236]
class TestManufCluster(TuyaManufClusterAttributes):
"""Cluster for synthetic tests."""
manufacturer_attributes = {617: ("test_attribute", t.uint32_t)}
class TestDevice(CustomDevice):
"""Device for synthetic tests."""
signature = {
MODELS_INFO: [("_test_manuf", "_test_device")],
ENDPOINTS: {
1: {
PROFILE_ID: zha.PROFILE_ID,
DEVICE_TYPE: zha.DeviceType.ON_OFF_SWITCH,
INPUT_CLUSTERS: [TestManufCluster.cluster_id],
OUTPUT_CLUSTERS: [],
}
},
}
replacement = {
ENDPOINTS: {
1: {
PROFILE_ID: zha.PROFILE_ID,
DEVICE_TYPE: zha.DeviceType.ON_OFF_SWITCH,
INPUT_CLUSTERS: [TestManufCluster],
OUTPUT_CLUSTERS: [],
}
},
}
@pytest.mark.parametrize("quirk", (TestDevice,))
async def test_tuya_receive_attribute(zigpy_device_from_quirk, quirk):
"""Test conversion of tuya commands to attributes."""
test_dev = zigpy_device_from_quirk(quirk)
tuya_cluster = test_dev.endpoints[1].tuya_manufacturer
listener = ClusterListener(tuya_cluster)
hdr, args = tuya_cluster.deserialize(ZCL_TUYA_ATTRIBUTE_617_TO_179)
tuya_cluster.handle_message(hdr, args)
assert len(listener.attribute_updates) == 1
assert listener.attribute_updates[0][0] == 617
assert listener.attribute_updates[0][1] == 179
@pytest.mark.parametrize("quirk", (TestDevice,))
async def test_tuya_send_attribute(zigpy_device_from_quirk, quirk):
"""Test conversion of attributes to tuya commands."""
test_dev = zigpy_device_from_quirk(quirk)
tuya_cluster = test_dev.endpoints[1].tuya_manufacturer
async def async_success(*args, **kwargs):
return foundation.Status.SUCCESS
with mock.patch.object(
tuya_cluster.endpoint, "request", side_effect=async_success
) as m1:
status = await tuya_cluster.write_attributes({617: 179})
m1.assert_called_with(
61184,
1,
b"\x01\x01\x00\x00\x01i\x02\x00\x04\x00\x00\x00\xb3",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.siren.TuyaSiren,))
async def test_siren_state_report(zigpy_device_from_quirk, quirk):
"""Test tuya siren standard state reporting from incoming commands."""
siren_dev = zigpy_device_from_quirk(quirk)
tuya_cluster = siren_dev.endpoints[1].tuya_manufacturer
temp_listener = ClusterListener(siren_dev.endpoints[1].temperature)
humid_listener = ClusterListener(siren_dev.endpoints[1].humidity)
switch_listener = ClusterListener(siren_dev.endpoints[1].on_off)
frames = (
ZCL_TUYA_SIREN_TEMPERATURE,
ZCL_TUYA_SIREN_HUMIDITY,
ZCL_TUYA_SIREN_ON,
ZCL_TUYA_SIREN_OFF,
)
for frame in frames:
hdr, args = tuya_cluster.deserialize(frame)
tuya_cluster.handle_message(hdr, args)
assert len(temp_listener.cluster_commands) == 0
assert len(temp_listener.attribute_updates) == 1
assert temp_listener.attribute_updates[0][0] == 0x0000
assert temp_listener.attribute_updates[0][1] == 1790
assert len(humid_listener.cluster_commands) == 0
assert len(humid_listener.attribute_updates) == 1
assert humid_listener.attribute_updates[0][0] == 0x0000
assert humid_listener.attribute_updates[0][1] == 8500
assert len(switch_listener.cluster_commands) == 0
assert len(switch_listener.attribute_updates) == 2
assert switch_listener.attribute_updates[0][0] == 0x0000
assert switch_listener.attribute_updates[0][1] == ON
assert switch_listener.attribute_updates[1][0] == 0x0000
assert switch_listener.attribute_updates[1][1] == OFF
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.siren.TuyaSiren,))
async def test_siren_send_attribute(zigpy_device_from_quirk, quirk):
"""Test tuya siren outgoing commands."""
siren_dev = zigpy_device_from_quirk(quirk)
tuya_cluster = siren_dev.endpoints[1].tuya_manufacturer
switch_cluster = siren_dev.endpoints[1].on_off
async def async_success(*args, **kwargs):
return foundation.Status.SUCCESS
with mock.patch.object(
tuya_cluster.endpoint, "request", side_effect=async_success
) as m1:
status = await switch_cluster.command(0x0000)
m1.assert_called_with(
61184,
1,
b"\x01\x01\x00\x00\x01h\x01\x00\x01\x00",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await switch_cluster.command(0x0001)
m1.assert_called_with(
61184,
2,
b"\x01\x02\x00\x00\x02h\x01\x00\x01\x01",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = switch_cluster.command(0x0003)
assert status == foundation.Status.UNSUP_CLUSTER_COMMAND
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.valve.SiterwellGS361_Type1,))
async def test_valve_state_report(zigpy_device_from_quirk, quirk):
"""Test thermostatic valves standard reporting from incoming commands."""
valve_dev = zigpy_device_from_quirk(quirk)
tuya_cluster = valve_dev.endpoints[1].tuya_manufacturer
thermostat_listener = ClusterListener(valve_dev.endpoints[1].thermostat)
frames = (
ZCL_TUYA_VALVE_TEMPERATURE,
ZCL_TUYA_VALVE_TARGET_TEMP,
ZCL_TUYA_VALVE_OFF,
ZCL_TUYA_VALVE_SCHEDULE,
ZCL_TUYA_VALVE_MANUAL,
)
for frame in frames:
hdr, args = tuya_cluster.deserialize(frame)
tuya_cluster.handle_message(hdr, args)
assert len(thermostat_listener.cluster_commands) == 0
assert len(thermostat_listener.attribute_updates) == 13
assert thermostat_listener.attribute_updates[0][0] == 0x0000 # TEMP
assert thermostat_listener.attribute_updates[0][1] == 1790
assert thermostat_listener.attribute_updates[1][0] == 0x0012 # TARGET
assert thermostat_listener.attribute_updates[1][1] == 500
assert thermostat_listener.attribute_updates[2][0] == 0x001C # OFF
assert thermostat_listener.attribute_updates[2][1] == 0x00
assert thermostat_listener.attribute_updates[3][0] == 0x001E
assert thermostat_listener.attribute_updates[3][1] == 0x00
assert thermostat_listener.attribute_updates[4][0] == 0x0029
assert thermostat_listener.attribute_updates[4][1] == 0x00
assert thermostat_listener.attribute_updates[5][0] == 0x001C # SCHEDULE
assert thermostat_listener.attribute_updates[5][1] == 0x04
assert thermostat_listener.attribute_updates[6][0] == 0x0025
assert thermostat_listener.attribute_updates[6][1] == 0x01
assert thermostat_listener.attribute_updates[7][0] == 0x001E
assert thermostat_listener.attribute_updates[7][1] == 0x04
assert thermostat_listener.attribute_updates[8][0] == 0x0029
assert thermostat_listener.attribute_updates[8][1] == 0x01
assert thermostat_listener.attribute_updates[9][0] == 0x001C # MANUAL
assert thermostat_listener.attribute_updates[9][1] == 0x04
assert thermostat_listener.attribute_updates[10][0] == 0x0025
assert thermostat_listener.attribute_updates[10][1] == 0x00
assert thermostat_listener.attribute_updates[11][0] == 0x001E
assert thermostat_listener.attribute_updates[11][1] == 0x04
assert thermostat_listener.attribute_updates[12][0] == 0x0029
assert thermostat_listener.attribute_updates[12][1] == 0x01
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.valve.SiterwellGS361_Type1,))
async def test_valve_send_attribute(zigpy_device_from_quirk, quirk):
"""Test thermostatic valve outgoing commands."""
valve_dev = zigpy_device_from_quirk(quirk)
tuya_cluster = valve_dev.endpoints[1].tuya_manufacturer
thermostat_cluster = valve_dev.endpoints[1].thermostat
async def async_success(*args, **kwargs):
return foundation.Status.SUCCESS
with mock.patch.object(
tuya_cluster.endpoint, "request", side_effect=async_success
) as m1:
status = await thermostat_cluster.write_attributes(
{
"occupied_heating_setpoint": 2500,
}
)
m1.assert_called_with(
61184,
1,
b"\x01\x01\x00\x00\x01\x02\x02\x00\x04\x00\x00\x00\xfa",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"system_mode": 0x00,
}
)
m1.assert_called_with(
61184,
2,
b"\x01\x02\x00\x00\x02\x04\x04\x00\x01\x00",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"system_mode": 0x04,
}
)
m1.assert_called_with(
61184,
3,
b"\x01\x03\x00\x00\x03\x04\x04\x00\x01\x02",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"programing_oper_mode": 0x01,
}
)
m1.assert_called_with(
61184,
4,
b"\x01\x04\x00\x00\x04\x04\x04\x00\x01\x01",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
# simulate a target temp update so that relative changes can work
hdr, args = tuya_cluster.deserialize(ZCL_TUYA_VALVE_TARGET_TEMP)
tuya_cluster.handle_message(hdr, args)
status = await thermostat_cluster.command(0x0000, 0x00, 20)
m1.assert_called_with(
61184,
5,
b"\x01\x05\x00\x00\x05\x02\x02\x00\x04\x00\x00\x00F",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.command(0x0002)
assert status == foundation.Status.UNSUP_CLUSTER_COMMAND
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.valve.MoesHY368_Type1,))
async def test_moes(zigpy_device_from_quirk, quirk):
"""Test thermostatic valve outgoing commands."""
valve_dev = zigpy_device_from_quirk(quirk)
tuya_cluster = valve_dev.endpoints[1].tuya_manufacturer
thermostat_cluster = valve_dev.endpoints[1].thermostat
onoff_cluster = valve_dev.endpoints[1].on_off
thermostat_ui_cluster = valve_dev.endpoints[1].thermostat_ui
thermostat_listener = ClusterListener(valve_dev.endpoints[1].thermostat)
onoff_listener = ClusterListener(valve_dev.endpoints[1].on_off)
frames = (
ZCL_TUYA_VALVE_TEMPERATURE,
ZCL_TUYA_VALVE_WINDOW_DETECTION,
ZCL_TUYA_VALVE_WORKDAY_SCHEDULE,
ZCL_TUYA_VALVE_WEEKEND_SCHEDULE,
ZCL_TUYA_VALVE_OFF,
ZCL_TUYA_VALVE_SCHEDULE,
ZCL_TUYA_VALVE_MANUAL,
ZCL_TUYA_VALVE_COMFORT,
ZCL_TUYA_VALVE_ECO,
ZCL_TUYA_VALVE_BOOST,
ZCL_TUYA_VALVE_COMPLEX,
ZCL_TUYA_VALVE_STATE_50,
)
for frame in frames:
hdr, args = tuya_cluster.deserialize(frame)
tuya_cluster.handle_message(hdr, args)
assert len(thermostat_listener.cluster_commands) == 0
assert len(thermostat_listener.attribute_updates) == 61
assert thermostat_listener.attribute_updates[0][0] == 0x0000
assert thermostat_listener.attribute_updates[0][1] == 1790
assert thermostat_listener.attribute_updates[1][0] == 0x4110
assert thermostat_listener.attribute_updates[1][1] == 6
assert thermostat_listener.attribute_updates[2][0] == 0x4111
assert thermostat_listener.attribute_updates[2][1] == 0
assert thermostat_listener.attribute_updates[3][0] == 0x4112
assert thermostat_listener.attribute_updates[3][1] == 2000
assert thermostat_listener.attribute_updates[4][0] == 0x4120
assert thermostat_listener.attribute_updates[4][1] == 8
assert thermostat_listener.attribute_updates[5][0] == 0x4121
assert thermostat_listener.attribute_updates[5][1] == 0
assert thermostat_listener.attribute_updates[6][0] == 0x4122
assert thermostat_listener.attribute_updates[6][1] == 1500
assert thermostat_listener.attribute_updates[7][0] == 0x4130
assert thermostat_listener.attribute_updates[7][1] == 11
assert thermostat_listener.attribute_updates[8][0] == 0x4131
assert thermostat_listener.attribute_updates[8][1] == 30
assert thermostat_listener.attribute_updates[9][0] == 0x4132
assert thermostat_listener.attribute_updates[9][1] == 1500
assert thermostat_listener.attribute_updates[10][0] == 0x4140
assert thermostat_listener.attribute_updates[10][1] == 12
assert thermostat_listener.attribute_updates[11][0] == 0x4141
assert thermostat_listener.attribute_updates[11][1] == 30
assert thermostat_listener.attribute_updates[12][0] == 0x4142
assert thermostat_listener.attribute_updates[12][1] == 1500
assert thermostat_listener.attribute_updates[13][0] == 0x4150
assert thermostat_listener.attribute_updates[13][1] == 17
assert thermostat_listener.attribute_updates[14][0] == 0x4151
assert thermostat_listener.attribute_updates[14][1] == 30
assert thermostat_listener.attribute_updates[15][0] == 0x4152
assert thermostat_listener.attribute_updates[15][1] == 2000
assert thermostat_listener.attribute_updates[16][0] == 0x4160
assert thermostat_listener.attribute_updates[16][1] == 22
assert thermostat_listener.attribute_updates[17][0] == 0x4161
assert thermostat_listener.attribute_updates[17][1] == 0
assert thermostat_listener.attribute_updates[18][0] == 0x4162
assert thermostat_listener.attribute_updates[18][1] == 1500
assert thermostat_listener.attribute_updates[19][0] == 0x4210
assert thermostat_listener.attribute_updates[19][1] == 6
assert thermostat_listener.attribute_updates[20][0] == 0x4211
assert thermostat_listener.attribute_updates[20][1] == 0
assert thermostat_listener.attribute_updates[21][0] == 0x4212
assert thermostat_listener.attribute_updates[21][1] == 2000
assert thermostat_listener.attribute_updates[22][0] == 0x4220
assert thermostat_listener.attribute_updates[22][1] == 8
assert thermostat_listener.attribute_updates[23][0] == 0x4221
assert thermostat_listener.attribute_updates[23][1] == 0
assert thermostat_listener.attribute_updates[24][0] == 0x4222
assert thermostat_listener.attribute_updates[24][1] == 1500
assert thermostat_listener.attribute_updates[25][0] == 0x4230
assert thermostat_listener.attribute_updates[25][1] == 11
assert thermostat_listener.attribute_updates[26][0] == 0x4231
assert thermostat_listener.attribute_updates[26][1] == 30
assert thermostat_listener.attribute_updates[27][0] == 0x4232
assert thermostat_listener.attribute_updates[27][1] == 1500
assert thermostat_listener.attribute_updates[28][0] == 0x4240
assert thermostat_listener.attribute_updates[28][1] == 12
assert thermostat_listener.attribute_updates[29][0] == 0x4241
assert thermostat_listener.attribute_updates[29][1] == 30
assert thermostat_listener.attribute_updates[30][0] == 0x4242
assert thermostat_listener.attribute_updates[30][1] == 1500
assert thermostat_listener.attribute_updates[31][0] == 0x4250
assert thermostat_listener.attribute_updates[31][1] == 17
assert thermostat_listener.attribute_updates[32][0] == 0x4251
assert thermostat_listener.attribute_updates[32][1] == 30
assert thermostat_listener.attribute_updates[33][0] == 0x4252
assert thermostat_listener.attribute_updates[33][1] == 2000
assert thermostat_listener.attribute_updates[34][0] == 0x4260
assert thermostat_listener.attribute_updates[34][1] == 22
assert thermostat_listener.attribute_updates[35][0] == 0x4261
assert thermostat_listener.attribute_updates[35][1] == 0
assert thermostat_listener.attribute_updates[36][0] == 0x4262
assert thermostat_listener.attribute_updates[36][1] == 1500
assert thermostat_listener.attribute_updates[37][0] == 0x4002
assert thermostat_listener.attribute_updates[37][1] == 0
assert thermostat_listener.attribute_updates[38][0] == 0x0025
assert thermostat_listener.attribute_updates[38][1] == 0
assert thermostat_listener.attribute_updates[39][0] == 0x0002
assert thermostat_listener.attribute_updates[39][1] == 0
assert thermostat_listener.attribute_updates[40][0] == 0x4002
assert thermostat_listener.attribute_updates[40][1] == 1
assert thermostat_listener.attribute_updates[41][0] == 0x0025
assert thermostat_listener.attribute_updates[41][1] == 1
assert thermostat_listener.attribute_updates[42][0] == 0x0002
assert thermostat_listener.attribute_updates[42][1] == 1
assert thermostat_listener.attribute_updates[43][0] == 0x4002
assert thermostat_listener.attribute_updates[43][1] == 2
assert thermostat_listener.attribute_updates[44][0] == 0x0025
assert thermostat_listener.attribute_updates[44][1] == 0
assert thermostat_listener.attribute_updates[45][0] == 0x0002
assert thermostat_listener.attribute_updates[45][1] == 1
assert thermostat_listener.attribute_updates[46][0] == 0x4002
assert thermostat_listener.attribute_updates[46][1] == 3
assert thermostat_listener.attribute_updates[47][0] == 0x0025
assert thermostat_listener.attribute_updates[47][1] == 0
assert thermostat_listener.attribute_updates[48][0] == 0x0002
assert thermostat_listener.attribute_updates[48][1] == 1
assert thermostat_listener.attribute_updates[49][0] == 0x4002
assert thermostat_listener.attribute_updates[49][1] == 4
assert thermostat_listener.attribute_updates[50][0] == 0x0025
assert thermostat_listener.attribute_updates[50][1] == 4
assert thermostat_listener.attribute_updates[51][0] == 0x0002
assert thermostat_listener.attribute_updates[51][1] == 1
assert thermostat_listener.attribute_updates[52][0] == 0x4002
assert thermostat_listener.attribute_updates[52][1] == 5
assert thermostat_listener.attribute_updates[53][0] == 0x0025
assert thermostat_listener.attribute_updates[53][1] == 0
assert thermostat_listener.attribute_updates[54][0] == 0x0002
assert thermostat_listener.attribute_updates[54][1] == 1
assert thermostat_listener.attribute_updates[55][0] == 0x4002
assert thermostat_listener.attribute_updates[55][1] == 6
assert thermostat_listener.attribute_updates[56][0] == 0x0025
assert thermostat_listener.attribute_updates[56][1] == 0
assert thermostat_listener.attribute_updates[57][0] == 0x0002
assert thermostat_listener.attribute_updates[57][1] == 1
assert thermostat_listener.attribute_updates[58][0] == 0x4004
assert thermostat_listener.attribute_updates[58][1] == 50
assert thermostat_listener.attribute_updates[59][0] == 0x001E
assert thermostat_listener.attribute_updates[59][1] == 4
assert thermostat_listener.attribute_updates[60][0] == 0x0029
assert thermostat_listener.attribute_updates[60][1] == 1
assert len(onoff_listener.cluster_commands) == 0
assert len(onoff_listener.attribute_updates) == 3
assert onoff_listener.attribute_updates[0][0] == 0x6001
assert onoff_listener.attribute_updates[0][1] == 5
assert onoff_listener.attribute_updates[1][0] == 0x6000
assert onoff_listener.attribute_updates[1][1] == 1600
assert onoff_listener.attribute_updates[2][0] == 0x0000 # TARGET
assert onoff_listener.attribute_updates[2][1] == 1
thermostat_ui_listener = ClusterListener(valve_dev.endpoints[1].thermostat_ui)
power_listener = ClusterListener(valve_dev.endpoints[1].power)
frames = (
ZCL_TUYA_VALVE_CHILD_LOCK_ON,
ZCL_TUYA_VALVE_AUTO_LOCK_ON,
ZCL_TUYA_VALVE_BATTERY_LOW,
)
for frame in frames:
hdr, args = tuya_cluster.deserialize(frame)
tuya_cluster.handle_message(hdr, args)
assert len(thermostat_ui_listener.cluster_commands) == 0
assert len(thermostat_ui_listener.attribute_updates) == 2
assert thermostat_ui_listener.attribute_updates[0][0] == 0x0001
assert thermostat_ui_listener.attribute_updates[0][1] == 1
assert thermostat_ui_listener.attribute_updates[1][0] == 0x5000
assert thermostat_ui_listener.attribute_updates[1][1] == 1
assert len(power_listener.cluster_commands) == 0
assert len(power_listener.attribute_updates) == 1
assert power_listener.attribute_updates[0][0] == 0x0021
assert power_listener.attribute_updates[0][1] == 10
async def async_success(*args, **kwargs):
return foundation.Status.SUCCESS
with mock.patch.object(
tuya_cluster.endpoint, "request", side_effect=async_success
) as m1:
status = await thermostat_cluster.write_attributes(
{
"occupied_heating_setpoint": 2500,
}
)
m1.assert_called_with(
61184,
1,
b"\x01\x01\x00\x00\x01\x02\x02\x00\x04\x00\x00\x00\xfa",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"operation_preset": 0x00,
}
)
m1.assert_called_with(
61184,
2,
b"\x01\x02\x00\x00\x02\x04\x04\x00\x01\x00",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"operation_preset": 0x02,
}
)
m1.assert_called_with(
61184,
3,
b"\x01\x03\x00\x00\x03\x04\x04\x00\x01\x02",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
# simulate a target temp update so that relative changes can work
hdr, args = tuya_cluster.deserialize(ZCL_TUYA_VALVE_TARGET_TEMP)
tuya_cluster.handle_message(hdr, args)
status = await thermostat_cluster.command(0x0000, 0x00, 20)
m1.assert_called_with(
61184,
4,
b"\x01\x04\x00\x00\x04\x02\x02\x00\x04\x00\x00\x00F",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await onoff_cluster.write_attributes(
{
"on_off": 0x00,
"window_detection_timeout_minutes": 0x02,
"window_detection_temperature": 2000,
}
)
m1.assert_called_with(
61184,
5,
b"\x01\x05\x00\x00\x05\x68\x00\x00\x03\x00\x14\x02",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"occupancy": 0x00,
}
)
m1.assert_called_with(
61184,
6,
b"\x01\x06\x00\x00\x06\x04\x04\x00\x01\x00",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"occupancy": 0x01,
"programing_oper_mode": 0x00,
}
)
m1.assert_called_with(
61184,
7,
b"\x01\x07\x00\x00\x07\x04\x04\x00\x01\x02",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"programing_oper_mode": 0x01,
}
)
m1.assert_called_with(
61184,
8,
b"\x01\x08\x00\x00\x08\x04\x04\x00\x01\x01",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"programing_oper_mode": 0x04,
}
)
m1.assert_called_with(
61184,
9,
b"\x01\x09\x00\x00\x09\x04\x04\x00\x01\x04",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"workday_schedule_1_temperature": 1700,
}
)
m1.assert_called_with(
61184,
10,
b"\x01\x0A\x00\x00\x0A\x70\x00\x00\x12\x06\x00\x11\x08\x00\x0F\x0B\x1E\x0F\x0C\x1E\x0F\x11\x1E\x14\x16\x00\x0F",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"workday_schedule_1_minute": 45,
}
)
m1.assert_called_with(
61184,
11,
b"\x01\x0B\x00\x00\x0B\x70\x00\x00\x12\x06\x2D\x14\x08\x00\x0F\x0B\x1E\x0F\x0C\x1E\x0F\x11\x1E\x14\x16\x00\x0F",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"workday_schedule_1_hour": 5,
}
)
m1.assert_called_with(
61184,
12,
b"\x01\x0C\x00\x00\x0C\x70\x00\x00\x12\x05\x00\x14\x08\x00\x0F\x0B\x1E\x0F\x0C\x1E\x0F\x11\x1E\x14\x16\x00\x0F",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"weekend_schedule_1_temperature": 1700,
}
)
m1.assert_called_with(
61184,
13,
b"\x01\x0D\x00\x00\x0D\x71\x00\x00\x12\x06\x00\x11\x08\x00\x0F\x0B\x1E\x0F\x0C\x1E\x0F\x11\x1E\x14\x16\x00\x0F",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"weekend_schedule_1_minute": 45,
}
)
m1.assert_called_with(
61184,
14,
b"\x01\x0E\x00\x00\x0E\x71\x00\x00\x12\x06\x2D\x14\x08\x00\x0F\x0B\x1E\x0F\x0C\x1E\x0F\x11\x1E\x14\x16\x00\x0F",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"weekend_schedule_1_hour": 5,
}
)
m1.assert_called_with(
61184,
15,
b"\x01\x0F\x00\x00\x0F\x71\x00\x00\x12\x05\x00\x14\x08\x00\x0F\x0B\x1E\x0F\x0C\x1E\x0F\x11\x1E\x14\x16\x00\x0F",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"system_mode": 0x01,
}
)
m1.assert_called_with(
61184,
16,
b"\x01\x10\x00\x00\x10\x04\x04\x00\x01\x06",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_ui_cluster.write_attributes(
{
"auto_lock": 0x00,
}
)
m1.assert_called_with(
61184,
17,
b"\x01\x11\x00\x00\x11\x74\x01\x00\x01\x00",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await onoff_cluster.command(0x0000)
m1.assert_called_with(
61184,
18,
b"\x01\x12\x00\x00\x12\x68\x00\x00\x03\x00\x10\x05",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await onoff_cluster.command(0x0001)
m1.assert_called_with(
61184,
19,
b"\x01\x13\x00\x00\x13\x68\x00\x00\x03\x01\x10\x05",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await onoff_cluster.command(0x0002)
m1.assert_called_with(
61184,
20,
b"\x01\x14\x00\x00\x14\x68\x00\x00\x03\x00\x10\x05",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await onoff_cluster.write_attributes({})
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.command(0x0002)
assert status == foundation.Status.UNSUP_CLUSTER_COMMAND
status = await onoff_cluster.command(0x0009)
assert status == foundation.Status.UNSUP_CLUSTER_COMMAND
origdatetime = datetime.datetime
datetime.datetime = NewDatetime
hdr, args = tuya_cluster.deserialize(ZCL_TUYA_SET_TIME_REQUEST)
tuya_cluster.handle_message(hdr, args)
m1.assert_called_with(
61184,
21,
b"\x01\x15\x24\x00\x08\x00\x00\x1C\x20\x00\x00\x0E\x10",
expect_reply=False,
command_id=0x0024,
)
datetime.datetime = origdatetime
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.electric_heating.MoesBHT,))
async def test_eheating_state_report(zigpy_device_from_quirk, quirk):
"""Test thermostatic valves standard reporting from incoming commands."""
electric_dev = zigpy_device_from_quirk(quirk)
tuya_cluster = electric_dev.endpoints[1].tuya_manufacturer
thermostat_listener = ClusterListener(electric_dev.endpoints[1].thermostat)
frames = (ZCL_TUYA_EHEAT_TEMPERATURE, ZCL_TUYA_EHEAT_TARGET_TEMP)
for frame in frames:
hdr, args = tuya_cluster.deserialize(frame)
tuya_cluster.handle_message(hdr, args)
assert len(thermostat_listener.cluster_commands) == 0
assert len(thermostat_listener.attribute_updates) == 2
assert thermostat_listener.attribute_updates[0][0] == 0x0000 # TEMP
assert thermostat_listener.attribute_updates[0][1] == 1790
assert thermostat_listener.attribute_updates[1][0] == 0x0012 # TARGET
assert thermostat_listener.attribute_updates[1][1] == 2100
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.electric_heating.MoesBHT,))
async def test_eheat_send_attribute(zigpy_device_from_quirk, quirk):
"""Test electric thermostat outgoing commands."""
eheat_dev = zigpy_device_from_quirk(quirk)
tuya_cluster = eheat_dev.endpoints[1].tuya_manufacturer
thermostat_cluster = eheat_dev.endpoints[1].thermostat
async def async_success(*args, **kwargs):
return foundation.Status.SUCCESS
with mock.patch.object(
tuya_cluster.endpoint, "request", side_effect=async_success
) as m1:
status = await thermostat_cluster.write_attributes(
{
"occupied_heating_setpoint": 2500,
}
)
m1.assert_called_with(
61184,
1,
b"\x01\x01\x00\x00\x01\x10\x02\x00\x04\x00\x00\x00\x19",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"system_mode": 0x00,
}
)
m1.assert_called_with(
61184,
2,
b"\x01\x02\x00\x00\x02\x01\x01\x00\x01\x00",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"system_mode": 0x04,
}
)
m1.assert_called_with(
61184,
3,
b"\x01\x03\x00\x00\x03\x01\x01\x00\x01\x01",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
# simulate a target temp update so that relative changes can work
hdr, args = tuya_cluster.deserialize(ZCL_TUYA_EHEAT_TARGET_TEMP)
tuya_cluster.handle_message(hdr, args)
status = await thermostat_cluster.command(0x0000, 0x00, 20)
m1.assert_called_with(
61184,
4,
b"\x01\x04\x00\x00\x04\x10\x02\x00\x04\x00\x00\x00\x17",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.command(0x0002)
assert status == foundation.Status.UNSUP_CLUSTER_COMMAND
@pytest.mark.parametrize(
"quirk, manufacturer",
(
(zhaquirks.tuya.ts0042.TuyaSmartRemote0042, "_TZ3000_owgcnkrh"),
(zhaquirks.tuya.ts0042.TuyaSmartRemote0042, "_TZ3400_keyjhapk"),
(zhaquirks.tuya.ts0042.TuyaSmartRemote0042, "_some_random_manuf"),
(zhaquirks.tuya.ts0042.BenexmartRemote0042, "_TZ3000_adkvzooy"),
(zhaquirks.tuya.ts0042.BenexmartRemote0042, "_TZ3400_keyjhapk"),
(zhaquirks.tuya.ts0042.BenexmartRemote0042, "another random manufacturer"),
(zhaquirks.tuya.ts0043.TuyaSmartRemote0043, "_TZ3000_bi6lpsew"),
(zhaquirks.tuya.ts0043.TuyaSmartRemote0043, "_TZ3000_a7ouggvs"),
(zhaquirks.tuya.ts0043.TuyaSmartRemote0043, "another random manufacturer"),
(zhaquirks.tuya.ts0043.BenexmartRemote0043, "_TZ3000_qzjcsmar"),
(zhaquirks.tuya.ts0043.BenexmartRemote0043, "another random manufacturer"),
),
)
async def test_tuya_wildcard_manufacturer(zigpy_device_from_quirk, quirk, manufacturer):
"""Test thermostatic valve outgoing commands."""
zigpy_dev = zigpy_device_from_quirk(quirk, apply_quirk=False)
zigpy_dev.manufacturer = manufacturer
quirked_dev = get_device(zigpy_dev)
assert isinstance(quirked_dev, quirk)
| 38.377778 | 140 | 0.6692 |
import asyncio
import datetime
from unittest import mock
import pytest
from zigpy.profiles import zha
from zigpy.quirks import CustomDevice, get_device
import zigpy.types as t
from zigpy.zcl import foundation
from zhaquirks.const import (
DEVICE_TYPE,
ENDPOINTS,
INPUT_CLUSTERS,
MODELS_INFO,
OFF,
ON,
OUTPUT_CLUSTERS,
PROFILE_ID,
ZONE_STATE,
)
from zhaquirks.tuya import Data, TuyaManufClusterAttributes
import zhaquirks.tuya.electric_heating
import zhaquirks.tuya.motion
import zhaquirks.tuya.siren
import zhaquirks.tuya.ts0042
import zhaquirks.tuya.ts0043
import zhaquirks.tuya.valve
from tests.common import ClusterListener
ZCL_TUYA_SET_TIME_REQUEST = b"\tp\x24\x00\00"
ZCL_TUYA_MOTION = b"\tL\x01\x00\x05\x03\x04\x00\x01\x02"
ZCL_TUYA_SWITCH_ON = b"\tQ\x02\x006\x01\x01\x00\x01\x01"
ZCL_TUYA_SWITCH_OFF = b"\tQ\x02\x006\x01\x01\x00\x01\x00"
ZCL_TUYA_ATTRIBUTE_617_TO_179 = b"\tp\x02\x00\x02i\x02\x00\x04\x00\x00\x00\xb3"
ZCL_TUYA_SIREN_TEMPERATURE = ZCL_TUYA_ATTRIBUTE_617_TO_179
ZCL_TUYA_SIREN_HUMIDITY = b"\tp\x02\x00\x02j\x02\x00\x04\x00\x00\x00U"
ZCL_TUYA_SIREN_ON = b"\t\t\x02\x00\x04h\x01\x00\x01\x01"
ZCL_TUYA_SIREN_OFF = b"\t\t\x02\x00\x04h\x01\x00\x01\x00"
ZCL_TUYA_VALVE_TEMPERATURE = b"\tp\x02\x00\x02\x03\x02\x00\x04\x00\x00\x00\xb3"
ZCL_TUYA_VALVE_TARGET_TEMP = b"\t3\x01\x03\x05\x02\x02\x00\x04\x00\x00\x002"
ZCL_TUYA_VALVE_OFF = b"\t2\x01\x03\x04\x04\x04\x00\x01\x00"
ZCL_TUYA_VALVE_SCHEDULE = b"\t2\x01\x03\x04\x04\x04\x00\x01\x01"
ZCL_TUYA_VALVE_MANUAL = b"\t2\x01\x03\x04\x04\x04\x00\x01\x02"
ZCL_TUYA_VALVE_COMFORT = b"\t2\x01\x03\x04\x04\x04\x00\x01\x03"
ZCL_TUYA_VALVE_ECO = b"\t2\x01\x03\x04\x04\x04\x00\x01\x04"
ZCL_TUYA_VALVE_BOOST = b"\t2\x01\x03\x04\x04\x04\x00\x01\x05"
ZCL_TUYA_VALVE_COMPLEX = b"\t2\x01\x03\x04\x04\x04\x00\x01\x06"
ZCL_TUYA_VALVE_WINDOW_DETECTION = b"\tp\x02\x00\x02\x68\x00\x00\x03\x01\x10\x05"
ZCL_TUYA_VALVE_WORKDAY_SCHEDULE = b"\tp\x02\x00\x02\x70\x00\x00\x12\x06\x00\x14\x08\x00\x0F\x0B\x1E\x0F\x0C\x1E\x0F\x11\x1E\x14\x16\x00\x0F"
ZCL_TUYA_VALVE_WEEKEND_SCHEDULE = b"\tp\x02\x00\x02\x71\x00\x00\x12\x06\x00\x14\x08\x00\x0F\x0B\x1E\x0F\x0C\x1E\x0F\x11\x1E\x14\x16\x00\x0F"
ZCL_TUYA_VALVE_STATE_50 = b"\t2\x01\x03\x04\x6D\x02\x00\x04\x00\x00\x00\x32"
ZCL_TUYA_VALVE_CHILD_LOCK_ON = b"\t2\x01\x03\x04\x07\x01\x00\x01\x01"
ZCL_TUYA_VALVE_AUTO_LOCK_ON = b"\t2\x01\x03\x04\x74\x01\x00\x01\x01"
ZCL_TUYA_VALVE_BATTERY_LOW = b"\t2\x01\x03\x04\x6E\x01\x00\x01\x01"
ZCL_TUYA_EHEAT_TEMPERATURE = b"\tp\x02\x00\x02\x18\x02\x00\x04\x00\x00\x00\xb3"
ZCL_TUYA_EHEAT_TARGET_TEMP = b"\t3\x01\x03\x05\x10\x02\x00\x04\x00\x00\x00\x15"
class NewDatetime(datetime.datetime):
@classmethod
def now(cls):
return cls(1970, 1, 1, 1, 0, 0)
@classmethod
def utcnow(cls):
return cls(1970, 1, 1, 2, 0, 0)
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.motion.TuyaMotion,))
async def test_motion(zigpy_device_from_quirk, quirk):
motion_dev = zigpy_device_from_quirk(quirk)
motion_cluster = motion_dev.endpoints[1].ias_zone
motion_listener = ClusterListener(motion_cluster)
tuya_cluster = motion_dev.endpoints[1].tuya_manufacturer
hdr, args = tuya_cluster.deserialize(ZCL_TUYA_MOTION)
with mock.patch.object(motion_cluster, "reset_s", 0):
tuya_cluster.handle_message(hdr, args)
assert len(motion_listener.cluster_commands) == 1
assert len(motion_listener.attribute_updates) == 1
assert motion_listener.cluster_commands[0][1] == ZONE_STATE
assert motion_listener.cluster_commands[0][2][0] == ON
await asyncio.gather(asyncio.sleep(0), asyncio.sleep(0), asyncio.sleep(0))
assert len(motion_listener.cluster_commands) == 2
assert motion_listener.cluster_commands[1][1] == ZONE_STATE
assert motion_listener.cluster_commands[1][2][0] == OFF
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.singleswitch.TuyaSingleSwitch,))
async def test_singleswitch_state_report(zigpy_device_from_quirk, quirk):
switch_dev = zigpy_device_from_quirk(quirk)
switch_cluster = switch_dev.endpoints[1].on_off
switch_listener = ClusterListener(switch_cluster)
tuya_cluster = switch_dev.endpoints[1].tuya_manufacturer
hdr, args = tuya_cluster.deserialize(ZCL_TUYA_SWITCH_ON)
tuya_cluster.handle_message(hdr, args)
hdr, args = tuya_cluster.deserialize(ZCL_TUYA_SWITCH_OFF)
tuya_cluster.handle_message(hdr, args)
assert len(switch_listener.cluster_commands) == 0
assert len(switch_listener.attribute_updates) == 2
assert switch_listener.attribute_updates[0][0] == 0x0000
assert switch_listener.attribute_updates[0][1] == ON
assert switch_listener.attribute_updates[1][0] == 0x0000
assert switch_listener.attribute_updates[1][1] == OFF
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.singleswitch.TuyaSingleSwitch,))
async def test_singleswitch_requests(zigpy_device_from_quirk, quirk):
switch_dev = zigpy_device_from_quirk(quirk)
switch_cluster = switch_dev.endpoints[1].on_off
tuya_cluster = switch_dev.endpoints[1].tuya_manufacturer
with mock.patch.object(
tuya_cluster.endpoint, "request", return_value=foundation.Status.SUCCESS
) as m1:
status = switch_cluster.command(0x0000)
m1.assert_called_with(
61184,
1,
b"\x01\x01\x00\x00\x00\x01\x01\x00\x01\x00",
expect_reply=True,
command_id=0,
)
assert status == 0
status = switch_cluster.command(0x0001)
m1.assert_called_with(
61184,
2,
b"\x01\x02\x00\x00\x00\x01\x01\x00\x01\x01",
expect_reply=True,
command_id=0,
)
assert status == 0
status = switch_cluster.command(0x0002)
assert status == foundation.Status.UNSUP_CLUSTER_COMMAND
async def test_tuya_data_conversion():
assert Data([4, 0, 0, 1, 39]).to_value(t.uint32_t) == 295
assert Data([4, 0, 0, 0, 220]).to_value(t.uint32_t) == 220
assert Data([4, 255, 255, 255, 236]).to_value(t.int32s) == -20
assert Data.from_value(t.uint32_t(295)) == [4, 0, 0, 1, 39]
assert Data.from_value(t.uint32_t(220)) == [4, 0, 0, 0, 220]
assert Data.from_value(t.int32s(-20)) == [4, 255, 255, 255, 236]
class TestManufCluster(TuyaManufClusterAttributes):
manufacturer_attributes = {617: ("test_attribute", t.uint32_t)}
class TestDevice(CustomDevice):
signature = {
MODELS_INFO: [("_test_manuf", "_test_device")],
ENDPOINTS: {
1: {
PROFILE_ID: zha.PROFILE_ID,
DEVICE_TYPE: zha.DeviceType.ON_OFF_SWITCH,
INPUT_CLUSTERS: [TestManufCluster.cluster_id],
OUTPUT_CLUSTERS: [],
}
},
}
replacement = {
ENDPOINTS: {
1: {
PROFILE_ID: zha.PROFILE_ID,
DEVICE_TYPE: zha.DeviceType.ON_OFF_SWITCH,
INPUT_CLUSTERS: [TestManufCluster],
OUTPUT_CLUSTERS: [],
}
},
}
@pytest.mark.parametrize("quirk", (TestDevice,))
async def test_tuya_receive_attribute(zigpy_device_from_quirk, quirk):
test_dev = zigpy_device_from_quirk(quirk)
tuya_cluster = test_dev.endpoints[1].tuya_manufacturer
listener = ClusterListener(tuya_cluster)
hdr, args = tuya_cluster.deserialize(ZCL_TUYA_ATTRIBUTE_617_TO_179)
tuya_cluster.handle_message(hdr, args)
assert len(listener.attribute_updates) == 1
assert listener.attribute_updates[0][0] == 617
assert listener.attribute_updates[0][1] == 179
@pytest.mark.parametrize("quirk", (TestDevice,))
async def test_tuya_send_attribute(zigpy_device_from_quirk, quirk):
test_dev = zigpy_device_from_quirk(quirk)
tuya_cluster = test_dev.endpoints[1].tuya_manufacturer
async def async_success(*args, **kwargs):
return foundation.Status.SUCCESS
with mock.patch.object(
tuya_cluster.endpoint, "request", side_effect=async_success
) as m1:
status = await tuya_cluster.write_attributes({617: 179})
m1.assert_called_with(
61184,
1,
b"\x01\x01\x00\x00\x01i\x02\x00\x04\x00\x00\x00\xb3",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.siren.TuyaSiren,))
async def test_siren_state_report(zigpy_device_from_quirk, quirk):
siren_dev = zigpy_device_from_quirk(quirk)
tuya_cluster = siren_dev.endpoints[1].tuya_manufacturer
temp_listener = ClusterListener(siren_dev.endpoints[1].temperature)
humid_listener = ClusterListener(siren_dev.endpoints[1].humidity)
switch_listener = ClusterListener(siren_dev.endpoints[1].on_off)
frames = (
ZCL_TUYA_SIREN_TEMPERATURE,
ZCL_TUYA_SIREN_HUMIDITY,
ZCL_TUYA_SIREN_ON,
ZCL_TUYA_SIREN_OFF,
)
for frame in frames:
hdr, args = tuya_cluster.deserialize(frame)
tuya_cluster.handle_message(hdr, args)
assert len(temp_listener.cluster_commands) == 0
assert len(temp_listener.attribute_updates) == 1
assert temp_listener.attribute_updates[0][0] == 0x0000
assert temp_listener.attribute_updates[0][1] == 1790
assert len(humid_listener.cluster_commands) == 0
assert len(humid_listener.attribute_updates) == 1
assert humid_listener.attribute_updates[0][0] == 0x0000
assert humid_listener.attribute_updates[0][1] == 8500
assert len(switch_listener.cluster_commands) == 0
assert len(switch_listener.attribute_updates) == 2
assert switch_listener.attribute_updates[0][0] == 0x0000
assert switch_listener.attribute_updates[0][1] == ON
assert switch_listener.attribute_updates[1][0] == 0x0000
assert switch_listener.attribute_updates[1][1] == OFF
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.siren.TuyaSiren,))
async def test_siren_send_attribute(zigpy_device_from_quirk, quirk):
siren_dev = zigpy_device_from_quirk(quirk)
tuya_cluster = siren_dev.endpoints[1].tuya_manufacturer
switch_cluster = siren_dev.endpoints[1].on_off
async def async_success(*args, **kwargs):
return foundation.Status.SUCCESS
with mock.patch.object(
tuya_cluster.endpoint, "request", side_effect=async_success
) as m1:
status = await switch_cluster.command(0x0000)
m1.assert_called_with(
61184,
1,
b"\x01\x01\x00\x00\x01h\x01\x00\x01\x00",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await switch_cluster.command(0x0001)
m1.assert_called_with(
61184,
2,
b"\x01\x02\x00\x00\x02h\x01\x00\x01\x01",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = switch_cluster.command(0x0003)
assert status == foundation.Status.UNSUP_CLUSTER_COMMAND
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.valve.SiterwellGS361_Type1,))
async def test_valve_state_report(zigpy_device_from_quirk, quirk):
valve_dev = zigpy_device_from_quirk(quirk)
tuya_cluster = valve_dev.endpoints[1].tuya_manufacturer
thermostat_listener = ClusterListener(valve_dev.endpoints[1].thermostat)
frames = (
ZCL_TUYA_VALVE_TEMPERATURE,
ZCL_TUYA_VALVE_TARGET_TEMP,
ZCL_TUYA_VALVE_OFF,
ZCL_TUYA_VALVE_SCHEDULE,
ZCL_TUYA_VALVE_MANUAL,
)
for frame in frames:
hdr, args = tuya_cluster.deserialize(frame)
tuya_cluster.handle_message(hdr, args)
assert len(thermostat_listener.cluster_commands) == 0
assert len(thermostat_listener.attribute_updates) == 13
assert thermostat_listener.attribute_updates[0][0] == 0x0000
assert thermostat_listener.attribute_updates[0][1] == 1790
assert thermostat_listener.attribute_updates[1][0] == 0x0012
assert thermostat_listener.attribute_updates[1][1] == 500
assert thermostat_listener.attribute_updates[2][0] == 0x001C
assert thermostat_listener.attribute_updates[2][1] == 0x00
assert thermostat_listener.attribute_updates[3][0] == 0x001E
assert thermostat_listener.attribute_updates[3][1] == 0x00
assert thermostat_listener.attribute_updates[4][0] == 0x0029
assert thermostat_listener.attribute_updates[4][1] == 0x00
assert thermostat_listener.attribute_updates[5][0] == 0x001C
assert thermostat_listener.attribute_updates[5][1] == 0x04
assert thermostat_listener.attribute_updates[6][0] == 0x0025
assert thermostat_listener.attribute_updates[6][1] == 0x01
assert thermostat_listener.attribute_updates[7][0] == 0x001E
assert thermostat_listener.attribute_updates[7][1] == 0x04
assert thermostat_listener.attribute_updates[8][0] == 0x0029
assert thermostat_listener.attribute_updates[8][1] == 0x01
assert thermostat_listener.attribute_updates[9][0] == 0x001C
assert thermostat_listener.attribute_updates[9][1] == 0x04
assert thermostat_listener.attribute_updates[10][0] == 0x0025
assert thermostat_listener.attribute_updates[10][1] == 0x00
assert thermostat_listener.attribute_updates[11][0] == 0x001E
assert thermostat_listener.attribute_updates[11][1] == 0x04
assert thermostat_listener.attribute_updates[12][0] == 0x0029
assert thermostat_listener.attribute_updates[12][1] == 0x01
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.valve.SiterwellGS361_Type1,))
async def test_valve_send_attribute(zigpy_device_from_quirk, quirk):
valve_dev = zigpy_device_from_quirk(quirk)
tuya_cluster = valve_dev.endpoints[1].tuya_manufacturer
thermostat_cluster = valve_dev.endpoints[1].thermostat
async def async_success(*args, **kwargs):
return foundation.Status.SUCCESS
with mock.patch.object(
tuya_cluster.endpoint, "request", side_effect=async_success
) as m1:
status = await thermostat_cluster.write_attributes(
{
"occupied_heating_setpoint": 2500,
}
)
m1.assert_called_with(
61184,
1,
b"\x01\x01\x00\x00\x01\x02\x02\x00\x04\x00\x00\x00\xfa",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"system_mode": 0x00,
}
)
m1.assert_called_with(
61184,
2,
b"\x01\x02\x00\x00\x02\x04\x04\x00\x01\x00",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"system_mode": 0x04,
}
)
m1.assert_called_with(
61184,
3,
b"\x01\x03\x00\x00\x03\x04\x04\x00\x01\x02",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"programing_oper_mode": 0x01,
}
)
m1.assert_called_with(
61184,
4,
b"\x01\x04\x00\x00\x04\x04\x04\x00\x01\x01",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
hdr, args = tuya_cluster.deserialize(ZCL_TUYA_VALVE_TARGET_TEMP)
tuya_cluster.handle_message(hdr, args)
status = await thermostat_cluster.command(0x0000, 0x00, 20)
m1.assert_called_with(
61184,
5,
b"\x01\x05\x00\x00\x05\x02\x02\x00\x04\x00\x00\x00F",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.command(0x0002)
assert status == foundation.Status.UNSUP_CLUSTER_COMMAND
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.valve.MoesHY368_Type1,))
async def test_moes(zigpy_device_from_quirk, quirk):
valve_dev = zigpy_device_from_quirk(quirk)
tuya_cluster = valve_dev.endpoints[1].tuya_manufacturer
thermostat_cluster = valve_dev.endpoints[1].thermostat
onoff_cluster = valve_dev.endpoints[1].on_off
thermostat_ui_cluster = valve_dev.endpoints[1].thermostat_ui
thermostat_listener = ClusterListener(valve_dev.endpoints[1].thermostat)
onoff_listener = ClusterListener(valve_dev.endpoints[1].on_off)
frames = (
ZCL_TUYA_VALVE_TEMPERATURE,
ZCL_TUYA_VALVE_WINDOW_DETECTION,
ZCL_TUYA_VALVE_WORKDAY_SCHEDULE,
ZCL_TUYA_VALVE_WEEKEND_SCHEDULE,
ZCL_TUYA_VALVE_OFF,
ZCL_TUYA_VALVE_SCHEDULE,
ZCL_TUYA_VALVE_MANUAL,
ZCL_TUYA_VALVE_COMFORT,
ZCL_TUYA_VALVE_ECO,
ZCL_TUYA_VALVE_BOOST,
ZCL_TUYA_VALVE_COMPLEX,
ZCL_TUYA_VALVE_STATE_50,
)
for frame in frames:
hdr, args = tuya_cluster.deserialize(frame)
tuya_cluster.handle_message(hdr, args)
assert len(thermostat_listener.cluster_commands) == 0
assert len(thermostat_listener.attribute_updates) == 61
assert thermostat_listener.attribute_updates[0][0] == 0x0000
assert thermostat_listener.attribute_updates[0][1] == 1790
assert thermostat_listener.attribute_updates[1][0] == 0x4110
assert thermostat_listener.attribute_updates[1][1] == 6
assert thermostat_listener.attribute_updates[2][0] == 0x4111
assert thermostat_listener.attribute_updates[2][1] == 0
assert thermostat_listener.attribute_updates[3][0] == 0x4112
assert thermostat_listener.attribute_updates[3][1] == 2000
assert thermostat_listener.attribute_updates[4][0] == 0x4120
assert thermostat_listener.attribute_updates[4][1] == 8
assert thermostat_listener.attribute_updates[5][0] == 0x4121
assert thermostat_listener.attribute_updates[5][1] == 0
assert thermostat_listener.attribute_updates[6][0] == 0x4122
assert thermostat_listener.attribute_updates[6][1] == 1500
assert thermostat_listener.attribute_updates[7][0] == 0x4130
assert thermostat_listener.attribute_updates[7][1] == 11
assert thermostat_listener.attribute_updates[8][0] == 0x4131
assert thermostat_listener.attribute_updates[8][1] == 30
assert thermostat_listener.attribute_updates[9][0] == 0x4132
assert thermostat_listener.attribute_updates[9][1] == 1500
assert thermostat_listener.attribute_updates[10][0] == 0x4140
assert thermostat_listener.attribute_updates[10][1] == 12
assert thermostat_listener.attribute_updates[11][0] == 0x4141
assert thermostat_listener.attribute_updates[11][1] == 30
assert thermostat_listener.attribute_updates[12][0] == 0x4142
assert thermostat_listener.attribute_updates[12][1] == 1500
assert thermostat_listener.attribute_updates[13][0] == 0x4150
assert thermostat_listener.attribute_updates[13][1] == 17
assert thermostat_listener.attribute_updates[14][0] == 0x4151
assert thermostat_listener.attribute_updates[14][1] == 30
assert thermostat_listener.attribute_updates[15][0] == 0x4152
assert thermostat_listener.attribute_updates[15][1] == 2000
assert thermostat_listener.attribute_updates[16][0] == 0x4160
assert thermostat_listener.attribute_updates[16][1] == 22
assert thermostat_listener.attribute_updates[17][0] == 0x4161
assert thermostat_listener.attribute_updates[17][1] == 0
assert thermostat_listener.attribute_updates[18][0] == 0x4162
assert thermostat_listener.attribute_updates[18][1] == 1500
assert thermostat_listener.attribute_updates[19][0] == 0x4210
assert thermostat_listener.attribute_updates[19][1] == 6
assert thermostat_listener.attribute_updates[20][0] == 0x4211
assert thermostat_listener.attribute_updates[20][1] == 0
assert thermostat_listener.attribute_updates[21][0] == 0x4212
assert thermostat_listener.attribute_updates[21][1] == 2000
assert thermostat_listener.attribute_updates[22][0] == 0x4220
assert thermostat_listener.attribute_updates[22][1] == 8
assert thermostat_listener.attribute_updates[23][0] == 0x4221
assert thermostat_listener.attribute_updates[23][1] == 0
assert thermostat_listener.attribute_updates[24][0] == 0x4222
assert thermostat_listener.attribute_updates[24][1] == 1500
assert thermostat_listener.attribute_updates[25][0] == 0x4230
assert thermostat_listener.attribute_updates[25][1] == 11
assert thermostat_listener.attribute_updates[26][0] == 0x4231
assert thermostat_listener.attribute_updates[26][1] == 30
assert thermostat_listener.attribute_updates[27][0] == 0x4232
assert thermostat_listener.attribute_updates[27][1] == 1500
assert thermostat_listener.attribute_updates[28][0] == 0x4240
assert thermostat_listener.attribute_updates[28][1] == 12
assert thermostat_listener.attribute_updates[29][0] == 0x4241
assert thermostat_listener.attribute_updates[29][1] == 30
assert thermostat_listener.attribute_updates[30][0] == 0x4242
assert thermostat_listener.attribute_updates[30][1] == 1500
assert thermostat_listener.attribute_updates[31][0] == 0x4250
assert thermostat_listener.attribute_updates[31][1] == 17
assert thermostat_listener.attribute_updates[32][0] == 0x4251
assert thermostat_listener.attribute_updates[32][1] == 30
assert thermostat_listener.attribute_updates[33][0] == 0x4252
assert thermostat_listener.attribute_updates[33][1] == 2000
assert thermostat_listener.attribute_updates[34][0] == 0x4260
assert thermostat_listener.attribute_updates[34][1] == 22
assert thermostat_listener.attribute_updates[35][0] == 0x4261
assert thermostat_listener.attribute_updates[35][1] == 0
assert thermostat_listener.attribute_updates[36][0] == 0x4262
assert thermostat_listener.attribute_updates[36][1] == 1500
assert thermostat_listener.attribute_updates[37][0] == 0x4002
assert thermostat_listener.attribute_updates[37][1] == 0
assert thermostat_listener.attribute_updates[38][0] == 0x0025
assert thermostat_listener.attribute_updates[38][1] == 0
assert thermostat_listener.attribute_updates[39][0] == 0x0002
assert thermostat_listener.attribute_updates[39][1] == 0
assert thermostat_listener.attribute_updates[40][0] == 0x4002
assert thermostat_listener.attribute_updates[40][1] == 1
assert thermostat_listener.attribute_updates[41][0] == 0x0025
assert thermostat_listener.attribute_updates[41][1] == 1
assert thermostat_listener.attribute_updates[42][0] == 0x0002
assert thermostat_listener.attribute_updates[42][1] == 1
assert thermostat_listener.attribute_updates[43][0] == 0x4002
assert thermostat_listener.attribute_updates[43][1] == 2
assert thermostat_listener.attribute_updates[44][0] == 0x0025
assert thermostat_listener.attribute_updates[44][1] == 0
assert thermostat_listener.attribute_updates[45][0] == 0x0002
assert thermostat_listener.attribute_updates[45][1] == 1
assert thermostat_listener.attribute_updates[46][0] == 0x4002
assert thermostat_listener.attribute_updates[46][1] == 3
assert thermostat_listener.attribute_updates[47][0] == 0x0025
assert thermostat_listener.attribute_updates[47][1] == 0
assert thermostat_listener.attribute_updates[48][0] == 0x0002
assert thermostat_listener.attribute_updates[48][1] == 1
assert thermostat_listener.attribute_updates[49][0] == 0x4002
assert thermostat_listener.attribute_updates[49][1] == 4
assert thermostat_listener.attribute_updates[50][0] == 0x0025
assert thermostat_listener.attribute_updates[50][1] == 4
assert thermostat_listener.attribute_updates[51][0] == 0x0002
assert thermostat_listener.attribute_updates[51][1] == 1
assert thermostat_listener.attribute_updates[52][0] == 0x4002
assert thermostat_listener.attribute_updates[52][1] == 5
assert thermostat_listener.attribute_updates[53][0] == 0x0025
assert thermostat_listener.attribute_updates[53][1] == 0
assert thermostat_listener.attribute_updates[54][0] == 0x0002
assert thermostat_listener.attribute_updates[54][1] == 1
assert thermostat_listener.attribute_updates[55][0] == 0x4002
assert thermostat_listener.attribute_updates[55][1] == 6
assert thermostat_listener.attribute_updates[56][0] == 0x0025
assert thermostat_listener.attribute_updates[56][1] == 0
assert thermostat_listener.attribute_updates[57][0] == 0x0002
assert thermostat_listener.attribute_updates[57][1] == 1
assert thermostat_listener.attribute_updates[58][0] == 0x4004
assert thermostat_listener.attribute_updates[58][1] == 50
assert thermostat_listener.attribute_updates[59][0] == 0x001E
assert thermostat_listener.attribute_updates[59][1] == 4
assert thermostat_listener.attribute_updates[60][0] == 0x0029
assert thermostat_listener.attribute_updates[60][1] == 1
assert len(onoff_listener.cluster_commands) == 0
assert len(onoff_listener.attribute_updates) == 3
assert onoff_listener.attribute_updates[0][0] == 0x6001
assert onoff_listener.attribute_updates[0][1] == 5
assert onoff_listener.attribute_updates[1][0] == 0x6000
assert onoff_listener.attribute_updates[1][1] == 1600
assert onoff_listener.attribute_updates[2][0] == 0x0000
assert onoff_listener.attribute_updates[2][1] == 1
thermostat_ui_listener = ClusterListener(valve_dev.endpoints[1].thermostat_ui)
power_listener = ClusterListener(valve_dev.endpoints[1].power)
frames = (
ZCL_TUYA_VALVE_CHILD_LOCK_ON,
ZCL_TUYA_VALVE_AUTO_LOCK_ON,
ZCL_TUYA_VALVE_BATTERY_LOW,
)
for frame in frames:
hdr, args = tuya_cluster.deserialize(frame)
tuya_cluster.handle_message(hdr, args)
assert len(thermostat_ui_listener.cluster_commands) == 0
assert len(thermostat_ui_listener.attribute_updates) == 2
assert thermostat_ui_listener.attribute_updates[0][0] == 0x0001
assert thermostat_ui_listener.attribute_updates[0][1] == 1
assert thermostat_ui_listener.attribute_updates[1][0] == 0x5000
assert thermostat_ui_listener.attribute_updates[1][1] == 1
assert len(power_listener.cluster_commands) == 0
assert len(power_listener.attribute_updates) == 1
assert power_listener.attribute_updates[0][0] == 0x0021
assert power_listener.attribute_updates[0][1] == 10
async def async_success(*args, **kwargs):
return foundation.Status.SUCCESS
with mock.patch.object(
tuya_cluster.endpoint, "request", side_effect=async_success
) as m1:
status = await thermostat_cluster.write_attributes(
{
"occupied_heating_setpoint": 2500,
}
)
m1.assert_called_with(
61184,
1,
b"\x01\x01\x00\x00\x01\x02\x02\x00\x04\x00\x00\x00\xfa",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"operation_preset": 0x00,
}
)
m1.assert_called_with(
61184,
2,
b"\x01\x02\x00\x00\x02\x04\x04\x00\x01\x00",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"operation_preset": 0x02,
}
)
m1.assert_called_with(
61184,
3,
b"\x01\x03\x00\x00\x03\x04\x04\x00\x01\x02",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
hdr, args = tuya_cluster.deserialize(ZCL_TUYA_VALVE_TARGET_TEMP)
tuya_cluster.handle_message(hdr, args)
status = await thermostat_cluster.command(0x0000, 0x00, 20)
m1.assert_called_with(
61184,
4,
b"\x01\x04\x00\x00\x04\x02\x02\x00\x04\x00\x00\x00F",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await onoff_cluster.write_attributes(
{
"on_off": 0x00,
"window_detection_timeout_minutes": 0x02,
"window_detection_temperature": 2000,
}
)
m1.assert_called_with(
61184,
5,
b"\x01\x05\x00\x00\x05\x68\x00\x00\x03\x00\x14\x02",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"occupancy": 0x00,
}
)
m1.assert_called_with(
61184,
6,
b"\x01\x06\x00\x00\x06\x04\x04\x00\x01\x00",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"occupancy": 0x01,
"programing_oper_mode": 0x00,
}
)
m1.assert_called_with(
61184,
7,
b"\x01\x07\x00\x00\x07\x04\x04\x00\x01\x02",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"programing_oper_mode": 0x01,
}
)
m1.assert_called_with(
61184,
8,
b"\x01\x08\x00\x00\x08\x04\x04\x00\x01\x01",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"programing_oper_mode": 0x04,
}
)
m1.assert_called_with(
61184,
9,
b"\x01\x09\x00\x00\x09\x04\x04\x00\x01\x04",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"workday_schedule_1_temperature": 1700,
}
)
m1.assert_called_with(
61184,
10,
b"\x01\x0A\x00\x00\x0A\x70\x00\x00\x12\x06\x00\x11\x08\x00\x0F\x0B\x1E\x0F\x0C\x1E\x0F\x11\x1E\x14\x16\x00\x0F",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"workday_schedule_1_minute": 45,
}
)
m1.assert_called_with(
61184,
11,
b"\x01\x0B\x00\x00\x0B\x70\x00\x00\x12\x06\x2D\x14\x08\x00\x0F\x0B\x1E\x0F\x0C\x1E\x0F\x11\x1E\x14\x16\x00\x0F",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"workday_schedule_1_hour": 5,
}
)
m1.assert_called_with(
61184,
12,
b"\x01\x0C\x00\x00\x0C\x70\x00\x00\x12\x05\x00\x14\x08\x00\x0F\x0B\x1E\x0F\x0C\x1E\x0F\x11\x1E\x14\x16\x00\x0F",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"weekend_schedule_1_temperature": 1700,
}
)
m1.assert_called_with(
61184,
13,
b"\x01\x0D\x00\x00\x0D\x71\x00\x00\x12\x06\x00\x11\x08\x00\x0F\x0B\x1E\x0F\x0C\x1E\x0F\x11\x1E\x14\x16\x00\x0F",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"weekend_schedule_1_minute": 45,
}
)
m1.assert_called_with(
61184,
14,
b"\x01\x0E\x00\x00\x0E\x71\x00\x00\x12\x06\x2D\x14\x08\x00\x0F\x0B\x1E\x0F\x0C\x1E\x0F\x11\x1E\x14\x16\x00\x0F",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"weekend_schedule_1_hour": 5,
}
)
m1.assert_called_with(
61184,
15,
b"\x01\x0F\x00\x00\x0F\x71\x00\x00\x12\x05\x00\x14\x08\x00\x0F\x0B\x1E\x0F\x0C\x1E\x0F\x11\x1E\x14\x16\x00\x0F",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"system_mode": 0x01,
}
)
m1.assert_called_with(
61184,
16,
b"\x01\x10\x00\x00\x10\x04\x04\x00\x01\x06",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_ui_cluster.write_attributes(
{
"auto_lock": 0x00,
}
)
m1.assert_called_with(
61184,
17,
b"\x01\x11\x00\x00\x11\x74\x01\x00\x01\x00",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await onoff_cluster.command(0x0000)
m1.assert_called_with(
61184,
18,
b"\x01\x12\x00\x00\x12\x68\x00\x00\x03\x00\x10\x05",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await onoff_cluster.command(0x0001)
m1.assert_called_with(
61184,
19,
b"\x01\x13\x00\x00\x13\x68\x00\x00\x03\x01\x10\x05",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await onoff_cluster.command(0x0002)
m1.assert_called_with(
61184,
20,
b"\x01\x14\x00\x00\x14\x68\x00\x00\x03\x00\x10\x05",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await onoff_cluster.write_attributes({})
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.command(0x0002)
assert status == foundation.Status.UNSUP_CLUSTER_COMMAND
status = await onoff_cluster.command(0x0009)
assert status == foundation.Status.UNSUP_CLUSTER_COMMAND
origdatetime = datetime.datetime
datetime.datetime = NewDatetime
hdr, args = tuya_cluster.deserialize(ZCL_TUYA_SET_TIME_REQUEST)
tuya_cluster.handle_message(hdr, args)
m1.assert_called_with(
61184,
21,
b"\x01\x15\x24\x00\x08\x00\x00\x1C\x20\x00\x00\x0E\x10",
expect_reply=False,
command_id=0x0024,
)
datetime.datetime = origdatetime
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.electric_heating.MoesBHT,))
async def test_eheating_state_report(zigpy_device_from_quirk, quirk):
electric_dev = zigpy_device_from_quirk(quirk)
tuya_cluster = electric_dev.endpoints[1].tuya_manufacturer
thermostat_listener = ClusterListener(electric_dev.endpoints[1].thermostat)
frames = (ZCL_TUYA_EHEAT_TEMPERATURE, ZCL_TUYA_EHEAT_TARGET_TEMP)
for frame in frames:
hdr, args = tuya_cluster.deserialize(frame)
tuya_cluster.handle_message(hdr, args)
assert len(thermostat_listener.cluster_commands) == 0
assert len(thermostat_listener.attribute_updates) == 2
assert thermostat_listener.attribute_updates[0][0] == 0x0000
assert thermostat_listener.attribute_updates[0][1] == 1790
assert thermostat_listener.attribute_updates[1][0] == 0x0012
assert thermostat_listener.attribute_updates[1][1] == 2100
@pytest.mark.parametrize("quirk", (zhaquirks.tuya.electric_heating.MoesBHT,))
async def test_eheat_send_attribute(zigpy_device_from_quirk, quirk):
eheat_dev = zigpy_device_from_quirk(quirk)
tuya_cluster = eheat_dev.endpoints[1].tuya_manufacturer
thermostat_cluster = eheat_dev.endpoints[1].thermostat
async def async_success(*args, **kwargs):
return foundation.Status.SUCCESS
with mock.patch.object(
tuya_cluster.endpoint, "request", side_effect=async_success
) as m1:
status = await thermostat_cluster.write_attributes(
{
"occupied_heating_setpoint": 2500,
}
)
m1.assert_called_with(
61184,
1,
b"\x01\x01\x00\x00\x01\x10\x02\x00\x04\x00\x00\x00\x19",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"system_mode": 0x00,
}
)
m1.assert_called_with(
61184,
2,
b"\x01\x02\x00\x00\x02\x01\x01\x00\x01\x00",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.write_attributes(
{
"system_mode": 0x04,
}
)
m1.assert_called_with(
61184,
3,
b"\x01\x03\x00\x00\x03\x01\x01\x00\x01\x01",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
hdr, args = tuya_cluster.deserialize(ZCL_TUYA_EHEAT_TARGET_TEMP)
tuya_cluster.handle_message(hdr, args)
status = await thermostat_cluster.command(0x0000, 0x00, 20)
m1.assert_called_with(
61184,
4,
b"\x01\x04\x00\x00\x04\x10\x02\x00\x04\x00\x00\x00\x17",
expect_reply=False,
command_id=0,
)
assert status == (foundation.Status.SUCCESS,)
status = await thermostat_cluster.command(0x0002)
assert status == foundation.Status.UNSUP_CLUSTER_COMMAND
@pytest.mark.parametrize(
"quirk, manufacturer",
(
(zhaquirks.tuya.ts0042.TuyaSmartRemote0042, "_TZ3000_owgcnkrh"),
(zhaquirks.tuya.ts0042.TuyaSmartRemote0042, "_TZ3400_keyjhapk"),
(zhaquirks.tuya.ts0042.TuyaSmartRemote0042, "_some_random_manuf"),
(zhaquirks.tuya.ts0042.BenexmartRemote0042, "_TZ3000_adkvzooy"),
(zhaquirks.tuya.ts0042.BenexmartRemote0042, "_TZ3400_keyjhapk"),
(zhaquirks.tuya.ts0042.BenexmartRemote0042, "another random manufacturer"),
(zhaquirks.tuya.ts0043.TuyaSmartRemote0043, "_TZ3000_bi6lpsew"),
(zhaquirks.tuya.ts0043.TuyaSmartRemote0043, "_TZ3000_a7ouggvs"),
(zhaquirks.tuya.ts0043.TuyaSmartRemote0043, "another random manufacturer"),
(zhaquirks.tuya.ts0043.BenexmartRemote0043, "_TZ3000_qzjcsmar"),
(zhaquirks.tuya.ts0043.BenexmartRemote0043, "another random manufacturer"),
),
)
async def test_tuya_wildcard_manufacturer(zigpy_device_from_quirk, quirk, manufacturer):
zigpy_dev = zigpy_device_from_quirk(quirk, apply_quirk=False)
zigpy_dev.manufacturer = manufacturer
quirked_dev = get_device(zigpy_dev)
assert isinstance(quirked_dev, quirk)
| true | true |
1c2bcb1045a9bfdca3102dc09f5c3dfe9e119723 | 350 | py | Python | music_site/artists/migrations/0002_auto_20200531_2240.py | UVG-Teams/music-space | 8f464b6b1cbe59afea3be3ab1b9ed4e25ab0b424 | [
"MIT"
] | null | null | null | music_site/artists/migrations/0002_auto_20200531_2240.py | UVG-Teams/music-space | 8f464b6b1cbe59afea3be3ab1b9ed4e25ab0b424 | [
"MIT"
] | null | null | null | music_site/artists/migrations/0002_auto_20200531_2240.py | UVG-Teams/music-space | 8f464b6b1cbe59afea3be3ab1b9ed4e25ab0b424 | [
"MIT"
] | null | null | null | # Generated by Django 3.0.4 on 2020-05-31 22:40
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('artists', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='artist',
old_name='artistid',
new_name='id',
),
]
| 18.421053 | 47 | 0.568571 |
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('artists', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='artist',
old_name='artistid',
new_name='id',
),
]
| true | true |
1c2bcb9944cc662cdfce1818d2d5730b669f6727 | 241 | py | Python | 2020/Day3/day3.py | dh256/adventofcode | 428eec13f4cbf153333a0e359bcff23070ef6d27 | [
"MIT"
] | null | null | null | 2020/Day3/day3.py | dh256/adventofcode | 428eec13f4cbf153333a0e359bcff23070ef6d27 | [
"MIT"
] | null | null | null | 2020/Day3/day3.py | dh256/adventofcode | 428eec13f4cbf153333a0e359bcff23070ef6d27 | [
"MIT"
] | null | null | null | from Map import Map,Slope
map = Map("input.txt")
# Part 1
slopes = [Slope(3,1)]
trees = map.traverse(slopes)
print(trees)
# Part 2
slopes = [Slope(3,1),Slope(1,1),Slope(5,1),Slope(7,1),Slope(1,2)]
trees = map.traverse(slopes)
print(trees) | 18.538462 | 65 | 0.676349 | from Map import Map,Slope
map = Map("input.txt")
slopes = [Slope(3,1)]
trees = map.traverse(slopes)
print(trees)
slopes = [Slope(3,1),Slope(1,1),Slope(5,1),Slope(7,1),Slope(1,2)]
trees = map.traverse(slopes)
print(trees) | true | true |
1c2bcc15f683de53f888261008c1e63ae818dbf9 | 10,555 | py | Python | src/ggrc/migrations/versions/20161220161315_275cd0dcaea_migrate_assessments_issues_data.py | Killswitchz/ggrc-core | 2460df94daf66727af248ad821462692917c97a9 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2018-03-30T11:28:48.000Z | 2018-03-30T11:28:48.000Z | src/ggrc/migrations/versions/20161220161315_275cd0dcaea_migrate_assessments_issues_data.py | trevordonnelly/ggrc-core | 499cf0d3cce70737b080991b12c203ec22015cea | [
"ECL-2.0",
"Apache-2.0"
] | 10 | 2018-07-06T00:04:23.000Z | 2021-02-26T21:13:20.000Z | src/ggrc/migrations/versions/20161220161315_275cd0dcaea_migrate_assessments_issues_data.py | zidarsk8/ggrc-core | 2509c989eddf434249d3bef50c21e08dbf56c1a4 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2017-11-11T22:16:56.000Z | 2017-11-11T22:16:56.000Z | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""
migrate-assessments-issues-data
Create Date: 2016-12-20 16:13:15.208946
"""
# disable Invalid constant name pylint warning for mandatory Alembic variables.
# pylint: disable=invalid-name
from collections import defaultdict
from logging import getLogger
from alembic import op
from sqlalchemy.sql import column
from sqlalchemy.sql import select
from sqlalchemy.sql import table
from sqlalchemy.sql import tuple_
from ggrc.models.assessment import Assessment
from ggrc.models.event import Event
from ggrc.models.issue import Issue
from ggrc.models.revision import Revision
from ggrc.models.snapshot import Snapshot
from ggrc.snapshotter.rules import Types
from ggrc.migrations.utils import get_relationship_cache
from ggrc.migrations.utils import get_revisions
from ggrc.migrations.utils import insert_payloads
from ggrc.migrations.utils import Stub
from ggrc.migrations.utils.migrator import get_migration_user_id
logger = getLogger(__name__) # pylint: disable=invalid-name
# revision identifiers, used by Alembic.
revision = '275cd0dcaea'
down_revision = '142272c4a0b6'
assessments_table = Assessment.__table__
issues_table = Issue.__table__
snapshots_table = Snapshot.__table__
revisions_table = Revision.__table__
events_table = Event.__table__
audits_table = table(
"audits",
column("id"),
column("context_id"),
column("program_id"),
)
programs_table = table(
"programs",
column("id"),
column("context_id")
)
def process_objects(connection, user_id, caches, object_settings):
"""Process objects
Used for processing of Assessments and Issues
"""
# pylint: disable=too-many-locals
snapshot_quads = get_or_create_snapshots(connection, user_id,
caches, object_settings)
link_snapshots_to_objects(connection, user_id, caches, object_settings,
snapshot_quads)
def get_or_create_snapshots(connection, user_id,
caches, object_settings):
"""Get or create snapshots for specific object type"""
# pylint: disable=too-many-locals
relationships_payload = []
snapshots_payload = []
snapshot_quads = set()
program_relationships = caches["program_rels"]
parent_snapshot_cache = caches["snapshots"]
program_contexts = caches["program_contexts"]
audit_programs = caches["audit_programs"]
audit_contexts = caches["audit_contexts"]
revisions_cache = caches["revisions"]
object_klass = object_settings["type"]
object_relationships = object_settings["object_relationships"]
object_select = object_settings["select_all"]
all_objects = connection.execute(object_select).fetchall()
for object_ in all_objects:
key = Stub(object_klass, object_.id)
objects = object_relationships[key]
audit = [x for x in objects if x.type == "Audit"]
others = [x for x in objects if x.type in Types.all]
if len(audit) != 1:
continue
if audit:
audit = audit[0]
others = set(others)
quads = {
("Audit", audit.id, obj_.type, obj_.id)
for obj_ in others
}
snapshot_quads.update(quads)
program_id = audit_programs[audit.id]
program_ctx_id = program_contexts[program_id]
existing_snapshots = parent_snapshot_cache[audit]
missing_snapshots = others - existing_snapshots
if missing_snapshots:
audit_context_id = audit_contexts[audit.id]
for obj_ in missing_snapshots:
if obj_ in revisions_cache:
snapshots_payload += [{
"parent_type": "Audit",
"parent_id": audit.id,
"child_type": obj_.type,
"child_id": obj_.id,
"revision_id": revisions_cache[obj_],
"context_id": audit_context_id,
"modified_by_id": user_id,
}]
relationships_payload += [{
"source_type": "Program",
"source_id": program_id,
"destination_type": obj_.type,
"destination_id": obj_.id,
"modified_by_id": user_id,
"context_id": program_ctx_id,
}, {
# this is because of our hack where we rely on
# relationships
"source_type": "Audit",
"source_id": audit.id,
"destination_type": obj_.type,
"destination_id": obj_.id,
"modified_by_id": user_id,
"context_id": audit_context_id,
}]
else:
logger.warning(
"Missing revision for object %s-%s", obj_.type, obj_.id)
missing_from_program_scope = (program_relationships[program_id] -
existing_snapshots)
if missing_from_program_scope:
for obj_ in missing_from_program_scope:
relationships_payload += [{
"source_type": "Program",
"source_id": program_id,
"destination_type": obj_.type,
"destination_id": obj_.id,
"modified_by_id": user_id,
"context_id": program_ctx_id,
}]
insert_payloads(connection, snapshots_payload, relationships_payload)
return snapshot_quads
def link_snapshots_to_objects(connection, user_id,
caches, object_settings, snapshot_quads):
"""Create relationships between snapshots and objects"""
# pylint: disable=too-many-locals
relationships_payload = []
audit_contexts = caches["audit_contexts"]
object_klass = object_settings["type"]
object_relationships = object_settings["object_relationships"]
object_select = object_settings["select_all"]
all_objects = connection.execute(object_select).fetchall()
if snapshot_quads:
snapshots = connection.execute(select([snapshots_table]).where(
tuple_(
Snapshot.parent_type,
Snapshot.parent_id,
Snapshot.child_type,
Snapshot.child_id,
).in_(snapshot_quads)
)).fetchall()
snapshot_cache = {
(obj_.parent_type, obj_.parent_id,
obj_.child_type, obj_.child_id): obj_.id
for obj_ in snapshots
}
for object_ in all_objects:
key = Stub(object_klass, object_.id)
objects = object_relationships[key]
audit = [x for x in objects if x.type == "Audit"]
others = [x for x in objects if x.type in Types.all]
if len(audit) != 1:
continue
if audit:
audit = audit[0]
audit_context_id = audit_contexts[audit.id]
others = set(others)
for obj_ in others:
quad = ("Audit", audit.id, obj_.type, obj_.id)
if quad in snapshot_cache:
relationships_payload += [{
"source_type": object_klass,
"source_id": object_.id,
"destination_type": "Snapshot",
"destination_id": snapshot_cache[quad],
"modified_by_id": user_id,
"context_id": audit_context_id,
}, {
"source_type": obj_.type,
"source_id": obj_.id,
"destination_type": "Snapshot",
"destination_id": snapshot_cache[quad],
"modified_by_id": user_id,
"context_id": audit_context_id,
}]
else:
logger.warning(
"Couldn't map %s-%s to Snapshot of object %s-%s because it "
"doesn't exist due to missing revision.",
object_klass, object_.id, obj_.type, obj_.id
)
insert_payloads(connection, relationships=relationships_payload)
def get_scope_snapshots(connection):
"""Create cache of audit snapshots
Create cache (defaultdict) of audits mapping from audit stub to set of
children stubs.
"""
cache = defaultdict(set)
query = select([snapshots_table])
result = connection.execute(query)
for snapshot in result:
parent = Stub(snapshot.parent_type, snapshot.parent_id)
child = Stub(snapshot.child_type, snapshot.child_id)
cache[parent].add(child)
return cache
def upgrade():
"""Primary upgrade function for upgrading assessments and issues
Primarily used for building various caches et al."""
# pylint: disable=too-many-locals
connection = op.get_bind()
program_sql = select([programs_table])
programs = connection.execute(program_sql)
program_contexts = {program.id: program.context_id for program in programs}
audit_sql = select([audits_table])
audits = connection.execute(audit_sql).fetchall()
if audits:
audit_contexts = {audit.id: audit.context_id for audit in audits}
audit_programs = {audit.id: audit.program_id for audit in audits}
program_cache = get_relationship_cache(connection, "Program", Types.all)
audit_cache = get_relationship_cache(connection, "Audit", Types.all)
parent_snapshot_cache = get_scope_snapshots(connection)
assessments_cache = get_relationship_cache(connection, "Assessment",
Types.all | {"Audit"})
issues_cache = get_relationship_cache(connection, "Issue",
Types.all | {"Audit"})
all_objects = (program_cache.values() + audit_cache.values() +
assessments_cache.values() + issues_cache.values())
revisionable_objects = set()
revisionable_objects = revisionable_objects.union(*all_objects)
revision_cache = get_revisions(connection, revisionable_objects)
caches = {
"program_rels": program_cache,
"audit_rels": audit_cache,
"snapshots": parent_snapshot_cache,
"program_contexts": program_contexts,
"audit_programs": audit_programs,
"audit_contexts": audit_contexts,
"revisions": revision_cache
}
objects = [
{
"type": "Assessment",
"select_all": assessments_table.select(),
"object_relationships": assessments_cache
},
{
"type": "Issue",
"select_all": issues_table.select(),
"object_relationships": issues_cache
},
]
if assessments_cache or issues_cache:
user_id = get_migration_user_id(connection)
for object_settings in objects:
process_objects(connection, user_id, caches, object_settings)
def downgrade():
pass
| 32.179878 | 79 | 0.645381 |
from collections import defaultdict
from logging import getLogger
from alembic import op
from sqlalchemy.sql import column
from sqlalchemy.sql import select
from sqlalchemy.sql import table
from sqlalchemy.sql import tuple_
from ggrc.models.assessment import Assessment
from ggrc.models.event import Event
from ggrc.models.issue import Issue
from ggrc.models.revision import Revision
from ggrc.models.snapshot import Snapshot
from ggrc.snapshotter.rules import Types
from ggrc.migrations.utils import get_relationship_cache
from ggrc.migrations.utils import get_revisions
from ggrc.migrations.utils import insert_payloads
from ggrc.migrations.utils import Stub
from ggrc.migrations.utils.migrator import get_migration_user_id
logger = getLogger(__name__)
revision = '275cd0dcaea'
down_revision = '142272c4a0b6'
assessments_table = Assessment.__table__
issues_table = Issue.__table__
snapshots_table = Snapshot.__table__
revisions_table = Revision.__table__
events_table = Event.__table__
audits_table = table(
"audits",
column("id"),
column("context_id"),
column("program_id"),
)
programs_table = table(
"programs",
column("id"),
column("context_id")
)
def process_objects(connection, user_id, caches, object_settings):
snapshot_quads = get_or_create_snapshots(connection, user_id,
caches, object_settings)
link_snapshots_to_objects(connection, user_id, caches, object_settings,
snapshot_quads)
def get_or_create_snapshots(connection, user_id,
caches, object_settings):
relationships_payload = []
snapshots_payload = []
snapshot_quads = set()
program_relationships = caches["program_rels"]
parent_snapshot_cache = caches["snapshots"]
program_contexts = caches["program_contexts"]
audit_programs = caches["audit_programs"]
audit_contexts = caches["audit_contexts"]
revisions_cache = caches["revisions"]
object_klass = object_settings["type"]
object_relationships = object_settings["object_relationships"]
object_select = object_settings["select_all"]
all_objects = connection.execute(object_select).fetchall()
for object_ in all_objects:
key = Stub(object_klass, object_.id)
objects = object_relationships[key]
audit = [x for x in objects if x.type == "Audit"]
others = [x for x in objects if x.type in Types.all]
if len(audit) != 1:
continue
if audit:
audit = audit[0]
others = set(others)
quads = {
("Audit", audit.id, obj_.type, obj_.id)
for obj_ in others
}
snapshot_quads.update(quads)
program_id = audit_programs[audit.id]
program_ctx_id = program_contexts[program_id]
existing_snapshots = parent_snapshot_cache[audit]
missing_snapshots = others - existing_snapshots
if missing_snapshots:
audit_context_id = audit_contexts[audit.id]
for obj_ in missing_snapshots:
if obj_ in revisions_cache:
snapshots_payload += [{
"parent_type": "Audit",
"parent_id": audit.id,
"child_type": obj_.type,
"child_id": obj_.id,
"revision_id": revisions_cache[obj_],
"context_id": audit_context_id,
"modified_by_id": user_id,
}]
relationships_payload += [{
"source_type": "Program",
"source_id": program_id,
"destination_type": obj_.type,
"destination_id": obj_.id,
"modified_by_id": user_id,
"context_id": program_ctx_id,
}, {
"source_type": "Audit",
"source_id": audit.id,
"destination_type": obj_.type,
"destination_id": obj_.id,
"modified_by_id": user_id,
"context_id": audit_context_id,
}]
else:
logger.warning(
"Missing revision for object %s-%s", obj_.type, obj_.id)
missing_from_program_scope = (program_relationships[program_id] -
existing_snapshots)
if missing_from_program_scope:
for obj_ in missing_from_program_scope:
relationships_payload += [{
"source_type": "Program",
"source_id": program_id,
"destination_type": obj_.type,
"destination_id": obj_.id,
"modified_by_id": user_id,
"context_id": program_ctx_id,
}]
insert_payloads(connection, snapshots_payload, relationships_payload)
return snapshot_quads
def link_snapshots_to_objects(connection, user_id,
caches, object_settings, snapshot_quads):
relationships_payload = []
audit_contexts = caches["audit_contexts"]
object_klass = object_settings["type"]
object_relationships = object_settings["object_relationships"]
object_select = object_settings["select_all"]
all_objects = connection.execute(object_select).fetchall()
if snapshot_quads:
snapshots = connection.execute(select([snapshots_table]).where(
tuple_(
Snapshot.parent_type,
Snapshot.parent_id,
Snapshot.child_type,
Snapshot.child_id,
).in_(snapshot_quads)
)).fetchall()
snapshot_cache = {
(obj_.parent_type, obj_.parent_id,
obj_.child_type, obj_.child_id): obj_.id
for obj_ in snapshots
}
for object_ in all_objects:
key = Stub(object_klass, object_.id)
objects = object_relationships[key]
audit = [x for x in objects if x.type == "Audit"]
others = [x for x in objects if x.type in Types.all]
if len(audit) != 1:
continue
if audit:
audit = audit[0]
audit_context_id = audit_contexts[audit.id]
others = set(others)
for obj_ in others:
quad = ("Audit", audit.id, obj_.type, obj_.id)
if quad in snapshot_cache:
relationships_payload += [{
"source_type": object_klass,
"source_id": object_.id,
"destination_type": "Snapshot",
"destination_id": snapshot_cache[quad],
"modified_by_id": user_id,
"context_id": audit_context_id,
}, {
"source_type": obj_.type,
"source_id": obj_.id,
"destination_type": "Snapshot",
"destination_id": snapshot_cache[quad],
"modified_by_id": user_id,
"context_id": audit_context_id,
}]
else:
logger.warning(
"Couldn't map %s-%s to Snapshot of object %s-%s because it "
"doesn't exist due to missing revision.",
object_klass, object_.id, obj_.type, obj_.id
)
insert_payloads(connection, relationships=relationships_payload)
def get_scope_snapshots(connection):
cache = defaultdict(set)
query = select([snapshots_table])
result = connection.execute(query)
for snapshot in result:
parent = Stub(snapshot.parent_type, snapshot.parent_id)
child = Stub(snapshot.child_type, snapshot.child_id)
cache[parent].add(child)
return cache
def upgrade():
connection = op.get_bind()
program_sql = select([programs_table])
programs = connection.execute(program_sql)
program_contexts = {program.id: program.context_id for program in programs}
audit_sql = select([audits_table])
audits = connection.execute(audit_sql).fetchall()
if audits:
audit_contexts = {audit.id: audit.context_id for audit in audits}
audit_programs = {audit.id: audit.program_id for audit in audits}
program_cache = get_relationship_cache(connection, "Program", Types.all)
audit_cache = get_relationship_cache(connection, "Audit", Types.all)
parent_snapshot_cache = get_scope_snapshots(connection)
assessments_cache = get_relationship_cache(connection, "Assessment",
Types.all | {"Audit"})
issues_cache = get_relationship_cache(connection, "Issue",
Types.all | {"Audit"})
all_objects = (program_cache.values() + audit_cache.values() +
assessments_cache.values() + issues_cache.values())
revisionable_objects = set()
revisionable_objects = revisionable_objects.union(*all_objects)
revision_cache = get_revisions(connection, revisionable_objects)
caches = {
"program_rels": program_cache,
"audit_rels": audit_cache,
"snapshots": parent_snapshot_cache,
"program_contexts": program_contexts,
"audit_programs": audit_programs,
"audit_contexts": audit_contexts,
"revisions": revision_cache
}
objects = [
{
"type": "Assessment",
"select_all": assessments_table.select(),
"object_relationships": assessments_cache
},
{
"type": "Issue",
"select_all": issues_table.select(),
"object_relationships": issues_cache
},
]
if assessments_cache or issues_cache:
user_id = get_migration_user_id(connection)
for object_settings in objects:
process_objects(connection, user_id, caches, object_settings)
def downgrade():
pass
| true | true |
1c2bcd1e3e93e7023f4d922645a64432b5bafb74 | 2,544 | py | Python | juriscraper/opinions/united_states_backscrapers/federal_special/cit_2012.py | umeboshi2/juriscraper | 16abceb3747947593841b1c2708de84dcc85c59d | [
"BSD-2-Clause"
] | null | null | null | juriscraper/opinions/united_states_backscrapers/federal_special/cit_2012.py | umeboshi2/juriscraper | 16abceb3747947593841b1c2708de84dcc85c59d | [
"BSD-2-Clause"
] | null | null | null | juriscraper/opinions/united_states_backscrapers/federal_special/cit_2012.py | umeboshi2/juriscraper | 16abceb3747947593841b1c2708de84dcc85c59d | [
"BSD-2-Clause"
] | 1 | 2021-03-03T00:03:16.000Z | 2021-03-03T00:03:16.000Z | from juriscraper.opinions.united_states.federal_special import cit
import time
from datetime import date
from lxml import html
class Site(cit.Site):
def __init__(self, *args, **kwargs):
super(Site, self).__init__(*args, **kwargs)
self.url = 'http://www.cit.uscourts.gov/SlipOpinions/SlipOps-2012.html'
self.court_id = self.__module__
def _get_download_urls(self):
return [t for t in self.html.xpath('//table[4]//tr/td[1]//a/@href')]
def _get_neutral_citations(self):
return [t for t in self.html.xpath('//table[4]//tr/td[1]//a/text()')]
def _get_case_names(self):
# Exclude confidential rows by ensuring there is a sibling row that
# contains an anchor (which confidential cases do not)
# There is also one stray case within a <p> tag we have to catch.
return [s for s in self.html.xpath('//table[4]//tr[position() > 1]/td[2][../td//a]/text()[1] | //table[4]//tr[position() > 1]/td[2][../td//a]/p/text()[1]')]
def _get_precedential_statuses(self):
return ['Published'] * len(self.case_names)
def _get_case_dates(self):
# This does not capture the release dates for the errata documents.
# The errata release date is listed in column 2. This will use the
# original release date instead.
dates = []
date_formats = ['%m/%d/%Y', '%m/%d/%y']
for date_string in self.html.xpath('//table[4]//tr/td[3][../td//a]/text()'):
for date_format in date_formats:
try:
d = date.fromtimestamp(time.mktime(
time.strptime(date_string, date_format)))
dates.append(d)
break
except ValueError:
# Try the next format
continue
return dates
def _get_docket_numbers(self):
docket_numbers = []
for e in self.html.xpath('//table[4]//tr[position() > 1]/td[4][../td//a]'):
docket_numbers.append(html.tostring(
e, method='text', encoding='unicode').strip())
return docket_numbers
def _get_judges(self):
judges = []
for e in self.html.xpath('//table[4]//tr[position() > 1]/td[5][../td//a]'):
s = html.tostring (e, method='text', encoding='unicode')
judges.append(s)
return judges
def _get_nature_of_suit(self):
return [t for t in self.html.xpath('//table[4]//tr/td[6][../td//a]/text()')]
| 41.704918 | 164 | 0.575865 | from juriscraper.opinions.united_states.federal_special import cit
import time
from datetime import date
from lxml import html
class Site(cit.Site):
def __init__(self, *args, **kwargs):
super(Site, self).__init__(*args, **kwargs)
self.url = 'http://www.cit.uscourts.gov/SlipOpinions/SlipOps-2012.html'
self.court_id = self.__module__
def _get_download_urls(self):
return [t for t in self.html.xpath('//table[4]//tr/td[1]//a/@href')]
def _get_neutral_citations(self):
return [t for t in self.html.xpath('//table[4]//tr/td[1]//a/text()')]
def _get_case_names(self):
return [s for s in self.html.xpath('//table[4]//tr[position() > 1]/td[2][../td//a]/text()[1] | //table[4]//tr[position() > 1]/td[2][../td//a]/p/text()[1]')]
def _get_precedential_statuses(self):
return ['Published'] * len(self.case_names)
def _get_case_dates(self):
dates = []
date_formats = ['%m/%d/%Y', '%m/%d/%y']
for date_string in self.html.xpath('//table[4]//tr/td[3][../td//a]/text()'):
for date_format in date_formats:
try:
d = date.fromtimestamp(time.mktime(
time.strptime(date_string, date_format)))
dates.append(d)
break
except ValueError:
continue
return dates
def _get_docket_numbers(self):
docket_numbers = []
for e in self.html.xpath('//table[4]//tr[position() > 1]/td[4][../td//a]'):
docket_numbers.append(html.tostring(
e, method='text', encoding='unicode').strip())
return docket_numbers
def _get_judges(self):
judges = []
for e in self.html.xpath('//table[4]//tr[position() > 1]/td[5][../td//a]'):
s = html.tostring (e, method='text', encoding='unicode')
judges.append(s)
return judges
def _get_nature_of_suit(self):
return [t for t in self.html.xpath('//table[4]//tr/td[6][../td//a]/text()')]
| true | true |
1c2bcd99377144a70c6b4cf337e8494afb4b82be | 1,898 | py | Python | observations/r/sitka89.py | hajime9652/observations | 2c8b1ac31025938cb17762e540f2f592e302d5de | [
"Apache-2.0"
] | 199 | 2017-07-24T01:34:27.000Z | 2022-01-29T00:50:55.000Z | observations/r/sitka89.py | hajime9652/observations | 2c8b1ac31025938cb17762e540f2f592e302d5de | [
"Apache-2.0"
] | 46 | 2017-09-05T19:27:20.000Z | 2019-01-07T09:47:26.000Z | observations/r/sitka89.py | hajime9652/observations | 2c8b1ac31025938cb17762e540f2f592e302d5de | [
"Apache-2.0"
] | 45 | 2017-07-26T00:10:44.000Z | 2022-03-16T20:44:59.000Z | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def sitka89(path):
"""Growth Curves for Sitka Spruce Trees in 1989
The `Sitka89` data frame has 632 rows and 4 columns. It gives repeated
measurements on the log-size of 79 Sitka spruce trees, 54 of which were
grown in ozone-enriched chambers and 25 were controls. The size was
measured eight times in 1989, at roughly monthly intervals.
This data frame contains the following columns:
`size`
measured size (height times diameter squared) of tree, on log scale.
`Time`
time of measurement in days since 1 January 1988.
`tree`
number of tree.
`treat`
either `"ozone"` for an ozone-enriched chamber or `"control"`.
P. J. Diggle, K.-Y. Liang and S. L. Zeger (1994) *Analysis of
Longitudinal Data.* Clarendon Press, Oxford
See Also
~~~~~~~~
Args:
path: str.
Path to directory which either stores file or otherwise file will
be downloaded and extracted there.
Filename is `sitka89.csv`.
Returns:
Tuple of np.ndarray `x_train` with 632 rows and 4 columns and
dictionary `metadata` of column headers (feature names).
"""
import pandas as pd
path = os.path.expanduser(path)
filename = 'sitka89.csv'
if not os.path.exists(os.path.join(path, filename)):
url = 'http://dustintran.com/data/r/MASS/Sitka89.csv'
maybe_download_and_extract(path, url,
save_file_name='sitka89.csv',
resume=False)
data = pd.read_csv(os.path.join(path, filename), index_col=0,
parse_dates=True)
x_train = data.values
metadata = {'columns': data.columns}
return x_train, metadata
| 27.507246 | 74 | 0.685458 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def sitka89(path):
import pandas as pd
path = os.path.expanduser(path)
filename = 'sitka89.csv'
if not os.path.exists(os.path.join(path, filename)):
url = 'http://dustintran.com/data/r/MASS/Sitka89.csv'
maybe_download_and_extract(path, url,
save_file_name='sitka89.csv',
resume=False)
data = pd.read_csv(os.path.join(path, filename), index_col=0,
parse_dates=True)
x_train = data.values
metadata = {'columns': data.columns}
return x_train, metadata
| true | true |
1c2bcda870c9e08e95030504c70d667134630c0e | 4,776 | py | Python | Elastic/searchIndex.py | tohardik/falcon2.0 | 76453360b9735b94a639fc98698900b2591bca9d | [
"MIT"
] | null | null | null | Elastic/searchIndex.py | tohardik/falcon2.0 | 76453360b9735b94a639fc98698900b2591bca9d | [
"MIT"
] | null | null | null | Elastic/searchIndex.py | tohardik/falcon2.0 | 76453360b9735b94a639fc98698900b2591bca9d | [
"MIT"
] | null | null | null | from elasticsearch import Elasticsearch
import editdistance
es = Elasticsearch(hosts=['http://geo-qa.cs.upb.de:9200/'])
entity_index_name = "geoqa-entity"
relation_index_name = "geoqa-relation"
def entitySearch(query):
results = []
###################################################
elasticResults = es.search(index=entity_index_name, body={
"query": {
"match": {"label": query}
}
, "size": 100
}
)
for result in elasticResults['hits']['hits']:
if result["_source"]["label"].lower().replace('.', '').strip() == query.lower().strip():
results.append([result["_source"]["label"], result["_source"]["uri"], result["_score"] * 50, 40])
else:
results.append([result["_source"]["label"], result["_source"]["uri"], result["_score"] * 40, 0])
###################################################
elasticResults = es.search(index=entity_index_name, body={
"query": {
"match": {
"label": {
"query": query,
"fuzziness": "AUTO"
}
}
}, "size": 15
# reduced from 100
}
)
for result in elasticResults['hits']['hits']:
edit_distance = editdistance.eval(result["_source"]["label"].lower().replace('.', '').strip(),
query.lower().strip())
if edit_distance <= 1:
results.append([result["_source"]["label"], result["_source"]["uri"], result["_score"] * 50, 30])
elif edit_distance <= 5:
results.append([result["_source"]["label"], result["_source"]["uri"], result["_score"] * 25, 0])
# else:
# results.append([result["_source"]["label"], result["_source"]["uri"], result["_score"] * 25, 0])
results = sorted(results, key=lambda x: (x[1][x[1].rfind("/")+1:], -x[3], -x[2]))
seen = set()
results = [x for x in results if x[1] not in seen and not seen.add(x[1])]
# results = results[:20]
results = sorted(results, key=lambda x: (-x[3], -x[2], x[1][x[1].rfind("/")+1:]))
return results[:15]
# for result in results['hits']['hits']:
# print (result["_score"])
# print (result["_source"])
# print("-----------")
def propertySearch(query):
results = []
###################################################
elasticResults = es.search(index=relation_index_name, body={
"query": {
"match": {"label": query}
}
, "size": 100
}
)
for result in elasticResults['hits']['hits']:
if result["_source"]["label"].lower().replace('.', '').strip() == query.lower().strip():
results.append([result["_source"]["label"], result["_source"]["uri"], result["_score"] * 50, 40])
else:
results.append([result["_source"]["label"], result["_source"]["uri"], result["_score"] * 40, 0])
###################################################
elasticResults = es.search(index=relation_index_name, body={
"query": {
"match": {
"label": {
"query": query,
"fuzziness": "AUTO"
}
}
}, "size": 10
}
)
for result in elasticResults['hits']['hits']:
edit_distance = editdistance.eval(result["_source"]["label"].lower().replace('.', '').strip(),
query.lower().strip())
if edit_distance <= 1:
results.append([result["_source"]["label"], result["_source"]["uri"], result["_score"] * 50, 40])
elif edit_distance <= 5:
results.append([result["_source"]["label"], result["_source"]["uri"], result["_score"] * 25, 0])
else:
results.append([result["_source"]["label"], result["_source"]["uri"], result["_score"] * 25, 0])
results = sorted(results, key=lambda x: (x[1][x[1].rfind("/") + 1:], -x[3], -x[2]))
seen = set()
results = [x for x in results if x[1] not in seen and not seen.add(x[1])]
# results = results[:20]
results = sorted(results, key=lambda x: (-x[3], -x[2], x[1][x[1].rfind("/")+1:]))
return results[:15]
def propertySearchExactmatch(query):
###################################################
elasticResults = es.search(index=relation_index_name, body={
"query": {
"match": {"label": query}
}
}
)
for result in elasticResults['hits']['hits']:
if result["_source"]["label"].lower().replace('.', '').strip() == query.lower().strip():
return True
return False
| 38.829268 | 110 | 0.479062 | from elasticsearch import Elasticsearch
import editdistance
es = Elasticsearch(hosts=['http://geo-qa.cs.upb.de:9200/'])
entity_index_name = "geoqa-entity"
relation_index_name = "geoqa-relation"
def entitySearch(query):
results = []
| true | true |
1c2bcdd474b8c2c081e8e5279f62cbb67e898626 | 2,430 | py | Python | megfile/utils/mutex.py | yujianpeng66/megfile | 6586c76abb45e07aef1e42ed0d78e7490d08df67 | [
"Apache-2.0",
"MIT"
] | 69 | 2021-08-28T15:03:26.000Z | 2022-03-04T23:43:22.000Z | megfile/utils/mutex.py | yujianpeng66/megfile | 6586c76abb45e07aef1e42ed0d78e7490d08df67 | [
"Apache-2.0",
"MIT"
] | 75 | 2021-08-30T02:36:46.000Z | 2022-03-29T07:59:11.000Z | megfile/utils/mutex.py | yujianpeng66/megfile | 6586c76abb45e07aef1e42ed0d78e7490d08df67 | [
"Apache-2.0",
"MIT"
] | 9 | 2021-08-30T10:46:52.000Z | 2022-01-08T08:26:58.000Z | import os
from abc import ABC, abstractmethod
from functools import wraps
from threading import RLock
from threading import local as _ThreadLocal
from typing import Any, Callable, Iterator
__all__ = [
'ThreadLocal',
'ProcessLocal',
]
class ForkAware(ABC):
def __init__(self):
self._process_id = os.getpid()
self._reset()
def __reduce__(self):
return type(self), ()
@abstractmethod
def _reset(self):
pass # pragma: no cover
def fork_aware(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
if self._process_id != os.getpid():
self._reset()
return func(self, *args, **kwargs)
return wrapper
class BaseLocal(ABC): # pragma: no cover
@property
@abstractmethod
def _data(self) -> dict:
pass
def __getitem__(self, key: str) -> Any:
return self._data[key]
def get(self, key: str, default: Any = None) -> Any:
return self._data.get(key, default)
def __setitem__(self, key: str, value: Any):
self._data[key] = value
def __delitem__(self, key: str):
del self._data[key]
def __contains__(self, key: str) -> bool:
return key in self._data
def __len__(self) -> int:
return len(self._data)
def __iter__(self) -> Iterator:
return iter(self._data)
class ThreadLocal(ForkAware, BaseLocal):
def _reset(self):
self._local = _ThreadLocal()
@property
@fork_aware
def _data(self):
return self._local.__dict__
def __call__(self, key: str, func: Callable, *args, **kwargs):
data = self._data # 不同线程拿到的 dict 不同,因此不用加锁
if key not in data:
data[key] = func(*args, **kwargs)
return data[key]
class ProcessLocal(ForkAware, BaseLocal):
"""
Provides a basic per-process mapping container that wipes itself if the current PID changed since the last get/set.
Aka `threading.local()`, but for processes instead of threads.
"""
_lock = None
def _reset(self):
self._lock = RLock()
self._local = {}
@property
@fork_aware
def _data(self):
return self._local
def __call__(self, key: str, func: Callable, *args, **kwargs) -> Any:
with self._lock:
data = self._data
if key not in data:
data[key] = func(*args, **kwargs)
return data[key]
| 22.71028 | 119 | 0.608642 | import os
from abc import ABC, abstractmethod
from functools import wraps
from threading import RLock
from threading import local as _ThreadLocal
from typing import Any, Callable, Iterator
__all__ = [
'ThreadLocal',
'ProcessLocal',
]
class ForkAware(ABC):
def __init__(self):
self._process_id = os.getpid()
self._reset()
def __reduce__(self):
return type(self), ()
@abstractmethod
def _reset(self):
pass
def fork_aware(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
if self._process_id != os.getpid():
self._reset()
return func(self, *args, **kwargs)
return wrapper
class BaseLocal(ABC):
@property
@abstractmethod
def _data(self) -> dict:
pass
def __getitem__(self, key: str) -> Any:
return self._data[key]
def get(self, key: str, default: Any = None) -> Any:
return self._data.get(key, default)
def __setitem__(self, key: str, value: Any):
self._data[key] = value
def __delitem__(self, key: str):
del self._data[key]
def __contains__(self, key: str) -> bool:
return key in self._data
def __len__(self) -> int:
return len(self._data)
def __iter__(self) -> Iterator:
return iter(self._data)
class ThreadLocal(ForkAware, BaseLocal):
def _reset(self):
self._local = _ThreadLocal()
@property
@fork_aware
def _data(self):
return self._local.__dict__
def __call__(self, key: str, func: Callable, *args, **kwargs):
data = self._data
if key not in data:
data[key] = func(*args, **kwargs)
return data[key]
class ProcessLocal(ForkAware, BaseLocal):
_lock = None
def _reset(self):
self._lock = RLock()
self._local = {}
@property
@fork_aware
def _data(self):
return self._local
def __call__(self, key: str, func: Callable, *args, **kwargs) -> Any:
with self._lock:
data = self._data
if key not in data:
data[key] = func(*args, **kwargs)
return data[key]
| true | true |
1c2bce00fcf67e341b874d95f2ab2bf80fdc16b1 | 66,979 | py | Python | django_evolution/mutations.py | beanbaginc/django-evolution | fb76e44a2361a69a440dca086c0cc67ac6a4300d | [
"BSD-3-Clause"
] | 18 | 2015-02-08T14:48:02.000Z | 2021-08-03T21:07:37.000Z | django_evolution/mutations.py | beanbaginc/django-evolution | fb76e44a2361a69a440dca086c0cc67ac6a4300d | [
"BSD-3-Clause"
] | 4 | 2015-01-07T01:15:08.000Z | 2020-08-06T06:52:13.000Z | django_evolution/mutations.py | beanbaginc/django-evolution | fb76e44a2361a69a440dca086c0cc67ac6a4300d | [
"BSD-3-Clause"
] | 13 | 2015-01-07T01:06:21.000Z | 2022-02-20T16:27:41.000Z | """Support for schema mutation operations and hint output."""
from __future__ import unicode_literals
import inspect
from functools import partial
from django.db import models
from django.db.utils import DEFAULT_DB_ALIAS
from django_evolution.compat import six
from django_evolution.compat.datastructures import OrderedDict
from django_evolution.consts import UpgradeMethod
from django_evolution.db import EvolutionOperationsMulti
from django_evolution.db.sql_result import SQLResult
from django_evolution.db.state import DatabaseState
from django_evolution.errors import (CannotSimulate, SimulationFailure,
EvolutionNotImplementedError)
from django_evolution.mock_models import MockModel, MockRelated, create_field
from django_evolution.signature import (AppSignature,
ConstraintSignature,
FieldSignature,
IndexSignature,
ProjectSignature)
from django_evolution.utils.models import get_database_for_model_name
class Simulation(object):
"""State for a database mutation simulation.
This provides state and utility functions for simulating a mutation on
a database signature. This is provided to :py:meth:`BaseMutation.simulate`
functions, given them access to all simulation state and a consistent way
of failing simulations.
"""
def __init__(self, mutation, app_label, project_sig, database_state,
legacy_app_label=None, database=DEFAULT_DB_ALIAS):
"""Initialize the simulation state.
Args:
mutation (BaseMutation):
The mutation this simulation applies to.
app_label (unicode):
The name of the application this simulation applies to.
project_sig (dict):
The project signature for the simulation to look up and
modify.
database_state (django_evolution.db.state.DatabaseState):
The database state for the simulation to look up and modify.
legacy_app_label (unicode, optional):
The legacy label of the app this simulation applies to.
This is based on the module name and is used in the
transitioning of pre-Django 1.7 signatures.
database (unicode, optional):
The registered database name in Django to simulate operating
on.
"""
assert isinstance(project_sig, ProjectSignature), \
'project_sig must be a ProjectSignature instance'
assert (database_state is None or
isinstance(database_state, DatabaseState)), \
'database_state must be None or a DatabaseState instance'
self.mutation = mutation
self.app_label = app_label
self.legacy_app_label = legacy_app_label or app_label
self.project_sig = project_sig
self.database_state = database_state
self.database = database
def get_evolver(self):
"""Return an evolver for the database.
Returns:
django_evolution.db.EvolutionOperationsMulti:
The database evolver for this type of database.
"""
return EvolutionOperationsMulti(self.database,
self.database_state).get_evolver()
def get_app_sig(self):
"""Return the current application signature.
Returns:
dict:
The application signature.
Returns:
django_evolution.signature.AppSignature:
The signature for the app.
Raises:
django_evolution.errors.SimulationFailure:
A signature could not be found for the application.
"""
app_sig = self.project_sig.get_app_sig(self.app_label)
if (app_sig is None and
self.legacy_app_label is not None and
self.legacy_app_label != self.app_label):
# Check if it can be found by the legacy label.
app_sig = self.project_sig.get_app_sig(self.legacy_app_label)
if app_sig:
return app_sig
self.fail('The application could not be found in the signature.')
def get_model_sig(self, model_name):
"""Return the signature for a model with the given name.
Args:
model_name (unicode):
The name of the model to fetch a signature for.
Returns:
django_evolution.signature.ModelSignature:
The signature for the model.
Raises:
django_evolution.errors.SimulationFailure:
A signature could not be found for the model or its parent
application.
"""
model_sig = self.get_app_sig().get_model_sig(model_name)
if model_sig:
return model_sig
self.fail('The model could not be found in the signature.',
model_name=model_name)
def get_field_sig(self, model_name, field_name):
"""Return the signature for a field with the given name.
Args:
model_name (unicode):
The name of the model containing the field.
field_name (unicode):
The name of the field to fetch a signature for.
Returns:
django_evolution.signature.FieldSignature:
The signature for the field.
Raises:
django_evolution.errors.SimulationFailure:
A signature could not be found for the field, its parent
model, or its parent application.
"""
field_sig = self.get_model_sig(model_name).get_field_sig(field_name)
if field_sig:
return field_sig
self.fail('The field could not be found in the signature.',
model_name=model_name,
field_name=field_name)
def fail(self, error, **error_vars):
"""Fail the simulation.
This will end up raising a
:py:class:`~django_evolution.errors.SimulationFailure` with an error
message based on the mutation's simulation failed message an the
provided message.
Args:
error (unicode):
The error message for this particular failure.
**error_vars (dict):
Variables to include in the error message. These will
override any defaults for the mutation's error.
Raises:
django_evolution.errors.SimulationFailure:
The resulting simulation failure with the given error.
"""
msg = '%s %s' % (self.mutation.simulation_failure_error, error)
error_dict = {
'app_label': self.app_label,
}
error_dict.update(
(key, getattr(self.mutation, value))
for key, value in six.iteritems(self.mutation.error_vars)
)
error_dict.update(error_vars)
raise SimulationFailure(msg % error_dict)
class BaseMutation(object):
"""Base class for a schema mutation.
These are responsible for simulating schema mutations and applying actual
mutations to a database signature.
"""
simulation_failure_error = 'Cannot simulate the mutation.'
error_vars = {}
def generate_hint(self):
"""Return a hinted evolution for the mutation.
This will generate a line that will be used in a hinted evolution
file. This method generally should not be overridden. Instead, use
:py:meth:`get_hint_params`.
Returns:
unicode:
A hinted evolution statement for this mutation.
"""
return '%s(%s)' % (self.__class__.__name__,
', '.join(self.get_hint_params()))
def get_hint_params(self):
"""Return parameters for the mutation's hinted evolution.
Returns:
list of unicode:
A list of parameter strings to pass to the mutation's constructor
in a hinted evolution.
"""
return []
def generate_dependencies(self, app_label, **kwargs):
"""Return automatic dependencies for the parent evolution.
This allows a mutation to affect the order in which the parent
evolution is applied, relative to other evolutions or migrations.
Version Added:
2.1
Args:
app_label (unicode):
The label of the app containing this mutation.
**kwargs (dict):
Additional keyword arguments, for future use.
Returns:
dict:
A dictionary of dependencies. This may have zero or more of the
following keys:
* ``before_migrations``
* ``after_migrations``
* ``before_evolutions``
* ``after_evolutions``
"""
return {}
def run_simulation(self, **kwargs):
"""Run a simulation for a mutation.
This will prepare and execute a simulation on this mutation,
constructing a :py:class:`Simulation` and passing it to
:py:meth:`simulate`. The simulation will apply a mutation on the
provided database signature, modifying it to match the state described
to the mutation. This allows Django Evolution to test evolutions before
they hit the database.
Args:
simulation (Simulation):
The state for the simulation.
Raises:
django_evolution.errors.CannotSimulate:
The simulation cannot be executed for this mutation. The
reason is in the exception's message.
django_evolution.errors.SimulationFailure:
The simulation failed. The reason is in the exception's
message.
"""
self.simulate(Simulation(self, **kwargs))
def simulate(self, simulation):
"""Perform a simulation of a mutation.
This will attempt to perform a mutation on the database signature,
modifying it to match the state described to the mutation. This allows
Django Evolution to test evolutions before they hit the database.
Args:
simulation (Simulation):
The state for the simulation.
Raises:
django_evolution.errors.CannotSimulate:
The simulation cannot be executed for this mutation. The
reason is in the exception's message.
django_evolution.errors.SimulationFailure:
The simulation failed. The reason is in the exception's
message.
"""
raise NotImplementedError
def mutate(self, mutator):
"""Schedule a database mutation on the mutator.
This will instruct the mutator to perform one or more database
mutations for an app. Those will be scheduled and later executed on the
database, if not optimized out.
Args:
mutator (django_evolution.mutators.AppMutator):
The mutator to perform an operation on.
Raises:
django_evolution.errors.EvolutionNotImplementedError:
The configured mutation is not supported on this type of
database.
"""
raise NotImplementedError
def is_mutable(self, app_label, project_sig, database_state, database):
"""Return whether the mutation can be applied to the database.
This should check if the database or parts of the signature matches
the attributes provided to the mutation.
Args:
app_label (unicode):
The label for the Django application to be mutated.
project_sig (dict):
The project's schema signature.
database_state (django_evolution.db.state.DatabaseState):
The database's schema signature.
database (unicode):
The name of the database the operation would be performed on.
Returns:
bool:
``True`` if the mutation can run. ``False`` if it cannot.
"""
return False
def serialize_value(self, value):
"""Serialize a value for use in a mutation statement.
This will attempt to represent the value as something Python can
execute, across Python versions. The string representation of the
value is used by default. If that representation is of a Unicode
string, and that string include a ``u`` prefix, it will be stripped.
Args:
value (object):
The value to serialize.
Returns:
unicode:
The serialized string.
"""
if isinstance(value, six.string_types):
value = repr(six.text_type(value))
if value.startswith('u'):
value = value[1:]
elif isinstance(value, list):
value = '[%s]' % ', '.join(
self.serialize_value(item)
for item in value
)
elif isinstance(value, tuple):
if len(value) == 1:
suffix = ','
else:
suffix = ''
value = '(%s%s)' % (
', '.join(
self.serialize_value(item)
for item in value
),
suffix,
)
elif isinstance(value, dict):
value = '{%s}' % ', '.join(
'%s: %s' % (self.serialize_value(dict_key),
self.serialize_value(dict_value))
for dict_key, dict_value in six.iteritems(value)
)
elif inspect.isclass(value):
if value.__module__.startswith('django.db.models'):
prefix = 'models.'
else:
prefix = ''
return prefix + value.__name__
elif hasattr(value, 'deconstruct'):
path, args, kwargs = value.deconstruct()
if path.startswith('django.db.models'):
path = 'models.%s' % path.rsplit('.', 1)[-1]
parts = ['%s(' % path]
if args:
parts.append(', '.join(
self.serialize_value(arg)
for arg in args
))
if kwargs:
parts.append(', '.join(
self.serialize_attr(key, value)
for key, value in six.iteritems(kwargs)
))
parts.append(')')
value = ''.join(parts)
else:
value = repr(value)
return value
def serialize_attr(self, attr_name, attr_value):
"""Serialize an attribute for use in a mutation statement.
This will create a ``name=value`` string, with the value serialized
using :py:meth:`serialize_value`.
Args:
attr_name (unicode):
The attribute's name.
attr_value (object):
The attribute's value.
Returns:
unicode:
The serialized attribute string.
"""
return '%s=%s' % (attr_name, self.serialize_value(attr_value))
def __hash__(self):
"""Return a hash of this mutation.
Returns:
int:
The mutation's hash.
"""
return id(self)
def __eq__(self, other):
"""Return whether this mutation equals another.
Two mutations are equal if they're of the same type and generate
the same hinted evolution.
Args:
other (BaseMutation):
The mutation to compare against.
Returns:
bool:
``True`` if the mutations are equal. ``False`` if they are not.
"""
return (type(self) is type(other) and
self.generate_hint() == other.generate_hint())
def __str__(self):
"""Return a hinted evolution for the mutation.
Returns:
unicode:
The hinted evolution.
"""
return self.generate_hint()
def __repr__(self):
"""Return a string representation of the mutation.
Returns:
unicode:
A string representation of the mutation.
"""
return '<%s>' % self
class BaseModelMutation(BaseMutation):
"""Base class for a mutation affecting a single model."""
error_vars = dict({
'model_name': 'model_name',
}, **BaseMutation.error_vars)
def __init__(self, model_name):
"""Initialize the mutation.
Args:
model_name (unicode):
The name of the model being mutated.
"""
super(BaseModelMutation, self).__init__()
self.model_name = model_name
def evolver(self, model, database_state, database=None):
if database is None:
database = get_database_for_model_name(model.app_label,
model.model_name)
return EvolutionOperationsMulti(database, database_state).get_evolver()
def mutate(self, mutator, model):
"""Schedule a model mutation on the mutator.
This will instruct the mutator to perform one or more database
mutations for a model. Those will be scheduled and later executed on
the database, if not optimized out.
Args:
mutator (django_evolution.mutators.ModelMutator):
The mutator to perform an operation on.
model (MockModel):
The model being mutated.
Raises:
django_evolution.errors.EvolutionNotImplementedError:
The configured mutation is not supported on this type of
database.
"""
raise NotImplementedError
def is_mutable(self, app_label, project_sig, database_state, database):
"""Return whether the mutation can be applied to the database.
This will if the database matches that of the model.
Args:
app_label (unicode):
The label for the Django application to be mutated.
project_sig (dict, unused):
The project's schema signature.
database_state (django_evolution.db.state.DatabaseState, unused):
The database state.
database (unicode):
The name of the database the operation would be performed on.
Returns:
bool:
``True`` if the mutation can run. ``False`` if it cannot.
"""
db_name = (database or
get_database_for_model_name(app_label, self.model_name))
return db_name and db_name == database
class BaseModelFieldMutation(BaseModelMutation):
"""Base class for any fields that mutate a model.
This is used for classes that perform any mutation on a model. Such
mutations will be provided a model they can work with.
Operations added to the mutator by this field will be associated with that
model. That will allow the operations backend to perform any optimizations
to improve evolution time for the model.
"""
error_vars = dict({
'field_name': 'field_name',
}, **BaseModelMutation.error_vars)
def __init__(self, model_name, field_name):
"""Initialize the mutation.
Args:
model_name (unicode):
The name of the model containing the field.
field_name (unicode):
The name of the field to mutate.
"""
super(BaseModelFieldMutation, self).__init__(model_name)
self.field_name = field_name
class DeleteField(BaseModelFieldMutation):
"""A mutation that deletes a field from a model."""
simulation_failure_error = (
'Cannot delete the field "%(field_name)s" on model '
'"%(app_label)s.%(model_name)s".'
)
def get_hint_params(self):
"""Return parameters for the mutation's hinted evolution.
Returns:
list of unicode:
A list of parameter strings to pass to the mutation's constructor
in a hinted evolution.
"""
return [
self.serialize_value(self.model_name),
self.serialize_value(self.field_name),
]
def simulate(self, simulation):
"""Simulate the mutation.
This will alter the database schema to remove the specified field,
modifying meta fields (``unique_together``) if necessary.
It will also check to make sure this is not a primary key and that
the field exists.
Args:
simulation (Simulation):
The state for the simulation.
Raises:
django_evolution.errors.SimulationFailure:
The simulation failed. The reason is in the exception's
message.
"""
model_sig = simulation.get_model_sig(self.model_name)
field_sig = simulation.get_field_sig(self.model_name, self.field_name)
if field_sig.get_attr_value('primary_key'):
simulation.fail('The field is a primary key and cannot '
'be deleted.')
# If the field was used in the unique_together attribute, update it.
new_unique_together = []
for unique_together_entry in model_sig.unique_together:
new_entry = tuple(
field_name
for field_name in unique_together_entry
if field_name != self.field_name
)
if new_entry:
new_unique_together.append(new_entry)
model_sig.unique_together = new_unique_together
# Simulate the deletion of the field.
model_sig.remove_field_sig(self.field_name)
def mutate(self, mutator, model):
"""Schedule a field deletion on the mutator.
This will instruct the mutator to perform a deletion of a field on
a model. It will be scheduled and later executed on the database, if
not optimized out.
Args:
mutator (django_evolution.mutators.ModelMutator):
The mutator to perform an operation on.
model (MockModel):
The model being mutated.
"""
field_sig = mutator.model_sig.get_field_sig(self.field_name)
field = create_field(project_sig=mutator.project_sig,
field_name=self.field_name,
field_type=field_sig.field_type,
field_attrs=field_sig.field_attrs,
parent_model=model,
related_model=field_sig.related_model)
if isinstance(field, models.ManyToManyField):
mutator.add_sql(
self,
mutator.evolver.delete_table(
field._get_m2m_db_table(model._meta)))
else:
mutator.delete_column(self, field)
class SQLMutation(BaseMutation):
"""A mutation that executes SQL on the database.
Unlike most mutations, this one is largely database-dependent. It allows
arbitrary SQL to be executed. It's recommended that the execution does
not modify the schema of a table (unless it's highly database-specific with
no counterpart in Django Evolution), but rather is limited to things like
populating data.
SQL statements cannot be optimized. Any scheduled database operations
prior to the SQL statement will be executed without any further
optimization. This can lead to longer database evolution times.
"""
def __init__(self, tag, sql, update_func=None):
"""Initialize the mutation.
Args:
tag (unicode):
A unique tag identifying this SQL operation.
sql (unicode):
The SQL to execute.
update_func (callable, optional):
A function to call to simulate updating the database signature.
This is required for :py:meth:`simulate` to work.
"""
super(SQLMutation, self).__init__()
self.tag = tag
self.sql = sql
self.update_func = update_func
def get_hint_params(self):
"""Return parameters for the mutation's hinted evolution.
Returns:
list of unicode:
A list of parameter strings to pass to the mutation's constructor
in a hinted evolution.
"""
return [self.tag]
def simulate(self, simulation):
"""Simulate a mutation for an application.
This will run the :py:attr:`update_func` provided when instantiating
the mutation, passing it ``app_label`` and ``project_sig``. It should
then modify the signature to match what the SQL statement would do.
Args:
simulation (Simulation):
The state for the simulation.
Raises:
django_evolution.errors.CannotSimulate:
:py:attr:`update_func` was not provided or was not a function.
django_evolution.errors.SimulationFailure:
The simulation failed. The reason is in the exception's
message. This would be run by :py:attr:`update_func`.
"""
if callable(self.update_func):
argspec = inspect.getargspec(self.update_func)
if len(argspec.args) == 1 and argspec.args[0] == 'simulation':
# New-style simulation function.
self.update_func(simulation)
return
elif len(argspec.args) == 2:
# Legacy simulation function.
project_sig = simulation.project_sig
serialized_sig = project_sig.serialize(sig_version=1)
self.update_func(simulation.app_label, serialized_sig)
new_project_sig = ProjectSignature.deserialize(serialized_sig)
# We have to reconstruct the existing project signature's state
# based on this.
app_sig_ids = [
app_sig.app_id
for app_sig in new_project_sig.app_sigs
]
for app_sig_id in app_sig_ids:
project_sig.remove_app_sig(app_sig_id)
for app_sig in new_project_sig.app_sigs:
project_sig.add_app_sig(app_sig)
return
raise CannotSimulate(
'SQLMutations must provide an update_func(simulation) or '
'legacy update_func(app_label, project_sig) parameter '
'in order to be simulated.')
def mutate(self, mutator):
"""Schedule a database mutation on the mutator.
This will instruct the mutator to execute the SQL for an app.
Args:
mutator (django_evolution.mutators.AppMutator):
The mutator to perform an operation on.
Raises:
django_evolution.errors.EvolutionNotImplementedError:
The configured mutation is not supported on this type of
database.
"""
mutator.add_sql(self, self.sql)
def is_mutable(self, *args, **kwargs):
"""Return whether the mutation can be applied to the database.
Args:
*args (tuple, unused):
Unused positional arguments.
**kwargs (tuple, unused):
Unused positional arguments.
Returns:
bool:
``True``, always.
"""
return True
class AddField(BaseModelFieldMutation):
"""A mutation that adds a field to a model."""
simulation_failure_error = (
'Cannot add the field "%(field_name)s" to model '
'"%(app_label)s.%(model_name)s".'
)
def __init__(self, model_name, field_name, field_type, initial=None,
**field_attrs):
"""Initialize the mutation.
Args:
model_name (unicode):
The name of the model to add the field to.
field_name (unicode):
The name of the new field.
field_type (cls):
The field class to use. This must be a subclass of
:py:class:`django.db.models.Field`.
initial (object, optional):
The initial value for the field. This is required if non-null.
**field_attrs (dict):
Attributes to set on the field.
"""
super(AddField, self).__init__(model_name, field_name)
self.field_type = field_type
self.field_attrs = field_attrs
self.initial = initial
def get_hint_params(self):
"""Return parameters for the mutation's hinted evolution.
Returns:
list of unicode:
A list of parameter strings to pass to the mutation's constructor
in a hinted evolution.
"""
params = [
self.serialize_attr(key, value)
for key, value in six.iteritems(self.field_attrs)
]
if self.initial is not None:
params.append(self.serialize_attr('initial', self.initial))
return [
self.serialize_value(self.model_name),
self.serialize_value(self.field_name),
self.serialize_value(self.field_type),
] + sorted(params)
def simulate(self, simulation):
"""Simulate the mutation.
This will alter the database schema to add the specified field.
Args:
simulation (Simulation):
The state for the simulation.
Raises:
django_evolution.errors.SimulationFailure:
The simulation failed. The reason is in the exception's
message.
"""
model_sig = simulation.get_model_sig(self.model_name)
if model_sig.get_field_sig(self.field_name) is not None:
simulation.fail('A field with this name already exists.')
if (not issubclass(self.field_type, models.ManyToManyField) and
not self.field_attrs.get('null')
and self.initial is None):
simulation.fail('A non-null initial value must be specified in '
'the mutation.')
field_attrs = self.field_attrs.copy()
related_model = field_attrs.pop('related_model', None)
field_sig = FieldSignature(field_name=self.field_name,
field_type=self.field_type,
field_attrs=field_attrs,
related_model=related_model)
model_sig.add_field_sig(field_sig)
def mutate(self, mutator, model):
"""Schedule a field addition on the mutator.
This will instruct the mutator to add a new field on a model. It will
be scheduled and later executed on the database, if not optimized out.
Args:
mutator (django_evolution.mutators.ModelMutator):
The mutator to perform an operation on.
model (MockModel):
The model being mutated.
"""
if issubclass(self.field_type, models.ManyToManyField):
self.add_m2m_table(mutator, model)
else:
self.add_column(mutator, model)
def add_column(self, mutator, model):
"""Add a standard column to the model.
Args:
mutator (django_evolution.mutators.ModelMutator):
The mutator to perform an operation on.
model (MockModel):
The model being mutated.
"""
field = self._create_field(mutator, model)
mutator.add_column(self, field, self.initial)
def add_m2m_table(self, mutator, model):
"""Add a ManyToMany column to the model and an accompanying table.
Args:
mutator (django_evolution.mutators.ModelMutator):
The mutator to perform an operation on.
model (MockModel):
The model being mutated.
"""
field = self._create_field(mutator, model)
related_app_label, related_model_name = \
self.field_attrs['related_model'].split('.')
related_sig = (
mutator.project_sig
.get_app_sig(related_app_label)
.get_model_sig(related_model_name)
)
related_model = MockModel(project_sig=mutator.project_sig,
app_name=related_app_label,
model_name=related_model_name,
model_sig=related_sig,
db_name=mutator.database)
related = MockRelated(related_model=related_model,
model=model,
field=field)
if hasattr(field, '_get_m2m_column_name'):
# Django < 1.2
field.m2m_column_name = \
partial(field._get_m2m_column_name, related)
field.m2m_reverse_name = \
partial(field._get_m2m_reverse_name, related)
field.m2m_column_name = \
partial(field._get_m2m_attr, related, 'column')
field.m2m_reverse_name = \
partial(field._get_m2m_reverse_attr, related, 'column')
mutator.add_sql(self, mutator.evolver.add_m2m_table(model, field))
def _create_field(self, mutator, parent_model):
"""Create a new field to add to the model.
Args:
mutator (django_evolution.mutators.ModelMutator):
The mutator to perform an operation on.
parent_model (django_evolution.mock_models.MockModel):
The model to add the field to.
Returns:
django.db.models.Field:
The newly-created field.
"""
field_attrs = self.field_attrs.copy()
related_model = field_attrs.pop('related_model', None)
return create_field(project_sig=mutator.project_sig,
field_name=self.field_name,
field_type=self.field_type,
field_attrs=field_attrs,
parent_model=parent_model,
related_model=related_model)
class RenameField(BaseModelFieldMutation):
"""A mutation that renames a field on a model."""
simulation_failure_error = (
'Cannot rename the field "%(field_name)s" on model '
'"%(app_label)s.%(model_name)s".'
)
def __init__(self, model_name, old_field_name, new_field_name,
db_column=None, db_table=None):
"""Initialize the mutation.
Args:
model_name (unicode):
The name of the model to add the field to.
old_field_name (unicode):
The old (existing) name of the field.
new_field_name (unicode):
The new name for the field.
db_column (unicode, optional):
The explicit column name to set for the field.
db_table (object, optional):
The explicit table name to use, if specifying a
:py:class:`~django.db.models.ManyToManyField`.
"""
super(RenameField, self).__init__(model_name, old_field_name)
self.old_field_name = old_field_name
self.new_field_name = new_field_name
self.db_column = db_column
self.db_table = db_table
def get_hint_params(self):
"""Return parameters for the mutation's hinted evolution.
Returns:
list of unicode:
A list of parameter strings to pass to the mutation's constructor
in a hinted evolution.
"""
params = [
self.serialize_value(self.model_name),
self.serialize_value(self.old_field_name),
self.serialize_value(self.new_field_name),
]
if self.db_column:
params.append(self.serialize_attr('db_column', self.db_column))
if self.db_table:
params.append(self.serialize_attr('db_table', self.db_table))
return params
def simulate(self, simulation):
"""Simulate the mutation.
This will alter the database schema to rename the specified field.
Args:
simulation (Simulation):
The state for the simulation.
Raises:
django_evolution.errors.SimulationFailure:
The simulation failed. The reason is in the exception's
message.
"""
model_sig = simulation.get_model_sig(self.model_name)
field_sig = simulation.get_field_sig(self.model_name,
self.old_field_name).clone()
field_sig.field_name = self.new_field_name
if issubclass(field_sig.field_type, models.ManyToManyField):
if self.db_table:
field_sig.field_attrs['db_table'] = self.db_table
else:
field_sig.field_attrs.pop('db_table', None)
elif self.db_column:
field_sig.field_attrs['db_column'] = self.db_column
else:
# db_column and db_table were not specified (or not specified for
# the appropriate field types). Clear the old value if one was set.
# This amounts to resetting the column or table name to the Django
# default name
field_sig.field_attrs.pop('db_column', None)
model_sig.remove_field_sig(self.old_field_name)
model_sig.add_field_sig(field_sig)
def mutate(self, mutator, model):
"""Schedule a field rename on the mutator.
This will instruct the mutator to rename a field on a model. It will be
scheduled and later executed on the database, if not optimized out.
Args:
mutator (django_evolution.mutators.ModelMutator):
The mutator to perform an operation on.
model (MockModel):
The model being mutated.
"""
old_field_sig = mutator.model_sig.get_field_sig(self.old_field_name)
field_type = old_field_sig.field_type
# Duplicate the old field sig, and apply the table/column changes.
new_field_sig = old_field_sig.clone()
if issubclass(old_field_sig.field_type, models.ManyToManyField):
if self.db_table:
new_field_sig.field_attrs['db_table'] = self.db_table
else:
new_field_sig.field_attrs.pop('db_table', None)
elif self.db_column:
new_field_sig.field_attrs['db_column'] = self.db_column
else:
new_field_sig.field_attrs.pop('db_column', None)
# Create the mock field instances.
new_model = MockModel(project_sig=mutator.project_sig,
app_name=mutator.app_label,
model_name=self.model_name,
model_sig=mutator.model_sig,
db_name=mutator.database)
old_field = create_field(project_sig=mutator.project_sig,
field_name=self.old_field_name,
field_type=field_type,
field_attrs=old_field_sig.field_attrs,
related_model=old_field_sig.related_model,
parent_model=new_model)
new_field = create_field(project_sig=mutator.project_sig,
field_name=self.new_field_name,
field_type=field_type,
field_attrs=new_field_sig.field_attrs,
related_model=new_field_sig.related_model,
parent_model=new_model)
evolver = mutator.evolver
if issubclass(field_type, models.ManyToManyField):
old_m2m_table = old_field._get_m2m_db_table(new_model._meta)
new_m2m_table = new_field._get_m2m_db_table(new_model._meta)
sql = evolver.rename_table(new_model, old_m2m_table, new_m2m_table)
else:
sql = evolver.rename_column(new_model, old_field, new_field)
mutator.add_sql(self, sql)
class ChangeField(BaseModelFieldMutation):
"""A mutation that changes attributes on a field on a model."""
simulation_failure_error = (
'Cannot change the field "%(field_name)s" on model '
'"%(app_label)s.%(model_name)s".'
)
def __init__(self, model_name, field_name, initial=None, **field_attrs):
"""Initialize the mutation.
Args:
model_name (unicode):
The name of the model containing the field to change.
field_name (unicode):
The name of the field to change.
initial (object, optional):
The initial value for the field. This is required if non-null.
**field_attrs (dict):
Attributes to set on the field.
"""
super(ChangeField, self).__init__(model_name, field_name)
self.field_attrs = field_attrs
self.initial = initial
def get_hint_params(self):
"""Return parameters for the mutation's hinted evolution.
Returns:
list of unicode:
A list of parameter strings to pass to the mutation's constructor
in a hinted evolution.
"""
params = [
self.serialize_attr(attr_name, attr_value)
for attr_name, attr_value in six.iteritems(self.field_attrs)
] + [
self.serialize_attr('initial', self.initial),
]
return [
self.serialize_value(self.model_name),
self.serialize_value(self.field_name),
] + sorted(params)
def simulate(self, simulation):
"""Simulate the mutation.
This will alter the database schema to change attributes for the
specified field.
Args:
simulation (Simulation):
The state for the simulation.
Raises:
django_evolution.errors.SimulationFailure:
The simulation failed. The reason is in the exception's
message.
"""
field_sig = simulation.get_field_sig(self.model_name, self.field_name)
field_sig.field_attrs.update(self.field_attrs)
if ('null' in self.field_attrs and not self.field_attrs['null'] and
not issubclass(field_sig.field_type, models.ManyToManyField) and
self.initial is None):
simulation.fail('A non-null initial value needs to be specified '
'in the mutation.')
def mutate(self, mutator, model):
"""Schedule a field change on the mutator.
This will instruct the mutator to change attributes on a field on a
model. It will be scheduled and later executed on the database, if not
optimized out.
Args:
mutator (django_evolution.mutators.ModelMutator):
The mutator to perform an operation on.
model (MockModel):
The model being mutated.
"""
field_sig = mutator.model_sig.get_field_sig(self.field_name)
field = model._meta.get_field(self.field_name)
for attr_name in six.iterkeys(self.field_attrs):
if attr_name not in mutator.evolver.supported_change_attrs:
raise EvolutionNotImplementedError(
"ChangeField does not support modifying the '%s' "
"attribute on '%s.%s'."
% (attr_name, self.model_name, self.field_name))
new_field_attrs = {}
for attr_name, attr_value in six.iteritems(self.field_attrs):
old_attr_value = field_sig.get_attr_value(attr_name)
# Avoid useless SQL commands if nothing has changed.
if old_attr_value != attr_value:
new_field_attrs[attr_name] = {
'old_value': old_attr_value,
'new_value': attr_value,
}
if new_field_attrs:
mutator.change_column(self, field, new_field_attrs)
class RenameModel(BaseModelMutation):
"""A mutation that renames a model."""
simulation_failure_error = \
'Cannot rename the model "%(app_label)s.%(model_name)s".'
def __init__(self, old_model_name, new_model_name, db_table):
"""Initialize the mutation.
Args:
old_model_name (unicode):
The old (existing) name of the model to rename.
new_model_name (unicode):
The new name for the model.
db_table (unicode):
The table name in the database for this model.
"""
super(RenameModel, self).__init__(old_model_name)
self.old_model_name = old_model_name
self.new_model_name = new_model_name
self.db_table = db_table
def get_hint_params(self):
"""Return parameters for the mutation's hinted evolution.
Returns:
list of unicode:
A list of parameter strings to pass to the mutation's constructor
in a hinted evolution.
"""
params = [
self.serialize_value(self.old_model_name),
self.serialize_value(self.new_model_name),
]
if self.db_table:
params.append(self.serialize_attr('db_table', self.db_table)),
return params
def simulate(self, simulation):
"""Simulate the mutation.
This will alter the database schema to rename the specified model.
Args:
simulation (Simulation):
The state for the simulation.
Raises:
django_evolution.errors.SimulationFailure:
The simulation failed. The reason is in the exception's
message.
"""
app_sig = simulation.get_app_sig()
model_sig = simulation.get_model_sig(self.old_model_name).clone()
model_sig.model_name = self.new_model_name
model_sig.table_name = self.db_table
app_sig.remove_model_sig(self.old_model_name)
app_sig.add_model_sig(model_sig)
old_related_model = '%s.%s' % (simulation.app_label,
self.old_model_name)
new_related_model = '%s.%s' % (simulation.app_label,
self.new_model_name)
for cur_app_sig in simulation.project_sig.app_sigs:
for cur_model_sig in cur_app_sig.model_sigs:
for cur_field_sig in cur_model_sig.field_sigs:
if cur_field_sig.related_model == old_related_model:
cur_field_sig.related_model = new_related_model
def mutate(self, mutator, model):
"""Schedule a model rename on the mutator.
This will instruct the mutator to rename a model. It will be scheduled
and later executed on the database, if not optimized out.
Args:
mutator (django_evolution.mutators.ModelMutator):
The mutator to perform an operation on.
model (MockModel):
The model being mutated.
"""
old_model_sig = mutator.model_sig
new_model_sig = old_model_sig.clone()
new_model_sig.model_name = self.new_model_name
new_model_sig.table_name = self.db_table
new_model = MockModel(project_sig=mutator.project_sig,
app_name=mutator.app_label,
model_name=self.new_model_name,
model_sig=new_model_sig,
db_name=mutator.database)
mutator.add_sql(
self,
mutator.evolver.rename_table(new_model,
old_model_sig.table_name,
new_model_sig.table_name))
class DeleteModel(BaseModelMutation):
"""A mutation that deletes a model."""
simulation_failure_error = \
'Cannot delete the model "%(app_label)s.%(model_name)s".'
def get_hint_params(self):
"""Return parameters for the mutation's hinted evolution.
Returns:
list of unicode:
A list of parameter strings to pass to the mutation's constructor
in a hinted evolution.
"""
return [self.serialize_value(self.model_name)]
def simulate(self, simulation):
"""Simulate the mutation.
This will alter the database schema to delete the specified model.
Args:
simulation (Simulation):
The state for the simulation.
Raises:
django_evolution.errors.SimulationFailure:
The simulation failed. The reason is in the exception's
message.
"""
app_sig = simulation.get_app_sig()
# Check for the model first, and then delete it.
simulation.get_model_sig(self.model_name)
app_sig.remove_model_sig(self.model_name)
def mutate(self, mutator, model):
"""Schedule a model deletion on the mutator.
This will instruct the mutator to delete a model. It will be scheduled
and later executed on the database, if not optimized out.
Args:
mutator (django_evolution.mutators.ModelMutator):
The mutator to perform an operation on.
model (MockModel):
The model being mutated.
"""
sql_result = SQLResult()
# Remove any many-to-many tables.
for field_sig in mutator.model_sig.field_sigs:
if issubclass(field_sig.field_type, models.ManyToManyField):
field = model._meta.get_field(field_sig.field_name)
m2m_table = field._get_m2m_db_table(model._meta)
sql_result.add(mutator.evolver.delete_table(m2m_table))
# Remove the table itself.
sql_result.add(mutator.evolver.delete_table(model._meta.db_table))
mutator.add_sql(self, sql_result)
class DeleteApplication(BaseMutation):
"""A mutation that deletes an application."""
simulation_failure_error = \
'Cannot delete the application "%(app_label)s".'
def simulate(self, simulation):
"""Simulate the mutation.
This will alter the database schema to delete the specified
application.
Args:
simulation (Simulation):
The state for the simulation.
Raises:
django_evolution.errors.SimulationFailure:
The simulation failed. The reason is in the exception's
message.
"""
if not simulation.database:
return
app_sig = simulation.get_app_sig()
# Simulate the deletion of the models.
for model_sig in list(app_sig.model_sigs):
model_name = model_sig.model_name
mutation = DeleteModel(model_name)
if mutation.is_mutable(app_label=simulation.app_label,
project_sig=simulation.project_sig,
database_state=simulation.database_state,
database=simulation.database):
# Check for the model's existence, and then delete.
simulation.get_model_sig(model_name)
app_sig.remove_model_sig(model_name)
def mutate(self, mutator):
"""Schedule an application deletion on the mutator.
This will instruct the mutator to delete an application, if it exists.
It will be scheduled and later executed on the database, if not
optimized out.
Args:
mutator (django_evolution.mutators.AppMutator):
The mutator to perform an operation on.
"""
# This test will introduce a regression, but we can't afford to remove
# all models at a same time if they aren't owned by the same database
if mutator.database:
app_sig = mutator.project_sig.get_app_sig(mutator.app_label)
for model_sig in list(app_sig.model_sigs):
model_name = model_sig.model_name
mutation = DeleteModel(model_name)
if mutation.is_mutable(app_label=mutator.app_label,
project_sig=mutator.project_sig,
database_state=mutator.database_state,
database=mutator.database):
mutator.run_mutation(mutation)
def is_mutable(self, *args, **kwargs):
"""Return whether the mutation can be applied to the database.
This will always return true. The mutation will safely handle the
application no longer being around.
Args:
*args (tuple, unused):
Positional arguments passed to the function.
**kwargs (dict, unused):
Keyword arguments passed to the function.
Returns:
bool:
``True``, always.
"""
return True
class ChangeMeta(BaseModelMutation):
"""A mutation that changes meta proeprties on a model."""
simulation_failure_error = (
'Cannot change the "%(prop_name)s" meta property on model '
'"%(app_label)s.%(model_name)s".'
)
error_vars = dict({
'prop_name': 'prop_name',
}, **BaseModelMutation.error_vars)
def __init__(self, model_name, prop_name, new_value):
"""Initialize the mutation.
Args:
model_name (unicode):
The name of the model to change meta properties on.
prop_name (unicode):
The name of the property to change.
new_value (object):
The new value for the property.
"""
super(ChangeMeta, self).__init__(model_name)
self.prop_name = prop_name
self.new_value = new_value
def get_hint_params(self):
"""Return parameters for the mutation's hinted evolution.
Returns:
list of unicode:
A list of parameter strings to pass to the mutation's constructor
in a hinted evolution.
"""
if self.prop_name in ('index_together', 'unique_together'):
# Make sure these always appear as lists and not tuples, for
# compatibility.
norm_value = list(self.new_value)
elif self.prop_name == 'constraints':
# Django >= 2.2
norm_value = [
OrderedDict(sorted(six.iteritems(constraint_data),
key=lambda pair: pair[0]))
for constraint_data in self.new_value
]
elif self.prop_name == 'indexes':
# Django >= 1.11
norm_value = [
OrderedDict(sorted(six.iteritems(index_data),
key=lambda pair: pair[0]))
for index_data in self.new_value
]
else:
norm_value = self.new_value
return [
self.serialize_value(self.model_name),
self.serialize_value(self.prop_name),
self.serialize_value(norm_value),
]
def simulate(self, simulation):
"""Simulate the mutation.
This will alter the database schema to change metadata on the specified
model.
Args:
simulation (Simulation):
The state for the simulation.
Raises:
django_evolution.errors.SimulationFailure:
The simulation failed. The reason is in the exception's
message.
"""
model_sig = simulation.get_model_sig(self.model_name)
evolver = simulation.get_evolver()
prop_name = self.prop_name
if not evolver.supported_change_meta.get(prop_name):
simulation.fail('The property cannot be modified on this '
'database.')
if prop_name == 'index_together':
model_sig.index_together = self.new_value
elif prop_name == 'unique_together':
model_sig.unique_together = self.new_value
model_sig._unique_together_applied = True
elif prop_name == 'constraints':
# Django >= 2.2
constraint_sigs = []
for constraint_data in self.new_value:
constraint_attrs = constraint_data.copy()
constraint_attrs.pop('name')
constraint_attrs.pop('type')
constraint_sigs.append(
ConstraintSignature(
name=constraint_data['name'],
constraint_type=constraint_data['type'],
attrs=constraint_attrs))
model_sig.constraint_sigs = constraint_sigs
elif prop_name == 'indexes':
# Django >= 1.11
model_sig.index_sigs = [
IndexSignature(name=index.get('name'),
fields=index['fields'])
for index in self.new_value
]
else:
simulation.fail('The property cannot be changed on a model.')
def mutate(self, mutator, model):
"""Schedule a model meta property change on the mutator.
This will instruct the mutator to change a meta property on a model. It
will be scheduled and later executed on the database, if not optimized
out.
Args:
mutator (django_evolution.mutators.ModelMutator):
The mutator to perform an operation on.
model (MockModel):
The model being mutated.
"""
mutator.change_meta(self, self.prop_name, self.new_value)
class RenameAppLabel(BaseMutation):
"""A mutation that renames the app label for an application."""
def __init__(self, old_app_label, new_app_label, legacy_app_label=None,
model_names=None):
super(RenameAppLabel, self).__init__()
self.old_app_label = old_app_label
self.new_app_label = new_app_label
self.legacy_app_label = legacy_app_label
if model_names is None:
self.model_names = None
else:
self.model_names = set(model_names)
def get_hint_params(self):
params = [
self.serialize_value(self.old_app_label),
self.serialize_value(self.new_app_label),
]
if self.legacy_app_label:
params.append(self.serialize_attr('legacy_app_label',
self.legacy_app_label))
return params
def is_mutable(self, app_label, project_sig, database_state, database):
"""Return whether the mutation can be applied to the database.
Args:
app_label (unicode):
The label for the Django application to be mutated.
project_sig (dict, unused):
The project's schema signature.
database_state (django_evolution.db.state.DatabaseState, unused):
The database state.
database (unicode):
The name of the database the operation would be performed on.
Returns:
bool:
``True`` if the mutation can run. ``False`` if it cannot.
"""
return True
def simulate(self, simulation):
"""Simulate the mutation.
This will alter the signature to make any changes needed for the
application's evolution storage.
"""
old_app_label = self.old_app_label
new_app_label = self.new_app_label
model_names = self.model_names
project_sig = simulation.project_sig
old_app_sig = project_sig.get_app_sig(old_app_label, required=True)
# Begin building the new AppSignature. For at least a short time, both
# the old and new will exist, as we begin moving some or all of the old
# to the new. The old will only be removed if it's empty after the
# rename (so that we don't get rid of anything if there's two apps
# sharing the same old app ID in the signature).
new_app_sig = AppSignature(app_id=new_app_label,
legacy_app_label=self.legacy_app_label,
upgrade_method=UpgradeMethod.EVOLUTIONS)
project_sig.add_app_sig(new_app_sig)
if model_names is None:
# Move over every single model listed under the app's signature.
model_sigs = [
model_sig
for model_sig in old_app_sig.model_sigs
]
else:
# Move over only the requested models, in case the app signature
# has the contents of two separate apps merged. Each will be
# validated by way of simulation.get_model_sig.
model_sigs = [
simulation.get_model_sig(model_name)
for model_name in model_names
]
# Copy over the models.
for model_sig in model_sigs:
old_app_sig.remove_model_sig(model_sig.model_name)
new_app_sig.add_model_sig(model_sig)
if old_app_sig.is_empty():
# The old app is now empty. We can remove the signature.
project_sig.remove_app_sig(old_app_sig.app_id)
# Update the simulation to refer to the new label.
simulation.app_label = new_app_label
# Go through the model signatures and update any that have a
# related_model property referencing the old app label.
for cur_app_sig in project_sig.app_sigs:
for cur_model_sig in cur_app_sig.model_sigs:
for cur_field_sig in cur_model_sig.field_sigs:
if cur_field_sig.related_model:
parts = cur_field_sig.related_model.split('.', 1)[1]
if parts[0] == old_app_label:
cur_field_sig.related_model = \
'%s.%s' % (new_app_label, parts[1])
def mutate(self, mutator):
"""Schedule an app mutation on the mutator.
This will inform the mutator of the new app label, for use in any
future operations.
Args:
mutator (django_evolution.mutators.AppMutator):
The mutator to perform an operation on.
"""
mutator.app_label = self.new_app_label
class MoveToDjangoMigrations(BaseMutation):
"""A mutation that uses Django migrations for an app's future upgrades.
This directs this app to evolve only up until this mutation, and to then
hand any future schema changes over to Django's migrations.
Once this mutation is used, no further mutations can be added for the app.
"""
def __init__(self, mark_applied=['0001_initial']):
"""Initialize the mutation.
Args:
mark_applied (unicode, optional):
The list of migrations to mark as applied. Each of these
should have been covered by the initial table or subsequent
evolutions. By default, this covers the ``0001_initial``
migration.
"""
self.mark_applied = set(mark_applied)
def is_mutable(self, *args, **kwargs):
"""Return whether the mutation can be applied to the database.
Args:
*args (tuple, unused):
Unused positional arguments.
**kwargs (tuple, unused):
Unused positional arguments.
Returns:
bool:
``True``, always.
"""
return True
def generate_dependencies(self, app_label, **kwargs):
"""Return automatic dependencies for the parent evolution.
This will generate a dependency forcing this evolution to apply
before the migrations that are marked as applied, ensuring that
subsequent migrations are applied in the correct order.
Version Added:
2.1
Args:
app_label (unicode):
The label of the app containing this mutation.
**kwargs (dict):
Additional keyword arguments, for future use.
Returns:
dict:
A dictionary of dependencies. This may have zero or more of the
following keys:
* ``before_migrations``
* ``after_migrations``
* ``before_evolutions``
* ``after_evolutions``
"""
# We set this to execute after the migrations to handle the following
# conditions:
#
# 1. If this app is being installed into the database for the first
# time, we want the migrations to handle it, and therefore want
# to make sure those operations happen first. This evolution and
# prior ones in the sequence will themselves be marked as applied,
# but won't make any changes to the database.
#
# 2. If the app was already installed, but this evolution is new and
# being applied for the first time, we'll have already installed
# the equivalent of these migrations that are being marked as
# applied. We'll want to make sure we've properly set up the
# graph for those migrations before we continue on with any
# migrations *after* the ones we're marking as applied. Otherwise,
# the order of dependencies and evolutions can end up being wrong.
return {
'after_migrations': set(
(app_label, migration_name)
for migration_name in self.mark_applied
)
}
def simulate(self, simulation):
"""Simulate the mutation.
This will alter the app's signature to mark it as being handled by
Django migrations.
Args:
simulation (Simulation):
The simulation being performed.
"""
app_sig = simulation.get_app_sig()
app_sig.upgrade_method = UpgradeMethod.MIGRATIONS
app_sig.applied_migrations = self.mark_applied
def mutate(self, mutator):
"""Schedule an app mutation on the mutator.
As this mutation just modifies state on the signature, no actual
database operations are performed.
Args:
mutator (django_evolution.mutators.AppMutator, unused):
The mutator to perform an operation on.
"""
pass
| 34.939489 | 79 | 0.592828 |
from __future__ import unicode_literals
import inspect
from functools import partial
from django.db import models
from django.db.utils import DEFAULT_DB_ALIAS
from django_evolution.compat import six
from django_evolution.compat.datastructures import OrderedDict
from django_evolution.consts import UpgradeMethod
from django_evolution.db import EvolutionOperationsMulti
from django_evolution.db.sql_result import SQLResult
from django_evolution.db.state import DatabaseState
from django_evolution.errors import (CannotSimulate, SimulationFailure,
EvolutionNotImplementedError)
from django_evolution.mock_models import MockModel, MockRelated, create_field
from django_evolution.signature import (AppSignature,
ConstraintSignature,
FieldSignature,
IndexSignature,
ProjectSignature)
from django_evolution.utils.models import get_database_for_model_name
class Simulation(object):
def __init__(self, mutation, app_label, project_sig, database_state,
legacy_app_label=None, database=DEFAULT_DB_ALIAS):
assert isinstance(project_sig, ProjectSignature), \
'project_sig must be a ProjectSignature instance'
assert (database_state is None or
isinstance(database_state, DatabaseState)), \
'database_state must be None or a DatabaseState instance'
self.mutation = mutation
self.app_label = app_label
self.legacy_app_label = legacy_app_label or app_label
self.project_sig = project_sig
self.database_state = database_state
self.database = database
def get_evolver(self):
return EvolutionOperationsMulti(self.database,
self.database_state).get_evolver()
def get_app_sig(self):
app_sig = self.project_sig.get_app_sig(self.app_label)
if (app_sig is None and
self.legacy_app_label is not None and
self.legacy_app_label != self.app_label):
app_sig = self.project_sig.get_app_sig(self.legacy_app_label)
if app_sig:
return app_sig
self.fail('The application could not be found in the signature.')
def get_model_sig(self, model_name):
model_sig = self.get_app_sig().get_model_sig(model_name)
if model_sig:
return model_sig
self.fail('The model could not be found in the signature.',
model_name=model_name)
def get_field_sig(self, model_name, field_name):
field_sig = self.get_model_sig(model_name).get_field_sig(field_name)
if field_sig:
return field_sig
self.fail('The field could not be found in the signature.',
model_name=model_name,
field_name=field_name)
def fail(self, error, **error_vars):
msg = '%s %s' % (self.mutation.simulation_failure_error, error)
error_dict = {
'app_label': self.app_label,
}
error_dict.update(
(key, getattr(self.mutation, value))
for key, value in six.iteritems(self.mutation.error_vars)
)
error_dict.update(error_vars)
raise SimulationFailure(msg % error_dict)
class BaseMutation(object):
simulation_failure_error = 'Cannot simulate the mutation.'
error_vars = {}
def generate_hint(self):
return '%s(%s)' % (self.__class__.__name__,
', '.join(self.get_hint_params()))
def get_hint_params(self):
return []
def generate_dependencies(self, app_label, **kwargs):
return {}
def run_simulation(self, **kwargs):
self.simulate(Simulation(self, **kwargs))
def simulate(self, simulation):
raise NotImplementedError
def mutate(self, mutator):
raise NotImplementedError
def is_mutable(self, app_label, project_sig, database_state, database):
return False
def serialize_value(self, value):
if isinstance(value, six.string_types):
value = repr(six.text_type(value))
if value.startswith('u'):
value = value[1:]
elif isinstance(value, list):
value = '[%s]' % ', '.join(
self.serialize_value(item)
for item in value
)
elif isinstance(value, tuple):
if len(value) == 1:
suffix = ','
else:
suffix = ''
value = '(%s%s)' % (
', '.join(
self.serialize_value(item)
for item in value
),
suffix,
)
elif isinstance(value, dict):
value = '{%s}' % ', '.join(
'%s: %s' % (self.serialize_value(dict_key),
self.serialize_value(dict_value))
for dict_key, dict_value in six.iteritems(value)
)
elif inspect.isclass(value):
if value.__module__.startswith('django.db.models'):
prefix = 'models.'
else:
prefix = ''
return prefix + value.__name__
elif hasattr(value, 'deconstruct'):
path, args, kwargs = value.deconstruct()
if path.startswith('django.db.models'):
path = 'models.%s' % path.rsplit('.', 1)[-1]
parts = ['%s(' % path]
if args:
parts.append(', '.join(
self.serialize_value(arg)
for arg in args
))
if kwargs:
parts.append(', '.join(
self.serialize_attr(key, value)
for key, value in six.iteritems(kwargs)
))
parts.append(')')
value = ''.join(parts)
else:
value = repr(value)
return value
def serialize_attr(self, attr_name, attr_value):
return '%s=%s' % (attr_name, self.serialize_value(attr_value))
def __hash__(self):
return id(self)
def __eq__(self, other):
return (type(self) is type(other) and
self.generate_hint() == other.generate_hint())
def __str__(self):
return self.generate_hint()
def __repr__(self):
return '<%s>' % self
class BaseModelMutation(BaseMutation):
error_vars = dict({
'model_name': 'model_name',
}, **BaseMutation.error_vars)
def __init__(self, model_name):
super(BaseModelMutation, self).__init__()
self.model_name = model_name
def evolver(self, model, database_state, database=None):
if database is None:
database = get_database_for_model_name(model.app_label,
model.model_name)
return EvolutionOperationsMulti(database, database_state).get_evolver()
def mutate(self, mutator, model):
raise NotImplementedError
def is_mutable(self, app_label, project_sig, database_state, database):
db_name = (database or
get_database_for_model_name(app_label, self.model_name))
return db_name and db_name == database
class BaseModelFieldMutation(BaseModelMutation):
error_vars = dict({
'field_name': 'field_name',
}, **BaseModelMutation.error_vars)
def __init__(self, model_name, field_name):
super(BaseModelFieldMutation, self).__init__(model_name)
self.field_name = field_name
class DeleteField(BaseModelFieldMutation):
simulation_failure_error = (
'Cannot delete the field "%(field_name)s" on model '
'"%(app_label)s.%(model_name)s".'
)
def get_hint_params(self):
return [
self.serialize_value(self.model_name),
self.serialize_value(self.field_name),
]
def simulate(self, simulation):
model_sig = simulation.get_model_sig(self.model_name)
field_sig = simulation.get_field_sig(self.model_name, self.field_name)
if field_sig.get_attr_value('primary_key'):
simulation.fail('The field is a primary key and cannot '
'be deleted.')
new_unique_together = []
for unique_together_entry in model_sig.unique_together:
new_entry = tuple(
field_name
for field_name in unique_together_entry
if field_name != self.field_name
)
if new_entry:
new_unique_together.append(new_entry)
model_sig.unique_together = new_unique_together
model_sig.remove_field_sig(self.field_name)
def mutate(self, mutator, model):
field_sig = mutator.model_sig.get_field_sig(self.field_name)
field = create_field(project_sig=mutator.project_sig,
field_name=self.field_name,
field_type=field_sig.field_type,
field_attrs=field_sig.field_attrs,
parent_model=model,
related_model=field_sig.related_model)
if isinstance(field, models.ManyToManyField):
mutator.add_sql(
self,
mutator.evolver.delete_table(
field._get_m2m_db_table(model._meta)))
else:
mutator.delete_column(self, field)
class SQLMutation(BaseMutation):
def __init__(self, tag, sql, update_func=None):
super(SQLMutation, self).__init__()
self.tag = tag
self.sql = sql
self.update_func = update_func
def get_hint_params(self):
return [self.tag]
def simulate(self, simulation):
if callable(self.update_func):
argspec = inspect.getargspec(self.update_func)
if len(argspec.args) == 1 and argspec.args[0] == 'simulation':
self.update_func(simulation)
return
elif len(argspec.args) == 2:
project_sig = simulation.project_sig
serialized_sig = project_sig.serialize(sig_version=1)
self.update_func(simulation.app_label, serialized_sig)
new_project_sig = ProjectSignature.deserialize(serialized_sig)
# based on this.
app_sig_ids = [
app_sig.app_id
for app_sig in new_project_sig.app_sigs
]
for app_sig_id in app_sig_ids:
project_sig.remove_app_sig(app_sig_id)
for app_sig in new_project_sig.app_sigs:
project_sig.add_app_sig(app_sig)
return
raise CannotSimulate(
'SQLMutations must provide an update_func(simulation) or '
'legacy update_func(app_label, project_sig) parameter '
'in order to be simulated.')
def mutate(self, mutator):
mutator.add_sql(self, self.sql)
def is_mutable(self, *args, **kwargs):
return True
class AddField(BaseModelFieldMutation):
simulation_failure_error = (
'Cannot add the field "%(field_name)s" to model '
'"%(app_label)s.%(model_name)s".'
)
def __init__(self, model_name, field_name, field_type, initial=None,
**field_attrs):
super(AddField, self).__init__(model_name, field_name)
self.field_type = field_type
self.field_attrs = field_attrs
self.initial = initial
def get_hint_params(self):
params = [
self.serialize_attr(key, value)
for key, value in six.iteritems(self.field_attrs)
]
if self.initial is not None:
params.append(self.serialize_attr('initial', self.initial))
return [
self.serialize_value(self.model_name),
self.serialize_value(self.field_name),
self.serialize_value(self.field_type),
] + sorted(params)
def simulate(self, simulation):
model_sig = simulation.get_model_sig(self.model_name)
if model_sig.get_field_sig(self.field_name) is not None:
simulation.fail('A field with this name already exists.')
if (not issubclass(self.field_type, models.ManyToManyField) and
not self.field_attrs.get('null')
and self.initial is None):
simulation.fail('A non-null initial value must be specified in '
'the mutation.')
field_attrs = self.field_attrs.copy()
related_model = field_attrs.pop('related_model', None)
field_sig = FieldSignature(field_name=self.field_name,
field_type=self.field_type,
field_attrs=field_attrs,
related_model=related_model)
model_sig.add_field_sig(field_sig)
def mutate(self, mutator, model):
if issubclass(self.field_type, models.ManyToManyField):
self.add_m2m_table(mutator, model)
else:
self.add_column(mutator, model)
def add_column(self, mutator, model):
field = self._create_field(mutator, model)
mutator.add_column(self, field, self.initial)
def add_m2m_table(self, mutator, model):
field = self._create_field(mutator, model)
related_app_label, related_model_name = \
self.field_attrs['related_model'].split('.')
related_sig = (
mutator.project_sig
.get_app_sig(related_app_label)
.get_model_sig(related_model_name)
)
related_model = MockModel(project_sig=mutator.project_sig,
app_name=related_app_label,
model_name=related_model_name,
model_sig=related_sig,
db_name=mutator.database)
related = MockRelated(related_model=related_model,
model=model,
field=field)
if hasattr(field, '_get_m2m_column_name'):
# Django < 1.2
field.m2m_column_name = \
partial(field._get_m2m_column_name, related)
field.m2m_reverse_name = \
partial(field._get_m2m_reverse_name, related)
field.m2m_column_name = \
partial(field._get_m2m_attr, related, 'column')
field.m2m_reverse_name = \
partial(field._get_m2m_reverse_attr, related, 'column')
mutator.add_sql(self, mutator.evolver.add_m2m_table(model, field))
def _create_field(self, mutator, parent_model):
field_attrs = self.field_attrs.copy()
related_model = field_attrs.pop('related_model', None)
return create_field(project_sig=mutator.project_sig,
field_name=self.field_name,
field_type=self.field_type,
field_attrs=field_attrs,
parent_model=parent_model,
related_model=related_model)
class RenameField(BaseModelFieldMutation):
simulation_failure_error = (
'Cannot rename the field "%(field_name)s" on model '
'"%(app_label)s.%(model_name)s".'
)
def __init__(self, model_name, old_field_name, new_field_name,
db_column=None, db_table=None):
super(RenameField, self).__init__(model_name, old_field_name)
self.old_field_name = old_field_name
self.new_field_name = new_field_name
self.db_column = db_column
self.db_table = db_table
def get_hint_params(self):
params = [
self.serialize_value(self.model_name),
self.serialize_value(self.old_field_name),
self.serialize_value(self.new_field_name),
]
if self.db_column:
params.append(self.serialize_attr('db_column', self.db_column))
if self.db_table:
params.append(self.serialize_attr('db_table', self.db_table))
return params
def simulate(self, simulation):
model_sig = simulation.get_model_sig(self.model_name)
field_sig = simulation.get_field_sig(self.model_name,
self.old_field_name).clone()
field_sig.field_name = self.new_field_name
if issubclass(field_sig.field_type, models.ManyToManyField):
if self.db_table:
field_sig.field_attrs['db_table'] = self.db_table
else:
field_sig.field_attrs.pop('db_table', None)
elif self.db_column:
field_sig.field_attrs['db_column'] = self.db_column
else:
# db_column and db_table were not specified (or not specified for
# the appropriate field types). Clear the old value if one was set.
# This amounts to resetting the column or table name to the Django
# default name
field_sig.field_attrs.pop('db_column', None)
model_sig.remove_field_sig(self.old_field_name)
model_sig.add_field_sig(field_sig)
def mutate(self, mutator, model):
old_field_sig = mutator.model_sig.get_field_sig(self.old_field_name)
field_type = old_field_sig.field_type
# Duplicate the old field sig, and apply the table/column changes.
new_field_sig = old_field_sig.clone()
if issubclass(old_field_sig.field_type, models.ManyToManyField):
if self.db_table:
new_field_sig.field_attrs['db_table'] = self.db_table
else:
new_field_sig.field_attrs.pop('db_table', None)
elif self.db_column:
new_field_sig.field_attrs['db_column'] = self.db_column
else:
new_field_sig.field_attrs.pop('db_column', None)
# Create the mock field instances.
new_model = MockModel(project_sig=mutator.project_sig,
app_name=mutator.app_label,
model_name=self.model_name,
model_sig=mutator.model_sig,
db_name=mutator.database)
old_field = create_field(project_sig=mutator.project_sig,
field_name=self.old_field_name,
field_type=field_type,
field_attrs=old_field_sig.field_attrs,
related_model=old_field_sig.related_model,
parent_model=new_model)
new_field = create_field(project_sig=mutator.project_sig,
field_name=self.new_field_name,
field_type=field_type,
field_attrs=new_field_sig.field_attrs,
related_model=new_field_sig.related_model,
parent_model=new_model)
evolver = mutator.evolver
if issubclass(field_type, models.ManyToManyField):
old_m2m_table = old_field._get_m2m_db_table(new_model._meta)
new_m2m_table = new_field._get_m2m_db_table(new_model._meta)
sql = evolver.rename_table(new_model, old_m2m_table, new_m2m_table)
else:
sql = evolver.rename_column(new_model, old_field, new_field)
mutator.add_sql(self, sql)
class ChangeField(BaseModelFieldMutation):
simulation_failure_error = (
'Cannot change the field "%(field_name)s" on model '
'"%(app_label)s.%(model_name)s".'
)
def __init__(self, model_name, field_name, initial=None, **field_attrs):
super(ChangeField, self).__init__(model_name, field_name)
self.field_attrs = field_attrs
self.initial = initial
def get_hint_params(self):
params = [
self.serialize_attr(attr_name, attr_value)
for attr_name, attr_value in six.iteritems(self.field_attrs)
] + [
self.serialize_attr('initial', self.initial),
]
return [
self.serialize_value(self.model_name),
self.serialize_value(self.field_name),
] + sorted(params)
def simulate(self, simulation):
field_sig = simulation.get_field_sig(self.model_name, self.field_name)
field_sig.field_attrs.update(self.field_attrs)
if ('null' in self.field_attrs and not self.field_attrs['null'] and
not issubclass(field_sig.field_type, models.ManyToManyField) and
self.initial is None):
simulation.fail('A non-null initial value needs to be specified '
'in the mutation.')
def mutate(self, mutator, model):
field_sig = mutator.model_sig.get_field_sig(self.field_name)
field = model._meta.get_field(self.field_name)
for attr_name in six.iterkeys(self.field_attrs):
if attr_name not in mutator.evolver.supported_change_attrs:
raise EvolutionNotImplementedError(
"ChangeField does not support modifying the '%s' "
"attribute on '%s.%s'."
% (attr_name, self.model_name, self.field_name))
new_field_attrs = {}
for attr_name, attr_value in six.iteritems(self.field_attrs):
old_attr_value = field_sig.get_attr_value(attr_name)
# Avoid useless SQL commands if nothing has changed.
if old_attr_value != attr_value:
new_field_attrs[attr_name] = {
'old_value': old_attr_value,
'new_value': attr_value,
}
if new_field_attrs:
mutator.change_column(self, field, new_field_attrs)
class RenameModel(BaseModelMutation):
simulation_failure_error = \
'Cannot rename the model "%(app_label)s.%(model_name)s".'
def __init__(self, old_model_name, new_model_name, db_table):
super(RenameModel, self).__init__(old_model_name)
self.old_model_name = old_model_name
self.new_model_name = new_model_name
self.db_table = db_table
def get_hint_params(self):
params = [
self.serialize_value(self.old_model_name),
self.serialize_value(self.new_model_name),
]
if self.db_table:
params.append(self.serialize_attr('db_table', self.db_table)),
return params
def simulate(self, simulation):
app_sig = simulation.get_app_sig()
model_sig = simulation.get_model_sig(self.old_model_name).clone()
model_sig.model_name = self.new_model_name
model_sig.table_name = self.db_table
app_sig.remove_model_sig(self.old_model_name)
app_sig.add_model_sig(model_sig)
old_related_model = '%s.%s' % (simulation.app_label,
self.old_model_name)
new_related_model = '%s.%s' % (simulation.app_label,
self.new_model_name)
for cur_app_sig in simulation.project_sig.app_sigs:
for cur_model_sig in cur_app_sig.model_sigs:
for cur_field_sig in cur_model_sig.field_sigs:
if cur_field_sig.related_model == old_related_model:
cur_field_sig.related_model = new_related_model
def mutate(self, mutator, model):
old_model_sig = mutator.model_sig
new_model_sig = old_model_sig.clone()
new_model_sig.model_name = self.new_model_name
new_model_sig.table_name = self.db_table
new_model = MockModel(project_sig=mutator.project_sig,
app_name=mutator.app_label,
model_name=self.new_model_name,
model_sig=new_model_sig,
db_name=mutator.database)
mutator.add_sql(
self,
mutator.evolver.rename_table(new_model,
old_model_sig.table_name,
new_model_sig.table_name))
class DeleteModel(BaseModelMutation):
simulation_failure_error = \
'Cannot delete the model "%(app_label)s.%(model_name)s".'
def get_hint_params(self):
return [self.serialize_value(self.model_name)]
def simulate(self, simulation):
app_sig = simulation.get_app_sig()
# Check for the model first, and then delete it.
simulation.get_model_sig(self.model_name)
app_sig.remove_model_sig(self.model_name)
def mutate(self, mutator, model):
sql_result = SQLResult()
# Remove any many-to-many tables.
for field_sig in mutator.model_sig.field_sigs:
if issubclass(field_sig.field_type, models.ManyToManyField):
field = model._meta.get_field(field_sig.field_name)
m2m_table = field._get_m2m_db_table(model._meta)
sql_result.add(mutator.evolver.delete_table(m2m_table))
# Remove the table itself.
sql_result.add(mutator.evolver.delete_table(model._meta.db_table))
mutator.add_sql(self, sql_result)
class DeleteApplication(BaseMutation):
simulation_failure_error = \
'Cannot delete the application "%(app_label)s".'
def simulate(self, simulation):
if not simulation.database:
return
app_sig = simulation.get_app_sig()
# Simulate the deletion of the models.
for model_sig in list(app_sig.model_sigs):
model_name = model_sig.model_name
mutation = DeleteModel(model_name)
if mutation.is_mutable(app_label=simulation.app_label,
project_sig=simulation.project_sig,
database_state=simulation.database_state,
database=simulation.database):
# Check for the model's existence, and then delete.
simulation.get_model_sig(model_name)
app_sig.remove_model_sig(model_name)
def mutate(self, mutator):
# all models at a same time if they aren't owned by the same database
if mutator.database:
app_sig = mutator.project_sig.get_app_sig(mutator.app_label)
for model_sig in list(app_sig.model_sigs):
model_name = model_sig.model_name
mutation = DeleteModel(model_name)
if mutation.is_mutable(app_label=mutator.app_label,
project_sig=mutator.project_sig,
database_state=mutator.database_state,
database=mutator.database):
mutator.run_mutation(mutation)
def is_mutable(self, *args, **kwargs):
return True
class ChangeMeta(BaseModelMutation):
simulation_failure_error = (
'Cannot change the "%(prop_name)s" meta property on model '
'"%(app_label)s.%(model_name)s".'
)
error_vars = dict({
'prop_name': 'prop_name',
}, **BaseModelMutation.error_vars)
def __init__(self, model_name, prop_name, new_value):
super(ChangeMeta, self).__init__(model_name)
self.prop_name = prop_name
self.new_value = new_value
def get_hint_params(self):
if self.prop_name in ('index_together', 'unique_together'):
norm_value = list(self.new_value)
elif self.prop_name == 'constraints':
norm_value = [
OrderedDict(sorted(six.iteritems(constraint_data),
key=lambda pair: pair[0]))
for constraint_data in self.new_value
]
elif self.prop_name == 'indexes':
norm_value = [
OrderedDict(sorted(six.iteritems(index_data),
key=lambda pair: pair[0]))
for index_data in self.new_value
]
else:
norm_value = self.new_value
return [
self.serialize_value(self.model_name),
self.serialize_value(self.prop_name),
self.serialize_value(norm_value),
]
def simulate(self, simulation):
model_sig = simulation.get_model_sig(self.model_name)
evolver = simulation.get_evolver()
prop_name = self.prop_name
if not evolver.supported_change_meta.get(prop_name):
simulation.fail('The property cannot be modified on this '
'database.')
if prop_name == 'index_together':
model_sig.index_together = self.new_value
elif prop_name == 'unique_together':
model_sig.unique_together = self.new_value
model_sig._unique_together_applied = True
elif prop_name == 'constraints':
constraint_sigs = []
for constraint_data in self.new_value:
constraint_attrs = constraint_data.copy()
constraint_attrs.pop('name')
constraint_attrs.pop('type')
constraint_sigs.append(
ConstraintSignature(
name=constraint_data['name'],
constraint_type=constraint_data['type'],
attrs=constraint_attrs))
model_sig.constraint_sigs = constraint_sigs
elif prop_name == 'indexes':
model_sig.index_sigs = [
IndexSignature(name=index.get('name'),
fields=index['fields'])
for index in self.new_value
]
else:
simulation.fail('The property cannot be changed on a model.')
def mutate(self, mutator, model):
mutator.change_meta(self, self.prop_name, self.new_value)
class RenameAppLabel(BaseMutation):
def __init__(self, old_app_label, new_app_label, legacy_app_label=None,
model_names=None):
super(RenameAppLabel, self).__init__()
self.old_app_label = old_app_label
self.new_app_label = new_app_label
self.legacy_app_label = legacy_app_label
if model_names is None:
self.model_names = None
else:
self.model_names = set(model_names)
def get_hint_params(self):
params = [
self.serialize_value(self.old_app_label),
self.serialize_value(self.new_app_label),
]
if self.legacy_app_label:
params.append(self.serialize_attr('legacy_app_label',
self.legacy_app_label))
return params
def is_mutable(self, app_label, project_sig, database_state, database):
return True
def simulate(self, simulation):
old_app_label = self.old_app_label
new_app_label = self.new_app_label
model_names = self.model_names
project_sig = simulation.project_sig
old_app_sig = project_sig.get_app_sig(old_app_label, required=True)
# rename (so that we don't get rid of anything if there's two apps
# sharing the same old app ID in the signature).
new_app_sig = AppSignature(app_id=new_app_label,
legacy_app_label=self.legacy_app_label,
upgrade_method=UpgradeMethod.EVOLUTIONS)
project_sig.add_app_sig(new_app_sig)
if model_names is None:
# Move over every single model listed under the app's signature.
model_sigs = [
model_sig
for model_sig in old_app_sig.model_sigs
]
else:
model_sigs = [
simulation.get_model_sig(model_name)
for model_name in model_names
]
for model_sig in model_sigs:
old_app_sig.remove_model_sig(model_sig.model_name)
new_app_sig.add_model_sig(model_sig)
if old_app_sig.is_empty():
project_sig.remove_app_sig(old_app_sig.app_id)
simulation.app_label = new_app_label
for cur_app_sig in project_sig.app_sigs:
for cur_model_sig in cur_app_sig.model_sigs:
for cur_field_sig in cur_model_sig.field_sigs:
if cur_field_sig.related_model:
parts = cur_field_sig.related_model.split('.', 1)[1]
if parts[0] == old_app_label:
cur_field_sig.related_model = \
'%s.%s' % (new_app_label, parts[1])
def mutate(self, mutator):
mutator.app_label = self.new_app_label
class MoveToDjangoMigrations(BaseMutation):
def __init__(self, mark_applied=['0001_initial']):
self.mark_applied = set(mark_applied)
def is_mutable(self, *args, **kwargs):
return True
def generate_dependencies(self, app_label, **kwargs):
#
# 2. If the app was already installed, but this evolution is new and
# being applied for the first time, we'll have already installed
# the order of dependencies and evolutions can end up being wrong.
return {
'after_migrations': set(
(app_label, migration_name)
for migration_name in self.mark_applied
)
}
def simulate(self, simulation):
app_sig = simulation.get_app_sig()
app_sig.upgrade_method = UpgradeMethod.MIGRATIONS
app_sig.applied_migrations = self.mark_applied
def mutate(self, mutator):
pass
| true | true |
1c2bceacda0de761c082d958508ce542e943c8d5 | 9,011 | py | Python | torchvision/models/detection/backbone_utils.py | Oxygen-Chen/vision | b37c8a3ca4c9c626cdac763c6be697231665b0f8 | [
"BSD-3-Clause"
] | 1 | 2021-10-23T01:14:27.000Z | 2021-10-23T01:14:27.000Z | torchvision/models/detection/backbone_utils.py | Oxygen-Chen/vision | b37c8a3ca4c9c626cdac763c6be697231665b0f8 | [
"BSD-3-Clause"
] | null | null | null | torchvision/models/detection/backbone_utils.py | Oxygen-Chen/vision | b37c8a3ca4c9c626cdac763c6be697231665b0f8 | [
"BSD-3-Clause"
] | null | null | null | import warnings
from typing import Callable, Dict, Optional, List, Union
from torch import nn, Tensor
from torchvision.ops import misc as misc_nn_ops
from torchvision.ops.feature_pyramid_network import FeaturePyramidNetwork, LastLevelMaxPool, ExtraFPNBlock
from .. import mobilenet
from .. import resnet
from .._utils import IntermediateLayerGetter
class BackboneWithFPN(nn.Module):
"""
Adds a FPN on top of a model.
Internally, it uses torchvision.models._utils.IntermediateLayerGetter to
extract a submodel that returns the feature maps specified in return_layers.
The same limitations of IntermediateLayerGetter apply here.
Args:
backbone (nn.Module)
return_layers (Dict[name, new_name]): a dict containing the names
of the modules for which the activations will be returned as
the key of the dict, and the value of the dict is the name
of the returned activation (which the user can specify).
in_channels_list (List[int]): number of channels for each feature map
that is returned, in the order they are present in the OrderedDict
out_channels (int): number of channels in the FPN.
Attributes:
out_channels (int): the number of channels in the FPN
"""
def __init__(
self,
backbone: nn.Module,
return_layers: Dict[str, str],
in_channels_list: List[int],
out_channels: int,
extra_blocks: Optional[ExtraFPNBlock] = None,
) -> None:
super(BackboneWithFPN, self).__init__()
if extra_blocks is None:
extra_blocks = LastLevelMaxPool()
self.body = IntermediateLayerGetter(backbone, return_layers=return_layers)
self.fpn = FeaturePyramidNetwork(
in_channels_list=in_channels_list,
out_channels=out_channels,
extra_blocks=extra_blocks,
)
self.out_channels = out_channels
def forward(self, x: Tensor) -> Dict[str, Tensor]:
x = self.body(x)
x = self.fpn(x)
return x
def resnet_fpn_backbone(
backbone_name: str,
pretrained: bool,
norm_layer: Callable[..., nn.Module] = misc_nn_ops.FrozenBatchNorm2d,
trainable_layers: int = 3,
returned_layers: Optional[List[int]] = None,
extra_blocks: Optional[ExtraFPNBlock] = None,
) -> BackboneWithFPN:
"""
Constructs a specified ResNet backbone with FPN on top. Freezes the specified number of layers in the backbone.
Examples::
>>> from torchvision.models.detection.backbone_utils import resnet_fpn_backbone
>>> backbone = resnet_fpn_backbone('resnet50', pretrained=True, trainable_layers=3)
>>> # get some dummy image
>>> x = torch.rand(1,3,64,64)
>>> # compute the output
>>> output = backbone(x)
>>> print([(k, v.shape) for k, v in output.items()])
>>> # returns
>>> [('0', torch.Size([1, 256, 16, 16])),
>>> ('1', torch.Size([1, 256, 8, 8])),
>>> ('2', torch.Size([1, 256, 4, 4])),
>>> ('3', torch.Size([1, 256, 2, 2])),
>>> ('pool', torch.Size([1, 256, 1, 1]))]
Args:
backbone_name (string): resnet architecture. Possible values are 'ResNet', 'resnet18', 'resnet34', 'resnet50',
'resnet101', 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d', 'wide_resnet50_2', 'wide_resnet101_2'
pretrained (bool): If True, returns a model with backbone pre-trained on Imagenet
norm_layer (callable): it is recommended to use the default value. For details visit:
(https://github.com/facebookresearch/maskrcnn-benchmark/issues/267)
trainable_layers (int): number of trainable (not frozen) resnet layers starting from final block.
Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable.
returned_layers (list of int): The layers of the network to return. Each entry must be in ``[1, 4]``.
By default all layers are returned.
extra_blocks (ExtraFPNBlock or None): if provided, extra operations will
be performed. It is expected to take the fpn features, the original
features and the names of the original features as input, and returns
a new list of feature maps and their corresponding names. By
default a ``LastLevelMaxPool`` is used.
"""
backbone = resnet.__dict__[backbone_name](pretrained=pretrained, norm_layer=norm_layer)
return _resnet_fpn_extractor(backbone, trainable_layers, returned_layers, extra_blocks)
def _resnet_fpn_extractor(
backbone: resnet.ResNet,
trainable_layers: int,
returned_layers: Optional[List[int]] = None,
extra_blocks: Optional[ExtraFPNBlock] = None,
) -> BackboneWithFPN:
# select layers that wont be frozen
assert 0 <= trainable_layers <= 5
layers_to_train = ["layer4", "layer3", "layer2", "layer1", "conv1"][:trainable_layers]
if trainable_layers == 5:
layers_to_train.append("bn1")
for name, parameter in backbone.named_parameters():
if all([not name.startswith(layer) for layer in layers_to_train]):
parameter.requires_grad_(False)
if extra_blocks is None:
extra_blocks = LastLevelMaxPool()
if returned_layers is None:
returned_layers = [1, 2, 3, 4]
assert min(returned_layers) > 0 and max(returned_layers) < 5
return_layers = {f"layer{k}": str(v) for v, k in enumerate(returned_layers)}
in_channels_stage2 = backbone.inplanes // 8
in_channels_list = [in_channels_stage2 * 2 ** (i - 1) for i in returned_layers]
out_channels = 256
return BackboneWithFPN(backbone, return_layers, in_channels_list, out_channels, extra_blocks=extra_blocks)
def _validate_trainable_layers(
pretrained: bool,
trainable_backbone_layers: Optional[int],
max_value: int,
default_value: int,
) -> int:
# don't freeze any layers if pretrained model or backbone is not used
if not pretrained:
if trainable_backbone_layers is not None:
warnings.warn(
"Changing trainable_backbone_layers has not effect if "
"neither pretrained nor pretrained_backbone have been set to True, "
"falling back to trainable_backbone_layers={} so that all layers are trainable".format(max_value)
)
trainable_backbone_layers = max_value
# by default freeze first blocks
if trainable_backbone_layers is None:
trainable_backbone_layers = default_value
assert 0 <= trainable_backbone_layers <= max_value
return trainable_backbone_layers
def mobilenet_backbone(
backbone_name: str,
pretrained: bool,
fpn: bool,
norm_layer: Callable[..., nn.Module] = misc_nn_ops.FrozenBatchNorm2d,
trainable_layers: int = 2,
returned_layers: Optional[List[int]] = None,
extra_blocks: Optional[ExtraFPNBlock] = None,
) -> nn.Module:
backbone = mobilenet.__dict__[backbone_name](pretrained=pretrained, norm_layer=norm_layer)
return _mobilenet_extractor(backbone, fpn, trainable_layers, returned_layers, extra_blocks)
def _mobilenet_extractor(
backbone: Union[mobilenet.MobileNetV2, mobilenet.MobileNetV3],
fpn: bool,
trainable_layers,
returned_layers: Optional[List[int]] = None,
extra_blocks: Optional[ExtraFPNBlock] = None,
) -> nn.Module:
backbone = backbone.features
# Gather the indices of blocks which are strided. These are the locations of C1, ..., Cn-1 blocks.
# The first and last blocks are always included because they are the C0 (conv1) and Cn.
stage_indices = [0] + [i for i, b in enumerate(backbone) if getattr(b, "_is_cn", False)] + [len(backbone) - 1]
num_stages = len(stage_indices)
# find the index of the layer from which we wont freeze
assert 0 <= trainable_layers <= num_stages
freeze_before = len(backbone) if trainable_layers == 0 else stage_indices[num_stages - trainable_layers]
for b in backbone[:freeze_before]:
for parameter in b.parameters():
parameter.requires_grad_(False)
out_channels = 256
if fpn:
if extra_blocks is None:
extra_blocks = LastLevelMaxPool()
if returned_layers is None:
returned_layers = [num_stages - 2, num_stages - 1]
assert min(returned_layers) >= 0 and max(returned_layers) < num_stages
return_layers = {f"{stage_indices[k]}": str(v) for v, k in enumerate(returned_layers)}
in_channels_list = [backbone[stage_indices[i]].out_channels for i in returned_layers]
return BackboneWithFPN(backbone, return_layers, in_channels_list, out_channels, extra_blocks=extra_blocks)
else:
m = nn.Sequential(
backbone,
# depthwise linear combination of channels to reduce their size
nn.Conv2d(backbone[-1].out_channels, out_channels, 1),
)
m.out_channels = out_channels # type: ignore[assignment]
return m
| 42.305164 | 118 | 0.678948 | import warnings
from typing import Callable, Dict, Optional, List, Union
from torch import nn, Tensor
from torchvision.ops import misc as misc_nn_ops
from torchvision.ops.feature_pyramid_network import FeaturePyramidNetwork, LastLevelMaxPool, ExtraFPNBlock
from .. import mobilenet
from .. import resnet
from .._utils import IntermediateLayerGetter
class BackboneWithFPN(nn.Module):
def __init__(
self,
backbone: nn.Module,
return_layers: Dict[str, str],
in_channels_list: List[int],
out_channels: int,
extra_blocks: Optional[ExtraFPNBlock] = None,
) -> None:
super(BackboneWithFPN, self).__init__()
if extra_blocks is None:
extra_blocks = LastLevelMaxPool()
self.body = IntermediateLayerGetter(backbone, return_layers=return_layers)
self.fpn = FeaturePyramidNetwork(
in_channels_list=in_channels_list,
out_channels=out_channels,
extra_blocks=extra_blocks,
)
self.out_channels = out_channels
def forward(self, x: Tensor) -> Dict[str, Tensor]:
x = self.body(x)
x = self.fpn(x)
return x
def resnet_fpn_backbone(
backbone_name: str,
pretrained: bool,
norm_layer: Callable[..., nn.Module] = misc_nn_ops.FrozenBatchNorm2d,
trainable_layers: int = 3,
returned_layers: Optional[List[int]] = None,
extra_blocks: Optional[ExtraFPNBlock] = None,
) -> BackboneWithFPN:
backbone = resnet.__dict__[backbone_name](pretrained=pretrained, norm_layer=norm_layer)
return _resnet_fpn_extractor(backbone, trainable_layers, returned_layers, extra_blocks)
def _resnet_fpn_extractor(
backbone: resnet.ResNet,
trainable_layers: int,
returned_layers: Optional[List[int]] = None,
extra_blocks: Optional[ExtraFPNBlock] = None,
) -> BackboneWithFPN:
assert 0 <= trainable_layers <= 5
layers_to_train = ["layer4", "layer3", "layer2", "layer1", "conv1"][:trainable_layers]
if trainable_layers == 5:
layers_to_train.append("bn1")
for name, parameter in backbone.named_parameters():
if all([not name.startswith(layer) for layer in layers_to_train]):
parameter.requires_grad_(False)
if extra_blocks is None:
extra_blocks = LastLevelMaxPool()
if returned_layers is None:
returned_layers = [1, 2, 3, 4]
assert min(returned_layers) > 0 and max(returned_layers) < 5
return_layers = {f"layer{k}": str(v) for v, k in enumerate(returned_layers)}
in_channels_stage2 = backbone.inplanes // 8
in_channels_list = [in_channels_stage2 * 2 ** (i - 1) for i in returned_layers]
out_channels = 256
return BackboneWithFPN(backbone, return_layers, in_channels_list, out_channels, extra_blocks=extra_blocks)
def _validate_trainable_layers(
pretrained: bool,
trainable_backbone_layers: Optional[int],
max_value: int,
default_value: int,
) -> int:
if not pretrained:
if trainable_backbone_layers is not None:
warnings.warn(
"Changing trainable_backbone_layers has not effect if "
"neither pretrained nor pretrained_backbone have been set to True, "
"falling back to trainable_backbone_layers={} so that all layers are trainable".format(max_value)
)
trainable_backbone_layers = max_value
# by default freeze first blocks
if trainable_backbone_layers is None:
trainable_backbone_layers = default_value
assert 0 <= trainable_backbone_layers <= max_value
return trainable_backbone_layers
def mobilenet_backbone(
backbone_name: str,
pretrained: bool,
fpn: bool,
norm_layer: Callable[..., nn.Module] = misc_nn_ops.FrozenBatchNorm2d,
trainable_layers: int = 2,
returned_layers: Optional[List[int]] = None,
extra_blocks: Optional[ExtraFPNBlock] = None,
) -> nn.Module:
backbone = mobilenet.__dict__[backbone_name](pretrained=pretrained, norm_layer=norm_layer)
return _mobilenet_extractor(backbone, fpn, trainable_layers, returned_layers, extra_blocks)
def _mobilenet_extractor(
backbone: Union[mobilenet.MobileNetV2, mobilenet.MobileNetV3],
fpn: bool,
trainable_layers,
returned_layers: Optional[List[int]] = None,
extra_blocks: Optional[ExtraFPNBlock] = None,
) -> nn.Module:
backbone = backbone.features
# Gather the indices of blocks which are strided. These are the locations of C1, ..., Cn-1 blocks.
# The first and last blocks are always included because they are the C0 (conv1) and Cn.
stage_indices = [0] + [i for i, b in enumerate(backbone) if getattr(b, "_is_cn", False)] + [len(backbone) - 1]
num_stages = len(stage_indices)
# find the index of the layer from which we wont freeze
assert 0 <= trainable_layers <= num_stages
freeze_before = len(backbone) if trainable_layers == 0 else stage_indices[num_stages - trainable_layers]
for b in backbone[:freeze_before]:
for parameter in b.parameters():
parameter.requires_grad_(False)
out_channels = 256
if fpn:
if extra_blocks is None:
extra_blocks = LastLevelMaxPool()
if returned_layers is None:
returned_layers = [num_stages - 2, num_stages - 1]
assert min(returned_layers) >= 0 and max(returned_layers) < num_stages
return_layers = {f"{stage_indices[k]}": str(v) for v, k in enumerate(returned_layers)}
in_channels_list = [backbone[stage_indices[i]].out_channels for i in returned_layers]
return BackboneWithFPN(backbone, return_layers, in_channels_list, out_channels, extra_blocks=extra_blocks)
else:
m = nn.Sequential(
backbone,
# depthwise linear combination of channels to reduce their size
nn.Conv2d(backbone[-1].out_channels, out_channels, 1),
)
m.out_channels = out_channels # type: ignore[assignment]
return m
| true | true |
1c2bcfe9bb399413031680f32f453d69c06781b7 | 8,336 | py | Python | doclabel/core/migrations/0001_initial.py | sondh0127/doclabel | 2cadea9fc925435aea49ac0b56c29474664ade4e | [
"MIT"
] | null | null | null | doclabel/core/migrations/0001_initial.py | sondh0127/doclabel | 2cadea9fc925435aea49ac0b56c29474664ade4e | [
"MIT"
] | null | null | null | doclabel/core/migrations/0001_initial.py | sondh0127/doclabel | 2cadea9fc925435aea49ac0b56c29474664ade4e | [
"MIT"
] | null | null | null | # Generated by Django 2.2.6 on 2019-10-24 13:09
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('contenttypes', '0002_remove_content_type_name'),
]
operations = [
migrations.CreateModel(
name='Project',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('description', models.TextField(default='')),
('guideline', models.TextField(default='')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('project_type', models.CharField(choices=[('DocumentClassification', 'document classification'), ('SequenceLabeling', 'sequence labeling'), ('Seq2seq', 'sequence to sequence')], max_length=30)),
('randomize_document_order', models.BooleanField(default=False)),
('collaborative_annotation', models.BooleanField(default=False)),
('polymorphic_ctype', models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='polymorphic_core.project_set+', to='contenttypes.ContentType')),
('users', models.ManyToManyField(related_name='projects', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
),
migrations.CreateModel(
name='Seq2seqProject',
fields=[
('project_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.Project')),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
bases=('core.project',),
),
migrations.CreateModel(
name='SequenceLabelingProject',
fields=[
('project_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.Project')),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
bases=('core.project',),
),
migrations.CreateModel(
name='TextClassificationProject',
fields=[
('project_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.Project')),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
bases=('core.project',),
),
migrations.CreateModel(
name='Label',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('text', models.CharField(max_length=100)),
('prefix_key', models.CharField(blank=True, choices=[('ctrl', 'ctrl'), ('shift', 'shift'), ('ctrl shift', 'ctrl shift')], max_length=10, null=True)),
('suffix_key', models.CharField(blank=True, choices=[('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'd'), ('e', 'e'), ('f', 'f'), ('g', 'g'), ('h', 'h'), ('i', 'i'), ('j', 'j'), ('k', 'k'), ('l', 'l'), ('m', 'm'), ('n', 'n'), ('o', 'o'), ('p', 'p'), ('q', 'q'), ('r', 'r'), ('s', 's'), ('t', 't'), ('u', 'u'), ('v', 'v'), ('w', 'w'), ('x', 'x'), ('y', 'y'), ('z', 'z')], max_length=1, null=True)),
('background_color', models.CharField(default='#209cee', max_length=7)),
('text_color', models.CharField(default='#ffffff', max_length=7)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='labels', to='core.Project')),
],
options={
'unique_together': {('project', 'text')},
},
),
migrations.CreateModel(
name='Document',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('text', models.TextField()),
('meta', models.TextField(default='{}')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('annotations_approved_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='documents', to='core.Project')),
],
),
migrations.CreateModel(
name='SequenceAnnotation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('prob', models.FloatField(default=0.0)),
('manual', models.BooleanField(default=False)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('start_offset', models.IntegerField()),
('end_offset', models.IntegerField()),
('document', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='seq_annotations', to='core.Document')),
('label', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Label')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'unique_together': {('document', 'user', 'label', 'start_offset', 'end_offset')},
},
),
migrations.CreateModel(
name='Seq2seqAnnotation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('prob', models.FloatField(default=0.0)),
('manual', models.BooleanField(default=False)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('text', models.CharField(max_length=500)),
('document', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='seq2seq_annotations', to='core.Document')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'unique_together': {('document', 'user', 'text')},
},
),
migrations.CreateModel(
name='DocumentAnnotation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('prob', models.FloatField(default=0.0)),
('manual', models.BooleanField(default=False)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('document', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='doc_annotations', to='core.Document')),
('label', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Label')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'unique_together': {('document', 'user', 'label')},
},
),
]
| 55.205298 | 408 | 0.568738 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('contenttypes', '0002_remove_content_type_name'),
]
operations = [
migrations.CreateModel(
name='Project',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('description', models.TextField(default='')),
('guideline', models.TextField(default='')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('project_type', models.CharField(choices=[('DocumentClassification', 'document classification'), ('SequenceLabeling', 'sequence labeling'), ('Seq2seq', 'sequence to sequence')], max_length=30)),
('randomize_document_order', models.BooleanField(default=False)),
('collaborative_annotation', models.BooleanField(default=False)),
('polymorphic_ctype', models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='polymorphic_core.project_set+', to='contenttypes.ContentType')),
('users', models.ManyToManyField(related_name='projects', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
),
migrations.CreateModel(
name='Seq2seqProject',
fields=[
('project_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.Project')),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
bases=('core.project',),
),
migrations.CreateModel(
name='SequenceLabelingProject',
fields=[
('project_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.Project')),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
bases=('core.project',),
),
migrations.CreateModel(
name='TextClassificationProject',
fields=[
('project_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.Project')),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
bases=('core.project',),
),
migrations.CreateModel(
name='Label',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('text', models.CharField(max_length=100)),
('prefix_key', models.CharField(blank=True, choices=[('ctrl', 'ctrl'), ('shift', 'shift'), ('ctrl shift', 'ctrl shift')], max_length=10, null=True)),
('suffix_key', models.CharField(blank=True, choices=[('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'd'), ('e', 'e'), ('f', 'f'), ('g', 'g'), ('h', 'h'), ('i', 'i'), ('j', 'j'), ('k', 'k'), ('l', 'l'), ('m', 'm'), ('n', 'n'), ('o', 'o'), ('p', 'p'), ('q', 'q'), ('r', 'r'), ('s', 's'), ('t', 't'), ('u', 'u'), ('v', 'v'), ('w', 'w'), ('x', 'x'), ('y', 'y'), ('z', 'z')], max_length=1, null=True)),
('background_color', models.CharField(default='#209cee', max_length=7)),
('text_color', models.CharField(default='#ffffff', max_length=7)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='labels', to='core.Project')),
],
options={
'unique_together': {('project', 'text')},
},
),
migrations.CreateModel(
name='Document',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('text', models.TextField()),
('meta', models.TextField(default='{}')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('annotations_approved_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='documents', to='core.Project')),
],
),
migrations.CreateModel(
name='SequenceAnnotation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('prob', models.FloatField(default=0.0)),
('manual', models.BooleanField(default=False)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('start_offset', models.IntegerField()),
('end_offset', models.IntegerField()),
('document', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='seq_annotations', to='core.Document')),
('label', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Label')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'unique_together': {('document', 'user', 'label', 'start_offset', 'end_offset')},
},
),
migrations.CreateModel(
name='Seq2seqAnnotation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('prob', models.FloatField(default=0.0)),
('manual', models.BooleanField(default=False)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('text', models.CharField(max_length=500)),
('document', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='seq2seq_annotations', to='core.Document')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'unique_together': {('document', 'user', 'text')},
},
),
migrations.CreateModel(
name='DocumentAnnotation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('prob', models.FloatField(default=0.0)),
('manual', models.BooleanField(default=False)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('document', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='doc_annotations', to='core.Document')),
('label', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Label')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'unique_together': {('document', 'user', 'label')},
},
),
]
| true | true |
1c2bd07b68bc5cdf7a5a5d3c69cee0798eb78adc | 2,806 | py | Python | torstack/core/rest.py | longniao/torstack | 148139eeca0f3cd8a8c2196ae2a6f8cea519d9b5 | [
"MIT"
] | 7 | 2018-12-11T03:41:04.000Z | 2018-12-11T06:08:45.000Z | torstack/core/rest.py | longniao/torstack | 148139eeca0f3cd8a8c2196ae2a6f8cea519d9b5 | [
"MIT"
] | null | null | null | torstack/core/rest.py | longniao/torstack | 148139eeca0f3cd8a8c2196ae2a6f8cea519d9b5 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
'''
torstack.core.session
Basic token definition.
:copyright: (c) 2018 by longniao <longniao@gmail.com>
:license: MIT, see LICENSE for more details.
'''
from torstack.core.session import CoreSession
class CoreRest(object):
REST_CONFIG = dict()
HEADER_CONFIG = dict()
RESPONSE_CONFIG = dict()
def __init__(self, driver, config={}):
self.__init_config(config)
self.__init_driver(driver)
def __init_config(self, config={}):
'''
Init rest configurations.
:param self:
:param config:
:return:
'''
rest_config = config['rest']
header_config = config['rest_header']
response_config = config['rest_response']
if config:
self.REST_CONFIG.update(rest_config)
if header_config:
self.HEADER_CONFIG.update(header_config)
if response_config:
self.RESPONSE_CONFIG.update(response_config)
def __init_driver(self, driver):
'''
setup rest driver.
:return:
'''
if driver:
self.driver = driver
else:
from torstack.storage.sync_file import SyncFile
self.driver = SyncFile()
def _generate_token(self, blength=36):
'''
generate token
:param blength:
:return:
'''
return EncipherLibrary.gen_token(blength)
def get(self, key, default=None):
'''
Return token value with name as key.
:param key:
:param default:
:return:
'''
value = self.driver.get(key)
if value:
if isinstance(value, str):
return value
else:
return value.decode('utf-8')
else:
return default
def set(self, key, value):
'''
Add/Update token value
:param key:
:param value:
:return:
'''
if isinstance(value, str):
token_string = value
elif isinstance(value, dict):
token_string = json.dumps(value)
elif isinstance(value, object):
token_string = json.dumps(value.__dict__)
else:
raise BaseException('10001', 'error data format: %s.' % str(value))
self.driver.save(key, token_string, self.REST_CONFIG['lifetime'])
def delete(self, key):
'''
Delete token key-value pair
:param key:
:return:
'''
return self.driver.delete(key)
def new_token(self):
'''
:return: new token
'''
return self._generate_token(36)
@property
def headers(self):
return self.HEADER_CONFIG
@property
def response(self):
return self.RESPONSE_CONFIG | 24.831858 | 79 | 0.557377 |
from torstack.core.session import CoreSession
class CoreRest(object):
REST_CONFIG = dict()
HEADER_CONFIG = dict()
RESPONSE_CONFIG = dict()
def __init__(self, driver, config={}):
self.__init_config(config)
self.__init_driver(driver)
def __init_config(self, config={}):
rest_config = config['rest']
header_config = config['rest_header']
response_config = config['rest_response']
if config:
self.REST_CONFIG.update(rest_config)
if header_config:
self.HEADER_CONFIG.update(header_config)
if response_config:
self.RESPONSE_CONFIG.update(response_config)
def __init_driver(self, driver):
if driver:
self.driver = driver
else:
from torstack.storage.sync_file import SyncFile
self.driver = SyncFile()
def _generate_token(self, blength=36):
return EncipherLibrary.gen_token(blength)
def get(self, key, default=None):
value = self.driver.get(key)
if value:
if isinstance(value, str):
return value
else:
return value.decode('utf-8')
else:
return default
def set(self, key, value):
if isinstance(value, str):
token_string = value
elif isinstance(value, dict):
token_string = json.dumps(value)
elif isinstance(value, object):
token_string = json.dumps(value.__dict__)
else:
raise BaseException('10001', 'error data format: %s.' % str(value))
self.driver.save(key, token_string, self.REST_CONFIG['lifetime'])
def delete(self, key):
return self.driver.delete(key)
def new_token(self):
return self._generate_token(36)
@property
def headers(self):
return self.HEADER_CONFIG
@property
def response(self):
return self.RESPONSE_CONFIG | true | true |
1c2bd15b25f8553f85262487587573b094708e24 | 4,723 | py | Python | lib/molecule/shell.py | santiagoroman/molecule | 4565cce0ea1f9b1e2dc3fb2aa668715ae466d534 | [
"MIT"
] | null | null | null | lib/molecule/shell.py | santiagoroman/molecule | 4565cce0ea1f9b1e2dc3fb2aa668715ae466d534 | [
"MIT"
] | null | null | null | lib/molecule/shell.py | santiagoroman/molecule | 4565cce0ea1f9b1e2dc3fb2aa668715ae466d534 | [
"MIT"
] | null | null | null | # Copyright (c) 2015-2018 Cisco Systems, Inc.
#
# 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.
"""Molecule Shell Module."""
import sys
from functools import lru_cache
import click
import click_completion
import pkg_resources
from click_help_colors import _colorize
import molecule
from molecule import command
from molecule.api import drivers
from molecule.command.base import click_group_ex
from molecule.config import MOLECULE_DEBUG, ansible_version
from molecule.util import lookup_config_file
click_completion.init()
LOCAL_CONFIG_SEARCH = ".config/molecule/config.yml"
LOCAL_CONFIG = lookup_config_file(LOCAL_CONFIG_SEARCH)
ENV_FILE = ".env.yml"
@lru_cache()
def _version_string() -> str:
v = pkg_resources.parse_version(molecule.__version__)
color = "bright_yellow" if v.is_prerelease else "green" # type: ignore
msg = "molecule %s\n" % _colorize(molecule.__version__, color)
details = f" ansible:{ansible_version()} python:{sys.version_info[0]}.{sys.version_info[1]}"
for driver in drivers():
details += f"\n {driver}:{driver.version} from {driver.module}"
msg += _colorize(details, "bright_black")
return msg
@click_group_ex() # type: ignore
@click.option(
"--debug/--no-debug",
default=MOLECULE_DEBUG,
help="Enable or disable debug mode. Default is disabled.",
)
@click.option(
"--base-config",
"-c",
default=LOCAL_CONFIG,
help=(
"Path to a base config. If provided Molecule will load "
"this config first, and deep merge each scenario's "
"molecule.yml on top. By default Molecule is looking for "
"'{}' "
"in current VCS repository and if not found it will look "
"in user home. ({})"
).format(LOCAL_CONFIG_SEARCH, LOCAL_CONFIG),
)
@click.option(
"--env-file",
"-e",
default=ENV_FILE,
help=("The file to read variables from when rendering molecule.yml. " "(.env.yml)"),
)
@click.version_option(
prog_name="molecule", version=molecule.__version__, message=_version_string()
) # type: ignore
@click.pass_context
def main(ctx, debug, base_config, env_file): # pragma: no cover
"""
Molecule aids in the development and testing of Ansible roles.
Enable autocomplete issue:
eval "$(_MOLECULE_COMPLETE=source molecule)"
"""
ctx.obj = {}
ctx.obj["args"] = {}
ctx.obj["args"]["debug"] = debug
ctx.obj["args"]["base_config"] = base_config
ctx.obj["args"]["env_file"] = env_file
# runtime environment checks to avoid delayed failures
if sys.version_info[0] > 2:
try:
if pkg_resources.get_distribution("futures"):
raise SystemExit(
"FATAL: futures package found, this package should not be installed in a Python 3 environment, please remove it. See https://github.com/agronholm/pythonfutures/issues/90"
)
except pkg_resources.DistributionNotFound:
pass
main.add_command(command.cleanup.cleanup)
main.add_command(command.check.check)
main.add_command(command.converge.converge)
main.add_command(command.create.create)
main.add_command(command.dependency.dependency)
main.add_command(command.destroy.destroy)
main.add_command(command.drivers.drivers)
main.add_command(command.idempotence.idempotence)
main.add_command(command.init.init)
main.add_command(command.lint.lint)
main.add_command(command.list.list)
main.add_command(command.login.login)
main.add_command(command.matrix.matrix)
main.add_command(command.prepare.prepare)
main.add_command(command.reset.reset)
main.add_command(command.side_effect.side_effect)
main.add_command(command.syntax.syntax)
main.add_command(command.test.test)
main.add_command(command.verify.verify)
| 35.780303 | 186 | 0.735973 |
import sys
from functools import lru_cache
import click
import click_completion
import pkg_resources
from click_help_colors import _colorize
import molecule
from molecule import command
from molecule.api import drivers
from molecule.command.base import click_group_ex
from molecule.config import MOLECULE_DEBUG, ansible_version
from molecule.util import lookup_config_file
click_completion.init()
LOCAL_CONFIG_SEARCH = ".config/molecule/config.yml"
LOCAL_CONFIG = lookup_config_file(LOCAL_CONFIG_SEARCH)
ENV_FILE = ".env.yml"
@lru_cache()
def _version_string() -> str:
v = pkg_resources.parse_version(molecule.__version__)
color = "bright_yellow" if v.is_prerelease else "green"
msg = "molecule %s\n" % _colorize(molecule.__version__, color)
details = f" ansible:{ansible_version()} python:{sys.version_info[0]}.{sys.version_info[1]}"
for driver in drivers():
details += f"\n {driver}:{driver.version} from {driver.module}"
msg += _colorize(details, "bright_black")
return msg
@click_group_ex()
@click.option(
"--debug/--no-debug",
default=MOLECULE_DEBUG,
help="Enable or disable debug mode. Default is disabled.",
)
@click.option(
"--base-config",
"-c",
default=LOCAL_CONFIG,
help=(
"Path to a base config. If provided Molecule will load "
"this config first, and deep merge each scenario's "
"molecule.yml on top. By default Molecule is looking for "
"'{}' "
"in current VCS repository and if not found it will look "
"in user home. ({})"
).format(LOCAL_CONFIG_SEARCH, LOCAL_CONFIG),
)
@click.option(
"--env-file",
"-e",
default=ENV_FILE,
help=("The file to read variables from when rendering molecule.yml. " "(.env.yml)"),
)
@click.version_option(
prog_name="molecule", version=molecule.__version__, message=_version_string()
) # type: ignore
@click.pass_context
def main(ctx, debug, base_config, env_file): # pragma: no cover
ctx.obj = {}
ctx.obj["args"] = {}
ctx.obj["args"]["debug"] = debug
ctx.obj["args"]["base_config"] = base_config
ctx.obj["args"]["env_file"] = env_file
# runtime environment checks to avoid delayed failures
if sys.version_info[0] > 2:
try:
if pkg_resources.get_distribution("futures"):
raise SystemExit(
"FATAL: futures package found, this package should not be installed in a Python 3 environment, please remove it. See https://github.com/agronholm/pythonfutures/issues/90"
)
except pkg_resources.DistributionNotFound:
pass
main.add_command(command.cleanup.cleanup)
main.add_command(command.check.check)
main.add_command(command.converge.converge)
main.add_command(command.create.create)
main.add_command(command.dependency.dependency)
main.add_command(command.destroy.destroy)
main.add_command(command.drivers.drivers)
main.add_command(command.idempotence.idempotence)
main.add_command(command.init.init)
main.add_command(command.lint.lint)
main.add_command(command.list.list)
main.add_command(command.login.login)
main.add_command(command.matrix.matrix)
main.add_command(command.prepare.prepare)
main.add_command(command.reset.reset)
main.add_command(command.side_effect.side_effect)
main.add_command(command.syntax.syntax)
main.add_command(command.test.test)
main.add_command(command.verify.verify)
| true | true |
1c2bd46572caa123338ba23666700dee981f07f2 | 3,714 | py | Python | tools/updateRouting/lib/mrt.py | shutingrz/prefix2as | d8f7664df43b772c00323da69f280f493ad5495d | [
"MIT"
] | 9 | 2018-05-15T08:28:15.000Z | 2019-05-03T05:39:04.000Z | tools/updateRouting/lib/mrt.py | shutingrz/prefix2as | d8f7664df43b772c00323da69f280f493ad5495d | [
"MIT"
] | null | null | null | tools/updateRouting/lib/mrt.py | shutingrz/prefix2as | d8f7664df43b772c00323da69f280f493ad5495d | [
"MIT"
] | null | null | null | import os, sys, subprocess, ipaddress, re
from logging import getLogger
logger = getLogger(__name__)
class MRTController():
def __init__(self, mrtpath=None, peer_as=None):
self.mrt = []
self.bgpdump_path = "bgpdump"
if mrtpath is not None:
self.read(mrtpath)
def setBgpdumpPath(self, bgpdump_path):
self.bgpdump_path = bgpdump_path
def read(self, mrtpath, peer_as=None):
logger.info("MRT data reading...")
mrt = []
if not os.path.exists(mrtpath):
raise FileNotFoundError("MRT path '%s' is not found." % mrtpath)
dumpout = self.bgpdump(mrtpath, self.bgpdump_path)
dumplines = dumpout.split("\n")
del dumpout
logger.debug("MRT data parse start.")
for dumpline in dumplines:
route = self._parse(dumpline, peer_as)
if route is None:
continue
else:
mrt.append(route)
del dumplines
logger.debug("MRT data parse end. (len=%s)" % len(mrt))
if len(mrt) > 0:
self.mrt = mrt
logger.info("...end")
def export(self):
if len(self.mrt) > 0:
return self.mrt
else:
raise Exception("MRT has no data.")
def print_mrt(self):
for route in self.mrt:
print(route.items())
def createSampleData(self):
mrt = []
line = "TABLE_DUMP2|1512571800|B|192.168.3.11|65009|1.0.132.0/22|7500 2497 38040 23969|INCOMPLETE|202.249.2.169|0|0||NAG||"
route = self._parse(line, None)
mrt.append(route)
self.mrt = mrt
def bgpdump(self, mrtpath, bgpdump_path):
#TABLE_DUMP2|1512571800|B|192.168.3.11|65009|1.0.132.0/22|7500 2497 38040 23969|INCOMPLETE|202.249.2.169|0|0||NAG||
logger.debug("bgpdump start: %s" % mrtpath)
try:
dumpout = subprocess.check_output([bgpdump_path, "-m", mrtpath])
dumpout = dumpout.decode(encoding="ascii")
except Exception as e:
raise Exception("bgpdump: load MRT data exception: %s" % e)
logger.debug("bgpdump finished.")
return dumpout
def _parse(self, line, peer_as=None):
route_arr = line.split("|")
if len(route_arr) < 14:
return None
route = {
# "type": route_arr[0], # TABLE_DUMP2
"date": route_arr[1], # 1501686000
# "flag": route_arr[2], # B
# "peer_ip": route_arr[3], # 192.168.2.65
"peer_as": route_arr[4], # 65009
"prefix": route_arr[5], # 1.0.4.0/22
"aspath": route_arr[6], # 59105 2518 4826 38803 56203
# "origin": route_arr[7], # IGP
# "nexthop": route_arr[8], # 103.48.31.82
# "localpref": route_arr[9], # 100
# "med": route_arr[10],# 0
# "comm": route_arr[11],# *blank
# "atomic_aggr":route_arr[12],# NAG
# "merge_aggr" :route_arr[13],# *blank
"asnum" :None,
"start_ip" :None,
"end_ip" :None,
"size" :None
}
if "::/" in route["prefix"]: #IPv6 is not supported.
return None
elif peer_as is not None:
if route["peer_as"] != peer_as: # for multi home
return None
asnum = route["aspath"].split(" ")[-1]
#asnum is sometimes surrounded by "{}"
if asnum.isdigit():
route["asnum"] = asnum
else:
match = re.search(r"{(?P<num>\d+)}", asnum)
if match:
num = match.group("num")
if num.isdigit():
route["asnum"] = num
else:
return None
else:
return None
#prefix data
netobj = ipaddress.ip_network(route["prefix"])
start_ip = int(netobj[0])
end_ip = int(netobj[-1])
size = end_ip - start_ip + 1
route["start_ip"] = str(start_ip)
route["end_ip"] = str(end_ip)
route["size"] = str(size)
if None in route.values():
return None
else:
return route
@classmethod
def bgpdump_dryrun(self, bgpdump_path):
try:
dumpout = subprocess.check_output([bgpdump_path, "-T"])
except Exception as e:
raise NameError("bgpdump is not found. Please set a correct bgpdump path.")
| 26.15493 | 125 | 0.639742 | import os, sys, subprocess, ipaddress, re
from logging import getLogger
logger = getLogger(__name__)
class MRTController():
def __init__(self, mrtpath=None, peer_as=None):
self.mrt = []
self.bgpdump_path = "bgpdump"
if mrtpath is not None:
self.read(mrtpath)
def setBgpdumpPath(self, bgpdump_path):
self.bgpdump_path = bgpdump_path
def read(self, mrtpath, peer_as=None):
logger.info("MRT data reading...")
mrt = []
if not os.path.exists(mrtpath):
raise FileNotFoundError("MRT path '%s' is not found." % mrtpath)
dumpout = self.bgpdump(mrtpath, self.bgpdump_path)
dumplines = dumpout.split("\n")
del dumpout
logger.debug("MRT data parse start.")
for dumpline in dumplines:
route = self._parse(dumpline, peer_as)
if route is None:
continue
else:
mrt.append(route)
del dumplines
logger.debug("MRT data parse end. (len=%s)" % len(mrt))
if len(mrt) > 0:
self.mrt = mrt
logger.info("...end")
def export(self):
if len(self.mrt) > 0:
return self.mrt
else:
raise Exception("MRT has no data.")
def print_mrt(self):
for route in self.mrt:
print(route.items())
def createSampleData(self):
mrt = []
line = "TABLE_DUMP2|1512571800|B|192.168.3.11|65009|1.0.132.0/22|7500 2497 38040 23969|INCOMPLETE|202.249.2.169|0|0||NAG||"
route = self._parse(line, None)
mrt.append(route)
self.mrt = mrt
def bgpdump(self, mrtpath, bgpdump_path):
logger.debug("bgpdump start: %s" % mrtpath)
try:
dumpout = subprocess.check_output([bgpdump_path, "-m", mrtpath])
dumpout = dumpout.decode(encoding="ascii")
except Exception as e:
raise Exception("bgpdump: load MRT data exception: %s" % e)
logger.debug("bgpdump finished.")
return dumpout
def _parse(self, line, peer_as=None):
route_arr = line.split("|")
if len(route_arr) < 14:
return None
route = {
route_arr[1],
route_arr[4],
"prefix": route_arr[5],
"aspath": route_arr[6],
one,
"end_ip" :None,
"size" :None
}
if "::/" in route["prefix"]:
return None
elif peer_as is not None:
if route["peer_as"] != peer_as:
return None
asnum = route["aspath"].split(" ")[-1]
if asnum.isdigit():
route["asnum"] = asnum
else:
match = re.search(r"{(?P<num>\d+)}", asnum)
if match:
num = match.group("num")
if num.isdigit():
route["asnum"] = num
else:
return None
else:
return None
netobj = ipaddress.ip_network(route["prefix"])
start_ip = int(netobj[0])
end_ip = int(netobj[-1])
size = end_ip - start_ip + 1
route["start_ip"] = str(start_ip)
route["end_ip"] = str(end_ip)
route["size"] = str(size)
if None in route.values():
return None
else:
return route
@classmethod
def bgpdump_dryrun(self, bgpdump_path):
try:
dumpout = subprocess.check_output([bgpdump_path, "-T"])
except Exception as e:
raise NameError("bgpdump is not found. Please set a correct bgpdump path.")
| true | true |
1c2bd4f33e0efe0ea487527f49586d9323f6f851 | 3,455 | py | Python | purity_fb/purity_fb_1dot7/models/bucket_post.py | tlewis-ps/purity_fb_python_client | 652835cbd485c95a86da27f8b661679727ec6ea0 | [
"Apache-2.0"
] | 5 | 2017-09-08T20:47:22.000Z | 2021-06-29T02:11:05.000Z | purity_fb/purity_fb_1dot7/models/bucket_post.py | tlewis-ps/purity_fb_python_client | 652835cbd485c95a86da27f8b661679727ec6ea0 | [
"Apache-2.0"
] | 16 | 2017-11-27T20:57:48.000Z | 2021-11-23T18:46:43.000Z | purity_fb/purity_fb_1dot7/models/bucket_post.py | tlewis-ps/purity_fb_python_client | 652835cbd485c95a86da27f8b661679727ec6ea0 | [
"Apache-2.0"
] | 22 | 2017-10-13T15:33:05.000Z | 2021-11-08T19:56:21.000Z | # coding: utf-8
"""
Pure Storage FlashBlade REST 1.7 Python SDK
Pure Storage FlashBlade REST 1.7 Python SDK, developed by [Pure Storage, Inc](http://www.purestorage.com/). Documentations can be found at [purity-fb.readthedocs.io](http://purity-fb.readthedocs.io/).
OpenAPI spec version: 1.7
Contact: info@purestorage.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class BucketPost(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
#BEGIN_CUSTOM
# IR-51527: Prevent Pytest from attempting to collect this class based on name.
__test__ = False
#END_CUSTOM
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'account': 'Reference'
}
attribute_map = {
'account': 'account'
}
def __init__(self, account=None): # noqa: E501
"""BucketPost - a model defined in Swagger""" # noqa: E501
self._account = None
self.discriminator = None
if account is not None:
self.account = account
@property
def account(self):
"""Gets the account of this BucketPost. # noqa: E501
the account of the bucket # noqa: E501
:return: The account of this BucketPost. # noqa: E501
:rtype: Reference
"""
return self._account
@account.setter
def account(self, account):
"""Sets the account of this BucketPost.
the account of the bucket # noqa: E501
:param account: The account of this BucketPost. # noqa: E501
:type: Reference
"""
self._account = account
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(BucketPost, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, BucketPost):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 28.089431 | 204 | 0.571925 |
import pprint
import re
import six
class BucketPost(object):
__test__ = False
swagger_types = {
'account': 'Reference'
}
attribute_map = {
'account': 'account'
}
def __init__(self, account=None):
self._account = None
self.discriminator = None
if account is not None:
self.account = account
@property
def account(self):
return self._account
@account.setter
def account(self, account):
self._account = account
def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(BucketPost, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
return pprint.pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
if not isinstance(other, BucketPost):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
1c2bd4fb69d5564412d0b4935bf6d627151c3049 | 1,718 | py | Python | lingcod/common/registration_backend/__init__.py | google-code-export/marinemap | b7d58db11720637845b6a83bf70435c32c5af531 | [
"BSD-3-Clause"
] | 3 | 2017-06-09T20:44:58.000Z | 2017-12-26T12:09:21.000Z | lingcod/common/registration_backend/__init__.py | underbluewaters/marinemap | c001e16615caa2178c65ca0684e1b6fd56d3f93d | [
"BSD-3-Clause"
] | null | null | null | lingcod/common/registration_backend/__init__.py | underbluewaters/marinemap | c001e16615caa2178c65ca0684e1b6fd56d3f93d | [
"BSD-3-Clause"
] | 3 | 2016-11-30T13:41:56.000Z | 2019-05-07T17:07:12.000Z | from registration.backends.default import DefaultBackend
from django.db import transaction
from django import forms
from django.contrib.sites.models import Site, RequestSite
from django.contrib.auth.models import User, Group
from registration.models import RegistrationManager, RegistrationProfile
from registration.forms import RegistrationForm
from registration import signals
from django.conf import settings
class CustomRegistrationForm(RegistrationForm):
first_name = forms.CharField(label="First Name")
last_name = forms.CharField(label="Last Name")
class LingcodBackend(DefaultBackend):
def get_form_class(self, request):
return CustomRegistrationForm
def register(self, request, **kwargs):
"""
Given a username, firstname, lastname, email address and password,
register a new user account, which will initially be inactive.
See django-registration docs for more info
"""
username, email, password, first, last = kwargs['username'], kwargs['email'], kwargs['password1'], \
kwargs['first_name'], kwargs['last_name']
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
new_user = RegistrationProfile.objects.create_inactive_user(username, email, password, site)
new_user.first_name = first
new_user.last_name = last
new_user.is_active = False
webreg_group = Group.objects.get(name=settings.GROUP_REGISTERED_BY_WEB)
new_user.groups.add(webreg_group)
new_user.save()
signals.user_registered.send(sender=self.__class__, user=new_user, request=request)
return new_user
| 39.953488 | 108 | 0.721187 | from registration.backends.default import DefaultBackend
from django.db import transaction
from django import forms
from django.contrib.sites.models import Site, RequestSite
from django.contrib.auth.models import User, Group
from registration.models import RegistrationManager, RegistrationProfile
from registration.forms import RegistrationForm
from registration import signals
from django.conf import settings
class CustomRegistrationForm(RegistrationForm):
first_name = forms.CharField(label="First Name")
last_name = forms.CharField(label="Last Name")
class LingcodBackend(DefaultBackend):
def get_form_class(self, request):
return CustomRegistrationForm
def register(self, request, **kwargs):
username, email, password, first, last = kwargs['username'], kwargs['email'], kwargs['password1'], \
kwargs['first_name'], kwargs['last_name']
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
new_user = RegistrationProfile.objects.create_inactive_user(username, email, password, site)
new_user.first_name = first
new_user.last_name = last
new_user.is_active = False
webreg_group = Group.objects.get(name=settings.GROUP_REGISTERED_BY_WEB)
new_user.groups.add(webreg_group)
new_user.save()
signals.user_registered.send(sender=self.__class__, user=new_user, request=request)
return new_user
| true | true |
1c2bd688676a727f79ca1b2423a2e52aadbb4b4e | 6,541 | py | Python | examples/03_connectivity/plot_atlas_comparison.py | ctw/nilearn | 932eee9c69cd8fbf40ee6af5cee77f8f93b25da3 | [
"BSD-2-Clause"
] | null | null | null | examples/03_connectivity/plot_atlas_comparison.py | ctw/nilearn | 932eee9c69cd8fbf40ee6af5cee77f8f93b25da3 | [
"BSD-2-Clause"
] | null | null | null | examples/03_connectivity/plot_atlas_comparison.py | ctw/nilearn | 932eee9c69cd8fbf40ee6af5cee77f8f93b25da3 | [
"BSD-2-Clause"
] | null | null | null | """
Comparing connectomes on different reference atlases
====================================================
This examples shows how to turn a parcellation into connectome for
visualization. This requires choosing centers for each parcel
or network, via :func:`nilearn.plotting.find_parcellation_cut_coords` for
parcellation based on labels and
:func:`nilearn.plotting.find_probabilistic_atlas_cut_coords` for
parcellation based on probabilistic values.
In the intermediary steps, we make use of
:class:`nilearn.maskers.NiftiLabelsMasker` and
:class:`nilearn.maskers.NiftiMapsMasker` to extract time series from nifti
objects using different parcellation atlases.
The time series of all subjects of the brain development dataset are concatenated and
given directly to :class:`nilearn.connectome.ConnectivityMeasure` for
computing parcel-wise correlation matrices for each atlas across all subjects.
Mean correlation matrix is displayed on glass brain on extracted coordinates.
# author: Amadeus Kanaan
"""
####################################################################
# Load atlases
# -------------
from nilearn import datasets
yeo = datasets.fetch_atlas_yeo_2011()
print('Yeo atlas nifti image (3D) with 17 parcels and liberal mask is located '
'at: %s' % yeo['thick_17'])
#########################################################################
# Load functional data
# --------------------
data = datasets.fetch_development_fmri(n_subjects=10)
print('Functional nifti images (4D, e.g., one subject) are located at : %r'
% data['func'][0])
print('Counfound csv files (of same subject) are located at : %r'
% data['confounds'][0])
##########################################################################
# Extract coordinates on Yeo atlas - parcellations
# ------------------------------------------------
from nilearn.maskers import NiftiLabelsMasker
from nilearn.connectome import ConnectivityMeasure
# ConenctivityMeasure from Nilearn uses simple 'correlation' to compute
# connectivity matrices for all subjects in a list
connectome_measure = ConnectivityMeasure(kind='correlation')
# useful for plotting connectivity interactions on glass brain
from nilearn import plotting
# create masker to extract functional data within atlas parcels
masker = NiftiLabelsMasker(labels_img=yeo['thick_17'], standardize=True,
memory='nilearn_cache')
# extract time series from all subjects and concatenate them
time_series = []
for func, confounds in zip(data.func, data.confounds):
time_series.append(masker.fit_transform(func, confounds=confounds))
# calculate correlation matrices across subjects and display
correlation_matrices = connectome_measure.fit_transform(time_series)
# Mean correlation matrix across 10 subjects can be grabbed like this,
# using connectome measure object
mean_correlation_matrix = connectome_measure.mean_
# grab center coordinates for atlas labels
coordinates = plotting.find_parcellation_cut_coords(labels_img=yeo['thick_17'])
# plot connectome with 80% edge strength in the connectivity
plotting.plot_connectome(mean_correlation_matrix, coordinates,
edge_threshold="80%",
title='Yeo Atlas 17 thick (func)')
##########################################################################
# Plot a directed connectome - asymmetric connectivity measure
# -----------------------------------------------------------------
# In this section, we use the lag-1 correlation as the connectivity
# measure, which leads to an asymmetric connectivity matrix.
# The plot_connectome function accepts both symmetric and asymmetric
# matrices, but plot the latter as a directed graph.
import numpy as np
# Define a custom function to compute lag correlation on the time series
def lag_correlation(time_series, lag):
n_subjects = len(time_series)
n_samples, n_features = time_series[0].shape
lag_cor = np.zeros((n_subjects, n_features, n_features))
for subject, serie in enumerate(time_series):
for i in range(n_features):
for j in range(n_features):
if lag == 0:
lag_cor[subject, i, j] = np.corrcoef(serie[:, i],
serie[:, j])[0, 1]
else:
lag_cor[subject, i, j] = np.corrcoef(serie[lag:, i],
serie[:-lag, j])[0, 1]
return np.mean(lag_cor, axis=0)
# Compute lag-0 and lag-1 correlations and plot associated connectomes
for lag in [0, 1]:
lag_correlation_matrix = lag_correlation(time_series, lag)
plotting.plot_connectome(lag_correlation_matrix, coordinates,
edge_threshold="90%",
title='Lag-{} correlation'.format(
lag))
##########################################################################
# Load probabilistic atlases - extracting coordinates on brain maps
# -----------------------------------------------------------------
dim = 64
difumo = datasets.fetch_atlas_difumo(
dimension=dim, resolution_mm=2, legacy_format=False
)
##########################################################################
# Iterate over fetched atlases to extract coordinates - probabilistic
# -------------------------------------------------------------------
from nilearn.maskers import NiftiMapsMasker
# create masker to extract functional data within atlas parcels
masker = NiftiMapsMasker(maps_img=difumo.maps, standardize=True,
memory='nilearn_cache')
# extract time series from all subjects and concatenate them
time_series = []
for func, confounds in zip(data.func, data.confounds):
time_series.append(masker.fit_transform(func, confounds=confounds))
# calculate correlation matrices across subjects and display
correlation_matrices = connectome_measure.fit_transform(time_series)
# Mean correlation matrix across 10 subjects can be grabbed like this,
# using connectome measure object
mean_correlation_matrix = connectome_measure.mean_
# grab center coordinates for probabilistic atlas
coordinates = plotting.find_probabilistic_atlas_cut_coords(maps_img=difumo.maps)
# plot connectome with 85% edge strength in the connectivity
plotting.plot_connectome(mean_correlation_matrix, coordinates,
edge_threshold="85%",
title='DiFuMo with {0} dimensions (probabilistic)'.format(dim))
plotting.show()
| 42.474026 | 88 | 0.64455 | true | true | |
1c2bd6aed7ee20af3634bd12110ddb6da35b153d | 15,241 | py | Python | eccpy/compare_raw.py | ricardo-ayres/eccpy | 39aaf51d1d18bbbc7c25ab3632f67ddbbbbd4fd5 | [
"MIT"
] | 28 | 2016-09-22T22:46:39.000Z | 2022-02-17T02:49:56.000Z | eccpy/compare_raw.py | ricardo-ayres/eccpy | 39aaf51d1d18bbbc7c25ab3632f67ddbbbbd4fd5 | [
"MIT"
] | 12 | 2016-08-02T13:36:03.000Z | 2022-01-27T13:37:15.000Z | eccpy/compare_raw.py | ricardo-ayres/eccpy | 39aaf51d1d18bbbc7c25ab3632f67ddbbbbd4fd5 | [
"MIT"
] | 10 | 2018-11-21T13:39:11.000Z | 2022-03-02T17:34:42.000Z | import ast
import eccpy.settings as eccpysettings
import eccpy.tools as tools
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import sys
def compare_rawdata(settings_excel_file, sample_names, **kwargs):
""" Compare raw dose-response curves between selected samples, for selected experiments.
Processes the datafiles in settings excel file marked as "TRUE" for "run gatherer."
Collects output from the "run_curvefit" program, but only for the selected samples.
Recreates the fitted curves from the four-parameter Hill equation, with the previously calculated hill_constants.
The output of the compare_rawdata is saved in the same folder as the "run_gatherer":
ORIGINAL_SUBFOLDER_WITH_SETTINGS_EXCEL_FILE/analysed/todays_date/
Running this script will overwrite any previous files with the same name (i.e., analysed on the same day)
Parameters
----------
settings_excel_file : String
Path to the settings file containing the list of datafiles for analysis, and also chosen parameters
sample_names : list of strings, or list of tuples
For the output of one figure comparing the raw data of samples:
sample_names will be a list of sample names
e.g. sample_names=["control_sample","sample1", "sample2]"
For the output of multiple figures comparing the raw data of samples:
sample_names will be a tuple of lists of of sample names
e.g. sample_names=(["control_sample","sample1"], ["control_sample","sample2]")
Note: for many output figures, creating a list_output_fig_names is recommended.
The strings (e.g. "sample1") must resemble the sample names as written in the original data files,
rather than shortened names (e.g. "s1") according to the list in the settings file.
Keyword Arguments
-----------------
list_output_fig_names : list of strings
List of output figure names that is used for a multiple analyses, where the sample_names is a list of tuples.
e.g.
sample_names=(["control_sample","sample1"], ["control_sample","sample2]", ["sample1","sample2]")
list_output_fig_names=["control_vs_sample1", "control_vs_sample2", "sample1_vs_sample2"]
Saved Files and Figures
-------
Dose_Response_Curve_Comparison : Scattergram (orig datapoints), line chart (fitted curves)
Dose-response curves for the selected samples (from sample_names), extracted from the selected experiments
as labelled "True" in the settings file.
Each unique sample is given a different colour.
x-axis : dose units
y-axis : response units
scattergram : original datapoints from experiment
line chart : fitted curve used to calculate EC50, recreated from saved hill_constants
Note
-------
The compare_rawdata function is best used for the comparison of 2-3 samples, with 5-10 experiments.
It currently can accept 8 different samples.
Increasing the number of samples or experiments is likely to result in a very cluttered graph.
"""
print("\nStarting compare_rawdata program")
# if there is a list of output figure names in the keyword arguments, check that the length matches the sample_names
if "list_output_fig_names" in kwargs.keys():
list_output_fig_names = kwargs["list_output_fig_names"]
# check that the list of sample tuples and list of names has the same length
if len(list_output_fig_names) != len(sample_names):
raise IndexError("The length of sample_names does not match the "
"list_output_fig_names. Please check your list of samples.")
# create output folder and output file basename
outpath, basename = eccpysettings.setup_output_folder(settings_excel_file, "compare_raw")
if not os.path.exists(outpath):
os.mkdir(outpath)
# setup tableau20 colour list
t20 = tools.setup_t20_colour_list()
# add black (k) to the front of the list
t20.insert(0,"0.5")
# add the relevant paths to the data files to the dataframe for files (dff)
settings, dff, df_samplenames = eccpysettings.read_settings_file(settings_excel_file)
# create a list of unique markers for the scattergram
markerlist = [".",",","o","v","^","<",">","1","2","3","4","8","s","p","*","h","H","+","x","D","d","|","_"]
# extend the list, in the unlikely case that someone has many replicates
markers = markerlist + markerlist + markerlist
# set transparency of datapoints
alpha = 0.5
# set default fontsize
plt.rcParams['font.size'] = 6
# define xycoordinates for later annotations
xyc = "axes fraction"
# extract list of adjusted datasets for analysis
datasets = ast.literal_eval(settings["datasets"])
# create boolean
at_least_one_sample_found_in_selected_datafiles = False
if not isinstance(sample_names[0], tuple):
# the list of sample names contains only strings, and therefore only a single raw analysis is performed
# convert to a list containing only one tuple, with the sample names for comparison
sample_names = [tuple(sample_names)]
for s_num, sample_tuple in enumerate(sample_names):
if True in list(dff.loc[:, "run gatherer"]):
n_files_to_analyse = dff.loc[dff["run gatherer"] == True].shape[0]
for d in datasets:
# change the dataset name (e.g. "_orig" to "") to an empty string if there is only one dataset for analysis
d_name = "" if len(datasets) == 1 else d
# close any open plots
plt.close("all")
# create new canvas (figure) containing a single plot (ax)
fig, ax = plt.subplots()
# create a counter for the number of files
file_counter = 0
# iterate through all of the data files labeled for analysis
for fn in dff.loc[dff["run gatherer"] == True].index:
file_counter += 1
# print a dot for each file analysed, for each sample name
sys.stdout.write(".")
sys.stdout.flush()
# open output summary file with LD50 values as pandas dataframe
ofd_EC50_eval_csv = dff.loc[fn,"ofd_EC50_eval_csv"]
if os.path.isfile(ofd_EC50_eval_csv):
filename = os.path.split(ofd_EC50_eval_csv)[1]
df = pd.read_csv(ofd_EC50_eval_csv)
# set the index as the sample_name (long name)
df.set_index("sample_name", inplace=True)
# redefine to only include data that is labelled as "data_seems_okay"
df = df.loc[df["data_seems_okay{}".format(d)] == True]
sample_counter = 0
for sample_name in sample_tuple:
# counter = 0
if sample_name in df.index:
at_least_one_sample_found_in_selected_datafiles = True
# obtain the bool, or series of bools that say if the data is okay
data_seems_okay_X = df.loc[sample_name,"data_seems_okay{}".format(d)]
# if it's not a series, the sample name was only found once in that experiment
if not isinstance(data_seems_okay_X, pd.Series):
# counter += 1
# convert the x_orig data from a stringlist to a numpy array
x = np.array(ast.literal_eval(df.loc[sample_name,"x{}".format(d)]))
# convert the y_orig data from sample_name stringlist to a numpy array
y = np.array(ast.literal_eval(df.loc[sample_name,"y{}".format(d)]))
# plot the datapoints for that set of data
if sample_counter == 0:
# if it's the first datapoint from that file, set a label for the legend
ax.scatter(x, y, color = t20[sample_counter], s=15, alpha=alpha,
marker=markers[file_counter], label=filename[:16])
else:
# otherwise, do not write another legend label
ax.scatter(x, y, color = t20[sample_counter], s=15, alpha=alpha,
marker=markers[file_counter], label="_nolabel_")
# retrieve the hill constants for the curve
hill_constants = ast.literal_eval(df.loc[sample_name,"hill_constants{}".format(d)])
# create 500 datapoints on the x-axis to plot the curve
x_fitted_norm = np.linspace(0, 1, 500)
# create the y datapoints using the sigmoid equation
y_fitted_norm = tools.hill_eq(hill_constants, x_fitted_norm)
# denormalise the x datapoints to the original concentrations
x_fitted = tools.denormalise_0_1(x_fitted_norm, x.min(), x.max())
# denormalise the y datapoints to the original concentrations
y_fitted = tools.denormalise_0_1(y_fitted_norm, y.min(), y.max())
# plot the curve of the fitted data, using the same colours as the datapoints
ax.plot(x_fitted, y_fitted, color = t20[sample_counter], alpha=alpha)
# sample_counter += 1
# if it is a series, the sample name was found more than once in that experiment
elif isinstance(data_seems_okay_X, pd.Series):
# retrieve the list of x datapoints, y datapoints, and hill constants from curve
x_list_replicates = list(df.loc[sample_name,"x{}".format(d)])
y_list_replicates = list(df.loc[sample_name,"y{}".format(d)])
hill_constants_reps = list(df.loc[sample_name,"hill_constants{}".format(d)])
for i in range(len(x_list_replicates)):
# counter += 1
# convert the x, y and hill constants from a stringlists to numpy arrays
x = np.array(ast.literal_eval(x_list_replicates[i]))
y = np.array(ast.literal_eval(y_list_replicates[i]))
hill_constants = np.array(ast.literal_eval(hill_constants_reps[i]))
# plot the datapoints for that set of data
if sample_counter == 0:
# if it's the first datapoint from that file, set a label for the legend
ax.scatter(x, y, color = t20[sample_counter], s=15, alpha=alpha,
marker=markers[file_counter], label=filename[:8])
else:
# otherwise, do not write another legend label
ax.scatter(x, y, color = t20[sample_counter], s=15, alpha=alpha,
marker=markers[file_counter], label="_nolabel_")
# create 500 datapoints on the x-axis to plot the curve
x_fitted_norm = np.linspace(0, 1, 500)
# create the y datapoints using the sigmoid equation
y_fitted_norm = tools.hill_eq(hill_constants, x_fitted_norm)
# denormalise the x datapoints to the original concentrations
x_fitted = tools.denormalise_0_1(x_fitted_norm, x.min(), x.max())
# denormalise the y datapoints to the original concentrations
y_fitted = tools.denormalise_0_1(y_fitted_norm, y.min(), y.max())
# plot the curve of the fitted data, using the same colours as the datapoints
ax.plot(x_fitted, y_fitted, color = t20[sample_counter], alpha=alpha)
else:
raise TypeError("data_seems_okay_X is neither bool nor series")
sample_counter += 1
if not at_least_one_sample_found_in_selected_datafiles:
raise ValueError("No samples found in the selected datasets!\nSamples: {}".format(sample_names))
xaxis_pos = 0.02
yaxis_pos = np.linspace(0.95,0.7,8)
for n, sample_name in enumerate(sample_tuple):
ax.annotate(text=sample_name, xy=(xaxis_pos,yaxis_pos[n]),
xycoords=xyc,
color = t20[n])
ymin, ymax = ax.get_ylim()
ax.set_ylim(ymin,ymax*1.3)
xmin, xmax = ax.get_xlim()
# ax.set_xlim(-10,xmax*1.1)
ax.set_xlim(xmin - xmax * 0.1, xmax * 1.1)
# ax.set_xlim(-10, 200)
ax.legend(ncol=2, scatterpoints=1)
if "list_output_fig_names" in kwargs.keys():
# set figure name "fig_name" for saving.
fig_name = list_output_fig_names[s_num]
else:
# If a list of tuple names is not given, use the sample_tuple number, "n"
fig_name = s_num
ax.set_title("comparison of raw data for selected samples ({e} experiments), "
"{b} {c}".format(b=d_name,c=os.path.split(settings_excel_file)[1],e=n_files_to_analyse))
# set xlabel, ylabel
ax.set_xlabel("{a} ({b})".format(a=settings["x-axis (dose) label"],b=settings["x-axis (dose) units"]))
ax.set_ylabel(settings["y-axis (response) label"],rotation='vertical')
# save the figure in png format
figpath = os.path.join(outpath, "{b}_{n}{d}.png".format(b=basename,n=fig_name,d=d_name))
fig.savefig(figpath, format = "png", dpi = 150)
plt.close("all")
print('\nComparison of raw data is finished.\nOutput files are saved in the following directory:\n{}'.format(outpath)) | 65.412017 | 123 | 0.558822 | import ast
import eccpy.settings as eccpysettings
import eccpy.tools as tools
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import sys
def compare_rawdata(settings_excel_file, sample_names, **kwargs):
print("\nStarting compare_rawdata program")
if "list_output_fig_names" in kwargs.keys():
list_output_fig_names = kwargs["list_output_fig_names"]
if len(list_output_fig_names) != len(sample_names):
raise IndexError("The length of sample_names does not match the "
"list_output_fig_names. Please check your list of samples.")
outpath, basename = eccpysettings.setup_output_folder(settings_excel_file, "compare_raw")
if not os.path.exists(outpath):
os.mkdir(outpath)
t20 = tools.setup_t20_colour_list()
t20.insert(0,"0.5")
settings, dff, df_samplenames = eccpysettings.read_settings_file(settings_excel_file)
markerlist = [".",",","o","v","^","<",">","1","2","3","4","8","s","p","*","h","H","+","x","D","d","|","_"]
markers = markerlist + markerlist + markerlist
alpha = 0.5
plt.rcParams['font.size'] = 6
xyc = "axes fraction"
datasets = ast.literal_eval(settings["datasets"])
at_least_one_sample_found_in_selected_datafiles = False
if not isinstance(sample_names[0], tuple):
sample_names = [tuple(sample_names)]
for s_num, sample_tuple in enumerate(sample_names):
if True in list(dff.loc[:, "run gatherer"]):
n_files_to_analyse = dff.loc[dff["run gatherer"] == True].shape[0]
for d in datasets:
d_name = "" if len(datasets) == 1 else d
plt.close("all")
fig, ax = plt.subplots()
file_counter = 0
for fn in dff.loc[dff["run gatherer"] == True].index:
file_counter += 1
sys.stdout.write(".")
sys.stdout.flush()
ofd_EC50_eval_csv = dff.loc[fn,"ofd_EC50_eval_csv"]
if os.path.isfile(ofd_EC50_eval_csv):
filename = os.path.split(ofd_EC50_eval_csv)[1]
df = pd.read_csv(ofd_EC50_eval_csv)
df.set_index("sample_name", inplace=True)
df = df.loc[df["data_seems_okay{}".format(d)] == True]
sample_counter = 0
for sample_name in sample_tuple:
if sample_name in df.index:
at_least_one_sample_found_in_selected_datafiles = True
data_seems_okay_X = df.loc[sample_name,"data_seems_okay{}".format(d)]
if not isinstance(data_seems_okay_X, pd.Series):
# counter += 1
# convert the x_orig data from a stringlist to a numpy array
x = np.array(ast.literal_eval(df.loc[sample_name,"x{}".format(d)]))
# convert the y_orig data from sample_name stringlist to a numpy array
y = np.array(ast.literal_eval(df.loc[sample_name,"y{}".format(d)]))
# plot the datapoints for that set of data
if sample_counter == 0:
# if it's the first datapoint from that file, set a label for the legend
ax.scatter(x, y, color = t20[sample_counter], s=15, alpha=alpha,
marker=markers[file_counter], label=filename[:16])
else:
ax.scatter(x, y, color = t20[sample_counter], s=15, alpha=alpha,
marker=markers[file_counter], label="_nolabel_")
hill_constants = ast.literal_eval(df.loc[sample_name,"hill_constants{}".format(d)])
x_fitted_norm = np.linspace(0, 1, 500)
y_fitted_norm = tools.hill_eq(hill_constants, x_fitted_norm)
x_fitted = tools.denormalise_0_1(x_fitted_norm, x.min(), x.max())
y_fitted = tools.denormalise_0_1(y_fitted_norm, y.min(), y.max())
ax.plot(x_fitted, y_fitted, color = t20[sample_counter], alpha=alpha)
elif isinstance(data_seems_okay_X, pd.Series):
x_list_replicates = list(df.loc[sample_name,"x{}".format(d)])
y_list_replicates = list(df.loc[sample_name,"y{}".format(d)])
hill_constants_reps = list(df.loc[sample_name,"hill_constants{}".format(d)])
for i in range(len(x_list_replicates)):
x = np.array(ast.literal_eval(x_list_replicates[i]))
y = np.array(ast.literal_eval(y_list_replicates[i]))
hill_constants = np.array(ast.literal_eval(hill_constants_reps[i]))
if sample_counter == 0:
ax.scatter(x, y, color = t20[sample_counter], s=15, alpha=alpha,
marker=markers[file_counter], label=filename[:8])
else:
# otherwise, do not write another legend label
ax.scatter(x, y, color = t20[sample_counter], s=15, alpha=alpha,
marker=markers[file_counter], label="_nolabel_")
# create 500 datapoints on the x-axis to plot the curve
x_fitted_norm = np.linspace(0, 1, 500)
# create the y datapoints using the sigmoid equation
y_fitted_norm = tools.hill_eq(hill_constants, x_fitted_norm)
# denormalise the x datapoints to the original concentrations
x_fitted = tools.denormalise_0_1(x_fitted_norm, x.min(), x.max())
# denormalise the y datapoints to the original concentrations
y_fitted = tools.denormalise_0_1(y_fitted_norm, y.min(), y.max())
# plot the curve of the fitted data, using the same colours as the datapoints
ax.plot(x_fitted, y_fitted, color = t20[sample_counter], alpha=alpha)
else:
raise TypeError("data_seems_okay_X is neither bool nor series")
sample_counter += 1
if not at_least_one_sample_found_in_selected_datafiles:
raise ValueError("No samples found in the selected datasets!\nSamples: {}".format(sample_names))
xaxis_pos = 0.02
yaxis_pos = np.linspace(0.95,0.7,8)
for n, sample_name in enumerate(sample_tuple):
ax.annotate(text=sample_name, xy=(xaxis_pos,yaxis_pos[n]),
xycoords=xyc,
color = t20[n])
ymin, ymax = ax.get_ylim()
ax.set_ylim(ymin,ymax*1.3)
xmin, xmax = ax.get_xlim()
# ax.set_xlim(-10,xmax*1.1)
ax.set_xlim(xmin - xmax * 0.1, xmax * 1.1)
# ax.set_xlim(-10, 200)
ax.legend(ncol=2, scatterpoints=1)
if "list_output_fig_names" in kwargs.keys():
# set figure name "fig_name" for saving.
fig_name = list_output_fig_names[s_num]
else:
# If a list of tuple names is not given, use the sample_tuple number, "n"
fig_name = s_num
ax.set_title("comparison of raw data for selected samples ({e} experiments), "
"{b} {c}".format(b=d_name,c=os.path.split(settings_excel_file)[1],e=n_files_to_analyse))
# set xlabel, ylabel
ax.set_xlabel("{a} ({b})".format(a=settings["x-axis (dose) label"],b=settings["x-axis (dose) units"]))
ax.set_ylabel(settings["y-axis (response) label"],rotation='vertical')
# save the figure in png format
figpath = os.path.join(outpath, "{b}_{n}{d}.png".format(b=basename,n=fig_name,d=d_name))
fig.savefig(figpath, format = "png", dpi = 150)
plt.close("all")
print('\nComparison of raw data is finished.\nOutput files are saved in the following directory:\n{}'.format(outpath)) | true | true |
1c2bd72336ca0ee7b873ea60f30072b4d4e88e4d | 693 | py | Python | migrations/0001_initial.py | nibir404/Crud-app | d04293bb406fdb2727c3e836ab7b0aaad71c5987 | [
"MIT"
] | null | null | null | migrations/0001_initial.py | nibir404/Crud-app | d04293bb406fdb2727c3e836ab7b0aaad71c5987 | [
"MIT"
] | null | null | null | migrations/0001_initial.py | nibir404/Crud-app | d04293bb406fdb2727c3e836ab7b0aaad71c5987 | [
"MIT"
] | null | null | null | # Generated by Django 3.1.4 on 2020-12-08 12:00
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Insert',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('f_name', models.CharField(max_length=100)),
('m_name', models.CharField(max_length=100)),
('age', models.CharField(max_length=100)),
],
),
]
| 27.72 | 115 | 0.545455 |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Insert',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('f_name', models.CharField(max_length=100)),
('m_name', models.CharField(max_length=100)),
('age', models.CharField(max_length=100)),
],
),
]
| true | true |
1c2bd7b146cb9086241020de734ef956e2f04b40 | 955 | py | Python | django_migration_linter/sql_analyser/analyser.py | vald-phoenix/django-migration-linter | 41a5dc731bf609a6530a15fa34788e2997655cbb | [
"Apache-2.0"
] | null | null | null | django_migration_linter/sql_analyser/analyser.py | vald-phoenix/django-migration-linter | 41a5dc731bf609a6530a15fa34788e2997655cbb | [
"Apache-2.0"
] | null | null | null | django_migration_linter/sql_analyser/analyser.py | vald-phoenix/django-migration-linter | 41a5dc731bf609a6530a15fa34788e2997655cbb | [
"Apache-2.0"
] | null | null | null | import logging
from django_migration_linter.sql_analyser import (
BaseAnalyser,
MySqlAnalyser,
PostgresqlAnalyser,
SqliteAnalyser,
)
logger = logging.getLogger(__name__)
def get_sql_analyser(database_vendor, exclude_migration_tests=None):
if "mysql" in database_vendor:
sql_analyser_class = MySqlAnalyser
elif "postgre" in database_vendor:
sql_analyser_class = PostgresqlAnalyser
elif "sqlite" in database_vendor:
sql_analyser_class = SqliteAnalyser
else:
sql_analyser_class = BaseAnalyser
logger.debug("Chosen SQL analyser class: %s", sql_analyser_class)
return sql_analyser_class(exclude_migration_tests)
def analyse_sql_statements(
sql_statements, database_vendor, exclude_migration_tests=None
):
sql_analyser = get_sql_analyser(database_vendor, exclude_migration_tests)
sql_analyser.analyse(sql_statements)
return sql_analyser.errors, sql_analyser.ignored
| 28.939394 | 77 | 0.774869 | import logging
from django_migration_linter.sql_analyser import (
BaseAnalyser,
MySqlAnalyser,
PostgresqlAnalyser,
SqliteAnalyser,
)
logger = logging.getLogger(__name__)
def get_sql_analyser(database_vendor, exclude_migration_tests=None):
if "mysql" in database_vendor:
sql_analyser_class = MySqlAnalyser
elif "postgre" in database_vendor:
sql_analyser_class = PostgresqlAnalyser
elif "sqlite" in database_vendor:
sql_analyser_class = SqliteAnalyser
else:
sql_analyser_class = BaseAnalyser
logger.debug("Chosen SQL analyser class: %s", sql_analyser_class)
return sql_analyser_class(exclude_migration_tests)
def analyse_sql_statements(
sql_statements, database_vendor, exclude_migration_tests=None
):
sql_analyser = get_sql_analyser(database_vendor, exclude_migration_tests)
sql_analyser.analyse(sql_statements)
return sql_analyser.errors, sql_analyser.ignored
| true | true |
1c2bd86baed6a9455e4f0050f9720b8b96eb9e27 | 3,683 | py | Python | flask_uwsgi_websocket/websocket.py | fredounnet/flask-uwsgi-websocket | 5d4a12ec3738cedbdb9e89ea34636de85f83a31e | [
"MIT"
] | null | null | null | flask_uwsgi_websocket/websocket.py | fredounnet/flask-uwsgi-websocket | 5d4a12ec3738cedbdb9e89ea34636de85f83a31e | [
"MIT"
] | null | null | null | flask_uwsgi_websocket/websocket.py | fredounnet/flask-uwsgi-websocket | 5d4a12ec3738cedbdb9e89ea34636de85f83a31e | [
"MIT"
] | null | null | null | import os
import sys
import uuid
from ._uwsgi import uwsgi
from gevent.monkey import patch_all
import werkzeug.routing
class WebSocketClient(object):
'''
Default WebSocket client has a blocking recieve method, but still exports
rest of uWSGI API.
'''
def __init__(self, environ, fd, timeout=60):
self.environ = environ
self.fd = fd
self.timeout = timeout
self.id = str(uuid.uuid1())
def receive(self):
return self.recv()
def recv(self):
return uwsgi.websocket_recv()
def recv_nb(self):
return uwsgi.websocket_recv_nb()
def send(self, msg):
return uwsgi.websocket_send(msg)
def send_binary(self, msg):
return uwsgi.websocket_send_binary(msg)
def send_from_sharedarea(self, id, pos):
return uwsgi.websocket_send_from_sharedarea(id, pos)
def send_binary_from_sharedarea(self, id, pos):
return uwsgi.websocket_send_binary_from_sharedarea(id, pos)
class WebSocketMiddleware(object):
'''
WebSocket Middleware that handles handshake and passes route a WebSocketClient.
'''
client = WebSocketClient
def __init__(self, wsgi_app, websocket):
self.wsgi_app = wsgi_app
self.websocket = websocket
def __call__(self, environ, start_response):
handler = self.websocket.routes.get(environ['PATH_INFO'])
if not handler or 'HTTP_SEC_WEBSOCKET_KEY' not in environ:
return self.wsgi_app(environ, start_response)
uwsgi.websocket_handshake(environ['HTTP_SEC_WEBSOCKET_KEY'], environ.get('HTTP_ORIGIN', ''))
handler(self.client(environ, uwsgi.connection_fd(), self.websocket.timeout))
class WebSocket(object):
'''
Flask extension which makes it easy to integrate uWSGI-powered WebSockets
into your applications.
'''
middleware = WebSocketMiddleware
def __init__(self, app=None, timeout=60):
if app:
self.init_app(app)
self.timeout = timeout
self.routes = werkzeug.routing.Map([])
def run(self, app=None, debug=False, host='localhost', port=5000, **kwargs):
if not app:
app = self.app.name + ':app'
# kwargs are treated as uwsgi arguments
if kwargs.get('master') is None:
kwargs['master'] = True
# boolean should be treated as empty value
for k,v in kwargs.items():
if v is True:
kwargs[k] = ''
# constructing uwsgi arguments
uwsgi_args = ' '.join(['--{0} {1}'.format(k,v) for k,v in kwargs.items()])
args = 'uwsgi --http {0}:{1} --http-websockets {2} --wsgi {3}'.format(host, port, uwsgi_args, app)
# set enviromental variable to trigger adding debug middleware
if self.app.debug or debug:
args = 'FLASK_UWSGI_DEBUG=true {0} --python-autoreload 1'.format(args)
# run uwsgi with our args
print('Running: {0}'.format(args))
sys.exit(os.system(args))
def init_app(self, app):
self.app = app
aggressive_patch = app.config.get('UWSGI_WEBSOCKET_AGGRESSIVE_PATCH', True)
patch_all(aggressive=aggressive_patch)
if os.environ.get('FLASK_UWSGI_DEBUG'):
from werkzeug.debug import DebuggedApplication
app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
app.debug = True
app.wsgi_app = self.middleware(app.wsgi_app, self)
app.run = lambda **kwargs: self.run(**kwargs)
def route(self, rule):
def decorator(f):
self.routes.add(werkzeug.routing.Rule(rule,endpoint=f))
return f
return decorator
| 30.94958 | 106 | 0.640239 | import os
import sys
import uuid
from ._uwsgi import uwsgi
from gevent.monkey import patch_all
import werkzeug.routing
class WebSocketClient(object):
def __init__(self, environ, fd, timeout=60):
self.environ = environ
self.fd = fd
self.timeout = timeout
self.id = str(uuid.uuid1())
def receive(self):
return self.recv()
def recv(self):
return uwsgi.websocket_recv()
def recv_nb(self):
return uwsgi.websocket_recv_nb()
def send(self, msg):
return uwsgi.websocket_send(msg)
def send_binary(self, msg):
return uwsgi.websocket_send_binary(msg)
def send_from_sharedarea(self, id, pos):
return uwsgi.websocket_send_from_sharedarea(id, pos)
def send_binary_from_sharedarea(self, id, pos):
return uwsgi.websocket_send_binary_from_sharedarea(id, pos)
class WebSocketMiddleware(object):
client = WebSocketClient
def __init__(self, wsgi_app, websocket):
self.wsgi_app = wsgi_app
self.websocket = websocket
def __call__(self, environ, start_response):
handler = self.websocket.routes.get(environ['PATH_INFO'])
if not handler or 'HTTP_SEC_WEBSOCKET_KEY' not in environ:
return self.wsgi_app(environ, start_response)
uwsgi.websocket_handshake(environ['HTTP_SEC_WEBSOCKET_KEY'], environ.get('HTTP_ORIGIN', ''))
handler(self.client(environ, uwsgi.connection_fd(), self.websocket.timeout))
class WebSocket(object):
middleware = WebSocketMiddleware
def __init__(self, app=None, timeout=60):
if app:
self.init_app(app)
self.timeout = timeout
self.routes = werkzeug.routing.Map([])
def run(self, app=None, debug=False, host='localhost', port=5000, **kwargs):
if not app:
app = self.app.name + ':app'
if kwargs.get('master') is None:
kwargs['master'] = True
for k,v in kwargs.items():
if v is True:
kwargs[k] = ''
uwsgi_args = ' '.join(['--{0} {1}'.format(k,v) for k,v in kwargs.items()])
args = 'uwsgi --http {0}:{1} --http-websockets {2} --wsgi {3}'.format(host, port, uwsgi_args, app)
if self.app.debug or debug:
args = 'FLASK_UWSGI_DEBUG=true {0} --python-autoreload 1'.format(args)
print('Running: {0}'.format(args))
sys.exit(os.system(args))
def init_app(self, app):
self.app = app
aggressive_patch = app.config.get('UWSGI_WEBSOCKET_AGGRESSIVE_PATCH', True)
patch_all(aggressive=aggressive_patch)
if os.environ.get('FLASK_UWSGI_DEBUG'):
from werkzeug.debug import DebuggedApplication
app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
app.debug = True
app.wsgi_app = self.middleware(app.wsgi_app, self)
app.run = lambda **kwargs: self.run(**kwargs)
def route(self, rule):
def decorator(f):
self.routes.add(werkzeug.routing.Rule(rule,endpoint=f))
return f
return decorator
| true | true |
1c2bd9983a1a0b99807debe83fa9f61f992689b4 | 3,961 | py | Python | api/dorest/dorest/configs/funcs.py | ichise-laboratory/uwkgm | 6505fa5d524336b30505804a3d241143cb1fa4bf | [
"BSD-3-Clause"
] | null | null | null | api/dorest/dorest/configs/funcs.py | ichise-laboratory/uwkgm | 6505fa5d524336b30505804a3d241143cb1fa4bf | [
"BSD-3-Clause"
] | 6 | 2020-11-25T10:49:45.000Z | 2021-09-22T18:50:03.000Z | api/dorest/dorest/configs/funcs.py | ichise-laboratory/uwkgm | 6505fa5d524336b30505804a3d241143cb1fa4bf | [
"BSD-3-Clause"
] | 1 | 2020-12-24T02:15:42.000Z | 2020-12-24T02:15:42.000Z | """Predefined functions for YAML/JSON configuration files
Refer to __init__.py in this module's package for usage
The Dorest project
:copyright: (c) 2020 Ichise Laboratory at NII & AIST
:author: Rungsiman Nararatwong
"""
import importlib
import os
from typing import Any, Dict, List, Union
import yaml
from django.conf import settings
from django.utils.crypto import get_random_string
from dorest.configs.consts import SUPPORTED_FILE_TYPES
def load_usr_pwd(*, path: str, username: str) -> Union[str, None]:
"""Load password of a user. The password is stored in a password file supposedly produced by some scripts in 'accounts' app's management commands.
There may be multiple versions of the password files, the format of the file names is prefix_dddd.yml, where d = [0-9].
This function will look for passwords in the latest password files first, then the older versions.
:param path: A directory that stores the password files
:param username: Target user
:return: Password or None if the password configuration did not exist
"""
files = sorted([file for file in os.listdir(path) if os.path.isfile(os.path.join(path, file))])
# Starts searching from the latest version of the password files
for name, index in {file[:-9]: int(file[-8:-4]) for file in files if any([s in file for s in SUPPORTED_FILE_TYPES])}.items():
i = index
# If the username was not found in the latest version of the password files, checks the older versions
while i:
users = yaml.safe_load(open('%s/%s_%04d.yml' % (path, name, i), 'r'))
if username in users:
return users[username]
i -= 1
return None
def resolve_module_path(*, path: str):
"""Resolves an absolute directory of a module
:param path: A string referring to a module in Python's import format
:return: An absolute directory
"""
return os.path.dirname(importlib.import_module(path).__file__)
def random_password(**kwargs) -> str:
"""Generates a random password using Django's random string generator
:param kwargs: Accepts 'length' and 'allow_chars' as defined in the Django's function
:return: A random password
"""
return get_random_string(**kwargs)
def envyml(*, var: str) -> Any:
"""Loads environment variables defined in a YAML file located in Django project's environment directory.
The path to the environment directory is stored in 'DOREST["ENV"]["PATH"]' in Django project's setting file.
An environment file contains a tree-structure configuration,
with its top level indicating which environment its subtree configuration should be applied.
For example, suppose there are two environments, 'development' and 'production',
and a variable 'policy' defined in 'security.yaml' as followed:
---
development:
policy: insecure
production:
policy: secure
---
Calling 'envyml("security.policy")', or "{{$envyml('var': 'security.policy')}}" in YAML configuration file,
would return the value "secure" or "insecure" depending on the active environment.
The name of the environment variable is stored in 'DOREST["ENV"]["NAME"]' in Django project's setting file.
:param var: A branch to node of interest within an environment configuration file
:return: A subtree or value of a leaf
"""
def walk(sub_tree: Dict[str, Any], sub_path: List[str]) -> Any:
return walk(sub_tree[sub_path[0]], sub_path[1:]) if len(sub_path) > 1 else sub_tree[sub_path[0]]
path = var.split('.')
return walk(yaml.safe_load(open('%s/%s.yaml' % (settings.DOREST['ENV']['PATH'], path[0]), 'r'))[os.environ[settings.DOREST['ENV']['NAME']]], path[1:])
def env(*, name: str) -> str:
"""Loads an environment variable
:param name: The environment variable name
:return: The value of the environment variable
"""
return os.environ[name]
| 37.367925 | 154 | 0.695784 |
import importlib
import os
from typing import Any, Dict, List, Union
import yaml
from django.conf import settings
from django.utils.crypto import get_random_string
from dorest.configs.consts import SUPPORTED_FILE_TYPES
def load_usr_pwd(*, path: str, username: str) -> Union[str, None]:
files = sorted([file for file in os.listdir(path) if os.path.isfile(os.path.join(path, file))])
for name, index in {file[:-9]: int(file[-8:-4]) for file in files if any([s in file for s in SUPPORTED_FILE_TYPES])}.items():
i = index
while i:
users = yaml.safe_load(open('%s/%s_%04d.yml' % (path, name, i), 'r'))
if username in users:
return users[username]
i -= 1
return None
def resolve_module_path(*, path: str):
return os.path.dirname(importlib.import_module(path).__file__)
def random_password(**kwargs) -> str:
return get_random_string(**kwargs)
def envyml(*, var: str) -> Any:
def walk(sub_tree: Dict[str, Any], sub_path: List[str]) -> Any:
return walk(sub_tree[sub_path[0]], sub_path[1:]) if len(sub_path) > 1 else sub_tree[sub_path[0]]
path = var.split('.')
return walk(yaml.safe_load(open('%s/%s.yaml' % (settings.DOREST['ENV']['PATH'], path[0]), 'r'))[os.environ[settings.DOREST['ENV']['NAME']]], path[1:])
def env(*, name: str) -> str:
return os.environ[name]
| true | true |
1c2bdb0fe6942436fcb97e18761d122d3ee8e8b1 | 20,030 | py | Python | bot/client.py | potocnikluka/discord-utility-bot | 6ccd808043812579278244dcaac1a5ce473d77cc | [
"MIT"
] | null | null | null | bot/client.py | potocnikluka/discord-utility-bot | 6ccd808043812579278244dcaac1a5ce473d77cc | [
"MIT"
] | 1 | 2021-07-18T14:50:40.000Z | 2021-07-18T15:31:38.000Z | bot/client.py | potocnikluka/discord-utility-bot | 6ccd808043812579278244dcaac1a5ce473d77cc | [
"MIT"
] | 1 | 2021-10-10T10:06:49.000Z | 2021-10-10T10:06:49.000Z | import os
import inspect
import sys
import traceback
import nextcord
import logging
from functools import partial
import bot.commands as commands
import bot.games as games
import bot.decorators as decorators
import bot.utils as utils
class UtilityClient(nextcord.Client):
"""Client connection handling events recieved from Discord."""
def __init__(self, *, version, database, log_level, **options):
super().__init__(**options)
self.version = version
self.logger = logging.getLogger('utility_client')
self.logger.setLevel(logging.INFO if not log_level else int(log_level))
self.ready = False
self.database = database
self.commands = {}
self.games = {}
self.decorated_methods = {}
self.queue = utils.Queue(self)
self.default_type = 'Hello world!'
self.default_deletion_times = {}
def __initialize_commands__(self, cmds, cmds_dict):
# fill commands/games dictionary with all commands objects
for Command in cmds:
# save the commands' decorated methods in a dict
command = Command(self)
cmds_dict[command.__class__.__name__] = command
if hasattr(command, 'default_deletion_time'):
self.default_deletion_times[
command.__class__.__name__] = command.default_deletion_time
self.logger.debug(
msg='Initializing command: ' + command.__class__.__name__)
for Dec in (dec for dec in decorators.__dict__.values()
if isinstance(dec, type)):
if not Dec or not hasattr(Dec, 'methods'):
continue
for v in Dec.methods(command).values():
if not v:
continue
self.decorated_methods.setdefault(
Dec.__name__,
{}).setdefault(command.__class__.__name__,
[]).append(partial(v, command))
async def call_decorated_methods(
self, method_type, command_name, *args):
"""
Call all command's methods with 'method_type' decorator.
"""
if (method_type not in self.decorated_methods or
command_name not in self.decorated_methods.get(method_type)):
return
self.logger.debug(
msg=f'Calling decorator methods: {method_type} ({command_name})')
for method in self.decorated_methods.get(method_type
).get(command_name):
if not inspect.iscoroutinefunction(method):
await method(*args)
else:
method(*args)
async def restart_deletion_timers(self):
deleting = await self.database.Messages.get_messages_by_info(
name='deletion_time')
self.logger.debug(msg='Restarting deletion timers')
for i in deleting:
try:
channel = self.get_channel(i.get('channel_id'))
msg = await channel.fetch_message(int(i.get('id')))
timestamp = i.get('info')
time_dif = utils.time_dif(timestamp)
if not time_dif or time_dif < 0:
await msg.delete()
else:
await msg.delete(delay=time_dif)
except Exception:
continue
async def on_ready(self):
try:
if not self.user:
self.logger.critical(msg='Client user failed to connect!')
return
self.logger.debug(msg="Client user logged in\n")
if not self.database or not self.database.connected:
self.logger.critical(msg='Failed connecting to database!')
await self.close()
return
self.logger.info(msg='Version: ' + self.version)
self.logger.info(msg='Client: ' + str(self.user))
activity = nextcord.Game(name='"Mention me!"', type=2)
status = nextcord.Status.idle
await self.change_presence(status=status, activity=activity)
self.logger.info(msg='Status: Playing {}'.format(activity))
# initialize all commands and games
self.__initialize_commands__(
(cls for cls in commands.__dict__.values()
if isinstance(cls, type)), self.commands)
self.__initialize_commands__(
(cls for cls in games.__dict__.values()
if isinstance(cls, type)), self.games)
await self.restart_deletion_timers()
self.ready = True
self.logger.info(msg='Client ready!\n')
except Exception as exception:
self.logger.critical(exception)
self.ready = False
await self.close()
def determine_msg_type(self, msg):
if (msg.author.id == self.user.id or
msg.author.bot or
msg.content.split() is None or
len(msg.content.split()) < 1):
return
if msg.reference is not None and msg.reference.message_id:
return 'reply'
if str(msg.channel.type) == 'public_thread':
return 'thread_message'
user = self.user if str(
msg.channel.type) == 'private' else msg.guild.me
if (len(msg.mentions) == 1 and msg.mentions[0].id == self.user.id and
msg.channel.permissions_for(user).send_messages):
return 'client_mention'
def check_client_permissions(self, msg):
return not isinstance(msg.channel, nextcord.TextChannel) or (
msg.channel.permissions_for(msg.guild.me).send_messages and
msg.channel.permissions_for(msg.guild.me).read_messages and
msg.channel.permissions_for(msg.guild.me).read_message_history and
msg.channel.permissions_for(msg.guild.me).manage_roles and
msg.channel.permissions_for(msg.guild.me).create_public_threads
)
async def validate_author(self, msg, type):
if type == 'client_mention':
return True
prev_msg = None
author_id = None
if type == 'reply':
prev_msg = await msg.channel.fetch_message(
msg.reference.message_id)
author_id = msg.author.id
elif type == 'thread_message':
prev_msg = await msg.channel.parent.fetch_message(
msg.channel.id)
author_id = msg.author.id
if type == 'menu_select':
prev_msg = await msg.message.channel.fetch_message(
msg.message.id)
author_id = msg.user.id
elif type == 'button_click':
prev_msg = await msg.message.channel.fetch_message(
msg.message.id)
author_id = msg.user.id
msg_info = await self.database.Messages.get_message(prev_msg.id)
if (author_id and not msg_info and type == 'reply'
and not isinstance(msg.channel, nextcord.TextChannel)):
return True
if not author_id or not msg_info:
self.logger.debug(msg='Failed validating author: no info')
return False
self.logger.debug(msg='Validating author: {} - {}'.format(
author_id, msg_info.get('author_id')))
return (not msg_info.get('author_id') or
str(msg_info.get('author_id')) == str(author_id))
async def on_message(self, msg):
if not self.ready or not self.check_client_permissions(msg):
return
# determine the type of message
msg_type = self.determine_msg_type(msg)
if (not msg_type or (
msg_type != 'reply' and
not isinstance(msg.channel, nextcord.TextChannel) and
not isinstance(msg.channel, nextcord.threads.Thread)) or
(msg_type == 'thread_message' and
not isinstance(msg.channel, nextcord.threads.Thread))):
return
# check if message is valid and user has the permissions to modify
# the message
if not await self.validate_author(msg, msg_type):
return
self.logger.debug(
msg='Validated message of type "{}" with id {}'.format(
msg_type, msg.id))
# dispatch the event in a queue, to avoid multiple or too few instances
# of same command
await self.queue.add_to_queue(
str(msg.id), msg_type, msg, function=self.dispatch)
async def on_client_mention(self, msg, old_author_id=None):
"""
Send the commands' main menu when the bot is tagged.
If 'old_author_id' is not None, 'msg' will be edited
instead of sending a new message.
"""
# All the command should be initialized with methods with @MenuSelect
# or @ButtonClick commands
self.logger.debug(msg='Main menu ({}): {}'.format(
'Client mention' if not old_author_id else 'Home button',
str(msg.id)))
embed = utils.UtilityEmbed(
type=self.default_type, version=self.version,
color=utils.colors['black'])
options = []
for name, command in self.commands.items():
opt = nextcord.SelectOption(label=name)
if hasattr(command, 'description'):
opt.description = command.description
options.append(opt)
view = utils.build_view([
nextcord.ui.Select(
placeholder='Select a command',
options=options),
utils.help_button(),
utils.delete_button()
])
author_id = None
if old_author_id is None:
author_id = msg.author.id
msg = await msg.channel.send(embed=embed, view=view)
else:
await self.database.Messages.delete_message(id=msg.id)
await msg.edit(embed=embed, view=view)
author_id = old_author_id
# persist the message
await self.database.Messages.add_message(
id=msg.id, channel_id=msg.channel.id, author_id=author_id)
async def on_reply(self, msg):
"""
Call methods with @Reply tag when user
replies to the bot's message.
"""
self.logger.debug(msg='Reply: ' + str(msg.id))
msg = await msg.channel.fetch_message(msg.id)
if msg is None:
return
referenced_msg = await msg.channel.fetch_message(
msg.reference.message_id)
if referenced_msg is None:
return
cmd = utils.UtilityEmbed(embed=referenced_msg.embeds[0]).get_type()
await self.call_decorated_methods(
'Reply', cmd, msg,
msg.author, referenced_msg)
async def on_thread_message(self, msg):
"""
Call methods with @Thread tag when user sends
a message in bot's thread.
"""
self.logger.debug(msg='Thread message: ' + str(msg.id))
parent_msg = await msg.channel.parent.fetch_message(msg.channel.id)
cmd = utils.UtilityEmbed(embed=parent_msg.embeds[0]).get_type()
await self.call_decorated_methods(
'Thread', cmd, msg, msg.author, parent_msg)
def determine_interaction_type(self, interaction):
if interaction.user.bot:
return
if interaction.data['component_type'] == 2:
return 'button_click'
elif interaction.data['component_type'] == 3:
return 'menu_select'
async def on_interaction(self, interaction):
"""
Determine type of interaction and trigger "on_button_click"
or "on_menu_select" events.
"""
if not self.ready or not self.check_client_permissions(
interaction.message):
return
try:
# defer interaction response to avoid
# "This interaction failed" in nextcord channel
# when clicking on a button created before bot restarted
await interaction.response.defer()
except nextcord.NotFound:
pass
interaction_type = self.determine_interaction_type(interaction)
if not interaction_type:
return
valid_interaction = await self.validate_author(
interaction, interaction_type)
if not valid_interaction:
return
self.logger.debug(
msg='Validated interaction of type "{}" on message {}'.format(
interaction_type, interaction.message.id))
# process interactions in a queue to avoid
# multiple or too few instances
if interaction_type == 'button_click':
await self.queue.add_to_queue(
str(interaction.message.id),
interaction,
function=self.on_button_click)
elif interaction_type == 'menu_select':
await self.queue.add_to_queue(
str(interaction.message.id),
interaction,
function=self.on_menu_select)
async def on_button_click(self, interaction):
"""
Call methods with @ButtonClick tag when user
clicks a button on bot's message.
Different events are triggered for buttons
'delete', 'help' and 'home'.
"""
self.logger.debug(msg='Button click: ' + str(interaction.message.id))
msg = await interaction.message.channel.fetch_message(
interaction.message.id)
if msg is None or len(msg.embeds) != 1:
return
cmd = utils.UtilityEmbed(embed=msg.embeds[0]).get_type()
if not cmd:
return
button = utils.get_component(interaction.data['custom_id'], msg)
if not button:
return
# if delete button call on_delete_button_click
if button.label in ['delete', 'help', 'home', 'back']:
# delete message if deletable
if button.label == 'delete':
self.dispatch('delete_button_click', msg)
return
# show help about the current stage of the interface
if button.label == 'help':
self.dispatch('help_button_click', msg)
return
if button.label == 'back':
await self.call_decorated_methods(
'MenuSelect',
utils.UtilityEmbed(embed=msg.embeds[0]).get_type(),
msg,
interaction.user,
interaction.data,
interaction.followup)
return
# return to main menu
if button.label == 'home':
await self.client.database.Messages.update_message_author(
id=msg.id, author_id=interaction.user.id)
self.dispatch('client_mention', msg, interaction.user.id)
return
await self.call_decorated_methods(
'ButtonClick',
cmd,
msg,
interaction.user,
button,
interaction.followup)
async def on_delete_button_click(self, msg):
"""
If the message is not pinned, delete it
"""
self.logger.debug(msg='Delete button: ' + str(msg.id))
if msg.pinned:
return
await msg.edit(content=None,
embed=utils.UtilityEmbed(
type='Message has been deleted.',
version=self.version,
color=utils.colors['green']),
delete_after=2,
view=None)
async def on_help_button_click(self, msg):
"""
Edit the message into a help message, based
on message's type.
"""
self.logger.debug(msg='Help button: ' + str(msg.id))
old_embed = utils.UtilityEmbed(embed=msg.embeds[0])
name = old_embed.get_type()
if not name:
return
embed = nextcord.Embed(title='Help')
embed.set_footer(text=old_embed.footer.text)
if name == self.default_type:
embed.description = ('Select a command in the main menu,\n' +
'then click on the "help" ' +
'button for more info about the command.\n' +
'**\nOnly the user who started ' +
'the menu may navigate it\n**')
else:
embed.description = self.commands[name].description
if name in self.decorated_methods['Help']:
embed.description += ('\n\n' + '\n'.join([
i()
for i in self.decorated_methods['Help'][name]
]))
if hasattr(self.commands[name], 'color'):
embed.color = self.commands[name].color
if name == self.default_type:
components = [utils.home_button(), utils.delete_button()]
else:
components = [utils.back_button(), utils.delete_button()]
view = utils.build_view(components)
embed.color = utils.colors['white']
await msg.edit(embed=embed, view=view)
async def on_menu_select(self, interaction):
"""
Call methods with @MenuSelect tag when user
selects a dropdown menu item on bot's message.
"""
self.logger.debug(msg='Menu select: ' + str(interaction.message.id))
msg = await interaction.message.channel.fetch_message(
interaction.message.id)
if msg is None or len(msg.embeds) != 1:
return
cmd = utils.UtilityEmbed(embed=msg.embeds[0]).get_type()
if (interaction.data and interaction.data.get('values') and
len(interaction.data['values']) > 0 and (
cmd == self.default_type or
interaction.data['values'][0] in self.games)):
await self.call_decorated_methods(
'MenuSelect',
interaction.data['values'][0],
msg,
interaction.user,
interaction.data,
interaction.followup)
else:
await self.call_decorated_methods(
'MenuSelect',
cmd,
msg,
interaction.user,
interaction.data,
interaction.followup)
async def on_raw_message_delete(self, msg):
# clean up message's info from database when deleted
self.logger.debug(msg='Deleting message: ' + str(msg.message_id))
await self.database.Messages.delete_message(id=msg.message_id)
async def on_raw_bulk_message_delete(self, payload):
# clean up bulk deleted message's info from
# database when deleted
self.logger.debug(msg='Bulk deleting {} messages'.format(
len(payload.message_ids)))
for i in payload.message_ids:
await self.database.Messages.delete_message(id=str(i))
async def on_error(self, error, *args, **kwargs):
root_dir = os.path.abspath(os.curdir)
if len(args) == 3:
ex_type, ex, tb = args
else:
ex_type, ex, tb = sys.exc_info()
x = traceback.format_list(traceback.extract_tb(tb))
# 10008 -> unknown message, can ignore as mostly
# when deleting an already deleted message
if 'error code: 10008' in str(ex):
return
result = [
'{}({})\n{}'.format(str(ex_type.__name__), str(ex), 56 * '-')
]
if str(ex) == 'MySQL Connection not available.':
await self.database.connect_database()
return
for i in x:
if root_dir in i and 'super()._run_event' not in i:
result.append(i)
self.logger.error('\n'.join(result) + '\n')
| 38.298279 | 79 | 0.570444 | import os
import inspect
import sys
import traceback
import nextcord
import logging
from functools import partial
import bot.commands as commands
import bot.games as games
import bot.decorators as decorators
import bot.utils as utils
class UtilityClient(nextcord.Client):
def __init__(self, *, version, database, log_level, **options):
super().__init__(**options)
self.version = version
self.logger = logging.getLogger('utility_client')
self.logger.setLevel(logging.INFO if not log_level else int(log_level))
self.ready = False
self.database = database
self.commands = {}
self.games = {}
self.decorated_methods = {}
self.queue = utils.Queue(self)
self.default_type = 'Hello world!'
self.default_deletion_times = {}
def __initialize_commands__(self, cmds, cmds_dict):
for Command in cmds:
command = Command(self)
cmds_dict[command.__class__.__name__] = command
if hasattr(command, 'default_deletion_time'):
self.default_deletion_times[
command.__class__.__name__] = command.default_deletion_time
self.logger.debug(
msg='Initializing command: ' + command.__class__.__name__)
for Dec in (dec for dec in decorators.__dict__.values()
if isinstance(dec, type)):
if not Dec or not hasattr(Dec, 'methods'):
continue
for v in Dec.methods(command).values():
if not v:
continue
self.decorated_methods.setdefault(
Dec.__name__,
{}).setdefault(command.__class__.__name__,
[]).append(partial(v, command))
async def call_decorated_methods(
self, method_type, command_name, *args):
if (method_type not in self.decorated_methods or
command_name not in self.decorated_methods.get(method_type)):
return
self.logger.debug(
msg=f'Calling decorator methods: {method_type} ({command_name})')
for method in self.decorated_methods.get(method_type
).get(command_name):
if not inspect.iscoroutinefunction(method):
await method(*args)
else:
method(*args)
async def restart_deletion_timers(self):
deleting = await self.database.Messages.get_messages_by_info(
name='deletion_time')
self.logger.debug(msg='Restarting deletion timers')
for i in deleting:
try:
channel = self.get_channel(i.get('channel_id'))
msg = await channel.fetch_message(int(i.get('id')))
timestamp = i.get('info')
time_dif = utils.time_dif(timestamp)
if not time_dif or time_dif < 0:
await msg.delete()
else:
await msg.delete(delay=time_dif)
except Exception:
continue
async def on_ready(self):
try:
if not self.user:
self.logger.critical(msg='Client user failed to connect!')
return
self.logger.debug(msg="Client user logged in\n")
if not self.database or not self.database.connected:
self.logger.critical(msg='Failed connecting to database!')
await self.close()
return
self.logger.info(msg='Version: ' + self.version)
self.logger.info(msg='Client: ' + str(self.user))
activity = nextcord.Game(name='"Mention me!"', type=2)
status = nextcord.Status.idle
await self.change_presence(status=status, activity=activity)
self.logger.info(msg='Status: Playing {}'.format(activity))
# initialize all commands and games
self.__initialize_commands__(
(cls for cls in commands.__dict__.values()
if isinstance(cls, type)), self.commands)
self.__initialize_commands__(
(cls for cls in games.__dict__.values()
if isinstance(cls, type)), self.games)
await self.restart_deletion_timers()
self.ready = True
self.logger.info(msg='Client ready!\n')
except Exception as exception:
self.logger.critical(exception)
self.ready = False
await self.close()
def determine_msg_type(self, msg):
if (msg.author.id == self.user.id or
msg.author.bot or
msg.content.split() is None or
len(msg.content.split()) < 1):
return
if msg.reference is not None and msg.reference.message_id:
return 'reply'
if str(msg.channel.type) == 'public_thread':
return 'thread_message'
user = self.user if str(
msg.channel.type) == 'private' else msg.guild.me
if (len(msg.mentions) == 1 and msg.mentions[0].id == self.user.id and
msg.channel.permissions_for(user).send_messages):
return 'client_mention'
def check_client_permissions(self, msg):
return not isinstance(msg.channel, nextcord.TextChannel) or (
msg.channel.permissions_for(msg.guild.me).send_messages and
msg.channel.permissions_for(msg.guild.me).read_messages and
msg.channel.permissions_for(msg.guild.me).read_message_history and
msg.channel.permissions_for(msg.guild.me).manage_roles and
msg.channel.permissions_for(msg.guild.me).create_public_threads
)
async def validate_author(self, msg, type):
if type == 'client_mention':
return True
prev_msg = None
author_id = None
if type == 'reply':
prev_msg = await msg.channel.fetch_message(
msg.reference.message_id)
author_id = msg.author.id
elif type == 'thread_message':
prev_msg = await msg.channel.parent.fetch_message(
msg.channel.id)
author_id = msg.author.id
if type == 'menu_select':
prev_msg = await msg.message.channel.fetch_message(
msg.message.id)
author_id = msg.user.id
elif type == 'button_click':
prev_msg = await msg.message.channel.fetch_message(
msg.message.id)
author_id = msg.user.id
msg_info = await self.database.Messages.get_message(prev_msg.id)
if (author_id and not msg_info and type == 'reply'
and not isinstance(msg.channel, nextcord.TextChannel)):
return True
if not author_id or not msg_info:
self.logger.debug(msg='Failed validating author: no info')
return False
self.logger.debug(msg='Validating author: {} - {}'.format(
author_id, msg_info.get('author_id')))
return (not msg_info.get('author_id') or
str(msg_info.get('author_id')) == str(author_id))
async def on_message(self, msg):
if not self.ready or not self.check_client_permissions(msg):
return
# determine the type of message
msg_type = self.determine_msg_type(msg)
if (not msg_type or (
msg_type != 'reply' and
not isinstance(msg.channel, nextcord.TextChannel) and
not isinstance(msg.channel, nextcord.threads.Thread)) or
(msg_type == 'thread_message' and
not isinstance(msg.channel, nextcord.threads.Thread))):
return
# check if message is valid and user has the permissions to modify
# the message
if not await self.validate_author(msg, msg_type):
return
self.logger.debug(
msg='Validated message of type "{}" with id {}'.format(
msg_type, msg.id))
# dispatch the event in a queue, to avoid multiple or too few instances
# of same command
await self.queue.add_to_queue(
str(msg.id), msg_type, msg, function=self.dispatch)
async def on_client_mention(self, msg, old_author_id=None):
# All the command should be initialized with methods with @MenuSelect
# or @ButtonClick commands
self.logger.debug(msg='Main menu ({}): {}'.format(
'Client mention' if not old_author_id else 'Home button',
str(msg.id)))
embed = utils.UtilityEmbed(
type=self.default_type, version=self.version,
color=utils.colors['black'])
options = []
for name, command in self.commands.items():
opt = nextcord.SelectOption(label=name)
if hasattr(command, 'description'):
opt.description = command.description
options.append(opt)
view = utils.build_view([
nextcord.ui.Select(
placeholder='Select a command',
options=options),
utils.help_button(),
utils.delete_button()
])
author_id = None
if old_author_id is None:
author_id = msg.author.id
msg = await msg.channel.send(embed=embed, view=view)
else:
await self.database.Messages.delete_message(id=msg.id)
await msg.edit(embed=embed, view=view)
author_id = old_author_id
# persist the message
await self.database.Messages.add_message(
id=msg.id, channel_id=msg.channel.id, author_id=author_id)
async def on_reply(self, msg):
self.logger.debug(msg='Reply: ' + str(msg.id))
msg = await msg.channel.fetch_message(msg.id)
if msg is None:
return
referenced_msg = await msg.channel.fetch_message(
msg.reference.message_id)
if referenced_msg is None:
return
cmd = utils.UtilityEmbed(embed=referenced_msg.embeds[0]).get_type()
await self.call_decorated_methods(
'Reply', cmd, msg,
msg.author, referenced_msg)
async def on_thread_message(self, msg):
self.logger.debug(msg='Thread message: ' + str(msg.id))
parent_msg = await msg.channel.parent.fetch_message(msg.channel.id)
cmd = utils.UtilityEmbed(embed=parent_msg.embeds[0]).get_type()
await self.call_decorated_methods(
'Thread', cmd, msg, msg.author, parent_msg)
def determine_interaction_type(self, interaction):
if interaction.user.bot:
return
if interaction.data['component_type'] == 2:
return 'button_click'
elif interaction.data['component_type'] == 3:
return 'menu_select'
async def on_interaction(self, interaction):
if not self.ready or not self.check_client_permissions(
interaction.message):
return
try:
# defer interaction response to avoid
# "This interaction failed" in nextcord channel
# when clicking on a button created before bot restarted
await interaction.response.defer()
except nextcord.NotFound:
pass
interaction_type = self.determine_interaction_type(interaction)
if not interaction_type:
return
valid_interaction = await self.validate_author(
interaction, interaction_type)
if not valid_interaction:
return
self.logger.debug(
msg='Validated interaction of type "{}" on message {}'.format(
interaction_type, interaction.message.id))
# process interactions in a queue to avoid
# multiple or too few instances
if interaction_type == 'button_click':
await self.queue.add_to_queue(
str(interaction.message.id),
interaction,
function=self.on_button_click)
elif interaction_type == 'menu_select':
await self.queue.add_to_queue(
str(interaction.message.id),
interaction,
function=self.on_menu_select)
async def on_button_click(self, interaction):
self.logger.debug(msg='Button click: ' + str(interaction.message.id))
msg = await interaction.message.channel.fetch_message(
interaction.message.id)
if msg is None or len(msg.embeds) != 1:
return
cmd = utils.UtilityEmbed(embed=msg.embeds[0]).get_type()
if not cmd:
return
button = utils.get_component(interaction.data['custom_id'], msg)
if not button:
return
# if delete button call on_delete_button_click
if button.label in ['delete', 'help', 'home', 'back']:
# delete message if deletable
if button.label == 'delete':
self.dispatch('delete_button_click', msg)
return
# show help about the current stage of the interface
if button.label == 'help':
self.dispatch('help_button_click', msg)
return
if button.label == 'back':
await self.call_decorated_methods(
'MenuSelect',
utils.UtilityEmbed(embed=msg.embeds[0]).get_type(),
msg,
interaction.user,
interaction.data,
interaction.followup)
return
# return to main menu
if button.label == 'home':
await self.client.database.Messages.update_message_author(
id=msg.id, author_id=interaction.user.id)
self.dispatch('client_mention', msg, interaction.user.id)
return
await self.call_decorated_methods(
'ButtonClick',
cmd,
msg,
interaction.user,
button,
interaction.followup)
async def on_delete_button_click(self, msg):
self.logger.debug(msg='Delete button: ' + str(msg.id))
if msg.pinned:
return
await msg.edit(content=None,
embed=utils.UtilityEmbed(
type='Message has been deleted.',
version=self.version,
color=utils.colors['green']),
delete_after=2,
view=None)
async def on_help_button_click(self, msg):
self.logger.debug(msg='Help button: ' + str(msg.id))
old_embed = utils.UtilityEmbed(embed=msg.embeds[0])
name = old_embed.get_type()
if not name:
return
embed = nextcord.Embed(title='Help')
embed.set_footer(text=old_embed.footer.text)
if name == self.default_type:
embed.description = ('Select a command in the main menu,\n' +
'then click on the "help" ' +
'button for more info about the command.\n' +
'**\nOnly the user who started ' +
'the menu may navigate it\n**')
else:
embed.description = self.commands[name].description
if name in self.decorated_methods['Help']:
embed.description += ('\n\n' + '\n'.join([
i()
for i in self.decorated_methods['Help'][name]
]))
if hasattr(self.commands[name], 'color'):
embed.color = self.commands[name].color
if name == self.default_type:
components = [utils.home_button(), utils.delete_button()]
else:
components = [utils.back_button(), utils.delete_button()]
view = utils.build_view(components)
embed.color = utils.colors['white']
await msg.edit(embed=embed, view=view)
async def on_menu_select(self, interaction):
self.logger.debug(msg='Menu select: ' + str(interaction.message.id))
msg = await interaction.message.channel.fetch_message(
interaction.message.id)
if msg is None or len(msg.embeds) != 1:
return
cmd = utils.UtilityEmbed(embed=msg.embeds[0]).get_type()
if (interaction.data and interaction.data.get('values') and
len(interaction.data['values']) > 0 and (
cmd == self.default_type or
interaction.data['values'][0] in self.games)):
await self.call_decorated_methods(
'MenuSelect',
interaction.data['values'][0],
msg,
interaction.user,
interaction.data,
interaction.followup)
else:
await self.call_decorated_methods(
'MenuSelect',
cmd,
msg,
interaction.user,
interaction.data,
interaction.followup)
async def on_raw_message_delete(self, msg):
# clean up message's info from database when deleted
self.logger.debug(msg='Deleting message: ' + str(msg.message_id))
await self.database.Messages.delete_message(id=msg.message_id)
async def on_raw_bulk_message_delete(self, payload):
# database when deleted
self.logger.debug(msg='Bulk deleting {} messages'.format(
len(payload.message_ids)))
for i in payload.message_ids:
await self.database.Messages.delete_message(id=str(i))
async def on_error(self, error, *args, **kwargs):
root_dir = os.path.abspath(os.curdir)
if len(args) == 3:
ex_type, ex, tb = args
else:
ex_type, ex, tb = sys.exc_info()
x = traceback.format_list(traceback.extract_tb(tb))
# 10008 -> unknown message, can ignore as mostly
# when deleting an already deleted message
if 'error code: 10008' in str(ex):
return
result = [
'{}({})\n{}'.format(str(ex_type.__name__), str(ex), 56 * '-')
]
if str(ex) == 'MySQL Connection not available.':
await self.database.connect_database()
return
for i in x:
if root_dir in i and 'super()._run_event' not in i:
result.append(i)
self.logger.error('\n'.join(result) + '\n')
| true | true |
1c2bdce8b5cb4cf01ff364e7c93fcedef0b4ad64 | 35,025 | py | Python | fairseq/models/dlcl_transformer.py | libeineu/SDT-Training | d33a836c1b3258748ec11c4d64998e0dcc9792df | [
"BSD-3-Clause"
] | 9 | 2020-10-04T06:20:40.000Z | 2021-05-19T06:25:54.000Z | fairseq/models/dlcl_transformer.py | libeineu/SDT-Training | d33a836c1b3258748ec11c4d64998e0dcc9792df | [
"BSD-3-Clause"
] | 1 | 2021-01-21T04:20:52.000Z | 2021-01-21T04:20:52.000Z | fairseq/models/dlcl_transformer.py | libeineu/SDT-Training | d33a836c1b3258748ec11c4d64998e0dcc9792df | [
"BSD-3-Clause"
] | 1 | 2021-01-19T06:12:27.000Z | 2021-01-19T06:12:27.000Z | # Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
# author: Bei Li
# email: libei_neu@outlook.com
# time: 2018/12/9
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import options, utils
from fairseq.modules import (
AdaptiveInput, AdaptiveSoftmax, CharacterTokenEmbedder, LayerNorm,
LearnedPositionalEmbedding, MultiheadAttention, SinusoidalPositionalEmbedding,
RelativeMultiheadAttention,
)
from . import (
FairseqIncrementalDecoder, FairseqEncoder, FairseqLanguageModel,
FairseqModel, register_model, register_model_architecture,
)
from fairseq.modules.layer_history import CreateLayerHistory
@register_model('dlcl_transformer')
class DLCLTransformerModel(FairseqModel):
"""
Transformer model from `"Attention Is All You Need" (Vaswani, et al, 2017)
<https://arxiv.org/abs/1706.03762>`_.
Args:
encoder (TransformerEncoder): the encoder
decoder (TransformerDecoder): the decoder
The Transformer model provides the following named architectures and
command-line arguments:
.. argparse::
:ref: fairseq.models.transformer_parser
:prog:
"""
def __init__(self, encoder, decoder):
super().__init__(encoder, decoder)
@staticmethod
def add_args(parser):
"""Add model-specific arguments to the parser."""
# fmt: off
parser.add_argument('--dropout', type=float, metavar='D',
help='dropout probability')
parser.add_argument('--attention-dropout', type=float, metavar='D',
help='dropout probability for attention weights')
parser.add_argument('--relu-dropout', type=float, metavar='D',
help='dropout probability after ReLU in FFN')
parser.add_argument('--encoder-embed-path', type=str, metavar='STR',
help='path to pre-trained encoder embedding')
parser.add_argument('--encoder-embed-dim', type=int, metavar='N',
help='encoder embedding dimension')
parser.add_argument('--encoder-ffn-embed-dim', type=int, metavar='N',
help='encoder embedding dimension for FFN')
parser.add_argument('--encoder-layers', type=int, metavar='N',
help='num encoder layers')
parser.add_argument('--encoder-attention-heads', type=int, metavar='N',
help='num encoder attention heads')
parser.add_argument('--encoder-normalize-before', action='store_true',
help='apply layernorm before each encoder block')
parser.add_argument('--encoder-learned-pos', action='store_true',
help='use learned positional embeddings in the encoder')
parser.add_argument('--decoder-embed-path', type=str, metavar='STR',
help='path to pre-trained decoder embedding')
parser.add_argument('--decoder-embed-dim', type=int, metavar='N',
help='decoder embedding dimension')
parser.add_argument('--decoder-ffn-embed-dim', type=int, metavar='N',
help='decoder embedding dimension for FFN')
parser.add_argument('--decoder-layers', type=int, metavar='N',
help='num decoder layers')
parser.add_argument('--decoder-attention-heads', type=int, metavar='N',
help='num decoder attention heads')
parser.add_argument('--decoder-learned-pos', action='store_true',
help='use learned positional embeddings in the decoder')
parser.add_argument('--decoder-normalize-before', action='store_true',
help='apply layernorm before each decoder block')
parser.add_argument('--share-decoder-input-output-embed', action='store_true',
help='share decoder input and output embeddings')
parser.add_argument('--share-all-embeddings', action='store_true',
help='share encoder, decoder and output embeddings'
' (requires shared dictionary and embed dim)')
parser.add_argument('--no-token-positional-embeddings', default=False, action='store_true',
help='if set, disables positional embeddings (outside self attention)')
parser.add_argument('--adaptive-softmax-cutoff', metavar='EXPR',
help='comma separated list of adaptive softmax cutoff points. '
'Must be used with adaptive_loss criterion'),
parser.add_argument('--adaptive-softmax-dropout', type=float, metavar='D',
help='sets adaptive softmax dropout for the tail projections')
parser.add_argument('--max-relative-length', type=int, default=-1,
help='the max relative length')
# fmt: on
### dense layer parameters
parser.add_argument('--encoder-history-type',
help='encoder layer history type')
parser.add_argument('--decoder-history-type',
help='decoder layer history type')
parser.add_argument('--encoder-integration-type', choices=['avg', 'sum'],
help='encoder layer integration type')
parser.add_argument('--decoder-integration-type', choices=['avg', 'sum'],
help='decoder layer integration type')
@classmethod
def build_model(cls, args, task):
"""Build a new model instance."""
# make sure all arguments are present in older models
base_architecture(args)
if not hasattr(args, 'max_source_positions'):
args.max_source_positions = 1024
if not hasattr(args, 'max_target_positions'):
args.max_target_positions = 1024
src_dict, tgt_dict = task.source_dictionary, task.target_dictionary
def build_embedding(dictionary, embed_dim, path=None):
num_embeddings = len(dictionary)
padding_idx = dictionary.pad()
emb = Embedding(num_embeddings, embed_dim, padding_idx)
# if provided, load from preloaded dictionaries
if path:
embed_dict = utils.parse_embedding(path)
utils.load_embedding(embed_dict, dictionary, emb)
return emb
if args.share_all_embeddings:
if src_dict != tgt_dict:
raise ValueError('--share-all-embeddings requires a joined dictionary')
if args.encoder_embed_dim != args.decoder_embed_dim:
raise ValueError(
'--share-all-embeddings requires --encoder-embed-dim to match --decoder-embed-dim')
if args.decoder_embed_path and (
args.decoder_embed_path != args.encoder_embed_path):
raise ValueError('--share-all-embeddings not compatible with --decoder-embed-path')
encoder_embed_tokens = build_embedding(
src_dict, args.encoder_embed_dim, args.encoder_embed_path
)
decoder_embed_tokens = encoder_embed_tokens
args.share_decoder_input_output_embed = True
else:
encoder_embed_tokens = build_embedding(
src_dict, args.encoder_embed_dim, args.encoder_embed_path
)
decoder_embed_tokens = build_embedding(
tgt_dict, args.decoder_embed_dim, args.decoder_embed_path
)
encoder = DLCLTransformerEncoder(args, src_dict, encoder_embed_tokens)
decoder = DLCLTransformerDecoder(args, tgt_dict, decoder_embed_tokens)
return DLCLTransformerModel(encoder, decoder)
class DLCLTransformerEncoder(FairseqEncoder):
"""
Transformer encoder consisting of *args.encoder_layers* layers. Each layer
is a :class:`TransformerEncoderLayer`.
Args:
args (argparse.Namespace): parsed command-line arguments
dictionary (~fairseq.data.Dictionary): encoding dictionary
embed_tokens (torch.nn.Embedding): input embedding
left_pad (bool, optional): whether the input is left-padded
(default: True).
"""
def __init__(self, args, dictionary, embed_tokens, left_pad=True):
super().__init__(dictionary)
self.dropout = args.dropout
embed_dim = embed_tokens.embedding_dim
self.padding_idx = embed_tokens.padding_idx
self.max_source_positions = args.max_source_positions
self.embed_tokens = embed_tokens
self.embed_scale = math.sqrt(embed_dim)
self.embed_positions = PositionalEmbedding(
args.max_source_positions, embed_dim, self.padding_idx,
left_pad=left_pad,
learned=args.encoder_learned_pos,
) if not args.no_token_positional_embeddings else None
# create encoder layer history
self.history = CreateLayerHistory(args, is_encoder=True)
self.layers = nn.ModuleList([])
self.layers.extend([
TransformerEncoderLayer(args)
for i in range(args.encoder_layers)
])
self.register_buffer('version', torch.Tensor([2]))
self.normalize = args.encoder_normalize_before
if self.normalize:
self.layer_norm = LayerNorm(embed_dim)
def forward(self, src_tokens, src_lengths):
"""
Args:
src_tokens (LongTensor): tokens in the source language of shape
`(batch, src_len)`
src_lengths (torch.LongTensor): lengths of each source sentence of
shape `(batch)`
Returns:
dict:
- **encoder_out** (Tensor): the last encoder layer's output of
shape `(src_len, batch, embed_dim)`
- **encoder_padding_mask** (ByteTensor): the positions of
padding elements of shape `(batch, src_len)`
"""
if self.history is not None:
self.history.clean()
# embed tokens and positions
x = self.embed_scale * self.embed_tokens(src_tokens)
if self.embed_positions is not None:
x += self.embed_positions(src_tokens)
x = F.dropout(x, p=self.dropout, training=self.training)
# B x T x C -> T x B x C
x = x.transpose(0, 1)
# add emb into history
if self.history is not None:
self.history.add(x)
# compute padding mask
encoder_padding_mask = src_tokens.eq(self.padding_idx)
if not encoder_padding_mask.any():
encoder_padding_mask = None
# encoder layers
for layer in self.layers:
if self.history is not None:
x = self.history.pop()
x = layer(x, encoder_padding_mask)
if self.history is not None:
self.history.add(x)
if self.history is not None:
x = self.history.pop()
if self.normalize:
x = self.layer_norm(x)
return {
'encoder_out': x, # T x B x C
'encoder_padding_mask': encoder_padding_mask, # B x T
}
def reorder_encoder_out(self, encoder_out, new_order):
"""
Reorder encoder output according to *new_order*.
Args:
encoder_out: output from the ``forward()`` method
new_order (LongTensor): desired order
Returns:
*encoder_out* rearranged according to *new_order*
"""
if encoder_out['encoder_out'] is not None:
encoder_out['encoder_out'] = \
encoder_out['encoder_out'].index_select(1, new_order)
if encoder_out['encoder_padding_mask'] is not None:
encoder_out['encoder_padding_mask'] = \
encoder_out['encoder_padding_mask'].index_select(0, new_order)
return encoder_out
def max_positions(self):
"""Maximum input length supported by the encoder."""
if self.embed_positions is None:
return self.max_source_positions
return min(self.max_source_positions, self.embed_positions.max_positions())
def upgrade_state_dict_named(self, state_dict, name):
"""Upgrade a (possibly old) state dict for new versions of fairseq."""
if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):
weights_key = '{}.embed_positions.weights'.format(name)
if weights_key in state_dict:
del state_dict[weights_key]
state_dict['{}.embed_positions._float_tensor'.format(name)] = torch.FloatTensor(1)
version_key = '{}.version'.format(name)
if utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) < 2:
# earlier checkpoints did not normalize after the stack of layers
self.layer_norm = None
self.normalize = False
state_dict[version_key] = torch.Tensor([1])
return state_dict
class DLCLTransformerDecoder(FairseqIncrementalDecoder):
"""
Transformer decoder consisting of *args.decoder_layers* layers. Each layer
is a :class:`TransformerDecoderLayer`.
Args:
args (argparse.Namespace): parsed command-line arguments
dictionary (~fairseq.data.Dictionary): decoding dictionary
embed_tokens (torch.nn.Embedding): output embedding
no_encoder_attn (bool, optional): whether to attend to encoder outputs
(default: False).
left_pad (bool, optional): whether the input is left-padded
(default: False).
final_norm (bool, optional): apply layer norm to the output of the
final decoder layer (default: True).
"""
def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False, left_pad=False, final_norm=True):
super().__init__(dictionary)
self.dropout = args.dropout
self.share_input_output_embed = args.share_decoder_input_output_embed
input_embed_dim = embed_tokens.embedding_dim
embed_dim = args.decoder_embed_dim
output_embed_dim = args.decoder_output_dim
padding_idx = embed_tokens.padding_idx
self.max_target_positions = args.max_target_positions
self.embed_tokens = embed_tokens
self.embed_scale = math.sqrt(embed_dim) # todo: try with input_embed_dim
self.project_in_dim = Linear(input_embed_dim, embed_dim, bias=False) if embed_dim != input_embed_dim else None
self.embed_positions = PositionalEmbedding(
args.max_target_positions, embed_dim, padding_idx,
left_pad=left_pad,
learned=args.decoder_learned_pos,
) if not args.no_token_positional_embeddings else None
# create decoder layer history
self.history = CreateLayerHistory(args, is_encoder=False)
self.layers = nn.ModuleList([])
self.layers.extend([
TransformerDecoderLayer(args, no_encoder_attn)
for _ in range(args.decoder_layers)
])
self.adaptive_softmax = None
self.project_out_dim = Linear(embed_dim, output_embed_dim, bias=False) \
if embed_dim != output_embed_dim and not args.tie_adaptive_weights else None
if args.adaptive_softmax_cutoff is not None:
self.adaptive_softmax = AdaptiveSoftmax(
len(dictionary),
output_embed_dim,
options.eval_str_list(args.adaptive_softmax_cutoff, type=int),
dropout=args.adaptive_softmax_dropout,
adaptive_inputs=embed_tokens if args.tie_adaptive_weights else None,
factor=args.adaptive_softmax_factor,
tie_proj=args.tie_adaptive_proj,
)
elif not self.share_input_output_embed:
self.embed_out = nn.Parameter(torch.Tensor(len(dictionary), output_embed_dim))
nn.init.normal_(self.embed_out, mean=0, std=output_embed_dim ** -0.5)
self.register_buffer('version', torch.Tensor([2]))
self.normalize = args.decoder_normalize_before and final_norm
if self.normalize:
self.layer_norm = LayerNorm(embed_dim)
def forward(self, prev_output_tokens, encoder_out=None, incremental_state=None):
"""
Args:
prev_output_tokens (LongTensor): previous decoder outputs of shape
`(batch, tgt_len)`, for input feeding/teacher forcing
encoder_out (Tensor, optional): output from the encoder, used for
encoder-side attention
incremental_state (dict): dictionary used for storing state during
:ref:`Incremental decoding`
Returns:
tuple:
- the last decoder layer's output of shape `(batch, tgt_len,
vocab)`
- the last decoder layer's attention weights of shape `(batch,
tgt_len, src_len)`
"""
# embed positions
if self.history is not None:
self.history.clean()
positions = self.embed_positions(
prev_output_tokens,
incremental_state=incremental_state,
) if self.embed_positions is not None else None
if incremental_state is not None:
prev_output_tokens = prev_output_tokens[:, -1:]
if positions is not None:
positions = positions[:, -1:]
# embed tokens and positions
x = self.embed_scale * self.embed_tokens(prev_output_tokens)
if self.project_in_dim is not None:
x = self.project_in_dim(x)
if positions is not None:
x += positions
x = F.dropout(x, p=self.dropout, training=self.training)
# B x T x C -> T x B x C
x = x.transpose(0, 1)
attn = None
inner_states = [x]
# add emb into history
if self.history is not None:
self.history.add(x)
# decoder layers
for layer in self.layers:
if self.history is not None:
x = self.history.pop()
x, attn = layer(
x,
encoder_out['encoder_out'] if encoder_out is not None else None,
encoder_out['encoder_padding_mask'] if encoder_out is not None else None,
incremental_state,
self_attn_mask=self.buffered_future_mask(x) if incremental_state is None else None,
)
inner_states.append(x)
if self.history is not None:
self.history.add(x)
if self.history is not None:
x = self.history.pop()
if self.normalize:
x = self.layer_norm(x)
# T x B x C -> B x T x C
x = x.transpose(0, 1)
if self.project_out_dim is not None:
x = self.project_out_dim(x)
if self.adaptive_softmax is None:
# project back to size of vocabulary
if self.share_input_output_embed:
x = F.linear(x, self.embed_tokens.weight)
else:
x = F.linear(x, self.embed_out)
return x, {'attn': attn, 'inner_states': inner_states}
def max_positions(self):
"""Maximum output length supported by the decoder."""
if self.embed_positions is None:
return self.max_target_positions
return min(self.max_target_positions, self.embed_positions.max_positions())
def buffered_future_mask(self, tensor):
dim = tensor.size(0)
if not hasattr(self, '_future_mask') or self._future_mask is None or self._future_mask.device != tensor.device:
self._future_mask = torch.triu(utils.fill_with_neg_inf(tensor.new(dim, dim)), 1)
if self._future_mask.size(0) < dim:
self._future_mask = torch.triu(utils.fill_with_neg_inf(self._future_mask.resize_(dim, dim)), 1)
return self._future_mask[:dim, :dim]
def upgrade_state_dict_named(self, state_dict, name):
"""Upgrade a (possibly old) state dict for new versions of fairseq."""
if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):
weights_key = '{}.embed_positions.weights'.format(name)
if weights_key in state_dict:
del state_dict[weights_key]
state_dict['{}.embed_positions._float_tensor'.format(name)] = torch.FloatTensor(1)
for i in range(len(self.layers)):
# update layer norms
layer_norm_map = {
'0': 'self_attn_layer_norm',
'1': 'encoder_attn_layer_norm',
'2': 'final_layer_norm'
}
for old, new in layer_norm_map.items():
for m in ('weight', 'bias'):
k = '{}.layers.{}.layer_norms.{}.{}'.format(name, i, old, m)
if k in state_dict:
state_dict['{}.layers.{}.{}.{}'.format(name, i, new, m)] = state_dict[k]
del state_dict[k]
if utils.item(state_dict.get('{}.version'.format(name), torch.Tensor([1]))[0]) < 2:
# earlier checkpoints did not normalize after the stack of layers
self.layer_norm = None
self.normalize = False
state_dict['{}.version'.format(name)] = torch.Tensor([1])
return state_dict
class TransformerEncoderLayer(nn.Module):
"""Encoder layer block.
In the original paper each operation (multi-head attention or FFN) is
postprocessed with: `dropout -> add residual -> layernorm`. In the
tensor2tensor code they suggest that learning is more robust when
preprocessing each layer with layernorm and postprocessing with:
`dropout -> add residual`. We default to the approach in the paper, but the
tensor2tensor approach can be enabled by setting
*args.encoder_normalize_before* to ``True``.
Args:
args (argparse.Namespace): parsed command-line arguments
"""
def __init__(self, args):
super().__init__()
self.embed_dim = args.encoder_embed_dim
if args.max_relative_length==-1:
self.self_attn = MultiheadAttention(
self.embed_dim, args.encoder_attention_heads,
dropout=args.attention_dropout,
)
else:
self.self_attn = RelativeMultiheadAttention(
self.embed_dim, args.encoder_attention_heads,
args.max_relative_length, dropout=args.attention_dropout,
)
self.dropout = args.dropout
self.relu_dropout = args.relu_dropout
self.normalize_before = args.encoder_normalize_before
self.fc1 = Linear(self.embed_dim, args.encoder_ffn_embed_dim)
self.fc2 = Linear(args.encoder_ffn_embed_dim, self.embed_dim)
self.layer_norms = nn.ModuleList([LayerNorm(self.embed_dim) for i in range(2)])
def forward(self, x, encoder_padding_mask):
"""
Args:
x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
encoder_padding_mask (ByteTensor): binary ByteTensor of shape
`(batch, src_len)` where padding elements are indicated by ``1``.
Returns:
encoded output of shape `(batch, src_len, embed_dim)`
"""
residual = x
x = self.maybe_layer_norm(0, x, before=True)
x, _ = self.self_attn(query=x, key=x, value=x, key_padding_mask=encoder_padding_mask)
x = F.dropout(x, p=self.dropout, training=self.training)
x = residual + x
x = self.maybe_layer_norm(0, x, after=True)
residual = x
x = self.maybe_layer_norm(1, x, before=True)
x = F.relu(self.fc1(x))
x = F.dropout(x, p=self.relu_dropout, training=self.training)
x = self.fc2(x)
x = F.dropout(x, p=self.dropout, training=self.training)
x = residual + x
x = self.maybe_layer_norm(1, x, after=True)
return x
def maybe_layer_norm(self, i, x, before=False, after=False):
assert before ^ after
if after ^ self.normalize_before:
return self.layer_norms[i](x)
else:
return x
class TransformerDecoderLayer(nn.Module):
"""Decoder layer block.
In the original paper each operation (multi-head attention, encoder
attention or FFN) is postprocessed with: `dropout -> add residual ->
layernorm`. In the tensor2tensor code they suggest that learning is more
robust when preprocessing each layer with layernorm and postprocessing with:
`dropout -> add residual`. We default to the approach in the paper, but the
tensor2tensor approach can be enabled by setting
*args.decoder_normalize_before* to ``True``.
Args:
args (argparse.Namespace): parsed command-line arguments
no_encoder_attn (bool, optional): whether to attend to encoder outputs
(default: False).
"""
def __init__(self, args, no_encoder_attn=False):
super().__init__()
self.embed_dim = args.decoder_embed_dim
if args.max_relative_length == -1:
self.self_attn = MultiheadAttention(
self.embed_dim, args.decoder_attention_heads,
dropout=args.attention_dropout,
)
else:
self.self_attn = RelativeMultiheadAttention(
self.embed_dim, args.decoder_attention_heads,
args.max_relative_length, dropout=args.attention_dropout,
)
self.dropout = args.dropout
self.relu_dropout = args.relu_dropout
self.normalize_before = args.decoder_normalize_before
self.self_attn_layer_norm = LayerNorm(self.embed_dim)
if no_encoder_attn:
self.encoder_attn = None
self.encoder_attn_layer_norm = None
else:
self.encoder_attn = MultiheadAttention(
self.embed_dim, args.decoder_attention_heads,
dropout=args.attention_dropout,
)
self.encoder_attn_layer_norm = LayerNorm(self.embed_dim)
self.fc1 = Linear(self.embed_dim, args.decoder_ffn_embed_dim)
self.fc2 = Linear(args.decoder_ffn_embed_dim, self.embed_dim)
self.final_layer_norm = LayerNorm(self.embed_dim)
self.need_attn = True
self.onnx_trace = False
def prepare_for_onnx_export_(self):
self.onnx_trace = True
def forward(self, x, encoder_out, encoder_padding_mask, incremental_state,
prev_self_attn_state=None, prev_attn_state=None, self_attn_mask=None,
self_attn_padding_mask=None):
"""
Args:
x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
encoder_padding_mask (ByteTensor): binary ByteTensor of shape
`(batch, src_len)` where padding elements are indicated by ``1``.
Returns:
encoded output of shape `(batch, src_len, embed_dim)`
"""
residual = x
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, before=True)
if prev_self_attn_state is not None:
if incremental_state is None:
incremental_state = {}
prev_key, prev_value = prev_self_attn_state
saved_state = {"prev_key": prev_key, "prev_value": prev_value}
self.self_attn._set_input_buffer(incremental_state, saved_state)
x, _ = self.self_attn(
query=x,
key=x,
value=x,
key_padding_mask=self_attn_padding_mask,
incremental_state=incremental_state,
need_weights=False,
attn_mask=self_attn_mask,
)
x = F.dropout(x, p=self.dropout, training=self.training)
x = residual + x
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, after=True)
attn = None
if self.encoder_attn is not None:
residual = x
x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, before=True)
if prev_attn_state is not None:
if incremental_state is None:
incremental_state = {}
prev_key, prev_value = prev_attn_state
saved_state = {"prev_key": prev_key, "prev_value": prev_value}
self.encoder_attn._set_input_buffer(incremental_state, saved_state)
x, attn = self.encoder_attn(
query=x,
key=encoder_out,
value=encoder_out,
key_padding_mask=encoder_padding_mask,
incremental_state=incremental_state,
static_kv=True,
need_weights=(not self.training and self.need_attn),
)
x = F.dropout(x, p=self.dropout, training=self.training)
x = residual + x
x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, after=True)
residual = x
x = self.maybe_layer_norm(self.final_layer_norm, x, before=True)
x = F.relu(self.fc1(x))
x = F.dropout(x, p=self.relu_dropout, training=self.training)
x = self.fc2(x)
x = F.dropout(x, p=self.dropout, training=self.training)
x = residual + x
x = self.maybe_layer_norm(self.final_layer_norm, x, after=True)
if self.onnx_trace:
saved_state = self.self_attn._get_input_buffer(incremental_state)
self_attn_state = saved_state["prev_key"], saved_state["prev_value"]
return x, attn, self_attn_state
return x, attn
def maybe_layer_norm(self, layer_norm, x, before=False, after=False):
assert before ^ after
if after ^ self.normalize_before:
return layer_norm(x)
else:
return x
def make_generation_fast_(self, need_attn=False, **kwargs):
self.need_attn = need_attn
def Embedding(num_embeddings, embedding_dim, padding_idx):
m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5)
nn.init.constant_(m.weight[padding_idx], 0)
return m
def Linear(in_features, out_features, bias=True):
m = nn.Linear(in_features, out_features, bias)
nn.init.xavier_uniform_(m.weight)
if bias:
nn.init.constant_(m.bias, 0.)
return m
def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad, learned=False):
if learned:
m = LearnedPositionalEmbedding(num_embeddings + padding_idx + 1, embedding_dim, padding_idx, left_pad)
nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5)
nn.init.constant_(m.weight[padding_idx], 0)
else:
m = SinusoidalPositionalEmbedding(embedding_dim, padding_idx, left_pad, num_embeddings + padding_idx + 1)
return m
@register_model_architecture('dlcl_transformer', 'dlcl_transformer')
def base_architecture(args):
args.encoder_embed_path = getattr(args, 'encoder_embed_path', None)
args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512)
args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 2048)
args.encoder_layers = getattr(args, 'encoder_layers', 6)
args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 8)
args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False)
args.encoder_learned_pos = getattr(args, 'encoder_learned_pos', False)
args.decoder_embed_path = getattr(args, 'decoder_embed_path', None)
args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', args.encoder_embed_dim)
args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', args.encoder_ffn_embed_dim)
args.decoder_layers = getattr(args, 'decoder_layers', 6)
args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 8)
args.decoder_normalize_before = getattr(args, 'decoder_normalize_before', False)
args.decoder_learned_pos = getattr(args, 'decoder_learned_pos', False)
args.attention_dropout = getattr(args, 'attention_dropout', 0.)
args.relu_dropout = getattr(args, 'relu_dropout', 0.)
args.dropout = getattr(args, 'dropout', 0.1)
args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', None)
args.adaptive_softmax_dropout = getattr(args, 'adaptive_softmax_dropout', 0)
args.share_decoder_input_output_embed = getattr(args, 'share_decoder_input_output_embed', False)
args.share_all_embeddings = getattr(args, 'share_all_embeddings', False)
args.no_token_positional_embeddings = getattr(args, 'no_token_positional_embeddings', False)
args.adaptive_input = getattr(args, 'adaptive_input', False)
args.decoder_output_dim = getattr(args, 'decoder_output_dim', args.decoder_embed_dim)
args.decoder_input_dim = getattr(args, 'decoder_input_dim', args.decoder_embed_dim)
args.encoder_history_type = getattr(args, 'encoder_history_type', 'dense')
args.decoder_history_type = getattr(args, 'decoder_history_type', 'dense')
args.encoder_integration_type = getattr(args, 'encoder_integration_type', 'avg')
args.decoder_integration_type = getattr(args, 'decoder_integration_type', 'avg')
args.max_relative_length = getattr(args, 'max_relative_length', args.max_relative_length)
@register_model_architecture('dlcl_transformer', 'dlcl_transformer_wmt_en_de')
def dlcl_transformer_wmt_en_de(args):
args.encoder_history_type = getattr(args, 'encoder_history_type', 'learnable_dense')
args.decoder_history_type = getattr(args, 'decoder_history_type', 'learnable_dense')
args.encoder_layers = 25
base_architecture(args)
@register_model_architecture('dlcl_transformer', 'dlcl_transformer_t2t_wmt_en_de')
def dlcl_transformer_t2t_wmt_en_de(args):
args.encoder_normalize_before = True
args.decoder_normalize_before = True
args.attention_dropout = getattr(args, 'attention_dropout', 0.1)
args.relu_dropout = getattr(args, 'relu_dropout', 0.1)
args.encoder_history_type = getattr(args, 'encoder_history_type', 'learnable_dense')
args.decoder_history_type = getattr(args, 'decoder_history_type', 'learnable_dense')
args.encoder_layers = 25
base_architecture(args)
@register_model_architecture('dlcl_transformer', 'dense_relative_transformer_wmt_en_de')
def dense_relative_transformer_wmt_en_de(args):
args.max_relative_length = 20
args.encoder_layers = 6
dlcl_transformer_wmt_en_de(args)
@register_model_architecture('dlcl_transformer', 'dense_relative_transformer_t2t_wmt_en_de')
def dense_relative_transformer_t2t_wmt_en_de(args):
args.max_relative_length = 20
args.encoder_layers = 6
dlcl_transformer_t2t_wmt_en_de(args)
| 43.081181 | 119 | 0.643198 |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import options, utils
from fairseq.modules import (
AdaptiveInput, AdaptiveSoftmax, CharacterTokenEmbedder, LayerNorm,
LearnedPositionalEmbedding, MultiheadAttention, SinusoidalPositionalEmbedding,
RelativeMultiheadAttention,
)
from . import (
FairseqIncrementalDecoder, FairseqEncoder, FairseqLanguageModel,
FairseqModel, register_model, register_model_architecture,
)
from fairseq.modules.layer_history import CreateLayerHistory
@register_model('dlcl_transformer')
class DLCLTransformerModel(FairseqModel):
def __init__(self, encoder, decoder):
super().__init__(encoder, decoder)
@staticmethod
def add_args(parser):
parser.add_argument('--dropout', type=float, metavar='D',
help='dropout probability')
parser.add_argument('--attention-dropout', type=float, metavar='D',
help='dropout probability for attention weights')
parser.add_argument('--relu-dropout', type=float, metavar='D',
help='dropout probability after ReLU in FFN')
parser.add_argument('--encoder-embed-path', type=str, metavar='STR',
help='path to pre-trained encoder embedding')
parser.add_argument('--encoder-embed-dim', type=int, metavar='N',
help='encoder embedding dimension')
parser.add_argument('--encoder-ffn-embed-dim', type=int, metavar='N',
help='encoder embedding dimension for FFN')
parser.add_argument('--encoder-layers', type=int, metavar='N',
help='num encoder layers')
parser.add_argument('--encoder-attention-heads', type=int, metavar='N',
help='num encoder attention heads')
parser.add_argument('--encoder-normalize-before', action='store_true',
help='apply layernorm before each encoder block')
parser.add_argument('--encoder-learned-pos', action='store_true',
help='use learned positional embeddings in the encoder')
parser.add_argument('--decoder-embed-path', type=str, metavar='STR',
help='path to pre-trained decoder embedding')
parser.add_argument('--decoder-embed-dim', type=int, metavar='N',
help='decoder embedding dimension')
parser.add_argument('--decoder-ffn-embed-dim', type=int, metavar='N',
help='decoder embedding dimension for FFN')
parser.add_argument('--decoder-layers', type=int, metavar='N',
help='num decoder layers')
parser.add_argument('--decoder-attention-heads', type=int, metavar='N',
help='num decoder attention heads')
parser.add_argument('--decoder-learned-pos', action='store_true',
help='use learned positional embeddings in the decoder')
parser.add_argument('--decoder-normalize-before', action='store_true',
help='apply layernorm before each decoder block')
parser.add_argument('--share-decoder-input-output-embed', action='store_true',
help='share decoder input and output embeddings')
parser.add_argument('--share-all-embeddings', action='store_true',
help='share encoder, decoder and output embeddings'
' (requires shared dictionary and embed dim)')
parser.add_argument('--no-token-positional-embeddings', default=False, action='store_true',
help='if set, disables positional embeddings (outside self attention)')
parser.add_argument('--adaptive-softmax-cutoff', metavar='EXPR',
help='comma separated list of adaptive softmax cutoff points. '
'Must be used with adaptive_loss criterion'),
parser.add_argument('--adaptive-softmax-dropout', type=float, metavar='D',
help='sets adaptive softmax dropout for the tail projections')
parser.add_argument('--max-relative-length', type=int, default=-1,
help='the max relative length')
ype',
help='encoder layer history type')
parser.add_argument('--decoder-history-type',
help='decoder layer history type')
parser.add_argument('--encoder-integration-type', choices=['avg', 'sum'],
help='encoder layer integration type')
parser.add_argument('--decoder-integration-type', choices=['avg', 'sum'],
help='decoder layer integration type')
@classmethod
def build_model(cls, args, task):
base_architecture(args)
if not hasattr(args, 'max_source_positions'):
args.max_source_positions = 1024
if not hasattr(args, 'max_target_positions'):
args.max_target_positions = 1024
src_dict, tgt_dict = task.source_dictionary, task.target_dictionary
def build_embedding(dictionary, embed_dim, path=None):
num_embeddings = len(dictionary)
padding_idx = dictionary.pad()
emb = Embedding(num_embeddings, embed_dim, padding_idx)
if path:
embed_dict = utils.parse_embedding(path)
utils.load_embedding(embed_dict, dictionary, emb)
return emb
if args.share_all_embeddings:
if src_dict != tgt_dict:
raise ValueError('--share-all-embeddings requires a joined dictionary')
if args.encoder_embed_dim != args.decoder_embed_dim:
raise ValueError(
'--share-all-embeddings requires --encoder-embed-dim to match --decoder-embed-dim')
if args.decoder_embed_path and (
args.decoder_embed_path != args.encoder_embed_path):
raise ValueError('--share-all-embeddings not compatible with --decoder-embed-path')
encoder_embed_tokens = build_embedding(
src_dict, args.encoder_embed_dim, args.encoder_embed_path
)
decoder_embed_tokens = encoder_embed_tokens
args.share_decoder_input_output_embed = True
else:
encoder_embed_tokens = build_embedding(
src_dict, args.encoder_embed_dim, args.encoder_embed_path
)
decoder_embed_tokens = build_embedding(
tgt_dict, args.decoder_embed_dim, args.decoder_embed_path
)
encoder = DLCLTransformerEncoder(args, src_dict, encoder_embed_tokens)
decoder = DLCLTransformerDecoder(args, tgt_dict, decoder_embed_tokens)
return DLCLTransformerModel(encoder, decoder)
class DLCLTransformerEncoder(FairseqEncoder):
def __init__(self, args, dictionary, embed_tokens, left_pad=True):
super().__init__(dictionary)
self.dropout = args.dropout
embed_dim = embed_tokens.embedding_dim
self.padding_idx = embed_tokens.padding_idx
self.max_source_positions = args.max_source_positions
self.embed_tokens = embed_tokens
self.embed_scale = math.sqrt(embed_dim)
self.embed_positions = PositionalEmbedding(
args.max_source_positions, embed_dim, self.padding_idx,
left_pad=left_pad,
learned=args.encoder_learned_pos,
) if not args.no_token_positional_embeddings else None
self.history = CreateLayerHistory(args, is_encoder=True)
self.layers = nn.ModuleList([])
self.layers.extend([
TransformerEncoderLayer(args)
for i in range(args.encoder_layers)
])
self.register_buffer('version', torch.Tensor([2]))
self.normalize = args.encoder_normalize_before
if self.normalize:
self.layer_norm = LayerNorm(embed_dim)
def forward(self, src_tokens, src_lengths):
if self.history is not None:
self.history.clean()
x = self.embed_scale * self.embed_tokens(src_tokens)
if self.embed_positions is not None:
x += self.embed_positions(src_tokens)
x = F.dropout(x, p=self.dropout, training=self.training)
x = x.transpose(0, 1)
if self.history is not None:
self.history.add(x)
encoder_padding_mask = src_tokens.eq(self.padding_idx)
if not encoder_padding_mask.any():
encoder_padding_mask = None
for layer in self.layers:
if self.history is not None:
x = self.history.pop()
x = layer(x, encoder_padding_mask)
if self.history is not None:
self.history.add(x)
if self.history is not None:
x = self.history.pop()
if self.normalize:
x = self.layer_norm(x)
return {
'encoder_out': x,
'encoder_padding_mask': encoder_padding_mask,
}
def reorder_encoder_out(self, encoder_out, new_order):
if encoder_out['encoder_out'] is not None:
encoder_out['encoder_out'] = \
encoder_out['encoder_out'].index_select(1, new_order)
if encoder_out['encoder_padding_mask'] is not None:
encoder_out['encoder_padding_mask'] = \
encoder_out['encoder_padding_mask'].index_select(0, new_order)
return encoder_out
def max_positions(self):
if self.embed_positions is None:
return self.max_source_positions
return min(self.max_source_positions, self.embed_positions.max_positions())
def upgrade_state_dict_named(self, state_dict, name):
if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):
weights_key = '{}.embed_positions.weights'.format(name)
if weights_key in state_dict:
del state_dict[weights_key]
state_dict['{}.embed_positions._float_tensor'.format(name)] = torch.FloatTensor(1)
version_key = '{}.version'.format(name)
if utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) < 2:
self.layer_norm = None
self.normalize = False
state_dict[version_key] = torch.Tensor([1])
return state_dict
class DLCLTransformerDecoder(FairseqIncrementalDecoder):
def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False, left_pad=False, final_norm=True):
super().__init__(dictionary)
self.dropout = args.dropout
self.share_input_output_embed = args.share_decoder_input_output_embed
input_embed_dim = embed_tokens.embedding_dim
embed_dim = args.decoder_embed_dim
output_embed_dim = args.decoder_output_dim
padding_idx = embed_tokens.padding_idx
self.max_target_positions = args.max_target_positions
self.embed_tokens = embed_tokens
self.embed_scale = math.sqrt(embed_dim)
self.project_in_dim = Linear(input_embed_dim, embed_dim, bias=False) if embed_dim != input_embed_dim else None
self.embed_positions = PositionalEmbedding(
args.max_target_positions, embed_dim, padding_idx,
left_pad=left_pad,
learned=args.decoder_learned_pos,
) if not args.no_token_positional_embeddings else None
self.history = CreateLayerHistory(args, is_encoder=False)
self.layers = nn.ModuleList([])
self.layers.extend([
TransformerDecoderLayer(args, no_encoder_attn)
for _ in range(args.decoder_layers)
])
self.adaptive_softmax = None
self.project_out_dim = Linear(embed_dim, output_embed_dim, bias=False) \
if embed_dim != output_embed_dim and not args.tie_adaptive_weights else None
if args.adaptive_softmax_cutoff is not None:
self.adaptive_softmax = AdaptiveSoftmax(
len(dictionary),
output_embed_dim,
options.eval_str_list(args.adaptive_softmax_cutoff, type=int),
dropout=args.adaptive_softmax_dropout,
adaptive_inputs=embed_tokens if args.tie_adaptive_weights else None,
factor=args.adaptive_softmax_factor,
tie_proj=args.tie_adaptive_proj,
)
elif not self.share_input_output_embed:
self.embed_out = nn.Parameter(torch.Tensor(len(dictionary), output_embed_dim))
nn.init.normal_(self.embed_out, mean=0, std=output_embed_dim ** -0.5)
self.register_buffer('version', torch.Tensor([2]))
self.normalize = args.decoder_normalize_before and final_norm
if self.normalize:
self.layer_norm = LayerNorm(embed_dim)
def forward(self, prev_output_tokens, encoder_out=None, incremental_state=None):
if self.history is not None:
self.history.clean()
positions = self.embed_positions(
prev_output_tokens,
incremental_state=incremental_state,
) if self.embed_positions is not None else None
if incremental_state is not None:
prev_output_tokens = prev_output_tokens[:, -1:]
if positions is not None:
positions = positions[:, -1:]
x = self.embed_scale * self.embed_tokens(prev_output_tokens)
if self.project_in_dim is not None:
x = self.project_in_dim(x)
if positions is not None:
x += positions
x = F.dropout(x, p=self.dropout, training=self.training)
x = x.transpose(0, 1)
attn = None
inner_states = [x]
if self.history is not None:
self.history.add(x)
for layer in self.layers:
if self.history is not None:
x = self.history.pop()
x, attn = layer(
x,
encoder_out['encoder_out'] if encoder_out is not None else None,
encoder_out['encoder_padding_mask'] if encoder_out is not None else None,
incremental_state,
self_attn_mask=self.buffered_future_mask(x) if incremental_state is None else None,
)
inner_states.append(x)
if self.history is not None:
self.history.add(x)
if self.history is not None:
x = self.history.pop()
if self.normalize:
x = self.layer_norm(x)
x = x.transpose(0, 1)
if self.project_out_dim is not None:
x = self.project_out_dim(x)
if self.adaptive_softmax is None:
if self.share_input_output_embed:
x = F.linear(x, self.embed_tokens.weight)
else:
x = F.linear(x, self.embed_out)
return x, {'attn': attn, 'inner_states': inner_states}
def max_positions(self):
if self.embed_positions is None:
return self.max_target_positions
return min(self.max_target_positions, self.embed_positions.max_positions())
def buffered_future_mask(self, tensor):
dim = tensor.size(0)
if not hasattr(self, '_future_mask') or self._future_mask is None or self._future_mask.device != tensor.device:
self._future_mask = torch.triu(utils.fill_with_neg_inf(tensor.new(dim, dim)), 1)
if self._future_mask.size(0) < dim:
self._future_mask = torch.triu(utils.fill_with_neg_inf(self._future_mask.resize_(dim, dim)), 1)
return self._future_mask[:dim, :dim]
def upgrade_state_dict_named(self, state_dict, name):
if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):
weights_key = '{}.embed_positions.weights'.format(name)
if weights_key in state_dict:
del state_dict[weights_key]
state_dict['{}.embed_positions._float_tensor'.format(name)] = torch.FloatTensor(1)
for i in range(len(self.layers)):
layer_norm_map = {
'0': 'self_attn_layer_norm',
'1': 'encoder_attn_layer_norm',
'2': 'final_layer_norm'
}
for old, new in layer_norm_map.items():
for m in ('weight', 'bias'):
k = '{}.layers.{}.layer_norms.{}.{}'.format(name, i, old, m)
if k in state_dict:
state_dict['{}.layers.{}.{}.{}'.format(name, i, new, m)] = state_dict[k]
del state_dict[k]
if utils.item(state_dict.get('{}.version'.format(name), torch.Tensor([1]))[0]) < 2:
self.layer_norm = None
self.normalize = False
state_dict['{}.version'.format(name)] = torch.Tensor([1])
return state_dict
class TransformerEncoderLayer(nn.Module):
def __init__(self, args):
super().__init__()
self.embed_dim = args.encoder_embed_dim
if args.max_relative_length==-1:
self.self_attn = MultiheadAttention(
self.embed_dim, args.encoder_attention_heads,
dropout=args.attention_dropout,
)
else:
self.self_attn = RelativeMultiheadAttention(
self.embed_dim, args.encoder_attention_heads,
args.max_relative_length, dropout=args.attention_dropout,
)
self.dropout = args.dropout
self.relu_dropout = args.relu_dropout
self.normalize_before = args.encoder_normalize_before
self.fc1 = Linear(self.embed_dim, args.encoder_ffn_embed_dim)
self.fc2 = Linear(args.encoder_ffn_embed_dim, self.embed_dim)
self.layer_norms = nn.ModuleList([LayerNorm(self.embed_dim) for i in range(2)])
def forward(self, x, encoder_padding_mask):
residual = x
x = self.maybe_layer_norm(0, x, before=True)
x, _ = self.self_attn(query=x, key=x, value=x, key_padding_mask=encoder_padding_mask)
x = F.dropout(x, p=self.dropout, training=self.training)
x = residual + x
x = self.maybe_layer_norm(0, x, after=True)
residual = x
x = self.maybe_layer_norm(1, x, before=True)
x = F.relu(self.fc1(x))
x = F.dropout(x, p=self.relu_dropout, training=self.training)
x = self.fc2(x)
x = F.dropout(x, p=self.dropout, training=self.training)
x = residual + x
x = self.maybe_layer_norm(1, x, after=True)
return x
def maybe_layer_norm(self, i, x, before=False, after=False):
assert before ^ after
if after ^ self.normalize_before:
return self.layer_norms[i](x)
else:
return x
class TransformerDecoderLayer(nn.Module):
def __init__(self, args, no_encoder_attn=False):
super().__init__()
self.embed_dim = args.decoder_embed_dim
if args.max_relative_length == -1:
self.self_attn = MultiheadAttention(
self.embed_dim, args.decoder_attention_heads,
dropout=args.attention_dropout,
)
else:
self.self_attn = RelativeMultiheadAttention(
self.embed_dim, args.decoder_attention_heads,
args.max_relative_length, dropout=args.attention_dropout,
)
self.dropout = args.dropout
self.relu_dropout = args.relu_dropout
self.normalize_before = args.decoder_normalize_before
self.self_attn_layer_norm = LayerNorm(self.embed_dim)
if no_encoder_attn:
self.encoder_attn = None
self.encoder_attn_layer_norm = None
else:
self.encoder_attn = MultiheadAttention(
self.embed_dim, args.decoder_attention_heads,
dropout=args.attention_dropout,
)
self.encoder_attn_layer_norm = LayerNorm(self.embed_dim)
self.fc1 = Linear(self.embed_dim, args.decoder_ffn_embed_dim)
self.fc2 = Linear(args.decoder_ffn_embed_dim, self.embed_dim)
self.final_layer_norm = LayerNorm(self.embed_dim)
self.need_attn = True
self.onnx_trace = False
def prepare_for_onnx_export_(self):
self.onnx_trace = True
def forward(self, x, encoder_out, encoder_padding_mask, incremental_state,
prev_self_attn_state=None, prev_attn_state=None, self_attn_mask=None,
self_attn_padding_mask=None):
residual = x
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, before=True)
if prev_self_attn_state is not None:
if incremental_state is None:
incremental_state = {}
prev_key, prev_value = prev_self_attn_state
saved_state = {"prev_key": prev_key, "prev_value": prev_value}
self.self_attn._set_input_buffer(incremental_state, saved_state)
x, _ = self.self_attn(
query=x,
key=x,
value=x,
key_padding_mask=self_attn_padding_mask,
incremental_state=incremental_state,
need_weights=False,
attn_mask=self_attn_mask,
)
x = F.dropout(x, p=self.dropout, training=self.training)
x = residual + x
x = self.maybe_layer_norm(self.self_attn_layer_norm, x, after=True)
attn = None
if self.encoder_attn is not None:
residual = x
x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, before=True)
if prev_attn_state is not None:
if incremental_state is None:
incremental_state = {}
prev_key, prev_value = prev_attn_state
saved_state = {"prev_key": prev_key, "prev_value": prev_value}
self.encoder_attn._set_input_buffer(incremental_state, saved_state)
x, attn = self.encoder_attn(
query=x,
key=encoder_out,
value=encoder_out,
key_padding_mask=encoder_padding_mask,
incremental_state=incremental_state,
static_kv=True,
need_weights=(not self.training and self.need_attn),
)
x = F.dropout(x, p=self.dropout, training=self.training)
x = residual + x
x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, after=True)
residual = x
x = self.maybe_layer_norm(self.final_layer_norm, x, before=True)
x = F.relu(self.fc1(x))
x = F.dropout(x, p=self.relu_dropout, training=self.training)
x = self.fc2(x)
x = F.dropout(x, p=self.dropout, training=self.training)
x = residual + x
x = self.maybe_layer_norm(self.final_layer_norm, x, after=True)
if self.onnx_trace:
saved_state = self.self_attn._get_input_buffer(incremental_state)
self_attn_state = saved_state["prev_key"], saved_state["prev_value"]
return x, attn, self_attn_state
return x, attn
def maybe_layer_norm(self, layer_norm, x, before=False, after=False):
assert before ^ after
if after ^ self.normalize_before:
return layer_norm(x)
else:
return x
def make_generation_fast_(self, need_attn=False, **kwargs):
self.need_attn = need_attn
def Embedding(num_embeddings, embedding_dim, padding_idx):
m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5)
nn.init.constant_(m.weight[padding_idx], 0)
return m
def Linear(in_features, out_features, bias=True):
m = nn.Linear(in_features, out_features, bias)
nn.init.xavier_uniform_(m.weight)
if bias:
nn.init.constant_(m.bias, 0.)
return m
def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad, learned=False):
if learned:
m = LearnedPositionalEmbedding(num_embeddings + padding_idx + 1, embedding_dim, padding_idx, left_pad)
nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5)
nn.init.constant_(m.weight[padding_idx], 0)
else:
m = SinusoidalPositionalEmbedding(embedding_dim, padding_idx, left_pad, num_embeddings + padding_idx + 1)
return m
@register_model_architecture('dlcl_transformer', 'dlcl_transformer')
def base_architecture(args):
args.encoder_embed_path = getattr(args, 'encoder_embed_path', None)
args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512)
args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 2048)
args.encoder_layers = getattr(args, 'encoder_layers', 6)
args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 8)
args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False)
args.encoder_learned_pos = getattr(args, 'encoder_learned_pos', False)
args.decoder_embed_path = getattr(args, 'decoder_embed_path', None)
args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', args.encoder_embed_dim)
args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', args.encoder_ffn_embed_dim)
args.decoder_layers = getattr(args, 'decoder_layers', 6)
args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 8)
args.decoder_normalize_before = getattr(args, 'decoder_normalize_before', False)
args.decoder_learned_pos = getattr(args, 'decoder_learned_pos', False)
args.attention_dropout = getattr(args, 'attention_dropout', 0.)
args.relu_dropout = getattr(args, 'relu_dropout', 0.)
args.dropout = getattr(args, 'dropout', 0.1)
args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', None)
args.adaptive_softmax_dropout = getattr(args, 'adaptive_softmax_dropout', 0)
args.share_decoder_input_output_embed = getattr(args, 'share_decoder_input_output_embed', False)
args.share_all_embeddings = getattr(args, 'share_all_embeddings', False)
args.no_token_positional_embeddings = getattr(args, 'no_token_positional_embeddings', False)
args.adaptive_input = getattr(args, 'adaptive_input', False)
args.decoder_output_dim = getattr(args, 'decoder_output_dim', args.decoder_embed_dim)
args.decoder_input_dim = getattr(args, 'decoder_input_dim', args.decoder_embed_dim)
args.encoder_history_type = getattr(args, 'encoder_history_type', 'dense')
args.decoder_history_type = getattr(args, 'decoder_history_type', 'dense')
args.encoder_integration_type = getattr(args, 'encoder_integration_type', 'avg')
args.decoder_integration_type = getattr(args, 'decoder_integration_type', 'avg')
args.max_relative_length = getattr(args, 'max_relative_length', args.max_relative_length)
@register_model_architecture('dlcl_transformer', 'dlcl_transformer_wmt_en_de')
def dlcl_transformer_wmt_en_de(args):
args.encoder_history_type = getattr(args, 'encoder_history_type', 'learnable_dense')
args.decoder_history_type = getattr(args, 'decoder_history_type', 'learnable_dense')
args.encoder_layers = 25
base_architecture(args)
@register_model_architecture('dlcl_transformer', 'dlcl_transformer_t2t_wmt_en_de')
def dlcl_transformer_t2t_wmt_en_de(args):
args.encoder_normalize_before = True
args.decoder_normalize_before = True
args.attention_dropout = getattr(args, 'attention_dropout', 0.1)
args.relu_dropout = getattr(args, 'relu_dropout', 0.1)
args.encoder_history_type = getattr(args, 'encoder_history_type', 'learnable_dense')
args.decoder_history_type = getattr(args, 'decoder_history_type', 'learnable_dense')
args.encoder_layers = 25
base_architecture(args)
@register_model_architecture('dlcl_transformer', 'dense_relative_transformer_wmt_en_de')
def dense_relative_transformer_wmt_en_de(args):
args.max_relative_length = 20
args.encoder_layers = 6
dlcl_transformer_wmt_en_de(args)
@register_model_architecture('dlcl_transformer', 'dense_relative_transformer_t2t_wmt_en_de')
def dense_relative_transformer_t2t_wmt_en_de(args):
args.max_relative_length = 20
args.encoder_layers = 6
dlcl_transformer_t2t_wmt_en_de(args)
| true | true |
1c2bdd7bd7931d3e116412a7d8fdf90c2c822f40 | 4,663 | py | Python | u2socks5.py | thisforeda/unicorn | 16ea5e05912850926cc897ec2bc20db09b7b50cd | [
"Apache-2.0"
] | 5 | 2017-12-08T09:57:17.000Z | 2019-01-16T12:50:42.000Z | u2socks5.py | thisforeda/unicorn | 16ea5e05912850926cc897ec2bc20db09b7b50cd | [
"Apache-2.0"
] | 1 | 2019-04-06T08:35:00.000Z | 2019-04-06T08:35:00.000Z | u2socks5.py | thisforeda/unicorn | 16ea5e05912850926cc897ec2bc20db09b7b50cd | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python3
#encoding=utf8
#
# Copyright 2017 thisforeda
#
# 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 struct
import socket
import asyncio
import functools
from unicorn import BaseProtocol
P = struct.pack
U = struct.unpack
UP = lambda b: U("!H", b)[0]
class SOCKS5(BaseProtocol):
STAGE_CONN_MADE = 0
STAGE_AUTH_DONE = 2
STAGE_TUNNEL_STREAMING = 3
ATYPE_DOMAIN = 3
ATYPE_IPV4 = 1
ATYPE_IPV6 = 4
def __init__(self, loop, cryptor, server):
self.loop = loop
self.transport = None
self.cryptor = cryptor.new()
self.server = server
self._tcp_tunnel = None
self._status = self.STAGE_CONN_MADE
def data_received(self, data):
if self._status == self.STAGE_TUNNEL_STREAMING:
self._tcp_tunnel.send_to_remote(data)
return
if self._status == self.STAGE_CONN_MADE:
v, nm, m = U("!BBB", data[:3])
if v == 0x05 and m == 0x00:
self._status = self.STAGE_AUTH_DONE
self.transport.write(b"\x05\x00")
return
self.transport.close()
if self._status == self.STAGE_AUTH_DONE:
cmd, rsv, at, *_ = U("!BBB", data[1:4])
if at == self.ATYPE_DOMAIN:
l = U("!B", data[4:5])[0]
a = data[5: 5 + l]
p = UP(data[5 + l: 7 + l])
elif at == self.ATYPE_IPV4:
a = data[4: 8]
p = UP(data[8: 12])
elif at == self.ATYPE_IPV6:
a = data[4:20]
p = UP(data[20: 22])
c = self.unicorn_tcp_tunnel(a,p,at,cmd)
asyncio.ensure_future(c)
def connection_lost(self, exc):
self.transport.close()
if self._tcp_tunnel:
self._tcp_tunnel.transport.close()
@asyncio.coroutine
def unicorn_tcp_tunnel(self, host, port, at, cmd):
class TcpRelay(asyncio.Protocol):
def data_received(self, data):
data = self.local.cryptor.dec(data)
if self._proto_packet:
data = P("!B2sB6s",5 , b'\x00', 1, b'\x00')
self._proto_packet = False
self.local.transport.write(data)
def send_to_remote(self, data):
data = self.local.cryptor.enc(data)
self.transport.write(data)
def connection_made(self, transport):
self.transport = transport
self._proto_packet = True
try:
al = len(host)
payload = self.cryptor.enc(
P("!HBBB%dsH" % al,
0x504b,
cmd,
at,
al,
host,
port
)
)
transport, u = yield from asyncio.wait_for(
self.loop.create_connection(
TcpRelay,
host=self.server['host'],
port=self.server['port']
),
15)
self._status = self.STAGE_TUNNEL_STREAMING
u.local = self
self._tcp_tunnel = u
transport.write(payload)
except (asyncio.TimeoutError, OSError):
self.transport.close()
return
if __name__ == "__main__":
import sys
from cryptor import Cryptor, RC4Cryptor
try:
if len(sys.argv) != 3:
raise Exception("missing arguments.")
Lhost, Lport = sys.argv[1].split(":")
Rhost, Rport, Rpasswd = sys.argv[2].split(":")
except Exception as err:
print (str(err))
print ("example argument line: local_address:local_port server_address:server_port:remote_passwd")
exit(1)
cryptor = RC4Cryptor(Rpasswd)
loop = asyncio.get_event_loop()
server = loop.run_until_complete(loop.create_server(
functools.partial(SOCKS5, loop, cryptor, {'host': Rhost, 'port': Rport}),
host=Lhost,
port=Lport
))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
| 29.700637 | 106 | 0.551147 |
import struct
import socket
import asyncio
import functools
from unicorn import BaseProtocol
P = struct.pack
U = struct.unpack
UP = lambda b: U("!H", b)[0]
class SOCKS5(BaseProtocol):
STAGE_CONN_MADE = 0
STAGE_AUTH_DONE = 2
STAGE_TUNNEL_STREAMING = 3
ATYPE_DOMAIN = 3
ATYPE_IPV4 = 1
ATYPE_IPV6 = 4
def __init__(self, loop, cryptor, server):
self.loop = loop
self.transport = None
self.cryptor = cryptor.new()
self.server = server
self._tcp_tunnel = None
self._status = self.STAGE_CONN_MADE
def data_received(self, data):
if self._status == self.STAGE_TUNNEL_STREAMING:
self._tcp_tunnel.send_to_remote(data)
return
if self._status == self.STAGE_CONN_MADE:
v, nm, m = U("!BBB", data[:3])
if v == 0x05 and m == 0x00:
self._status = self.STAGE_AUTH_DONE
self.transport.write(b"\x05\x00")
return
self.transport.close()
if self._status == self.STAGE_AUTH_DONE:
cmd, rsv, at, *_ = U("!BBB", data[1:4])
if at == self.ATYPE_DOMAIN:
l = U("!B", data[4:5])[0]
a = data[5: 5 + l]
p = UP(data[5 + l: 7 + l])
elif at == self.ATYPE_IPV4:
a = data[4: 8]
p = UP(data[8: 12])
elif at == self.ATYPE_IPV6:
a = data[4:20]
p = UP(data[20: 22])
c = self.unicorn_tcp_tunnel(a,p,at,cmd)
asyncio.ensure_future(c)
def connection_lost(self, exc):
self.transport.close()
if self._tcp_tunnel:
self._tcp_tunnel.transport.close()
@asyncio.coroutine
def unicorn_tcp_tunnel(self, host, port, at, cmd):
class TcpRelay(asyncio.Protocol):
def data_received(self, data):
data = self.local.cryptor.dec(data)
if self._proto_packet:
data = P("!B2sB6s",5 , b'\x00', 1, b'\x00')
self._proto_packet = False
self.local.transport.write(data)
def send_to_remote(self, data):
data = self.local.cryptor.enc(data)
self.transport.write(data)
def connection_made(self, transport):
self.transport = transport
self._proto_packet = True
try:
al = len(host)
payload = self.cryptor.enc(
P("!HBBB%dsH" % al,
0x504b,
cmd,
at,
al,
host,
port
)
)
transport, u = yield from asyncio.wait_for(
self.loop.create_connection(
TcpRelay,
host=self.server['host'],
port=self.server['port']
),
15)
self._status = self.STAGE_TUNNEL_STREAMING
u.local = self
self._tcp_tunnel = u
transport.write(payload)
except (asyncio.TimeoutError, OSError):
self.transport.close()
return
if __name__ == "__main__":
import sys
from cryptor import Cryptor, RC4Cryptor
try:
if len(sys.argv) != 3:
raise Exception("missing arguments.")
Lhost, Lport = sys.argv[1].split(":")
Rhost, Rport, Rpasswd = sys.argv[2].split(":")
except Exception as err:
print (str(err))
print ("example argument line: local_address:local_port server_address:server_port:remote_passwd")
exit(1)
cryptor = RC4Cryptor(Rpasswd)
loop = asyncio.get_event_loop()
server = loop.run_until_complete(loop.create_server(
functools.partial(SOCKS5, loop, cryptor, {'host': Rhost, 'port': Rport}),
host=Lhost,
port=Lport
))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
| true | true |
1c2bdda1cd6e99640ba34b990716e88ead6bbeea | 13,262 | py | Python | pyWAPOR/ETLook/radiation.py | hectornieto/wapor-et-look | bc0b98be58d1680de2f82909809ac876f78f2d85 | [
"Apache-2.0"
] | 1 | 2021-05-24T08:12:03.000Z | 2021-05-24T08:12:03.000Z | pyWAPOR/ETLook/radiation.py | hectornieto/wapor-et-look | bc0b98be58d1680de2f82909809ac876f78f2d85 | [
"Apache-2.0"
] | 2 | 2020-06-25T08:27:55.000Z | 2020-08-28T07:38:17.000Z | pyWAPOR/ETLook/radiation.py | DHI-GRAS/wapor-et-look | e05b8f24616af8fc99ac1d646c878b353cb35aef | [
"Apache-2.0"
] | 4 | 2020-09-23T09:51:59.000Z | 2021-08-10T08:59:14.000Z | import numpy as np
from pyWAPOR.ETLook import constants as c
def interception_wm2(int_mm, lh_24):
r"""
Computes the energy equivalent for the interception in Wm-2 if it
is provide in mm/day
.. math ::
I = \frac{\lambda I^*}{86400}
Parameters
----------
int_mm : float
interception
:math:`I^*`
[mm day-1]
lh_24 : float
daily latent heat for evaporation
:math:`\lambda`
[J kg-1]
Returns
-------
int_wm2 : float
interception
:math:`I`
[W m-2]
Examples
--------
>>> import ETLook.radiation as rad
>>> import ETLook.meteo as meteo
>>> lh = meteo.latent_heat_daily(20.0)
>>> rad.interception_wm2(1.0, lh)
28.40023148148148
"""
return int_mm * (lh_24/c.day_sec)
def soil_fraction(lai):
r"""
Computes the effect of the vegetation has in separating the net radiation
into a soil and canopy component. If the canopy has a full cover almost
no radiation reaches the soil.
.. math ::
s_f = \exp\left(-0.6*I_{lai}\right)
Parameters
----------
lai : float
leaf area index
:math:`I_{lai}`
[-]
Returns
-------
sf_soil : float
soil fraction
:math:`s_f`
[-]
Examples
--------
>>> import ETLook.radiation as rad
>>> rad.soil_fraction(3.0)
0.16529888822158656
"""
return np.exp(-0.6*lai)
def longwave_radiation_fao_etref(t_air_k_24, vp_24, trans_24):
r"""
Computes the net longwave radiation according to the FAO 56 manual. For the
reference ET calculation the values for vp_slope, vp_offset, lw_slope and
lw_offset are being provided as defaults
.. math ::
L^{*}=\sigma\left(T_{a,K}\right)^{4}
\left(vp_off-vp_slp\sqrt{0.1e_{a}}
\right)\left(lw_slp\frac{\tau}{0.75}+lw_off\right)
where the following constant is used
* :math:`\sigma` = Stefan Boltzmann constant = 5.67 e-8 J s-1 m-2 K-4
Parameters
----------
t_air_k_24 : float
daily air temperature in Kelvin
:math:`T_{a,K}`
[-]
vp_24 : float
daily vapour pressure
:math:`e_{a}`
[mbar]
trans_24 : float
daily atmospheric transmissivity
:math:`\tau`
[-]
Returns
-------
l_net : float
daily net longwave radiation
:math:`L^{*}`
[Wm-2]
Examples
--------
>>> import ETLook.radiation as rad
>>> rad.longwave_radiation_fao_etref(t_air_k=302.5, vp=10.3, trans_24=0.6)
68.594182173686306
"""
vp_slope=0.14
vp_offset=0.34
lw_slope=1.35
lw_offset=-0.35
return longwave_radiation_fao(t_air_k_24, vp_24, trans_24, vp_slope, vp_offset, lw_slope, lw_offset)
def longwave_radiation_fao(t_air_k_24, vp_24, trans_24, vp_slope=0.14, vp_offset=0.34,
lw_slope=1.35, lw_offset=-0.35):
r"""
Computes the net longwave radiation according to the FAO 56 manual.
.. math ::
L^{*}=\sigma\left(T_{a,K}\right)^{4}
\left(vp_{off}-vp_{slope}\sqrt{0.1e_{a}}
\right)\left(lw_{slope}\frac{\tau}{0.75}+lw_{off}\right)
where the following constant is used
* :math:`\sigma` = Stefan Boltzmann constant = 5.67 e-8 J s-1 m-2 K-4
Parameters
----------
t_air_k_24 : float
daily air temperature in Kelvin
:math:`T_{a,K}`
[-]
vp_24 : float
daily vapour pressure
:math:`e_{a}`
[mbar]
trans_24 : float
daily atmospheric transmissivity
:math:`\tau`
[-]
vp_slope : float
slope of the vp-term in the FAO-56 longwave radiation relationship
:math:`vp_{slope}`
[-]
vp_offset : float
offset of the vp-term in the FAO-56 longwave radiation relationship
:math:`vp_{off}`
[-]
lw_slope : float
slope of the tau-term in the FAO-56 longwave radiation relationship
:math:`lw_{slope}`
[-]
lw_offset : float
offset of the tau-term in the FAO-56 longwave radiation relationship
:math:`lw_{off}`
[-]
Returns
-------
l_net : float
daily net longwave radiation
:math:`L^{*}`
[Wm-2]
Examples
--------
>>> import ETLook.radiation as rad
>>> rad.longwave_radiation_fao(t_air_k=302.5, vp=10.3, trans_24=0.6)
68.594182173686306
"""
return c.sb*t_air_k_24**4*(vp_offset-vp_slope*np.sqrt(0.1*vp_24))*(lw_offset + lw_slope*(trans_24/0.75))
def net_radiation(r0, ra_24, l_net, int_wm2):
r"""
Computes the net radiation
.. math ::
Q^{*} = \left[\left(1-\alpha_{0}\right)S^{\downarrow}-L^{*}-I\right]
Parameters
----------
r0 : float
albedo
:math:`\alpha_{0}`
[-]
ra_24 : float
daily solar radiation
:math:`S^{\downarrow}`
[Wm-2]
l_net : float
daily net longwave radiation
:math:`L^{*}`
[wm-2]
int_wm2 : float
interception
:math:`I`
[Wm-2]
Returns
-------
rn_24 : float
daily net radiation
:math:`Q^{*}`
[Wm-2]
Examples
--------
>>> import ETLook.radiation as rad
>>> rad.net_radiation(r0=0.10, ra_24=123., l_net=24., int_wm2=0)
86.7
"""
return (1-r0)*ra_24-l_net-int_wm2
def net_radiation_canopy(rn_24, sf_soil):
r"""
Computes the net radiation for the canopy
.. math ::
Q^{*}_{canopy} = \left(1-s_f\right) Q^{*}
Parameters
----------
rn_24 : float
net radiation
:math:`Q^{*}`
[Wm-2]
sf_soil : float
soil fraction
:math:`s_f`
[-]
Returns
-------
rn_24_canopy : float
net radiation for the canopy
:math:`Q^{*}_{canopy}`
[Wm-2]
Examples
--------
>>> import ETLook.radiation as rad
>>> rad.net_radiation_canopy(rn_24=200, sf_soil=0.4)
120.0
"""
return rn_24 * (1-sf_soil)
def net_radiation_soil(rn_24, sf_soil):
"""
Computes the net radiation for the soil
.. math ::
Q^{*}_{soil} = s_f Q^{*}
Parameters
----------
rn_24 : float
net radiation
:math:`Q^{*}`
[Wm-2]
sf_soil : float
soil fraction
:math:`s_f`
[-]
Returns
-------
rn_24_soil : float
net radiation for the soil
:math:`Q^{*}_{soil}`
[Wm-2]
Examples
--------
>>> import ETLook.radiation as rad
>>> rad.net_radiation_soil(rn_24=200, sf_soil=0.4)
80.0
"""
return rn_24 * sf_soil
def net_radiation_grass(ra_24, l_net, r0_grass=0.23):
r"""
Computes the net radiation for reference grass
.. math ::
Q^{*} = \left[\left(1-\alpha_{0, grass}\right)S^{\downarrow}-L^{*}-I\right]
Parameters
----------
ra_24 : float
daily solar radiation
:math:`S^{\downarrow}`
[Wm-2]
l_net : float
daily net longwave radiation
:math:`L^{*}`
[wm-2]
r0_grass : float
albedo for reference grass
:math:`\alpha_{0, grass}`
[-]
Returns
-------
rn_24_grass : float
daily net radiation for reference grass
:math:`Q^{*}`
[Wm-2]
Examples
--------
>>> import ETLook.radiation as rad
>>> rad.net_radiation_grass(ra_24=123., l_net=24.)
70.7
"""
return (1-r0_grass)*ra_24-l_net
def volumetric_heat_capacity(se_top=1.0, porosity=0.4):
r"""
Computes the volumetric heat capacity of the soil
.. math ::
\rho c_{p}=10e^{6}\left[\left(1-\phi\right)^{2}+
2.5\phi+4.2\phi S_{e,top}\right]
Parameters
----------
se_top : float
effective saturation of the topsoil
:math:`S_{e,top}`
[-]
porosity : float
porosity of the soil
:math:`\phi`
[-]
Returns
-------
vhc : float
volumetric heat capacity
:math:`\rho c_{p}`
[J m-3 K-1]
Examples
--------
>>> import ETLook.radiation as rad
>>> rad.volumetric_heat_capacity(se_top=0.4, porosity = 0.5)
23400000.0
"""
return ((1-porosity)**2+2.5*porosity+4.2*porosity*se_top)*10**6
def soil_thermal_conductivity(se_top):
r"""
Computes the soil thermal conductivity
.. math ::
k=0.15+18.5S_{e,top}
Parameters
----------
se_top : float
effective saturation of the topsoil
:math:`S_{e,top}`
[-]
Returns
-------
stc : float
soil thermal conductivity
:math:`k`
[W m-1 K-1]
Examples
--------
>>> import ETLook.radiation as rad
>>> rad.soil_thermal_conductivity(se_top=0.4)
0.8900000000000001
"""
return 0.15 + 1.85 * se_top
def damping_depth(stc, vhc):
r"""
Computes the damping depth
.. math ::
z_{d}=\sqrt{\frac{2kP}{2\pi\rho c_{p}}}
with the following constant
* :math:`P` period (seconds within a year)
Parameters
----------
stc : float
soil thermal conductivity
:math:`k`
[W m-1 K-1]
vhc : float
volumetric heat capacity
:math:`\rho c_{p}`
[J m-3 K-1]
Returns
-------
dd : float
damping depth
:math:`z_{d}`
[m]
Examples
--------
>>> import ETLook.radiation as rad
>>> rad.damping_depth(stc=0.9, vhc=volumetric_heat_capacity())
0.54514600029013294
"""
return np.sqrt((2*stc*c.year_sec)/(vhc*2*np.pi))
#TODO north-south transition with regard to latitude
def bare_soil_heat_flux(doy, dd, stc, t_amp_year, lat):
r"""
Computes the bare soil heat flux
.. math ::
G_{0}=\frac{\sqrt{2}A_{t,year}k\sin\left(\frac{2\pi J}{P}-
\frac{\pi}{4}\right)}{z_{d}}
where the following constant is used
* :math:`P` period (seconds within a year)
The term :math:`-\frac{\pi}{4}` is a phase shift for northern latitudes.
For southern latitudes the phase shift will be :math:`-\frac{\pi}{4}+\pi`
Parameters
----------
stc : float
soil thermal conductivity
:math:`k`
[W m-1 K-1]
dd : float
damping depth
:math:`z_{d}`
[m]
t_amp_year : float
yearly air temperature amplitude
:math:`A_{t,year}`
[m]
doy : float
julian day of the year
:math:`J`
[-]
lat : float
latitude
:math:`\lambda`
[rad]
Returns
-------
g0_bs : float
bare soil heat flux
:math:`G_{0}`
[m]
Examples
--------
>>> import ETLook.radiation as rad
>>> stc = rad.soil_thermal_conductivity(se_top=1.0)
>>> vhc = rad.volumetric_heat_capacity(se_top=1.0)
>>> dd = damping_depth(stc,vhc)
>>> rad.bare_soil_heat_flux(126, dd, stc, t_amp_year=13.4, lat=40*(math.pi/180.0))
array([ 45.82350561])
"""
phase = np.where(lat > 0, -np.pi/4.0, -np.pi/4.0+np.pi)
out = (np.sqrt(2.0)*t_amp_year*stc*np.sin(2*np.pi/c.year_sec*doy*c.day_sec+phase))/dd
return out
def soil_heat_flux(g0_bs, sf_soil, land_mask, rn_24_soil, trans_24, ra_24, l_net, rn_slope=0.92, rn_offset=-61.0):
r"""
Computes the soil heat flux
.. math ::
G=s_f G_{0}
Parameters
----------
g0_bs : float
bare soil heat flux
:math:`G_{0}`
[W m-2]
sf_soil : float
soil fraction
:math:`s_f`
[-]
land_mask : int
land use classification
:math:`l`
[-]
rn_24_soil : float
net radiation for the soil
:math:`Q^{*}_{soil}`
[Wm-2]
trans_24 : float
daily atmospheric transmissivity
:math:`\tau`
[-]
rn_slope : float
slope rn/g0 relation water
:math:`lws`
[-]
rn_offset : float
offset rn/g0 relation water
:math:`lwo`
[-]
ra_24 : float
daily solar radiation
:math:`S^{\downarrow}`
[Wm-2]
l_net : float
daily net longwave radiation
:math:`L^{*}`
[wm-2]
Returns
-------
g0_24 : float
daily soil heat flux
:math:`G`
[W m-2]
Examples
--------
>>> import ETLook.radiation as rad
>>> rad.soil_heat_flux(g0_bs=12.4, sf_soil=0.4)
4.960000000000001
"""
def land_city_func(g0_bs, sf_soil):
return g0_bs * sf_soil
def water_func(ra_24, trans_24, l_net, rn_slope, rn_offset, rn_24_soil):
rn_24_clear = 0.95 * ra_24 / trans_24 - l_net
g0_24_clear = rn_24_clear * rn_slope + rn_offset
g0_24_clear = np.minimum(g0_24_clear, 0.5 * rn_24_clear)
# adjust water heat storage to current net radiation conditions
g0_24 = g0_24_clear * rn_24_soil / rn_24_clear
return g0_24
g0 = np.zeros_like(land_mask)
g0 = np.where(land_mask == 1, land_city_func(g0_bs, sf_soil), g0)
g0 = np.where(land_mask == 2, water_func(ra_24, trans_24, l_net, rn_slope, rn_offset, rn_24_soil), g0)
g0 = np.where(land_mask == 3, land_city_func(g0_bs, sf_soil), g0)
return g0
| 22.826162 | 114 | 0.54856 | import numpy as np
from pyWAPOR.ETLook import constants as c
def interception_wm2(int_mm, lh_24):
return int_mm * (lh_24/c.day_sec)
def soil_fraction(lai):
return np.exp(-0.6*lai)
def longwave_radiation_fao_etref(t_air_k_24, vp_24, trans_24):
vp_slope=0.14
vp_offset=0.34
lw_slope=1.35
lw_offset=-0.35
return longwave_radiation_fao(t_air_k_24, vp_24, trans_24, vp_slope, vp_offset, lw_slope, lw_offset)
def longwave_radiation_fao(t_air_k_24, vp_24, trans_24, vp_slope=0.14, vp_offset=0.34,
lw_slope=1.35, lw_offset=-0.35):
return c.sb*t_air_k_24**4*(vp_offset-vp_slope*np.sqrt(0.1*vp_24))*(lw_offset + lw_slope*(trans_24/0.75))
def net_radiation(r0, ra_24, l_net, int_wm2):
return (1-r0)*ra_24-l_net-int_wm2
def net_radiation_canopy(rn_24, sf_soil):
return rn_24 * (1-sf_soil)
def net_radiation_soil(rn_24, sf_soil):
return rn_24 * sf_soil
def net_radiation_grass(ra_24, l_net, r0_grass=0.23):
return (1-r0_grass)*ra_24-l_net
def volumetric_heat_capacity(se_top=1.0, porosity=0.4):
return ((1-porosity)**2+2.5*porosity+4.2*porosity*se_top)*10**6
def soil_thermal_conductivity(se_top):
return 0.15 + 1.85 * se_top
def damping_depth(stc, vhc):
return np.sqrt((2*stc*c.year_sec)/(vhc*2*np.pi))
def bare_soil_heat_flux(doy, dd, stc, t_amp_year, lat):
phase = np.where(lat > 0, -np.pi/4.0, -np.pi/4.0+np.pi)
out = (np.sqrt(2.0)*t_amp_year*stc*np.sin(2*np.pi/c.year_sec*doy*c.day_sec+phase))/dd
return out
def soil_heat_flux(g0_bs, sf_soil, land_mask, rn_24_soil, trans_24, ra_24, l_net, rn_slope=0.92, rn_offset=-61.0):
def land_city_func(g0_bs, sf_soil):
return g0_bs * sf_soil
def water_func(ra_24, trans_24, l_net, rn_slope, rn_offset, rn_24_soil):
rn_24_clear = 0.95 * ra_24 / trans_24 - l_net
g0_24_clear = rn_24_clear * rn_slope + rn_offset
g0_24_clear = np.minimum(g0_24_clear, 0.5 * rn_24_clear)
g0_24 = g0_24_clear * rn_24_soil / rn_24_clear
return g0_24
g0 = np.zeros_like(land_mask)
g0 = np.where(land_mask == 1, land_city_func(g0_bs, sf_soil), g0)
g0 = np.where(land_mask == 2, water_func(ra_24, trans_24, l_net, rn_slope, rn_offset, rn_24_soil), g0)
g0 = np.where(land_mask == 3, land_city_func(g0_bs, sf_soil), g0)
return g0
| true | true |
1c2bdda97544d685b3b4c3ba20721a0f071f60d9 | 3,824 | py | Python | reinforcement_learning/rl_traveling_salesman_vehicle_routing_coach/src/evaluate-coach.py | jerrypeng7773/amazon-sagemaker-examples | c5ddecce1f739a345465b9a38b064983a129141d | [
"Apache-2.0"
] | 2,610 | 2020-10-01T14:14:53.000Z | 2022-03-31T18:02:31.000Z | reinforcement_learning/rl_traveling_salesman_vehicle_routing_coach/src/evaluate-coach.py | jerrypeng7773/amazon-sagemaker-examples | c5ddecce1f739a345465b9a38b064983a129141d | [
"Apache-2.0"
] | 1,959 | 2020-09-30T20:22:42.000Z | 2022-03-31T23:58:37.000Z | reinforcement_learning/rl_traveling_salesman_vehicle_routing_coach/src/evaluate-coach.py | jerrypeng7773/amazon-sagemaker-examples | c5ddecce1f739a345465b9a38b064983a129141d | [
"Apache-2.0"
] | 2,052 | 2020-09-30T22:11:46.000Z | 2022-03-31T23:02:51.000Z | import argparse
import os
import rl_coach
from rl_coach.base_parameters import Frameworks, TaskParameters
from rl_coach.core_types import EnvironmentSteps
from sagemaker_rl.coach_launcher import CoachConfigurationList, SageMakerCoachPresetLauncher
def inplace_replace_in_file(filepath, old, new):
with open(filepath, "r") as f:
contents = f.read()
with open(filepath, "w") as f:
contents = contents.replace(old, new)
f.write(contents)
class MyLauncher(SageMakerCoachPresetLauncher):
def default_preset_name(self):
"""This points to a .py file that configures everything about the RL job.
It can be overridden at runtime by specifying the RLCOACH_PRESET hyperparameter.
"""
return "preset-tsp-easy"
def start_single_threaded(self, task_parameters, graph_manager, args):
"""Override to use custom evaluate_steps, instead of infinite steps. Just evaluate."""
graph_manager.agent_params.visualization.dump_csv = (
False # issues with CSV export in evaluation only
)
graph_manager.create_graph(task_parameters)
graph_manager.evaluate(EnvironmentSteps(args.evaluate_steps))
graph_manager.close()
def get_config_args(self, parser):
"""Overrides the default CLI parsing.
Sets the configuration parameters for what a SageMaker run should do.
Note, this does not support the "play" mode.
"""
### Parse Arguments
# first, convert the parser to a Namespace object with all default values.
empty_arg_list = []
args, _ = parser.parse_known_args(args=empty_arg_list)
parser = self.sagemaker_argparser()
sage_args, unknown = parser.parse_known_args()
### Set Arguments
args.preset = sage_args.RLCOACH_PRESET
backend = os.getenv("COACH_BACKEND", "tensorflow")
args.framework = args.framework = Frameworks[backend]
args.checkpoint_save_dir = None
args.checkpoint_restore_dir = "/opt/ml/input/data/checkpoint"
# Correct TensorFlow checkpoint file (https://github.com/tensorflow/tensorflow/issues/9146)
if backend == "tensorflow":
checkpoint_filepath = os.path.join(args.checkpoint_restore_dir, "checkpoint")
inplace_replace_in_file(checkpoint_filepath, "/opt/ml/output/data/checkpoint", ".")
# Override experiment_path used for outputs (note CSV not stored, see `start_single_threaded`).
args.experiment_path = "/opt/ml/output/intermediate"
rl_coach.logger.experiment_path = "/opt/ml/output/intermediate" # for gifs
args.evaluate = True # not actually used, but must be set (see `evaluate_steps`)
args.evaluate_steps = sage_args.evaluate_steps
args.no_summary = True # so process doesn't hang at end
# must be set
self.hyperparameters = CoachConfigurationList()
return args
def sagemaker_argparser(self):
"""
Expose only the CLI arguments that make sense in the SageMaker context.
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-p",
"--RLCOACH_PRESET",
help="(string) Name of the file with the RLCoach preset",
default=self.default_preset_name(),
type=str,
)
parser.add_argument(
"--evaluate_steps",
help="(int) Number of evaluation steps to takr",
default=1000,
type=int,
)
return parser
@classmethod
def evaluate_main(cls):
"""Entrypoint for training.
Parses command-line arguments and starts training.
"""
evaluator = cls()
evaluator.launch()
if __name__ == "__main__":
MyLauncher.evaluate_main()
| 39.020408 | 103 | 0.664487 | import argparse
import os
import rl_coach
from rl_coach.base_parameters import Frameworks, TaskParameters
from rl_coach.core_types import EnvironmentSteps
from sagemaker_rl.coach_launcher import CoachConfigurationList, SageMakerCoachPresetLauncher
def inplace_replace_in_file(filepath, old, new):
with open(filepath, "r") as f:
contents = f.read()
with open(filepath, "w") as f:
contents = contents.replace(old, new)
f.write(contents)
class MyLauncher(SageMakerCoachPresetLauncher):
def default_preset_name(self):
return "preset-tsp-easy"
def start_single_threaded(self, task_parameters, graph_manager, args):
graph_manager.agent_params.visualization.dump_csv = (
False
)
graph_manager.create_graph(task_parameters)
graph_manager.evaluate(EnvironmentSteps(args.evaluate_steps))
graph_manager.close()
def get_config_args(self, parser):
[]
args, _ = parser.parse_known_args(args=empty_arg_list)
parser = self.sagemaker_argparser()
sage_args, unknown = parser.parse_known_args()
s.RLCOACH_PRESET
backend = os.getenv("COACH_BACKEND", "tensorflow")
args.framework = args.framework = Frameworks[backend]
args.checkpoint_save_dir = None
args.checkpoint_restore_dir = "/opt/ml/input/data/checkpoint"
if backend == "tensorflow":
checkpoint_filepath = os.path.join(args.checkpoint_restore_dir, "checkpoint")
inplace_replace_in_file(checkpoint_filepath, "/opt/ml/output/data/checkpoint", ".")
args.experiment_path = "/opt/ml/output/intermediate"
rl_coach.logger.experiment_path = "/opt/ml/output/intermediate"
args.evaluate = True
args.evaluate_steps = sage_args.evaluate_steps
args.no_summary = True
# must be set
self.hyperparameters = CoachConfigurationList()
return args
def sagemaker_argparser(self):
parser = argparse.ArgumentParser()
parser.add_argument(
"-p",
"--RLCOACH_PRESET",
help="(string) Name of the file with the RLCoach preset",
default=self.default_preset_name(),
type=str,
)
parser.add_argument(
"--evaluate_steps",
help="(int) Number of evaluation steps to takr",
default=1000,
type=int,
)
return parser
@classmethod
def evaluate_main(cls):
evaluator = cls()
evaluator.launch()
if __name__ == "__main__":
MyLauncher.evaluate_main()
| true | true |
1c2bddb37a35a95625d7b40d40467e4b804ab7b0 | 15,925 | py | Python | mindspore/ops/operations/debug_ops.py | kungfu-team/mindspore-bert | 71501cf52ae01db9d6a73fb64bcfe68a6509dc32 | [
"Apache-2.0"
] | null | null | null | mindspore/ops/operations/debug_ops.py | kungfu-team/mindspore-bert | 71501cf52ae01db9d6a73fb64bcfe68a6509dc32 | [
"Apache-2.0"
] | null | null | null | mindspore/ops/operations/debug_ops.py | kungfu-team/mindspore-bert | 71501cf52ae01db9d6a73fb64bcfe68a6509dc32 | [
"Apache-2.0"
] | null | null | null | # 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.
# ============================================================================
"""debug_ops"""
from types import FunctionType, MethodType
from mindspore import context
from ..._checkparam import Validator as validator
from ..._checkparam import Rel
from ...common import dtype as mstype
from ..primitive import prim_attr_register, PrimitiveWithInfer
def _check_mode(class_name):
"""Check for PyNative mode."""
mode = context.get_context('mode')
if mode == context.PYNATIVE_MODE:
raise RuntimeError(f'{class_name} operator does not support PyNative mode.')
def _check_summary_param(name, value, class_name):
"""Checks the name and value is valid for summary."""
_check_mode(class_name)
n_type = name['dtype']
n_value = name['value']
validator.check_value_type('name', n_type, [type(mstype.string)], class_name)
if not n_value:
raise ValueError(f"For 'name' the value should by valid string in {class_name}, but got an empty string.")
v_type = value['dtype']
validator.check_value_type('value', v_type, [type(mstype.tensor)], class_name)
# Note: The return value of the summary operator is not used,
# so there's nothing special about the return `dtype` or `shape`, any value is ok.
# The `value` should be set to None, else summary operators may be optimized at compile graph phase,
# it cause summary operators can not record data in constant folding scene.
SUMMARY_RETURN_VALUE = {'dtype': mstype.int32, 'shape': [1], 'value': None}
class ScalarSummary(PrimitiveWithInfer):
"""
Outputs a scalar to a protocol buffer through a scalar summary operator.
Inputs:
- **name** (str) - The name of the input variable, it must not be an empty string.
- **value** (Tensor) - The value of scalar, and the shape of value must be [] or [1].
Raises:
TypeError: If `name` is not a str.
TypeError: If `value` is not a Tensor.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import mindspore.nn as nn
>>> import mindspore.ops as ops
>>>
>>>
>>> class SummaryDemo(nn.Cell):
... def __init__(self,):
... super(SummaryDemo, self).__init__()
... self.summary = ops.ScalarSummary()
... self.add = ops.Add()
...
... def construct(self, x, y):
... name = "x"
... self.summary(name, x)
... x = self.add(x, y)
... return x
...
"""
@prim_attr_register
def __init__(self):
"""init"""
self.add_prim_attr("side_effect_io", True)
def __infer__(self, name, value):
_check_summary_param(name, value, self.__class__.__name__)
v_shape = value['shape']
# In the summary, the value whose shape is [1] is also considered as a scalar.
if v_shape and v_shape != [1]:
raise ValueError(f"For 'value' the type should be scalar, "
f"shape should be [] or [1] in {self.__class__.__name__}, but got {v_shape}.")
return SUMMARY_RETURN_VALUE
class ImageSummary(PrimitiveWithInfer):
"""
Outputs the image tensor to protocol buffer through image summary operator.
Inputs:
- **name** (str) - The name of the input variable, it must not be an empty string.
- **value** (Tensor) - The value of image, the rank of tensor must be 4.
Raises:
TypeError: If `name` is not a str.
TypeError: If `value` is not a Tensor.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import mindspore.nn as nn
>>> import mindspore.ops as ops
>>>
>>>
>>> class Net(nn.Cell):
... def __init__(self):
... super(Net, self).__init__()
... self.summary = ops.ImageSummary()
...
... def construct(self, x):
... name = "image"
... out = self.summary(name, x)
... return out
...
"""
@prim_attr_register
def __init__(self):
"""init"""
self.add_prim_attr("side_effect_io", True)
def __infer__(self, name, value):
_check_summary_param(name, value, self.__class__.__name__)
# The shape dim of image should be 4.
v_shape = value['shape']
image_dim = 4
if len(v_shape) != image_dim:
raise ValueError(f"For 'value' the dim should be {image_dim} in {self.__class__.__name__},"
f" but got {len(v_shape)}.")
return SUMMARY_RETURN_VALUE
class TensorSummary(PrimitiveWithInfer):
"""
Outputs a tensor to a protocol buffer through a tensor summary operator.
Inputs:
- **name** (str) - The name of the input variable.
- **value** (Tensor) - The value of tensor, and the rank of tensor must be greater than 0.
Raises:
TypeError: If `name` is not a str.
TypeError: If `value` is not a Tensor.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import mindspore.nn as nn
>>> import mindspore.ops as ops
>>>
>>>
>>> class SummaryDemo(nn.Cell):
... def __init__(self,):
... super(SummaryDemo, self).__init__()
... self.summary = ops.TensorSummary()
... self.add = ops.Add()
...
... def construct(self, x, y):
... x = self.add(x, y)
... name = "x"
... self.summary(name, x)
... return x
...
"""
@prim_attr_register
def __init__(self):
"""init"""
self.add_prim_attr("side_effect_io", True)
def __infer__(self, name, value):
_check_summary_param(name, value, self.__class__.__name__)
v_shape = value['shape']
# In the summary, the value whose shape is [] is not considered as a tensor.
if not v_shape:
raise ValueError(f"For 'value' the type should be tensor in {self.__class__.__name__}, "
f"shape should not be [].")
return SUMMARY_RETURN_VALUE
class HistogramSummary(PrimitiveWithInfer):
"""
Outputs the tensor to protocol buffer through histogram summary operator.
Inputs:
- **name** (str) - The name of the input variable.
- **value** (Tensor) - The value of tensor, and the rank of tensor must be greater than 0.
Raises:
TypeError: If `name` is not a str.
TypeError: If `value` is not a Tensor.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import mindspore.nn as nn
>>> import mindspore.ops as ops
>>>
>>>
>>> class SummaryDemo(nn.Cell):
... def __init__(self,):
... super(SummaryDemo, self).__init__()
... self.summary = ops.HistogramSummary()
... self.add = ops.Add()
...
... def construct(self, x, y):
... x = self.add(x, y)
... name = "x"
... self.summary(name, x)
... return x
...
"""
@prim_attr_register
def __init__(self):
"""init"""
self.add_prim_attr("side_effect_io", True)
def __infer__(self, name, value):
_check_summary_param(name, value, self.__class__.__name__)
v_shape = value['shape']
# In the summary, the histogram value should be a tensor whose shape is not [].
if not v_shape:
raise ValueError(f"For 'value' the type should be tensor in {self.__class__.__name__}, "
f"shape should not be [].")
return SUMMARY_RETURN_VALUE
class InsertGradientOf(PrimitiveWithInfer):
"""
Attaches callback to the graph node that will be invoked on the node's gradient.
Args:
f (Function): MindSpore's Function. Callback function.
Inputs:
- **input_x** (Any) - The graph node to attach to.
Outputs:
Tensor, returns `input_x` directly. `InsertGradientOf` does not affect the forward result.
Raises:
TypeError: If `f` is not a function of mindspore.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> def clip_gradient(dx):
... ret = dx
... if ret > 1.0:
... ret = 1.0
...
... if ret < 0.2:
... ret = 0.2
...
... return ret
...
>>> clip = ops.InsertGradientOf(clip_gradient)
>>> grad_all = ops.GradOperation(get_all=True)
>>> def InsertGradientOfClipDemo():
... def clip_test(x, y):
... x = clip(x)
... y = clip(y)
... c = x * y
... return c
...
... @ms_function
... def f(x, y):
... return clip_test(x, y)
...
... def fd(x, y):
... return grad_all(clip_test)(x, y)
...
... print("forward: ", f(1.1, 0.1))
... print("clip_gradient:", fd(1.1, 0.1))
...
"""
@prim_attr_register
def __init__(self, f):
self.add_prim_attr('side_effect_backprop', True)
self.f = f
def infer_shape(self, x_shape):
return x_shape
def infer_dtype(self, x_type):
return x_type
class HookBackward(PrimitiveWithInfer):
"""
This operation is used as a tag to hook gradient in intermediate variables. Note that this function
is only supported in Pynative Mode.
Note:
The hook function must be defined like `hook_fn(grad) -> Tensor or None`,
where grad is the gradient passed to the primitive and gradient may be
modified and passed to next primitive. The difference between a hook function and
callback of InsertGradientOf is that a hook function is executed in the python
environment while callback will be parsed and added to the graph.
Args:
hook_fn (Function): Python function. hook function.
Inputs:
- **inputs** (Tensor) - The variable to hook.
Raises:
TypeError: If `inputs` are not a Tensor.
TypeError: If `hook_fn` is not a function of python.
Examples:
>>> def hook_fn(grad_out):
... print(grad_out)
...
>>> grad_all = GradOperation(get_all=True)
>>> hook = ops.HookBackward(hook_fn)
>>> def hook_test(x, y):
... z = x * y
... z = hook(z)
... z = z * y
... return z
...
>>> def backward(x, y):
... return grad_all(hook_test)(x, y)
...
>>> output = backward(1, 2)
>>> print(output)
"""
def __init__(self, hook_fn, cell_id=""):
super(HookBackward, self).__init__(self.__class__.__name__)
self.add_prim_attr("cell_id", cell_id)
self.init_attrs["cell_id"] = cell_id
if not isinstance(hook_fn, (FunctionType, MethodType)):
raise TypeError("Hook function should be python function type.")
self.register_hook(hook_fn)
self.cell_id = cell_id
def infer_shape(self, *inputs_shape):
if len(inputs_shape) == 1:
return inputs_shape[0]
return inputs_shape
def infer_dtype(self, *inputs_type):
if len(inputs_type) == 1:
return inputs_type[0]
return inputs_type
class Print(PrimitiveWithInfer):
"""
Outputs the tensor or string to stdout.
Note:
In pynative mode, please use python print function.
In graph mode, the bool, int and float would be converted into Tensor to print,
str remains unchanged.
Inputs:
- **input_x** (Union[Tensor, bool, int, float, str]) - The graph node to attach to.
Supports multiple inputs which are separated by ','.
Raises:
TypeError: If `input_x` is not one of the following: Tensor, bool, int, float, str.
Supported Platforms:
``Ascend`` ``GPU``
Examples:
>>> class PrintDemo(nn.Cell):
... def __init__(self):
... super(PrintDemo, self).__init__()
... self.print = ops.Print()
...
... def construct(self, x, y):
... self.print('Print Tensor x and Tensor y:', x, y)
... return x
...
>>> x = Tensor(np.ones([2, 1]).astype(np.int32))
>>> y = Tensor(np.ones([2, 2]).astype(np.int32))
>>> net = PrintDemo()
>>> result = net(x, y)
Print Tensor x and Tensor y:
[[1]
[1]]
[[1 1]
[1 1]]
"""
@prim_attr_register
def __init__(self):
self.add_prim_attr("side_effect_io", True)
def __call__(self, *args):
for arg in args:
print(arg)
def infer_shape(self, *inputs):
return [1]
def infer_dtype(self, *inputs):
# check argument types except the last one (io state).
for ele in inputs[:-1]:
validator.check_subclass("input", ele,
[mstype.tensor, mstype.int_, mstype.float_, mstype.bool_, mstype.string],
self.name)
return mstype.int32
class Assert(PrimitiveWithInfer):
"""
Asserts that the given condition is True.
If input condition evaluates to false, print the list of tensor in data.
Args:
summarize (int): Print this many entries of each tensor.
Inputs:
- **condition** [Union[Tensor[bool], bool]] - The condition to evaluate.
- **input_data** (Union(tuple[Tensor], list[Tensor])) - The tensors to print out when condition is false.
Raises:
TypeError: If `summarize` is not an int.
TypeError: If `condition` is neither a Tensor nor a bool.
TypeError: If `input_data` is neither a tuple nor a list.
Examples:
>>> class AssertDemo(nn.Cell):
... def __init__(self):
... super(AssertDemo, self).__init__()
... self.assert1 = ops.Assert(summarize=10)
... self.add = ops.Add()
...
... def construct(self, x, y):
... data = self.add(x, y)
... self.assert1(True, [data])
... return data
...
"""
@prim_attr_register
def __init__(self, summarize=3):
"""Initialize Assert"""
self.summarize = validator.check_value_type("summarize", summarize, [int], self.name)
def infer_shape(self, condition, inputs):
condition_len = len(condition)
validator.check_int(condition_len, 1, Rel.LE, "condition's rank", self.name)
if condition_len == 1:
validator.check_equal_int(condition[0], 1, "condition[0]", self.name)
return [1]
def infer_dtype(self, condition, inputs):
validator.check_scalar_or_tensor_types_same({"condition": condition}, [mstype.bool_], self.name)
for dtype in inputs:
validator.check_subclass("input", dtype, [mstype.tensor], self.name)
return mstype.int32
| 32.566462 | 114 | 0.565777 |
from types import FunctionType, MethodType
from mindspore import context
from ..._checkparam import Validator as validator
from ..._checkparam import Rel
from ...common import dtype as mstype
from ..primitive import prim_attr_register, PrimitiveWithInfer
def _check_mode(class_name):
mode = context.get_context('mode')
if mode == context.PYNATIVE_MODE:
raise RuntimeError(f'{class_name} operator does not support PyNative mode.')
def _check_summary_param(name, value, class_name):
_check_mode(class_name)
n_type = name['dtype']
n_value = name['value']
validator.check_value_type('name', n_type, [type(mstype.string)], class_name)
if not n_value:
raise ValueError(f"For 'name' the value should by valid string in {class_name}, but got an empty string.")
v_type = value['dtype']
validator.check_value_type('value', v_type, [type(mstype.tensor)], class_name)
# The `value` should be set to None, else summary operators may be optimized at compile graph phase,
# it cause summary operators can not record data in constant folding scene.
SUMMARY_RETURN_VALUE = {'dtype': mstype.int32, 'shape': [1], 'value': None}
class ScalarSummary(PrimitiveWithInfer):
@prim_attr_register
def __init__(self):
self.add_prim_attr("side_effect_io", True)
def __infer__(self, name, value):
_check_summary_param(name, value, self.__class__.__name__)
v_shape = value['shape']
# In the summary, the value whose shape is [1] is also considered as a scalar.
if v_shape and v_shape != [1]:
raise ValueError(f"For 'value' the type should be scalar, "
f"shape should be [] or [1] in {self.__class__.__name__}, but got {v_shape}.")
return SUMMARY_RETURN_VALUE
class ImageSummary(PrimitiveWithInfer):
@prim_attr_register
def __init__(self):
self.add_prim_attr("side_effect_io", True)
def __infer__(self, name, value):
_check_summary_param(name, value, self.__class__.__name__)
# The shape dim of image should be 4.
v_shape = value['shape']
image_dim = 4
if len(v_shape) != image_dim:
raise ValueError(f"For 'value' the dim should be {image_dim} in {self.__class__.__name__},"
f" but got {len(v_shape)}.")
return SUMMARY_RETURN_VALUE
class TensorSummary(PrimitiveWithInfer):
@prim_attr_register
def __init__(self):
self.add_prim_attr("side_effect_io", True)
def __infer__(self, name, value):
_check_summary_param(name, value, self.__class__.__name__)
v_shape = value['shape']
# In the summary, the value whose shape is [] is not considered as a tensor.
if not v_shape:
raise ValueError(f"For 'value' the type should be tensor in {self.__class__.__name__}, "
f"shape should not be [].")
return SUMMARY_RETURN_VALUE
class HistogramSummary(PrimitiveWithInfer):
@prim_attr_register
def __init__(self):
self.add_prim_attr("side_effect_io", True)
def __infer__(self, name, value):
_check_summary_param(name, value, self.__class__.__name__)
v_shape = value['shape']
# In the summary, the histogram value should be a tensor whose shape is not [].
if not v_shape:
raise ValueError(f"For 'value' the type should be tensor in {self.__class__.__name__}, "
f"shape should not be [].")
return SUMMARY_RETURN_VALUE
class InsertGradientOf(PrimitiveWithInfer):
@prim_attr_register
def __init__(self, f):
self.add_prim_attr('side_effect_backprop', True)
self.f = f
def infer_shape(self, x_shape):
return x_shape
def infer_dtype(self, x_type):
return x_type
class HookBackward(PrimitiveWithInfer):
def __init__(self, hook_fn, cell_id=""):
super(HookBackward, self).__init__(self.__class__.__name__)
self.add_prim_attr("cell_id", cell_id)
self.init_attrs["cell_id"] = cell_id
if not isinstance(hook_fn, (FunctionType, MethodType)):
raise TypeError("Hook function should be python function type.")
self.register_hook(hook_fn)
self.cell_id = cell_id
def infer_shape(self, *inputs_shape):
if len(inputs_shape) == 1:
return inputs_shape[0]
return inputs_shape
def infer_dtype(self, *inputs_type):
if len(inputs_type) == 1:
return inputs_type[0]
return inputs_type
class Print(PrimitiveWithInfer):
@prim_attr_register
def __init__(self):
self.add_prim_attr("side_effect_io", True)
def __call__(self, *args):
for arg in args:
print(arg)
def infer_shape(self, *inputs):
return [1]
def infer_dtype(self, *inputs):
# check argument types except the last one (io state).
for ele in inputs[:-1]:
validator.check_subclass("input", ele,
[mstype.tensor, mstype.int_, mstype.float_, mstype.bool_, mstype.string],
self.name)
return mstype.int32
class Assert(PrimitiveWithInfer):
@prim_attr_register
def __init__(self, summarize=3):
self.summarize = validator.check_value_type("summarize", summarize, [int], self.name)
def infer_shape(self, condition, inputs):
condition_len = len(condition)
validator.check_int(condition_len, 1, Rel.LE, "condition's rank", self.name)
if condition_len == 1:
validator.check_equal_int(condition[0], 1, "condition[0]", self.name)
return [1]
def infer_dtype(self, condition, inputs):
validator.check_scalar_or_tensor_types_same({"condition": condition}, [mstype.bool_], self.name)
for dtype in inputs:
validator.check_subclass("input", dtype, [mstype.tensor], self.name)
return mstype.int32
| true | true |
1c2bde7e21b5791e6b0be6b7981c4980a2ceffae | 1,817 | py | Python | clonebuild.py | pombreda/pydee | 133609d4e378361d968e7a06baa11256e0e2f403 | [
"MIT"
] | null | null | null | clonebuild.py | pombreda/pydee | 133609d4e378361d968e7a06baa11256e0e2f403 | [
"MIT"
] | null | null | null | clonebuild.py | pombreda/pydee | 133609d4e378361d968e7a06baa11256e0e2f403 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
#
# Copyright © 2009 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see pydeelib/__init__.py for details)
"""
Cloning Pydee mercurial repository
Building:
.tar.gz source distribution package
.exe and .egg installers
"""
import os, shutil, tarfile
import os.path as osp
import pydeelib as mod
name = 'pydee'
parentdir = osp.join(os.getcwd(), osp.pardir)
version = '%s-%s' % (name, mod.__version__)
os.chdir(parentdir)
if osp.isdir(version):
## Removing temporary directory if it already exists
shutil.rmtree(version)
os.system('hg clone %s %s' % (name, version))
## Creating source distribution archive
tar = tarfile.open("%s.tar.gz" % version, "w|gz")
tar.add(version, recursive=True)
tar.close()
## Building .exe and .egg installers
os.chdir(version)
build_cmd = 'python setup.py build_ext --compiler=mingw32'
os.system('%s bdist_wininst' % build_cmd)
os.system('%s bdist_egg' % build_cmd)
# No longer building the .msi installer since it does not support
# prerelease version numbering (e.g. 1.0.0beta1):
#os.system('%s bdist_msi' % build_cmd)
## Moving .exe and .egg files to the parent directory
os.chdir(parentdir)
dist = osp.join(version, "dist")
info = osp.join(version, "%s.egg-info" % name)
# No longer building the .msi installer since it does not support
# prerelease version numbering (e.g. 1.0.0beta1):
#for name in ["%s.win32-py2.5.msi" % version,
# "%s.win32.exe" % version,
for name in ["%s.win32.exe" % version,
"%s-py2.5.egg" % version]:
shutil.copy(osp.join(dist, name), osp.join(parentdir, name))
name = "PKG-INFO"
shutil.copy(osp.join(info, name), osp.join(parentdir, "%s-info" % version))
## Removing temporary directory
shutil.rmtree(version)
| 31.327586 | 76 | 0.678041 |
import os, shutil, tarfile
import os.path as osp
import pydeelib as mod
name = 'pydee'
parentdir = osp.join(os.getcwd(), osp.pardir)
version = '%s-%s' % (name, mod.__version__)
os.chdir(parentdir)
if osp.isdir(version):
%s' % (name, version))
on, "w|gz")
tar.add(version, recursive=True)
tar.close()
hon setup.py build_ext --compiler=mingw32'
os.system('%s bdist_wininst' % build_cmd)
os.system('%s bdist_egg' % build_cmd)
)
info = osp.join(version, "%s.egg-info" % name)
for name in ["%s.win32.exe" % version,
"%s-py2.5.egg" % version]:
shutil.copy(osp.join(dist, name), osp.join(parentdir, name))
name = "PKG-INFO"
shutil.copy(osp.join(info, name), osp.join(parentdir, "%s-info" % version))
| true | true |
1c2be15f633c8e26a248021a3d87732554d93dc9 | 958 | py | Python | modules/python-codes/modules/databases/mysql/modules/theory-practice/src/insert_into_function.py | drigols/Studies | 9c293156935b491ded24be6b511daac67fd43538 | [
"MIT"
] | null | null | null | modules/python-codes/modules/databases/mysql/modules/theory-practice/src/insert_into_function.py | drigols/Studies | 9c293156935b491ded24be6b511daac67fd43538 | [
"MIT"
] | null | null | null | modules/python-codes/modules/databases/mysql/modules/theory-practice/src/insert_into_function.py | drigols/Studies | 9c293156935b491ded24be6b511daac67fd43538 | [
"MIT"
] | null | null | null | import mysql.connector
def insert_varibles_into_table(id, name, price, purchase_date):
try:
connection = mysql.connector.connect(
host='localhost',
database='Electronics',
user='root',
password='toor'
)
except mysql.connector.Error as error:
print("Failed to insert into MySQL table {}".format(error))
else:
insert_query = """
INSERT INTO Laptop (Id, Name, Price, Purchase_date)
VALUES (%s, %s, %s, %s)
"""
cursor = connection.cursor()
record = (id, name, price, purchase_date)
cursor.execute(insert_query, record)
connection.commit()
print("Record inserted successfully into Laptop table")
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
# Drive
insert_varibles_into_table(1, 'Acer', 6999, '2019-04-14')
insert_varibles_into_table(2, 'MacBook Pro', 2499, '2019-06-20')
| 29.9375 | 64 | 0.655532 | import mysql.connector
def insert_varibles_into_table(id, name, price, purchase_date):
try:
connection = mysql.connector.connect(
host='localhost',
database='Electronics',
user='root',
password='toor'
)
except mysql.connector.Error as error:
print("Failed to insert into MySQL table {}".format(error))
else:
insert_query = """
INSERT INTO Laptop (Id, Name, Price, Purchase_date)
VALUES (%s, %s, %s, %s)
"""
cursor = connection.cursor()
record = (id, name, price, purchase_date)
cursor.execute(insert_query, record)
connection.commit()
print("Record inserted successfully into Laptop table")
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
insert_varibles_into_table(1, 'Acer', 6999, '2019-04-14')
insert_varibles_into_table(2, 'MacBook Pro', 2499, '2019-06-20')
| true | true |
1c2be3fa240a7a8e67431b08479f6796c2934516 | 16,344 | py | Python | spark_auto_mapper_fhir/resources/evidence.py | imranq2/SparkAutoMapper.FHIR | dd23b218fb0097d1edc2f3e688e8d6d4d7278bd2 | [
"Apache-2.0"
] | 1 | 2020-10-31T23:25:07.000Z | 2020-10-31T23:25:07.000Z | spark_auto_mapper_fhir/resources/evidence.py | icanbwell/SparkAutoMapper.FHIR | 98f368e781b46523142c7cb513c670d659a93c9b | [
"Apache-2.0"
] | null | null | null | spark_auto_mapper_fhir/resources/evidence.py | icanbwell/SparkAutoMapper.FHIR | 98f368e781b46523142c7cb513c670d659a93c9b | [
"Apache-2.0"
] | null | null | null | from __future__ import annotations
from typing import Optional, TYPE_CHECKING, Union
# noinspection PyPackageRequirements
from pyspark.sql.types import StructType, DataType
from spark_auto_mapper_fhir.fhir_types.date import FhirDate
from spark_auto_mapper_fhir.fhir_types.date_time import FhirDateTime
from spark_auto_mapper_fhir.fhir_types.list import FhirList
from spark_auto_mapper_fhir.fhir_types.string import FhirString
from spark_auto_mapper_fhir.complex_types.meta import Meta
from spark_auto_mapper_fhir.extensions.extension_base import ExtensionBase
from spark_auto_mapper_fhir.fhir_types.id import FhirId
from spark_auto_mapper_fhir.fhir_types.uri import FhirUri
from spark_auto_mapper_fhir.base_types.fhir_resource_base import FhirResourceBase
from spark_fhir_schemas.r4.resources.evidence import EvidenceSchema
if TYPE_CHECKING:
pass
# id_ (id)
# meta (Meta)
# implicitRules (uri)
# language (CommonLanguages)
from spark_auto_mapper_fhir.value_sets.common_languages import CommonLanguagesCode
# text (Narrative)
from spark_auto_mapper_fhir.complex_types.narrative import Narrative
# contained (ResourceContainer)
from spark_auto_mapper_fhir.complex_types.resource_container import (
ResourceContainer,
)
# extension (Extension)
# modifierExtension (Extension)
# url (uri)
# identifier (Identifier)
from spark_auto_mapper_fhir.complex_types.identifier import Identifier
# version (string)
# name (string)
# title (string)
# shortTitle (string)
# subtitle (string)
# status (PublicationStatus)
from spark_auto_mapper_fhir.value_sets.publication_status import (
PublicationStatusCode,
)
# date (dateTime)
# publisher (string)
# contact (ContactDetail)
from spark_auto_mapper_fhir.complex_types.contact_detail import ContactDetail
# description (markdown)
from spark_auto_mapper_fhir.fhir_types.markdown import FhirMarkdown
# note (Annotation)
from spark_auto_mapper_fhir.complex_types.annotation import Annotation
# useContext (UsageContext)
from spark_auto_mapper_fhir.complex_types.usage_context import UsageContext
# jurisdiction (CodeableConcept)
from spark_auto_mapper_fhir.complex_types.codeable_concept import CodeableConcept
# Import for CodeableConcept for jurisdiction
from spark_auto_mapper_fhir.value_sets.jurisdiction_value_set import (
JurisdictionValueSetCode,
)
# End Import for CodeableConcept for jurisdiction
# copyright (markdown)
# approvalDate (date)
# lastReviewDate (date)
# effectivePeriod (Period)
from spark_auto_mapper_fhir.complex_types.period import Period
# topic (CodeableConcept)
# Import for CodeableConcept for topic
from spark_auto_mapper_fhir.value_sets.definition_topic import DefinitionTopicCode
# End Import for CodeableConcept for topic
# author (ContactDetail)
# editor (ContactDetail)
# reviewer (ContactDetail)
# endorser (ContactDetail)
# relatedArtifact (RelatedArtifact)
from spark_auto_mapper_fhir.complex_types.related_artifact import RelatedArtifact
# exposureBackground (Reference)
from spark_auto_mapper_fhir.complex_types.reference import Reference
# Imports for References for exposureBackground
from spark_auto_mapper_fhir.resources.evidence_variable import EvidenceVariable
# exposureVariant (Reference)
# Imports for References for exposureVariant
# outcome (Reference)
# Imports for References for outcome
# This file is auto-generated by generate_classes so do not edit manually
# noinspection PyPep8Naming
class Evidence(FhirResourceBase):
"""
Evidence
evidence.xsd
The Evidence resource describes the conditional state (population and any
exposures being compared within the population) and outcome (if specified)
that the knowledge (evidence, assertion, recommendation) is about.
If the element is present, it must have either a @value, an @id, or extensions
"""
# noinspection PyPep8Naming
def __init__(
self,
*,
id_: Optional[FhirId] = None,
meta: Optional[Meta] = None,
implicitRules: Optional[FhirUri] = None,
language: Optional[CommonLanguagesCode] = None,
text: Optional[Narrative] = None,
contained: Optional[FhirList[ResourceContainer]] = None,
extension: Optional[FhirList[ExtensionBase]] = None,
modifierExtension: Optional[FhirList[ExtensionBase]] = None,
url: Optional[FhirUri] = None,
identifier: Optional[FhirList[Identifier]] = None,
version: Optional[FhirString] = None,
name: Optional[FhirString] = None,
title: Optional[FhirString] = None,
shortTitle: Optional[FhirString] = None,
subtitle: Optional[FhirString] = None,
status: PublicationStatusCode,
date: Optional[FhirDateTime] = None,
publisher: Optional[FhirString] = None,
contact: Optional[FhirList[ContactDetail]] = None,
description: Optional[FhirMarkdown] = None,
note: Optional[FhirList[Annotation]] = None,
useContext: Optional[FhirList[UsageContext]] = None,
jurisdiction: Optional[
FhirList[CodeableConcept[JurisdictionValueSetCode]]
] = None,
copyright: Optional[FhirMarkdown] = None,
approvalDate: Optional[FhirDate] = None,
lastReviewDate: Optional[FhirDate] = None,
effectivePeriod: Optional[Period] = None,
topic: Optional[FhirList[CodeableConcept[DefinitionTopicCode]]] = None,
author: Optional[FhirList[ContactDetail]] = None,
editor: Optional[FhirList[ContactDetail]] = None,
reviewer: Optional[FhirList[ContactDetail]] = None,
endorser: Optional[FhirList[ContactDetail]] = None,
relatedArtifact: Optional[FhirList[RelatedArtifact]] = None,
exposureBackground: Reference[EvidenceVariable],
exposureVariant: Optional[FhirList[Reference[EvidenceVariable]]] = None,
outcome: Optional[FhirList[Reference[EvidenceVariable]]] = None,
) -> None:
"""
The Evidence resource describes the conditional state (population and any
exposures being compared within the population) and outcome (if specified)
that the knowledge (evidence, assertion, recommendation) is about.
If the element is present, it must have either a @value, an @id, or extensions
:param id_: The logical id of the resource, as used in the URL for the resource. Once
assigned, this value never changes.
:param meta: The metadata about the resource. This is content that is maintained by the
infrastructure. Changes to the content might not always be associated with
version changes to the resource.
:param implicitRules: A reference to a set of rules that were followed when the resource was
constructed, and which must be understood when processing the content. Often,
this is a reference to an implementation guide that defines the special rules
along with other profiles etc.
:param language: The base language in which the resource is written.
:param text: A human-readable narrative that contains a summary of the resource and can be
used to represent the content of the resource to a human. The narrative need
not encode all the structured data, but is required to contain sufficient
detail to make it "clinically safe" for a human to just read the narrative.
Resource definitions may define what content should be represented in the
narrative to ensure clinical safety.
:param contained: These resources do not have an independent existence apart from the resource
that contains them - they cannot be identified independently, and nor can they
have their own independent transaction scope.
:param extension: May be used to represent additional information that is not part of the basic
definition of the resource. To make the use of extensions safe and manageable,
there is a strict set of governance applied to the definition and use of
extensions. Though any implementer can define an extension, there is a set of
requirements that SHALL be met as part of the definition of the extension.
:param modifierExtension: May be used to represent additional information that is not part of the basic
definition of the resource and that modifies the understanding of the element
that contains it and/or the understanding of the containing element's
descendants. Usually modifier elements provide negation or qualification. To
make the use of extensions safe and manageable, there is a strict set of
governance applied to the definition and use of extensions. Though any
implementer is allowed to define an extension, there is a set of requirements
that SHALL be met as part of the definition of the extension. Applications
processing a resource are required to check for modifier extensions.
Modifier extensions SHALL NOT change the meaning of any elements on Resource
or DomainResource (including cannot change the meaning of modifierExtension
itself).
:param url: An absolute URI that is used to identify this evidence when it is referenced
in a specification, model, design or an instance; also called its canonical
identifier. This SHOULD be globally unique and SHOULD be a literal address at
which at which an authoritative instance of this evidence is (or will be)
published. This URL can be the target of a canonical reference. It SHALL
remain the same when the evidence is stored on different servers.
:param identifier: A formal identifier that is used to identify this evidence when it is
represented in other formats, or referenced in a specification, model, design
or an instance.
:param version: The identifier that is used to identify this version of the evidence when it
is referenced in a specification, model, design or instance. This is an
arbitrary value managed by the evidence author and is not expected to be
globally unique. For example, it might be a timestamp (e.g. yyyymmdd) if a
managed version is not available. There is also no expectation that versions
can be placed in a lexicographical sequence. To provide a version consistent
with the Decision Support Service specification, use the format
Major.Minor.Revision (e.g. 1.0.0). For more information on versioning
knowledge assets, refer to the Decision Support Service specification. Note
that a version is required for non-experimental active artifacts.
:param name: A natural language name identifying the evidence. This name should be usable
as an identifier for the module by machine processing applications such as
code generation.
:param title: A short, descriptive, user-friendly title for the evidence.
:param shortTitle: The short title provides an alternate title for use in informal descriptive
contexts where the full, formal title is not necessary.
:param subtitle: An explanatory or alternate title for the Evidence giving additional
information about its content.
:param status: The status of this evidence. Enables tracking the life-cycle of the content.
:param date: The date (and optionally time) when the evidence was published. The date must
change when the business version changes and it must change if the status code
changes. In addition, it should change when the substantive content of the
evidence changes.
:param publisher: The name of the organization or individual that published the evidence.
:param contact: Contact details to assist a user in finding and communicating with the
publisher.
:param description: A free text natural language description of the evidence from a consumer's
perspective.
:param note: A human-readable string to clarify or explain concepts about the resource.
:param useContext: The content was developed with a focus and intent of supporting the contexts
that are listed. These contexts may be general categories (gender, age, ...)
or may be references to specific programs (insurance plans, studies, ...) and
may be used to assist with indexing and searching for appropriate evidence
instances.
:param jurisdiction: A legal or geographic region in which the evidence is intended to be used.
:param copyright: A copyright statement relating to the evidence and/or its contents. Copyright
statements are generally legal restrictions on the use and publishing of the
evidence.
:param approvalDate: The date on which the resource content was approved by the publisher. Approval
happens once when the content is officially approved for usage.
:param lastReviewDate: The date on which the resource content was last reviewed. Review happens
periodically after approval but does not change the original approval date.
:param effectivePeriod: The period during which the evidence content was or is planned to be in active
use.
:param topic: Descriptive topics related to the content of the Evidence. Topics provide a
high-level categorization grouping types of Evidences that can be useful for
filtering and searching.
:param author: An individiual or organization primarily involved in the creation and
maintenance of the content.
:param editor: An individual or organization primarily responsible for internal coherence of
the content.
:param reviewer: An individual or organization primarily responsible for review of some aspect
of the content.
:param endorser: An individual or organization responsible for officially endorsing the content
for use in some setting.
:param relatedArtifact: Related artifacts such as additional documentation, justification, or
bibliographic references.
:param exposureBackground: A reference to a EvidenceVariable resource that defines the population for the
research.
:param exposureVariant: A reference to a EvidenceVariable resource that defines the exposure for the
research.
:param outcome: A reference to a EvidenceVariable resomece that defines the outcome for the
research.
"""
super().__init__(
resourceType="Evidence",
id_=id_,
meta=meta,
implicitRules=implicitRules,
language=language,
text=text,
contained=contained,
extension=extension,
modifierExtension=modifierExtension,
url=url,
identifier=identifier,
version=version,
name=name,
title=title,
shortTitle=shortTitle,
subtitle=subtitle,
status=status,
date=date,
publisher=publisher,
contact=contact,
description=description,
note=note,
useContext=useContext,
jurisdiction=jurisdiction,
copyright=copyright,
approvalDate=approvalDate,
lastReviewDate=lastReviewDate,
effectivePeriod=effectivePeriod,
topic=topic,
author=author,
editor=editor,
reviewer=reviewer,
endorser=endorser,
relatedArtifact=relatedArtifact,
exposureBackground=exposureBackground,
exposureVariant=exposureVariant,
outcome=outcome,
)
def get_schema(
self, include_extension: bool
) -> Optional[Union[StructType, DataType]]:
return EvidenceSchema.get_schema(include_extension=include_extension)
| 51.396226 | 117 | 0.711331 | from __future__ import annotations
from typing import Optional, TYPE_CHECKING, Union
from pyspark.sql.types import StructType, DataType
from spark_auto_mapper_fhir.fhir_types.date import FhirDate
from spark_auto_mapper_fhir.fhir_types.date_time import FhirDateTime
from spark_auto_mapper_fhir.fhir_types.list import FhirList
from spark_auto_mapper_fhir.fhir_types.string import FhirString
from spark_auto_mapper_fhir.complex_types.meta import Meta
from spark_auto_mapper_fhir.extensions.extension_base import ExtensionBase
from spark_auto_mapper_fhir.fhir_types.id import FhirId
from spark_auto_mapper_fhir.fhir_types.uri import FhirUri
from spark_auto_mapper_fhir.base_types.fhir_resource_base import FhirResourceBase
from spark_fhir_schemas.r4.resources.evidence import EvidenceSchema
if TYPE_CHECKING:
pass
from spark_auto_mapper_fhir.value_sets.common_languages import CommonLanguagesCode
from spark_auto_mapper_fhir.complex_types.narrative import Narrative
from spark_auto_mapper_fhir.complex_types.resource_container import (
ResourceContainer,
)
from spark_auto_mapper_fhir.complex_types.identifier import Identifier
from spark_auto_mapper_fhir.value_sets.publication_status import (
PublicationStatusCode,
)
from spark_auto_mapper_fhir.complex_types.contact_detail import ContactDetail
from spark_auto_mapper_fhir.fhir_types.markdown import FhirMarkdown
from spark_auto_mapper_fhir.complex_types.annotation import Annotation
from spark_auto_mapper_fhir.complex_types.usage_context import UsageContext
from spark_auto_mapper_fhir.complex_types.codeable_concept import CodeableConcept
from spark_auto_mapper_fhir.value_sets.jurisdiction_value_set import (
JurisdictionValueSetCode,
)
from spark_auto_mapper_fhir.complex_types.period import Period
from spark_auto_mapper_fhir.value_sets.definition_topic import DefinitionTopicCode
from spark_auto_mapper_fhir.complex_types.related_artifact import RelatedArtifact
from spark_auto_mapper_fhir.complex_types.reference import Reference
from spark_auto_mapper_fhir.resources.evidence_variable import EvidenceVariable
class Evidence(FhirResourceBase):
def __init__(
self,
*,
id_: Optional[FhirId] = None,
meta: Optional[Meta] = None,
implicitRules: Optional[FhirUri] = None,
language: Optional[CommonLanguagesCode] = None,
text: Optional[Narrative] = None,
contained: Optional[FhirList[ResourceContainer]] = None,
extension: Optional[FhirList[ExtensionBase]] = None,
modifierExtension: Optional[FhirList[ExtensionBase]] = None,
url: Optional[FhirUri] = None,
identifier: Optional[FhirList[Identifier]] = None,
version: Optional[FhirString] = None,
name: Optional[FhirString] = None,
title: Optional[FhirString] = None,
shortTitle: Optional[FhirString] = None,
subtitle: Optional[FhirString] = None,
status: PublicationStatusCode,
date: Optional[FhirDateTime] = None,
publisher: Optional[FhirString] = None,
contact: Optional[FhirList[ContactDetail]] = None,
description: Optional[FhirMarkdown] = None,
note: Optional[FhirList[Annotation]] = None,
useContext: Optional[FhirList[UsageContext]] = None,
jurisdiction: Optional[
FhirList[CodeableConcept[JurisdictionValueSetCode]]
] = None,
copyright: Optional[FhirMarkdown] = None,
approvalDate: Optional[FhirDate] = None,
lastReviewDate: Optional[FhirDate] = None,
effectivePeriod: Optional[Period] = None,
topic: Optional[FhirList[CodeableConcept[DefinitionTopicCode]]] = None,
author: Optional[FhirList[ContactDetail]] = None,
editor: Optional[FhirList[ContactDetail]] = None,
reviewer: Optional[FhirList[ContactDetail]] = None,
endorser: Optional[FhirList[ContactDetail]] = None,
relatedArtifact: Optional[FhirList[RelatedArtifact]] = None,
exposureBackground: Reference[EvidenceVariable],
exposureVariant: Optional[FhirList[Reference[EvidenceVariable]]] = None,
outcome: Optional[FhirList[Reference[EvidenceVariable]]] = None,
) -> None:
super().__init__(
resourceType="Evidence",
id_=id_,
meta=meta,
implicitRules=implicitRules,
language=language,
text=text,
contained=contained,
extension=extension,
modifierExtension=modifierExtension,
url=url,
identifier=identifier,
version=version,
name=name,
title=title,
shortTitle=shortTitle,
subtitle=subtitle,
status=status,
date=date,
publisher=publisher,
contact=contact,
description=description,
note=note,
useContext=useContext,
jurisdiction=jurisdiction,
copyright=copyright,
approvalDate=approvalDate,
lastReviewDate=lastReviewDate,
effectivePeriod=effectivePeriod,
topic=topic,
author=author,
editor=editor,
reviewer=reviewer,
endorser=endorser,
relatedArtifact=relatedArtifact,
exposureBackground=exposureBackground,
exposureVariant=exposureVariant,
outcome=outcome,
)
def get_schema(
self, include_extension: bool
) -> Optional[Union[StructType, DataType]]:
return EvidenceSchema.get_schema(include_extension=include_extension)
| true | true |
1c2be47f10631d5a8e7cf6eb4ce1ccb2182f99fc | 5,849 | py | Python | k8sclient/models/v1_endpoint_subset.py | Arvinhub/client-python | d67df30f635231d68dc4c20b9b7e234c616c1e6a | [
"Apache-2.0"
] | 1 | 2021-06-16T02:57:18.000Z | 2021-06-16T02:57:18.000Z | k8sclient/models/v1_endpoint_subset.py | Arvinhub/client-python | d67df30f635231d68dc4c20b9b7e234c616c1e6a | [
"Apache-2.0"
] | null | null | null | k8sclient/models/v1_endpoint_subset.py | Arvinhub/client-python | d67df30f635231d68dc4c20b9b7e234c616c1e6a | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: unversioned
Generated by: https://github.com/swagger-api/swagger-codegen.git
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 pprint import pformat
from six import iteritems
import re
class V1EndpointSubset(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, addresses=None, not_ready_addresses=None, ports=None):
"""
V1EndpointSubset - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'addresses': 'list[V1EndpointAddress]',
'not_ready_addresses': 'list[V1EndpointAddress]',
'ports': 'list[V1EndpointPort]'
}
self.attribute_map = {
'addresses': 'addresses',
'not_ready_addresses': 'notReadyAddresses',
'ports': 'ports'
}
self._addresses = addresses
self._not_ready_addresses = not_ready_addresses
self._ports = ports
@property
def addresses(self):
"""
Gets the addresses of this V1EndpointSubset.
IP addresses which offer the related ports that are marked as ready. These endpoints should be considered safe for load balancers and clients to utilize.
:return: The addresses of this V1EndpointSubset.
:rtype: list[V1EndpointAddress]
"""
return self._addresses
@addresses.setter
def addresses(self, addresses):
"""
Sets the addresses of this V1EndpointSubset.
IP addresses which offer the related ports that are marked as ready. These endpoints should be considered safe for load balancers and clients to utilize.
:param addresses: The addresses of this V1EndpointSubset.
:type: list[V1EndpointAddress]
"""
self._addresses = addresses
@property
def not_ready_addresses(self):
"""
Gets the not_ready_addresses of this V1EndpointSubset.
IP addresses which offer the related ports but are not currently marked as ready because they have not yet finished starting, have recently failed a readiness check, or have recently failed a liveness check.
:return: The not_ready_addresses of this V1EndpointSubset.
:rtype: list[V1EndpointAddress]
"""
return self._not_ready_addresses
@not_ready_addresses.setter
def not_ready_addresses(self, not_ready_addresses):
"""
Sets the not_ready_addresses of this V1EndpointSubset.
IP addresses which offer the related ports but are not currently marked as ready because they have not yet finished starting, have recently failed a readiness check, or have recently failed a liveness check.
:param not_ready_addresses: The not_ready_addresses of this V1EndpointSubset.
:type: list[V1EndpointAddress]
"""
self._not_ready_addresses = not_ready_addresses
@property
def ports(self):
"""
Gets the ports of this V1EndpointSubset.
Port numbers available on the related IP addresses.
:return: The ports of this V1EndpointSubset.
:rtype: list[V1EndpointPort]
"""
return self._ports
@ports.setter
def ports(self, ports):
"""
Sets the ports of this V1EndpointSubset.
Port numbers available on the related IP addresses.
:param ports: The ports of this V1EndpointSubset.
:type: list[V1EndpointPort]
"""
self._ports = ports
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| 32.675978 | 215 | 0.622158 |
from pprint import pformat
from six import iteritems
import re
class V1EndpointSubset(object):
def __init__(self, addresses=None, not_ready_addresses=None, ports=None):
self.swagger_types = {
'addresses': 'list[V1EndpointAddress]',
'not_ready_addresses': 'list[V1EndpointAddress]',
'ports': 'list[V1EndpointPort]'
}
self.attribute_map = {
'addresses': 'addresses',
'not_ready_addresses': 'notReadyAddresses',
'ports': 'ports'
}
self._addresses = addresses
self._not_ready_addresses = not_ready_addresses
self._ports = ports
@property
def addresses(self):
return self._addresses
@addresses.setter
def addresses(self, addresses):
self._addresses = addresses
@property
def not_ready_addresses(self):
return self._not_ready_addresses
@not_ready_addresses.setter
def not_ready_addresses(self, not_ready_addresses):
self._not_ready_addresses = not_ready_addresses
@property
def ports(self):
return self._ports
@ports.setter
def ports(self, ports):
self._ports = ports
def to_dict(self):
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
return pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
1c2be5f8b532542090580e19f142e26cb4f30576 | 304 | py | Python | src_cs/f2py/importTest.py | marcomangano/idwarp | 3e0d4837a9b926b1cd227654365ca4adfbc08cbe | [
"Apache-2.0"
] | null | null | null | src_cs/f2py/importTest.py | marcomangano/idwarp | 3e0d4837a9b926b1cd227654365ca4adfbc08cbe | [
"Apache-2.0"
] | null | null | null | src_cs/f2py/importTest.py | marcomangano/idwarp | 3e0d4837a9b926b1cd227654365ca4adfbc08cbe | [
"Apache-2.0"
] | null | null | null | #! /usr/bin/env python
import sys
name = 'idwarp_cs'
print("Testing if module %s can be imported..." % name)
import_cmd = "import %s" % name
try:
exec(import_cmd)
except Exception as err:
print("Error: %s." % err)
sys.exit(1)
# end try
print("Module %s was successfully imported." % name)
| 19 | 55 | 0.657895 |
import sys
name = 'idwarp_cs'
print("Testing if module %s can be imported..." % name)
import_cmd = "import %s" % name
try:
exec(import_cmd)
except Exception as err:
print("Error: %s." % err)
sys.exit(1)
print("Module %s was successfully imported." % name)
| true | true |
1c2be683bc08652843c9c39c1d44570e125e0e4a | 2,496 | py | Python | src/programy/parser/template/nodes/normalise.py | ItsPhant/program-y | c2b211fcaf8cedc7d6d95a8ea9470a913efa1622 | [
"MIT"
] | null | null | null | src/programy/parser/template/nodes/normalise.py | ItsPhant/program-y | c2b211fcaf8cedc7d6d95a8ea9470a913efa1622 | [
"MIT"
] | null | null | null | src/programy/parser/template/nodes/normalise.py | ItsPhant/program-y | c2b211fcaf8cedc7d6d95a8ea9470a913efa1622 | [
"MIT"
] | 1 | 2020-02-21T17:58:05.000Z | 2020-02-21T17:58:05.000Z | """
Copyright (c) 2016-17 Keith Sterling http://www.keithsterling.com
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.
"""
import logging
from programy.parser.template.nodes.base import TemplateNode
######################################################################################################################
#
class TemplateNormalizeNode(TemplateNode):
def __init__(self):
TemplateNode.__init__(self)
def resolve_to_string(self, bot, clientid):
string = self.resolve_children_to_string(bot, clientid)
resolved = bot.brain.normals.normalise_string(string)
if logging.getLogger().isEnabledFor(logging.DEBUG):
logging.debug("[%s] resolved to [%s]", self.to_string(), resolved)
return resolved
def resolve(self, bot, clientid):
try:
return self.resolve_to_string(bot, clientid)
except Exception as excep:
logging.exception(excep)
return ""
def to_string(self):
return "NORMALIZE"
def to_xml(self, bot, clientid):
xml = "<normalize>"
xml += self.children_to_xml(bot, clientid)
xml += "</normalize>"
return xml
#######################################################################################################
# NORMALIZE_EXPRESSION ::== <normalize>TEMPLATE_EXPRESSION</normalize>
def add_default_star(self):
return True
def parse_expression(self, graph, expression):
self._parse_node(graph, expression)
| 40.918033 | 120 | 0.658253 |
import logging
from programy.parser.template.nodes.base import TemplateNode
| true | true |
1c2be7b6bf5c647793eaa54f0ac554ba1e28e82b | 11,671 | py | Python | autobahn/autobahn/wamp/test/test_protocol.py | luhn/AutobahnPython | 7d519052ab42dc029598ab9e2dbdd7af8e08341f | [
"Apache-2.0"
] | null | null | null | autobahn/autobahn/wamp/test/test_protocol.py | luhn/AutobahnPython | 7d519052ab42dc029598ab9e2dbdd7af8e08341f | [
"Apache-2.0"
] | null | null | null | autobahn/autobahn/wamp/test/test_protocol.py | luhn/AutobahnPython | 7d519052ab42dc029598ab9e2dbdd7af8e08341f | [
"Apache-2.0"
] | null | null | null | ###############################################################################
##
## Copyright (C) 2014 Tavendo GmbH
##
## 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 __future__ import absolute_import
import os
if os.environ.get('USE_TWISTED', False):
from twisted.trial import unittest
#import unittest
from twisted.internet.defer import Deferred, inlineCallbacks
from autobahn import wamp
from autobahn.wamp import message
from autobahn.wamp import serializer
from autobahn.wamp import protocol
from autobahn.wamp import role
from autobahn import util
from autobahn.wamp.exception import ApplicationError, NotAuthorized, InvalidUri
from autobahn.wamp import types
from autobahn.twisted.wamp import ApplicationSession
class MockTransport:
def __init__(self, handler):
self._log = False
self._handler = handler
self._serializer = serializer.JsonSerializer()
self._registrations = {}
self._invocations = {}
self._handler.onOpen(self)
self._my_session_id = util.id()
roles = [
role.RoleBrokerFeatures(),
role.RoleDealerFeatures()
]
msg = message.Welcome(self._my_session_id, roles)
self._handler.onMessage(msg)
def send(self, msg):
if self._log:
bytes, isbinary = self._serializer.serialize(msg)
print("Send: {}".format(bytes))
reply = None
if isinstance(msg, message.Publish):
if msg.topic.startswith(u'com.myapp'):
if msg.acknowledge:
reply = message.Published(msg.request, util.id())
elif len(msg.topic) == 0:
reply = message.Error(message.Publish.MESSAGE_TYPE, msg.request, u'wamp.error.invalid_uri')
else:
reply = message.Error(message.Publish.MESSAGE_TYPE, msg.request, u'wamp.error.not_authorized')
elif isinstance(msg, message.Call):
if msg.procedure == u'com.myapp.procedure1':
reply = message.Result(msg.request, args = [100])
elif msg.procedure == u'com.myapp.procedure2':
reply = message.Result(msg.request, args = [1, 2, 3])
elif msg.procedure == u'com.myapp.procedure3':
reply = message.Result(msg.request, args = [1, 2, 3], kwargs = {u'foo': u'bar', u'baz': 23})
elif msg.procedure.startswith(u'com.myapp.myproc'):
registration = self._registrations[msg.procedure]
request = util.id()
self._invocations[request] = msg.request
reply = message.Invocation(request, registration, args = msg.args, kwargs = msg.kwargs)
else:
reply = message.Error(message.Call.MESSAGE_TYPE, msg.request, u'wamp.error.no_such_procedure')
elif isinstance(msg, message.Yield):
if self._invocations.has_key(msg.request):
request = self._invocations[msg.request]
reply = message.Result(request, args = msg.args, kwargs = msg.kwargs)
elif isinstance(msg, message.Subscribe):
reply = message.Subscribed(msg.request, util.id())
elif isinstance(msg, message.Unsubscribe):
reply = message.Unsubscribed(msg.request)
elif isinstance(msg, message.Register):
registration = util.id()
self._registrations[msg.procedure] = registration
reply = message.Registered(msg.request, registration)
elif isinstance(msg, message.Unregister):
reply = message.Unregistered(msg.request)
if reply:
if self._log:
bytes, isbinary = self._serializer.serialize(reply)
print("Receive: {}".format(bytes))
self._handler.onMessage(reply)
def isOpen(self):
return True
def close(self):
pass
def abort(self):
pass
class TestPublisher(unittest.TestCase):
@inlineCallbacks
def test_publish(self):
handler = ApplicationSession()
MockTransport(handler)
publication = yield handler.publish(u'com.myapp.topic1')
self.assertEqual(publication, None)
publication = yield handler.publish(u'com.myapp.topic1', 1, 2, 3)
self.assertEqual(publication, None)
publication = yield handler.publish(u'com.myapp.topic1', 1, 2, 3, foo = 23, bar = 'hello')
self.assertEqual(publication, None)
publication = yield handler.publish(u'com.myapp.topic1', options = types.PublishOptions(excludeMe = False))
self.assertEqual(publication, None)
publication = yield handler.publish(u'com.myapp.topic1', 1, 2, 3, foo = 23, bar = 'hello', options = types.PublishOptions(excludeMe = False, exclude = [100, 200, 300]))
self.assertEqual(publication, None)
@inlineCallbacks
def test_publish_acknowledged(self):
handler = ApplicationSession()
MockTransport(handler)
publication = yield handler.publish(u'com.myapp.topic1', options = types.PublishOptions(acknowledge = True))
self.assertTrue(type(publication.id) in (int, long))
publication = yield handler.publish(u'com.myapp.topic1', 1, 2, 3, options = types.PublishOptions(acknowledge = True))
self.assertTrue(type(publication.id) in (int, long))
publication = yield handler.publish(u'com.myapp.topic1', 1, 2, 3, foo = 23, bar = 'hello', options = types.PublishOptions(acknowledge = True))
self.assertTrue(type(publication.id) in (int, long))
publication = yield handler.publish(u'com.myapp.topic1', options = types.PublishOptions(excludeMe = False, acknowledge = True))
self.assertTrue(type(publication.id) in (int, long))
publication = yield handler.publish(u'com.myapp.topic1', 1, 2, 3, foo = 23, bar = 'hello', options = types.PublishOptions(excludeMe = False, exclude = [100, 200, 300], acknowledge = True))
self.assertTrue(type(publication.id) in (int, long))
@inlineCallbacks
def test_publish_undefined_exception(self):
handler = ApplicationSession()
MockTransport(handler)
options = types.PublishOptions(acknowledge = True)
yield self.assertFailure(handler.publish(u'de.myapp.topic1', options = options), ApplicationError)
yield self.assertFailure(handler.publish(u'', options = options), ApplicationError)
@inlineCallbacks
def test_publish_defined_exception(self):
handler = ApplicationSession()
MockTransport(handler)
options = types.PublishOptions(acknowledge = True)
handler.define(NotAuthorized)
yield self.assertFailure(handler.publish(u'de.myapp.topic1', options = options), NotAuthorized)
handler.define(InvalidUri)
yield self.assertFailure(handler.publish(u'', options = options), InvalidUri)
@inlineCallbacks
def test_call(self):
handler = ApplicationSession()
MockTransport(handler)
res = yield handler.call(u'com.myapp.procedure1')
self.assertEqual(res, 100)
res = yield handler.call(u'com.myapp.procedure1', 1, 2, 3)
self.assertEqual(res, 100)
res = yield handler.call(u'com.myapp.procedure1', 1, 2, 3, foo = 23, bar = 'hello')
self.assertEqual(res, 100)
res = yield handler.call(u'com.myapp.procedure1', options = types.CallOptions(timeout = 10000))
self.assertEqual(res, 100)
res = yield handler.call(u'com.myapp.procedure1', 1, 2, 3, foo = 23, bar = 'hello', options = types.CallOptions(timeout = 10000))
self.assertEqual(res, 100)
@inlineCallbacks
def test_call_with_complex_result(self):
handler = ApplicationSession()
MockTransport(handler)
res = yield handler.call(u'com.myapp.procedure2')
self.assertIsInstance(res, types.CallResult)
self.assertEqual(res.results, (1, 2, 3))
self.assertEqual(res.kwresults, {})
res = yield handler.call(u'com.myapp.procedure3')
self.assertIsInstance(res, types.CallResult)
self.assertEqual(res.results, (1, 2, 3))
self.assertEqual(res.kwresults, {'foo':'bar', 'baz': 23})
@inlineCallbacks
def test_subscribe(self):
handler = ApplicationSession()
MockTransport(handler)
def on_event(*args, **kwargs):
print("got event", args, kwargs)
subscription = yield handler.subscribe(on_event, u'com.myapp.topic1')
self.assertTrue(type(subscription.id) in (int, long))
subscription = yield handler.subscribe(on_event, u'com.myapp.topic1', options = types.SubscribeOptions(match = 'wildcard'))
self.assertTrue(type(subscription.id) in (int, long))
@inlineCallbacks
def test_unsubscribe(self):
handler = ApplicationSession()
MockTransport(handler)
def on_event(*args, **kwargs):
print("got event", args, kwargs)
subscription = yield handler.subscribe(on_event, u'com.myapp.topic1')
yield subscription.unsubscribe()
@inlineCallbacks
def test_register(self):
handler = ApplicationSession()
MockTransport(handler)
def on_call(*args, **kwargs):
print("got call", args, kwargs)
registration = yield handler.register(on_call, u'com.myapp.procedure1')
self.assertTrue(type(registration.id) in (int, long))
registration = yield handler.register(on_call, u'com.myapp.procedure1', options = types.RegisterOptions(pkeys = [0, 1, 2]))
self.assertTrue(type(registration.id) in (int, long))
@inlineCallbacks
def test_unregister(self):
handler = ApplicationSession()
MockTransport(handler)
def on_call(*args, **kwargs):
print("got call", args, kwargs)
registration = yield handler.register(on_call, u'com.myapp.procedure1')
yield registration.unregister()
@inlineCallbacks
def test_invoke(self):
handler = ApplicationSession()
MockTransport(handler)
def myproc1():
return 23
yield handler.register(myproc1, u'com.myapp.myproc1')
res = yield handler.call(u'com.myapp.myproc1')
self.assertEqual(res, 23)
# ## variant 1: works
# def test_publish1(self):
# d = self.handler.publish(u'de.myapp.topic1')
# self.assertFailure(d, ApplicationError)
# ## variant 2: works
# @inlineCallbacks
# def test_publish2(self):
# yield self.assertFailure(self.handler.publish(u'de.myapp.topic1'), ApplicationError)
# ## variant 3: does NOT work
# @inlineCallbacks
# def test_publish3(self):
# with self.assertRaises(ApplicationError):
# yield self.handler.publish(u'de.myapp.topic1')
if __name__ == '__main__':
unittest.main()
| 36.021605 | 197 | 0.630966 | yield self.assertFailure(handler.publish(u'', options = options), InvalidUri)
@inlineCallbacks
def test_call(self):
handler = ApplicationSession()
MockTransport(handler)
res = yield handler.call(u'com.myapp.procedure1')
self.assertEqual(res, 100)
res = yield handler.call(u'com.myapp.procedure1', 1, 2, 3)
self.assertEqual(res, 100)
res = yield handler.call(u'com.myapp.procedure1', 1, 2, 3, foo = 23, bar = 'hello')
self.assertEqual(res, 100)
res = yield handler.call(u'com.myapp.procedure1', options = types.CallOptions(timeout = 10000))
self.assertEqual(res, 100)
res = yield handler.call(u'com.myapp.procedure1', 1, 2, 3, foo = 23, bar = 'hello', options = types.CallOptions(timeout = 10000))
self.assertEqual(res, 100)
@inlineCallbacks
def test_call_with_complex_result(self):
handler = ApplicationSession()
MockTransport(handler)
res = yield handler.call(u'com.myapp.procedure2')
self.assertIsInstance(res, types.CallResult)
self.assertEqual(res.results, (1, 2, 3))
self.assertEqual(res.kwresults, {})
res = yield handler.call(u'com.myapp.procedure3')
self.assertIsInstance(res, types.CallResult)
self.assertEqual(res.results, (1, 2, 3))
self.assertEqual(res.kwresults, {'foo':'bar', 'baz': 23})
@inlineCallbacks
def test_subscribe(self):
handler = ApplicationSession()
MockTransport(handler)
def on_event(*args, **kwargs):
print("got event", args, kwargs)
subscription = yield handler.subscribe(on_event, u'com.myapp.topic1')
self.assertTrue(type(subscription.id) in (int, long))
subscription = yield handler.subscribe(on_event, u'com.myapp.topic1', options = types.SubscribeOptions(match = 'wildcard'))
self.assertTrue(type(subscription.id) in (int, long))
@inlineCallbacks
def test_unsubscribe(self):
handler = ApplicationSession()
MockTransport(handler)
def on_event(*args, **kwargs):
print("got event", args, kwargs)
subscription = yield handler.subscribe(on_event, u'com.myapp.topic1')
yield subscription.unsubscribe()
@inlineCallbacks
def test_register(self):
handler = ApplicationSession()
MockTransport(handler)
def on_call(*args, **kwargs):
print("got call", args, kwargs)
registration = yield handler.register(on_call, u'com.myapp.procedure1')
self.assertTrue(type(registration.id) in (int, long))
registration = yield handler.register(on_call, u'com.myapp.procedure1', options = types.RegisterOptions(pkeys = [0, 1, 2]))
self.assertTrue(type(registration.id) in (int, long))
@inlineCallbacks
def test_unregister(self):
handler = ApplicationSession()
MockTransport(handler)
def on_call(*args, **kwargs):
print("got call", args, kwargs)
registration = yield handler.register(on_call, u'com.myapp.procedure1')
yield registration.unregister()
@inlineCallbacks
def test_invoke(self):
handler = ApplicationSession()
MockTransport(handler)
def myproc1():
return 23
yield handler.register(myproc1, u'com.myapp.myproc1')
res = yield handler.call(u'com.myapp.myproc1')
self.assertEqual(res, 23)
.main()
| true | true |
1c2be827a79715beef77ec9b12b82a536c44c9a2 | 2,175 | py | Python | setup.py | sleepy-owl/hummingbird | d23d8f2eb6864f88461fe1e0044f2f981b7d5881 | [
"MIT"
] | 1 | 2021-02-25T19:55:49.000Z | 2021-02-25T19:55:49.000Z | setup.py | hsaputra/hummingbird | 0ebd6be58880615bc86eab3648056682b40de614 | [
"MIT"
] | null | null | null | setup.py | hsaputra/hummingbird | 0ebd6be58880615bc86eab3648056682b40de614 | [
"MIT"
] | null | null | null | from distutils.core import setup
from setuptools import find_packages
import os
import sys
this = os.path.dirname(__file__)
packages = find_packages()
assert packages
# read version from the package file.
with (open(os.path.join(this, "hummingbird/__init__.py"), "r")) as f:
line = [_ for _ in [_.strip("\r\n ") for _ in f.readlines()] if _.startswith("__version__")]
if len(line) > 0:
version_str = line[0].split("=")[1].strip('" ')
README = os.path.join(os.getcwd(), "README.md")
with open(README) as f:
long_description = f.read()
start_pos = long_description.find("## Introduction")
if start_pos >= 0:
long_description = long_description[start_pos:]
install_requires = [
"numpy>=1.15,<=1.19.4",
"onnxconverter-common>=1.6.0,<=1.7.0",
"scipy<=1.5.4",
"scikit-learn>=0.21.3,<=0.23.2",
"torch>=1.4.*,<=1.7.1",
"psutil",
"dill",
]
onnx_requires = [
"onnxruntime>=1.0.0",
"onnxmltools>=1.6.0",
]
extra_requires = [
# The need each for these depends on which libraries you plan to convert from
"xgboost>=0.90",
"lightgbm>=2.2,<3",
]
setup(
name="hummingbird-ml",
version=version_str,
description="Convert trained traditional machine learning models into tensor computations",
long_description=long_description,
long_description_content_type="text/markdown",
license="MIT License",
author="Microsoft Corporation",
author_email="hummingbird-dev@microsoft.com",
url="https://github.com/microsoft/hummingbird",
packages=packages,
include_package_data=True,
install_requires=install_requires,
extras_require={
"tests": ["flake8", "pytest", "coverage", "pre-commit"],
"sparkml": ["pyspark>=2.4.4"],
"onnx": onnx_requires,
"extra": extra_requires,
"benchmark": onnx_requires + extra_requires + ["memory-profiler", "psutil"],
},
classifiers=[
"Environment :: Console",
"Intended Audience :: Developers",
"Programming Language :: Python",
"Operating System :: OS Independent",
"License :: OSI Approved :: MIT License",
],
python_requires=">=3.6",
)
| 30.633803 | 96 | 0.645517 | from distutils.core import setup
from setuptools import find_packages
import os
import sys
this = os.path.dirname(__file__)
packages = find_packages()
assert packages
with (open(os.path.join(this, "hummingbird/__init__.py"), "r")) as f:
line = [_ for _ in [_.strip("\r\n ") for _ in f.readlines()] if _.startswith("__version__")]
if len(line) > 0:
version_str = line[0].split("=")[1].strip('" ')
README = os.path.join(os.getcwd(), "README.md")
with open(README) as f:
long_description = f.read()
start_pos = long_description.find("s >= 0:
long_description = long_description[start_pos:]
install_requires = [
"numpy>=1.15,<=1.19.4",
"onnxconverter-common>=1.6.0,<=1.7.0",
"scipy<=1.5.4",
"scikit-learn>=0.21.3,<=0.23.2",
"torch>=1.4.*,<=1.7.1",
"psutil",
"dill",
]
onnx_requires = [
"onnxruntime>=1.0.0",
"onnxmltools>=1.6.0",
]
extra_requires = [
# The need each for these depends on which libraries you plan to convert from
"xgboost>=0.90",
"lightgbm>=2.2,<3",
]
setup(
name="hummingbird-ml",
version=version_str,
description="Convert trained traditional machine learning models into tensor computations",
long_description=long_description,
long_description_content_type="text/markdown",
license="MIT License",
author="Microsoft Corporation",
author_email="hummingbird-dev@microsoft.com",
url="https://github.com/microsoft/hummingbird",
packages=packages,
include_package_data=True,
install_requires=install_requires,
extras_require={
"tests": ["flake8", "pytest", "coverage", "pre-commit"],
"sparkml": ["pyspark>=2.4.4"],
"onnx": onnx_requires,
"extra": extra_requires,
"benchmark": onnx_requires + extra_requires + ["memory-profiler", "psutil"],
},
classifiers=[
"Environment :: Console",
"Intended Audience :: Developers",
"Programming Language :: Python",
"Operating System :: OS Independent",
"License :: OSI Approved :: MIT License",
],
python_requires=">=3.6",
)
| true | true |
1c2bea7f40256e88ea7c3a0fe6b7339cd1b14381 | 8,781 | py | Python | WISDEM/wisdem/commonse/akima.py | ebranlard/WEIS | 59851a0c3b2e801bd413ca4887ab4b78e58f928a | [
"Apache-2.0"
] | null | null | null | WISDEM/wisdem/commonse/akima.py | ebranlard/WEIS | 59851a0c3b2e801bd413ca4887ab4b78e58f928a | [
"Apache-2.0"
] | null | null | null | WISDEM/wisdem/commonse/akima.py | ebranlard/WEIS | 59851a0c3b2e801bd413ca4887ab4b78e58f928a | [
"Apache-2.0"
] | null | null | null | """
Simple interpolant based on Andrew Ning's implementation of Akima splines.
Includes derivatives wrt training points. Akima spline is regenerated during each compute.
https://github.com/andrewning/akima
"""
import numpy as np
def abs_smooth_dv(x, x_deriv, delta_x):
"""
Compute the absolute value in a smooth differentiable manner.
The valley is rounded off using a quadratic function.
Parameters
----------
x : float
Quantity value
x_deriv : float
Derivative value
delta_x : float
Half width of the rounded section.
Returns
-------
float
Smooth absolute value of the quantity.
float
Smooth absolute value of the derivative.
"""
if x >= delta_x:
y_deriv = x_deriv
y = x
elif x <= -delta_x:
y_deriv = -x_deriv
y = -x
else:
y_deriv = 2.0 * x * x_deriv / (2.0 * delta_x)
y = x ** 2 / (2.0 * delta_x) + delta_x / 2.0
return y, y_deriv
def akima_interp_with_derivs(xpt, ypt, x, delta_x=0.1):
a = Akima(xpt, ypt, delta_x)
return a.interp(x)
class Akima(object):
def __init__(self, xpt, ypt, delta_x=0.1, eps=1e-30):
"""
Train the akima spline and save the derivatives.
Conversion of fortran function AKIMA_DV.
Parameters
----------
xpt : ndarray
Values at which the akima spline was trained.
ypt : ndarray
Training values for the akima spline.
"""
xpt = np.array(xpt)
ncp = np.size(xpt)
nbdirs = 2 * ncp
ypt = np.array(ypt)
self.flatFlag = ypt.ndim == 1
if self.flatFlag:
assert xpt.size == ypt.size
ypt = ypt.reshape((1, ypt.size))
if ypt.shape[0] == ncp:
ypt = ypt.T
vec_size = ypt.shape[0]
# Poly points and derivs
p1 = np.empty((vec_size, ncp - 1), dtype=ypt.dtype)
p2 = np.empty((vec_size, ncp - 1), dtype=ypt.dtype)
p3 = np.empty((vec_size, ncp - 1), dtype=ypt.dtype)
p0d = np.empty((vec_size, nbdirs, ncp - 1), dtype=ypt.dtype)
p1d = np.empty((vec_size, nbdirs, ncp - 1), dtype=ypt.dtype)
p2d = np.empty((vec_size, nbdirs, ncp - 1), dtype=ypt.dtype)
p3d = np.empty((vec_size, nbdirs, ncp - 1), dtype=ypt.dtype)
md = np.zeros((nbdirs, ncp + 3), dtype=ypt.dtype)
m = np.zeros((ncp + 3,), dtype=ypt.dtype)
td = np.zeros((nbdirs, ncp), dtype=ypt.dtype)
t = np.zeros((ncp,), dtype=ypt.dtype)
xptd = np.vstack([np.eye(ncp, dtype=ypt.dtype), np.zeros((ncp, ncp), dtype=ypt.dtype)])
yptd = np.vstack([np.zeros((ncp, ncp), dtype=ypt.dtype), np.eye(ncp, dtype=ypt.dtype)])
dx = xpt[1:] - xpt[:-1]
dx2 = dx ** 2
dxd = xptd[:, 1:] - xptd[:, :-1]
p0 = ypt[:, :-1]
for jj in range(vec_size):
ypt_jj = ypt[jj, :]
# Compute segment slopes
temp = (yptd[:, 1:] - yptd[:, :-1]) * (xpt[1:] - xpt[:-1]) - (ypt_jj[1:] - ypt_jj[:-1]) * (
xptd[:, 1:] - xptd[:, :-1]
)
md[:, 2 : ncp + 1] = np.divide(
temp, (xpt[1:] - xpt[:-1]) ** 2, out=np.zeros_like(temp), where=(xpt[1:] - xpt[:-1]) != 0.0
)
# m[2:ncp + 1] = (ypt_jj[1:] - ypt_jj[:-1]) / (xpt[1:] - xpt[:-1])
m[2 : ncp + 1] = np.divide(
ypt_jj[1:] - ypt_jj[:-1],
xpt[1:] - xpt[:-1],
out=np.zeros_like(ypt_jj[1:]),
where=(xpt[1:] - xpt[:-1]) != 0.0,
)
# Estimation for end points.
md[:, 1] = 2.0 * md[:, 2] - md[:, 3]
md[:, 0] = 2.0 * md[:, 1] - md[:, 2]
md[:, ncp + 1] = 2.0 * md[:, ncp] - md[:, ncp - 1]
md[:, ncp + 2] = 2.0 * md[:, ncp + 1] - md[:, ncp]
m[1] = 2.0 * m[2] - m[3]
m[0] = 2.0 * m[1] - m[2]
m[ncp + 1] = 2.0 * m[ncp] - m[ncp - 1]
m[ncp + 2] = 2.0 * m[ncp + 1] - m[ncp]
# Slope at points.
for i in range(2, ncp + 1):
m1d = md[:, i - 2]
m2d = md[:, i - 1]
m3d = md[:, i]
m4d = md[:, i + 1]
arg1d = m4d - m3d
m1 = m[i - 2]
m2 = m[i - 1]
m3 = m[i]
m4 = m[i + 1]
arg1 = m4 - m3
w1, w1d = abs_smooth_dv(arg1, arg1d, delta_x)
arg1d = m2d - m1d
arg1 = m2 - m1
w2, w2d = abs_smooth_dv(arg1, arg1d, delta_x)
if w1 < eps and w2 < eps:
# Special case to avoid divide by zero.
td[:, i - 2] = 0.5 * (m2d + m3d)
t[i - 2] = 0.5 * (m2 + m3)
else:
td[:, i - 2] = (
(w1d * m2 + w1 * m2d + w2d * m3 + w2 * m3d) * (w1 + w2) - (w1 * m2 + w2 * m3) * (w1d + w2d)
) / (w1 + w2) ** 2
t[i - 2] = (w1 * m2 + w2 * m3) / (w1 + w2)
# Polynomial Coefficients
t1 = t[:-1]
t2 = t[1:]
p1[jj, :] = t1
p2[jj, :] = np.divide(
(3.0 * m[2 : ncp + 1] - 2.0 * t1 - t2), dx, out=np.zeros_like(p2[jj, :]), where=dx != 0.0
) # (3.0 * m[2:ncp + 1] - 2.0 * t1 - t2) / dx
p3[jj, :] = np.divide(
(t1 + t2 - 2.0 * m[2 : ncp + 1]), dx2, out=np.zeros_like(p3[jj, :]), where=dx2 != 0.0
) # (t1 + t2 - 2.0 * m[2:ncp + 1]) / dx2
p0d[jj, ...] = yptd[:, :-1]
p1d[jj, ...] = td[:, :-1]
temp = (3.0 * md[:, 2 : ncp + 1] - 2.0 * td[:, :-1] - td[:, 1:]) * dx - (
3.0 * m[2 : ncp + 1] - 2.0 * t1 - t2
) * dxd
p2d[jj, ...] = np.divide(temp, dx2, out=np.zeros_like(p2d[jj, ...]), where=dx2 != 0.0)
temp = (td[:, :-1] + td[:, 1:] - 2.0 * md[:, 2 : ncp + 1]) * dx2 - (
t1 + t2 - 2.0 * m[2 : ncp + 1]
) * 2 * dx * dxd
p3d[jj, ...] = np.divide(temp, dx2 ** 2, out=np.zeros_like(p3d[jj, ...]), where=dx2 != 0.0)
self.xpt = xpt
self.p0 = p0
self.p1 = p1
self.p2 = p2
self.p3 = p3
self.dp0_dxcp = p0d[:, :ncp, :].transpose((0, 2, 1))
self.dp0_dycp = p0d[:, ncp:, :].transpose((0, 2, 1))
self.dp1_dxcp = p1d[:, :ncp, :].transpose((0, 2, 1))
self.dp1_dycp = p1d[:, ncp:, :].transpose((0, 2, 1))
self.dp2_dxcp = p2d[:, :ncp, :].transpose((0, 2, 1))
self.dp2_dycp = p2d[:, ncp:, :].transpose((0, 2, 1))
self.dp3_dxcp = p3d[:, :ncp, :].transpose((0, 2, 1))
self.dp3_dycp = p3d[:, ncp:, :].transpose((0, 2, 1))
def __call__(self, x):
return self.interp(x)
def interp(self, x):
xcp = self.xpt
ncp = np.size(xcp)
n = np.size(x)
vec_size = self.p0.shape[0]
p0 = self.p0
p1 = self.p1
p2 = self.p2
p3 = self.p3
# All vectorized points uses same grid, so find these once.
j_idx = np.zeros(n, dtype=np.int)
for i in range(n):
# Find location in array (use end segments if out of bounds)
if x[i] < xcp[0]:
j = 0
else:
# Linear search for now
for j in range(ncp - 2, -1, -1):
if x[i] >= xcp[j]:
break
j_idx[i] = j
dx = x - xcp[j_idx]
dx2 = dx * dx
dx3 = dx2 * dx
# Evaluate polynomial (and derivative)
y = p0[:, j_idx] + p1[:, j_idx] * dx + p2[:, j_idx] * dx2 + p3[:, j_idx] * dx3
dydx = p1[:, j_idx] + 2.0 * p2[:, j_idx] * dx + 3.0 * p3[:, j_idx] * dx2
dydxcp = (
self.dp0_dxcp[:, j_idx, :]
+ np.einsum("kij,i->kij", self.dp1_dxcp[:, j_idx, :], dx)
+ np.einsum("kij,i->kij", self.dp2_dxcp[:, j_idx, :], dx2)
+ np.einsum("kij,i->kij", self.dp3_dxcp[:, j_idx, :], dx3)
)
for jj in range(vec_size):
for i in range(n):
j = j_idx[i]
dydxcp[jj, i, j] -= dydx[jj, i]
dydycp = (
self.dp0_dycp[:, j_idx, :]
+ np.einsum("kij,i->kij", self.dp1_dycp[:, j_idx, :], dx)
+ np.einsum("kij,i->kij", self.dp2_dycp[:, j_idx, :], dx2)
+ np.einsum("kij,i->kij", self.dp3_dycp[:, j_idx, :], dx3)
)
if self.flatFlag:
y = np.squeeze(y)
dydx = np.squeeze(dydx)
dydxcp = np.squeeze(dydxcp)
dydycp = np.squeeze(dydycp)
return (y, dydx, dydxcp, dydycp)
| 33.135849 | 115 | 0.439016 | import numpy as np
def abs_smooth_dv(x, x_deriv, delta_x):
if x >= delta_x:
y_deriv = x_deriv
y = x
elif x <= -delta_x:
y_deriv = -x_deriv
y = -x
else:
y_deriv = 2.0 * x * x_deriv / (2.0 * delta_x)
y = x ** 2 / (2.0 * delta_x) + delta_x / 2.0
return y, y_deriv
def akima_interp_with_derivs(xpt, ypt, x, delta_x=0.1):
a = Akima(xpt, ypt, delta_x)
return a.interp(x)
class Akima(object):
def __init__(self, xpt, ypt, delta_x=0.1, eps=1e-30):
xpt = np.array(xpt)
ncp = np.size(xpt)
nbdirs = 2 * ncp
ypt = np.array(ypt)
self.flatFlag = ypt.ndim == 1
if self.flatFlag:
assert xpt.size == ypt.size
ypt = ypt.reshape((1, ypt.size))
if ypt.shape[0] == ncp:
ypt = ypt.T
vec_size = ypt.shape[0]
p1 = np.empty((vec_size, ncp - 1), dtype=ypt.dtype)
p2 = np.empty((vec_size, ncp - 1), dtype=ypt.dtype)
p3 = np.empty((vec_size, ncp - 1), dtype=ypt.dtype)
p0d = np.empty((vec_size, nbdirs, ncp - 1), dtype=ypt.dtype)
p1d = np.empty((vec_size, nbdirs, ncp - 1), dtype=ypt.dtype)
p2d = np.empty((vec_size, nbdirs, ncp - 1), dtype=ypt.dtype)
p3d = np.empty((vec_size, nbdirs, ncp - 1), dtype=ypt.dtype)
md = np.zeros((nbdirs, ncp + 3), dtype=ypt.dtype)
m = np.zeros((ncp + 3,), dtype=ypt.dtype)
td = np.zeros((nbdirs, ncp), dtype=ypt.dtype)
t = np.zeros((ncp,), dtype=ypt.dtype)
xptd = np.vstack([np.eye(ncp, dtype=ypt.dtype), np.zeros((ncp, ncp), dtype=ypt.dtype)])
yptd = np.vstack([np.zeros((ncp, ncp), dtype=ypt.dtype), np.eye(ncp, dtype=ypt.dtype)])
dx = xpt[1:] - xpt[:-1]
dx2 = dx ** 2
dxd = xptd[:, 1:] - xptd[:, :-1]
p0 = ypt[:, :-1]
for jj in range(vec_size):
ypt_jj = ypt[jj, :]
temp = (yptd[:, 1:] - yptd[:, :-1]) * (xpt[1:] - xpt[:-1]) - (ypt_jj[1:] - ypt_jj[:-1]) * (
xptd[:, 1:] - xptd[:, :-1]
)
md[:, 2 : ncp + 1] = np.divide(
temp, (xpt[1:] - xpt[:-1]) ** 2, out=np.zeros_like(temp), where=(xpt[1:] - xpt[:-1]) != 0.0
)
m[2 : ncp + 1] = np.divide(
ypt_jj[1:] - ypt_jj[:-1],
xpt[1:] - xpt[:-1],
out=np.zeros_like(ypt_jj[1:]),
where=(xpt[1:] - xpt[:-1]) != 0.0,
)
md[:, 1] = 2.0 * md[:, 2] - md[:, 3]
md[:, 0] = 2.0 * md[:, 1] - md[:, 2]
md[:, ncp + 1] = 2.0 * md[:, ncp] - md[:, ncp - 1]
md[:, ncp + 2] = 2.0 * md[:, ncp + 1] - md[:, ncp]
m[1] = 2.0 * m[2] - m[3]
m[0] = 2.0 * m[1] - m[2]
m[ncp + 1] = 2.0 * m[ncp] - m[ncp - 1]
m[ncp + 2] = 2.0 * m[ncp + 1] - m[ncp]
for i in range(2, ncp + 1):
m1d = md[:, i - 2]
m2d = md[:, i - 1]
m3d = md[:, i]
m4d = md[:, i + 1]
arg1d = m4d - m3d
m1 = m[i - 2]
m2 = m[i - 1]
m3 = m[i]
m4 = m[i + 1]
arg1 = m4 - m3
w1, w1d = abs_smooth_dv(arg1, arg1d, delta_x)
arg1d = m2d - m1d
arg1 = m2 - m1
w2, w2d = abs_smooth_dv(arg1, arg1d, delta_x)
if w1 < eps and w2 < eps:
td[:, i - 2] = 0.5 * (m2d + m3d)
t[i - 2] = 0.5 * (m2 + m3)
else:
td[:, i - 2] = (
(w1d * m2 + w1 * m2d + w2d * m3 + w2 * m3d) * (w1 + w2) - (w1 * m2 + w2 * m3) * (w1d + w2d)
) / (w1 + w2) ** 2
t[i - 2] = (w1 * m2 + w2 * m3) / (w1 + w2)
t1 = t[:-1]
t2 = t[1:]
p1[jj, :] = t1
p2[jj, :] = np.divide(
(3.0 * m[2 : ncp + 1] - 2.0 * t1 - t2), dx, out=np.zeros_like(p2[jj, :]), where=dx != 0.0
)
p3[jj, :] = np.divide(
(t1 + t2 - 2.0 * m[2 : ncp + 1]), dx2, out=np.zeros_like(p3[jj, :]), where=dx2 != 0.0
)
p0d[jj, ...] = yptd[:, :-1]
p1d[jj, ...] = td[:, :-1]
temp = (3.0 * md[:, 2 : ncp + 1] - 2.0 * td[:, :-1] - td[:, 1:]) * dx - (
3.0 * m[2 : ncp + 1] - 2.0 * t1 - t2
) * dxd
p2d[jj, ...] = np.divide(temp, dx2, out=np.zeros_like(p2d[jj, ...]), where=dx2 != 0.0)
temp = (td[:, :-1] + td[:, 1:] - 2.0 * md[:, 2 : ncp + 1]) * dx2 - (
t1 + t2 - 2.0 * m[2 : ncp + 1]
) * 2 * dx * dxd
p3d[jj, ...] = np.divide(temp, dx2 ** 2, out=np.zeros_like(p3d[jj, ...]), where=dx2 != 0.0)
self.xpt = xpt
self.p0 = p0
self.p1 = p1
self.p2 = p2
self.p3 = p3
self.dp0_dxcp = p0d[:, :ncp, :].transpose((0, 2, 1))
self.dp0_dycp = p0d[:, ncp:, :].transpose((0, 2, 1))
self.dp1_dxcp = p1d[:, :ncp, :].transpose((0, 2, 1))
self.dp1_dycp = p1d[:, ncp:, :].transpose((0, 2, 1))
self.dp2_dxcp = p2d[:, :ncp, :].transpose((0, 2, 1))
self.dp2_dycp = p2d[:, ncp:, :].transpose((0, 2, 1))
self.dp3_dxcp = p3d[:, :ncp, :].transpose((0, 2, 1))
self.dp3_dycp = p3d[:, ncp:, :].transpose((0, 2, 1))
def __call__(self, x):
return self.interp(x)
def interp(self, x):
xcp = self.xpt
ncp = np.size(xcp)
n = np.size(x)
vec_size = self.p0.shape[0]
p0 = self.p0
p1 = self.p1
p2 = self.p2
p3 = self.p3
j_idx = np.zeros(n, dtype=np.int)
for i in range(n):
if x[i] < xcp[0]:
j = 0
else:
for j in range(ncp - 2, -1, -1):
if x[i] >= xcp[j]:
break
j_idx[i] = j
dx = x - xcp[j_idx]
dx2 = dx * dx
dx3 = dx2 * dx
y = p0[:, j_idx] + p1[:, j_idx] * dx + p2[:, j_idx] * dx2 + p3[:, j_idx] * dx3
dydx = p1[:, j_idx] + 2.0 * p2[:, j_idx] * dx + 3.0 * p3[:, j_idx] * dx2
dydxcp = (
self.dp0_dxcp[:, j_idx, :]
+ np.einsum("kij,i->kij", self.dp1_dxcp[:, j_idx, :], dx)
+ np.einsum("kij,i->kij", self.dp2_dxcp[:, j_idx, :], dx2)
+ np.einsum("kij,i->kij", self.dp3_dxcp[:, j_idx, :], dx3)
)
for jj in range(vec_size):
for i in range(n):
j = j_idx[i]
dydxcp[jj, i, j] -= dydx[jj, i]
dydycp = (
self.dp0_dycp[:, j_idx, :]
+ np.einsum("kij,i->kij", self.dp1_dycp[:, j_idx, :], dx)
+ np.einsum("kij,i->kij", self.dp2_dycp[:, j_idx, :], dx2)
+ np.einsum("kij,i->kij", self.dp3_dycp[:, j_idx, :], dx3)
)
if self.flatFlag:
y = np.squeeze(y)
dydx = np.squeeze(dydx)
dydxcp = np.squeeze(dydxcp)
dydycp = np.squeeze(dydycp)
return (y, dydx, dydxcp, dydycp)
| true | true |
1c2beb0e3e9708ace96894a559d9ac33ce15a4c7 | 2,998 | py | Python | stemmer/find_potential_stems.py | Esukhia/text_utils | 562065d4dedba127f8aaeee03ca3d9f071805f62 | [
"MIT"
] | 1 | 2017-01-26T22:37:57.000Z | 2017-01-26T22:37:57.000Z | stemmer/find_potential_stems.py | Esukhia/tibtext_utils | 562065d4dedba127f8aaeee03ca3d9f071805f62 | [
"MIT"
] | null | null | null | stemmer/find_potential_stems.py | Esukhia/tibtext_utils | 562065d4dedba127f8aaeee03ca3d9f071805f62 | [
"MIT"
] | null | null | null | from collections import defaultdict
from PyTib.common import open_file, write_csv, tib_sort
def format_families(families):
lemmas_sorted = tib_sort(list(families.keys()))
formatted = []
for lemma in lemmas_sorted:
members = families[lemma]
formatted.append('{}: {}'.format(lemma, ' '.join(members)))
return '\n'.join(tib_sort(formatted))
def find_potentials(shorter_words, longer_words):
prefix_family = defaultdict(list)
infix_family = defaultdict(list)
postfix_family = defaultdict(list)
for short in shorter_words:
for long in longer_words:
if long.startswith(short+'་'):
prefix_family[short].append(long)
if '་{}་'.format(short) in long:
infix_family[short].append(long)
if long.endswith('་'+short):
postfix_family[short].append(long)
return {'prefixes': prefix_family, 'infixes': infix_family, 'postfixes': postfix_family}
def count_syl_amount(string):
return string.count('་')+1
def find_all_potentials(words):
total_potentials = {}
# generate lists of different sizes and process them
maximum_word_length = sorted(list(set([count_syl_amount(a) for a in words])), reverse=True)[0]
for i in range(maximum_word_length-1): # -1 because we want to ensure there are always longer words
current_size = i+1
shorter_list = [word for word in words if count_syl_amount(word) == current_size]
longer_list = [word for word in words if count_syl_amount(word) > current_size]
potentials = find_potentials(shorter_list, longer_list)
for kind, groups in potentials.items():
for stem, members in groups.items():
# initialize structure
if stem not in total_potentials.keys():
total_potentials[stem] = {}
if kind not in total_potentials[stem].keys():
total_potentials[stem][kind] = []
total_potentials[stem][kind].append(members)
return total_potentials
def format_potentials(potentials):
rows = []
lemmas_sorted = tib_sort(list(potentials.keys()))
for lemma in lemmas_sorted:
lemma_field = lemma
family = potentials[lemma]
comments = {'prefixes': 'as a prefix', 'infixes': 'as an infix', 'postfixes': 'as a postfix'}
for kind in ['prefixes', 'infixes', 'postfixes']:
if kind in family.keys():
current_row = [lemma_field, comments[kind]]
for members in family[kind]:
current_row.extend(members)
rows.append(current_row)
rows.append([])
return rows
def main():
word_list = open_file('resources/uncompound_lexicon.txt').strip().split('\n')
all_potentials = find_all_potentials(word_list)
formatted = format_potentials(all_potentials)
write_csv('output/affixes.csv', formatted)
if __name__ == '__main__':
main()
| 37.475 | 104 | 0.641761 | from collections import defaultdict
from PyTib.common import open_file, write_csv, tib_sort
def format_families(families):
lemmas_sorted = tib_sort(list(families.keys()))
formatted = []
for lemma in lemmas_sorted:
members = families[lemma]
formatted.append('{}: {}'.format(lemma, ' '.join(members)))
return '\n'.join(tib_sort(formatted))
def find_potentials(shorter_words, longer_words):
prefix_family = defaultdict(list)
infix_family = defaultdict(list)
postfix_family = defaultdict(list)
for short in shorter_words:
for long in longer_words:
if long.startswith(short+'་'):
prefix_family[short].append(long)
if '་{}་'.format(short) in long:
infix_family[short].append(long)
if long.endswith('་'+short):
postfix_family[short].append(long)
return {'prefixes': prefix_family, 'infixes': infix_family, 'postfixes': postfix_family}
def count_syl_amount(string):
return string.count('་')+1
def find_all_potentials(words):
total_potentials = {}
maximum_word_length = sorted(list(set([count_syl_amount(a) for a in words])), reverse=True)[0]
for i in range(maximum_word_length-1):
current_size = i+1
shorter_list = [word for word in words if count_syl_amount(word) == current_size]
longer_list = [word for word in words if count_syl_amount(word) > current_size]
potentials = find_potentials(shorter_list, longer_list)
for kind, groups in potentials.items():
for stem, members in groups.items():
if stem not in total_potentials.keys():
total_potentials[stem] = {}
if kind not in total_potentials[stem].keys():
total_potentials[stem][kind] = []
total_potentials[stem][kind].append(members)
return total_potentials
def format_potentials(potentials):
rows = []
lemmas_sorted = tib_sort(list(potentials.keys()))
for lemma in lemmas_sorted:
lemma_field = lemma
family = potentials[lemma]
comments = {'prefixes': 'as a prefix', 'infixes': 'as an infix', 'postfixes': 'as a postfix'}
for kind in ['prefixes', 'infixes', 'postfixes']:
if kind in family.keys():
current_row = [lemma_field, comments[kind]]
for members in family[kind]:
current_row.extend(members)
rows.append(current_row)
rows.append([])
return rows
def main():
word_list = open_file('resources/uncompound_lexicon.txt').strip().split('\n')
all_potentials = find_all_potentials(word_list)
formatted = format_potentials(all_potentials)
write_csv('output/affixes.csv', formatted)
if __name__ == '__main__':
main()
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.