content stringlengths 27 928k | path stringlengths 4 230 | size int64 27 928k | nl_text stringlengths 21 396k | nl_size int64 21 396k | nl_language stringlengths 2 3 | nl_language_score float64 0.04 1 |
|---|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
"""
Copyright (c) 2012 University of Oxford
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.
"""
from rdfdatabank.lib.auth_entry import list_silos, list_usernames, list_group_usernames, add_silo, add_group_users
def sync_members(g):
# NOTE: g._register_silos() IS AN EXPENSIVE OPERATION.
# THIS FUNCTION IS EXPENSIVE AND SHOULD BE CALLED ONLY IF REALLY NECESSARY
#g = ag.granary
g.state.revert()
g._register_silos()
granary_list = g.silos
granary_list_database = list_silos()
usernames = list_usernames()
for silo in granary_list:
if not silo in granary_list_database:
add_silo(silo)
kw = g.describe_silo(silo)
#Get existing owners, admins, managers and submitters from silo metadata
owners = []
admins = []
managers = []
submitters = []
if 'administrators' in kw and kw['administrators']:
admins = [x.strip() for x in kw['administrators'].split(",") if x]
if 'managers' in kw and kw['managers']:
managers = [x.strip() for x in kw['managers'].split(",") if x]
if 'submitters' in kw and kw['submitters']:
submitters = [x.strip() for x in kw['submitters'].split(",") if x]
# Check users in silo metadata are valid users
owners = [x for x in owners if x in usernames]
admins = [x for x in admins if x in usernames]
managers = [x for x in managers if x in usernames]
submitters = [x for x in submitters if x in usernames]
#Synchronize members in silo metadata with users in database
d_admins = []
d_managers = []
d_sunbmitters = []
if silo in granary_list_database:
d_admins, d_managers, d_submitters = list_group_usernames(silo)
admins.extend(d_admins)
managers.extend(d_managers)
submitters.extend(d_submitters)
# Ensure users are listed just once in silo metadata and owner is superset
owners.extend(admins)
owners.extend(managers)
owners.extend(submitters)
admins = list(set(admins))
managers = list(set(managers))
submitters = list(set(submitters))
owners = list(set(owners))
# Add users in silo metadata to the database
new_silo_users = []
for a in admins:
if not a in d_admins:
new_silo_users.append((a, 'administrator'))
for a in managers:
if not a in d_managers:
new_silo_users.append((a, 'manager'))
for a in new_submitters:
if not a in d_submitters:
new_silo_users.append((a, 'submitter'))
if new_silo_users:
add_group_users(silo, new_silo_users)
#Write members into silo
kw['owners'] = ','.join(owners)
kw['administrators'] = ','.join(admins)
kw['managers'] = ','.join(managers)
kw['submitters'] = ','.join(submitters)
g.describe_silo(silo, **kw)
g.sync()
return
| rdfdatabank/lib/data_sync.py | 4,060 | Copyright (c) 2012 University of Oxford
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.
-*- coding: utf-8 -*- NOTE: g._register_silos() IS AN EXPENSIVE OPERATION. THIS FUNCTION IS EXPENSIVE AND SHOULD BE CALLED ONLY IF REALLY NECESSARYg = ag.granaryGet existing owners, admins, managers and submitters from silo metadata Check users in silo metadata are valid usersSynchronize members in silo metadata with users in database Ensure users are listed just once in silo metadata and owner is superset Add users in silo metadata to the databaseWrite members into silo | 1,544 | en | 0.866357 |
import mysql.connector
import json
import os
import requests
def getAllFindings(host, database, user, password, table, where):
db = mysql.connector.connect(host=host, database=database, user=user, password=password)
cursor = db.cursor()
cursor.execute("SELECT distinct findingCode, specimenOrganCode FROM " + table + " " + where)
return cursor.fetchall()
def getDrugs(api, filename):
if filename is None:
drugs = getDrugsMapping(api)
else:
if os.path.isfile(filename):
with open(filename, 'r') as drug_file:
drugs = json.loads(drug_file.read())
else:
drugs = getDrugsMapping(api)
with open(filename, 'w') as drug_file:
drug_file.write(json.dumps(drugs))
return drugs
def getDrugsMapping(api):
result = {}
clinicalCompounds = getClinicalCompounds(api)
preclinicalCompounds = getPreclinicalCompounds(api)
# iterate over the clinical and preclinical compounds and match them om inchiKey
for clinicalCompound in clinicalCompounds:
for preclinicalCompound in preclinicalCompounds:
if (clinicalCompound['inchiKey'] is not None) and (clinicalCompound['inchiKey'] == preclinicalCompound['inchiKey']):
inchiKey = clinicalCompound['inchiKey']
if inchiKey not in result:
result[inchiKey] = {
'inchiKey': inchiKey,
'clinicalName': clinicalCompound['name'],
'preclinicalName': preclinicalCompound['name']
}
result[inchiKey][preclinicalCompound['source']] = preclinicalCompound['findingIds']
result[inchiKey][clinicalCompound['source']] = clinicalCompound['findingIds']
return result
def getClinicalCompounds(api):
ct_compounds = api.ClinicalTrials().getAllCompounds();
for ct_compound in ct_compounds:
ct_compound['source'] = 'ClinicalTrials'
ml_compounds = api.Medline().getAllCompounds();
for ml_compound in ml_compounds:
ml_compound['source'] = 'Medline'
fa_compounds = api.Faers().getAllCompounds();
for fa_compound in fa_compounds:
fa_compound['source'] = 'Faers'
dm_compounds = api.DailyMed().getAllCompounds();
for dm_compound in dm_compounds:
dm_compound['source'] = 'DailyMed'
return ct_compounds + ml_compounds + fa_compounds + dm_compounds
def getPreclinicalCompounds(api):
et_compounds = api.eToxSys().getAllCompounds()
for et_compound in et_compounds:
et_compound['source'] = 'eToxSys'
return et_compounds
def getFindingsByIds(api, service, findingIds):
result = []
record_count = 0
query = {
"filter": {
"criteria": [
[
{
"field": {
"dataClassKey": "FINDING",
"name": "id"
},
"primitiveType": "Integer",
"comparisonOperator": "IN",
"values": None
},
]
]
},
"selectedFields": [
{
"dataClassKey": "FINDING",
"names": [
"id",
"specimenOrgan", "specimenOrganCode", "specimenOrganVocabulary",
"findingIdentifier", "finding", "findingCode", "findingVocabulary", "findingType",
"severity", "observation", "frequency",
"dose", "doseUnit",
"timepoint", "timepointUnit",
"treatmentRelated",
"compoundId",
"studyId",
"createdDate", "modifiedDate", "sex"
]
}
],
"offset": 0,
"limit": 500
}
for offset in range(0, len(findingIds), 500):
query['filter']['criteria'][0][0]['values'] = [{'value': findingId} for findingId in findingIds[offset:offset+500]]
r = requests.post(service.endpoint + 'query', verify=False, headers={"Authorization": f"Bearer {api.get_token()}"}, json=query, timeout=None)
if r.status_code == 200:
response = json.loads(r.text)
for record in response['resultData']['data']:
record['FINDING']['source'] = response['origin']
result.append(record['FINDING'])
elif r.status_code == 401:
api.reconnect()
continue
return result
| Concordance/condordance_utils.py | 4,611 | iterate over the clinical and preclinical compounds and match them om inchiKey | 78 | en | 0.818684 |
"""
Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
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.
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.
"""
from cfnlint.rules.outputs.Name import Name # pylint: disable=E0401
from .. import BaseRuleTestCase
class TestName(BaseRuleTestCase):
"""Test template outputs Names"""
def setUp(self):
"""Setup"""
super(TestName, self).setUp()
self.collection.register(Name())
self.success_templates = [
'fixtures/templates/good/outputs/name.yaml'
]
def test_file_positive(self):
"""Test Positive"""
self.helper_file_positive()
def test_file_negative(self):
"""Test failure"""
self.helper_file_negative('fixtures/templates/bad/outputs/name.yaml', 1)
| test/rules/outputs/test_name.py | 1,601 | Test template outputs Names
Setup
Test failure
Test Positive
Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
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.
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.
pylint: disable=E0401 | 1,015 | en | 0.86346 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=line-too-long
from ._client_factory import iotcentral_service_factory
def load_command_table(self, _):
from azure.cli.core.commands import CliCommandType
iotcentral_sdk = CliCommandType(
operations_tmpl='azure.mgmt.iotcentral.operations#IoTCentaralOperations.{}'
)
update_custom_util = CliCommandType(
operations_tmpl='azure.cli.command_modules.iotcentral.custom#{}')
with self.command_group('iotcentral app', iotcentral_sdk, client_factory=iotcentral_service_factory) as g:
g.custom_command('create', 'iotcentral_app_create')
g.custom_command('list', 'iotcentral_app_list')
g.custom_command('show', 'iotcentral_app_get')
g.generic_update_command('update', getter_name='iotcentral_app_get',
setter_name='iotcentral_app_update', command_type=update_custom_util)
g.custom_command('delete', 'iotcentral_app_delete')
| src/azure-cli/azure/cli/command_modules/iotcentral/commands.py | 1,292 | -------------------------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. -------------------------------------------------------------------------------------------- pylint: disable=line-too-long | 366 | en | 0.409024 |
# Copyright 2015 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.
# ==============================================================================
"""RNN helpers for TensorFlow models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import rnn_cell_impl
from tensorflow.python.ops import tensor_array_ops
from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.util import nest
# pylint: disable=protected-access
_state_size_with_prefix = rnn_cell_impl._state_size_with_prefix
# pylint: enable=protected-access
def _infer_state_dtype(explicit_dtype, state):
"""Infer the dtype of an RNN state.
Args:
explicit_dtype: explicitly declared dtype or None.
state: RNN's hidden state. Must be a Tensor or a nested iterable containing
Tensors.
Returns:
dtype: inferred dtype of hidden state.
Raises:
ValueError: if `state` has heterogeneous dtypes or is empty.
"""
if explicit_dtype is not None:
return explicit_dtype
elif nest.is_sequence(state):
inferred_dtypes = [element.dtype for element in nest.flatten(state)]
if not inferred_dtypes:
raise ValueError("Unable to infer dtype from empty state.")
all_same = all([x == inferred_dtypes[0] for x in inferred_dtypes])
if not all_same:
raise ValueError(
"State has tensors of different inferred_dtypes. Unable to infer a "
"single representative dtype.")
return inferred_dtypes[0]
else:
return state.dtype
def _on_device(fn, device):
"""Build the subgraph defined by lambda `fn` on `device` if it's not None."""
if device:
with ops.device(device):
return fn()
else:
return fn()
# pylint: disable=unused-argument
def _rnn_step(
time, sequence_length, min_sequence_length, max_sequence_length,
zero_output, state, call_cell, state_size, skip_conditionals=False):
"""Calculate one step of a dynamic RNN minibatch.
Returns an (output, state) pair conditioned on the sequence_lengths.
When skip_conditionals=False, the pseudocode is something like:
if t >= max_sequence_length:
return (zero_output, state)
if t < min_sequence_length:
return call_cell()
# Selectively output zeros or output, old state or new state depending
# on if we've finished calculating each row.
new_output, new_state = call_cell()
final_output = np.vstack([
zero_output if time >= sequence_lengths[r] else new_output_r
for r, new_output_r in enumerate(new_output)
])
final_state = np.vstack([
state[r] if time >= sequence_lengths[r] else new_state_r
for r, new_state_r in enumerate(new_state)
])
return (final_output, final_state)
Args:
time: Python int, the current time step
sequence_length: int32 `Tensor` vector of size [batch_size]
min_sequence_length: int32 `Tensor` scalar, min of sequence_length
max_sequence_length: int32 `Tensor` scalar, max of sequence_length
zero_output: `Tensor` vector of shape [output_size]
state: Either a single `Tensor` matrix of shape `[batch_size, state_size]`,
or a list/tuple of such tensors.
call_cell: lambda returning tuple of (new_output, new_state) where
new_output is a `Tensor` matrix of shape `[batch_size, output_size]`.
new_state is a `Tensor` matrix of shape `[batch_size, state_size]`.
state_size: The `cell.state_size` associated with the state.
skip_conditionals: Python bool, whether to skip using the conditional
calculations. This is useful for `dynamic_rnn`, where the input tensor
matches `max_sequence_length`, and using conditionals just slows
everything down.
Returns:
A tuple of (`final_output`, `final_state`) as given by the pseudocode above:
final_output is a `Tensor` matrix of shape [batch_size, output_size]
final_state is either a single `Tensor` matrix, or a tuple of such
matrices (matching length and shapes of input `state`).
Raises:
ValueError: If the cell returns a state tuple whose length does not match
that returned by `state_size`.
"""
# Convert state to a list for ease of use
flat_state = nest.flatten(state)
flat_zero_output = nest.flatten(zero_output)
def _copy_one_through(output, new_output):
copy_cond = (time >= sequence_length)
return _on_device(
lambda: array_ops.where(copy_cond, output, new_output),
device=new_output.op.device)
def _copy_some_through(flat_new_output, flat_new_state):
# Use broadcasting select to determine which values should get
# the previous state & zero output, and which values should get
# a calculated state & output.
flat_new_output = [
_copy_one_through(zero_output, new_output)
for zero_output, new_output in zip(flat_zero_output, flat_new_output)]
flat_new_state = [
_copy_one_through(state, new_state)
for state, new_state in zip(flat_state, flat_new_state)]
return flat_new_output + flat_new_state
def _maybe_copy_some_through():
"""Run RNN step. Pass through either no or some past state."""
new_output, new_state = call_cell()
nest.assert_same_structure(state, new_state)
flat_new_state = nest.flatten(new_state)
flat_new_output = nest.flatten(new_output)
return control_flow_ops.cond(
# if t < min_seq_len: calculate and return everything
time < min_sequence_length, lambda: flat_new_output + flat_new_state,
# else copy some of it through
lambda: _copy_some_through(flat_new_output, flat_new_state))
# TODO(ebrevdo): skipping these conditionals may cause a slowdown,
# but benefits from removing cond() and its gradient. We should
# profile with and without this switch here.
if skip_conditionals:
# Instead of using conditionals, perform the selective copy at all time
# steps. This is faster when max_seq_len is equal to the number of unrolls
# (which is typical for dynamic_rnn).
new_output, new_state = call_cell()
nest.assert_same_structure(state, new_state)
new_state = nest.flatten(new_state)
new_output = nest.flatten(new_output)
final_output_and_state = _copy_some_through(new_output, new_state)
else:
empty_update = lambda: flat_zero_output + flat_state
final_output_and_state = control_flow_ops.cond(
# if t >= max_seq_len: copy all state through, output zeros
time >= max_sequence_length, empty_update,
# otherwise calculation is required: copy some or all of it through
_maybe_copy_some_through)
if len(final_output_and_state) != len(flat_zero_output) + len(flat_state):
raise ValueError("Internal error: state and output were not concatenated "
"correctly.")
final_output = final_output_and_state[:len(flat_zero_output)]
final_state = final_output_and_state[len(flat_zero_output):]
for output, flat_output in zip(final_output, flat_zero_output):
output.set_shape(flat_output.get_shape())
for substate, flat_substate in zip(final_state, flat_state):
substate.set_shape(flat_substate.get_shape())
final_output = nest.pack_sequence_as(
structure=zero_output, flat_sequence=final_output)
final_state = nest.pack_sequence_as(
structure=state, flat_sequence=final_state)
return final_output, final_state
def _reverse_seq(input_seq, lengths):
"""Reverse a list of Tensors up to specified lengths.
Args:
input_seq: Sequence of seq_len tensors of dimension (batch_size, n_features)
or nested tuples of tensors.
lengths: A `Tensor` of dimension batch_size, containing lengths for each
sequence in the batch. If "None" is specified, simply reverses
the list.
Returns:
time-reversed sequence
"""
if lengths is None:
return list(reversed(input_seq))
flat_input_seq = tuple(nest.flatten(input_) for input_ in input_seq)
flat_results = [[] for _ in range(len(input_seq))]
for sequence in zip(*flat_input_seq):
input_shape = tensor_shape.unknown_shape(
ndims=sequence[0].get_shape().ndims)
for input_ in sequence:
input_shape.merge_with(input_.get_shape())
input_.set_shape(input_shape)
# Join into (time, batch_size, depth)
s_joined = array_ops.stack(sequence)
# TODO(schuster, ebrevdo): Remove cast when reverse_sequence takes int32
if lengths is not None:
lengths = math_ops.to_int64(lengths)
# Reverse along dimension 0
s_reversed = array_ops.reverse_sequence(s_joined, lengths, 0, 1)
# Split again into list
result = array_ops.unstack(s_reversed)
for r, flat_result in zip(result, flat_results):
r.set_shape(input_shape)
flat_result.append(r)
results = [nest.pack_sequence_as(structure=input_, flat_sequence=flat_result)
for input_, flat_result in zip(input_seq, flat_results)]
return results
def bidirectional_dynamic_rnn(cell_fw, cell_bw, inputs, sequence_length=None,
initial_state_fw=None, initial_state_bw=None,
dtype=None, parallel_iterations=None,
swap_memory=False, time_major=False, scope=None):
"""Creates a dynamic version of bidirectional recurrent neural network.
Similar to the unidirectional case above (rnn) but takes input and builds
independent forward and backward RNNs. The input_size of forward and
backward cell must match. The initial state for both directions is zero by
default (but can be set optionally) and no intermediate states are ever
returned -- the network is fully unrolled for the given (passed in)
length(s) of the sequence(s) or completely unrolled if length(s) is not
given.
Args:
cell_fw: An instance of RNNCell, to be used for forward direction.
cell_bw: An instance of RNNCell, to be used for backward direction.
inputs: The RNN inputs.
If time_major == False (default), this must be a tensor of shape:
`[batch_size, max_time, input_size]`.
If time_major == True, this must be a tensor of shape:
`[max_time, batch_size, input_size]`.
[batch_size, input_size].
sequence_length: An int32/int64 vector, size `[batch_size]`,
containing the actual lengths for each of the sequences.
initial_state_fw: (optional) An initial state for the forward RNN.
This must be a tensor of appropriate type and shape
`[batch_size, cell_fw.state_size]`.
If `cell_fw.state_size` is a tuple, this should be a tuple of
tensors having shapes `[batch_size, s] for s in cell_fw.state_size`.
initial_state_bw: (optional) Same as for `initial_state_fw`, but using
the corresponding properties of `cell_bw`.
dtype: (optional) The data type for the initial states and expected output.
Required if initial_states are not provided or RNN states have a
heterogeneous dtype.
parallel_iterations: (Default: 32). The number of iterations to run in
parallel. Those operations which do not have any temporal dependency
and can be run in parallel, will be. This parameter trades off
time for space. Values >> 1 use more memory but take less time,
while smaller values use less memory but computations take longer.
swap_memory: Transparently swap the tensors produced in forward inference
but needed for back prop from GPU to CPU. This allows training RNNs
which would typically not fit on a single GPU, with very minimal (or no)
performance penalty.
time_major: The shape format of the `inputs` and `outputs` Tensors.
If true, these `Tensors` must be shaped `[max_time, batch_size, depth]`.
If false, these `Tensors` must be shaped `[batch_size, max_time, depth]`.
Using `time_major = True` is a bit more efficient because it avoids
transposes at the beginning and end of the RNN calculation. However,
most TensorFlow data is batch-major, so by default this function
accepts input and emits output in batch-major form.
dtype: (optional) The data type for the initial state. Required if
either of the initial states are not provided.
scope: VariableScope for the created subgraph; defaults to
"bidirectional_rnn"
Returns:
A tuple (outputs, output_states) where:
outputs: A tuple (output_fw, output_bw) containing the forward and
the backward rnn output `Tensor`.
If time_major == False (default),
output_fw will be a `Tensor` shaped:
`[batch_size, max_time, cell_fw.output_size]`
and output_bw will be a `Tensor` shaped:
`[batch_size, max_time, cell_bw.output_size]`.
If time_major == True,
output_fw will be a `Tensor` shaped:
`[max_time, batch_size, cell_fw.output_size]`
and output_bw will be a `Tensor` shaped:
`[max_time, batch_size, cell_bw.output_size]`.
It returns a tuple instead of a single concatenated `Tensor`, unlike
in the `bidirectional_rnn`. If the concatenated one is preferred,
the forward and backward outputs can be concatenated as
`tf.concat(outputs, 2)`.
output_states: A tuple (output_state_fw, output_state_bw) containing
the forward and the backward final states of bidirectional rnn.
Raises:
TypeError: If `cell_fw` or `cell_bw` is not an instance of `RNNCell`.
"""
# pylint: disable=protected-access
if not isinstance(cell_fw, rnn_cell_impl._RNNCell):
raise TypeError("cell_fw must be an instance of RNNCell")
if not isinstance(cell_bw, rnn_cell_impl._RNNCell):
raise TypeError("cell_bw must be an instance of RNNCell")
# pylint: enable=protected-access
with vs.variable_scope(scope or "bidirectional_rnn"):
# Forward direction
with vs.variable_scope("fw") as fw_scope:
output_fw, output_state_fw = dynamic_rnn(
cell=cell_fw, inputs=inputs, sequence_length=sequence_length,
initial_state=initial_state_fw, dtype=dtype,
parallel_iterations=parallel_iterations, swap_memory=swap_memory,
time_major=time_major, scope=fw_scope)
# Backward direction
if not time_major:
time_dim = 1
batch_dim = 0
else:
time_dim = 0
batch_dim = 1
with vs.variable_scope("bw") as bw_scope:
inputs_reverse = array_ops.reverse_sequence(
input=inputs, seq_lengths=sequence_length,
seq_dim=time_dim, batch_dim=batch_dim)
tmp, output_state_bw = dynamic_rnn(
cell=cell_bw, inputs=inputs_reverse, sequence_length=sequence_length,
initial_state=initial_state_bw, dtype=dtype,
parallel_iterations=parallel_iterations, swap_memory=swap_memory,
time_major=time_major, scope=bw_scope)
output_bw = array_ops.reverse_sequence(
input=tmp, seq_lengths=sequence_length,
seq_dim=time_dim, batch_dim=batch_dim)
outputs = (output_fw, output_bw)
output_states = (output_state_fw, output_state_bw)
return (outputs, output_states)
def dynamic_rnn(cell, inputs, sequence_length=None, initial_state=None,
dtype=None, parallel_iterations=None, swap_memory=False,
time_major=False, scope=None):
"""Creates a recurrent neural network specified by RNNCell `cell`.
This function is functionally identical to the function `rnn` above, but
performs fully dynamic unrolling of `inputs`.
Unlike `rnn`, the input `inputs` is not a Python list of `Tensors`, one for
each frame. Instead, `inputs` may be a single `Tensor` where
the maximum time is either the first or second dimension (see the parameter
`time_major`). Alternatively, it may be a (possibly nested) tuple of
Tensors, each of them having matching batch and time dimensions.
The corresponding output is either a single `Tensor` having the same number
of time steps and batch size, or a (possibly nested) tuple of such tensors,
matching the nested structure of `cell.output_size`.
The parameter `sequence_length` is optional and is used to copy-through state
and zero-out outputs when past a batch element's sequence length. So it's more
for correctness than performance, unlike in rnn().
Args:
cell: An instance of RNNCell.
inputs: The RNN inputs.
If `time_major == False` (default), this must be a `Tensor` of shape:
`[batch_size, max_time, ...]`, or a nested tuple of such
elements.
If `time_major == True`, this must be a `Tensor` of shape:
`[max_time, batch_size, ...]`, or a nested tuple of such
elements.
This may also be a (possibly nested) tuple of Tensors satisfying
this property. The first two dimensions must match across all the inputs,
but otherwise the ranks and other shape components may differ.
In this case, input to `cell` at each time-step will replicate the
structure of these tuples, except for the time dimension (from which the
time is taken).
The input to `cell` at each time step will be a `Tensor` or (possibly
nested) tuple of Tensors each with dimensions `[batch_size, ...]`.
sequence_length: (optional) An int32/int64 vector sized `[batch_size]`.
initial_state: (optional) An initial state for the RNN.
If `cell.state_size` is an integer, this must be
a `Tensor` of appropriate type and shape `[batch_size, cell.state_size]`.
If `cell.state_size` is a tuple, this should be a tuple of
tensors having shapes `[batch_size, s] for s in cell.state_size`.
dtype: (optional) The data type for the initial state and expected output.
Required if initial_state is not provided or RNN state has a heterogeneous
dtype.
parallel_iterations: (Default: 32). The number of iterations to run in
parallel. Those operations which do not have any temporal dependency
and can be run in parallel, will be. This parameter trades off
time for space. Values >> 1 use more memory but take less time,
while smaller values use less memory but computations take longer.
swap_memory: Transparently swap the tensors produced in forward inference
but needed for back prop from GPU to CPU. This allows training RNNs
which would typically not fit on a single GPU, with very minimal (or no)
performance penalty.
time_major: The shape format of the `inputs` and `outputs` Tensors.
If true, these `Tensors` must be shaped `[max_time, batch_size, depth]`.
If false, these `Tensors` must be shaped `[batch_size, max_time, depth]`.
Using `time_major = True` is a bit more efficient because it avoids
transposes at the beginning and end of the RNN calculation. However,
most TensorFlow data is batch-major, so by default this function
accepts input and emits output in batch-major form.
scope: VariableScope for the created subgraph; defaults to "rnn".
Returns:
A pair (outputs, state) where:
outputs: The RNN output `Tensor`.
If time_major == False (default), this will be a `Tensor` shaped:
`[batch_size, max_time, cell.output_size]`.
If time_major == True, this will be a `Tensor` shaped:
`[max_time, batch_size, cell.output_size]`.
Note, if `cell.output_size` is a (possibly nested) tuple of integers
or `TensorShape` objects, then `outputs` will be a tuple having the
same structure as `cell.output_size`, containing Tensors having shapes
corresponding to the shape data in `cell.output_size`.
state: The final state. If `cell.state_size` is an int, this
will be shaped `[batch_size, cell.state_size]`. If it is a
`TensorShape`, this will be shaped `[batch_size] + cell.state_size`.
If it is a (possibly nested) tuple of ints or `TensorShape`, this will
be a tuple having the corresponding shapes.
Raises:
TypeError: If `cell` is not an instance of RNNCell.
ValueError: If inputs is None or an empty list.
"""
# pylint: disable=protected-access
if not isinstance(cell, rnn_cell_impl._RNNCell):
raise TypeError("cell must be an instance of RNNCell")
# pylint: enable=protected-access
# By default, time_major==False and inputs are batch-major: shaped
# [batch, time, depth]
# For internal calculations, we transpose to [time, batch, depth]
flat_input = nest.flatten(inputs)
if not time_major:
# (B,T,D) => (T,B,D)
flat_input = tuple(array_ops.transpose(input_, [1, 0, 2])
for input_ in flat_input)
parallel_iterations = parallel_iterations or 32
if sequence_length is not None:
sequence_length = math_ops.to_int32(sequence_length)
if sequence_length.get_shape().ndims not in (None, 1):
raise ValueError(
"sequence_length must be a vector of length batch_size, "
"but saw shape: %s" % sequence_length.get_shape())
sequence_length = array_ops.identity( # Just to find it in the graph.
sequence_length, name="sequence_length")
# Create a new scope in which the caching device is either
# determined by the parent scope, or is set to place the cached
# Variable using the same placement as for the rest of the RNN.
with vs.variable_scope(scope or "rnn") as varscope:
if varscope.caching_device is None:
varscope.set_caching_device(lambda op: op.device)
input_shape = tuple(array_ops.shape(input_) for input_ in flat_input)
batch_size = input_shape[0][1]
for input_ in input_shape:
if input_[1].get_shape() != batch_size.get_shape():
raise ValueError("All inputs should have the same batch size")
if initial_state is not None:
state = initial_state
else:
if not dtype:
raise ValueError("If no initial_state is provided, dtype must be.")
state = cell.zero_state(batch_size, dtype)
def _assert_has_shape(x, shape):
x_shape = array_ops.shape(x)
packed_shape = array_ops.stack(shape)
return control_flow_ops.Assert(
math_ops.reduce_all(math_ops.equal(x_shape, packed_shape)),
["Expected shape for Tensor %s is " % x.name,
packed_shape, " but saw shape: ", x_shape])
if sequence_length is not None:
# Perform some shape validation
with ops.control_dependencies(
[_assert_has_shape(sequence_length, [batch_size])]):
sequence_length = array_ops.identity(
sequence_length, name="CheckSeqLen")
inputs = nest.pack_sequence_as(structure=inputs, flat_sequence=flat_input)
(outputs, final_state) = _dynamic_rnn_loop(
cell,
inputs,
state,
parallel_iterations=parallel_iterations,
swap_memory=swap_memory,
sequence_length=sequence_length,
dtype=dtype)
# Outputs of _dynamic_rnn_loop are always shaped [time, batch, depth].
# If we are performing batch-major calculations, transpose output back
# to shape [batch, time, depth]
if not time_major:
# (T,B,D) => (B,T,D)
flat_output = nest.flatten(outputs)
flat_output = [array_ops.transpose(output, [1, 0, 2])
for output in flat_output]
outputs = nest.pack_sequence_as(
structure=outputs, flat_sequence=flat_output)
return (outputs, final_state)
def _dynamic_rnn_loop(cell,
inputs,
initial_state,
parallel_iterations,
swap_memory,
sequence_length=None,
dtype=None):
"""Internal implementation of Dynamic RNN.
Args:
cell: An instance of RNNCell.
inputs: A `Tensor` of shape [time, batch_size, input_size], or a nested
tuple of such elements.
initial_state: A `Tensor` of shape `[batch_size, state_size]`, or if
`cell.state_size` is a tuple, then this should be a tuple of
tensors having shapes `[batch_size, s] for s in cell.state_size`.
parallel_iterations: Positive Python int.
swap_memory: A Python boolean
sequence_length: (optional) An `int32` `Tensor` of shape [batch_size].
dtype: (optional) Expected dtype of output. If not specified, inferred from
initial_state.
Returns:
Tuple `(final_outputs, final_state)`.
final_outputs:
A `Tensor` of shape `[time, batch_size, cell.output_size]`. If
`cell.output_size` is a (possibly nested) tuple of ints or `TensorShape`
objects, then this returns a (possibly nsted) tuple of Tensors matching
the corresponding shapes.
final_state:
A `Tensor`, or possibly nested tuple of Tensors, matching in length
and shapes to `initial_state`.
Raises:
ValueError: If the input depth cannot be inferred via shape inference
from the inputs.
"""
state = initial_state
assert isinstance(parallel_iterations, int), "parallel_iterations must be int"
state_size = cell.state_size
flat_input = nest.flatten(inputs)
flat_output_size = nest.flatten(cell.output_size)
# Construct an initial output
input_shape = array_ops.shape(flat_input[0])
time_steps = input_shape[0]
batch_size = input_shape[1]
inputs_got_shape = tuple(input_.get_shape().with_rank_at_least(3)
for input_ in flat_input)
const_time_steps, const_batch_size = inputs_got_shape[0].as_list()[:2]
for shape in inputs_got_shape:
if not shape[2:].is_fully_defined():
raise ValueError(
"Input size (depth of inputs) must be accessible via shape inference,"
" but saw value None.")
got_time_steps = shape[0].value
got_batch_size = shape[1].value
if const_time_steps != got_time_steps:
raise ValueError(
"Time steps is not the same for all the elements in the input in a "
"batch.")
if const_batch_size != got_batch_size:
raise ValueError(
"Batch_size is not the same for all the elements in the input.")
# Prepare dynamic conditional copying of state & output
def _create_zero_arrays(size):
size = _state_size_with_prefix(size, prefix=[batch_size])
return array_ops.zeros(
array_ops.stack(size), _infer_state_dtype(dtype, state))
flat_zero_output = tuple(_create_zero_arrays(output)
for output in flat_output_size)
zero_output = nest.pack_sequence_as(structure=cell.output_size,
flat_sequence=flat_zero_output)
if sequence_length is not None:
min_sequence_length = math_ops.reduce_min(sequence_length)
max_sequence_length = math_ops.reduce_max(sequence_length)
time = array_ops.constant(0, dtype=dtypes.int32, name="time")
with ops.name_scope("dynamic_rnn") as scope:
base_name = scope
def _create_ta(name, dtype):
return tensor_array_ops.TensorArray(dtype=dtype,
size=time_steps,
tensor_array_name=base_name + name)
output_ta = tuple(_create_ta("output_%d" % i,
_infer_state_dtype(dtype, state))
for i in range(len(flat_output_size)))
input_ta = tuple(_create_ta("input_%d" % i, flat_input[0].dtype)
for i in range(len(flat_input)))
input_ta = tuple(ta.unstack(input_)
for ta, input_ in zip(input_ta, flat_input))
def _time_step(time, output_ta_t, state):
"""Take a time step of the dynamic RNN.
Args:
time: int32 scalar Tensor.
output_ta_t: List of `TensorArray`s that represent the output.
state: nested tuple of vector tensors that represent the state.
Returns:
The tuple (time + 1, output_ta_t with updated flow, new_state).
"""
input_t = tuple(ta.read(time) for ta in input_ta)
# Restore some shape information
for input_, shape in zip(input_t, inputs_got_shape):
input_.set_shape(shape[1:])
input_t = nest.pack_sequence_as(structure=inputs, flat_sequence=input_t)
call_cell = lambda: cell(input_t, state)
if sequence_length is not None:
(output, new_state) = _rnn_step(
time=time,
sequence_length=sequence_length,
min_sequence_length=min_sequence_length,
max_sequence_length=max_sequence_length,
zero_output=zero_output,
state=state,
call_cell=call_cell,
state_size=state_size,
skip_conditionals=True)
else:
(output, new_state) = call_cell()
# Pack state if using state tuples
output = nest.flatten(output)
output_ta_t = tuple(
ta.write(time, out) for ta, out in zip(output_ta_t, output))
return (time + 1, output_ta_t, new_state)
_, output_final_ta, final_state = control_flow_ops.while_loop(
cond=lambda time, *_: time < time_steps,
body=_time_step,
loop_vars=(time, output_ta, state),
parallel_iterations=parallel_iterations,
swap_memory=swap_memory)
# Unpack final output if not using output tuples.
final_outputs = tuple(ta.stack() for ta in output_final_ta)
# Restore some shape information
for output, output_size in zip(final_outputs, flat_output_size):
shape = _state_size_with_prefix(
output_size, prefix=[const_time_steps, const_batch_size])
output.set_shape(shape)
final_outputs = nest.pack_sequence_as(
structure=cell.output_size, flat_sequence=final_outputs)
return (final_outputs, final_state)
def raw_rnn(cell, loop_fn,
parallel_iterations=None, swap_memory=False, scope=None):
"""Creates an `RNN` specified by RNNCell `cell` and loop function `loop_fn`.
**NOTE: This method is still in testing, and the API may change.**
This function is a more primitive version of `dynamic_rnn` that provides
more direct access to the inputs each iteration. It also provides more
control over when to start and finish reading the sequence, and
what to emit for the output.
For example, it can be used to implement the dynamic decoder of a seq2seq
model.
Instead of working with `Tensor` objects, most operations work with
`TensorArray` objects directly.
The operation of `raw_rnn`, in pseudo-code, is basically the following:
```python
time = tf.constant(0, dtype=tf.int32)
(finished, next_input, initial_state, _, loop_state) = loop_fn(
time=time, cell_output=None, cell_state=None, loop_state=None)
emit_ta = TensorArray(dynamic_size=True, dtype=initial_state.dtype)
state = initial_state
while not all(finished):
(output, cell_state) = cell(next_input, state)
(next_finished, next_input, next_state, emit, loop_state) = loop_fn(
time=time + 1, cell_output=output, cell_state=cell_state,
loop_state=loop_state)
# Emit zeros and copy forward state for minibatch entries that are finished.
state = tf.where(finished, state, next_state)
emit = tf.where(finished, tf.zeros_like(emit), emit)
emit_ta = emit_ta.write(time, emit)
# If any new minibatch entries are marked as finished, mark these.
finished = tf.logical_or(finished, next_finished)
time += 1
return (emit_ta, state, loop_state)
```
with the additional properties that output and state may be (possibly nested)
tuples, as determined by `cell.output_size` and `cell.state_size`, and
as a result the final `state` and `emit_ta` may themselves be tuples.
A simple implementation of `dynamic_rnn` via `raw_rnn` looks like this:
```python
inputs = tf.placeholder(shape=(max_time, batch_size, input_depth),
dtype=tf.float32)
sequence_length = tf.placeholder(shape=(batch_size,), dtype=tf.int32)
inputs_ta = tf.TensorArray(dtype=tf.float32, size=max_time)
inputs_ta = inputs_ta.unstack(inputs)
cell = tf.contrib.rnn.LSTMCell(num_units)
def loop_fn(time, cell_output, cell_state, loop_state):
emit_output = cell_output # == None for time == 0
if cell_output is None: # time == 0
next_cell_state = cell.zero_state(batch_size, tf.float32)
else:
next_cell_state = cell_state
elements_finished = (time >= sequence_length)
finished = tf.reduce_all(elements_finished)
next_input = tf.cond(
finished,
lambda: tf.zeros([batch_size, input_depth], dtype=tf.float32),
lambda: inputs_ta.read(time))
next_loop_state = None
return (elements_finished, next_input, next_cell_state,
emit_output, next_loop_state)
outputs_ta, final_state, _ = raw_rnn(cell, loop_fn)
outputs = outputs_ta.stack()
```
Args:
cell: An instance of RNNCell.
loop_fn: A callable that takes inputs
`(time, cell_output, cell_state, loop_state)`
and returns the tuple
`(finished, next_input, next_cell_state, emit_output, next_loop_state)`.
Here `time` is an int32 scalar `Tensor`, `cell_output` is a
`Tensor` or (possibly nested) tuple of tensors as determined by
`cell.output_size`, and `cell_state` is a `Tensor`
or (possibly nested) tuple of tensors, as determined by the `loop_fn`
on its first call (and should match `cell.state_size`).
The outputs are: `finished`, a boolean `Tensor` of
shape `[batch_size]`, `next_input`: the next input to feed to `cell`,
`next_cell_state`: the next state to feed to `cell`,
and `emit_output`: the output to store for this iteration.
Note that `emit_output` should be a `Tensor` or (possibly nested)
tuple of tensors with shapes and structure matching `cell.output_size`
and `cell_output` above. The parameter `cell_state` and output
`next_cell_state` may be either a single or (possibly nested) tuple
of tensors. The parameter `loop_state` and
output `next_loop_state` may be either a single or (possibly nested) tuple
of `Tensor` and `TensorArray` objects. This last parameter
may be ignored by `loop_fn` and the return value may be `None`. If it
is not `None`, then the `loop_state` will be propagated through the RNN
loop, for use purely by `loop_fn` to keep track of its own state.
The `next_loop_state` parameter returned may be `None`.
The first call to `loop_fn` will be `time = 0`, `cell_output = None`,
`cell_state = None`, and `loop_state = None`. For this call:
The `next_cell_state` value should be the value with which to initialize
the cell's state. It may be a final state from a previous RNN or it
may be the output of `cell.zero_state()`. It should be a
(possibly nested) tuple structure of tensors.
If `cell.state_size` is an integer, this must be
a `Tensor` of appropriate type and shape `[batch_size, cell.state_size]`.
If `cell.state_size` is a `TensorShape`, this must be a `Tensor` of
appropriate type and shape `[batch_size] + cell.state_size`.
If `cell.state_size` is a (possibly nested) tuple of ints or
`TensorShape`, this will be a tuple having the corresponding shapes.
The `emit_output` value may be either `None` or a (possibly nested)
tuple structure of tensors, e.g.,
`(tf.zeros(shape_0, dtype=dtype_0), tf.zeros(shape_1, dtype=dtype_1))`.
If this first `emit_output` return value is `None`,
then the `emit_ta` result of `raw_rnn` will have the same structure and
dtypes as `cell.output_size`. Otherwise `emit_ta` will have the same
structure, shapes (prepended with a `batch_size` dimension), and dtypes
as `emit_output`. The actual values returned for `emit_output` at this
initializing call are ignored. Note, this emit structure must be
consistent across all time steps.
parallel_iterations: (Default: 32). The number of iterations to run in
parallel. Those operations which do not have any temporal dependency
and can be run in parallel, will be. This parameter trades off
time for space. Values >> 1 use more memory but take less time,
while smaller values use less memory but computations take longer.
swap_memory: Transparently swap the tensors produced in forward inference
but needed for back prop from GPU to CPU. This allows training RNNs
which would typically not fit on a single GPU, with very minimal (or no)
performance penalty.
scope: VariableScope for the created subgraph; defaults to "rnn".
Returns:
A tuple `(emit_ta, final_state, final_loop_state)` where:
`emit_ta`: The RNN output `TensorArray`.
If `loop_fn` returns a (possibly nested) set of Tensors for
`emit_output` during initialization, (inputs `time = 0`,
`cell_output = None`, and `loop_state = None`), then `emit_ta` will
have the same structure, dtypes, and shapes as `emit_output` instead.
If `loop_fn` returns `emit_output = None` during this call,
the structure of `cell.output_size` is used:
If `cell.output_size` is a (possibly nested) tuple of integers
or `TensorShape` objects, then `emit_ta` will be a tuple having the
same structure as `cell.output_size`, containing TensorArrays whose
elements' shapes correspond to the shape data in `cell.output_size`.
`final_state`: The final cell state. If `cell.state_size` is an int, this
will be shaped `[batch_size, cell.state_size]`. If it is a
`TensorShape`, this will be shaped `[batch_size] + cell.state_size`.
If it is a (possibly nested) tuple of ints or `TensorShape`, this will
be a tuple having the corresponding shapes.
`final_loop_state`: The final loop state as returned by `loop_fn`.
Raises:
TypeError: If `cell` is not an instance of RNNCell, or `loop_fn` is not
a `callable`.
"""
# pylint: disable=protected-access
if not isinstance(cell, rnn_cell_impl._RNNCell):
raise TypeError("cell must be an instance of RNNCell")
# pylint: enable=protected-access
if not callable(loop_fn):
raise TypeError("loop_fn must be a callable")
parallel_iterations = parallel_iterations or 32
# Create a new scope in which the caching device is either
# determined by the parent scope, or is set to place the cached
# Variable using the same placement as for the rest of the RNN.
with vs.variable_scope(scope or "rnn") as varscope:
if varscope.caching_device is None:
varscope.set_caching_device(lambda op: op.device)
time = constant_op.constant(0, dtype=dtypes.int32)
(elements_finished, next_input, initial_state, emit_structure,
init_loop_state) = loop_fn(
time, None, None, None) # time, cell_output, cell_state, loop_state
flat_input = nest.flatten(next_input)
# Need a surrogate loop state for the while_loop if none is available.
loop_state = (init_loop_state if init_loop_state is not None
else constant_op.constant(0, dtype=dtypes.int32))
input_shape = [input_.get_shape() for input_ in flat_input]
static_batch_size = input_shape[0][0]
for input_shape_i in input_shape:
# Static verification that batch sizes all match
static_batch_size.merge_with(input_shape_i[0])
batch_size = static_batch_size.value
if batch_size is None:
batch_size = array_ops.shape(flat_input[0])[0]
nest.assert_same_structure(initial_state, cell.state_size)
state = initial_state
flat_state = nest.flatten(state)
flat_state = [ops.convert_to_tensor(s) for s in flat_state]
state = nest.pack_sequence_as(structure=state,
flat_sequence=flat_state)
if emit_structure is not None:
flat_emit_structure = nest.flatten(emit_structure)
flat_emit_size = [emit.get_shape() for emit in flat_emit_structure]
flat_emit_dtypes = [emit.dtype for emit in flat_emit_structure]
else:
emit_structure = cell.output_size
flat_emit_size = nest.flatten(emit_structure)
flat_emit_dtypes = [flat_state[0].dtype] * len(flat_emit_size)
flat_emit_ta = [
tensor_array_ops.TensorArray(
dtype=dtype_i, dynamic_size=True, size=0, name="rnn_output_%d" % i)
for i, dtype_i in enumerate(flat_emit_dtypes)]
emit_ta = nest.pack_sequence_as(structure=emit_structure,
flat_sequence=flat_emit_ta)
flat_zero_emit = [
array_ops.zeros(
_state_size_with_prefix(size_i, prefix=[batch_size]),
dtype_i)
for size_i, dtype_i in zip(flat_emit_size, flat_emit_dtypes)]
zero_emit = nest.pack_sequence_as(structure=emit_structure,
flat_sequence=flat_zero_emit)
def condition(unused_time, elements_finished, *_):
return math_ops.logical_not(math_ops.reduce_all(elements_finished))
def body(time, elements_finished, current_input,
emit_ta, state, loop_state):
"""Internal while loop body for raw_rnn.
Args:
time: time scalar.
elements_finished: batch-size vector.
current_input: possibly nested tuple of input tensors.
emit_ta: possibly nested tuple of output TensorArrays.
state: possibly nested tuple of state tensors.
loop_state: possibly nested tuple of loop state tensors.
Returns:
Tuple having the same size as Args but with updated values.
"""
(next_output, cell_state) = cell(current_input, state)
nest.assert_same_structure(state, cell_state)
nest.assert_same_structure(cell.output_size, next_output)
next_time = time + 1
(next_finished, next_input, next_state, emit_output,
next_loop_state) = loop_fn(
next_time, next_output, cell_state, loop_state)
nest.assert_same_structure(state, next_state)
nest.assert_same_structure(current_input, next_input)
nest.assert_same_structure(emit_ta, emit_output)
# If loop_fn returns None for next_loop_state, just reuse the
# previous one.
loop_state = loop_state if next_loop_state is None else next_loop_state
def _copy_some_through(current, candidate):
"""Copy some tensors through via array_ops.where."""
current_flat = nest.flatten(current)
candidate_flat = nest.flatten(candidate)
# pylint: disable=g-long-lambda,cell-var-from-loop
result_flat = [
_on_device(
lambda: array_ops.where(
elements_finished, current_i, candidate_i),
device=candidate_i.op.device)
for (current_i, candidate_i) in zip(current_flat, candidate_flat)]
# pylint: enable=g-long-lambda,cell-var-from-loop
return nest.pack_sequence_as(
structure=current, flat_sequence=result_flat)
emit_output = _copy_some_through(zero_emit, emit_output)
next_state = _copy_some_through(state, next_state)
emit_output_flat = nest.flatten(emit_output)
emit_ta_flat = nest.flatten(emit_ta)
elements_finished = math_ops.logical_or(elements_finished, next_finished)
emit_ta_flat = [
ta.write(time, emit)
for (ta, emit) in zip(emit_ta_flat, emit_output_flat)]
emit_ta = nest.pack_sequence_as(
structure=emit_structure, flat_sequence=emit_ta_flat)
return (next_time, elements_finished, next_input,
emit_ta, next_state, loop_state)
returned = control_flow_ops.while_loop(
condition, body, loop_vars=[
time, elements_finished, next_input,
emit_ta, state, loop_state],
parallel_iterations=parallel_iterations,
swap_memory=swap_memory)
(emit_ta, final_state, final_loop_state) = returned[-3:]
if init_loop_state is None:
final_loop_state = None
return (emit_ta, final_state, final_loop_state)
| tensorflow/python/ops/rnn.py | 44,670 | Copy some tensors through via array_ops.where.
Internal implementation of Dynamic RNN.
Args:
cell: An instance of RNNCell.
inputs: A `Tensor` of shape [time, batch_size, input_size], or a nested
tuple of such elements.
initial_state: A `Tensor` of shape `[batch_size, state_size]`, or if
`cell.state_size` is a tuple, then this should be a tuple of
tensors having shapes `[batch_size, s] for s in cell.state_size`.
parallel_iterations: Positive Python int.
swap_memory: A Python boolean
sequence_length: (optional) An `int32` `Tensor` of shape [batch_size].
dtype: (optional) Expected dtype of output. If not specified, inferred from
initial_state.
Returns:
Tuple `(final_outputs, final_state)`.
final_outputs:
A `Tensor` of shape `[time, batch_size, cell.output_size]`. If
`cell.output_size` is a (possibly nested) tuple of ints or `TensorShape`
objects, then this returns a (possibly nsted) tuple of Tensors matching
the corresponding shapes.
final_state:
A `Tensor`, or possibly nested tuple of Tensors, matching in length
and shapes to `initial_state`.
Raises:
ValueError: If the input depth cannot be inferred via shape inference
from the inputs.
Infer the dtype of an RNN state.
Args:
explicit_dtype: explicitly declared dtype or None.
state: RNN's hidden state. Must be a Tensor or a nested iterable containing
Tensors.
Returns:
dtype: inferred dtype of hidden state.
Raises:
ValueError: if `state` has heterogeneous dtypes or is empty.
Run RNN step. Pass through either no or some past state.
Build the subgraph defined by lambda `fn` on `device` if it's not None.
Reverse a list of Tensors up to specified lengths.
Args:
input_seq: Sequence of seq_len tensors of dimension (batch_size, n_features)
or nested tuples of tensors.
lengths: A `Tensor` of dimension batch_size, containing lengths for each
sequence in the batch. If "None" is specified, simply reverses
the list.
Returns:
time-reversed sequence
Calculate one step of a dynamic RNN minibatch.
Returns an (output, state) pair conditioned on the sequence_lengths.
When skip_conditionals=False, the pseudocode is something like:
if t >= max_sequence_length:
return (zero_output, state)
if t < min_sequence_length:
return call_cell()
# Selectively output zeros or output, old state or new state depending
# on if we've finished calculating each row.
new_output, new_state = call_cell()
final_output = np.vstack([
zero_output if time >= sequence_lengths[r] else new_output_r
for r, new_output_r in enumerate(new_output)
])
final_state = np.vstack([
state[r] if time >= sequence_lengths[r] else new_state_r
for r, new_state_r in enumerate(new_state)
])
return (final_output, final_state)
Args:
time: Python int, the current time step
sequence_length: int32 `Tensor` vector of size [batch_size]
min_sequence_length: int32 `Tensor` scalar, min of sequence_length
max_sequence_length: int32 `Tensor` scalar, max of sequence_length
zero_output: `Tensor` vector of shape [output_size]
state: Either a single `Tensor` matrix of shape `[batch_size, state_size]`,
or a list/tuple of such tensors.
call_cell: lambda returning tuple of (new_output, new_state) where
new_output is a `Tensor` matrix of shape `[batch_size, output_size]`.
new_state is a `Tensor` matrix of shape `[batch_size, state_size]`.
state_size: The `cell.state_size` associated with the state.
skip_conditionals: Python bool, whether to skip using the conditional
calculations. This is useful for `dynamic_rnn`, where the input tensor
matches `max_sequence_length`, and using conditionals just slows
everything down.
Returns:
A tuple of (`final_output`, `final_state`) as given by the pseudocode above:
final_output is a `Tensor` matrix of shape [batch_size, output_size]
final_state is either a single `Tensor` matrix, or a tuple of such
matrices (matching length and shapes of input `state`).
Raises:
ValueError: If the cell returns a state tuple whose length does not match
that returned by `state_size`.
Take a time step of the dynamic RNN.
Args:
time: int32 scalar Tensor.
output_ta_t: List of `TensorArray`s that represent the output.
state: nested tuple of vector tensors that represent the state.
Returns:
The tuple (time + 1, output_ta_t with updated flow, new_state).
Creates a dynamic version of bidirectional recurrent neural network.
Similar to the unidirectional case above (rnn) but takes input and builds
independent forward and backward RNNs. The input_size of forward and
backward cell must match. The initial state for both directions is zero by
default (but can be set optionally) and no intermediate states are ever
returned -- the network is fully unrolled for the given (passed in)
length(s) of the sequence(s) or completely unrolled if length(s) is not
given.
Args:
cell_fw: An instance of RNNCell, to be used for forward direction.
cell_bw: An instance of RNNCell, to be used for backward direction.
inputs: The RNN inputs.
If time_major == False (default), this must be a tensor of shape:
`[batch_size, max_time, input_size]`.
If time_major == True, this must be a tensor of shape:
`[max_time, batch_size, input_size]`.
[batch_size, input_size].
sequence_length: An int32/int64 vector, size `[batch_size]`,
containing the actual lengths for each of the sequences.
initial_state_fw: (optional) An initial state for the forward RNN.
This must be a tensor of appropriate type and shape
`[batch_size, cell_fw.state_size]`.
If `cell_fw.state_size` is a tuple, this should be a tuple of
tensors having shapes `[batch_size, s] for s in cell_fw.state_size`.
initial_state_bw: (optional) Same as for `initial_state_fw`, but using
the corresponding properties of `cell_bw`.
dtype: (optional) The data type for the initial states and expected output.
Required if initial_states are not provided or RNN states have a
heterogeneous dtype.
parallel_iterations: (Default: 32). The number of iterations to run in
parallel. Those operations which do not have any temporal dependency
and can be run in parallel, will be. This parameter trades off
time for space. Values >> 1 use more memory but take less time,
while smaller values use less memory but computations take longer.
swap_memory: Transparently swap the tensors produced in forward inference
but needed for back prop from GPU to CPU. This allows training RNNs
which would typically not fit on a single GPU, with very minimal (or no)
performance penalty.
time_major: The shape format of the `inputs` and `outputs` Tensors.
If true, these `Tensors` must be shaped `[max_time, batch_size, depth]`.
If false, these `Tensors` must be shaped `[batch_size, max_time, depth]`.
Using `time_major = True` is a bit more efficient because it avoids
transposes at the beginning and end of the RNN calculation. However,
most TensorFlow data is batch-major, so by default this function
accepts input and emits output in batch-major form.
dtype: (optional) The data type for the initial state. Required if
either of the initial states are not provided.
scope: VariableScope for the created subgraph; defaults to
"bidirectional_rnn"
Returns:
A tuple (outputs, output_states) where:
outputs: A tuple (output_fw, output_bw) containing the forward and
the backward rnn output `Tensor`.
If time_major == False (default),
output_fw will be a `Tensor` shaped:
`[batch_size, max_time, cell_fw.output_size]`
and output_bw will be a `Tensor` shaped:
`[batch_size, max_time, cell_bw.output_size]`.
If time_major == True,
output_fw will be a `Tensor` shaped:
`[max_time, batch_size, cell_fw.output_size]`
and output_bw will be a `Tensor` shaped:
`[max_time, batch_size, cell_bw.output_size]`.
It returns a tuple instead of a single concatenated `Tensor`, unlike
in the `bidirectional_rnn`. If the concatenated one is preferred,
the forward and backward outputs can be concatenated as
`tf.concat(outputs, 2)`.
output_states: A tuple (output_state_fw, output_state_bw) containing
the forward and the backward final states of bidirectional rnn.
Raises:
TypeError: If `cell_fw` or `cell_bw` is not an instance of `RNNCell`.
Internal while loop body for raw_rnn.
Args:
time: time scalar.
elements_finished: batch-size vector.
current_input: possibly nested tuple of input tensors.
emit_ta: possibly nested tuple of output TensorArrays.
state: possibly nested tuple of state tensors.
loop_state: possibly nested tuple of loop state tensors.
Returns:
Tuple having the same size as Args but with updated values.
Creates a recurrent neural network specified by RNNCell `cell`.
This function is functionally identical to the function `rnn` above, but
performs fully dynamic unrolling of `inputs`.
Unlike `rnn`, the input `inputs` is not a Python list of `Tensors`, one for
each frame. Instead, `inputs` may be a single `Tensor` where
the maximum time is either the first or second dimension (see the parameter
`time_major`). Alternatively, it may be a (possibly nested) tuple of
Tensors, each of them having matching batch and time dimensions.
The corresponding output is either a single `Tensor` having the same number
of time steps and batch size, or a (possibly nested) tuple of such tensors,
matching the nested structure of `cell.output_size`.
The parameter `sequence_length` is optional and is used to copy-through state
and zero-out outputs when past a batch element's sequence length. So it's more
for correctness than performance, unlike in rnn().
Args:
cell: An instance of RNNCell.
inputs: The RNN inputs.
If `time_major == False` (default), this must be a `Tensor` of shape:
`[batch_size, max_time, ...]`, or a nested tuple of such
elements.
If `time_major == True`, this must be a `Tensor` of shape:
`[max_time, batch_size, ...]`, or a nested tuple of such
elements.
This may also be a (possibly nested) tuple of Tensors satisfying
this property. The first two dimensions must match across all the inputs,
but otherwise the ranks and other shape components may differ.
In this case, input to `cell` at each time-step will replicate the
structure of these tuples, except for the time dimension (from which the
time is taken).
The input to `cell` at each time step will be a `Tensor` or (possibly
nested) tuple of Tensors each with dimensions `[batch_size, ...]`.
sequence_length: (optional) An int32/int64 vector sized `[batch_size]`.
initial_state: (optional) An initial state for the RNN.
If `cell.state_size` is an integer, this must be
a `Tensor` of appropriate type and shape `[batch_size, cell.state_size]`.
If `cell.state_size` is a tuple, this should be a tuple of
tensors having shapes `[batch_size, s] for s in cell.state_size`.
dtype: (optional) The data type for the initial state and expected output.
Required if initial_state is not provided or RNN state has a heterogeneous
dtype.
parallel_iterations: (Default: 32). The number of iterations to run in
parallel. Those operations which do not have any temporal dependency
and can be run in parallel, will be. This parameter trades off
time for space. Values >> 1 use more memory but take less time,
while smaller values use less memory but computations take longer.
swap_memory: Transparently swap the tensors produced in forward inference
but needed for back prop from GPU to CPU. This allows training RNNs
which would typically not fit on a single GPU, with very minimal (or no)
performance penalty.
time_major: The shape format of the `inputs` and `outputs` Tensors.
If true, these `Tensors` must be shaped `[max_time, batch_size, depth]`.
If false, these `Tensors` must be shaped `[batch_size, max_time, depth]`.
Using `time_major = True` is a bit more efficient because it avoids
transposes at the beginning and end of the RNN calculation. However,
most TensorFlow data is batch-major, so by default this function
accepts input and emits output in batch-major form.
scope: VariableScope for the created subgraph; defaults to "rnn".
Returns:
A pair (outputs, state) where:
outputs: The RNN output `Tensor`.
If time_major == False (default), this will be a `Tensor` shaped:
`[batch_size, max_time, cell.output_size]`.
If time_major == True, this will be a `Tensor` shaped:
`[max_time, batch_size, cell.output_size]`.
Note, if `cell.output_size` is a (possibly nested) tuple of integers
or `TensorShape` objects, then `outputs` will be a tuple having the
same structure as `cell.output_size`, containing Tensors having shapes
corresponding to the shape data in `cell.output_size`.
state: The final state. If `cell.state_size` is an int, this
will be shaped `[batch_size, cell.state_size]`. If it is a
`TensorShape`, this will be shaped `[batch_size] + cell.state_size`.
If it is a (possibly nested) tuple of ints or `TensorShape`, this will
be a tuple having the corresponding shapes.
Raises:
TypeError: If `cell` is not an instance of RNNCell.
ValueError: If inputs is None or an empty list.
Creates an `RNN` specified by RNNCell `cell` and loop function `loop_fn`.
**NOTE: This method is still in testing, and the API may change.**
This function is a more primitive version of `dynamic_rnn` that provides
more direct access to the inputs each iteration. It also provides more
control over when to start and finish reading the sequence, and
what to emit for the output.
For example, it can be used to implement the dynamic decoder of a seq2seq
model.
Instead of working with `Tensor` objects, most operations work with
`TensorArray` objects directly.
The operation of `raw_rnn`, in pseudo-code, is basically the following:
```python
time = tf.constant(0, dtype=tf.int32)
(finished, next_input, initial_state, _, loop_state) = loop_fn(
time=time, cell_output=None, cell_state=None, loop_state=None)
emit_ta = TensorArray(dynamic_size=True, dtype=initial_state.dtype)
state = initial_state
while not all(finished):
(output, cell_state) = cell(next_input, state)
(next_finished, next_input, next_state, emit, loop_state) = loop_fn(
time=time + 1, cell_output=output, cell_state=cell_state,
loop_state=loop_state)
# Emit zeros and copy forward state for minibatch entries that are finished.
state = tf.where(finished, state, next_state)
emit = tf.where(finished, tf.zeros_like(emit), emit)
emit_ta = emit_ta.write(time, emit)
# If any new minibatch entries are marked as finished, mark these.
finished = tf.logical_or(finished, next_finished)
time += 1
return (emit_ta, state, loop_state)
```
with the additional properties that output and state may be (possibly nested)
tuples, as determined by `cell.output_size` and `cell.state_size`, and
as a result the final `state` and `emit_ta` may themselves be tuples.
A simple implementation of `dynamic_rnn` via `raw_rnn` looks like this:
```python
inputs = tf.placeholder(shape=(max_time, batch_size, input_depth),
dtype=tf.float32)
sequence_length = tf.placeholder(shape=(batch_size,), dtype=tf.int32)
inputs_ta = tf.TensorArray(dtype=tf.float32, size=max_time)
inputs_ta = inputs_ta.unstack(inputs)
cell = tf.contrib.rnn.LSTMCell(num_units)
def loop_fn(time, cell_output, cell_state, loop_state):
emit_output = cell_output # == None for time == 0
if cell_output is None: # time == 0
next_cell_state = cell.zero_state(batch_size, tf.float32)
else:
next_cell_state = cell_state
elements_finished = (time >= sequence_length)
finished = tf.reduce_all(elements_finished)
next_input = tf.cond(
finished,
lambda: tf.zeros([batch_size, input_depth], dtype=tf.float32),
lambda: inputs_ta.read(time))
next_loop_state = None
return (elements_finished, next_input, next_cell_state,
emit_output, next_loop_state)
outputs_ta, final_state, _ = raw_rnn(cell, loop_fn)
outputs = outputs_ta.stack()
```
Args:
cell: An instance of RNNCell.
loop_fn: A callable that takes inputs
`(time, cell_output, cell_state, loop_state)`
and returns the tuple
`(finished, next_input, next_cell_state, emit_output, next_loop_state)`.
Here `time` is an int32 scalar `Tensor`, `cell_output` is a
`Tensor` or (possibly nested) tuple of tensors as determined by
`cell.output_size`, and `cell_state` is a `Tensor`
or (possibly nested) tuple of tensors, as determined by the `loop_fn`
on its first call (and should match `cell.state_size`).
The outputs are: `finished`, a boolean `Tensor` of
shape `[batch_size]`, `next_input`: the next input to feed to `cell`,
`next_cell_state`: the next state to feed to `cell`,
and `emit_output`: the output to store for this iteration.
Note that `emit_output` should be a `Tensor` or (possibly nested)
tuple of tensors with shapes and structure matching `cell.output_size`
and `cell_output` above. The parameter `cell_state` and output
`next_cell_state` may be either a single or (possibly nested) tuple
of tensors. The parameter `loop_state` and
output `next_loop_state` may be either a single or (possibly nested) tuple
of `Tensor` and `TensorArray` objects. This last parameter
may be ignored by `loop_fn` and the return value may be `None`. If it
is not `None`, then the `loop_state` will be propagated through the RNN
loop, for use purely by `loop_fn` to keep track of its own state.
The `next_loop_state` parameter returned may be `None`.
The first call to `loop_fn` will be `time = 0`, `cell_output = None`,
`cell_state = None`, and `loop_state = None`. For this call:
The `next_cell_state` value should be the value with which to initialize
the cell's state. It may be a final state from a previous RNN or it
may be the output of `cell.zero_state()`. It should be a
(possibly nested) tuple structure of tensors.
If `cell.state_size` is an integer, this must be
a `Tensor` of appropriate type and shape `[batch_size, cell.state_size]`.
If `cell.state_size` is a `TensorShape`, this must be a `Tensor` of
appropriate type and shape `[batch_size] + cell.state_size`.
If `cell.state_size` is a (possibly nested) tuple of ints or
`TensorShape`, this will be a tuple having the corresponding shapes.
The `emit_output` value may be either `None` or a (possibly nested)
tuple structure of tensors, e.g.,
`(tf.zeros(shape_0, dtype=dtype_0), tf.zeros(shape_1, dtype=dtype_1))`.
If this first `emit_output` return value is `None`,
then the `emit_ta` result of `raw_rnn` will have the same structure and
dtypes as `cell.output_size`. Otherwise `emit_ta` will have the same
structure, shapes (prepended with a `batch_size` dimension), and dtypes
as `emit_output`. The actual values returned for `emit_output` at this
initializing call are ignored. Note, this emit structure must be
consistent across all time steps.
parallel_iterations: (Default: 32). The number of iterations to run in
parallel. Those operations which do not have any temporal dependency
and can be run in parallel, will be. This parameter trades off
time for space. Values >> 1 use more memory but take less time,
while smaller values use less memory but computations take longer.
swap_memory: Transparently swap the tensors produced in forward inference
but needed for back prop from GPU to CPU. This allows training RNNs
which would typically not fit on a single GPU, with very minimal (or no)
performance penalty.
scope: VariableScope for the created subgraph; defaults to "rnn".
Returns:
A tuple `(emit_ta, final_state, final_loop_state)` where:
`emit_ta`: The RNN output `TensorArray`.
If `loop_fn` returns a (possibly nested) set of Tensors for
`emit_output` during initialization, (inputs `time = 0`,
`cell_output = None`, and `loop_state = None`), then `emit_ta` will
have the same structure, dtypes, and shapes as `emit_output` instead.
If `loop_fn` returns `emit_output = None` during this call,
the structure of `cell.output_size` is used:
If `cell.output_size` is a (possibly nested) tuple of integers
or `TensorShape` objects, then `emit_ta` will be a tuple having the
same structure as `cell.output_size`, containing TensorArrays whose
elements' shapes correspond to the shape data in `cell.output_size`.
`final_state`: The final cell state. If `cell.state_size` is an int, this
will be shaped `[batch_size, cell.state_size]`. If it is a
`TensorShape`, this will be shaped `[batch_size] + cell.state_size`.
If it is a (possibly nested) tuple of ints or `TensorShape`, this will
be a tuple having the corresponding shapes.
`final_loop_state`: The final loop state as returned by `loop_fn`.
Raises:
TypeError: If `cell` is not an instance of RNNCell, or `loop_fn` is not
a `callable`.
RNN helpers for TensorFlow models.
Copyright 2015 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. ============================================================================== pylint: disable=protected-access pylint: enable=protected-access pylint: disable=unused-argument Convert state to a list for ease of use Use broadcasting select to determine which values should get the previous state & zero output, and which values should get a calculated state & output. if t < min_seq_len: calculate and return everything else copy some of it through TODO(ebrevdo): skipping these conditionals may cause a slowdown, but benefits from removing cond() and its gradient. We should profile with and without this switch here. Instead of using conditionals, perform the selective copy at all time steps. This is faster when max_seq_len is equal to the number of unrolls (which is typical for dynamic_rnn). if t >= max_seq_len: copy all state through, output zeros otherwise calculation is required: copy some or all of it through Join into (time, batch_size, depth) TODO(schuster, ebrevdo): Remove cast when reverse_sequence takes int32 Reverse along dimension 0 Split again into list pylint: disable=protected-access pylint: enable=protected-access Forward direction Backward direction pylint: disable=protected-access pylint: enable=protected-access By default, time_major==False and inputs are batch-major: shaped [batch, time, depth] For internal calculations, we transpose to [time, batch, depth] (B,T,D) => (T,B,D) Just to find it in the graph. Create a new scope in which the caching device is either determined by the parent scope, or is set to place the cached Variable using the same placement as for the rest of the RNN. Perform some shape validation Outputs of _dynamic_rnn_loop are always shaped [time, batch, depth]. If we are performing batch-major calculations, transpose output back to shape [batch, time, depth] (T,B,D) => (B,T,D) Construct an initial output Prepare dynamic conditional copying of state & output Restore some shape information Pack state if using state tuples Unpack final output if not using output tuples. Restore some shape information pylint: disable=protected-access pylint: enable=protected-access Create a new scope in which the caching device is either determined by the parent scope, or is set to place the cached Variable using the same placement as for the rest of the RNN. time, cell_output, cell_state, loop_state Need a surrogate loop state for the while_loop if none is available. Static verification that batch sizes all match If loop_fn returns None for next_loop_state, just reuse the previous one. pylint: disable=g-long-lambda,cell-var-from-loop pylint: enable=g-long-lambda,cell-var-from-loop | 24,642 | en | 0.780209 |
"""
Module containing NetPyNE metadata
"""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
metadata = {
# ---------------------------------------------------------------------------------------------------------------------
# netParams
# ---------------------------------------------------------------------------------------------------------------------
"netParams": {
"label": "Network Parameters",
"suggestions": "",
"help": "",
"hintText": "",
"children": {
"popParams": {
"label": "Population Parameters",
"suggestions": "",
"help": "",
"hintText": "",
"children": {
"cellType": {
"label": "Cell type",
"suggestions": "",
"help": "Arbitrary cell type attribute/tag assigned to all cells in this population; can be used as condition to apply specific cell properties. e.g. 'Pyr' (for pyramidal neurons) or 'FS' (for fast-spiking interneurons)",
"hintText": "",
"type": "str"
},
"numCells": {
"label": "Number of cells",
"suggestions": "",
"help": "The total number of cells in this population.",
"hintText": "number of cells",
"type": "int"
},
"density": {
"label": "Cell density (neurons/mm^3)",
"suggestions": "",
"help": "The cell density in neurons/mm3. The volume occupied by each population can be customized (see xRange, yRange and zRange); otherwise the full network volume will be used (defined in netParams: sizeX, sizeY, sizeZ). density can be expressed as a function of normalized location (xnorm, ynorm or znorm), by providing a string with the variable and any common Python mathematical operators/functions. e.g. '1e5 * exp(-ynorm/2)'. ",
"hintText": "density in neurons/mm3",
"type": "str"
},
"gridSpacing": {
"label": "Grid spacing (um)",
"suggestions": "",
"help": "Fixed grid spacing between cells (in um). Cells will be placed in a grid, with the total number of cells be determined based on spacing and sizeX, sizeY, sizeZ. e.g. a spacing of 20 with sizeX=sizeY=sizeZ=100 will lead to 5*5*5=125 cells.",
"hintText": "fixed grid spacing",
"type": "int"
},
"cellModel": {
"label": "Cell model",
"help": "Can be either 1) an arbitrary cell model attribute/tag assigned to all cells in this population, and used later as a condition to apply specific cell properties. e.g. 'HH' (standard Hodkgin-Huxley type cell model) or 'Izhi2007' (Izhikevich point neuron model), 2) a point process artificial cell, with its parameters defined directly in this population entry, i.e. no need for cell propoerties (e.g. 'NetStim', VecStim', 'IntFire1')",
"suggestions": [
"VecStim",
"NetStim",
"IntFire1"
],
"type": "str"
},
"xRange": {
"label": "X-axis range (um)",
"help": "Range of neuron positions in x-axis (horizontal length), specified as a 2-element list [min, max] using absolute values in um (e.g.[100, 200]).",
"suggestions": "",
"hintText": "",
"type": "list(float)"
},
"xnormRange": {
"label": "X-axis normalized range (0-1)",
"help": "Range of neuron positions in x-axis (horizontal length), specified as a 2-element list [min, max] using normalized values between 0 and 1 as fraction of sizeX (e.g.[0.1,0.2]).",
"suggestions": "",
"hintText": "",
"default": [
0,
1
],
"type": "list(float)"
},
"yRange": {
"label": "Y-axis range (um)",
"help": "Range of neuron positions in y-axis (vertical height=cortical depth), specified as 2-element list [min, max] using absolute values in um (e.g.[100,200]).",
"suggestions": "",
"hintText": "",
"type": "list(float)"
},
"ynormRange": {
"label": "Y-axis normalized range (0-1)",
"help": "Range of neuron positions in y-axis (vertical height=cortical depth), specified as a 2-element list [min, max] using normalized values between 0 and 1 as fraction of sizeY (e.g.[0.1,0.2]).",
"suggestions": "",
"hintText": "",
"type": "list(float)"
},
"zRange": {
"label": "Z-axis range (um)",
"help": "Range of neuron positions in z-axis (horizontal depth), specified as a 2-element list [min, max] using absolute value in um (e.g.[100,200]).",
"suggestions": "",
"hintText": "",
"type": "list(float)"
},
"znormRange": {
"label": "Z-axis normalized range (0-1)",
"help": "Range of neuron positions in z-axis (horizontal depth), specified as a 2-element list [min, max] using normalized values between 0 and 1 as fraction of sizeZ (e.g.[0.1,0.2]).",
"suggestions": "",
"hintText": "",
"type": "list(float)"
},
"interval": {
"label": "Spike interval (ms)",
"help": "Spike interval in ms.",
"suggestions": "",
"hintText": "50",
"type": "float"
},
"rate": {
"label": "Firing rate (Hz)",
"help": "Firing rate in Hz (note this is the inverse of the NetStim interval property).",
"suggestions": "",
"hintText": "",
"type": "float"
},
"noise": {
"label": "Noise fraction (0-1)",
"help": "Fraction of noise in NetStim (0 = deterministic; 1 = completely random).",
"suggestions": "",
"hintText": "0.5",
"type": "list(float)"
},
"start": {
"label": "Start time (ms)",
"help": "Time of first spike in ms (default = 0).",
"suggestions": "",
"hintText": "0",
"type": "list(float)"
},
"number": {
"label": "Max number of spikes",
"help": "Max number of spikes generated (default = 1e12).",
"suggestions": "",
"hintText": "",
"type": "list(float)"
},
"seed": {
"label": "Randomizer seed (optional)",
"help": " Seed for randomizer (optional; defaults to value set in simConfig.seeds['stim'])",
"suggestions": "",
"hintText": "",
"type": "list(float)"
},
"spkTimes": {
"label": "Spike times",
"help": "List of spike times (only for 'VecStim') e.g. [1, 10, 40, 50], range(1,500,10), or any variable containing a Python list.",
"suggestions": "",
"hintText": "",
"type": "list(float)"
},
"pulses": {
"label": "Pulses",
"help": "List of spiking pulses (only for 'VecStim'); each item includes the start (ms), end (ms), rate (Hz), and noise (0 to 1) pulse parameters. ",
"suggestions": "",
"hintText": "",
"type": "list(float)"
}
}
},
"scale": {
"label": "scale factor",
"help": "Scale factor multiplier for number of cells (default: 1)",
"suggestions": "",
"hintText": "",
"default": 1,
"type": "float"
},
"shape": {
"label": "network shape",
"help": "Shape of network: 'cuboid', 'cylinder' or 'ellipsoid' (default: 'cuboid')",
"suggestions": "",
"hintText": "",
"options": [
"cuboid",
"cylinder",
"ellipsoid"
],
"default": "cuboid",
"type": "str"
},
"sizeX": {
"label": "x-dimension",
"help": "x-dimension (horizontal length) network size in um (default: 100)",
"suggestions": "",
"hintText": "",
"default": 100,
"type": "float"
},
"sizeY": {
"label": "y-dimension",
"help": "y-dimension (horizontal length) network size in um (default: 100)",
"suggestions": "",
"hintText": "",
"default": 100,
"type": "float"
},
"sizeZ": {
"label": "z-dimension",
"help": "z-dimension (horizontal length) network size in um (default: 100)",
"suggestions": "",
"hintText": "",
"default": 100,
"type": "float"
},
"rotateCellsRandomly": {
"label": "random rotation",
"help": "Random rotation of cells around y-axis [min,max] radians, e.g. [0, 3.0] (default: False)",
"suggestions": "",
"hintText": "",
"type": "list(float)"
},
"defaultWeight": {
"label": "default weight connection",
"help": "Default connection weight (default: 1)",
"suggestions": "",
"hintText": "",
"default": 1,
"type": "float"
},
"defaultDelay": {
"label": "default delay",
"help": "Default connection delay, in ms (default: 1)",
"suggestions": "",
"hintText": "",
"default": 1,
"type": "float"
},
"propVelocity": {
"label": "conduction velocity",
"help": "Conduction velocity in um/ms (e.g. 500 um/ms = 0.5 m/s) (default: 500)",
"suggestions": "",
"hintText": "",
"default": 500,
"type": "float"
},
"scaleConnWeight": {
"label": "connection weight scale factor",
"help": "Connection weight scale factor (excludes NetStims) (default: 1)",
"suggestions": "",
"hintText": "",
"default": 1,
"type": "float"
},
"scaleConnWeightNetStims": {
"label": "connection weight scale factor for NetStims",
"help": "Connection weight scale factor for NetStims (default: 1)",
"suggestions": "",
"hintText": "",
"default": 1,
"type": "float"
},
"scaleConnWeightModels": {
"label": "Connection weight scale factor for each cell model",
"help": "Connection weight scale factor for each cell model, e.g. {'HH': 0.1, 'Izhi': 0.2} (default: {})",
"suggestions": "",
"hintText": "",
"type": "dict"
},
"popTagsCopiedToCells": {
"label": "",
"help": "List of tags that will be copied from the population to the cells (default: ['pop', 'cellModel', 'cellType'])}",
"suggestions": "",
"hintText": "",
"type": "list(float)"
},
# ---------------------------------------------------------------------------------------------------------------------
# netParams.cellParams
# ---------------------------------------------------------------------------------------------------------------------
"cellParams": {
"label": "Cell Parameters",
"suggestions": "",
"help": "",
"hintText": "",
"children": {
"conds": {
"label": "Conds",
"suggestions": "",
"help": "",
"hintText": "",
"children": {
"pop": {
"label": "Population",
"help": "Apply the cell rule only to cells belonging to this population (or list of populations).",
"suggestions": "",
"hintText": "",
"type": "list(str)"
},
"cellType": {
"label": "Cell type",
"suggestions": "",
"help": "Apply the cell rule only to cells with this cell type attribute/tag.",
"hintText": "",
"type": "list(str)"
},
"cellModel": {
"label": "Cell model",
"suggestions": "",
"help": "Apply the cell rule only to cells with this cell model attribute/tag.",
"hintText": "",
"type": "list(str)"
},
"x": {
"label": "Range of x-axis locations",
"suggestions": "",
"help": "Apply the cell rule only to cells within these x-axis locations.",
"hintText": ""
},
"y": {
"label": "Range of y-axis locations",
"suggestions": "",
"help": "Apply the cell rule only to cells within these y-axis locations.",
"hintText": ""
},
"z": {
"label": "Range of z-axis locations",
"suggestions": "",
"help": "Apply the cell rule only to cells within these z-axis locations.",
"hintText": ""
},
"xnorm": {
"label": "Range of normalized x-axis locations",
"suggestions": "",
"help": "Apply the cell rule only to cells within these normalized x-axis locations.",
"hintText": ""
},
"ynorm": {
"label": "Range of normalized y-axis locations",
"suggestions": "",
"help": "Apply the cell rule only to cells within these normalized y-axis locations.",
"hintText": ""
},
"znorm": {
"label": "Range of normalized z-axis locations",
"suggestions": "",
"help": "Apply the cell rule only to cells within these normalized z-axis locations.",
"hintText": ""
}
}
},
"secs": {
"label": "Sections",
"suggestions": "",
"help": "",
"hintText": "",
"children": {
"geom": {
"label": "Cell geometry",
"suggestions": "",
"help": "",
"hintText": "",
"children": {
"diam": {
"label": "Diameter (um)",
"default": 10,
"suggestions": "",
"help": "",
"hintText": "10",
"type": "float"
},
"L": {
"label": "Length (um)",
"default": 50,
"suggestions": "",
"help": "",
"hintText": "50",
"type": "float"
},
"Ra": {
"label": "Axial resistance, Ra (ohm-cm)",
"default": 100,
"suggestions": "",
"help": "",
"hintText": "100",
"type": "float"
},
"cm": {
"label": "Membrane capacitance, cm (uF/cm2)",
"suggestions": "",
"help": "",
"hintText": "1",
"type": "float"
},
"pt3d": {
"label": "3D points",
"suggestions": "",
"help": "",
"hintText": "",
"type": "list(list(float))"
},
"nseg": {
"label": "Number of segments, nseg",
"default": 1,
"suggestions": "",
"help": "",
"hintText": "1",
"type": "float"
}
},
"mechs": {
"label": "Mechanisms",
"help": "Dictionary of density/distributed mechanisms, including the name of the mechanism (e.g. hh or pas) and a list of properties of the mechanism (e.g. {'g': 0.003, 'e': -70}).",
"suggestions": "",
"hintText": "",
"type": "float"
},
"ions": {
"label": "Ions",
"help": "Dictionary of ions, including the name of the ion (e.g. hh or pas) and a list of properties of the ion (e.g. {'e': -70}).",
"suggestions": "",
"hintText": ""
},
"pointps": {
"label": "Point processes",
"help": "Dictionary of point processes (excluding synaptic mechanisms). The key contains an arbitrary label (e.g. 'Izhi') The value contains a dictionary with the point process properties (e.g. {'mod':'Izhi2007a', 'a':0.03, 'b':-2, 'c':-50, 'd':100, 'celltype':1}).",
"suggestions": "",
"hintText": "",
"children": {
"mod": {
"label": "Point process name",
"help": "The name of the NEURON mechanism, e.g. 'Izhi2007a'",
"suggestions": "",
"hintText": "",
"type": "float"
},
"loc": {
"label": "Location (0-1)",
"help": "Section location where to place synaptic mechanism, e.g. 1.0, default=0.5.",
"suggestions": "",
"hintText": "",
"type": "float"
},
"vref": {
"label": "Point process variable for voltage (optional)",
"help": "Internal mechanism variable containing the cell membrane voltage, e.g. 'V'.",
"suggestions": "",
"hintText": "",
"type": "float"
},
"synList": {
"label": "Point process list of synapses (optional)",
"help": "list of internal mechanism synaptic mechanism labels, e.g. ['AMPA', 'NMDA', 'GABAB'].",
"suggestions": "",
"hintText": "",
"type": "float"
}
},
"vinit": {
"label": "Initial membrance voltage, vinit (mV)",
"help": "(optional) Initial membrane voltage (in mV) of the section (default: -65).e.g. cellRule['secs']['soma']['vinit'] = -72",
"suggestions": "",
"hintText": ""
},
"spikeGenLoc": {
"label": "Spike generation location (0-1)",
"help": "(optional) Indicates that this section is responsible for spike generation (instead of the default 'soma'), and provides the location (segment) where spikes are generated.e.g. cellRule['secs']['axon']['spikeGenLoc'] = 1.0.",
"suggestions": "",
"hintText": ""
},
"threshold": {
"label": "Spike threshold voltage (mV)",
"help": "(optional) Threshold voltage (in mV) used to detect a spike originating in this section of the cell. If omitted, defaults to netParams.defaultThreshold = 10.0.e.g. cellRule['secs']['soma']['threshold'] = 5.0.",
"suggestions": "",
"hintText": ""
}
},
"secLists": {
"label": "Section lists (optional) ",
"help": "Dictionary of sections lists (e.g. {'all': ['soma', 'dend']})",
"suggestions": "",
"hintText": ""
}
},
"topol": {
"label": "Topology",
"help": "Topological properties, including parentSec (label of parent section), parentX (parent location where to make connection) and childX (current section child location where to make connection).",
"suggestions": "",
"hintText": "",
"children": {
"parentSec": {
"label": "Parent Section",
"suggestions": [
"soma"
],
"help": "label of parent section",
"hintText": "soma",
"type": "str"
},
"parentX": {
"label": "Parent connection location",
"suggestions": [
0,
1
],
"help": "Parent location where to make connection",
"hintText": "1",
"type": "float"
},
"childX": {
"label": "Child connection location",
"suggestions": [
0,
1
],
"help": "Current section child location where to make connection",
"hintText": "1",
"type": "float"
}
}
}
}
}
}
},
# ---------------------------------------------------------------------------------------------------------------------
# netParams.synMechParams
# ---------------------------------------------------------------------------------------------------------------------
"synMechParams": {
"label": "Synaptic mechanism parameters",
"suggestions": "",
"help": "",
"hintText": "",
"children": {
"mod": {
"label": "NMODL mechanism name",
"help": "The NMODL mechanism name (e.g. 'ExpSyn'); note this does not always coincide with the name of the mod file.",
"suggestions": "",
"options": [
"ExpSyn",
"Exp2Syn"
],
"hintText": "",
"type": "str"
},
"selfNetCon": {
"label": "Self NetCon parameters",
"help": "Dict with parameters of NetCon between the cell voltage and the synapse, required by some synaptic mechanisms such as the homeostatic synapse (hsyn). e.g. 'selfNetCon': {'sec': 'soma' , threshold: -15, 'weight': -1, 'delay': 0} (by default the source section, 'sec' = 'soma').",
"suggestions": "",
"hintText": ""
},
"tau1": {
"label": "Time constant for exponential 1 (ms)",
"help": "Define the time constant for the first exponential.",
"suggestions": "",
"hintText": "1",
"type": "float"
},
"tau2": {
"label": "Time constant for exponential 2 (ms)",
"help": "Define the time constant for the second exponential.",
"suggestions": "",
"hintText": "5",
"type": "float"
},
"e": {
"label": "Reversal potential (mV)",
"help": "Reversal potential of the synaptic receptors.",
"suggestions": "",
"hintText": "0",
"type": "float"
},
"i": {
"label": "synaptic current (nA)",
"help": "Synaptic current in nA.",
"suggestions": "",
"hintText": "10",
"type": "float"
}
}
},
# ---------------------------------------------------------------------------------------------------------------------
# netParams.connParams
# ---------------------------------------------------------------------------------------------------------------------
"connParams": {
"label": "Connectivity parameters",
"suggestions": "",
"help": "",
"hintText": "",
"children": {
"preConds": {
"label": "Conditions for the presynaptic cells",
"help": "Presynaptic cell conditions defined using attributes/tags and the required value e.g. {'cellType': 'PYR'}. Values can be lists, e.g. {'pop': ['Exc1', 'Exc2']}. For location properties, the list values correspond to the min and max values, e.g. {'ynorm': [0.1, 0.6]}.",
"suggestions": "",
"hintText": "",
"children": {
"pop": {
"label": "Population (multiple selection available)",
"suggestions": "",
"help": "Cells belonging to this population (or list of populations) will be connected pre-synaptically.",
"hintText": ""
},
"cellType": {
"label": "Cell type (multiple selection available)",
"suggestions": "",
"help": "Ccells with this cell type attribute/tag will be connected pre-synaptically.",
"hintText": ""
},
"cellModel": {
"label": "Cell model (multiple selection available)",
"suggestions": "",
"help": "Cells with this cell model attribute/tag will be connected pre-synaptically.",
"hintText": ""
},
"x": {
"label": "Range of x-axis locations",
"suggestions": "",
"help": "Cells within these x-axis locations will be connected pre-synaptically.",
"hintText": ""
},
"y": {
"label": "Range of y-axis locations",
"suggestions": "",
"help": "Cells within these y-axis locations will be connected pre-synaptically.",
"hintText": ""
},
"z": {
"label": "Range of z-axis locations",
"suggestions": "",
"help": "Cells within these z-axis locations will be connected pre-synaptically..",
"hintText": ""
},
"xnorm": {
"label": "Range of normalized x-axis locations",
"suggestions": "",
"help": "Cells within these normalized x-axis locations will be connected pre-synaptically.",
"hintText": ""
},
"ynorm": {
"label": "Range of normalized y-axis locations",
"suggestions": "",
"help": "Cells within these normalized y-axis locations will be connected pre-synaptically.",
"hintText": ""
},
"znorm": {
"label": "Range of normalized z-axis locations",
"suggestions": "",
"help": "Cells within these normalized z-axis locations will be connected pre-synaptically.",
"hintText": ""
}
}
},
"postConds": {
"label": "Conditions for the postsynaptic cells",
"help": "Defined as a dictionary with the attributes/tags of the postsynaptic cell and the required values e.g. {'cellType': 'PYR'}. Values can be lists, e.g. {'pop': ['Exc1', 'Exc2']}. For location properties, the list values correspond to the min and max values, e.g. {'ynorm': [0.1, 0.6]}.",
"suggestions": "",
"hintText": "",
"children": {
"pop": {
"label": "Population (multiple selection available)",
"suggestions": "",
"help": "Cells belonging to this population (or list of populations) will be connected post-synaptically.",
"hintText": ""
},
"cellType": {
"label": "Cell type (multiple selection available)",
"suggestions": "",
"help": "Ccells with this cell type attribute/tag will be connected post-synaptically.",
"hintText": ""
},
"cellModel": {
"label": "Cell model (multiple selection available)",
"suggestions": "",
"help": "Cells with this cell model attribute/tag will be connected post-synaptically.",
"hintText": ""
},
"x": {
"label": "Range of x-axis locations",
"suggestions": "",
"help": "Cells within these x-axis locations will be connected post-synaptically.",
"hintText": ""
},
"y": {
"label": "Range of y-axis locations",
"suggestions": "",
"help": "Cells within these y-axis locations will be connected post-synaptically.",
"hintText": ""
},
"z": {
"label": "Range of z-axis locations",
"suggestions": "",
"help": "Cells within these z-axis locations will be connected post-synaptically..",
"hintText": ""
},
"xnorm": {
"label": "Range of normalized x-axis locations",
"suggestions": "",
"help": "Cells within these normalized x-axis locations will be connected post-synaptically.",
"hintText": ""
},
"ynorm": {
"label": "Range of normalized y-axis locations",
"suggestions": "",
"help": "Cells within these normalized y-axis locations will be connected post-synaptically.",
"hintText": ""
},
"znorm": {
"label": "Range of normalized z-axis locations",
"suggestions": "",
"help": "Cells within these normalized z-axis locations will be connected post-synaptically.",
"hintText": ""
}
}
},
"sec": {
"label": "Postsynaptic neuron section",
"help": "Name of target section on the postsynaptic neuron (e.g. 'soma'). If omitted, defaults to 'soma' if exists, otherwise to first section in the cell sections list. If synsPerConn > 1, a list of sections or sectionList can be specified, and synapses will be distributed uniformly along the specified section(s), taking into account the length of each section.",
"suggestions": "",
"hintText": "soma",
"type": "list(str)"
},
"loc": {
"label": "Postsynaptic neuron location (0-1)",
"help": "Location of target synaptic mechanism (e.g. 0.3). If omitted, defaults to 0.5. Can be single value, or list (if have synsPerConn > 1) or list of lists (If have both a list of synMechs and synsPerConn > 1).",
"suggestions": "",
"hintText": "0.5",
"type": "list(float)"
},
"synMech": {
"label": "Synaptic mechanism",
"help": "Label (or list of labels) of target synaptic mechanism on the postsynaptic neuron (e.g. 'AMPA' or ['AMPA', 'NMDA']). If omitted employs first synaptic mechanism in the cell synaptic mechanisms list. If have list, a separate connection is created to each synMech; and a list of weights, delays and or locs can be provided.",
"suggestions": "",
"hintText": ""
},
"synsPerConn": {
"label": "Number of individual synaptic contacts per connection",
"help": "Number of individual synaptic contacts (synapses) per cell-to-cell connection (connection). Can be defined as a function (see Functions as strings). If omitted, defaults to 1.",
"suggestions": "",
"hintText": "",
"default": 1
},
"weight": {
"label": "Weight of synaptic connection",
"help": "Strength of synaptic connection (e.g. 0.01). Associated to a change in conductance, but has different meaning and scale depending on the synaptic mechanism and cell model. Can be defined as a function (see Functions as strings). If omitted, defaults to netParams.defaultWeight = 1.",
"suggestions": "",
"hintText": "",
"type": "func"
},
"delay": {
"label": "Connection delay (ms)",
"help": "Time (in ms) for the presynaptic spike to reach the postsynaptic neuron. Can be defined as a function (see Functions as strings). If omitted, defaults to netParams.defaultDelay = 1.",
"suggestions": "",
"hintText": "",
"type": "func"
},
"probability": {
"label": "Probability of connection (0-1)",
"help": "Probability of connection between each pre and postsynaptic cell (0 to 1). Can be a string that defines as a function, e.g. '0.1*dist_3D+uniform(0.2,0.4)' (see Documentation on 'Functions as strings'). Overrides the convergence, divergence and fromList parameters.",
"suggestions": "0.1",
"hintText": "",
"type": "func"
},
"convergence": {
"label": "Convergence",
"help": "Number of pre-synaptic cells connected to each post-synaptic cell. Can be a string that defines as a function, e.g. '2*dist_3D+uniform(2,4)' (see Documentation on 'Functions as strings'). Overrides the divergence and fromList parameters.",
"suggestions": "5",
"hintText": "",
"type": "func"
},
"divergence": {
"label": "Divergence",
"help": "Number of post-synaptic cells connected to each pre-synaptic cell. Can be a string that defines as a function, e.g. '2*dist_3D+uniform(2,4)' (see Documentation on 'Functions as strings'). Overrides the fromList parameter.",
"suggestions": "5",
"hintText": "",
"type": "func"
},
"connList": {
"label": "Explicit list of one-to-one connections",
"help": "Each connection is indicated with relative ids of cell in pre and post populations, e.g. [[0,1],[3,1]] creates a connection between pre cell 0 and post cell 1; and pre cell 3 and post cell 1. Weights, delays and locs can also be specified as a list for each of the individual cell connection. These lists can be 2D or 3D if combined with multiple synMechs and synsPerConn > 1 (the outer dimension will correspond to the connList).",
"suggestions": "",
"hintText": "list(list(float))"
},
"connFunc": {
"label": "Internal connectivity function to use (not required)",
"help": "Automatically set to probConn, convConn, divConn or fromList, when the probability, convergence, divergence or connList parameters are included, respectively. Otherwise defaults to fullConn, ie. all-to-all connectivity.",
"suggestions": "",
"hintText": ""
},
"shape": {
"label": "Weight shape",
"help": "Modifies the conn weight dynamically during the simulation based on the specified pattern. Contains a dictionary with the following fields: 'switchOnOff' - times at which to switch on and off the weight, 'pulseType' - type of pulse to generate; either 'square' or 'gaussian', 'pulsePeriod' - period (in ms) of the pulse, 'pulseWidth' - width (in ms) of the pulse.",
"suggestions": "",
"hintText": ""
},
"plasticity": {
"label": "Plasticity mechanism",
"help": "Requires 2 fields: mech to specifiy the name of the plasticity mechanism, and params containing a dictionary with the parameters of the mechanism, e.g. {'mech': 'STDP', 'params': {'hebbwt': 0.01, 'antiwt':-0.01, 'wmax': 50, 'RLon': 1 'tauhebb': 10}}.",
"suggestions": "",
"hintText": "",
"type": "dict"
}
}
},
# ---------------------------------------------------------------------------------------------------------------------
# netParams.stimSourceParams
# ---------------------------------------------------------------------------------------------------------------------
"stimSourceParams": {
"label": "Stimulation source parameters",
"suggestions": "",
"help": "",
"hintText": "",
"children": {
"type": {
"label": "Point process used as stimulator",
"help": "Point process used as stimulator; allowed values: 'IClamp', 'VClamp', 'SEClamp', 'NetStim' and 'AlphaSynapse'. Note that NetStims can be added both using this method, or by creating a population of 'cellModel': 'NetStim' and adding the appropriate connections.",
"suggestions": "",
"hintText": "",
"default": "IClamp",
"type": "str"
},
"dur": {
"label": "Current clamp duration (ms)",
"help": "Duration of current clamp injection in ms",
"suggestions": "",
"hintText": "10",
"type": "float"
},
"amp": {
"label": "Current clamp amplitude (nA)",
"help": "Amplitude of current injection in nA",
"suggestions": "",
"hintText": "10",
"type": "float"
},
"del": {
"label": "Current clamp delay (ms)",
"help": "Delay (time when turned on after simulation starts) of current clamp in ms.",
"suggestions": "",
"hintText": "5",
"type": "float"
},
"vClampAmp": {
"label": "Current clamp amplitude (nA)",
"help": "Voltage clamp with three levels. Clamp is on at time 0, and off at time dur[0]+dur[1]+dur[2].",
"suggestions": "",
"hintText": "10",
"type": "list(float)"
},
"vClampDur": {
"label": "Current clamp delay (ms)",
"help": "Voltage clamp with three levels. Clamp is on at time 0, and off at time dur[0]+dur[1]+dur[2].",
"suggestions": "",
"hintText": "5",
"type": "list(float)"
},
"interval": {
"label": "Interval between spikes (ms)",
"help": "Define the mean time interval between spike.",
"suggestions": "10",
"hintText": "",
"type": "float"
},
"rate": {
"label": "Firing rate (Hz)",
"help": "Firing rate in Hz (note this is the inverse of the NetStim interval property).",
"suggestions": "",
"hintText": "",
"type": "float"
},
"rstim": {
"label": "Voltage clamp stimulation resistance",
"help": "Voltage clamp stimulation resistance.",
"suggestions": "",
"hintText": "",
"type": "float"
},
"gain": {
"label": "Voltage clamp amplifier gain",
"help": "Voltage clamp amplifier gain.",
"suggestions": "",
"hintText": "",
"type": "float"
},
"number": {
"label": "Maximum number of spikes",
"help": "Maximum number of spikes generated by the NetStim.",
"suggestions": "",
"hintText": "",
"type": "float"
},
"start": {
"label": "Start time of first spike",
"help": "Define the start time for the first spike.",
"suggestions": "0",
"hintText": "",
"type": "float"
},
"noise": {
"label": "Noise/randomness fraction (0-1)",
"help": "Fractional noise, 0 <= noise <= 1, means that an interval between spikes consists of a fixed interval of duration (1 - noise)*interval plus a negexp interval of mean duration noise*interval. Note that the most likely negexp interval has duration 0.",
"suggestions": "0.5",
"hintText": "",
"type": "float"
},
"tau1": {
"label": "Voltage clamp tau1",
"help": "Voltage clamp tau1.",
"suggestions": "",
"hintText": "",
"type": "float"
},
"tau2": {
"label": "Voltage clamp tau2",
"help": "Voltage clamp tau2.",
"suggestions": "",
"hintText": "",
"type": "float"
},
"i": {
"label": "Voltage clamp current (nA)",
"help": "Voltage clamp injected current in nA.",
"suggestions": "",
"hintText": "",
"type": "float"
},
"onset": {
"label": "Alpha synapse onset time (ms)",
"help": "Alpha synapse onset time.",
"suggestions": "",
"hintText": "",
"type": "float"
},
"tau": {
"label": "Alpha synapse time constant (ms)",
"help": "Alpha synapse time constant (ms).",
"suggestions": "",
"hintText": "",
"type": "float"
},
"gmax": {
"label": "Alpha synapse maximum conductance",
"help": "Alpha synapse maximum conductance.",
"suggestions": "",
"hintText": "",
"type": "float"
},
"e": {
"label": "Alpha synapse equilibrium potential",
"help": "Alpha synapse equilibrium potential.",
"suggestions": "",
"hintText": "",
"type": "float"
},
"rs": {
"label": "Voltage clamp resistance (MOhm)",
"help": "Voltage clamp resistance (MOhm).",
"suggestions": "",
"hintText": "",
"type": "float"
},
"vc": {
"label": "Voltage clamp reference voltage (mV)",
"help": "Voltage clamp reference voltage (mV).",
"suggestions": "",
"hintText": "",
"type": "float"
}
}
},
# ---------------------------------------------------------------------------------------------------------------------
# netParams.stimTargetParams
# ---------------------------------------------------------------------------------------------------------------------
"stimTargetParams": {
"label": "Stimulation target parameters",
"suggestions": "",
"help": "",
"hintText": "",
"children": {
"source": {
"label": "Stimulation source",
"help": "Label of the stimulation source (e.g. 'electrode_current').",
"suggestions": "",
"hintText": ""
},
"conds": {
"label": "Conditions of cells where the stimulation will be applied",
"help": "Conditions of cells where the stimulation will be applied. Can include a field 'cellList' with the relative cell indices within the subset of cells selected (e.g. 'conds': {'cellType':'PYR', 'y':[100,200], 'cellList': [1,2,3]}).",
"suggestions": "",
"hintText": "",
"children": {
"pop": {
"label": "Target population",
"help": "Populations that will receive the stimulation e.g. {'pop': ['Exc1', 'Exc2']}",
"suggestions": "",
"hintText": "",
"type": "list(float)"
},
"cellType": {
"label": "Target cell type",
"suggestions": "",
"help": "Cell types that will receive the stimulation",
"hintText": "",
"type": "str"
},
"cellModel": {
"label": "Target cell model",
"help": "Cell models that will receive the stimulation.",
"suggestions": "",
"type": "str"
},
"x": {
"label": "Range of x-axis locations",
"suggestions": "",
"help": "Cells within this x-axis locations will receive stimulation",
"hintText": ""
},
"y": {
"label": "Range of y-axis locations",
"suggestions": "",
"help": "Cells within this y-axis locations will receive stimulation",
"hintText": ""
},
"z": {
"label": "Range of z-axis locations",
"suggestions": "",
"help": "Cells within this z-axis locations will receive stimulation",
"hintText": ""
},
"xnorm": {
"label": "Range of normalized x-axis locations",
"suggestions": "",
"help": "Cells withing this normalized x-axis locations will receive stimulation",
"hintText": ""
},
"ynorm": {
"label": "Range of normalized y-axis locations",
"suggestions": "",
"help": "Cells within this normalized y-axis locations will receive stimulation",
"hintText": ""
},
"znorm": {
"label": "Range of normalized z-axis locations",
"suggestions": "",
"help": "Cells within this normalized z-axis locations will receive stimulation",
"hintText": ""
},
"cellList": {
"label": "Target cell global indices (gids)",
"help": "Global indices (gids) of neurons to receive stimulation. ([1, 8, 12])",
"suggestions": "",
"hintText": "",
"type": "list(float)"
},
}
},
"sec": {
"label": "Target section",
"help": "Target section (default: 'soma').",
"suggestions": "",
"hintText": "",
"type": "str"
},
"loc": {
"label": "Target location",
"help": "Target location (default: 0.5). Can be defined as a function (see Functions as strings).",
"suggestions": "",
"hintText": "",
"type": "float"
},
"synMech": {
"label": "Target synaptic mechanism",
"help": "Synaptic mechanism label to connect NetStim to. Optional; only for NetStims.",
"suggestions": "",
"hintText": ""
},
"weight": {
"label": "Weight of connection between NetStim and cell",
"help": "Weight of connection between NetStim and cell. Optional; only for NetStims. Can be defined as a function (see Functions as strings).",
"suggestions": "",
"hintText": ""
},
"delay": {
"label": "Delay of connection between NetStim and cell",
"help": "Delay of connection between NetStim and cell (default: 1). Optional; only for NetStims. Can be defined as a function (see Functions as strings).",
"suggestions": "",
"hintText": ""
},
"synsPerConn": {
"label": "Number of synaptic contacts per connection between NetStim and cell",
"help": "Number of synaptic contacts of connection between NetStim and cell (default: 1). Optional; only for NetStims. Can be defined as a function (see Functions as strings).",
"suggestions": "",
"hintText": ""
}
}
},
# ---------------------------------------------------------------------------------------------------------------------
# netParams.importCellParams
# ---------------------------------------------------------------------------------------------------------------------
"importCellParams": {
"label": "Import cell from .hoc or .py templates",
"suggestions": "",
"help": "",
"hintText": "",
"children": {
"fileName": {
"label": "Absolute path to file",
"help": "Absolute path to .hoc or .py template file.",
"suggestions": "",
"hintText": "",
"type": "str"
},
"cellName": {
"label": "Cell template/class name",
"help": "Template or class name defined inside the .hoc or .py file",
"suggestions": "",
"hintText": "",
"type": "str"
},
"label": {
"label": "Cell rule label",
"help": "Give a name to this cell rule.",
"suggestions": "",
"hintText": "",
"type": "str"
},
"importSynMechs": {
"label": "Import synaptic mechanisms",
"help": "If true, synaptic mechanisms will also be imported from the file. (default: False)",
"suggestions": "",
"hintText": "",
"type": "bool"
},
"compileMod": {
"label": "Compile mod files",
"help": "If true, mod files will be compiled before importing the cell. (default: false)",
"suggestions": "",
"hintText": "",
"type": "bool"
},
"modFolder": {
"label": "Path to mod folder",
"help": "Define the absolute path to the folder containing the mod files.",
"suggestions": "",
"hintText": "",
"type": "str"
},
}
}
}
},
# ---------------------------------------------------------------------------------------------------------------------
# simConfig
# ---------------------------------------------------------------------------------------------------------------------
"simConfig": {
"label": "Simulation Configuration",
"suggestions": "",
"help": "",
"hintText": "",
"children": {
"simLabel": {
"label": "Simulation label",
"help": "Choose a label for this simulation",
"suggestions": "",
"type": "str"
},
"duration": {
"label": "Duration (ms)",
"help": "Simulation duration in ms (default: 1000)",
"suggestions": "",
"default": 1000,
"type": "float"
},
"dt": {
"label": "Time step, dt",
"help": "Simulation time step in ms (default: 0.1)",
"suggestions": "",
"default": 0.025,
"type": "float"
},
"seeds": {
"label": "Randomizer seeds",
"help": "Dictionary with random seeds for connectivity, input stimulation, and cell locations (default: {'conn': 1, 'stim': 1, 'loc': 1}).",
"suggestions": "",
"type": "dict"
},
"addSynMechs": {
"label": "Add synaptic mechanisms",
"help": "Whether to add synaptic mechanisms or not (default: True).",
"suggestions": "",
"type": "bool"
},
"includeParamsLabel": {
"label": "Include parameter rule label",
"help": "Include label of parameters rule that created that cell, conn or stim (default: True).",
"suggestions": "",
"type": "bool"
},
"timing": {
"label": "Show timing",
"help": "Show and record timing of each process (default: True).",
"suggestions": "",
"type": "bool"
},
"verbose": {
"label": "Verbose mode",
"help": "Show detailed messages (default: False).",
"suggestions": "",
"type": "bool"
},
"saveFolder": {
"label": "Output folder",
"help": "Path where to save output data (default: '')",
"suggestions": "",
"type": "str"
},
"filename": {
"label": "Output file name",
"help": "Name of file to save model output (default: 'model_output')",
"suggestions": "",
"default": "model_output",
"type": "str"
},
"saveDataInclude": {
"label": "Data to include in output file",
"help": "Data structures to save to file (default: ['netParams', 'netCells', 'netPops', 'simConfig', 'simData'])",
"suggestions": "",
"type": "list(str)"
},
"timestampFilename": {
"label": "Add timestamp to file name",
"help": "Add timestamp to filename to avoid overwriting (default: False)",
"suggestions": "",
"type": "bool"
},
"savePickle": {
"label": "Save as Pickle",
"help": "Save data to pickle file (default: False).",
"suggestions": "",
"type": "bool"
},
"saveJson": {
"label": "Save as JSON",
"help": "Save dat to json file (default: False).",
"suggestions": "",
"type": "bool"
},
"saveMat": {
"label": "Save as MAT",
"help": "Save data to mat file (default: False).",
"suggestions": "",
"type": "bool"
},
"saveHDF5": {
"label": "Save as HDF5",
"help": "Save data to save to HDF5 file (under development) (default: False).",
"suggestions": "",
"type": "bool"
},
"saveDpk": {
"label": "Save as DPK",
"help": "Save data to .dpk pickled file (default: False).",
"suggestions": "",
"type": "bool"
},
"checkErrors": {
"label": "Check parameter errors",
"help": "check for errors (default: False).",
"suggestions": "",
"type": "bool"
},
"checkErrorsVerbose": {
"label": "Check parameter errors verbose mode",
"help": "check errors vervose (default: False)",
"suggestions": "",
"type": "bool"
},
"backupCfgFile": {
"label": "Copy simulation configuration file to this folder:",
"help": "Copy cfg file to folder, eg. ['cfg.py', 'backupcfg/'] (default: []).",
"suggestions": "",
"type": "list(str)"
},
"recordCells": {
"label": "Cells to record traces from",
"help": "List of cells from which to record traces. Can include cell gids (e.g. 5), population labels (e.g. 'S' to record from one cell of the 'S' population), or 'all', to record from all cells. NOTE: All cells selected in the include argument of simConfig.analysis['plotTraces'] will be automatically included in recordCells. (default: []).",
"suggestions": "",
"type": "list(float)"
},
"recordTraces": {
"label": "Traces to record from cells",
"help": "Dict of traces to record (default: {} ; example: {'V_soma': {'sec':'soma','loc':0.5,'var':'v'} }).",
"suggestions": "",
"type": "dict(dict)",
"default": "{\"V_soma\": {\"sec\": \"soma\", \"loc\": 0.5, \"var\": \"v\"}}"
},
"saveCSV": {
"label": "Save as CSV",
"help": "save cvs file (under development) (default: False)",
"suggestions": "",
"type": "bool"
},
"saveDat": {
"label": "Save as DAT ",
"help": "save .dat file (default: False)",
"suggestions": "",
"type": "bool"
},
"saveCellSecs": {
"label": "Store cell sections after simulation",
"help": "Save cell sections after gathering data from nodes post simulation; set to False to reduce memory required (default: True)",
"suggestions": "",
"type": "bool"
},
"saveCellConns": {
"label": "Store cell connections after simulation",
"help": "Save cell connections after gathering data from nodes post simulation; set to False to reduce memory required (default: True)",
"suggestions": "",
"type": "bool"
},
"recordStim": {
"label": "Record spikes of artificial stimulators (NetStims and VecStims)",
"help": "Record spikes of NetStims and VecStims (default: False).",
"suggestions": "",
"type": "bool"
},
"recordLFP": {
"label": "Record LFP electrode locations",
"help": "3D locations of local field potential (LFP) electrodes, e.g. [[50, 100, 50], [50, 200]] (default: False).",
"suggestions": "",
"type": "list(list(float))"
},
"saveLFPCells": {
"label": "Store LFP of individual cells",
"help": "Store LFP generated individually by each cell in sim.allSimData['LFPCells'].",
"suggestions": "",
"type": "bool"
},
"recordStep": {
"label": "Time step for data recording (ms)",
"help": "Step size in ms for data recording (default: 0.1).",
"suggestions": "",
"default": 0.1,
"type": "float"
},
"printRunTime": {
"label": "Interval to print run time at (s)",
"help": "Print run time at interval (in sec) specified here (eg. 0.1) (default: False).",
"suggestions": "",
"type": "float"
},
"printSynsAfterRule": {
"label": "Print total connections",
"help": "Print total connections after each conn rule is applied.",
"suggestions": "",
"type": "bool"
},
"printPopAvgRates": {
"label": "Print population average firing rates",
"help": "Print population avg firing rates after run (default: False).",
"suggestions": "",
"type": "bool"
},
"connRandomSecFromList": {
"label": "Select random sections from list for connection",
"help": "Select random section (and location) from list even when synsPerConn=1 (default: True).",
"suggestions": "",
"type": "bool"
},
"compactConnFormat": {
"label": "Use compact connection format (list instead of dicT)",
"help": "Replace dict format with compact list format for conns (need to provide list of keys to include) (default: False).",
"suggestions": "",
"type": "bool"
},
"gatherOnlySimData": {
"label": "Gather only simulation output data",
"help": "Omits gathering of net and cell data thus reducing gatherData time (default: False).",
"suggestions": "",
"type": "bool"
},
"createPyStruct": {
"label": "Create Python structure",
"help": "Create Python structure (simulator-independent) when instantiating network (default: True).",
"suggestions": "",
"type": "bool"
},
"createNEURONObj": {
"label": "Create NEURON objects",
"help": "Create runnable network in NEURON when instantiating netpyne network metadata (default: True).",
"suggestions": "",
"type": "bool"
},
"cvode_active": {
"label": "use CVode",
"help": "Use CVode variable time step (default: False).",
"suggestions": "",
"type": "bool"
},
"cache_efficient": {
"label": "use CVode cache_efficient",
"help": "Use CVode cache_efficient option to optimize load when running on many cores (default: False).",
"suggestions": "",
"type": "bool"
},
"hParams": {
"label": "Set global parameters (temperature, initial voltage, etc)",
"help": "Dictionary with parameters of h module (default: {'celsius': 6.3, 'v_init': -65.0, 'clamp_resist': 0.001}).",
"suggestions": "",
"type": "dict"
},
"saveTxt": {
"label": "Save as TXT",
"help": "Save data to txt file (under development) (default: False)",
"suggestions": "",
"type": "bool"
},
"saveTiming": {
"label": "Save timing data to file",
"help": " Save timing data to pickle file (default: False).",
"suggestions": "",
"type": "bool"
},
# ---------------------------------------------------------------------------------------------------------------------
# simConfig.analysis
# ---------------------------------------------------------------------------------------------------------------------
"analysis": {
"label": "Analysis",
"suggestions": "",
"help": "",
"hintText": "",
"children": {
"plotRaster": {
"label": "Raster plot",
"suggestions": "",
"help": "Plot raster (spikes over time) of network cells.",
"hintText": "",
"children": {
"include": {
"label": "Cells to include",
"suggestions": "",
"help": "List of cells to include (['all'|,'allCells'|,'allNetStims'|,120|,'L4'|,('L2', 56)|,('L5',[4,5,6])])",
"hintText": "",
"type": "str"
},
"timeRange": {
"label": "Time range [min,max] (ms)",
"suggestions": "",
"help": "Time range of spikes shown; if None shows all ([start,stop])",
"hintText": "",
"type": "list(float)"
},
"maxSpikes": {
"label": "Maximum number of spikes to plot",
"suggestions": "",
"help": "maximum number of spikes that will be plotted (int).",
"hintText": "",
"type": "float"
},
"orderBy": {
"label": "Order by",
"suggestions": "",
"help": "Unique numeric cell property to order y-axis by, e.g. 'gid', 'ynorm', 'y' ('gid'|'y'|'ynorm'|...)",
"hintText": "",
"options": [
"gid",
"y",
"ynorm"
],
"type": "str"
},
"orderInverse": {
"label": "Invert y-axis",
"suggestions": "",
"help": "Invert the y-axis order (True|False)",
"hintText": "",
"type": "bool"
},
"labels": {
"label": "Population labels",
"suggestions": "",
"help": "Show population labels in a legend or overlayed on one side of raster ('legend'|'overlay'))",
"hintText": "",
"type": "str"
},
"popRates": {
"label": "Include population rates",
"suggestions": "",
"help": "Include population rates ('legend'|'overlay')",
"hintText": "",
"options": [
"legend",
"overlay"
],
"type": "str"
},
"spikeHist": {
"label": "Overlay spike histogram",
"suggestions": "",
"help": "overlay line over raster showing spike histogram (spikes/bin) (None|'overlay'|'subplot')",
"hintText": "",
"options": [
"None",
"overlay",
"subplot"
],
"type": "str"
},
"spikeHistBin": {
"label": "Bin size for histogram",
"suggestions": "",
"help": "Size of bin in ms to use for histogram (int)",
"hintText": "",
"type": "float"
},
"syncLines": {
"label": "Synchronization lines",
"suggestions": "",
"help": "calculate synchorny measure and plot vertical lines for each spike to evidence synchrony (True|False)",
"hintText": "",
"type": "bool"
},
"figSize": {
"label": "Figure size",
"suggestions": "",
"help": "Size of figure ((width, height))",
"hintText": "",
"type": "str"
},
"saveData": {
"label": "Save data",
"suggestions": "",
"help": "File name where to save the final data used to generate the figure (None|'fileName').",
"hintText": "",
"type": "str"
},
"saveFig": {
"label": "Save figure file name",
"suggestions": "",
"help": "File name where to save the figure (None|'fileName')",
"hintText": "",
"type": "str"
},
"showFig": {
"label": "Show figure",
"suggestions": "",
"help": "Whether to show the figure or not (True|False).",
"hintText": "",
"type": "bool"
}
}
},
"plotSpikeHist": {
"label": "Plot Spike Histogram",
"suggestions": "",
"help": "Plot spike histogram.",
"hintText": "",
"children": {
"include": {
"label": "Cells to include",
"suggestions": "",
"help": "List of cells to include (['all'|,'allCells'|,'allNetStims'|,120|,'L4'|,('L2', 56)|,('L5',[4,5,6])])",
"hintText": "",
"type": "list"
},
"timeRange": {
"label": "Time range [min,max] (ms)",
"suggestions": "",
"help": "Time range of spikes shown; if None shows all ([start,stop])",
"hintText": "",
"type": "list(float)"
},
"binSize": {
"label": "bin size for histogram",
"suggestions": "",
"help": "Size of bin in ms to use for histogram (int)",
"hintText": "",
"type": "int"
},
"overlay": {
"label": "show overlay",
"suggestions": "",
"help": "Whether to overlay the data lines or plot in separate subplots (True|False)",
"hintText": "",
"type": "bool"
},
"graphType": {
"label": "type of Graph",
"suggestions": "",
"help": " Type of graph to use (line graph or bar plot) ('line'|'bar')",
"hintText": "",
"options": [
"line",
"bar"
],
"type": "str"
},
"yaxis": {
"label": "axis units",
"suggestions": "",
"help": "Units of y axis (firing rate in Hz, or spike count) ('rate'|'count')",
"hintText": "",
"options": [
"rate",
"count"
],
"type": "str"
},
"figSize": {
"label": "Figure size",
"suggestions": "",
"help": "Size of figure ((width, height))",
"hintText": "",
"type": ""
},
"saveData": {
"label": "Save data",
"suggestions": "",
"help": "File name where to save the final data used to generate the figure (None|'fileName').",
"hintText": "",
"type": "str"
},
"saveFig": {
"label": "Save figure file name",
"help": "File name where to save the figure (None|'fileName')",
"hintText": "",
"type": "str"
},
"showFig": {
"label": "Show figure",
"suggestions": "",
"help": "Whether to show the figure or not (True|False).",
"hintText": "",
"type": "bool"
}
}
},
"plotRatePSD": {
"label": "Plot Rate PSD",
"suggestions": "",
"help": "Plot spikes power spectral density (PSD).",
"hintText": "",
"children": {
"include": {
"label": "Cells to include",
"suggestions": "",
"help": "List of cells to include (['all'|,'allCells'|,'allNetStims'|,120|,'L4'|,('L2', 56)|,('L5',[4,5,6])])",
"hintText": "",
"type": "list"
},
"timeRange": {
"label": "Time range [min,max] (ms)",
"suggestions": "",
"help": "Time range of spikes shown; if None shows all ([start,stop])",
"hintText": "",
"type": "list(float)"
},
"binSize": {
"label": "Bin size",
"suggestions": "",
"help": "Size of bin in ms to use (int)",
"hintText": "",
"type": "float"
},
"maxFreq": {
"label": "maximum frequency",
"suggestions": "",
"help": " Maximum frequency to show in plot (float).",
"hintText": "",
"type": "float"
},
"NFFT": {
"label": "Number of point",
"suggestions": "",
"help": "The number of data points used in each block for the FFT (power of 2)",
"hintText": "",
"type": "float"
},
"noverlap": {
"label": "Number of overlap points",
"suggestions": "",
"help": "Number of points of overlap between segments (< nperseg).",
"hintText": "",
"type": "float"
},
"smooth": {
"label": "Window size",
"suggestions": "",
"help": "Window size for smoothing; no smoothing if 0.",
"hintText": "",
"type": "float"
},
"overlay": {
"label": "Overlay data",
"suggestions": "",
"help": "Whether to overlay the data lines or plot in separate subplots (True|False).",
"hintText": "",
"type": "bool"
},
"figSize": {
"label": "Figure size",
"suggestions": "",
"help": "Size of figure ((width, height))",
"hintText": "",
"type": ""
},
"saveData": {
"label": "Save data",
"suggestions": "",
"help": "File name where to save the final data used to generate the figure (None|'fileName').",
"hintText": "",
"type": "str"
},
"saveFig": {
"label": "Save figure file name",
"suggestions": "",
"help": "File name where to save the figure (None|'fileName')",
"hintText": "",
"type": "str"
},
"showFig": {
"label": "Show figure",
"suggestions": "",
"help": "Whether to show the figure or not (True|False).",
"hintText": "",
"type": "bool"
}
}
},
"plotSpikeStats": {
"label": "Plot Spike Statistics",
"suggestions": "",
"help": "Plot spike histogram.",
"hintText": "",
"children": {
"include": {
"label": "Cells to include",
"suggestions": "",
"help": "List of cells to include (['all'|,'allCells'|,'allNetStims'|,120|,'L4'|,('L2', 56)|,('L5',[4,5,6])])",
"hintText": "",
"type": "list"
},
"timeRange": {
"label": "Time range [min,max] (ms)",
"suggestions": "",
"help": "Time range of spikes shown; if None shows all ([start,stop])",
"hintText": "",
"type": "list(float)"
},
"graphType": {
"label": "type of graph",
"suggestions": "",
"help": "Type of graph to use ('boxplot').",
"hintText": "",
"options": [
"boxplot"
],
"type": "str"
},
"stats": {
"label": "meassure type to calculate stats",
"suggestions": "",
"help": "List of types measure to calculate stats over: cell firing rates, interspike interval coefficient of variation (ISI CV), pairwise synchrony, and/or overall synchrony (sync measures calculated using PySpike SPIKE-Synchrony measure) (['rate', |'isicv'| 'pairsync' |'sync'|]).",
"hintText": "",
"options": [
"rate",
"isicv",
"pairsync",
"sync"
],
"type": "str"
},
"popColors": {
"label": "color for each population",
"suggestions": "",
"help": "Dictionary with color (value) used for each population/key.",
"hintText": "",
"type": "dict"
},
"figSize": {
"label": "figure size",
"suggestions": "",
"help": "Size of figure ((width, height)).",
"hintText": "",
"type": ""
},
"saveData": {
"label": "Save data",
"suggestions": "",
"help": "File name where to save the final data used to generate the figure (None|'fileName').",
"hintText": "",
"type": "str"
},
"saveFig": {
"label": "Save figure file name",
"suggestions": "",
"help": "File name where to save the figure (None|'fileName').",
"hintText": "",
"type": "str"
},
"showFig": {
"label": "Show figure",
"suggestions": "",
"help": "Whether to show the figure or not (True|False).",
"hintText": "",
"type": "bool"
}
}
},
"plotTraces": {
"label": "Plot Traces",
"suggestions": "",
"help": "Plot recorded traces (specified in simConfig.recordTraces).",
"hintText": "",
"children": {
"include": {
"label": "Cells to include",
"suggestions": "",
"help": "List of cells to include (['all'|,'allCells'|,'allNetStims'|,120|,'L4'|,('L2', 56)|,('L5',[4,5,6])])",
"hintText": "",
"type": "list(float)"
},
"timeRange": {
"label": "Time range [min,max] (ms)",
"suggestions": "",
"help": "Time range for shown Traces ; if None shows all ([start,stop])",
"hintText": "",
"type": "list(float)"
},
"overlay": {
"label": "overlay data",
"suggestions": "",
"help": "Whether to overlay the data lines or plot in separate subplots (True|False).",
"hintText": "",
"type": "bool"
},
"oneFigPer": {
"label": "plot one figure per cell/trace",
"suggestions": "",
"help": "Whether to plot one figure per cell or per trace (showing multiple cells) ('cell'|'trace').",
"hintText": "",
"options": [
"cell",
"traces"
],
"type": "str"
},
"rerun": {
"label": "re-run simulation",
"suggestions": "",
"help": "rerun simulation so new set of cells gets recorded (True|False).",
"hintText": "",
"type": "bool"
},
"figSize": {
"label": "Figure size",
"suggestions": "",
"help": "Size of figure ((width, height))",
"hintText": "",
"type": ""
},
"saveData": {
"label": "Save data",
"suggestions": "",
"help": "File name where to save the final data used to generate the figure (None|'fileName').",
"hintText": "",
"type": "str"
},
"saveFig": {
"label": "Save figure file name",
"suggestions": "",
"help": "File name where to save the figure (None|'fileName')",
"hintText": "",
"type": "str"
},
"showFig": {
"label": "Show figure",
"suggestions": "",
"help": "Whether to show the figure or not (True|False).",
"hintText": "",
"type": "bool"
}
}
},
"plotLFP": {
"label": "Plot LFP",
"suggestions": "",
"help": "Plot LFP / extracellular electrode recordings (time-resolved, power spectral density, time-frequency and 3D locations).",
"hintText": "",
"children": {
"electrodes": {
"label": "electrode to show",
"suggestions": "",
"help": " List of electrodes to include; 'avg'=avg of all electrodes; 'all'=each electrode separately (['avg', 'all', 0, 1, ...]).",
"hintText": "",
"type": "list"
},
"plots": {
"label": "Select plot types to show (multiple selection available)",
"suggestions": "",
"help": "list of plot types to show (['timeSeries', 'PSD', 'timeFreq', 'locations']).",
"hintText": "",
"options": [
"timeSeries",
"PSD",
"spectrogram",
"locations"
],
"type": "str"
},
"timeRange": {
"label": "Time range [min,max] (ms)",
"suggestions": "",
"help": "Time range for shown Traces ; if None shows all ([start,stop])",
"hintText": "",
"type": "list(float)"
},
"NFFT": {
"label": "NFFT",
"suggestions": "",
"help": "The number of data points used in each block for the FFT (power of 2) (float)",
"hintText": "",
"type": "float"
},
"noverlap": {
"label": "Overlap",
"suggestions": "",
"help": "Number of points of overlap between segments (int, < nperseg).",
"hintText": "",
"type": "float"
},
"maxFreq": {
"label": "Maximum Frequency",
"suggestions": "",
"help": "Maximum frequency shown in plot for PSD and time-freq (float).",
"hintText": "",
"type": "float"
},
"nperseg": {
"label": "Segment length (nperseg)",
"suggestions": "",
"help": "Length of each segment for time-freq (int).",
"hintText": "",
"type": "float"
},
"smooth": {
"label": "Window size",
"suggestions": "",
"help": "Window size for smoothing; no smoothing if 0 (int).",
"hintText": "",
"type": "float"
},
"separation": {
"label": "Separation factor",
"suggestions": "",
"help": "Separation factor between time-resolved LFP plots; multiplied by max LFP value (float).",
"hintText": "",
"type": "float"
},
"includeAxon": {
"label": "Include axon",
"suggestions": "",
"help": "Whether to show the axon in the location plot (boolean).",
"hintText": "",
"type": "bool"
},
"figSize": {
"label": "Figure size",
"suggestions": "",
"help": "Size of figure ((width, height))",
"hintText": "",
"type": ""
},
"saveData": {
"label": "Save data",
"suggestions": "",
"help": "File name where to save the final data used to generate the figure (None|'fileName').",
"hintText": "",
"type": "str"
},
"saveFig": {
"label": "Save figure file name",
"suggestions": "",
"help": "File name where to save the figure (None|'fileName')",
"hintText": "",
"type": "str"
},
"showFig": {
"label": "Show figure",
"suggestions": "",
"help": "Whether to show the figure or not (True|False).",
"hintText": "",
"type": "bool"
}
}
},
"plotShape": {
"label": "Plot Shape",
"suggestions": "",
"help": "",
"hintText": "Plot 3D cell shape using Matplotlib or NEURON Interviews PlotShape.",
"children": {
"includePre": {
"label": "population (or cell by index) to presyn",
"suggestions": "",
"help": "List of cells to include (['all'|,'allCells'|,'allNetStims'|,120|,'L4'|,('L2', 56)|,('L5',[4,5,6])])",
"hintText": "",
"type": "list"
},
"includePost": {
"label": "population (or cell by index) to postsyn",
"suggestions": "",
"help": "List of cells to include (['all'|,'allCells'|,'allNetStims'|,120|,'L4'|,('L2', 56)|,('L5',[4,5,6])])",
"hintText": "",
"type": "list"
},
"synStyle": {
"label": "synaptic marker style",
"suggestions": "",
"help": "Style of marker to show synapses (Matplotlib markers).",
"hintText": "",
"type": "str"
},
"dist": {
"label": "3D distance",
"suggestions": "",
"help": "3D distance (like zoom).",
"hintText": "",
"type": "float"
},
"synSize": {
"label": "synapses marker size",
"suggestions": "",
"help": "Size of marker to show synapses.",
"hintText": "",
"type": "float"
},
"cvar": {
"label": "variable to represent in shape plot",
"suggestions": "",
"help": "Variable to represent in shape plot ('numSyns'|'weightNorm').",
"hintText": "",
"options": [
"numSyns",
"weightNorm"
],
"type": "str"
},
"cvals": {
"label": "value to represent in shape plot",
"suggestions": "",
"help": "List of values to represent in shape plot; must be same as num segments (list of size num segments; ).",
"hintText": "",
"type": "list(float)"
},
"iv": {
"label": "use NEURON iv",
"suggestions": "",
"help": "Use NEURON Interviews (instead of matplotlib) to show shape plot (True|False).",
"hintText": "",
"type": "bool"
},
"ivprops": {
"label": "properties for iv",
"suggestions": "",
"help": "Dict of properties to plot using Interviews (dict).",
"hintText": "",
"type": "dict"
},
"showSyns": {
"label": "show synaptic connections in 3D",
"suggestions": "",
"help": "Show synaptic connections in 3D (True|False).",
"hintText": "",
"type": "bool"
},
"bkgColor": {
"label": "background color",
"suggestions": "",
"help": "RGBA list/tuple with bakcground color eg. (0.5, 0.2, 0.1, 1.0) (list/tuple with 4 floats).",
"hintText": "",
"type": "list(float)"
},
"showElectrodes": {
"label": "show electrodes",
"suggestions": "",
"help": "Show electrodes in 3D (True|False).",
"hintText": "",
"type": "bool"
},
"includeAxon": {
"label": "include Axon in shape plot",
"suggestions": "",
"help": "Include axon in shape plot (True|False).",
"hintText": "",
"type": "bool"
},
"figSize": {
"label": "Figure size",
"suggestions": "",
"help": "Size of figure ((width, height))",
"hintText": "",
"type": ""
},
"saveData": {
"label": "Save data",
"suggestions": "",
"help": "File name where to save the final data used to generate the figure (None|'fileName').",
"hintText": "",
"type": "str"
},
"saveFig": {
"label": "Save figure file name",
"suggestions": "",
"help": "File name where to save the figure (None|'fileName')",
"hintText": "",
"type": "str"
},
"showFig": {
"label": "Show figure",
"suggestions": "",
"help": "Whether to show the figure or not (True|False).",
"hintText": "",
"type": "bool"
}
}
},
"plot2Dnet": {
"label": "Plot 2D net",
"suggestions": "",
"help": "Plot 2D representation of network cell positions and connections.",
"hintText": "",
"children": {
"include": {
"label": "Cells to include",
"suggestions": "",
"help": "List of cells to show (['all'|,'allCells'|,'allNetStims'|,120|,'L4'|,('L2', 56)|,('L5',[4,5,6])]).",
"hintText": "",
"type": "list"
},
"showConns": {
"label": "show connections",
"suggestions": "",
"help": "Whether to show connections or not (True|False).",
"hintText": "",
"type": "bool"
},
"view": {
"label": "perspective view",
"suggestions": "",
"help": "Perspective view, either front ('xy') or top-down ('xz').",
"hintText": "",
"options": [
"xy",
"xz"
],
"type": "str"
},
"figSize": {
"label": "Figure size",
"suggestions": "",
"help": "Size of figure ((width, height))",
"hintText": "",
"type": ""
},
"saveData": {
"label": "Save data",
"suggestions": "",
"help": "File name where to save the final data used to generate the figure (None|'fileName').",
"hintText": "",
"type": "str"
},
"saveFig": {
"label": "Save figure file name",
"suggestions": "",
"help": "File name where to save the figure (None|'fileName')",
"hintText": "",
"type": "str"
},
"showFig": {
"label": "Show figure",
"suggestions": "",
"help": "Whether to show the figure or not (True|False).",
"hintText": "",
"type": "bool"
}
}
},
"plotConn": {
"label": "Plot Connectivity",
"suggestions": "",
"help": "Plot network connectivity.",
"hintText": "",
"children": {
"include": {
"label": "Cells to include",
"suggestions": "",
"help": "List of cells to show (['all'|,'allCells'|,'allNetStims'|,120|,'L4'|,('L2', 56)|,('L5',[4,5,6])]).",
"hintText": "",
"type": "list"
},
"feature": {
"label": "feature to show",
"suggestions": "",
"help": "Feature to show in connectivity matrix; the only features applicable to groupBy='cell' are 'weight', 'delay' and 'numConns'; 'strength' = weight * probability ('weight'|'delay'|'numConns'|'probability'|'strength'|'convergence'|'divergence')g.",
"hintText": "",
"options": [
"weight",
"delay",
"numConns",
"probability",
"strength",
"convergency",
"divergency"
],
"type": "str"
},
"groupBy": {
"label": "group by",
"suggestions": "",
"help": "Show matrix for individual cells or populations ('pop'|'cell').",
"hintText": "",
"options": [
"pop",
"cell"
],
"type": "str"
},
"orderBy": {
"label": "order by",
"suggestions": "",
"help": "Unique numeric cell property to order x and y axes by, e.g. 'gid', 'ynorm', 'y' (requires groupBy='cells') ('gid'|'y'|'ynorm'|...).",
"hintText": "",
"options": [
"gid",
"y",
"ynorm"
],
"type": "str"
},
"figSize": {
"label": "Figure size",
"suggestions": "",
"help": "Size of figure ((width, height))",
"hintText": "",
"type": ""
},
"saveData": {
"label": "Save data",
"suggestions": "",
"help": "File name where to save the final data used to generate the figure (None|'fileName').",
"hintText": "",
"type": "str"
},
"saveFig": {
"label": "Save figure file name",
"suggestions": "",
"help": "File name where to save the figure (None|'fileName')",
"hintText": "",
"type": "str"
},
"showFig": {
"label": "Show figure",
"suggestions": "",
"help": "Whether to show the figure or not (True|False).",
"hintText": "",
"type": "bool"
}
}
},
"granger": {
"label": "Granger",
"suggestions": "",
"help": "Calculate and optionally plot Granger Causality.",
"hintText": "",
"children": {
"cells1": {
"label": "population (or cell by index) to subset 1",
"suggestions": "",
"help": "Subset of cells from which to obtain spike train 1 (['all',|'allCells','allNetStims',|,120,|,'E1'|,('L2', 56)|,('L5',[4,5,6])]).",
"hintText": "",
"type": "list"
},
"cells2": {
"label": "population (or cell by index cell) to subset 2",
"suggestions": "",
"help": "Subset of cells from which to obtain spike train 2 (['all',|'allCells','allNetStims',|,120,|,'E1'|,('L2', 56)|,('L5',[4,5,6])]).",
"hintText": "",
"type": "list"
},
"spks1": {
"label": "spike times to train 1",
"suggestions": "",
"help": "Spike train 1; list of spike times; if omitted then obtains spikes from cells1 (list).",
"hintText": "",
"type": "list"
},
"spks2": {
"label": "spike times to train 2",
"suggestions": "",
"help": "Spike train 2; list of spike times; if omitted then obtains spikes from cells1 (list).",
"hintText": "",
"type": "list"
},
"timeRange": {
"label": "Time range [min,max] (ms)",
"suggestions": "",
"help": "Range of time to calculate nTE in ms ([min, max]).",
"hintText": "",
"type": "list(float)"
},
"binSize": {
"label": "bin size",
"suggestions": "",
"help": "Bin size used to convert spike times into histogram (int).",
"hintText": "",
"type": "float"
},
"label1": {
"label": "label for train 1",
"suggestions": "",
"help": "Label for spike train 1 to use in plot (string).",
"hintText": "",
"type": "str"
},
"label2": {
"label": "label for train 2",
"suggestions": "",
"help": "Label for spike train 2 to use in plot (string).",
"hintText": "",
"type": "str"
},
"figSize": {
"label": "Figure size",
"suggestions": "",
"help": "Size of figure ((width, height))",
"hintText": "",
"type": ""
},
"saveData": {
"label": "Save data",
"suggestions": "",
"help": "File name where to save the final data used to generate the figure (None|'fileName').",
"hintText": "",
"type": "str"
},
"saveFig": {
"label": "Save figure file name",
"suggestions": "",
"help": "File name where to save the figure (None|'fileName')",
"hintText": "",
"type": "str"
},
"showFig": {
"label": "Show figure",
"suggestions": "",
"help": "Whether to show the figure or not (True|False).",
"hintText": "",
"type": "bool"
}
}
},
"nTE": {
"label": "Normalize Transfer Entropy",
"suggestions": "",
"help": "Calculate normalized transfer entropy.",
"hintText": "",
"children": {
"cell1": {
"label": "Cell Subset 1",
"suggestions": "",
"help": "Subset of cells from which to obtain spike train 1 (['all',|'allCells','allNetStims',|,120,|,'E1'|,('L2', 56)|,('L5',[4,5,6])]).",
"hintText": "",
"type": "list"
},
"cell2": {
"label": "Cell Subset 2",
"suggestions": "",
"help": "Subset of cells from which to obtain spike train 2 (['all',|'allCells','allNetStims',|,120,|,'E1'|,('L2', 56)|,('L5',[4,5,6])]).",
"hintText": "",
"type": "list"
},
"spks1": {
"label": "Spike train 1",
"suggestions": "",
"help": "Spike train 1; list of spike times; if omitted then obtains spikes from cells1 (list).",
"hintText": "",
"type": "list(float)"
},
"spks2": {
"label": "Spike train 2",
"suggestions": "",
"help": "Spike train 2; list of spike times; if omitted then obtains spikes from cells1 (list).",
"hintText": "",
"type": "list(float)"
},
"timeRange": {
"label": "Time range [min,max] (ms)",
"suggestions": "",
"help": "Range of time to calculate nTE in ms ([min, max]).",
"hintText": "",
"type": "list(float)"
},
"binSize": {
"label": "Bin size",
"suggestions": "",
"help": "Bin size used to convert spike times into histogram (int).",
"hintText": "",
"type": "float"
},
"numShuffle": {
"label": "Number of Shuffles",
"suggestions": "",
"help": "Number of times to shuffle spike train 1 to calculate TEshuffled; note: nTE = (TE - TEShuffled)/H(X2F|X2P) (int).",
"hintText": "",
"type": "float"
},
"figSize": {
"label": "Figure size",
"suggestions": "",
"help": "Size of figure ((width, height))",
"hintText": "",
"type": ""
},
"saveData": {
"label": "Save data",
"suggestions": "",
"help": "File name where to save the final data used to generate the figure (None|'fileName').",
"hintText": "",
"type": "str"
},
"saveFig": {
"label": "Save figure file name",
"suggestions": "",
"help": "File name where to save the figure (None|'fileName')",
"hintText": "",
"type": "str"
},
"showFig": {
"label": "Show figure",
"suggestions": "",
"help": "Whether to show the figure or not (True|False).",
"hintText": "",
"type": "bool"
}
}
}
}
}
}
}
}
| netpyne/metadata/metadata.py | 132,055 | Module containing NetPyNE metadata
--------------------------------------------------------------------------------------------------------------------- netParams --------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------- netParams.cellParams --------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------- netParams.synMechParams --------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------- netParams.connParams --------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------- netParams.stimSourceParams --------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------- netParams.stimTargetParams --------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------- netParams.importCellParams --------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------- simConfig --------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------- simConfig.analysis --------------------------------------------------------------------------------------------------------------------- | 2,346 | en | 0.117911 |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test mining RPCs
- getmininginfo
- getblocktemplate proposal mode
- submitblock"""
import copy
from binascii import b2a_hex
from decimal import Decimal
from test_framework.blocktools import create_coinbase
from test_framework.mininode import CBlock
from test_framework.test_framework import LivecoinTestFramework
from test_framework.util import assert_equal, assert_raises_rpc_error
def b2x(b):
return b2a_hex(b).decode('ascii')
def assert_template(node, block, expect, rehash=True):
if rehash:
block.hashMerkleRoot = block.calc_merkle_root()
rsp = node.getblocktemplate({'data': b2x(block.serialize()), 'mode': 'proposal'})
assert_equal(rsp, expect)
class MiningTest(LivecoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = False
def run_test(self):
node = self.nodes[0]
self.log.info('getmininginfo')
mining_info = node.getmininginfo()
assert_equal(mining_info['blocks'], 200)
assert_equal(mining_info['chain'], 'regtest')
assert_equal(mining_info['currentblocktx'], 0)
assert_equal(mining_info['currentblockweight'], 0)
assert_equal(mining_info['difficulty'], Decimal('4.656542373906925E-10'))
assert_equal(mining_info['networkhashps'], Decimal('0.003333333333333334'))
assert_equal(mining_info['pooledtx'], 0)
# Mine a block to leave initial block download
node.generate(1)
tmpl = node.getblocktemplate()
self.log.info("getblocktemplate: Test capability advertised")
assert 'proposal' in tmpl['capabilities']
assert 'coinbasetxn' not in tmpl
coinbase_tx = create_coinbase(height=int(tmpl["height"]) + 1)
# sequence numbers must not be max for nLockTime to have effect
coinbase_tx.vin[0].nSequence = 2 ** 32 - 2
coinbase_tx.rehash()
block = CBlock()
block.nVersion = tmpl["version"]
block.hashPrevBlock = int(tmpl["previousblockhash"], 16)
block.nTime = tmpl["curtime"]
block.nBits = int(tmpl["bits"], 16)
block.nNonce = 0
block.vtx = [coinbase_tx]
self.log.info("getblocktemplate: Test valid block")
assert_template(node, block, None)
self.log.info("submitblock: Test block decode failure")
assert_raises_rpc_error(-22, "Block decode failed", node.submitblock, b2x(block.serialize()[:-15]))
self.log.info("getblocktemplate: Test bad input hash for coinbase transaction")
bad_block = copy.deepcopy(block)
bad_block.vtx[0].vin[0].prevout.hash += 1
bad_block.vtx[0].rehash()
assert_template(node, bad_block, 'bad-cb-missing')
self.log.info("submitblock: Test invalid coinbase transaction")
assert_raises_rpc_error(-22, "Block does not start with a coinbase", node.submitblock, b2x(bad_block.serialize()))
self.log.info("getblocktemplate: Test truncated final transaction")
assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': b2x(block.serialize()[:-1]), 'mode': 'proposal'})
self.log.info("getblocktemplate: Test duplicate transaction")
bad_block = copy.deepcopy(block)
bad_block.vtx.append(bad_block.vtx[0])
assert_template(node, bad_block, 'bad-txns-duplicate')
self.log.info("getblocktemplate: Test invalid transaction")
bad_block = copy.deepcopy(block)
bad_tx = copy.deepcopy(bad_block.vtx[0])
bad_tx.vin[0].prevout.hash = 255
bad_tx.rehash()
bad_block.vtx.append(bad_tx)
assert_template(node, bad_block, 'bad-txns-inputs-missingorspent')
self.log.info("getblocktemplate: Test nonfinal transaction")
bad_block = copy.deepcopy(block)
bad_block.vtx[0].nLockTime = 2 ** 32 - 1
bad_block.vtx[0].rehash()
assert_template(node, bad_block, 'bad-txns-nonfinal')
self.log.info("getblocktemplate: Test bad tx count")
# The tx count is immediately after the block header
TX_COUNT_OFFSET = 80
bad_block_sn = bytearray(block.serialize())
assert_equal(bad_block_sn[TX_COUNT_OFFSET], 1)
bad_block_sn[TX_COUNT_OFFSET] += 1
assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': b2x(bad_block_sn), 'mode': 'proposal'})
self.log.info("getblocktemplate: Test bad bits")
bad_block = copy.deepcopy(block)
bad_block.nBits = 469762303 # impossible in the real world
assert_template(node, bad_block, 'bad-diffbits')
self.log.info("getblocktemplate: Test bad merkle root")
bad_block = copy.deepcopy(block)
bad_block.hashMerkleRoot += 1
assert_template(node, bad_block, 'bad-txnmrklroot', False)
self.log.info("getblocktemplate: Test bad timestamps")
bad_block = copy.deepcopy(block)
bad_block.nTime = 2 ** 31 - 1
assert_template(node, bad_block, 'time-too-new')
bad_block.nTime = 0
assert_template(node, bad_block, 'time-too-old')
self.log.info("getblocktemplate: Test not best block")
bad_block = copy.deepcopy(block)
bad_block.hashPrevBlock = 123
assert_template(node, bad_block, 'inconclusive-not-best-prevblk')
if __name__ == '__main__':
MiningTest().main()
| test/functional/mining_basic.py | 5,584 | Test mining RPCs
- getmininginfo
- getblocktemplate proposal mode
- submitblock
!/usr/bin/env python3 Copyright (c) 2014-2017 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. Mine a block to leave initial block download sequence numbers must not be max for nLockTime to have effect The tx count is immediately after the block header impossible in the real world | 475 | en | 0.715059 |
import tarfile
import textwrap
import pytoml
from .app import App
from .exceptions import TockLoaderException
from .tbfh import TBFHeader
class TAB:
'''
Tock Application Bundle object. This class handles the TAB format.
'''
def __init__ (self, tab_path):
self.tab = tarfile.open(tab_path)
def extract_app (self, arch):
'''
Return an `App` object from this TAB. You must specify the desired
MCU architecture so the correct binary can be retrieved.
'''
binary_tarinfo = self.tab.getmember('{}.bin'.format(arch))
binary = self.tab.extractfile(binary_tarinfo).read()
# First get the TBF header from the correct binary in the TAB
tbfh = TBFHeader(binary)
if tbfh.is_valid():
name_or_params = tbfh.get_app_name()
if isinstance(name_or_params, str):
name = name_or_params
else:
start = name_or_params[0]
end = start+name_or_params[1]
name = binary[start:end].decode('utf-8')
# Check that total size actually matches the binary that we got.
if tbfh.get_app_size() < len(binary):
# It's fine if the binary is smaller, but the binary cannot be
# longer than the amount of reserved space (`total_size` in the
# TBF header) for the app.
raise TockLoaderException('Invalid TAB, the app binary is longer than its defined total_size')
return App(tbfh, None, name, binary)
else:
raise TockLoaderException('Invalid TBF found in app in TAB')
def is_compatible_with_board (self, board):
'''
Check if the Tock app is compatible with a particular Tock board.
'''
metadata = self.parse_metadata()
if metadata['tab-version'] == 1:
return 'only-for-boards' not in metadata or \
board in metadata['only-for-boards'] or \
metadata['only-for-boards'] == ''
else:
raise TockLoaderException('Unable to understand version {} of metadata'.format(metadata['tab-version']))
def parse_metadata (self):
'''
Open and parse the included metadata file in the TAB.
'''
metadata_tarinfo = self.tab.getmember('metadata.toml')
metadata_str = self.tab.extractfile(metadata_tarinfo).read().decode('utf-8')
return pytoml.loads(metadata_str)
def get_supported_architectures (self):
'''
Return a list of architectures that this TAB has compiled binaries for.
'''
contained_files = self.tab.getnames()
return [i[:-4] for i in contained_files if i[-4:] == '.bin']
def get_tbf_header (self):
'''
Return a TBFHeader object with the TBF header from the app in the TAB.
TBF headers are not architecture specific, so we pull from a random
binary if there are multiple architectures supported.
'''
# Find a .bin file
for f in self.tab.getnames():
if f[-4:] == '.bin':
binary_tarinfo = self.tab.getmember(f)
binary = self.tab.extractfile(binary_tarinfo).read()
# Get the TBF header from a binary in the TAB
return TBFHeader(binary)
return None
def __str__ (self):
out = ''
metadata = self.parse_metadata()
out += 'TAB: {}\n'.format(metadata['name'])
for k,v in sorted(metadata.items()):
if k == 'name':
continue
out += ' {}: {}\n'.format(k,v)
out += ' supported architectures: {}\n'.format(', '.join(self.get_supported_architectures()))
out += ' TBF Header\n'
out += textwrap.indent(str(self.get_tbf_header()), ' ')
return out
| tockloader/tab.py | 3,297 | Tock Application Bundle object. This class handles the TAB format.
Return an `App` object from this TAB. You must specify the desired
MCU architecture so the correct binary can be retrieved.
Return a list of architectures that this TAB has compiled binaries for.
Return a TBFHeader object with the TBF header from the app in the TAB.
TBF headers are not architecture specific, so we pull from a random
binary if there are multiple architectures supported.
Check if the Tock app is compatible with a particular Tock board.
Open and parse the included metadata file in the TAB.
First get the TBF header from the correct binary in the TAB Check that total size actually matches the binary that we got. It's fine if the binary is smaller, but the binary cannot be longer than the amount of reserved space (`total_size` in the TBF header) for the app. Find a .bin file Get the TBF header from a binary in the TAB | 909 | en | 0.821311 |
from __future__ import absolute_import
from __future__ import unicode_literals
import types
import copy
from django import forms
from django.forms.forms import NON_FIELD_ERRORS
from django.core.validators import EMPTY_VALUES
from django.db import models
from django.db.models.fields import FieldDoesNotExist
from django.utils import six
from django.utils.text import capfirst
from django.utils.translation import ugettext as _
from sys import version_info
try:
from django.db.models.constants import LOOKUP_SEP
except ImportError: # pragma: nocover
# Django < 1.5 fallback
from django.db.models.sql.constants import LOOKUP_SEP # noqa
try:
from collections import OrderedDict
except ImportError: # pragma: nocover
# Django < 1.5 fallback
from django.utils.datastructures import SortedDict as OrderedDict # noqa
try:
from django.db.models.related import RelatedObject as ForeignObjectRel
except ImportError: # pragma: nocover
# Django >= 1.8 replaces RelatedObject with ForeignObjectRel
from django.db.models.fields.related import ForeignObjectRel
from .filters import (Filter, CharFilter, BooleanFilter,
ChoiceFilter, DateFilter, DateTimeFilter, TimeFilter, ModelChoiceFilter,
ModelMultipleChoiceFilter, NumberFilter)
ORDER_BY_FIELD = 'o'
# There is a bug with deepcopy in 2.6, patch if we are running python < 2.7
# http://bugs.python.org/issue1515
if version_info < (2, 7, 0):
def _deepcopy_method(x, memo):
return type(x)(x.im_func, copy.deepcopy(x.im_self, memo), x.im_class)
copy._deepcopy_dispatch[types.MethodType] = _deepcopy_method
class STRICTNESS(object):
"""
Values of False & True chosen for backward compatability reasons.
Originally, these were the only options.
"""
IGNORE = False
RETURN_NO_RESULTS = True
RAISE_VALIDATION_ERROR = "RAISE"
def get_declared_filters(bases, attrs, with_base_filters=True):
filters = []
for filter_name, obj in list(attrs.items()):
if isinstance(obj, Filter):
obj = attrs.pop(filter_name)
if getattr(obj, 'name', None) is None:
obj.name = filter_name
filters.append((filter_name, obj))
filters.sort(key=lambda x: x[1].creation_counter)
if with_base_filters:
for base in bases[::-1]:
if hasattr(base, 'base_filters'):
filters = list(base.base_filters.items()) + filters
else:
for base in bases[::-1]:
if hasattr(base, 'declared_filters'):
filters = list(base.declared_filters.items()) + filters
return OrderedDict(filters)
def get_model_field(model, f):
parts = f.split(LOOKUP_SEP)
opts = model._meta
for name in parts[:-1]:
try:
rel = opts.get_field_by_name(name)[0]
except FieldDoesNotExist:
return None
if isinstance(rel, ForeignObjectRel):
if hasattr(rel, "related_model"):
# django >= 1.8 (ForeignObjectRel)
opts = rel.related_model._meta
else:
# django < 1.8 (RelatedObject)
opts = rel.opts
else:
model = rel.rel.to
opts = model._meta
try:
rel, model, direct, m2m = opts.get_field_by_name(parts[-1])
except FieldDoesNotExist:
return None
return rel
def filters_for_model(model, fields=None, exclude=None, filter_for_field=None,
filter_for_reverse_field=None):
field_dict = OrderedDict()
opts = model._meta
if fields is None:
fields = [f.name for f in sorted(opts.fields + opts.many_to_many)
if not isinstance(f, models.AutoField)]
# Loop through the list of fields.
for f in fields:
# Skip the field if excluded.
if exclude is not None and f in exclude:
continue
field = get_model_field(model, f)
# Do nothing if the field doesn't exist.
if field is None:
field_dict[f] = None
continue
if isinstance(field, ForeignObjectRel):
filter_ = filter_for_reverse_field(field, f)
if filter_:
field_dict[f] = filter_
# If fields is a dictionary, it must contain lists.
elif isinstance(fields, dict):
# Create a filter for each lookup type.
for lookup_type in fields[f]:
filter_ = filter_for_field(field, f, lookup_type)
if filter_:
filter_name = f
# Don't add "exact" to filter names
if lookup_type != 'exact':
filter_name = f + LOOKUP_SEP + lookup_type
field_dict[filter_name] = filter_
# If fields is a list, it contains strings.
else:
filter_ = filter_for_field(field, f)
if filter_:
field_dict[f] = filter_
return field_dict
def get_full_clean_override(together):
def full_clean(form):
def add_error(message):
try:
form.add_error(None, message)
except AttributeError:
form._errors[NON_FIELD_ERRORS] = message
def all_valid(fieldset):
cleaned_data = form.cleaned_data
count = len([i for i in fieldset if cleaned_data.get(i)])
return 0 < count < len(fieldset)
super(form.__class__, form).full_clean()
message = 'Following fields must be together: %s'
if isinstance(together[0], (list, tuple)):
for each in together:
if all_valid(each):
return add_error(message % ','.join(each))
elif all_valid(together):
return add_error(message % ','.join(together))
return full_clean
class FilterSetOptions(object):
def __init__(self, options=None):
self.model = getattr(options, 'model', None)
self.fields = getattr(options, 'fields', None)
self.exclude = getattr(options, 'exclude', None)
self.order_by = getattr(options, 'order_by', False)
self.form = getattr(options, 'form', forms.Form)
self.together = getattr(options, 'together', None)
class FilterSetMetaclass(type):
def __new__(cls, name, bases, attrs):
try:
parents = [b for b in bases if issubclass(b, FilterSet)]
except NameError:
# We are defining FilterSet itself here
parents = None
declared_filters = get_declared_filters(bases, attrs, False)
new_class = super(
FilterSetMetaclass, cls).__new__(cls, name, bases, attrs)
if not parents:
return new_class
opts = new_class._meta = FilterSetOptions(
getattr(new_class, 'Meta', None))
if opts.model:
filters = filters_for_model(opts.model, opts.fields, opts.exclude,
new_class.filter_for_field,
new_class.filter_for_reverse_field)
filters.update(declared_filters)
else:
filters = declared_filters
if None in filters.values():
raise TypeError("Meta.fields contains a field that isn't defined "
"on this FilterSet")
new_class.declared_filters = declared_filters
new_class.base_filters = filters
return new_class
FILTER_FOR_DBFIELD_DEFAULTS = {
models.AutoField: {
'filter_class': NumberFilter
},
models.CharField: {
'filter_class': CharFilter
},
models.TextField: {
'filter_class': CharFilter
},
models.BooleanField: {
'filter_class': BooleanFilter
},
models.DateField: {
'filter_class': DateFilter
},
models.DateTimeField: {
'filter_class': DateTimeFilter
},
models.TimeField: {
'filter_class': TimeFilter
},
models.OneToOneField: {
'filter_class': ModelChoiceFilter,
'extra': lambda f: {
'queryset': f.rel.to._default_manager.complex_filter(
f.rel.limit_choices_to),
'to_field_name': f.rel.field_name,
}
},
models.ForeignKey: {
'filter_class': ModelChoiceFilter,
'extra': lambda f: {
'queryset': f.rel.to._default_manager.complex_filter(
f.rel.limit_choices_to),
'to_field_name': f.rel.field_name
}
},
models.ManyToManyField: {
'filter_class': ModelMultipleChoiceFilter,
'extra': lambda f: {
'queryset': f.rel.to._default_manager.complex_filter(
f.rel.limit_choices_to),
}
},
models.DecimalField: {
'filter_class': NumberFilter,
},
models.SmallIntegerField: {
'filter_class': NumberFilter,
},
models.IntegerField: {
'filter_class': NumberFilter,
},
models.PositiveIntegerField: {
'filter_class': NumberFilter,
},
models.PositiveSmallIntegerField: {
'filter_class': NumberFilter,
},
models.FloatField: {
'filter_class': NumberFilter,
},
models.NullBooleanField: {
'filter_class': BooleanFilter,
},
models.SlugField: {
'filter_class': CharFilter,
},
models.EmailField: {
'filter_class': CharFilter,
},
models.FilePathField: {
'filter_class': CharFilter,
},
models.URLField: {
'filter_class': CharFilter,
},
models.IPAddressField: {
'filter_class': CharFilter,
},
models.CommaSeparatedIntegerField: {
'filter_class': CharFilter,
},
}
class BaseFilterSet(object):
filter_overrides = {}
order_by_field = ORDER_BY_FIELD
# What to do on on validation errors
strict = STRICTNESS.RETURN_NO_RESULTS
def __init__(self, data=None, queryset=None, prefix=None, strict=None):
self.is_bound = data is not None
self.data = data or {}
if queryset is None:
queryset = self._meta.model._default_manager.all()
self.queryset = queryset
self.form_prefix = prefix
if strict is not None:
self.strict = strict
self.filters = copy.deepcopy(self.base_filters)
# propagate the model being used through the filters
for filter_ in self.filters.values():
filter_.model = self._meta.model
# Apply the parent to the filters, this will allow the filters to access the filterset
for filter_key, filter_ in six.iteritems(self.filters):
filter_.parent = self
def __iter__(self):
for obj in self.qs:
yield obj
def __len__(self):
return len(self.qs)
def __getitem__(self, key):
return self.qs[key]
@property
def qs(self):
if not hasattr(self, '_qs'):
valid = self.is_bound and self.form.is_valid()
if self.is_bound and not valid:
if self.strict == STRICTNESS.RAISE_VALIDATION_ERROR:
raise forms.ValidationError(self.form.errors)
elif bool(self.strict) == STRICTNESS.RETURN_NO_RESULTS:
self._qs = self.queryset.none()
return self._qs
# else STRICTNESS.IGNORE... ignoring
# start with all the results and filter from there
qs = self.queryset.all()
for name, filter_ in six.iteritems(self.filters):
value = None
if valid:
value = self.form.cleaned_data[name]
else:
raw_value = self.form[name].value()
try:
value = self.form.fields[name].clean(raw_value)
except forms.ValidationError:
if self.strict == STRICTNESS.RAISE_VALIDATION_ERROR:
raise
elif bool(self.strict) == STRICTNESS.RETURN_NO_RESULTS:
self._qs = self.queryset.none()
return self._qs
# else STRICTNESS.IGNORE... ignoring
if value is not None: # valid & clean data
qs = filter_.filter(qs, value)
if self._meta.order_by:
order_field = self.form.fields[self.order_by_field]
data = self.form[self.order_by_field].data
ordered_value = None
try:
ordered_value = order_field.clean(data)
except forms.ValidationError:
pass
if ordered_value in EMPTY_VALUES and self.strict:
ordered_value = self.form.fields[self.order_by_field].choices[0][0]
if ordered_value:
qs = qs.order_by(*self.get_order_by(ordered_value))
self._qs = qs
return self._qs
def count(self):
return self.qs.count()
@property
def form(self):
if not hasattr(self, '_form'):
fields = OrderedDict([
(name, filter_.field)
for name, filter_ in six.iteritems(self.filters)])
fields[self.order_by_field] = self.ordering_field
Form = type(str('%sForm' % self.__class__.__name__),
(self._meta.form,), fields)
if self._meta.together:
Form.full_clean = get_full_clean_override(self._meta.together)
if self.is_bound:
self._form = Form(self.data, prefix=self.form_prefix)
else:
self._form = Form(prefix=self.form_prefix)
return self._form
def get_ordering_field(self):
if self._meta.order_by:
if isinstance(self._meta.order_by, (list, tuple)):
if isinstance(self._meta.order_by[0], (list, tuple)):
# e.g. (('field', 'Display name'), ...)
choices = [(f[0], f[1]) for f in self._meta.order_by]
else:
choices = [(f, _('%s (descending)' % capfirst(f[1:])) if f[0] == '-' else capfirst(f))
for f in self._meta.order_by]
else:
# add asc and desc field names
# use the filter's label if provided
choices = []
for f, fltr in self.filters.items():
choices.extend([
(fltr.name or f, fltr.label or capfirst(f)),
("-%s" % (fltr.name or f), _('%s (descending)' % (fltr.label or capfirst(f))))
])
return forms.ChoiceField(label=_("Ordering"), required=False,
choices=choices)
@property
def ordering_field(self):
if not hasattr(self, '_ordering_field'):
self._ordering_field = self.get_ordering_field()
return self._ordering_field
def get_order_by(self, order_choice):
return [order_choice]
@classmethod
def filter_for_field(cls, f, name, lookup_type='exact'):
filter_for_field = dict(FILTER_FOR_DBFIELD_DEFAULTS)
filter_for_field.update(cls.filter_overrides)
default = {
'name': name,
'label': capfirst(f.verbose_name),
'lookup_type': lookup_type
}
if f.choices:
default['choices'] = f.choices
return ChoiceFilter(**default)
data = filter_for_field.get(f.__class__)
if data is None:
# could be a derived field, inspect parents
for class_ in f.__class__.mro():
# skip if class_ is models.Field or object
# 1st item in mro() is original class
if class_ in (f.__class__, models.Field, object):
continue
data = filter_for_field.get(class_)
if data:
break
if data is None:
return
filter_class = data.get('filter_class')
default.update(data.get('extra', lambda f: {})(f))
if filter_class is not None:
return filter_class(**default)
@classmethod
def filter_for_reverse_field(cls, f, name):
rel = f.field.rel
queryset = f.field.model._default_manager.all()
default = {
'name': name,
'label': capfirst(rel.related_name),
'queryset': queryset,
}
if rel.multiple:
return ModelMultipleChoiceFilter(**default)
else:
return ModelChoiceFilter(**default)
class FilterSet(six.with_metaclass(FilterSetMetaclass, BaseFilterSet)):
pass
def filterset_factory(model):
meta = type(str('Meta'), (object,), {'model': model})
filterset = type(str('%sFilterSet' % model._meta.object_name),
(FilterSet,), {'Meta': meta})
return filterset
| django_filters/filterset.py | 17,044 | Values of False & True chosen for backward compatability reasons.
Originally, these were the only options.
pragma: nocover Django < 1.5 fallback noqa pragma: nocover Django < 1.5 fallback noqa pragma: nocover Django >= 1.8 replaces RelatedObject with ForeignObjectRel There is a bug with deepcopy in 2.6, patch if we are running python < 2.7 http://bugs.python.org/issue1515 django >= 1.8 (ForeignObjectRel) django < 1.8 (RelatedObject) Loop through the list of fields. Skip the field if excluded. Do nothing if the field doesn't exist. If fields is a dictionary, it must contain lists. Create a filter for each lookup type. Don't add "exact" to filter names If fields is a list, it contains strings. We are defining FilterSet itself here What to do on on validation errors propagate the model being used through the filters Apply the parent to the filters, this will allow the filters to access the filterset else STRICTNESS.IGNORE... ignoring start with all the results and filter from there else STRICTNESS.IGNORE... ignoring valid & clean data e.g. (('field', 'Display name'), ...) add asc and desc field names use the filter's label if provided could be a derived field, inspect parents skip if class_ is models.Field or object 1st item in mro() is original class | 1,272 | en | 0.7991 |
"""empty message
Revision ID: 780c29109b25
Revises: 911cc5d772fc
Create Date: 2020-08-30 15:22:15.026266
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "780c29109b25"
down_revision = "911cc5d772fc"
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_foreign_key(None, "feedback", "user", ["author_id"], ["id"])
op.drop_column("feedback", "author")
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column("feedback", sa.Column("author", sa.VARCHAR(length=20), nullable=True))
op.drop_constraint(None, "feedback", type_="foreignkey")
# ### end Alembic commands ###
| migrations/versions/780c29109b25_.py | 831 | empty message
Revision ID: 780c29109b25
Revises: 911cc5d772fc
Create Date: 2020-08-30 15:22:15.026266
revision identifiers, used by Alembic. commands auto generated by Alembic - please adjust! end Alembic commands commands auto generated by Alembic - please adjust! end Alembic commands | 296 | en | 0.604746 |
import numpy as np
import os
import cv2
from PIL import Image
import numpy as np
import random
import itertools
import matplotlib.pyplot as plt # plt 用于显示图片
from tqdm import tqdm
# 标注文件数据处理
def read_pslot(annt_file):
# print(annt_file)
with open(annt_file, "r") as f:
annt = f.readlines()
# print("annt", annt)
l = []
l_ign = []
for line in annt:
line_annt = line.strip('\n').split(' ')
# print(line_annt)
if len(line_annt) != 13 or line_annt[0] != 'line' or line_annt[-4] == '3':
continue
if line_annt[-4] in ['0', '1']:
l.append(np.array([int(line_annt[i + 1]) for i in range(8)]))
# continue
# if line_annt[-4] in ['1', '5']:
# l_ign.append(np.array([int(line_annt[i + 1]) for i in range(8)]))
# continue
return l, l_ign
# 标点
def colorize(points_list, img, save_path, item, line, point_color):
save_path = os.path.join(save_path, str(
item.strip('.jpg'))+"_"+str(line)+".jpg")
img2 = img.copy()
# print(save_path)
# points_list = 384 * np.abs(np.array(outputs[0], dtype=np.float))
point_size = 1
thickness = 4 # 可以为 0、4、8
for i in range(4):
cv2.circle(img2, (int(points_list[i][0]), int(points_list[i][1])),
point_size, point_color, thickness)
# print(save_path)
cv2.imwrite(save_path, img2)
# 画线
def paint_line(img, dst, cropimg_path, num):
img2 = img.copy()
cv2.line(img2, (int(dst[0][0]), int(dst[0][1])), (int(
dst[1][0]), int(dst[1][1])), (255, 0, 0), 5)
cv2.line(img2, (int(dst[1][0]), int(dst[1][1])), (int(
dst[2][0]), int(dst[2][1])), (255, 0, 0), 5)
cv2.line(img2, (int(dst[2][0]), int(dst[2][1])), (int(
dst[3][0]), int(dst[3][1])), (255, 0, 0), 5)
cv2.line(img2, (int(dst[3][0]), int(dst[3][1])), (int(
dst[0][0]), int(dst[0][1])), (255, 0, 0), 5)
cropimg_path1 = os.path.join(
cropimg_path, i.strip('.jpg')+'_'+str(num)+'.jpg')
cv2.imwrite(cropimg_path1, img2)
def Crop_pic(ps, img_path, cropimg_path, perspective_path, txt_file, i, trans_path, save_path1, save_path2):
# single pic
img = cv2.imread(img_path)
perspective3 = np.float32([[0, 0], [383, 0], [383, 383], [0, 383]])
perspective3_ = np.float32([[0, 0], [383, 0], [383, 383]])
num = 0
for line in ps:
num = num + 1
# 随机生成4个坐标
arr0 = random.randint(80, 120)
arr1 = random.randint(80, 120)
arr2 = random.randint(263, 303)
arr3 = random.randint(80, 120)
arr4 = random.randint(263, 303)
arr5 = random.randint(263, 303)
arr6 = random.randint(80, 120)
arr7 = random.randint(263, 303)
perspective0 = np.float32([[line[0], line[1]], [line[2], line[3]], [
line[4], line[5]], [line[6], line[7]]])
perspective0_ = np.float32([[line[0], line[1]], [line[2], line[3]], [
line[4], line[5]]])
colorize(perspective0, img, save_path1, i, num, (0, 255, 0))
perspective1 = np.float32(
[[arr0, arr1], [arr2, arr3], [arr4, arr5], [arr6, arr7]])
perspective1_ = np.float32(
[[arr0, arr1], [arr2, arr3], [arr4, arr5]])
# 求逆变换矩阵
# trans_inv = cv2.getPerspectiveTransform(perspective1, perspective0)
trans_inv = cv2.getAffineTransform(perspective1_, perspective0_)
# 求逆投影变换后的点坐标
dst = []
# mat = np.array(
# [[[0, 0], [383, 0], [383, 383], [0, 383]]], dtype=np.float32)
mat = np.array(
[[0, 0, 1], [383, 0, 1], [383, 383, 1], [0, 383, 1]], dtype=np.float32)
mat = mat.transpose()
# dst = cv2.perspectiveTransform(mat, trans_inv)
dst = np.dot(trans_inv, mat)
dst = dst.transpose()
# 画线
paint_line(img, dst, cropimg_path, num)
# 将停车位投影变换后得到在384*384分辨率下的停车位图像
# perspective2 = np.float32([[dst[0][0][0], dst[0][0][1]], [dst[0][1][0], dst[0][1][1]], [
# dst[0][2][0], dst[0][2][1]], [dst[0][3][0], dst[0][3][1]]])
perspective2_ = np.float32([[dst[0][0], dst[0][1]], [dst[1][0], dst[1][1]], [
dst[2][0], dst[2][1]]])
# trans = cv2.getPerspectiveTransform(perspective2, perspective3)
# dst2 = cv2.warpPerspective(img, trans, (384, 384))
trans = cv2.getAffineTransform(perspective2_, perspective3_)
dst2 = cv2.warpAffine(img, trans, (384, 384))
# 保存原图四个内角点在384*384图片上的坐标
# mat2 = np.array([[[line[0], line[1]], [line[2], line[3]], [
# line[4], line[5]], [line[6], line[7]]]], dtype=np.float32)
mat2 = np.array([[line[0], line[1], 1], [line[2], line[3], 1], [
line[4], line[5], 1], [line[6], line[7], 1]], dtype=np.float32)
mat2 = mat2.transpose()
point = np.dot(trans, mat2)
point = point.transpose()
# point = cv2.perspectiveTransform(mat2, trans)
# point = np.dot(mat2, trans)
perspective_path1 = os.path.join(
perspective_path, i.strip('.jpg')+'_'+str(num)+'.jpg')
# print(perspective_path)
cv2.imwrite(perspective_path1, dst2)
colorize(point, dst2, save_path2, i, num, (0, 255, 0))
# 把四个坐标点记录下来
txt_file1 = os.path.join(
txt_file, i.strip('.jpg')+'_'+str(num)+'_OA.txt')
with open(txt_file1, "w") as f:
for j in range(4):
f.write(str(point[j][0]))
f.write(' ')
f.write(str(point[j][1]))
f.write('\n')
# 把转换矩阵记录下来
trans_path1 = os.path.join(
trans_path, i.strip('.jpg')+'_'+str(num)+'.txt')
with open(trans_path1, "w") as ff:
for j in range(2):
for k in range(3):
ff.write(str(trans_inv[j][k]))
ff.write(" ")
# 计算四个点的预测点与真值点之间的误差
def get_acc(y, y_hat, dis):
total = 0
total = 0
for i in range(4):
total += ((y[i][0]-y_hat[i][0])**2 + (y[i][1]-y_hat[i][1])**2)**0.5
total /= 4
if total < dis:
return 1
else:
return 0
def output_pic(img_path, output_path, trans_path, fina_path, ps2, pix, point_path):
img_pred = cv2.imread(img_path)
point_pred = []
trans_inv = []
point_pred = np.loadtxt(output_path)
point_pred = 384*np.expand_dims(point_pred, axis=0)
trans_inv = np.loadtxt(trans_path)
trans_inv = trans_inv.reshape(3, 3)
trans_inv = np.mat(trans_inv)
point_ground = np.loadtxt(point_path)
point_ground = np.expand_dims(point_ground, axis=0)
point_ground2 = cv2.perspectiveTransform(point_ground, trans_inv)
point_size = 1
thickness = 4
for i in range(4):
cv2.circle(img_pred, (int(point_ground2[0][i][0]), int(point_ground2[0][i][1])),
point_size, (0, 255, 0), thickness)
cv2.imwrite(fina_path, img_pred)
point_pred2 = cv2.perspectiveTransform(point_pred, trans_inv)
# 红色
point_color = (0, 0, 255)
point_color2 = (0, 255, 0)
for i in range(4):
cv2.circle(img_pred, (int(point_pred2[0][i][0]), int(point_pred2[0][i][1])),
point_size, point_color, thickness)
cv2.imwrite(fina_path, img_pred)
point_pred3 = point_pred2[0]
ps2 = ps2[0].reshape(4, 2)
tmp = get_acc(point_pred3, point_ground2[0], pix)
return tmp
# 精度
def output(pix):
accuracy = 0
for i in os.listdir(test_dir):
output_path = os.path.join(
"/media/alpha4TB/ziqi/Parking/CNN/output", i.strip('.jpg')+'.txt')
img_path = os.path.join(
"/media/alpha4TB/ziqi/Parking/Ps_locate_dataset/img", i)
trans_inv = os.path.join(
"/media/alpha4TB/ziqi/Parking/Ps_locate_dataset/trans_inv", i.strip('.jpg')+'.txt')
fina_path = os.path.join(
"/media/alpha4TB/ziqi/Parking/Ps_locate_dataset/fina", i)
annt_path2 = os.path.join(
'./Ps_locate_dataset/annt', i.strip('.jpg')+'_OA.txt')
point_path = os.path.join(
"/media/alpha4TB/ziqi/Parking/Ps_locate_dataset/point", i.strip('.jpg')+'_OA.txt')
# print(fina_path)
ps2, _ = read_pslot(annt_path2)
tmp = output_pic(img_path, output_path,
trans_inv, fina_path, ps2, pix, point_path)
accuracy += tmp
return accuracy
if __name__ == "__main__":
data_dir = '/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/pic'
label_dir = '/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/annotation'
crop_dir = '/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/crop_img'
perspective_dir = '/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/perspective_img'
txt_dir = '/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/point'
cnt = 0
f1 = open(
"/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/train_list.txt", "w")
# f2 = open("./Ps_locate_dataset/val_list.txt", "w")
test_dir = "/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/test_img"
trans_path = "/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/trans_inv"
save_path1 = "/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/src_img"
save_path2 = "/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/perspective2_img"
pbar = tqdm(total=len(os.listdir(data_dir)))
for i in os.listdir(data_dir):
# print(i)
annt_file = os.path.join(label_dir, i.strip('.jpg')+'_OA.txt')
img_path = os.path.join(data_dir, i)
ps, _ = read_pslot(annt_file)
Crop_pic(ps, img_path, crop_dir,
perspective_dir, txt_dir, i, trans_path, save_path1, save_path2)
pbar.update(1)
pbar.close()
# acc = []
# for k in range(31):
# print("k", k)
# x1 = output(k)
# x1 = 100 * x1 / 743
# acc.append(x1)
# x1 = round(x1, 3)
# print(acc)
# print(len(acc))
# # 设置画布大小
# plt.figure(figsize=(30, 15))
# # 标题
# plt.title("accruracy distribution")
# # 数据
# plt.bar(range(len(acc)), acc)
# # 横坐标描述
# plt.xlabel('pixel')
# # 纵坐标描述
# plt.ylabel('accuracy')
# # # 设置数字标签
# # for a, b in zip(x, acc):
# # plt.text(a, b, b, ha='center', va='bottom', fontsize=10)
# plt.savefig(
# "/media/alpha4TB/ziqi/Parking/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/accuracy.png")
# 保存训练数据的文件名
filenames = os.listdir(perspective_dir)
filenames.sort()
print(filenames[0])
for i in os.listdir(perspective_dir):
perspective_path = os.path.join(perspective_dir, i)
f1.write(perspective_path)
f1.write('\n')
f1.close()
| preprocessing/make_dataset_new.py | 11,369 | plt 用于显示图片 标注文件数据处理 print(annt_file) print("annt", annt) print(line_annt) continue if line_annt[-4] in ['1', '5']: l_ign.append(np.array([int(line_annt[i + 1]) for i in range(8)])) continue 标点 print(save_path) points_list = 384 * np.abs(np.array(outputs[0], dtype=np.float)) 可以为 0、4、8 print(save_path) 画线 single pic 随机生成4个坐标 求逆变换矩阵 trans_inv = cv2.getPerspectiveTransform(perspective1, perspective0) 求逆投影变换后的点坐标 mat = np.array( [[[0, 0], [383, 0], [383, 383], [0, 383]]], dtype=np.float32) dst = cv2.perspectiveTransform(mat, trans_inv) 画线 将停车位投影变换后得到在384*384分辨率下的停车位图像 perspective2 = np.float32([[dst[0][0][0], dst[0][0][1]], [dst[0][1][0], dst[0][1][1]], [ dst[0][2][0], dst[0][2][1]], [dst[0][3][0], dst[0][3][1]]]) trans = cv2.getPerspectiveTransform(perspective2, perspective3) dst2 = cv2.warpPerspective(img, trans, (384, 384)) 保存原图四个内角点在384*384图片上的坐标 mat2 = np.array([[[line[0], line[1]], [line[2], line[3]], [ line[4], line[5]], [line[6], line[7]]]], dtype=np.float32) point = cv2.perspectiveTransform(mat2, trans) point = np.dot(mat2, trans) print(perspective_path) 把四个坐标点记录下来 把转换矩阵记录下来 计算四个点的预测点与真值点之间的误差 红色 精度 print(fina_path) f2 = open("./Ps_locate_dataset/val_list.txt", "w") print(i) acc = [] for k in range(31): print("k", k) x1 = output(k) x1 = 100 * x1 / 743 acc.append(x1) x1 = round(x1, 3) print(acc) print(len(acc)) 设置画布大小 plt.figure(figsize=(30, 15)) 标题 plt.title("accruracy distribution") 数据 plt.bar(range(len(acc)), acc) 横坐标描述 plt.xlabel('pixel') 纵坐标描述 plt.ylabel('accuracy') 设置数字标签 for a, b in zip(x, acc): plt.text(a, b, b, ha='center', va='bottom', fontsize=10) plt.savefig( "/media/alpha4TB/ziqi/Parking/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/accuracy.png") 保存训练数据的文件名 | 1,794 | zh | 0.23805 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/vision_v1p1beta1/proto/image_annotator.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2
from google.cloud.vision_v1p1beta1.proto import geometry_pb2 as google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2
from google.cloud.vision_v1p1beta1.proto import text_annotation_pb2 as google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_text__annotation__pb2
from google.cloud.vision_v1p1beta1.proto import web_detection_pb2 as google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_web__detection__pb2
from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2
from google.type import color_pb2 as google_dot_type_dot_color__pb2
from google.type import latlng_pb2 as google_dot_type_dot_latlng__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='google/cloud/vision_v1p1beta1/proto/image_annotator.proto',
package='google.cloud.vision.v1p1beta1',
syntax='proto3',
serialized_pb=_b('\n9google/cloud/vision_v1p1beta1/proto/image_annotator.proto\x12\x1dgoogle.cloud.vision.v1p1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x32google/cloud/vision_v1p1beta1/proto/geometry.proto\x1a\x39google/cloud/vision_v1p1beta1/proto/text_annotation.proto\x1a\x37google/cloud/vision_v1p1beta1/proto/web_detection.proto\x1a\x17google/rpc/status.proto\x1a\x17google/type/color.proto\x1a\x18google/type/latlng.proto\"\xe1\x02\n\x07\x46\x65\x61ture\x12\x39\n\x04type\x18\x01 \x01(\x0e\x32+.google.cloud.vision.v1p1beta1.Feature.Type\x12\x13\n\x0bmax_results\x18\x02 \x01(\x05\x12\r\n\x05model\x18\x03 \x01(\t\"\xf6\x01\n\x04Type\x12\x14\n\x10TYPE_UNSPECIFIED\x10\x00\x12\x12\n\x0e\x46\x41\x43\x45_DETECTION\x10\x01\x12\x16\n\x12LANDMARK_DETECTION\x10\x02\x12\x12\n\x0eLOGO_DETECTION\x10\x03\x12\x13\n\x0fLABEL_DETECTION\x10\x04\x12\x12\n\x0eTEXT_DETECTION\x10\x05\x12\x1b\n\x17\x44OCUMENT_TEXT_DETECTION\x10\x0b\x12\x19\n\x15SAFE_SEARCH_DETECTION\x10\x06\x12\x14\n\x10IMAGE_PROPERTIES\x10\x07\x12\x0e\n\nCROP_HINTS\x10\t\x12\x11\n\rWEB_DETECTION\x10\n\"7\n\x0bImageSource\x12\x15\n\rgcs_image_uri\x18\x01 \x01(\t\x12\x11\n\timage_uri\x18\x02 \x01(\t\"T\n\x05Image\x12\x0f\n\x07\x63ontent\x18\x01 \x01(\x0c\x12:\n\x06source\x18\x02 \x01(\x0b\x32*.google.cloud.vision.v1p1beta1.ImageSource\"\x9b\x0e\n\x0e\x46\x61\x63\x65\x41nnotation\x12\x42\n\rbounding_poly\x18\x01 \x01(\x0b\x32+.google.cloud.vision.v1p1beta1.BoundingPoly\x12\x45\n\x10\x66\x64_bounding_poly\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p1beta1.BoundingPoly\x12I\n\tlandmarks\x18\x03 \x03(\x0b\x32\x36.google.cloud.vision.v1p1beta1.FaceAnnotation.Landmark\x12\x12\n\nroll_angle\x18\x04 \x01(\x02\x12\x11\n\tpan_angle\x18\x05 \x01(\x02\x12\x12\n\ntilt_angle\x18\x06 \x01(\x02\x12\x1c\n\x14\x64\x65tection_confidence\x18\x07 \x01(\x02\x12\x1e\n\x16landmarking_confidence\x18\x08 \x01(\x02\x12\x41\n\x0ejoy_likelihood\x18\t \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12\x44\n\x11sorrow_likelihood\x18\n \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12\x43\n\x10\x61nger_likelihood\x18\x0b \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12\x46\n\x13surprise_likelihood\x18\x0c \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12K\n\x18under_exposed_likelihood\x18\r \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12\x45\n\x12\x62lurred_likelihood\x18\x0e \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12\x46\n\x13headwear_likelihood\x18\x0f \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x1a\xc7\x07\n\x08Landmark\x12I\n\x04type\x18\x03 \x01(\x0e\x32;.google.cloud.vision.v1p1beta1.FaceAnnotation.Landmark.Type\x12\x39\n\x08position\x18\x04 \x01(\x0b\x32\'.google.cloud.vision.v1p1beta1.Position\"\xb4\x06\n\x04Type\x12\x14\n\x10UNKNOWN_LANDMARK\x10\x00\x12\x0c\n\x08LEFT_EYE\x10\x01\x12\r\n\tRIGHT_EYE\x10\x02\x12\x18\n\x14LEFT_OF_LEFT_EYEBROW\x10\x03\x12\x19\n\x15RIGHT_OF_LEFT_EYEBROW\x10\x04\x12\x19\n\x15LEFT_OF_RIGHT_EYEBROW\x10\x05\x12\x1a\n\x16RIGHT_OF_RIGHT_EYEBROW\x10\x06\x12\x19\n\x15MIDPOINT_BETWEEN_EYES\x10\x07\x12\x0c\n\x08NOSE_TIP\x10\x08\x12\r\n\tUPPER_LIP\x10\t\x12\r\n\tLOWER_LIP\x10\n\x12\x0e\n\nMOUTH_LEFT\x10\x0b\x12\x0f\n\x0bMOUTH_RIGHT\x10\x0c\x12\x10\n\x0cMOUTH_CENTER\x10\r\x12\x15\n\x11NOSE_BOTTOM_RIGHT\x10\x0e\x12\x14\n\x10NOSE_BOTTOM_LEFT\x10\x0f\x12\x16\n\x12NOSE_BOTTOM_CENTER\x10\x10\x12\x19\n\x15LEFT_EYE_TOP_BOUNDARY\x10\x11\x12\x19\n\x15LEFT_EYE_RIGHT_CORNER\x10\x12\x12\x1c\n\x18LEFT_EYE_BOTTOM_BOUNDARY\x10\x13\x12\x18\n\x14LEFT_EYE_LEFT_CORNER\x10\x14\x12\x1a\n\x16RIGHT_EYE_TOP_BOUNDARY\x10\x15\x12\x1a\n\x16RIGHT_EYE_RIGHT_CORNER\x10\x16\x12\x1d\n\x19RIGHT_EYE_BOTTOM_BOUNDARY\x10\x17\x12\x19\n\x15RIGHT_EYE_LEFT_CORNER\x10\x18\x12\x1f\n\x1bLEFT_EYEBROW_UPPER_MIDPOINT\x10\x19\x12 \n\x1cRIGHT_EYEBROW_UPPER_MIDPOINT\x10\x1a\x12\x14\n\x10LEFT_EAR_TRAGION\x10\x1b\x12\x15\n\x11RIGHT_EAR_TRAGION\x10\x1c\x12\x12\n\x0eLEFT_EYE_PUPIL\x10\x1d\x12\x13\n\x0fRIGHT_EYE_PUPIL\x10\x1e\x12\x15\n\x11\x46OREHEAD_GLABELLA\x10\x1f\x12\x11\n\rCHIN_GNATHION\x10 \x12\x14\n\x10\x43HIN_LEFT_GONION\x10!\x12\x15\n\x11\x43HIN_RIGHT_GONION\x10\"\"4\n\x0cLocationInfo\x12$\n\x07lat_lng\x18\x01 \x01(\x0b\x32\x13.google.type.LatLng\"=\n\x08Property\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t\x12\x14\n\x0cuint64_value\x18\x03 \x01(\x04\"\xbc\x02\n\x10\x45ntityAnnotation\x12\x0b\n\x03mid\x18\x01 \x01(\t\x12\x0e\n\x06locale\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\x12\r\n\x05score\x18\x04 \x01(\x02\x12\x12\n\nconfidence\x18\x05 \x01(\x02\x12\x12\n\ntopicality\x18\x06 \x01(\x02\x12\x42\n\rbounding_poly\x18\x07 \x01(\x0b\x32+.google.cloud.vision.v1p1beta1.BoundingPoly\x12>\n\tlocations\x18\x08 \x03(\x0b\x32+.google.cloud.vision.v1p1beta1.LocationInfo\x12;\n\nproperties\x18\t \x03(\x0b\x32\'.google.cloud.vision.v1p1beta1.Property\"\xbc\x02\n\x14SafeSearchAnnotation\x12\x38\n\x05\x61\x64ult\x18\x01 \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12\x38\n\x05spoof\x18\x02 \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12:\n\x07medical\x18\x03 \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12;\n\x08violence\x18\x04 \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12\x37\n\x04racy\x18\t \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\"a\n\x0bLatLongRect\x12(\n\x0bmin_lat_lng\x18\x01 \x01(\x0b\x32\x13.google.type.LatLng\x12(\n\x0bmax_lat_lng\x18\x02 \x01(\x0b\x32\x13.google.type.LatLng\"U\n\tColorInfo\x12!\n\x05\x63olor\x18\x01 \x01(\x0b\x32\x12.google.type.Color\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x16\n\x0epixel_fraction\x18\x03 \x01(\x02\"T\n\x18\x44ominantColorsAnnotation\x12\x38\n\x06\x63olors\x18\x01 \x03(\x0b\x32(.google.cloud.vision.v1p1beta1.ColorInfo\"c\n\x0fImageProperties\x12P\n\x0f\x64ominant_colors\x18\x01 \x01(\x0b\x32\x37.google.cloud.vision.v1p1beta1.DominantColorsAnnotation\"\x7f\n\x08\x43ropHint\x12\x42\n\rbounding_poly\x18\x01 \x01(\x0b\x32+.google.cloud.vision.v1p1beta1.BoundingPoly\x12\x12\n\nconfidence\x18\x02 \x01(\x02\x12\x1b\n\x13importance_fraction\x18\x03 \x01(\x02\"R\n\x13\x43ropHintsAnnotation\x12;\n\ncrop_hints\x18\x01 \x03(\x0b\x32\'.google.cloud.vision.v1p1beta1.CropHint\"(\n\x0f\x43ropHintsParams\x12\x15\n\raspect_ratios\x18\x01 \x03(\x02\"1\n\x12WebDetectionParams\x12\x1b\n\x13include_geo_results\x18\x02 \x01(\x08\"\x85\x02\n\x0cImageContext\x12\x41\n\rlat_long_rect\x18\x01 \x01(\x0b\x32*.google.cloud.vision.v1p1beta1.LatLongRect\x12\x16\n\x0elanguage_hints\x18\x02 \x03(\t\x12I\n\x11\x63rop_hints_params\x18\x04 \x01(\x0b\x32..google.cloud.vision.v1p1beta1.CropHintsParams\x12O\n\x14web_detection_params\x18\x06 \x01(\x0b\x32\x31.google.cloud.vision.v1p1beta1.WebDetectionParams\"\xc9\x01\n\x14\x41nnotateImageRequest\x12\x33\n\x05image\x18\x01 \x01(\x0b\x32$.google.cloud.vision.v1p1beta1.Image\x12\x38\n\x08\x66\x65\x61tures\x18\x02 \x03(\x0b\x32&.google.cloud.vision.v1p1beta1.Feature\x12\x42\n\rimage_context\x18\x03 \x01(\x0b\x32+.google.cloud.vision.v1p1beta1.ImageContext\"\xc2\x06\n\x15\x41nnotateImageResponse\x12G\n\x10\x66\x61\x63\x65_annotations\x18\x01 \x03(\x0b\x32-.google.cloud.vision.v1p1beta1.FaceAnnotation\x12M\n\x14landmark_annotations\x18\x02 \x03(\x0b\x32/.google.cloud.vision.v1p1beta1.EntityAnnotation\x12I\n\x10logo_annotations\x18\x03 \x03(\x0b\x32/.google.cloud.vision.v1p1beta1.EntityAnnotation\x12J\n\x11label_annotations\x18\x04 \x03(\x0b\x32/.google.cloud.vision.v1p1beta1.EntityAnnotation\x12I\n\x10text_annotations\x18\x05 \x03(\x0b\x32/.google.cloud.vision.v1p1beta1.EntityAnnotation\x12K\n\x14\x66ull_text_annotation\x18\x0c \x01(\x0b\x32-.google.cloud.vision.v1p1beta1.TextAnnotation\x12S\n\x16safe_search_annotation\x18\x06 \x01(\x0b\x32\x33.google.cloud.vision.v1p1beta1.SafeSearchAnnotation\x12S\n\x1bimage_properties_annotation\x18\x08 \x01(\x0b\x32..google.cloud.vision.v1p1beta1.ImageProperties\x12Q\n\x15\x63rop_hints_annotation\x18\x0b \x01(\x0b\x32\x32.google.cloud.vision.v1p1beta1.CropHintsAnnotation\x12\x42\n\rweb_detection\x18\r \x01(\x0b\x32+.google.cloud.vision.v1p1beta1.WebDetection\x12!\n\x05\x65rror\x18\t \x01(\x0b\x32\x12.google.rpc.Status\"c\n\x1a\x42\x61tchAnnotateImagesRequest\x12\x45\n\x08requests\x18\x01 \x03(\x0b\x32\x33.google.cloud.vision.v1p1beta1.AnnotateImageRequest\"f\n\x1b\x42\x61tchAnnotateImagesResponse\x12G\n\tresponses\x18\x01 \x03(\x0b\x32\x34.google.cloud.vision.v1p1beta1.AnnotateImageResponse*e\n\nLikelihood\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x11\n\rVERY_UNLIKELY\x10\x01\x12\x0c\n\x08UNLIKELY\x10\x02\x12\x0c\n\x08POSSIBLE\x10\x03\x12\n\n\x06LIKELY\x10\x04\x12\x0f\n\x0bVERY_LIKELY\x10\x05\x32\xc6\x01\n\x0eImageAnnotator\x12\xb3\x01\n\x13\x42\x61tchAnnotateImages\x12\x39.google.cloud.vision.v1p1beta1.BatchAnnotateImagesRequest\x1a:.google.cloud.vision.v1p1beta1.BatchAnnotateImagesResponse\"%\x82\xd3\xe4\x93\x02\x1f\"\x1a/v1p1beta1/images:annotate:\x01*B\x82\x01\n!com.google.cloud.vision.v1p1beta1B\x13ImageAnnotatorProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p1beta1;vision\xf8\x01\x01\x62\x06proto3')
,
dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2.DESCRIPTOR,google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_text__annotation__pb2.DESCRIPTOR,google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_web__detection__pb2.DESCRIPTOR,google_dot_rpc_dot_status__pb2.DESCRIPTOR,google_dot_type_dot_color__pb2.DESCRIPTOR,google_dot_type_dot_latlng__pb2.DESCRIPTOR,])
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_LIKELIHOOD = _descriptor.EnumDescriptor(
name='Likelihood',
full_name='google.cloud.vision.v1p1beta1.Likelihood',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='UNKNOWN', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='VERY_UNLIKELY', index=1, number=1,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='UNLIKELY', index=2, number=2,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='POSSIBLE', index=3, number=3,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LIKELY', index=4, number=4,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='VERY_LIKELY', index=5, number=5,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=5631,
serialized_end=5732,
)
_sym_db.RegisterEnumDescriptor(_LIKELIHOOD)
Likelihood = enum_type_wrapper.EnumTypeWrapper(_LIKELIHOOD)
UNKNOWN = 0
VERY_UNLIKELY = 1
UNLIKELY = 2
POSSIBLE = 3
LIKELY = 4
VERY_LIKELY = 5
_FEATURE_TYPE = _descriptor.EnumDescriptor(
name='Type',
full_name='google.cloud.vision.v1p1beta1.Feature.Type',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='TYPE_UNSPECIFIED', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='FACE_DETECTION', index=1, number=1,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LANDMARK_DETECTION', index=2, number=2,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LOGO_DETECTION', index=3, number=3,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LABEL_DETECTION', index=4, number=4,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TEXT_DETECTION', index=5, number=5,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='DOCUMENT_TEXT_DETECTION', index=6, number=11,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SAFE_SEARCH_DETECTION', index=7, number=6,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='IMAGE_PROPERTIES', index=8, number=7,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CROP_HINTS', index=9, number=9,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='WEB_DETECTION', index=10, number=10,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=474,
serialized_end=720,
)
_sym_db.RegisterEnumDescriptor(_FEATURE_TYPE)
_FACEANNOTATION_LANDMARK_TYPE = _descriptor.EnumDescriptor(
name='Type',
full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.Landmark.Type',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='UNKNOWN_LANDMARK', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LEFT_EYE', index=1, number=1,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='RIGHT_EYE', index=2, number=2,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LEFT_OF_LEFT_EYEBROW', index=3, number=3,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='RIGHT_OF_LEFT_EYEBROW', index=4, number=4,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LEFT_OF_RIGHT_EYEBROW', index=5, number=5,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='RIGHT_OF_RIGHT_EYEBROW', index=6, number=6,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='MIDPOINT_BETWEEN_EYES', index=7, number=7,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='NOSE_TIP', index=8, number=8,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='UPPER_LIP', index=9, number=9,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LOWER_LIP', index=10, number=10,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='MOUTH_LEFT', index=11, number=11,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='MOUTH_RIGHT', index=12, number=12,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='MOUTH_CENTER', index=13, number=13,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='NOSE_BOTTOM_RIGHT', index=14, number=14,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='NOSE_BOTTOM_LEFT', index=15, number=15,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='NOSE_BOTTOM_CENTER', index=16, number=16,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LEFT_EYE_TOP_BOUNDARY', index=17, number=17,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LEFT_EYE_RIGHT_CORNER', index=18, number=18,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LEFT_EYE_BOTTOM_BOUNDARY', index=19, number=19,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LEFT_EYE_LEFT_CORNER', index=20, number=20,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='RIGHT_EYE_TOP_BOUNDARY', index=21, number=21,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='RIGHT_EYE_RIGHT_CORNER', index=22, number=22,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='RIGHT_EYE_BOTTOM_BOUNDARY', index=23, number=23,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='RIGHT_EYE_LEFT_CORNER', index=24, number=24,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LEFT_EYEBROW_UPPER_MIDPOINT', index=25, number=25,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='RIGHT_EYEBROW_UPPER_MIDPOINT', index=26, number=26,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LEFT_EAR_TRAGION', index=27, number=27,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='RIGHT_EAR_TRAGION', index=28, number=28,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LEFT_EYE_PUPIL', index=29, number=29,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='RIGHT_EYE_PUPIL', index=30, number=30,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='FOREHEAD_GLABELLA', index=31, number=31,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CHIN_GNATHION', index=32, number=32,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CHIN_LEFT_GONION', index=33, number=33,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CHIN_RIGHT_GONION', index=34, number=34,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=1865,
serialized_end=2685,
)
_sym_db.RegisterEnumDescriptor(_FACEANNOTATION_LANDMARK_TYPE)
_FEATURE = _descriptor.Descriptor(
name='Feature',
full_name='google.cloud.vision.v1p1beta1.Feature',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='type', full_name='google.cloud.vision.v1p1beta1.Feature.type', index=0,
number=1, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='max_results', full_name='google.cloud.vision.v1p1beta1.Feature.max_results', index=1,
number=2, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='model', full_name='google.cloud.vision.v1p1beta1.Feature.model', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
_FEATURE_TYPE,
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=367,
serialized_end=720,
)
_IMAGESOURCE = _descriptor.Descriptor(
name='ImageSource',
full_name='google.cloud.vision.v1p1beta1.ImageSource',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='gcs_image_uri', full_name='google.cloud.vision.v1p1beta1.ImageSource.gcs_image_uri', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='image_uri', full_name='google.cloud.vision.v1p1beta1.ImageSource.image_uri', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=722,
serialized_end=777,
)
_IMAGE = _descriptor.Descriptor(
name='Image',
full_name='google.cloud.vision.v1p1beta1.Image',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='content', full_name='google.cloud.vision.v1p1beta1.Image.content', index=0,
number=1, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='source', full_name='google.cloud.vision.v1p1beta1.Image.source', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=779,
serialized_end=863,
)
_FACEANNOTATION_LANDMARK = _descriptor.Descriptor(
name='Landmark',
full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.Landmark',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='type', full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.Landmark.type', index=0,
number=3, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='position', full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.Landmark.position', index=1,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
_FACEANNOTATION_LANDMARK_TYPE,
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1718,
serialized_end=2685,
)
_FACEANNOTATION = _descriptor.Descriptor(
name='FaceAnnotation',
full_name='google.cloud.vision.v1p1beta1.FaceAnnotation',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='bounding_poly', full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.bounding_poly', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='fd_bounding_poly', full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.fd_bounding_poly', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='landmarks', full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.landmarks', index=2,
number=3, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='roll_angle', full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.roll_angle', index=3,
number=4, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='pan_angle', full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.pan_angle', index=4,
number=5, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='tilt_angle', full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.tilt_angle', index=5,
number=6, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='detection_confidence', full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.detection_confidence', index=6,
number=7, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='landmarking_confidence', full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.landmarking_confidence', index=7,
number=8, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='joy_likelihood', full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.joy_likelihood', index=8,
number=9, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='sorrow_likelihood', full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.sorrow_likelihood', index=9,
number=10, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='anger_likelihood', full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.anger_likelihood', index=10,
number=11, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='surprise_likelihood', full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.surprise_likelihood', index=11,
number=12, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='under_exposed_likelihood', full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.under_exposed_likelihood', index=12,
number=13, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='blurred_likelihood', full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.blurred_likelihood', index=13,
number=14, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='headwear_likelihood', full_name='google.cloud.vision.v1p1beta1.FaceAnnotation.headwear_likelihood', index=14,
number=15, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[_FACEANNOTATION_LANDMARK, ],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=866,
serialized_end=2685,
)
_LOCATIONINFO = _descriptor.Descriptor(
name='LocationInfo',
full_name='google.cloud.vision.v1p1beta1.LocationInfo',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='lat_lng', full_name='google.cloud.vision.v1p1beta1.LocationInfo.lat_lng', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=2687,
serialized_end=2739,
)
_PROPERTY = _descriptor.Descriptor(
name='Property',
full_name='google.cloud.vision.v1p1beta1.Property',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='google.cloud.vision.v1p1beta1.Property.name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='value', full_name='google.cloud.vision.v1p1beta1.Property.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='uint64_value', full_name='google.cloud.vision.v1p1beta1.Property.uint64_value', index=2,
number=3, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=2741,
serialized_end=2802,
)
_ENTITYANNOTATION = _descriptor.Descriptor(
name='EntityAnnotation',
full_name='google.cloud.vision.v1p1beta1.EntityAnnotation',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='mid', full_name='google.cloud.vision.v1p1beta1.EntityAnnotation.mid', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='locale', full_name='google.cloud.vision.v1p1beta1.EntityAnnotation.locale', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='description', full_name='google.cloud.vision.v1p1beta1.EntityAnnotation.description', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='score', full_name='google.cloud.vision.v1p1beta1.EntityAnnotation.score', index=3,
number=4, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='confidence', full_name='google.cloud.vision.v1p1beta1.EntityAnnotation.confidence', index=4,
number=5, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='topicality', full_name='google.cloud.vision.v1p1beta1.EntityAnnotation.topicality', index=5,
number=6, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='bounding_poly', full_name='google.cloud.vision.v1p1beta1.EntityAnnotation.bounding_poly', index=6,
number=7, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='locations', full_name='google.cloud.vision.v1p1beta1.EntityAnnotation.locations', index=7,
number=8, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='properties', full_name='google.cloud.vision.v1p1beta1.EntityAnnotation.properties', index=8,
number=9, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=2805,
serialized_end=3121,
)
_SAFESEARCHANNOTATION = _descriptor.Descriptor(
name='SafeSearchAnnotation',
full_name='google.cloud.vision.v1p1beta1.SafeSearchAnnotation',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='adult', full_name='google.cloud.vision.v1p1beta1.SafeSearchAnnotation.adult', index=0,
number=1, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='spoof', full_name='google.cloud.vision.v1p1beta1.SafeSearchAnnotation.spoof', index=1,
number=2, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='medical', full_name='google.cloud.vision.v1p1beta1.SafeSearchAnnotation.medical', index=2,
number=3, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='violence', full_name='google.cloud.vision.v1p1beta1.SafeSearchAnnotation.violence', index=3,
number=4, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='racy', full_name='google.cloud.vision.v1p1beta1.SafeSearchAnnotation.racy', index=4,
number=9, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=3124,
serialized_end=3440,
)
_LATLONGRECT = _descriptor.Descriptor(
name='LatLongRect',
full_name='google.cloud.vision.v1p1beta1.LatLongRect',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='min_lat_lng', full_name='google.cloud.vision.v1p1beta1.LatLongRect.min_lat_lng', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='max_lat_lng', full_name='google.cloud.vision.v1p1beta1.LatLongRect.max_lat_lng', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=3442,
serialized_end=3539,
)
_COLORINFO = _descriptor.Descriptor(
name='ColorInfo',
full_name='google.cloud.vision.v1p1beta1.ColorInfo',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='color', full_name='google.cloud.vision.v1p1beta1.ColorInfo.color', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='score', full_name='google.cloud.vision.v1p1beta1.ColorInfo.score', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='pixel_fraction', full_name='google.cloud.vision.v1p1beta1.ColorInfo.pixel_fraction', index=2,
number=3, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=3541,
serialized_end=3626,
)
_DOMINANTCOLORSANNOTATION = _descriptor.Descriptor(
name='DominantColorsAnnotation',
full_name='google.cloud.vision.v1p1beta1.DominantColorsAnnotation',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='colors', full_name='google.cloud.vision.v1p1beta1.DominantColorsAnnotation.colors', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=3628,
serialized_end=3712,
)
_IMAGEPROPERTIES = _descriptor.Descriptor(
name='ImageProperties',
full_name='google.cloud.vision.v1p1beta1.ImageProperties',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='dominant_colors', full_name='google.cloud.vision.v1p1beta1.ImageProperties.dominant_colors', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=3714,
serialized_end=3813,
)
_CROPHINT = _descriptor.Descriptor(
name='CropHint',
full_name='google.cloud.vision.v1p1beta1.CropHint',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='bounding_poly', full_name='google.cloud.vision.v1p1beta1.CropHint.bounding_poly', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='confidence', full_name='google.cloud.vision.v1p1beta1.CropHint.confidence', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='importance_fraction', full_name='google.cloud.vision.v1p1beta1.CropHint.importance_fraction', index=2,
number=3, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=3815,
serialized_end=3942,
)
_CROPHINTSANNOTATION = _descriptor.Descriptor(
name='CropHintsAnnotation',
full_name='google.cloud.vision.v1p1beta1.CropHintsAnnotation',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='crop_hints', full_name='google.cloud.vision.v1p1beta1.CropHintsAnnotation.crop_hints', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=3944,
serialized_end=4026,
)
_CROPHINTSPARAMS = _descriptor.Descriptor(
name='CropHintsParams',
full_name='google.cloud.vision.v1p1beta1.CropHintsParams',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='aspect_ratios', full_name='google.cloud.vision.v1p1beta1.CropHintsParams.aspect_ratios', index=0,
number=1, type=2, cpp_type=6, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=4028,
serialized_end=4068,
)
_WEBDETECTIONPARAMS = _descriptor.Descriptor(
name='WebDetectionParams',
full_name='google.cloud.vision.v1p1beta1.WebDetectionParams',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='include_geo_results', full_name='google.cloud.vision.v1p1beta1.WebDetectionParams.include_geo_results', index=0,
number=2, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=4070,
serialized_end=4119,
)
_IMAGECONTEXT = _descriptor.Descriptor(
name='ImageContext',
full_name='google.cloud.vision.v1p1beta1.ImageContext',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='lat_long_rect', full_name='google.cloud.vision.v1p1beta1.ImageContext.lat_long_rect', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='language_hints', full_name='google.cloud.vision.v1p1beta1.ImageContext.language_hints', index=1,
number=2, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='crop_hints_params', full_name='google.cloud.vision.v1p1beta1.ImageContext.crop_hints_params', index=2,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='web_detection_params', full_name='google.cloud.vision.v1p1beta1.ImageContext.web_detection_params', index=3,
number=6, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=4122,
serialized_end=4383,
)
_ANNOTATEIMAGEREQUEST = _descriptor.Descriptor(
name='AnnotateImageRequest',
full_name='google.cloud.vision.v1p1beta1.AnnotateImageRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='image', full_name='google.cloud.vision.v1p1beta1.AnnotateImageRequest.image', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='features', full_name='google.cloud.vision.v1p1beta1.AnnotateImageRequest.features', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='image_context', full_name='google.cloud.vision.v1p1beta1.AnnotateImageRequest.image_context', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=4386,
serialized_end=4587,
)
_ANNOTATEIMAGERESPONSE = _descriptor.Descriptor(
name='AnnotateImageResponse',
full_name='google.cloud.vision.v1p1beta1.AnnotateImageResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='face_annotations', full_name='google.cloud.vision.v1p1beta1.AnnotateImageResponse.face_annotations', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='landmark_annotations', full_name='google.cloud.vision.v1p1beta1.AnnotateImageResponse.landmark_annotations', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='logo_annotations', full_name='google.cloud.vision.v1p1beta1.AnnotateImageResponse.logo_annotations', index=2,
number=3, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='label_annotations', full_name='google.cloud.vision.v1p1beta1.AnnotateImageResponse.label_annotations', index=3,
number=4, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='text_annotations', full_name='google.cloud.vision.v1p1beta1.AnnotateImageResponse.text_annotations', index=4,
number=5, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='full_text_annotation', full_name='google.cloud.vision.v1p1beta1.AnnotateImageResponse.full_text_annotation', index=5,
number=12, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='safe_search_annotation', full_name='google.cloud.vision.v1p1beta1.AnnotateImageResponse.safe_search_annotation', index=6,
number=6, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='image_properties_annotation', full_name='google.cloud.vision.v1p1beta1.AnnotateImageResponse.image_properties_annotation', index=7,
number=8, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='crop_hints_annotation', full_name='google.cloud.vision.v1p1beta1.AnnotateImageResponse.crop_hints_annotation', index=8,
number=11, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='web_detection', full_name='google.cloud.vision.v1p1beta1.AnnotateImageResponse.web_detection', index=9,
number=13, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='error', full_name='google.cloud.vision.v1p1beta1.AnnotateImageResponse.error', index=10,
number=9, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=4590,
serialized_end=5424,
)
_BATCHANNOTATEIMAGESREQUEST = _descriptor.Descriptor(
name='BatchAnnotateImagesRequest',
full_name='google.cloud.vision.v1p1beta1.BatchAnnotateImagesRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='requests', full_name='google.cloud.vision.v1p1beta1.BatchAnnotateImagesRequest.requests', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=5426,
serialized_end=5525,
)
_BATCHANNOTATEIMAGESRESPONSE = _descriptor.Descriptor(
name='BatchAnnotateImagesResponse',
full_name='google.cloud.vision.v1p1beta1.BatchAnnotateImagesResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='responses', full_name='google.cloud.vision.v1p1beta1.BatchAnnotateImagesResponse.responses', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=5527,
serialized_end=5629,
)
_FEATURE.fields_by_name['type'].enum_type = _FEATURE_TYPE
_FEATURE_TYPE.containing_type = _FEATURE
_IMAGE.fields_by_name['source'].message_type = _IMAGESOURCE
_FACEANNOTATION_LANDMARK.fields_by_name['type'].enum_type = _FACEANNOTATION_LANDMARK_TYPE
_FACEANNOTATION_LANDMARK.fields_by_name['position'].message_type = google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2._POSITION
_FACEANNOTATION_LANDMARK.containing_type = _FACEANNOTATION
_FACEANNOTATION_LANDMARK_TYPE.containing_type = _FACEANNOTATION_LANDMARK
_FACEANNOTATION.fields_by_name['bounding_poly'].message_type = google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY
_FACEANNOTATION.fields_by_name['fd_bounding_poly'].message_type = google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY
_FACEANNOTATION.fields_by_name['landmarks'].message_type = _FACEANNOTATION_LANDMARK
_FACEANNOTATION.fields_by_name['joy_likelihood'].enum_type = _LIKELIHOOD
_FACEANNOTATION.fields_by_name['sorrow_likelihood'].enum_type = _LIKELIHOOD
_FACEANNOTATION.fields_by_name['anger_likelihood'].enum_type = _LIKELIHOOD
_FACEANNOTATION.fields_by_name['surprise_likelihood'].enum_type = _LIKELIHOOD
_FACEANNOTATION.fields_by_name['under_exposed_likelihood'].enum_type = _LIKELIHOOD
_FACEANNOTATION.fields_by_name['blurred_likelihood'].enum_type = _LIKELIHOOD
_FACEANNOTATION.fields_by_name['headwear_likelihood'].enum_type = _LIKELIHOOD
_LOCATIONINFO.fields_by_name['lat_lng'].message_type = google_dot_type_dot_latlng__pb2._LATLNG
_ENTITYANNOTATION.fields_by_name['bounding_poly'].message_type = google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY
_ENTITYANNOTATION.fields_by_name['locations'].message_type = _LOCATIONINFO
_ENTITYANNOTATION.fields_by_name['properties'].message_type = _PROPERTY
_SAFESEARCHANNOTATION.fields_by_name['adult'].enum_type = _LIKELIHOOD
_SAFESEARCHANNOTATION.fields_by_name['spoof'].enum_type = _LIKELIHOOD
_SAFESEARCHANNOTATION.fields_by_name['medical'].enum_type = _LIKELIHOOD
_SAFESEARCHANNOTATION.fields_by_name['violence'].enum_type = _LIKELIHOOD
_SAFESEARCHANNOTATION.fields_by_name['racy'].enum_type = _LIKELIHOOD
_LATLONGRECT.fields_by_name['min_lat_lng'].message_type = google_dot_type_dot_latlng__pb2._LATLNG
_LATLONGRECT.fields_by_name['max_lat_lng'].message_type = google_dot_type_dot_latlng__pb2._LATLNG
_COLORINFO.fields_by_name['color'].message_type = google_dot_type_dot_color__pb2._COLOR
_DOMINANTCOLORSANNOTATION.fields_by_name['colors'].message_type = _COLORINFO
_IMAGEPROPERTIES.fields_by_name['dominant_colors'].message_type = _DOMINANTCOLORSANNOTATION
_CROPHINT.fields_by_name['bounding_poly'].message_type = google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY
_CROPHINTSANNOTATION.fields_by_name['crop_hints'].message_type = _CROPHINT
_IMAGECONTEXT.fields_by_name['lat_long_rect'].message_type = _LATLONGRECT
_IMAGECONTEXT.fields_by_name['crop_hints_params'].message_type = _CROPHINTSPARAMS
_IMAGECONTEXT.fields_by_name['web_detection_params'].message_type = _WEBDETECTIONPARAMS
_ANNOTATEIMAGEREQUEST.fields_by_name['image'].message_type = _IMAGE
_ANNOTATEIMAGEREQUEST.fields_by_name['features'].message_type = _FEATURE
_ANNOTATEIMAGEREQUEST.fields_by_name['image_context'].message_type = _IMAGECONTEXT
_ANNOTATEIMAGERESPONSE.fields_by_name['face_annotations'].message_type = _FACEANNOTATION
_ANNOTATEIMAGERESPONSE.fields_by_name['landmark_annotations'].message_type = _ENTITYANNOTATION
_ANNOTATEIMAGERESPONSE.fields_by_name['logo_annotations'].message_type = _ENTITYANNOTATION
_ANNOTATEIMAGERESPONSE.fields_by_name['label_annotations'].message_type = _ENTITYANNOTATION
_ANNOTATEIMAGERESPONSE.fields_by_name['text_annotations'].message_type = _ENTITYANNOTATION
_ANNOTATEIMAGERESPONSE.fields_by_name['full_text_annotation'].message_type = google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_text__annotation__pb2._TEXTANNOTATION
_ANNOTATEIMAGERESPONSE.fields_by_name['safe_search_annotation'].message_type = _SAFESEARCHANNOTATION
_ANNOTATEIMAGERESPONSE.fields_by_name['image_properties_annotation'].message_type = _IMAGEPROPERTIES
_ANNOTATEIMAGERESPONSE.fields_by_name['crop_hints_annotation'].message_type = _CROPHINTSANNOTATION
_ANNOTATEIMAGERESPONSE.fields_by_name['web_detection'].message_type = google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_web__detection__pb2._WEBDETECTION
_ANNOTATEIMAGERESPONSE.fields_by_name['error'].message_type = google_dot_rpc_dot_status__pb2._STATUS
_BATCHANNOTATEIMAGESREQUEST.fields_by_name['requests'].message_type = _ANNOTATEIMAGEREQUEST
_BATCHANNOTATEIMAGESRESPONSE.fields_by_name['responses'].message_type = _ANNOTATEIMAGERESPONSE
DESCRIPTOR.message_types_by_name['Feature'] = _FEATURE
DESCRIPTOR.message_types_by_name['ImageSource'] = _IMAGESOURCE
DESCRIPTOR.message_types_by_name['Image'] = _IMAGE
DESCRIPTOR.message_types_by_name['FaceAnnotation'] = _FACEANNOTATION
DESCRIPTOR.message_types_by_name['LocationInfo'] = _LOCATIONINFO
DESCRIPTOR.message_types_by_name['Property'] = _PROPERTY
DESCRIPTOR.message_types_by_name['EntityAnnotation'] = _ENTITYANNOTATION
DESCRIPTOR.message_types_by_name['SafeSearchAnnotation'] = _SAFESEARCHANNOTATION
DESCRIPTOR.message_types_by_name['LatLongRect'] = _LATLONGRECT
DESCRIPTOR.message_types_by_name['ColorInfo'] = _COLORINFO
DESCRIPTOR.message_types_by_name['DominantColorsAnnotation'] = _DOMINANTCOLORSANNOTATION
DESCRIPTOR.message_types_by_name['ImageProperties'] = _IMAGEPROPERTIES
DESCRIPTOR.message_types_by_name['CropHint'] = _CROPHINT
DESCRIPTOR.message_types_by_name['CropHintsAnnotation'] = _CROPHINTSANNOTATION
DESCRIPTOR.message_types_by_name['CropHintsParams'] = _CROPHINTSPARAMS
DESCRIPTOR.message_types_by_name['WebDetectionParams'] = _WEBDETECTIONPARAMS
DESCRIPTOR.message_types_by_name['ImageContext'] = _IMAGECONTEXT
DESCRIPTOR.message_types_by_name['AnnotateImageRequest'] = _ANNOTATEIMAGEREQUEST
DESCRIPTOR.message_types_by_name['AnnotateImageResponse'] = _ANNOTATEIMAGERESPONSE
DESCRIPTOR.message_types_by_name['BatchAnnotateImagesRequest'] = _BATCHANNOTATEIMAGESREQUEST
DESCRIPTOR.message_types_by_name['BatchAnnotateImagesResponse'] = _BATCHANNOTATEIMAGESRESPONSE
DESCRIPTOR.enum_types_by_name['Likelihood'] = _LIKELIHOOD
Feature = _reflection.GeneratedProtocolMessageType('Feature', (_message.Message,), dict(
DESCRIPTOR = _FEATURE,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """Users describe the type of Google Cloud Vision API tasks to perform over
images by using *Feature*\ s. Each Feature indicates a type of image
detection task to perform. Features encode the Cloud Vision API vertical
to operate on and the number of top-scoring results to return.
Attributes:
type:
The feature type.
max_results:
Maximum number of results of this type.
model:
Model to use for the feature. Supported values:
"builtin/stable" (the default if unset) and "builtin/latest".
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.Feature)
))
_sym_db.RegisterMessage(Feature)
ImageSource = _reflection.GeneratedProtocolMessageType('ImageSource', (_message.Message,), dict(
DESCRIPTOR = _IMAGESOURCE,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """External image source (Google Cloud Storage image location).
Attributes:
gcs_image_uri:
NOTE: For new code ``image_uri`` below is preferred. Google
Cloud Storage image URI, which must be in the following form:
``gs://bucket_name/object_name`` (for details, see `Google
Cloud Storage Request URIs
<https://cloud.google.com/storage/docs/reference-uris>`__).
NOTE: Cloud Storage object versioning is not supported.
image_uri:
Image URI which supports: 1) Google Cloud Storage image URI,
which must be in the following form:
``gs://bucket_name/object_name`` (for details, see `Google
Cloud Storage Request URIs
<https://cloud.google.com/storage/docs/reference-uris>`__).
NOTE: Cloud Storage object versioning is not supported. 2)
Publicly accessible image HTTP/HTTPS URL. This is preferred
over the legacy ``gcs_image_uri`` above. When both
``gcs_image_uri`` and ``image_uri`` are specified,
``image_uri`` takes precedence.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.ImageSource)
))
_sym_db.RegisterMessage(ImageSource)
Image = _reflection.GeneratedProtocolMessageType('Image', (_message.Message,), dict(
DESCRIPTOR = _IMAGE,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """Client image to perform Google Cloud Vision API tasks over.
Attributes:
content:
Image content, represented as a stream of bytes. Note: as with
all ``bytes`` fields, protobuffers use a pure binary
representation, whereas JSON representations use base64.
source:
Google Cloud Storage image location. If both ``content`` and
``source`` are provided for an image, ``content`` takes
precedence and is used to perform the image annotation
request.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.Image)
))
_sym_db.RegisterMessage(Image)
FaceAnnotation = _reflection.GeneratedProtocolMessageType('FaceAnnotation', (_message.Message,), dict(
Landmark = _reflection.GeneratedProtocolMessageType('Landmark', (_message.Message,), dict(
DESCRIPTOR = _FACEANNOTATION_LANDMARK,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """A face-specific landmark (for example, a face feature).
Attributes:
type:
Face landmark type.
position:
Face landmark position.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.FaceAnnotation.Landmark)
))
,
DESCRIPTOR = _FACEANNOTATION,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """A face annotation object contains the results of face detection.
Attributes:
bounding_poly:
The bounding polygon around the face. The coordinates of the
bounding box are in the original image's scale, as returned in
``ImageParams``. The bounding box is computed to "frame" the
face in accordance with human expectations. It is based on the
landmarker results. Note that one or more x and/or y
coordinates may not be generated in the ``BoundingPoly`` (the
polygon will be unbounded) if only a partial face appears in
the image to be annotated.
fd_bounding_poly:
The ``fd_bounding_poly`` bounding polygon is tighter than the
``boundingPoly``, and encloses only the skin part of the face.
Typically, it is used to eliminate the face from any image
analysis that detects the "amount of skin" visible in an
image. It is not based on the landmarker results, only on the
initial face detection, hence the fd (face detection) prefix.
landmarks:
Detected face landmarks.
roll_angle:
Roll angle, which indicates the amount of clockwise/anti-
clockwise rotation of the face relative to the image vertical
about the axis perpendicular to the face. Range [-180,180].
pan_angle:
Yaw angle, which indicates the leftward/rightward angle that
the face is pointing relative to the vertical plane
perpendicular to the image. Range [-180,180].
tilt_angle:
Pitch angle, which indicates the upwards/downwards angle that
the face is pointing relative to the image's horizontal plane.
Range [-180,180].
detection_confidence:
Detection confidence. Range [0, 1].
landmarking_confidence:
Face landmarking confidence. Range [0, 1].
joy_likelihood:
Joy likelihood.
sorrow_likelihood:
Sorrow likelihood.
anger_likelihood:
Anger likelihood.
surprise_likelihood:
Surprise likelihood.
under_exposed_likelihood:
Under-exposed likelihood.
blurred_likelihood:
Blurred likelihood.
headwear_likelihood:
Headwear likelihood.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.FaceAnnotation)
))
_sym_db.RegisterMessage(FaceAnnotation)
_sym_db.RegisterMessage(FaceAnnotation.Landmark)
LocationInfo = _reflection.GeneratedProtocolMessageType('LocationInfo', (_message.Message,), dict(
DESCRIPTOR = _LOCATIONINFO,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """Detected entity location information.
Attributes:
lat_lng:
lat/long location coordinates.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.LocationInfo)
))
_sym_db.RegisterMessage(LocationInfo)
Property = _reflection.GeneratedProtocolMessageType('Property', (_message.Message,), dict(
DESCRIPTOR = _PROPERTY,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """A ``Property`` consists of a user-supplied name/value pair.
Attributes:
name:
Name of the property.
value:
Value of the property.
uint64_value:
Value of numeric properties.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.Property)
))
_sym_db.RegisterMessage(Property)
EntityAnnotation = _reflection.GeneratedProtocolMessageType('EntityAnnotation', (_message.Message,), dict(
DESCRIPTOR = _ENTITYANNOTATION,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """Set of detected entity features.
Attributes:
mid:
Opaque entity ID. Some IDs may be available in `Google
Knowledge Graph Search API
<https://developers.google.com/knowledge-graph/>`__.
locale:
The language code for the locale in which the entity textual
``description`` is expressed.
description:
Entity textual description, expressed in its ``locale``
language.
score:
Overall score of the result. Range [0, 1].
confidence:
The accuracy of the entity detection in an image. For example,
for an image in which the "Eiffel Tower" entity is detected,
this field represents the confidence that there is a tower in
the query image. Range [0, 1].
topicality:
The relevancy of the ICA (Image Content Annotation) label to
the image. For example, the relevancy of "tower" is likely
higher to an image containing the detected "Eiffel Tower" than
to an image containing a detected distant towering building,
even though the confidence that there is a tower in each image
may be the same. Range [0, 1].
bounding_poly:
Image region to which this entity belongs. Not produced for
``LABEL_DETECTION`` features.
locations:
The location information for the detected entity. Multiple
``LocationInfo`` elements can be present because one location
may indicate the location of the scene in the image, and
another location may indicate the location of the place where
the image was taken. Location information is usually present
for landmarks.
properties:
Some entities may have optional user-supplied ``Property``
(name/value) fields, such a score or string that qualifies the
entity.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.EntityAnnotation)
))
_sym_db.RegisterMessage(EntityAnnotation)
SafeSearchAnnotation = _reflection.GeneratedProtocolMessageType('SafeSearchAnnotation', (_message.Message,), dict(
DESCRIPTOR = _SAFESEARCHANNOTATION,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """Set of features pertaining to the image, computed by computer vision
methods over safe-search verticals (for example, adult, spoof, medical,
violence).
Attributes:
adult:
Represents the adult content likelihood for the image. Adult
content may contain elements such as nudity, pornographic
images or cartoons, or sexual activities.
spoof:
Spoof likelihood. The likelihood that an modification was made
to the image's canonical version to make it appear funny or
offensive.
medical:
Likelihood that this is a medical image.
violence:
Likelihood that this image contains violent content.
racy:
Likelihood that the request image contains racy content. Racy
content may include (but is not limited to) skimpy or sheer
clothing, strategically covered nudity, lewd or provocative
poses, or close-ups of sensitive body areas.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.SafeSearchAnnotation)
))
_sym_db.RegisterMessage(SafeSearchAnnotation)
LatLongRect = _reflection.GeneratedProtocolMessageType('LatLongRect', (_message.Message,), dict(
DESCRIPTOR = _LATLONGRECT,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """Rectangle determined by min and max ``LatLng`` pairs.
Attributes:
min_lat_lng:
Min lat/long pair.
max_lat_lng:
Max lat/long pair.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.LatLongRect)
))
_sym_db.RegisterMessage(LatLongRect)
ColorInfo = _reflection.GeneratedProtocolMessageType('ColorInfo', (_message.Message,), dict(
DESCRIPTOR = _COLORINFO,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """Color information consists of RGB channels, score, and the fraction of
the image that the color occupies in the image.
Attributes:
color:
RGB components of the color.
score:
Image-specific score for this color. Value in range [0, 1].
pixel_fraction:
The fraction of pixels the color occupies in the image. Value
in range [0, 1].
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.ColorInfo)
))
_sym_db.RegisterMessage(ColorInfo)
DominantColorsAnnotation = _reflection.GeneratedProtocolMessageType('DominantColorsAnnotation', (_message.Message,), dict(
DESCRIPTOR = _DOMINANTCOLORSANNOTATION,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """Set of dominant colors and their corresponding scores.
Attributes:
colors:
RGB color values with their score and pixel fraction.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.DominantColorsAnnotation)
))
_sym_db.RegisterMessage(DominantColorsAnnotation)
ImageProperties = _reflection.GeneratedProtocolMessageType('ImageProperties', (_message.Message,), dict(
DESCRIPTOR = _IMAGEPROPERTIES,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """Stores image properties, such as dominant colors.
Attributes:
dominant_colors:
If present, dominant colors completed successfully.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.ImageProperties)
))
_sym_db.RegisterMessage(ImageProperties)
CropHint = _reflection.GeneratedProtocolMessageType('CropHint', (_message.Message,), dict(
DESCRIPTOR = _CROPHINT,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """Single crop hint that is used to generate a new crop when serving an
image.
Attributes:
bounding_poly:
The bounding polygon for the crop region. The coordinates of
the bounding box are in the original image's scale, as
returned in ``ImageParams``.
confidence:
Confidence of this being a salient region. Range [0, 1].
importance_fraction:
Fraction of importance of this salient region with respect to
the original image.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.CropHint)
))
_sym_db.RegisterMessage(CropHint)
CropHintsAnnotation = _reflection.GeneratedProtocolMessageType('CropHintsAnnotation', (_message.Message,), dict(
DESCRIPTOR = _CROPHINTSANNOTATION,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """Set of crop hints that are used to generate new crops when serving
images.
Attributes:
crop_hints:
Crop hint results.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.CropHintsAnnotation)
))
_sym_db.RegisterMessage(CropHintsAnnotation)
CropHintsParams = _reflection.GeneratedProtocolMessageType('CropHintsParams', (_message.Message,), dict(
DESCRIPTOR = _CROPHINTSPARAMS,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """Parameters for crop hints annotation request.
Attributes:
aspect_ratios:
Aspect ratios in floats, representing the ratio of the width
to the height of the image. For example, if the desired aspect
ratio is 4/3, the corresponding float value should be 1.33333.
If not specified, the best possible crop is returned. The
number of provided aspect ratios is limited to a maximum of
16; any aspect ratios provided after the 16th are ignored.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.CropHintsParams)
))
_sym_db.RegisterMessage(CropHintsParams)
WebDetectionParams = _reflection.GeneratedProtocolMessageType('WebDetectionParams', (_message.Message,), dict(
DESCRIPTOR = _WEBDETECTIONPARAMS,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """Parameters for web detection request.
Attributes:
include_geo_results:
Whether to include results derived from the geo information in
the image.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.WebDetectionParams)
))
_sym_db.RegisterMessage(WebDetectionParams)
ImageContext = _reflection.GeneratedProtocolMessageType('ImageContext', (_message.Message,), dict(
DESCRIPTOR = _IMAGECONTEXT,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """Image context and/or feature-specific parameters.
Attributes:
lat_long_rect:
lat/long rectangle that specifies the location of the image.
language_hints:
List of languages to use for TEXT\_DETECTION. In most cases,
an empty value yields the best results since it enables
automatic language detection. For languages based on the Latin
alphabet, setting ``language_hints`` is not needed. In rare
cases, when the language of the text in the image is known,
setting a hint will help get better results (although it will
be a significant hindrance if the hint is wrong). Text
detection returns an error if one or more of the specified
languages is not one of the `supported languages
</vision/docs/languages>`__.
crop_hints_params:
Parameters for crop hints annotation request.
web_detection_params:
Parameters for web detection.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.ImageContext)
))
_sym_db.RegisterMessage(ImageContext)
AnnotateImageRequest = _reflection.GeneratedProtocolMessageType('AnnotateImageRequest', (_message.Message,), dict(
DESCRIPTOR = _ANNOTATEIMAGEREQUEST,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """Request for performing Google Cloud Vision API tasks over a
user-provided image, with user-requested features.
Attributes:
image:
The image to be processed.
features:
Requested features.
image_context:
Additional context that may accompany the image.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.AnnotateImageRequest)
))
_sym_db.RegisterMessage(AnnotateImageRequest)
AnnotateImageResponse = _reflection.GeneratedProtocolMessageType('AnnotateImageResponse', (_message.Message,), dict(
DESCRIPTOR = _ANNOTATEIMAGERESPONSE,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """Response to an image annotation request.
Attributes:
face_annotations:
If present, face detection has completed successfully.
landmark_annotations:
If present, landmark detection has completed successfully.
logo_annotations:
If present, logo detection has completed successfully.
label_annotations:
If present, label detection has completed successfully.
text_annotations:
If present, text (OCR) detection has completed successfully.
full_text_annotation:
If present, text (OCR) detection or document (OCR) text
detection has completed successfully. This annotation provides
the structural hierarchy for the OCR detected text.
safe_search_annotation:
If present, safe-search annotation has completed successfully.
image_properties_annotation:
If present, image properties were extracted successfully.
crop_hints_annotation:
If present, crop hints have completed successfully.
web_detection:
If present, web detection has completed successfully.
error:
If set, represents the error message for the operation. Note
that filled-in image annotations are guaranteed to be correct,
even when ``error`` is set.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.AnnotateImageResponse)
))
_sym_db.RegisterMessage(AnnotateImageResponse)
BatchAnnotateImagesRequest = _reflection.GeneratedProtocolMessageType('BatchAnnotateImagesRequest', (_message.Message,), dict(
DESCRIPTOR = _BATCHANNOTATEIMAGESREQUEST,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """Multiple image annotation requests are batched into a single service
call.
Attributes:
requests:
Individual image annotation requests for this batch.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.BatchAnnotateImagesRequest)
))
_sym_db.RegisterMessage(BatchAnnotateImagesRequest)
BatchAnnotateImagesResponse = _reflection.GeneratedProtocolMessageType('BatchAnnotateImagesResponse', (_message.Message,), dict(
DESCRIPTOR = _BATCHANNOTATEIMAGESRESPONSE,
__module__ = 'google.cloud.vision_v1p1beta1.proto.image_annotator_pb2'
,
__doc__ = """Response to a batch image annotation request.
Attributes:
responses:
Individual responses to image annotation requests within the
batch.
""",
# @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.BatchAnnotateImagesResponse)
))
_sym_db.RegisterMessage(BatchAnnotateImagesResponse)
DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n!com.google.cloud.vision.v1p1beta1B\023ImageAnnotatorProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p1beta1;vision\370\001\001'))
try:
# THESE ELEMENTS WILL BE DEPRECATED.
# Please use the generated *_pb2_grpc.py files instead.
import grpc
from grpc.beta import implementations as beta_implementations
from grpc.beta import interfaces as beta_interfaces
from grpc.framework.common import cardinality
from grpc.framework.interfaces.face import utilities as face_utilities
class ImageAnnotatorStub(object):
"""Service that performs Google Cloud Vision API detection tasks over client
images, such as face, landmark, logo, label, and text detection. The
ImageAnnotator service returns detected entities from the images.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.BatchAnnotateImages = channel.unary_unary(
'/google.cloud.vision.v1p1beta1.ImageAnnotator/BatchAnnotateImages',
request_serializer=BatchAnnotateImagesRequest.SerializeToString,
response_deserializer=BatchAnnotateImagesResponse.FromString,
)
class ImageAnnotatorServicer(object):
"""Service that performs Google Cloud Vision API detection tasks over client
images, such as face, landmark, logo, label, and text detection. The
ImageAnnotator service returns detected entities from the images.
"""
def BatchAnnotateImages(self, request, context):
"""Run image detection and annotation for a batch of images.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_ImageAnnotatorServicer_to_server(servicer, server):
rpc_method_handlers = {
'BatchAnnotateImages': grpc.unary_unary_rpc_method_handler(
servicer.BatchAnnotateImages,
request_deserializer=BatchAnnotateImagesRequest.FromString,
response_serializer=BatchAnnotateImagesResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'google.cloud.vision.v1p1beta1.ImageAnnotator', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
class BetaImageAnnotatorServicer(object):
"""The Beta API is deprecated for 0.15.0 and later.
It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This class was generated
only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0."""
"""Service that performs Google Cloud Vision API detection tasks over client
images, such as face, landmark, logo, label, and text detection. The
ImageAnnotator service returns detected entities from the images.
"""
def BatchAnnotateImages(self, request, context):
"""Run image detection and annotation for a batch of images.
"""
context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
class BetaImageAnnotatorStub(object):
"""The Beta API is deprecated for 0.15.0 and later.
It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This class was generated
only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0."""
"""Service that performs Google Cloud Vision API detection tasks over client
images, such as face, landmark, logo, label, and text detection. The
ImageAnnotator service returns detected entities from the images.
"""
def BatchAnnotateImages(self, request, timeout, metadata=None, with_call=False, protocol_options=None):
"""Run image detection and annotation for a batch of images.
"""
raise NotImplementedError()
BatchAnnotateImages.future = None
def beta_create_ImageAnnotator_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None):
"""The Beta API is deprecated for 0.15.0 and later.
It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This function was
generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0"""
request_deserializers = {
('google.cloud.vision.v1p1beta1.ImageAnnotator', 'BatchAnnotateImages'): BatchAnnotateImagesRequest.FromString,
}
response_serializers = {
('google.cloud.vision.v1p1beta1.ImageAnnotator', 'BatchAnnotateImages'): BatchAnnotateImagesResponse.SerializeToString,
}
method_implementations = {
('google.cloud.vision.v1p1beta1.ImageAnnotator', 'BatchAnnotateImages'): face_utilities.unary_unary_inline(servicer.BatchAnnotateImages),
}
server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout)
return beta_implementations.server(method_implementations, options=server_options)
def beta_create_ImageAnnotator_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None):
"""The Beta API is deprecated for 0.15.0 and later.
It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This function was
generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0"""
request_serializers = {
('google.cloud.vision.v1p1beta1.ImageAnnotator', 'BatchAnnotateImages'): BatchAnnotateImagesRequest.SerializeToString,
}
response_deserializers = {
('google.cloud.vision.v1p1beta1.ImageAnnotator', 'BatchAnnotateImages'): BatchAnnotateImagesResponse.FromString,
}
cardinalities = {
'BatchAnnotateImages': cardinality.Cardinality.UNARY_UNARY,
}
stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size)
return beta_implementations.dynamic_stub(channel, 'google.cloud.vision.v1p1beta1.ImageAnnotator', cardinalities, options=stub_options)
except ImportError:
pass
# @@protoc_insertion_point(module_scope)
| vision/google/cloud/vision_v1p1beta1/proto/image_annotator_pb2.py | 89,814 | The Beta API is deprecated for 0.15.0 and later.
It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This class was generated
only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0.
The Beta API is deprecated for 0.15.0 and later.
It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This class was generated
only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0.
Service that performs Google Cloud Vision API detection tasks over client
images, such as face, landmark, logo, label, and text detection. The
ImageAnnotator service returns detected entities from the images.
Service that performs Google Cloud Vision API detection tasks over client
images, such as face, landmark, logo, label, and text detection. The
ImageAnnotator service returns detected entities from the images.
Run image detection and annotation for a batch of images.
Run image detection and annotation for a batch of images.
Run image detection and annotation for a batch of images.
Constructor.
Args:
channel: A grpc.Channel.
The Beta API is deprecated for 0.15.0 and later.
It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This function was
generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0
The Beta API is deprecated for 0.15.0 and later.
It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This function was
generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0
Generated by the protocol buffer compiler. DO NOT EDIT! source: google/cloud/vision_v1p1beta1/proto/image_annotator.proto @@protoc_insertion_point(imports) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.Feature) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.ImageSource) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.Image) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.FaceAnnotation.Landmark) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.FaceAnnotation) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.LocationInfo) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.Property) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.EntityAnnotation) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.SafeSearchAnnotation) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.LatLongRect) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.ColorInfo) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.DominantColorsAnnotation) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.ImageProperties) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.CropHint) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.CropHintsAnnotation) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.CropHintsParams) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.WebDetectionParams) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.ImageContext) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.AnnotateImageRequest) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.AnnotateImageResponse) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.BatchAnnotateImagesRequest) @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.BatchAnnotateImagesResponse) THESE ELEMENTS WILL BE DEPRECATED. Please use the generated *_pb2_grpc.py files instead. @@protoc_insertion_point(module_scope) | 3,817 | en | 0.629222 |
import logging
# noinspection PyPackageRequirements
from telegram.ext import CommandHandler, ConversationHandler
# noinspection PyPackageRequirements
from telegram import ChatAction, Update
from bot import stickersbot
from bot.utils import decorators
from bot.utils import utils
from bot.database.base import session_scope
from bot.database.models.pack import Pack
from bot.strings import Strings
logger = logging.getLogger(__name__)
@decorators.action(ChatAction.TYPING)
@decorators.restricted
@decorators.failwithmessage
def on_list_command(update: Update, _):
logger.info('/list')
# packs = db.get_user_packs(update.effective_user.id, as_namedtuple=True)
with session_scope() as session:
packs = session.query(Pack).filter_by(user_id=update.effective_user.id).order_by(Pack.title).all()
packs = packs[:98] # can't include more than 100 entities
strings_list = ['<a href="{}">{}</a> ({})'.format(utils.name2link(pack.name), pack.title, 'a' if pack.is_animated else 's') for pack in packs]
if not strings_list:
update.message.reply_text(Strings.LIST_NO_PACKS)
return
update.message.reply_html('• {}'.format('\n• '.join(strings_list)) + Strings.LIST_FOOTER)
return ConversationHandler.END # /list should end whatever conversation the user was having
stickersbot.add_handler(CommandHandler(['list', 'l'], on_list_command))
| bot/handlers/packs/list.py | 1,403 | noinspection PyPackageRequirements noinspection PyPackageRequirements packs = db.get_user_packs(update.effective_user.id, as_namedtuple=True) can't include more than 100 entities /list should end whatever conversation the user was having | 237 | en | 0.807229 |
# -*- coding: utf-8 -*-
'''
QSDsan: Quantitative Sustainable Design for sanitation and resource recovery systems
This module is developed by:
Joy Zhang <joycheung1994@gmail.com>
This module is under the University of Illinois/NCSA Open Source License.
Please refer to https://github.com/QSD-Group/QSDsan/blob/main/LICENSE.txt
for license details.
'''
from .. import SanUnit, WasteStream, Process, Processes, CompiledProcesses
from ._clarifier import _settling_flux
from sympy import symbols, lambdify, Matrix
from scipy.integrate import solve_ivp
from warnings import warn
from math import floor, ceil
import numpy as np
import pandas as pd
from numba import njit
__all__ = ('CSTR',
'SBR',
# 'PFR',
)
def _add_aeration_to_growth_model(aer, model):
if isinstance(aer, Process):
processes = Processes(model.tuple)
processes.append(aer)
processes.compile()
else:
processes = model
processes.compile()
return processes
# %%
@njit(cache=True)
def dydt_cstr_no_rxn_fixed_aer(QC_ins, dQC_ins, V_arr, Q_e_arr, _dstate, Cs):
Q_ins = QC_ins[:, -1]
C_ins = QC_ins[:, :-1]
flow_in = Q_ins @ C_ins / V_arr
Q_e_arr[:] = Q_ins.sum(axis=0)
_dstate[-1] = dQC_ins[:, -1].sum(axis=0)
flow_out = Q_e_arr * Cs / V_arr
_dstate[:-1] = flow_in - flow_out
@njit(cache=True)
def dydt_cstr_no_rxn_controlled_aer(QC_ins, dQC_ins, V_arr, Q_e_arr, _dstate, Cs):
Q_ins = QC_ins[:, -1]
C_ins = QC_ins[:, :-1]
flow_in = Q_ins @ C_ins / V_arr
Q_e_arr[:] = Q_ins.sum(axis=0)
_dstate[-1] = dQC_ins[:, -1].sum(axis=0)
flow_out = Q_e_arr * Cs / V_arr
_dstate[:-1] = flow_in - flow_out
#%%
class CSTR(SanUnit):
'''
A single continuous stirred tank reactor.
Parameters
----------
ID : str
ID for the reactor.
ins : :class:`WasteStream`
Influents to the reactor. Can be an array of up to 3 WasteStream objects by
default, typically wastewater to be treated, recycled effluent, recycled
activated sludge.
outs : :class:`WasteStream`
Treated effluent.
split : iterable of float
Volumetric splits of effluent flows if there are more than one effluent.
The default is None.
V_max : float
Designed volume, in [m^3]. The default is 1000.
aeration : float or :class:`Process`, optional
Aeration setting. Either specify a targeted dissolved oxygen concentration
in [mg O2/L] or provide a :class:`Process` object to represent aeration,
or None for no aeration. The default is 2.0.
DO_ID : str, optional
The :class:`Component` ID for dissolved oxygen, only relevant when the
reactor is aerated. The default is 'S_O2'.
suspended_growth_model : :class:`Processes`, optional
The suspended growth biokinetic model. The default is None.
'''
_N_ins = 3
_N_outs = 1
_ins_size_is_fixed = False
_outs_size_is_fixed = False
def __init__(self, ID='', ins=None, outs=(), split=None, thermo=None,
init_with='WasteStream', V_max=1000, aeration=2.0,
DO_ID='S_O2', suspended_growth_model=None,
isdynamic=True, **kwargs):
SanUnit.__init__(self, ID, ins, outs, thermo, init_with, isdynamic=isdynamic)
self._V_max = V_max
self._aeration = aeration
self._DO_ID = DO_ID
self._model = suspended_growth_model
self._concs = None
self._mixed = WasteStream()
self.split = split
for attr, value in kwargs.items():
setattr(self, attr, value)
@property
def V_max(self):
'''[float] The designed maximum liquid volume, not accounting for increased volume due to aeration, in m^3.'''
return self._V_max
@V_max.setter
def V_max(self, Vm):
self._V_max = Vm
@property
def aeration(self):
'''[:class:`Process` or float or NoneType] Aeration model.'''
return self._aeration
@aeration.setter
def aeration(self, ae):
if ae is None or isinstance(ae, Process): self._aeration = ae
elif isinstance(ae, (float, int)):
if ae < 0:
raise ValueError('targeted dissolved oxygen concentration for aeration must be non-negative.')
else:
if ae > 14:
warn(f'targeted dissolved oxygen concentration for {self.ID} might exceed the saturated level.')
self._aeration = ae
else:
raise TypeError(f'aeration must be one of the following types: float, '
f'int, Process, NoneType. Not {type(ae)}')
@property
def suspended_growth_model(self):
'''[:class:`CompiledProcesses` or NoneType] Suspended growth model.'''
return self._model
@suspended_growth_model.setter
def suspended_growth_model(self, model):
if isinstance(model, CompiledProcesses) or model is None: self._model = model
else: raise TypeError(f'suspended_growth_model must be one of the following '
f'types: CompiledProesses, NoneType. Not {type(model)}')
@property
def DO_ID(self):
'''[str] The `Component` ID for dissolved oxygen used in the suspended growth model and the aeration model.'''
return self._DO_ID
@DO_ID.setter
def DO_ID(self, doid):
if doid not in self.components.IDs:
raise ValueError(f'DO_ID must be in the set of `CompiledComponents` used to set thermo, '
f'i.e., one of {self.components.IDs}.')
self._DO_ID = doid
@property
def split(self):
'''[numpy.1darray or NoneType] The volumetric split of outs.'''
return self._split
@split.setter
def split(self, split):
if split is None: self._split = split
else:
if len(split) != len(self._outs):
raise ValueError('split and outs must have the same size')
self._split = np.array(split)/sum(split)
@property
def state(self):
'''The state of the CSTR, including component concentrations [mg/L] and flow rate [m^3/d].'''
if self._state is None: return None
else:
return dict(zip(list(self.components.IDs) + ['Q'], self._state))
@state.setter
def state(self, QCs):
QCs = np.asarray(QCs)
if QCs.shape != (len(self.components)+1, ):
raise ValueError(f'state must be a 1D array of length {len(self.components) + 1},'
'indicating component concentrations [mg/L] and total flow rate [m^3/d]')
self._state = QCs
def set_init_conc(self, **kwargs):
'''set the initial concentrations [mg/L] of the CSTR.'''
Cs = np.zeros(len(self.components))
cmpx = self.components.index
for k, v in kwargs.items(): Cs[cmpx(k)] = v
self._concs = Cs
def _init_state(self):
mixed = self._mixed
Q = mixed.get_total_flow('m3/d')
if self._concs is not None: Cs = self._concs
else: Cs = mixed.conc
self._state = np.append(Cs, Q).astype('float64')
self._dstate = self._state * 0.
def _update_state(self):
arr = self._state
if self.split is None: self._outs[0].state = arr
else:
for ws, spl in zip(self._outs, self.split):
y = arr.copy()
y[-1] *= spl
ws.state = y
def _update_dstate(self):
arr = self._dstate
if self.split is None: self._outs[0].dstate = arr
else:
for ws, spl in zip(self._outs, self.split):
y = arr.copy()
y[-1] *= spl
ws.dstate = y
def _run(self):
'''Only to converge volumetric flows.'''
mixed = self._mixed # avoid creating multiple new streams
mixed.mix_from(self.ins)
Q = mixed.F_vol # m3/hr
if self.split is None: self.outs[0].copy_like(mixed)
else:
for ws, spl in zip(self._outs, self.split):
ws.copy_like(mixed)
ws.set_total_flow(Q*spl, 'm3/hr')
def get_retained_mass(self, biomass_IDs):
cmps = self.components
mass = cmps.i_mass * self._state[:-1]
return self._V_max * mass[cmps.indices(biomass_IDs)].sum()
@property
def ODE(self):
if self._ODE is None:
self._compile_ODE()
return self._ODE
def _compile_ODE(self):
isa = isinstance
C = list(symbols(self.components.IDs))
m = len(C)
if self._model is None:
warn(f'{self.ID} was initialized without a suspended growth model, '
f'and thus run as a non-reactive unit')
r = lambda *args: np.zeros(m)
else:
processes = _add_aeration_to_growth_model(self._aeration, self._model)
r_eqs = list(processes.production_rates.rate_of_production)
r = lambdify(C, r_eqs, 'numpy')
_dstate = self._dstate
_update_dstate = self._update_dstate
V_arr = np.full(m, self._V_max)
Q_e_arr = np.zeros(m)
if isa(self._aeration, (float, int)):
i = self.components.index(self._DO_ID)
fixed_DO = self._aeration
def dy_dt(t, QC_ins, QC, dQC_ins):
Cs = QC[:-1]
Cs[i] = fixed_DO
dydt_cstr_no_rxn_controlled_aer(QC_ins, dQC_ins, V_arr, Q_e_arr, _dstate, Cs)
_dstate[:-1] += r(*Cs)
_dstate[i] = 0
_update_dstate()
else:
def dy_dt(t, QC_ins, QC, dQC_ins):
Cs = QC[:-1]
dydt_cstr_no_rxn_fixed_aer(QC_ins, dQC_ins, V_arr, Q_e_arr, _dstate, Cs)
_dstate[:-1] += r(*Cs)
_update_dstate()
self._ODE = dy_dt
def _design(self):
pass
class SBR(SanUnit):
'''
Sequential batch reactors operated in parallel. The number of reactors is
determined by operation cycle and influent flowrate. [1]_
Parameters
----------
ID : str
ID for the reactors. The default is ''.
ins : :class:`WasteStream`
Influent to the reactor. Expected number of influent is 1.
outs : :class:`WasteStream`
Treated effluent and wasted sludge.
surface_area : float, optional
Surface area of the reactor bottom, in [m^2]. The reactor is assumed
to be cylinder. The default is 1500.
height : float, optional
Height of the reactor, in [m]. The default is 4.
operation_cycle : iterable of float, optional
Operation cycle of the SBR, time for each stage specified in [h]. There
are 7 stages: 1 - fill, 2 - fill, 3 - mix, 4 - mix, 5 - settle, 6 - decant,
7 - desludge. The first 4 stages are modeled as a biological reactor.
The 5th stage is modeled as a 1D N-layer settler. The last 2 stages are
assumed inactive. The default is (0.5, 1.5, 2.0, 0, 1.0, 0.5, 0.1).
aeration : iterable of float and/or :class:`Process`, optional
Aeration settings for the first 4 stages of the operation cycle. Either
specify a targeted dissolved oxygen concentration in [mg O2/L] or provide
a :class:`Process` object to represent aeration, or None for no aeration.
The default is (None, None, None, 2.0).
DO_ID : str, optional
The :class:`Component` ID for dissolved oxygen, only relevant when the
reactor is aerated. The default is 'S_O2'.
suspended_growth_model : :class:`Processes`, optional
The suspended growth biokinetic model. The default is None.
N_layer : int, optional
The number of layers to model settling. The default is 10.
pumped_flow : float, optional
Designed effluent flowrate, in [m^3/d]. The default is None.
underflow : float, optional
Designed wasted activated sludge flowrate, in [m^3/d]. The default is None.
X_threshold : float, optional
Threshold suspended solid concentration, in [g/m^3]. The default is 3000.
v_max : float, optional
Maximum theoretical (i.e. Vesilind) settling velocity, in [m/d]. The
default is 474.
v_max_practical : float, optional
Maximum practical settling velocity, in [m/d]. The default is 250.
rh : float, optional
Hindered zone settling parameter in the double-exponential settling velocity
function, in [m^3/g]. The default is 5.76e-4.
rp : float, optional
Flocculant zone settling parameter in the double-exponential settling velocity
function, in [m^3/g]. The default is 2.86e-3.
fns : float, optional
Non-settleable fraction of the suspended solids, dimensionless. Must be within
[0, 1]. The default is 2.28e-3.
cache_state : bool, optional
Whether to store volume and composition of retained sludge in the tank from
most recent run. The default is True.
References
----------
.. [1] Takács, I.; Patry, G. G.; Nolasco, D. A Dynamic Model of the Clarification
-Thickening Process. Water Res. 1991, 25 (10), 1263–1271.
https://doi.org/10.1016/0043-1354(91)90066-Y.
'''
_N_ins = 1
_N_outs = 2
def __init__(self, ID='', ins=None, outs=(), thermo=None, init_with='WasteStream',
surface_area=1500, height=4,
operation_cycle=(0.5, 1.5, 2.0, 0, 1.0, 0.5, 0.1),
aeration=(None, None, None, 2.0), DO_ID='S_O2',
suspended_growth_model=None, N_layer=10,
pumped_flow=None, underflow=None,
X_threshold=3000, v_max=474, v_max_practical=250,
rh=5.76e-4, rp=2.86e-3, fns=2.28e-3,
cache_state=True, **kwargs):
SanUnit.__init__(self, ID, ins, outs, thermo, init_with)
self._V = surface_area * height
self._A = surface_area
self._h = height
self._operation_cycle = operation_cycle
self._aeration = aeration
self._DO_ID = DO_ID
self._model = suspended_growth_model
self._N_layer = N_layer
self._Q_e = pumped_flow
self._Q_WAS = underflow
self._X_t = X_threshold
self._v_max = v_max
self._v_max_p = v_max_practical
self._rh = rh
self._rp = rp
self._fns = fns
self._cache_state = cache_state
for attr, value in kwargs.items():
setattr(self, attr, value)
self._init_Vas = None
self._init_Cas = None
self._dynamic_composition = None
@property
def operation_cycle(self):
return dict(zip(('fill_1', 'fill_2', 'mix_1', 'mix_2', 'settle', 'decant', 'desludge'),
self._operation_cycle))
@property
def total_cycle_time(self):
return sum(self._operation_cycle)
@property
def aeration(self):
return dict(zip(('fill_1', 'fill_2', 'mix_1', 'mix_2'),
self._aeration[:4]))
@property
def C_t(self):
if self._dynamic_composition:
return pd.DataFrame(self._dynamic_composition,
columns = ['Time[d]'] + list(self.components.IDs))
else: return None
def _run(self, cache_state=True):
if self._model is None:
raise RuntimeError(f'{self.ID} was initialized without a suspended growth model.')
else:
isa = isinstance
inf = self.ins[0]
Q_in = inf.get_total_flow('m3/d')
eff, sludge = self.outs
eff.copy_like(inf)
sludge.copy_like(inf)
C_in = inf.mass / inf.F_vol * 1e3 # concentrations in g/m3
cmps = self.components
C = list(symbols(cmps.IDs))
if self._init_Vas is not None:
V_0 = self._init_Vas
C_0 = self._init_Cas
else:
V_0 = 0
C_0 = C_in
n = self._N_layer
if self._aeration.count(None) == len(self._aeration):
Vmax = self._V
hj = self._h/n
else:
Vmax = self._V*0.75
hj = self._h*0.75/n
# ********fill and mix/aerate stages***********
T_fill = (Vmax - V_0)/Q_in # maximum total fill time in day
T = [t/24 for t in self._operation_cycle] # operation cycle in day
if T_fill <= T[0]:
schedule = [T_fill, T[0]-T_fill] + T[1:4]
aer = [self._aeration[0], self._aeration[0]] + list(self._aeration[1:4])
fill = [True] + [False]*4
V_total = Vmax
elif T_fill <= T[0]+T[1]:
schedule = [T[0], T_fill-T[0], T[0]+T[1]-T_fill] + T[2:4]
aer = list(self._aeration[:2]) + [self._aeration[1]] + list(self._aeration[2:4])
fill = [True]*2 + [False]*3
V_total = Vmax
else:
schedule = T[:4]
aer = list(self._aeration[:4])
fill = [True]*2 + [False]*2
V_total = Q_in*(T[0]+T[1])+V_0
hj = V_total/self._V*self._h/n
for i in range(1, len(schedule)):
if fill[-i] == fill[-i-1] and aer[-i] == aer[-i-1]:
schedule[-i-1] += schedule[-i]
schedule[-i] = 0
t_arr = np.array([])
y_mat = np.ndarray([])
for i in range(len(schedule)):
if schedule[i] > 0:
dC_dt, J_func = self._compile_dC_dt(V_0, Q_in, C_in, C, fill[i], aer[i])
if isa(aer[i], (float, int)): C_0[cmps.index(self._DO_ID)] = aer[i]
sol = solve_ivp(dC_dt, (0, schedule[i]), C_0, method='BDF', jac=J_func)
C_0 = sol.y.transpose()[-1]
V_0 += Q_in * schedule[i] * fill[i]
t_arr = np.concatenate((t_arr, sol.t + t_arr[-1]))
y_mat = np.hstack((y_mat, sol.y))
self._dynamic_composition = np.vstack((t_arr, y_mat)).transpose()
# *********settle, decant, desludge**********
eff.set_flow(C_0*eff.F_vol, 'g/hr', self.components.IDs)
X_0 = eff.get_TSS()
X_min = X_0 * self._fns
T_settle = T[4]
def dX_dt(t, X):
VX = [_settling_flux(x, self._v_max, self._v_max_p, X_min, self._rh, self._rp) for x in X]
J = [VX[j] if X[j+1] <= self._X_t else min(VX[j], VX[j+1]) for j in range(n-1)]
settle_out = np.array(J + [0])
settle_in = np.array([0] + J)
dXdt = (settle_in - settle_out)/hj
return dXdt
sol = solve_ivp(dX_dt, (0, T_settle), np.ones(n)*X_0)
X = sol.y.transpose()[-1]
V_eff = min(T[5]*self._Q_e, V_total*(n-1)/n)
n_eff = V_eff/V_total
w_eff = np.array([1]*floor(n_eff)+[n_eff-floor(n_eff)])
X_eff = np.average(X[:ceil(n_eff)], weights=w_eff)
eff_mass_flow = (X_eff/X_0*cmps.x + (1-cmps.x))*C_0*V_eff/T[5]
eff.set_flow(eff_mass_flow, 'g/d', cmps.IDs)
V_was = min(T[6]*self._Q_WAS, V_total-V_eff)
X_as = (V_total*X_0 - V_eff*X_eff) / (V_total-V_eff)
C_as = (X_as/X_0*cmps.x + (1-cmps.x))*C_0
was_mass_flow = C_as*V_was/T[6]
sludge.set_flow(was_mass_flow, 'g/d', cmps.IDs)
if self._cache_state:
self._init_Vas = V_total - V_eff - V_was
self._init_Cas = C_as
def _design(self):
pass
def _compile_dC_dt(self, V0, Qin, Cin, C, fill, aer):
isa = isinstance
processes = _add_aeration_to_growth_model(aer, self._model)
if fill:
t = symbols('t')
mass_balance_terms = list(zip(Cin, C, processes.production_rates.rate_of_production))
C_dot_eqs = [(cin-c)/(t+V0/Qin) + r for cin, c, r in mass_balance_terms]
if isa(aer, (float, int)): C_dot_eqs[self.components.index(self._DO_ID)] = 0
def dC_dt(t, y):
C_dot = lambdify([t]+C, C_dot_eqs)
return C_dot(t, *y)
J = Matrix(dC_dt(t, C)).jacobian(C)
else:
C_dot_eqs = processes.production_rates.rate_of_production
if isa(aer, (float, int)): C_dot_eqs[self.components.index(self._DO_ID)] = 0
def dC_dt(t, y):
C_dot = lambdify(C, C_dot_eqs)
return C_dot(*y)
J = Matrix(dC_dt(None, C)).jacobian(C)
def J_func(t, y):
J_func = lambdify(C, J)
return J_func(*y)
return (dC_dt, J_func)
# class PFR(SanUnit):
# _N_ins = 1
# _N_outs = 2
# def __init__(self, ID='', ins=None, outs=(), **kwargs):
# SanUnit.__init__(self, ID, ins, outs)
# def _run(self, steady_state=True):
# pass
# def _design(self):
# pass | qsdsan/sanunits/_suspended_growth_bioreactor.py | 21,130 | A single continuous stirred tank reactor.
Parameters
----------
ID : str
ID for the reactor.
ins : :class:`WasteStream`
Influents to the reactor. Can be an array of up to 3 WasteStream objects by
default, typically wastewater to be treated, recycled effluent, recycled
activated sludge.
outs : :class:`WasteStream`
Treated effluent.
split : iterable of float
Volumetric splits of effluent flows if there are more than one effluent.
The default is None.
V_max : float
Designed volume, in [m^3]. The default is 1000.
aeration : float or :class:`Process`, optional
Aeration setting. Either specify a targeted dissolved oxygen concentration
in [mg O2/L] or provide a :class:`Process` object to represent aeration,
or None for no aeration. The default is 2.0.
DO_ID : str, optional
The :class:`Component` ID for dissolved oxygen, only relevant when the
reactor is aerated. The default is 'S_O2'.
suspended_growth_model : :class:`Processes`, optional
The suspended growth biokinetic model. The default is None.
Sequential batch reactors operated in parallel. The number of reactors is
determined by operation cycle and influent flowrate. [1]_
Parameters
----------
ID : str
ID for the reactors. The default is ''.
ins : :class:`WasteStream`
Influent to the reactor. Expected number of influent is 1.
outs : :class:`WasteStream`
Treated effluent and wasted sludge.
surface_area : float, optional
Surface area of the reactor bottom, in [m^2]. The reactor is assumed
to be cylinder. The default is 1500.
height : float, optional
Height of the reactor, in [m]. The default is 4.
operation_cycle : iterable of float, optional
Operation cycle of the SBR, time for each stage specified in [h]. There
are 7 stages: 1 - fill, 2 - fill, 3 - mix, 4 - mix, 5 - settle, 6 - decant,
7 - desludge. The first 4 stages are modeled as a biological reactor.
The 5th stage is modeled as a 1D N-layer settler. The last 2 stages are
assumed inactive. The default is (0.5, 1.5, 2.0, 0, 1.0, 0.5, 0.1).
aeration : iterable of float and/or :class:`Process`, optional
Aeration settings for the first 4 stages of the operation cycle. Either
specify a targeted dissolved oxygen concentration in [mg O2/L] or provide
a :class:`Process` object to represent aeration, or None for no aeration.
The default is (None, None, None, 2.0).
DO_ID : str, optional
The :class:`Component` ID for dissolved oxygen, only relevant when the
reactor is aerated. The default is 'S_O2'.
suspended_growth_model : :class:`Processes`, optional
The suspended growth biokinetic model. The default is None.
N_layer : int, optional
The number of layers to model settling. The default is 10.
pumped_flow : float, optional
Designed effluent flowrate, in [m^3/d]. The default is None.
underflow : float, optional
Designed wasted activated sludge flowrate, in [m^3/d]. The default is None.
X_threshold : float, optional
Threshold suspended solid concentration, in [g/m^3]. The default is 3000.
v_max : float, optional
Maximum theoretical (i.e. Vesilind) settling velocity, in [m/d]. The
default is 474.
v_max_practical : float, optional
Maximum practical settling velocity, in [m/d]. The default is 250.
rh : float, optional
Hindered zone settling parameter in the double-exponential settling velocity
function, in [m^3/g]. The default is 5.76e-4.
rp : float, optional
Flocculant zone settling parameter in the double-exponential settling velocity
function, in [m^3/g]. The default is 2.86e-3.
fns : float, optional
Non-settleable fraction of the suspended solids, dimensionless. Must be within
[0, 1]. The default is 2.28e-3.
cache_state : bool, optional
Whether to store volume and composition of retained sludge in the tank from
most recent run. The default is True.
References
----------
.. [1] Takács, I.; Patry, G. G.; Nolasco, D. A Dynamic Model of the Clarification
-Thickening Process. Water Res. 1991, 25 (10), 1263–1271.
https://doi.org/10.1016/0043-1354(91)90066-Y.
[str] The `Component` ID for dissolved oxygen used in the suspended growth model and the aeration model.
[float] The designed maximum liquid volume, not accounting for increased volume due to aeration, in m^3.
Only to converge volumetric flows.
[:class:`Process` or float or NoneType] Aeration model.
set the initial concentrations [mg/L] of the CSTR.
[numpy.1darray or NoneType] The volumetric split of outs.
The state of the CSTR, including component concentrations [mg/L] and flow rate [m^3/d].
[:class:`CompiledProcesses` or NoneType] Suspended growth model.
QSDsan: Quantitative Sustainable Design for sanitation and resource recovery systems
This module is developed by:
Joy Zhang <joycheung1994@gmail.com>
This module is under the University of Illinois/NCSA Open Source License.
Please refer to https://github.com/QSD-Group/QSDsan/blob/main/LICENSE.txt
for license details.
-*- coding: utf-8 -*- 'PFR', %%%% avoid creating multiple new streams m3/hr concentrations in g/m3 ********fill and mix/aerate stages*********** maximum total fill time in day operation cycle in day *********settle, decant, desludge********** class PFR(SanUnit): _N_ins = 1 _N_outs = 2 def __init__(self, ID='', ins=None, outs=(), **kwargs): SanUnit.__init__(self, ID, ins, outs) def _run(self, steady_state=True): pass def _design(self): pass | 5,488 | en | 0.693432 |
# vim: set et sw=4 sts=4 fileencoding=utf-8:
#
# Python camera library for the Rasperry-Pi camera module
# Copyright (c) 2013-2017 Dave Jones <dave@waveform.org.uk>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import (
unicode_literals,
print_function,
division,
absolute_import,
)
# Make Py2's str equivalent to Py3's
str = type('')
import warnings
import datetime
import mimetypes
import ctypes as ct
import threading
from fractions import Fraction
from operator import itemgetter
from collections import namedtuple
from . import bcm_host, mmal, mmalobj as mo
from .exc import (
PiCameraError,
PiCameraValueError,
PiCameraRuntimeError,
PiCameraClosed,
PiCameraNotRecording,
PiCameraAlreadyRecording,
PiCameraMMALError,
PiCameraDeprecated,
PiCameraFallback,
)
from .encoders import (
PiVideoFrame,
PiVideoEncoder,
PiRawVideoEncoder,
PiCookedVideoEncoder,
PiRawOneImageEncoder,
PiRawMultiImageEncoder,
PiCookedOneImageEncoder,
PiCookedMultiImageEncoder,
)
from .renderers import (
PiPreviewRenderer,
PiOverlayRenderer,
PiNullSink,
)
from .color import Color
try:
from RPi import GPIO
except ImportError:
# Can't find RPi.GPIO so just null-out the reference
GPIO = None
def docstring_values(values, indent=8):
"""
Formats a dictionary of values for inclusion in a docstring.
"""
return ('\n' + ' ' * indent).join(
"* ``'%s'``" % k
for (k, v) in
sorted(values.items(), key=itemgetter(1)))
class PiCameraMaxResolution(object):
"""
Singleton representing the maximum resolution of the camera module.
"""
PiCameraMaxResolution = PiCameraMaxResolution()
class PiCameraMaxFramerate(object):
"""
Singleton representing the maximum framerate of the camera module.
"""
PiCameraMaxFramerate = PiCameraMaxFramerate()
class PiCamera(object):
"""
Provides a pure Python interface to the Raspberry Pi's camera module.
Upon construction, this class initializes the camera. The *camera_num*
parameter (which defaults to 0) selects the camera module that the instance
will represent. Only the Raspberry Pi compute module currently supports
more than one camera.
The *sensor_mode*, *resolution*, *framerate*, *framerate_range*, and
*clock_mode* parameters provide initial values for the :attr:`sensor_mode`,
:attr:`resolution`, :attr:`framerate`, :attr:`framerate_range`, and
:attr:`clock_mode` attributes of the class (these attributes are all
relatively expensive to set individually, hence setting them all upon
construction is a speed optimization). Please refer to the attribute
documentation for more information and default values.
The *stereo_mode* and *stereo_decimate* parameters configure dual cameras
on a compute module for sterescopic mode. These parameters can only be set
at construction time; they cannot be altered later without closing the
:class:`PiCamera` instance and recreating it. The *stereo_mode* parameter
defaults to ``'none'`` (no stereoscopic mode) but can be set to
``'side-by-side'`` or ``'top-bottom'`` to activate a stereoscopic mode. If
the *stereo_decimate* parameter is ``True``, the resolution of the two
cameras will be halved so that the resulting image has the same dimensions
as if stereoscopic mode were not being used.
The *led_pin* parameter can be used to specify the GPIO pin which should be
used to control the camera's LED via the :attr:`led` attribute. If this is
not specified, it should default to the correct value for your Pi platform.
You should only need to specify this parameter if you are using a custom
DeviceTree blob (this is only typical on the `Compute Module`_ platform).
No preview or recording is started automatically upon construction. Use
the :meth:`capture` method to capture images, the :meth:`start_recording`
method to begin recording video, or the :meth:`start_preview` method to
start live display of the camera's input.
Several attributes are provided to adjust the camera's configuration. Some
of these can be adjusted while a recording is running, like
:attr:`brightness`. Others, like :attr:`resolution`, can only be adjusted
when the camera is idle.
When you are finished with the camera, you should ensure you call the
:meth:`close` method to release the camera resources::
camera = PiCamera()
try:
# do something with the camera
pass
finally:
camera.close()
The class supports the context manager protocol to make this particularly
easy (upon exiting the :keyword:`with` statement, the :meth:`close` method
is automatically called)::
with PiCamera() as camera:
# do something with the camera
pass
.. versionchanged:: 1.8
Added *stereo_mode* and *stereo_decimate* parameters.
.. versionchanged:: 1.9
Added *resolution*, *framerate*, and *sensor_mode* parameters.
.. versionchanged:: 1.10
Added *led_pin* parameter.
.. versionchanged:: 1.11
Added *clock_mode* parameter, and permitted setting of resolution as
appropriately formatted string.
.. versionchanged:: 1.13
Added *framerate_range* parameter.
.. _Compute Module: https://www.raspberrypi.org/documentation/hardware/computemodule/cmio-camera.md
"""
CAMERA_PREVIEW_PORT = 0
CAMERA_VIDEO_PORT = 1
CAMERA_CAPTURE_PORT = 2
MAX_RESOLUTION = PiCameraMaxResolution # modified by PiCamera.__init__
MAX_FRAMERATE = PiCameraMaxFramerate # modified by PiCamera.__init__
DEFAULT_ANNOTATE_SIZE = 32
CAPTURE_TIMEOUT = 60
METER_MODES = {
'average': mmal.MMAL_PARAM_EXPOSUREMETERINGMODE_AVERAGE,
'spot': mmal.MMAL_PARAM_EXPOSUREMETERINGMODE_SPOT,
'backlit': mmal.MMAL_PARAM_EXPOSUREMETERINGMODE_BACKLIT,
'matrix': mmal.MMAL_PARAM_EXPOSUREMETERINGMODE_MATRIX,
}
EXPOSURE_MODES = {
'off': mmal.MMAL_PARAM_EXPOSUREMODE_OFF,
'auto': mmal.MMAL_PARAM_EXPOSUREMODE_AUTO,
'night': mmal.MMAL_PARAM_EXPOSUREMODE_NIGHT,
'nightpreview': mmal.MMAL_PARAM_EXPOSUREMODE_NIGHTPREVIEW,
'backlight': mmal.MMAL_PARAM_EXPOSUREMODE_BACKLIGHT,
'spotlight': mmal.MMAL_PARAM_EXPOSUREMODE_SPOTLIGHT,
'sports': mmal.MMAL_PARAM_EXPOSUREMODE_SPORTS,
'snow': mmal.MMAL_PARAM_EXPOSUREMODE_SNOW,
'beach': mmal.MMAL_PARAM_EXPOSUREMODE_BEACH,
'verylong': mmal.MMAL_PARAM_EXPOSUREMODE_VERYLONG,
'fixedfps': mmal.MMAL_PARAM_EXPOSUREMODE_FIXEDFPS,
'antishake': mmal.MMAL_PARAM_EXPOSUREMODE_ANTISHAKE,
'fireworks': mmal.MMAL_PARAM_EXPOSUREMODE_FIREWORKS,
}
FLASH_MODES = {
'off': mmal.MMAL_PARAM_FLASH_OFF,
'auto': mmal.MMAL_PARAM_FLASH_AUTO,
'on': mmal.MMAL_PARAM_FLASH_ON,
'redeye': mmal.MMAL_PARAM_FLASH_REDEYE,
'fillin': mmal.MMAL_PARAM_FLASH_FILLIN,
'torch': mmal.MMAL_PARAM_FLASH_TORCH,
}
AWB_MODES = {
'off': mmal.MMAL_PARAM_AWBMODE_OFF,
'auto': mmal.MMAL_PARAM_AWBMODE_AUTO,
'sunlight': mmal.MMAL_PARAM_AWBMODE_SUNLIGHT,
'cloudy': mmal.MMAL_PARAM_AWBMODE_CLOUDY,
'shade': mmal.MMAL_PARAM_AWBMODE_SHADE,
'tungsten': mmal.MMAL_PARAM_AWBMODE_TUNGSTEN,
'fluorescent': mmal.MMAL_PARAM_AWBMODE_FLUORESCENT,
'incandescent': mmal.MMAL_PARAM_AWBMODE_INCANDESCENT,
'flash': mmal.MMAL_PARAM_AWBMODE_FLASH,
'horizon': mmal.MMAL_PARAM_AWBMODE_HORIZON,
}
IMAGE_EFFECTS = {
'none': mmal.MMAL_PARAM_IMAGEFX_NONE,
'negative': mmal.MMAL_PARAM_IMAGEFX_NEGATIVE,
'solarize': mmal.MMAL_PARAM_IMAGEFX_SOLARIZE,
# The following don't work
#'posterize': mmal.MMAL_PARAM_IMAGEFX_POSTERIZE,
#'whiteboard': mmal.MMAL_PARAM_IMAGEFX_WHITEBOARD,
#'blackboard': mmal.MMAL_PARAM_IMAGEFX_BLACKBOARD,
'sketch': mmal.MMAL_PARAM_IMAGEFX_SKETCH,
'denoise': mmal.MMAL_PARAM_IMAGEFX_DENOISE,
'emboss': mmal.MMAL_PARAM_IMAGEFX_EMBOSS,
'oilpaint': mmal.MMAL_PARAM_IMAGEFX_OILPAINT,
'hatch': mmal.MMAL_PARAM_IMAGEFX_HATCH,
'gpen': mmal.MMAL_PARAM_IMAGEFX_GPEN,
'pastel': mmal.MMAL_PARAM_IMAGEFX_PASTEL,
'watercolor': mmal.MMAL_PARAM_IMAGEFX_WATERCOLOUR,
'film': mmal.MMAL_PARAM_IMAGEFX_FILM,
'blur': mmal.MMAL_PARAM_IMAGEFX_BLUR,
'saturation': mmal.MMAL_PARAM_IMAGEFX_SATURATION,
'colorswap': mmal.MMAL_PARAM_IMAGEFX_COLOURSWAP,
'washedout': mmal.MMAL_PARAM_IMAGEFX_WASHEDOUT,
'posterise': mmal.MMAL_PARAM_IMAGEFX_POSTERISE,
'colorpoint': mmal.MMAL_PARAM_IMAGEFX_COLOURPOINT,
'colorbalance': mmal.MMAL_PARAM_IMAGEFX_COLOURBALANCE,
'cartoon': mmal.MMAL_PARAM_IMAGEFX_CARTOON,
'deinterlace1': mmal.MMAL_PARAM_IMAGEFX_DEINTERLACE_DOUBLE,
'deinterlace2': mmal.MMAL_PARAM_IMAGEFX_DEINTERLACE_ADV,
}
DRC_STRENGTHS = {
'off': mmal.MMAL_PARAMETER_DRC_STRENGTH_OFF,
'low': mmal.MMAL_PARAMETER_DRC_STRENGTH_LOW,
'medium': mmal.MMAL_PARAMETER_DRC_STRENGTH_MEDIUM,
'high': mmal.MMAL_PARAMETER_DRC_STRENGTH_HIGH,
}
RAW_FORMATS = {
'yuv',
'rgb',
'rgba',
'bgr',
'bgra',
}
STEREO_MODES = {
'none': mmal.MMAL_STEREOSCOPIC_MODE_NONE,
'side-by-side': mmal.MMAL_STEREOSCOPIC_MODE_SIDE_BY_SIDE,
'top-bottom': mmal.MMAL_STEREOSCOPIC_MODE_BOTTOM,
}
CLOCK_MODES = {
'reset': mmal.MMAL_PARAM_TIMESTAMP_MODE_RESET_STC,
'raw': mmal.MMAL_PARAM_TIMESTAMP_MODE_RAW_STC,
}
_METER_MODES_R = {v: k for (k, v) in METER_MODES.items()}
_EXPOSURE_MODES_R = {v: k for (k, v) in EXPOSURE_MODES.items()}
_FLASH_MODES_R = {v: k for (k, v) in FLASH_MODES.items()}
_AWB_MODES_R = {v: k for (k, v) in AWB_MODES.items()}
_IMAGE_EFFECTS_R = {v: k for (k, v) in IMAGE_EFFECTS.items()}
_DRC_STRENGTHS_R = {v: k for (k, v) in DRC_STRENGTHS.items()}
_STEREO_MODES_R = {v: k for (k, v) in STEREO_MODES.items()}
_CLOCK_MODES_R = {v: k for (k, v) in CLOCK_MODES.items()}
__slots__ = (
'_used_led',
'_led_pin',
'_camera',
'_camera_config',
'_camera_exception',
'_revision',
'_preview',
'_preview_alpha',
'_preview_layer',
'_preview_fullscreen',
'_preview_window',
'_splitter',
'_splitter_connection',
'_encoders_lock',
'_encoders',
'_overlays',
'_raw_format',
'_image_effect_params',
'_exif_tags',
)
def __init__(
self, camera_num=0, stereo_mode='none', stereo_decimate=False,
resolution=None, framerate=None, sensor_mode=0, led_pin=None,
clock_mode='reset', framerate_range=None):
bcm_host.bcm_host_init()
mimetypes.add_type('application/h264', '.h264', False)
mimetypes.add_type('application/mjpeg', '.mjpg', False)
mimetypes.add_type('application/mjpeg', '.mjpeg', False)
self._used_led = False
if GPIO and led_pin is None:
try:
led_pin = {
(0, 0): 2, # compute module (default for cam 0)
(0, 1): 30, # compute module (default for cam 1)
(1, 0): 5, # Pi 1 model B rev 1
(2, 0): 5, # Pi 1 model B rev 2 or model A
(3, 0): 32, # Pi 1 model B+ or Pi 2 model B
}[(GPIO.RPI_REVISION, camera_num)]
except KeyError:
raise PiCameraError(
'Unable to determine default GPIO LED pin for RPi '
'revision %d and camera num %d' % (
GPIO.RPI_REVISION, camera_num))
self._led_pin = led_pin
self._camera = None
self._camera_config = None
self._camera_exception = None
self._preview = None
self._preview_alpha = 255
self._preview_layer = 2
self._preview_fullscreen = True
self._preview_window = None
self._splitter = None
self._splitter_connection = None
self._encoders_lock = threading.Lock()
self._encoders = {}
self._overlays = []
self._raw_format = 'yuv'
self._image_effect_params = None
with mo.MMALCameraInfo() as camera_info:
info = camera_info.control.params[mmal.MMAL_PARAMETER_CAMERA_INFO]
self._revision = 'ov5647'
if camera_info.info_rev > 1:
self._revision = info.cameras[camera_num].camera_name.decode('ascii')
self._exif_tags = {
'IFD0.Model': 'RP_%s' % self._revision,
'IFD0.Make': 'RaspberryPi',
}
if PiCamera.MAX_RESOLUTION is PiCameraMaxResolution:
PiCamera.MAX_RESOLUTION = mo.PiResolution(
info.cameras[camera_num].max_width,
info.cameras[camera_num].max_height,
)
if PiCamera.MAX_FRAMERATE is PiCameraMaxFramerate:
if self._revision.upper() == 'OV5647':
PiCamera.MAX_FRAMERATE = 90
else:
PiCamera.MAX_FRAMERATE = 120
if resolution is None:
# Get screen resolution
w = ct.c_uint32()
h = ct.c_uint32()
if bcm_host.graphics_get_display_size(0, w, h) == -1:
w = 1280
h = 720
else:
w = int(w.value)
h = int(h.value)
resolution = mo.PiResolution(w, h)
elif resolution is PiCameraMaxResolution:
resolution = PiCamera.MAX_RESOLUTION
else:
resolution = mo.to_resolution(resolution)
if framerate_range is None:
if framerate is None:
framerate = 30
elif framerate is PiCameraMaxFramerate:
framerate = PiCamera.MAX_FRAMERATE
else:
framerate = mo.to_fraction(framerate)
elif framerate is not None:
raise PiCameraValueError(
"Can't specify framerate and framerate_range")
else:
try:
low, high = framerate_range
except TypeError:
raise PiCameraValueError(
"framerate_range must have (low, high) values")
if low is PiCameraMaxFramerate:
low = PiCamera.MAX_FRAMERATE
if high is PiCameraMaxFramerate:
high = PiCamera.MAX_FRAMERATE
framerate = (mo.to_fraction(low), mo.to_fraction(high))
try:
stereo_mode = self.STEREO_MODES[stereo_mode]
except KeyError:
raise PiCameraValueError('Invalid stereo mode: %s' % stereo_mode)
try:
clock_mode = self.CLOCK_MODES[clock_mode]
except KeyError:
raise PiCameraValueError('Invalid clock mode: %s' % clock_mode)
try:
self._init_camera(camera_num, stereo_mode, stereo_decimate)
self._configure_camera(sensor_mode, framerate, resolution, clock_mode)
self._init_preview()
self._init_splitter()
self._camera.enable()
self._init_defaults()
except:
self.close()
raise
def _init_led(self):
global GPIO
if GPIO:
try:
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(self._led_pin, GPIO.OUT, initial=GPIO.LOW)
self._used_led = True
except RuntimeError:
# We're probably not running as root. In this case, forget the
# GPIO reference so we don't try anything further
GPIO = None
def _init_camera(self, num, stereo_mode, stereo_decimate):
try:
self._camera = mo.MMALCamera()
except PiCameraMMALError as e:
if e.status == mmal.MMAL_ENOMEM:
raise PiCameraError(
"Camera is not enabled. Try running 'sudo raspi-config' "
"and ensure that the camera has been enabled.")
else:
raise
self._camera_config = self._camera.control.params[mmal.MMAL_PARAMETER_CAMERA_CONFIG]
# Don't attempt to set this if stereo mode isn't requested as it'll
# break compatibility on older firmwares
if stereo_mode != mmal.MMAL_STEREOSCOPIC_MODE_NONE:
for p in self._camera.outputs:
mp = mmal.MMAL_PARAMETER_STEREOSCOPIC_MODE_T(
mmal.MMAL_PARAMETER_HEADER_T(
mmal.MMAL_PARAMETER_STEREOSCOPIC_MODE,
ct.sizeof(mmal.MMAL_PARAMETER_STEREOSCOPIC_MODE_T),
),
mode=stereo_mode,
decimate=stereo_decimate,
swap_eyes=False,
)
p.params[mmal.MMAL_PARAMETER_STEREOSCOPIC_MODE] = mp
# Must be done *after* stereo-scopic setting
self._camera.control.params[mmal.MMAL_PARAMETER_CAMERA_NUM] = num
def _init_defaults(self):
self.sharpness = 0
self.contrast = 0
self.brightness = 50
self.saturation = 0
self.iso = 0 # auto
self.video_stabilization = False
self.exposure_compensation = 0
self.exposure_mode = 'auto'
self.meter_mode = 'average'
self.awb_mode = 'auto'
self.image_effect = 'none'
self.color_effects = None
self.rotation = 0
self.hflip = self.vflip = False
self.zoom = (0.0, 0.0, 1.0, 1.0)
def _init_splitter(self):
# Create a splitter component for the video port. This is to permit
# video recordings and captures where use_video_port=True to occur
# simultaneously (#26)
self._splitter = mo.MMALSplitter()
self._splitter.inputs[0].connect(
self._camera.outputs[self.CAMERA_VIDEO_PORT]).enable()
def _init_preview(self):
# Create a null-sink component, enable it and connect it to the
# camera's preview port. If nothing is connected to the preview port,
# the camera doesn't measure exposure and captured images gradually
# fade to black (issue #22)
self._preview = PiNullSink(
self, self._camera.outputs[self.CAMERA_PREVIEW_PORT])
def _start_capture(self, port):
# Only enable capture if the port is the camera's still port, or if
# there's a single active encoder on the video splitter
if (
port == self._camera.outputs[self.CAMERA_CAPTURE_PORT] or
len([e for e in self._encoders.values() if e.active]) == 1):
port.params[mmal.MMAL_PARAMETER_CAPTURE] = True
def _stop_capture(self, port):
# Only disable capture if the port is the camera's still port, or if
# there's a single active encoder on the video splitter
if (
port == self._camera.outputs[self.CAMERA_CAPTURE_PORT] or
len([e for e in self._encoders.values() if e.active]) == 1):
port.params[mmal.MMAL_PARAMETER_CAPTURE] = False
def _check_camera_open(self):
"""
Raise an exception if the camera is already closed, or if the camera
has encountered a fatal error.
"""
exc, self._camera_exception = self._camera_exception, None
if exc:
raise exc
if self.closed:
raise PiCameraClosed("Camera is closed")
def _check_recording_stopped(self):
"""
Raise an exception if the camera is currently recording.
"""
if self.recording:
raise PiCameraRuntimeError("Recording is currently running")
def _get_ports(self, from_video_port, splitter_port):
"""
Determine the camera and output ports for given capture options.
See :ref:`camera_hardware` for more information on picamera's usage of
camera, splitter, and encoder ports. The general idea here is that the
capture (still) port operates on its own, while the video port is
always connected to a splitter component, so requests for a video port
also have to specify which splitter port they want to use.
"""
self._check_camera_open()
if from_video_port and (splitter_port in self._encoders):
raise PiCameraAlreadyRecording(
'The camera is already using port %d ' % splitter_port)
camera_port = (
self._camera.outputs[self.CAMERA_VIDEO_PORT]
if from_video_port else
self._camera.outputs[self.CAMERA_CAPTURE_PORT]
)
output_port = (
self._splitter.outputs[splitter_port]
if from_video_port else
camera_port
)
return (camera_port, output_port)
def _get_output_format(self, output):
"""
Given an output object, attempt to determine the requested format.
We attempt to determine the filename of the *output* object and derive
a MIME type from the extension. If *output* has no filename, an error
is raised.
"""
if isinstance(output, bytes):
filename = output.decode('utf-8')
elif isinstance(output, str):
filename = output
else:
try:
filename = output.name
except AttributeError:
raise PiCameraValueError(
'Format must be specified when output has no filename')
(type, encoding) = mimetypes.guess_type(filename, strict=False)
if not type:
raise PiCameraValueError(
'Unable to determine type from filename %s' % filename)
return type
def _get_image_format(self, output, format=None):
"""
Given an output object and an optional format, attempt to determine the
requested image format.
This method is used by all capture methods to determine the requested
output format. If *format* is specified as a MIME-type the "image/"
prefix is stripped. If *format* is not specified, then
:meth:`_get_output_format` will be called to attempt to determine
format from the *output* object.
"""
if isinstance(format, bytes):
format = format.decode('utf-8')
format = format or self._get_output_format(output)
format = (
format[6:] if format.startswith('image/') else
format)
if format == 'x-ms-bmp':
format = 'bmp'
if format == 'raw':
format = self.raw_format
return format
def _get_video_format(self, output, format=None):
"""
Given an output object and an optional format, attempt to determine the
requested video format.
This method is used by all recording methods to determine the requested
output format. If *format* is specified as a MIME-type the "video/" or
"application/" prefix will be stripped. If *format* is not specified,
then :meth:`_get_output_format` will be called to attempt to determine
format from the *output* object.
"""
if isinstance(format, bytes):
format = format.decode('utf-8')
format = format or self._get_output_format(output)
format = (
format[6:] if format.startswith('video/') else
format[12:] if format.startswith('application/') else
format)
return format
def _get_image_encoder(
self, camera_port, output_port, format, resize, **options):
"""
Construct an image encoder for the requested parameters.
This method is called by :meth:`capture` and :meth:`capture_continuous`
to construct an image encoder. The *camera_port* parameter gives the
MMAL camera port that should be enabled for capture by the encoder. The
*output_port* parameter gives the MMAL port that the encoder should
read output from (this may be the same as the camera port, but may be
different if other component(s) like a splitter have been placed in the
pipeline). The *format* parameter indicates the image format and will
be one of:
* ``'jpeg'``
* ``'png'``
* ``'gif'``
* ``'bmp'``
* ``'yuv'``
* ``'rgb'``
* ``'rgba'``
* ``'bgr'``
* ``'bgra'``
The *resize* parameter indicates the size that the encoder should
resize the output to (presumably by including a resizer in the
pipeline). Finally, *options* includes extra keyword arguments that
should be passed verbatim to the encoder.
"""
encoder_class = (
PiRawOneImageEncoder if format in self.RAW_FORMATS else
PiCookedOneImageEncoder)
return encoder_class(
self, camera_port, output_port, format, resize, **options)
def _get_images_encoder(
self, camera_port, output_port, format, resize, **options):
"""
Construct a multi-image encoder for the requested parameters.
This method is largely equivalent to :meth:`_get_image_encoder` with
the exception that the encoder returned should expect to be passed an
iterable of outputs to its :meth:`~PiEncoder.start` method, rather than
a single output object. This method is called by the
:meth:`capture_sequence` method.
All parameters are the same as in :meth:`_get_image_encoder`. Please
refer to the documentation for that method for further information.
"""
encoder_class = (
PiRawMultiImageEncoder if format in self.RAW_FORMATS else
PiCookedMultiImageEncoder)
return encoder_class(
self, camera_port, output_port, format, resize, **options)
def _get_video_encoder(
self, camera_port, output_port, format, resize, **options):
"""
Construct a video encoder for the requested parameters.
This method is called by :meth:`start_recording` and
:meth:`record_sequence` to construct a video encoder. The
*camera_port* parameter gives the MMAL camera port that should be
enabled for capture by the encoder. The *output_port* parameter gives
the MMAL port that the encoder should read output from (this may be the
same as the camera port, but may be different if other component(s)
like a splitter have been placed in the pipeline). The *format*
parameter indicates the video format and will be one of:
* ``'h264'``
* ``'mjpeg'``
The *resize* parameter indicates the size that the encoder should
resize the output to (presumably by including a resizer in the
pipeline). Finally, *options* includes extra keyword arguments that
should be passed verbatim to the encoder.
"""
encoder_class = (
PiRawVideoEncoder if format in self.RAW_FORMATS else
PiCookedVideoEncoder)
return encoder_class(
self, camera_port, output_port, format, resize, **options)
def close(self):
"""
Finalizes the state of the camera.
After successfully constructing a :class:`PiCamera` object, you should
ensure you call the :meth:`close` method once you are finished with the
camera (e.g. in the ``finally`` section of a ``try..finally`` block).
This method stops all recording and preview activities and releases all
resources associated with the camera; this is necessary to prevent GPU
memory leaks.
"""
for port in list(self._encoders):
self.stop_recording(splitter_port=port)
assert not self.recording
for overlay in list(self._overlays):
self.remove_overlay(overlay)
if self._preview:
self._preview.close()
self._preview = None
if self._splitter:
self._splitter.close()
self._splitter = None
if self._camera:
self._camera.close()
self._camera = None
exc, self._camera_exception = self._camera_exception, None
if exc:
raise exc
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
self.close()
def start_preview(self, **options):
"""
Displays the preview overlay.
This method starts a camera preview as an overlay on the Pi's primary
display (HDMI or composite). A :class:`PiRenderer` instance (more
specifically, a :class:`PiPreviewRenderer`) is constructed with the
keyword arguments captured in *options*, and is returned from the
method (this instance is also accessible from the :attr:`preview`
attribute for as long as the renderer remains active). By default, the
renderer will be opaque and fullscreen.
This means the default preview overrides whatever is currently visible
on the display. More specifically, the preview does not rely on a
graphical environment like X-Windows (it can run quite happily from a
TTY console); it is simply an overlay on the Pi's video output. To stop
the preview and reveal the display again, call :meth:`stop_preview`.
The preview can be started and stopped multiple times during the
lifetime of the :class:`PiCamera` object.
All other camera properties can be modified "live" while the preview is
running (e.g. :attr:`brightness`).
.. note::
Because the default preview typically obscures the screen, ensure
you have a means of stopping a preview before starting one. If the
preview obscures your interactive console you won't be able to
Alt+Tab back to it as the preview isn't in a window. If you are in
an interactive Python session, simply pressing Ctrl+D usually
suffices to terminate the environment, including the camera and its
associated preview.
"""
self._check_camera_open()
self._preview.close()
options.setdefault('layer', self._preview_layer)
options.setdefault('alpha', self._preview_alpha)
options.setdefault('fullscreen', self._preview_fullscreen)
options.setdefault('window', self._preview_window)
renderer = PiPreviewRenderer(
self, self._camera.outputs[self.CAMERA_PREVIEW_PORT], **options)
self._preview = renderer
return renderer
def stop_preview(self):
"""
Hides the preview overlay.
If :meth:`start_preview` has previously been called, this method shuts
down the preview display which generally results in the underlying
display becoming visible again. If a preview is not currently running,
no exception is raised - the method will simply do nothing.
"""
self._check_camera_open()
self._preview.close()
self._preview = PiNullSink(
self, self._camera.outputs[self.CAMERA_PREVIEW_PORT])
def add_overlay(self, source, size=None, format=None, **options):
"""
Adds a static overlay to the preview output.
This method creates a new static overlay using the same rendering
mechanism as the preview. Overlays will appear on the Pi's video
output, but will not appear in captures or video recordings. Multiple
overlays can exist; each call to :meth:`add_overlay` returns a new
:class:`PiOverlayRenderer` instance representing the overlay.
The *source* must be an object that supports the :ref:`buffer protocol
<bufferobjects>` in one of the supported unencoded formats: ``'yuv'``,
``'rgb'``, ``'rgba'``, ``'bgr'``, or ``'bgra'``. The format can
specified explicitly with the optional *format* parameter. If not
specified, the method will attempt to guess the format based on the
length of *source* and the *size* (assuming 3 bytes per pixel for RGB,
and 4 bytes for RGBA).
The optional *size* parameter specifies the size of the source image as
a ``(width, height)`` tuple. If this is omitted or ``None`` then the
size is assumed to be the same as the camera's current
:attr:`resolution`.
The length of *source* must take into account that widths are rounded
up to the nearest multiple of 32, and heights to the nearest multiple
of 16. For example, if *size* is ``(1280, 720)``, and *format* is
``'rgb'``, then *source* must be a buffer with length 1280 × 720 × 3
bytes, or 2,764,800 bytes (because 1280 is a multiple of 32, and 720 is
a multiple of 16 no extra rounding is required). However, if *size* is
``(97, 57)``, and *format* is ``'rgb'`` then *source* must be a buffer
with length 128 × 64 × 3 bytes, or 24,576 bytes (pixels beyond column
97 and row 57 in the source will be ignored).
New overlays default to *layer* 0, whilst the preview defaults to layer
2. Higher numbered layers obscure lower numbered layers, hence new
overlays will be invisible (if the preview is running) by default. You
can make the new overlay visible either by making any existing preview
transparent (with the :attr:`~PiRenderer.alpha` property) or by moving
the overlay into a layer higher than the preview (with the
:attr:`~PiRenderer.layer` property).
All keyword arguments captured in *options* are passed onto the
:class:`PiRenderer` constructor. All camera properties except
:attr:`resolution` and :attr:`framerate` can be modified while overlays
exist. The reason for these exceptions is that the overlay has a static
resolution and changing the camera's mode would require resizing of the
source.
.. warning::
If too many overlays are added, the display output will be disabled
and a reboot will generally be required to restore the display.
Overlays are composited "on the fly". Hence, a real-time constraint
exists wherein for each horizontal line of HDMI output, the content
of all source layers must be fetched, resized, converted, and
blended to produce the output pixels.
If enough overlays exist (where "enough" is a number dependent on
overlay size, display resolution, bus frequency, and several other
factors making it unrealistic to calculate in advance), this
process breaks down and video output fails. One solution is to add
``dispmanx_offline=1`` to ``/boot/config.txt`` to force the use of
an off-screen buffer. Be aware that this requires more GPU memory
and may reduce the update rate.
.. _RGB: https://en.wikipedia.org/wiki/RGB
.. _RGBA: https://en.wikipedia.org/wiki/RGBA_color_space
.. versionadded:: 1.8
.. versionchanged:: 1.13
Added *format* parameter
"""
self._check_camera_open()
renderer = PiOverlayRenderer(self, source, size, format, **options)
self._overlays.append(renderer)
return renderer
def remove_overlay(self, overlay):
"""
Removes a static overlay from the preview output.
This method removes an overlay which was previously created by
:meth:`add_overlay`. The *overlay* parameter specifies the
:class:`PiRenderer` instance that was returned by :meth:`add_overlay`.
.. versionadded:: 1.8
"""
if not overlay in self._overlays:
raise PiCameraValueError(
"The specified overlay is not owned by this instance of "
"PiCamera")
overlay.close()
self._overlays.remove(overlay)
def start_recording(
self, output, format=None, resize=None, splitter_port=1, **options):
"""
Start recording video from the camera, storing it in *output*.
If *output* is a string, it will be treated as a filename for a new
file which the video will be written to. If *output* is not a string,
but is an object with a ``write`` method, it is assumed to be a
file-like object and the video data is appended to it (the
implementation only assumes the object has a ``write()`` method - no
other methods are required but ``flush`` will be called at the end of
recording if it is present). If *output* is not a string, and has no
``write`` method it is assumed to be a writeable object implementing
the buffer protocol. In this case, the video frames will be written
sequentially to the underlying buffer (which must be large enough to
accept all frame data).
If *format* is ``None`` (the default), the method will attempt to guess
the required video format from the extension of *output* (if it's a
string), or from the *name* attribute of *output* (if it has one). In
the case that the format cannot be determined, a
:exc:`PiCameraValueError` will be raised.
If *format* is not ``None``, it must be a string specifying the format
that you want the video output in. The format can be a MIME-type or
one of the following strings:
* ``'h264'`` - Write an H.264 video stream
* ``'mjpeg'`` - Write an M-JPEG video stream
* ``'yuv'`` - Write the raw video data to a file in YUV420 format
* ``'rgb'`` - Write the raw video data to a file in 24-bit RGB format
* ``'rgba'`` - Write the raw video data to a file in 32-bit RGBA format
* ``'bgr'`` - Write the raw video data to a file in 24-bit BGR format
* ``'bgra'`` - Write the raw video data to a file in 32-bit BGRA format
If *resize* is not ``None`` (the default), it must be a two-element
tuple specifying the width and height that the video recording should
be resized to. This is particularly useful for recording video using
the full resolution of the camera sensor (which is not possible in
H.264 without down-sizing the output).
The *splitter_port* parameter specifies the port of the built-in
splitter that the video encoder will be attached to. This defaults to
``1`` and most users will have no need to specify anything different.
If you wish to record multiple (presumably resized) streams
simultaneously, specify a value between ``0`` and ``3`` inclusive for
this parameter, ensuring that you do not specify a port that is
currently in use.
Certain formats accept additional options which can be specified
as keyword arguments. The ``'h264'`` format accepts the following
additional options:
* *profile* - The H.264 profile to use for encoding. Defaults to
'high', but can be one of 'baseline', 'main', 'extended', 'high', or
'constrained'.
* *level* - The `H.264 level`_ to use for encoding. Defaults to '4',
but can be any H.264 level up to '4.2'.
* *intra_period* - The key frame rate (the rate at which I-frames are
inserted in the output). Defaults to ``None``, but can be any 32-bit
integer value representing the number of frames between successive
I-frames. The special value 0 causes the encoder to produce a single
initial I-frame, and then only P-frames subsequently. Note that
:meth:`split_recording` will fail in this mode.
* *intra_refresh* - The key frame format (the way in which I-frames
will be inserted into the output stream). Defaults to ``None``, but
can be one of 'cyclic', 'adaptive', 'both', or 'cyclicrows'.
* *inline_headers* - When ``True``, specifies that the encoder should
output SPS/PPS headers within the stream to ensure GOPs (groups of
pictures) are self describing. This is important for streaming
applications where the client may wish to seek within the stream, and
enables the use of :meth:`split_recording`. Defaults to ``True`` if
not specified.
* *sei* - When ``True``, specifies the encoder should include
"Supplemental Enhancement Information" within the output stream.
Defaults to ``False`` if not specified.
* *sps_timing* - When ``True`` the encoder includes the camera's
framerate in the SPS header. Defaults to ``False`` if not specified.
* *motion_output* - Indicates the output destination for motion vector
estimation data. When ``None`` (the default), motion data is not
output. Otherwise, this can be a filename string, a file-like object,
or a writeable buffer object (as with the *output* parameter).
All encoded formats accept the following additional options:
* *bitrate* - The bitrate at which video will be encoded. Defaults to
17000000 (17Mbps) if not specified. The maximum value depends on the
selected `H.264 level`_ and profile. Bitrate 0 indicates the encoder
should not use bitrate control (the encoder is limited by the quality
only).
* *quality* - Specifies the quality that the encoder should attempt
to maintain. For the ``'h264'`` format, use values between 10 and 40
where 10 is extremely high quality, and 40 is extremely low (20-25 is
usually a reasonable range for H.264 encoding). For the ``mjpeg``
format, use JPEG quality values between 1 and 100 (where higher
values are higher quality). Quality 0 is special and seems to be
a "reasonable quality" default.
* *quantization* - Deprecated alias for *quality*.
.. versionchanged:: 1.0
The *resize* parameter was added, and ``'mjpeg'`` was added as a
recording format
.. versionchanged:: 1.3
The *splitter_port* parameter was added
.. versionchanged:: 1.5
The *quantization* parameter was deprecated in favor of *quality*,
and the *motion_output* parameter was added.
.. versionchanged:: 1.11
Support for buffer outputs was added.
.. _H.264 level: https://en.wikipedia.org/wiki/H.264/MPEG-4_AVC#Levels
"""
if 'quantization' in options:
warnings.warn(
PiCameraDeprecated(
'The quantization option is deprecated; please use '
'quality instead (same value)'))
with self._encoders_lock:
camera_port, output_port = self._get_ports(True, splitter_port)
format = self._get_video_format(output, format)
encoder = self._get_video_encoder(
camera_port, output_port, format, resize, **options)
self._encoders[splitter_port] = encoder
try:
encoder.start(output, options.get('motion_output'))
except Exception as e:
encoder.close()
with self._encoders_lock:
del self._encoders[splitter_port]
raise
def split_recording(self, output, splitter_port=1, **options):
"""
Continue the recording in the specified output; close existing output.
When called, the video encoder will wait for the next appropriate
split point (an inline SPS header), then will cease writing to the
current output (and close it, if it was specified as a filename), and
continue writing to the newly specified *output*.
The *output* parameter is treated as in the :meth:`start_recording`
method (it can be a string, a file-like object, or a writeable
buffer object).
The *motion_output* parameter can be used to redirect the output of the
motion vector data in the same fashion as *output*. If *motion_output*
is ``None`` (the default) then motion vector data will not be
redirected and will continue being written to the output specified by
the *motion_output* parameter given to :meth:`start_recording`.
Alternatively, if you only wish to redirect motion vector data, you can
set *output* to ``None`` and given a new value for *motion_output*.
The *splitter_port* parameter specifies which port of the video
splitter the encoder you wish to change outputs is attached to. This
defaults to ``1`` and most users will have no need to specify anything
different. Valid values are between ``0`` and ``3`` inclusive.
Note that unlike :meth:`start_recording`, you cannot specify format or
other options as these cannot be changed in the middle of recording.
Only the new *output* (and *motion_output*) can be specified.
Furthermore, the format of the recording is currently limited to H264,
and *inline_headers* must be ``True`` when :meth:`start_recording` is
called (this is the default).
.. versionchanged:: 1.3
The *splitter_port* parameter was added
.. versionchanged:: 1.5
The *motion_output* parameter was added
.. versionchanged:: 1.11
Support for buffer outputs was added.
"""
try:
with self._encoders_lock:
encoder = self._encoders[splitter_port]
except KeyError:
raise PiCameraNotRecording(
'There is no recording in progress on '
'port %d' % splitter_port)
else:
encoder.split(output, options.get('motion_output'))
def request_key_frame(self, splitter_port=1):
"""
Request the encoder generate a key-frame as soon as possible.
When called, the video encoder running on the specified *splitter_port*
will attempt to produce a key-frame (full-image frame) as soon as
possible. The *splitter_port* defaults to ``1``. Valid values are
between ``0`` and ``3`` inclusive.
.. note::
This method is only meaningful for recordings encoded in the H264
format as MJPEG produces full frames for every frame recorded.
Furthermore, there's no guarantee that the *next* frame will be
a key-frame; this is simply a request to produce one as soon as
possible after the call.
.. versionadded:: 1.11
"""
try:
with self._encoders_lock:
encoder = self._encoders[splitter_port]
except KeyError:
raise PiCameraNotRecording(
'There is no recording in progress on '
'port %d' % splitter_port)
else:
encoder.request_key_frame()
def wait_recording(self, timeout=0, splitter_port=1):
"""
Wait on the video encoder for timeout seconds.
It is recommended that this method is called while recording to check
for exceptions. If an error occurs during recording (for example out of
disk space) the recording will stop, but an exception will only be
raised when the :meth:`wait_recording` or :meth:`stop_recording`
methods are called.
If ``timeout`` is 0 (the default) the function will immediately return
(or raise an exception if an error has occurred).
The *splitter_port* parameter specifies which port of the video
splitter the encoder you wish to wait on is attached to. This
defaults to ``1`` and most users will have no need to specify anything
different. Valid values are between ``0`` and ``3`` inclusive.
.. versionchanged:: 1.3
The *splitter_port* parameter was added
"""
assert timeout is not None
try:
with self._encoders_lock:
encoder = self._encoders[splitter_port]
except KeyError:
raise PiCameraNotRecording(
'There is no recording in progress on '
'port %d' % splitter_port)
else:
encoder.wait(timeout)
def stop_recording(self, splitter_port=1):
"""
Stop recording video from the camera.
After calling this method the video encoder will be shut down and
output will stop being written to the file-like object specified with
:meth:`start_recording`. If an error occurred during recording and
:meth:`wait_recording` has not been called since the error then this
method will raise the exception.
The *splitter_port* parameter specifies which port of the video
splitter the encoder you wish to stop is attached to. This defaults to
``1`` and most users will have no need to specify anything different.
Valid values are between ``0`` and ``3`` inclusive.
.. versionchanged:: 1.3
The *splitter_port* parameter was added
"""
try:
with self._encoders_lock:
encoder = self._encoders[splitter_port]
except KeyError:
raise PiCameraNotRecording(
'There is no recording in progress on '
'port %d' % splitter_port)
else:
try:
self.wait_recording(0, splitter_port)
finally:
encoder.close()
with self._encoders_lock:
del self._encoders[splitter_port]
def record_sequence(
self, outputs, format='h264', resize=None, splitter_port=1, **options):
"""
Record a sequence of video clips from the camera.
This method accepts a sequence or iterator of *outputs* each of which
must either be a string specifying a filename for output, or a
file-like object with a ``write`` method.
The method acts as an iterator itself, yielding each item of the
sequence in turn. In this way, the caller can control how long to
record to each item by only permitting the loop to continue when ready
to switch to the next output.
The *format*, *splitter_port*, *resize*, and *options* parameters are
the same as in :meth:`start_recording`, but *format* defaults to
``'h264'``. The format is **not** derived from the filenames in
*outputs* by this method.
For example, to record 3 consecutive 10-second video clips, writing the
output to a series of H.264 files named clip01.h264, clip02.h264, and
clip03.h264 one could use the following::
import picamera
with picamera.PiCamera() as camera:
for filename in camera.record_sequence([
'clip01.h264',
'clip02.h264',
'clip03.h264']):
print('Recording to %s' % filename)
camera.wait_recording(10)
Alternatively, a more flexible method of writing the previous example
(which is easier to expand to a large number of output files) is by
using a generator expression as the input sequence::
import picamera
with picamera.PiCamera() as camera:
for filename in camera.record_sequence(
'clip%02d.h264' % i for i in range(3)):
print('Recording to %s' % filename)
camera.wait_recording(10)
More advanced techniques are also possible by utilising infinite
sequences, such as those generated by :func:`itertools.cycle`. In the
following example, recording is switched between two in-memory streams.
Whilst one stream is recording, the other is being analysed. The script
only stops recording when a video recording meets some criteria defined
by the ``process`` function::
import io
import itertools
import picamera
with picamera.PiCamera() as camera:
analyse = None
for stream in camera.record_sequence(
itertools.cycle((io.BytesIO(), io.BytesIO()))):
if analyse is not None:
if process(analyse):
break
analyse.seek(0)
analyse.truncate()
camera.wait_recording(5)
analyse = stream
.. versionadded:: 1.3
"""
with self._encoders_lock:
camera_port, output_port = self._get_ports(True, splitter_port)
format = self._get_video_format('', format)
encoder = self._get_video_encoder(
camera_port, output_port, format, resize, **options)
self._encoders[splitter_port] = encoder
try:
start = True
for output in outputs:
if start:
start = False
encoder.start(output, options.get('motion_output'))
else:
encoder.split(output)
yield output
finally:
try:
encoder.wait(0)
finally:
encoder.close()
with self._encoders_lock:
del self._encoders[splitter_port]
def capture(
self, output, format=None, use_video_port=False, resize=None,
splitter_port=0, bayer=False, **options):
"""
Capture an image from the camera, storing it in *output*.
If *output* is a string, it will be treated as a filename for a new
file which the image will be written to. If *output* is not a string,
but is an object with a ``write`` method, it is assumed to be a
file-like object and the image data is appended to it (the
implementation only assumes the object has a ``write`` method - no
other methods are required but ``flush`` will be called at the end of
capture if it is present). If *output* is not a string, and has no
``write`` method it is assumed to be a writeable object implementing
the buffer protocol. In this case, the image data will be written
directly to the underlying buffer (which must be large enough to accept
the image data).
If *format* is ``None`` (the default), the method will attempt to guess
the required image format from the extension of *output* (if it's a
string), or from the *name* attribute of *output* (if it has one). In
the case that the format cannot be determined, a
:exc:`PiCameraValueError` will be raised.
If *format* is not ``None``, it must be a string specifying the format
that you want the image output in. The format can be a MIME-type or
one of the following strings:
* ``'jpeg'`` - Write a JPEG file
* ``'png'`` - Write a PNG file
* ``'gif'`` - Write a GIF file
* ``'bmp'`` - Write a Windows bitmap file
* ``'yuv'`` - Write the raw image data to a file in YUV420 format
* ``'rgb'`` - Write the raw image data to a file in 24-bit RGB format
* ``'rgba'`` - Write the raw image data to a file in 32-bit RGBA format
* ``'bgr'`` - Write the raw image data to a file in 24-bit BGR format
* ``'bgra'`` - Write the raw image data to a file in 32-bit BGRA format
* ``'raw'`` - Deprecated option for raw captures; the format is taken
from the deprecated :attr:`raw_format` attribute
The *use_video_port* parameter controls whether the camera's image or
video port is used to capture images. It defaults to ``False`` which
means that the camera's image port is used. This port is slow but
produces better quality pictures. If you need rapid capture up to the
rate of video frames, set this to ``True``.
When *use_video_port* is ``True``, the *splitter_port* parameter
specifies the port of the video splitter that the image encoder will be
attached to. This defaults to ``0`` and most users will have no need to
specify anything different. This parameter is ignored when
*use_video_port* is ``False``. See :ref:`mmal` for more information
about the video splitter.
If *resize* is not ``None`` (the default), it must be a two-element
tuple specifying the width and height that the image should be resized
to.
.. warning::
If *resize* is specified, or *use_video_port* is ``True``, Exif
metadata will **not** be included in JPEG output. This is due to an
underlying firmware limitation.
Certain file formats accept additional options which can be specified
as keyword arguments. Currently, only the ``'jpeg'`` encoder accepts
additional options, which are:
* *quality* - Defines the quality of the JPEG encoder as an integer
ranging from 1 to 100. Defaults to 85. Please note that JPEG quality
is not a percentage and `definitions of quality`_ vary widely.
* *restart* - Defines the restart interval for the JPEG encoder as a
number of JPEG MCUs. The actual restart interval used will be a
multiple of the number of MCUs per row in the resulting image.
* *thumbnail* - Defines the size and quality of the thumbnail to embed
in the Exif metadata. Specifying ``None`` disables thumbnail
generation. Otherwise, specify a tuple of ``(width, height,
quality)``. Defaults to ``(64, 48, 35)``.
* *bayer* - If ``True``, the raw bayer data from the camera's sensor
is included in the Exif metadata.
.. note::
The so-called "raw" formats listed above (``'yuv'``, ``'rgb'``,
etc.) do not represent the raw bayer data from the camera's sensor.
Rather they provide access to the image data after GPU processing,
but before format encoding (JPEG, PNG, etc). Currently, the only
method of accessing the raw bayer data is via the *bayer* parameter
described above.
.. versionchanged:: 1.0
The *resize* parameter was added, and raw capture formats can now
be specified directly
.. versionchanged:: 1.3
The *splitter_port* parameter was added, and *bayer* was added as
an option for the ``'jpeg'`` format
.. versionchanged:: 1.11
Support for buffer outputs was added.
.. _definitions of quality: http://photo.net/learn/jpeg/#qual
"""
if format == 'raw':
warnings.warn(
PiCameraDeprecated(
'The "raw" format option is deprecated; specify the '
'required format directly instead ("yuv", "rgb", etc.)'))
if use_video_port and bayer:
raise PiCameraValueError(
'bayer is only valid with still port captures')
if 'burst' in options:
raise PiCameraValueError(
'burst is only valid with capture_sequence or capture_continuous')
with self._encoders_lock:
camera_port, output_port = self._get_ports(use_video_port, splitter_port)
format = self._get_image_format(output, format)
encoder = self._get_image_encoder(
camera_port, output_port, format, resize, **options)
if use_video_port:
self._encoders[splitter_port] = encoder
try:
if bayer:
camera_port.params[mmal.MMAL_PARAMETER_ENABLE_RAW_CAPTURE] = True
encoder.start(output)
# Wait for the callback to set the event indicating the end of
# image capture
if not encoder.wait(self.CAPTURE_TIMEOUT):
raise PiCameraRuntimeError(
'Timed out waiting for capture to end')
finally:
encoder.close()
with self._encoders_lock:
if use_video_port:
del self._encoders[splitter_port]
def capture_sequence(
self, outputs, format='jpeg', use_video_port=False, resize=None,
splitter_port=0, burst=False, bayer=False, **options):
"""
Capture a sequence of consecutive images from the camera.
This method accepts a sequence or iterator of *outputs* each of which
must either be a string specifying a filename for output, or a
file-like object with a ``write`` method, or a writeable buffer object.
For each item in the sequence or iterator of outputs, the camera
captures a single image as fast as it can.
The *format*, *use_video_port*, *splitter_port*, *resize*, and
*options* parameters are the same as in :meth:`capture`, but *format*
defaults to ``'jpeg'``. The format is **not** derived from the
filenames in *outputs* by this method.
If *use_video_port* is ``False`` (the default), the *burst* parameter
can be used to make still port captures faster. Specifically, this
prevents the preview from switching resolutions between captures which
significantly speeds up consecutive captures from the still port. The
downside is that this mode is currently has several bugs; the major
issue is that if captures are performed too quickly some frames will
come back severely underexposed. It is recommended that users avoid the
*burst* parameter unless they absolutely require it and are prepared to
work around such issues.
For example, to capture 3 consecutive images::
import time
import picamera
with picamera.PiCamera() as camera:
camera.start_preview()
time.sleep(2)
camera.capture_sequence([
'image1.jpg',
'image2.jpg',
'image3.jpg',
])
camera.stop_preview()
If you wish to capture a large number of images, a list comprehension
or generator expression can be used to construct the list of filenames
to use::
import time
import picamera
with picamera.PiCamera() as camera:
camera.start_preview()
time.sleep(2)
camera.capture_sequence([
'image%02d.jpg' % i
for i in range(100)
])
camera.stop_preview()
More complex effects can be obtained by using a generator function to
provide the filenames or output objects.
.. versionchanged:: 1.0
The *resize* parameter was added, and raw capture formats can now
be specified directly
.. versionchanged:: 1.3
The *splitter_port* parameter was added
.. versionchanged:: 1.11
Support for buffer outputs was added.
"""
if use_video_port:
if burst:
raise PiCameraValueError(
'burst is only valid with still port captures')
if bayer:
raise PiCameraValueError(
'bayer is only valid with still port captures')
with self._encoders_lock:
camera_port, output_port = self._get_ports(use_video_port, splitter_port)
format = self._get_image_format('', format)
if use_video_port:
encoder = self._get_images_encoder(
camera_port, output_port, format, resize, **options)
self._encoders[splitter_port] = encoder
else:
encoder = self._get_image_encoder(
camera_port, output_port, format, resize, **options)
try:
if use_video_port:
encoder.start(outputs)
encoder.wait()
else:
if burst:
camera_port.params[mmal.MMAL_PARAMETER_CAMERA_BURST_CAPTURE] = True
try:
for output in outputs:
if bayer:
camera_port.params[mmal.MMAL_PARAMETER_ENABLE_RAW_CAPTURE] = True
encoder.start(output)
if not encoder.wait(self.CAPTURE_TIMEOUT):
raise PiCameraRuntimeError(
'Timed out waiting for capture to end')
finally:
if burst:
camera_port.params[mmal.MMAL_PARAMETER_CAMERA_BURST_CAPTURE] = False
finally:
encoder.close()
with self._encoders_lock:
if use_video_port:
del self._encoders[splitter_port]
def capture_continuous(
self, output, format=None, use_video_port=False, resize=None,
splitter_port=0, burst=False, bayer=False, **options):
"""
Capture images continuously from the camera as an infinite iterator.
This method returns an infinite iterator of images captured
continuously from the camera. If *output* is a string, each captured
image is stored in a file named after *output* after substitution of
two values with the :meth:`~str.format` method. Those two values are:
* ``{counter}`` - a simple incrementor that starts at 1 and increases
by 1 for each image taken
* ``{timestamp}`` - a :class:`~datetime.datetime` instance
The table below contains several example values of *output* and the
sequence of filenames those values could produce:
.. tabularcolumns:: |p{80mm}|p{40mm}|p{10mm}|
+--------------------------------------------+--------------------------------------------+-------+
| *output* Value | Filenames | Notes |
+============================================+============================================+=======+
| ``'image{counter}.jpg'`` | image1.jpg, image2.jpg, image3.jpg, ... | |
+--------------------------------------------+--------------------------------------------+-------+
| ``'image{counter:02d}.jpg'`` | image01.jpg, image02.jpg, image03.jpg, ... | |
+--------------------------------------------+--------------------------------------------+-------+
| ``'image{timestamp}.jpg'`` | image2013-10-05 12:07:12.346743.jpg, | (1) |
| | image2013-10-05 12:07:32.498539, ... | |
+--------------------------------------------+--------------------------------------------+-------+
| ``'image{timestamp:%H-%M-%S-%f}.jpg'`` | image12-10-02-561527.jpg, | |
| | image12-10-14-905398.jpg | |
+--------------------------------------------+--------------------------------------------+-------+
| ``'{timestamp:%H%M%S}-{counter:03d}.jpg'`` | 121002-001.jpg, 121013-002.jpg, | (2) |
| | 121014-003.jpg, ... | |
+--------------------------------------------+--------------------------------------------+-------+
1. Note that because timestamp's default output includes colons (:),
the resulting filenames are not suitable for use on Windows. For
this reason (and the fact the default contains spaces) it is
strongly recommended you always specify a format when using
``{timestamp}``.
2. You can use both ``{timestamp}`` and ``{counter}`` in a single
format string (multiple times too!) although this tends to be
redundant.
If *output* is not a string, but has a ``write`` method, it is assumed
to be a file-like object and each image is simply written to this
object sequentially. In this case you will likely either want to write
something to the object between the images to distinguish them, or
clear the object between iterations. If *output* is not a string, and
has no ``write`` method, it is assumed to be a writeable object
supporting the buffer protocol; each image is simply written to the
buffer sequentially.
The *format*, *use_video_port*, *splitter_port*, *resize*, and
*options* parameters are the same as in :meth:`capture`.
If *use_video_port* is ``False`` (the default), the *burst* parameter
can be used to make still port captures faster. Specifically, this
prevents the preview from switching resolutions between captures which
significantly speeds up consecutive captures from the still port. The
downside is that this mode is currently has several bugs; the major
issue is that if captures are performed too quickly some frames will
come back severely underexposed. It is recommended that users avoid the
*burst* parameter unless they absolutely require it and are prepared to
work around such issues.
For example, to capture 60 images with a one second delay between them,
writing the output to a series of JPEG files named image01.jpg,
image02.jpg, etc. one could do the following::
import time
import picamera
with picamera.PiCamera() as camera:
camera.start_preview()
try:
for i, filename in enumerate(
camera.capture_continuous('image{counter:02d}.jpg')):
print(filename)
time.sleep(1)
if i == 59:
break
finally:
camera.stop_preview()
Alternatively, to capture JPEG frames as fast as possible into an
in-memory stream, performing some processing on each stream until
some condition is satisfied::
import io
import time
import picamera
with picamera.PiCamera() as camera:
stream = io.BytesIO()
for foo in camera.capture_continuous(stream, format='jpeg'):
# Truncate the stream to the current position (in case
# prior iterations output a longer image)
stream.truncate()
stream.seek(0)
if process(stream):
break
.. versionchanged:: 1.0
The *resize* parameter was added, and raw capture formats can now
be specified directly
.. versionchanged:: 1.3
The *splitter_port* parameter was added
.. versionchanged:: 1.11
Support for buffer outputs was added.
"""
if use_video_port:
if burst:
raise PiCameraValueError(
'burst is only valid with still port captures')
if bayer:
raise PiCameraValueError(
'bayer is only valid with still port captures')
with self._encoders_lock:
camera_port, output_port = self._get_ports(use_video_port, splitter_port)
format = self._get_image_format(output, format)
encoder = self._get_image_encoder(
camera_port, output_port, format, resize, **options)
if use_video_port:
self._encoders[splitter_port] = encoder
try:
if burst:
camera_port.params[mmal.MMAL_PARAMETER_CAMERA_BURST_CAPTURE] = True
try:
if isinstance(output, bytes):
# If we're fed a bytes string, assume it's UTF-8 encoded
# and convert it to Unicode. Technically this is wrong
# (file-systems use all sorts of encodings), but UTF-8 is a
# reasonable default and this keeps compatibility with
# Python 2 simple although it breaks the edge cases of
# non-UTF-8 encoded bytes strings with non-UTF-8 encoded
# file-systems
output = output.decode('utf-8')
if isinstance(output, str):
counter = 1
while True:
filename = output.format(
counter=counter,
timestamp=datetime.datetime.now(),
)
if bayer:
camera_port.params[mmal.MMAL_PARAMETER_ENABLE_RAW_CAPTURE] = True
encoder.start(filename)
if not encoder.wait(self.CAPTURE_TIMEOUT):
raise PiCameraRuntimeError(
'Timed out waiting for capture to end')
yield filename
counter += 1
else:
while True:
if bayer:
camera_port.params[mmal.MMAL_PARAMETER_ENABLE_RAW_CAPTURE] = True
encoder.start(output)
if not encoder.wait(self.CAPTURE_TIMEOUT):
raise PiCameraRuntimeError(
'Timed out waiting for capture to end')
yield output
finally:
if burst:
camera_port.params[mmal.MMAL_PARAMETER_CAMERA_BURST_CAPTURE] = False
finally:
encoder.close()
with self._encoders_lock:
if use_video_port:
del self._encoders[splitter_port]
@property
def closed(self):
"""
Returns ``True`` if the :meth:`close` method has been called.
"""
return not self._camera
@property
def recording(self):
"""
Returns ``True`` if the :meth:`start_recording` method has been called,
and no :meth:`stop_recording` call has been made yet.
"""
return any(
isinstance(e, PiVideoEncoder) and e.active
for e in self._encoders.values()
)
@property
def previewing(self):
"""
Returns ``True`` if the :meth:`start_preview` method has been called,
and no :meth:`stop_preview` call has been made yet.
.. deprecated:: 1.8
Test whether :attr:`preview` is ``None`` instead.
"""
warnings.warn(
PiCameraDeprecated(
'PiCamera.previewing is deprecated; test PiCamera.preview '
'is not None instead'))
return isinstance(self._preview, PiPreviewRenderer)
@property
def revision(self):
"""
Returns a string representing the revision of the Pi's camera module.
At the time of writing, the string returned is 'ov5647' for the V1
module, and 'imx219' for the V2 module.
"""
return self._revision
@property
def exif_tags(self):
"""
Holds a mapping of the Exif tags to apply to captured images.
.. note::
Please note that Exif tagging is only supported with the ``jpeg``
format.
By default several Exif tags are automatically applied to any images
taken with the :meth:`capture` method: ``IFD0.Make`` (which is set to
``RaspberryPi``), ``IFD0.Model`` (which is set to ``RP_OV5647``), and
three timestamp tags: ``IFD0.DateTime``, ``EXIF.DateTimeOriginal``, and
``EXIF.DateTimeDigitized`` which are all set to the current date and
time just before the picture is taken.
If you wish to set additional Exif tags, or override any of the
aforementioned tags, simply add entries to the exif_tags map before
calling :meth:`capture`. For example::
camera.exif_tags['IFD0.Copyright'] = 'Copyright (c) 2013 Foo Industries'
The Exif standard mandates ASCII encoding for all textual values, hence
strings containing non-ASCII characters will cause an encoding error to
be raised when :meth:`capture` is called. If you wish to set binary
values, use a :func:`bytes` value::
camera.exif_tags['EXIF.UserComment'] = b'Something containing\\x00NULL characters'
.. warning::
Binary Exif values are currently ignored; this appears to be a
libmmal or firmware bug.
You may also specify datetime values, integer, or float values, all of
which will be converted to appropriate ASCII strings (datetime values
are formatted as ``YYYY:MM:DD HH:MM:SS`` in accordance with the Exif
standard).
The currently supported Exif tags are:
+-------+-------------------------------------------------------------+
| Group | Tags |
+=======+=============================================================+
| IFD0, | ImageWidth, ImageLength, BitsPerSample, Compression, |
| IFD1 | PhotometricInterpretation, ImageDescription, Make, Model, |
| | StripOffsets, Orientation, SamplesPerPixel, RowsPerString, |
| | StripByteCounts, Xresolution, Yresolution, |
| | PlanarConfiguration, ResolutionUnit, TransferFunction, |
| | Software, DateTime, Artist, WhitePoint, |
| | PrimaryChromaticities, JPEGInterchangeFormat, |
| | JPEGInterchangeFormatLength, YcbCrCoefficients, |
| | YcbCrSubSampling, YcbCrPositioning, ReferenceBlackWhite, |
| | Copyright |
+-------+-------------------------------------------------------------+
| EXIF | ExposureTime, FNumber, ExposureProgram, |
| | SpectralSensitivity, ISOSpeedRatings, OECF, ExifVersion, |
| | DateTimeOriginal, DateTimeDigitized, |
| | ComponentsConfiguration, CompressedBitsPerPixel, |
| | ShutterSpeedValue, ApertureValue, BrightnessValue, |
| | ExposureBiasValue, MaxApertureValue, SubjectDistance, |
| | MeteringMode, LightSource, Flash, FocalLength, SubjectArea, |
| | MakerNote, UserComment, SubSecTime, SubSecTimeOriginal, |
| | SubSecTimeDigitized, FlashpixVersion, ColorSpace, |
| | PixelXDimension, PixelYDimension, RelatedSoundFile, |
| | FlashEnergy, SpacialFrequencyResponse, |
| | FocalPlaneXResolution, FocalPlaneYResolution, |
| | FocalPlaneResolutionUnit, SubjectLocation, ExposureIndex, |
| | SensingMethod, FileSource, SceneType, CFAPattern, |
| | CustomRendered, ExposureMode, WhiteBalance, |
| | DigitalZoomRatio, FocalLengthIn35mmFilm, SceneCaptureType, |
| | GainControl, Contrast, Saturation, Sharpness, |
| | DeviceSettingDescription, SubjectDistanceRange, |
| | ImageUniqueID |
+-------+-------------------------------------------------------------+
| GPS | GPSVersionID, GPSLatitudeRef, GPSLatitude, GPSLongitudeRef, |
| | GPSLongitude, GPSAltitudeRef, GPSAltitude, GPSTimeStamp, |
| | GPSSatellites, GPSStatus, GPSMeasureMode, GPSDOP, |
| | GPSSpeedRef, GPSSpeed, GPSTrackRef, GPSTrack, |
| | GPSImgDirectionRef, GPSImgDirection, GPSMapDatum, |
| | GPSDestLatitudeRef, GPSDestLatitude, GPSDestLongitudeRef, |
| | GPSDestLongitude, GPSDestBearingRef, GPSDestBearing, |
| | GPSDestDistanceRef, GPSDestDistance, GPSProcessingMethod, |
| | GPSAreaInformation, GPSDateStamp, GPSDifferential |
+-------+-------------------------------------------------------------+
| EINT | InteroperabilityIndex, InteroperabilityVersion, |
| | RelatedImageFileFormat, RelatedImageWidth, |
| | RelatedImageLength |
+-------+-------------------------------------------------------------+
"""
return self._exif_tags
def _set_led(self, value):
if not self._used_led:
self._init_led()
if not GPIO:
raise PiCameraRuntimeError(
"GPIO library not found, or not accessible; please install "
"RPi.GPIO and run the script as root")
GPIO.output(self._led_pin, bool(value))
led = property(None, _set_led, doc="""
Sets the state of the camera's LED via GPIO.
If a GPIO library is available (only RPi.GPIO is currently supported),
and if the python process has the necessary privileges (typically this
means running as root via sudo), this property can be used to set the
state of the camera's LED as a boolean value (``True`` is on, ``False``
is off).
.. note::
This is a write-only property. While it can be used to control the
camera's LED, you cannot query the state of the camera's LED using
this property.
.. note::
At present, the camera's LED cannot be controlled on the Pi 3
(the GPIOs used to control the camera LED were re-routed to GPIO
expander on the Pi 3).
.. warning::
There are circumstances in which the camera firmware may override
an existing LED setting. For example, in the case that the firmware
resets the camera (as can happen with a CSI-2 timeout), the LED may
also be reset. If you wish to guarantee that the LED remain off at
all times, you may prefer to use the ``disable_camera_led`` option
in `config.txt`_ (this has the added advantage that sudo privileges
and GPIO access are not required, at least for LED control).
.. _config.txt: https://www.raspberrypi.org/documentation/configuration/config-txt.md
""")
def _get_raw_format(self):
warnings.warn(
PiCameraDeprecated(
'PiCamera.raw_format is deprecated; use required format '
'directly with capture methods instead'))
return self._raw_format
def _set_raw_format(self, value):
warnings.warn(
PiCameraDeprecated(
'PiCamera.raw_format is deprecated; use required format '
'directly with capture methods instead'))
if value not in self.RAW_FORMATS:
raise PiCameraValueError("Invalid raw format: %s" % value)
self._raw_format = value
raw_format = property(_get_raw_format, _set_raw_format, doc="""
Retrieves or sets the raw format of the camera's ports.
.. deprecated:: 1.0
Please use ``'yuv'`` or ``'rgb'`` directly as a format in the
various capture methods instead.
""")
def _get_timestamp(self):
self._check_camera_open()
return self._camera.control.params[mmal.MMAL_PARAMETER_SYSTEM_TIME]
timestamp = property(_get_timestamp, doc="""
Retrieves the system time according to the camera firmware.
The camera's timestamp is a 64-bit integer representing the number of
microseconds since the last system boot. When the camera's
:attr:`clock_mode` is ``'raw'`` the values returned by this attribute
are comparable to those from the :attr:`frame`
:attr:`~PiVideoFrame.timestamp` attribute.
""")
def _get_frame(self):
self._check_camera_open()
for e in self._encoders.values():
try:
return e.frame
except AttributeError:
pass
raise PiCameraRuntimeError(
"Cannot query frame information when camera is not recording")
frame = property(_get_frame, doc="""
Retrieves information about the current frame recorded from the camera.
When video recording is active (after a call to
:meth:`start_recording`), this attribute will return a
:class:`PiVideoFrame` tuple containing information about the current
frame that the camera is recording.
If multiple video recordings are currently in progress (after multiple
calls to :meth:`start_recording` with different values for the
``splitter_port`` parameter), which encoder's frame information is
returned is arbitrary. If you require information from a specific
encoder, you will need to extract it from :attr:`_encoders` explicitly.
Querying this property when the camera is not recording will result in
an exception.
.. note::
There is a small window of time when querying this attribute will
return ``None`` after calling :meth:`start_recording`. If this
attribute returns ``None``, this means that the video encoder has
been initialized, but the camera has not yet returned any frames.
""")
def _disable_camera(self):
"""
An internal method for disabling the camera, e.g. for re-configuration.
This disables the splitter and preview connections (if they exist).
"""
self._splitter.connection.disable()
self._preview.renderer.connection.disable()
self._camera.disable()
def _enable_camera(self):
"""
An internal method for enabling the camera after re-configuration.
This ensures the splitter configuration is consistent, then re-enables
the camera along with the splitter and preview connections.
"""
self._camera.enable()
self._preview.renderer.connection.enable()
self._splitter.connection.enable()
def _configure_splitter(self):
"""
Ensures all splitter output ports have a sensible format (I420) and
buffer sizes.
This method is used to ensure the splitter configuration is sane,
typically after :meth:`_configure_camera` is called.
"""
self._splitter.inputs[0].copy_from(self._camera.outputs[self.CAMERA_VIDEO_PORT])
self._splitter.inputs[0].commit()
def _control_callback(self, port, buf):
try:
if buf.command == mmal.MMAL_EVENT_ERROR:
raise PiCameraRuntimeError(
"No data recevied from sensor. Check all connections, "
"including the SUNNY chip on the camera board")
elif buf.command != mmal.MMAL_EVENT_PARAMETER_CHANGED:
raise PiCameraRuntimeError(
"Received unexpected camera control callback event, 0x%08x" % buf[0].cmd)
except Exception as exc:
# Pass the exception to the main thread; next time
# check_camera_open() is called this will get raised
self._camera_exception = exc
def _configure_camera(
self, sensor_mode, framerate, resolution, clock_mode,
old_sensor_mode=0):
"""
An internal method for setting a new camera mode, framerate,
resolution, and/or clock_mode.
This method is used by the setters of the :attr:`resolution`,
:attr:`framerate`, and :attr:`sensor_mode` properties. It assumes the
camera is currently disabled. The *old_mode* and *new_mode* arguments
are required to ensure correct operation on older firmwares
(specifically that we don't try to set the sensor mode when both old
and new modes are 0 or automatic).
"""
old_cc = mmal.MMAL_PARAMETER_CAMERA_CONFIG_T.from_buffer_copy(self._camera_config)
old_ports = [
(port.framesize, port.framerate, port.params[mmal.MMAL_PARAMETER_FPS_RANGE])
for port in self._camera.outputs
]
if old_sensor_mode != 0 or sensor_mode != 0:
self._camera.control.params[mmal.MMAL_PARAMETER_CAMERA_CUSTOM_SENSOR_CONFIG] = sensor_mode
if not self._camera.control.enabled:
# Initial setup
self._camera.control.enable(self._control_callback)
preview_resolution = resolution
elif (
self._camera.outputs[self.CAMERA_PREVIEW_PORT].framesize ==
self._camera.outputs[self.CAMERA_VIDEO_PORT].framesize
):
preview_resolution = resolution
else:
preview_resolution = self._camera.outputs[self.CAMERA_PREVIEW_PORT].framesize
try:
try:
fps_low, fps_high = framerate
except TypeError:
fps_low = fps_high = framerate
else:
framerate = 0
fps_range = mmal.MMAL_PARAMETER_FPS_RANGE_T(
mmal.MMAL_PARAMETER_HEADER_T(
mmal.MMAL_PARAMETER_FPS_RANGE,
ct.sizeof(mmal.MMAL_PARAMETER_FPS_RANGE_T)
),
fps_low=mo.to_rational(fps_low),
fps_high=mo.to_rational(fps_high),
)
cc = self._camera_config
cc.max_stills_w = resolution.width
cc.max_stills_h = resolution.height
cc.stills_yuv422 = 0
cc.one_shot_stills = 1
cc.max_preview_video_w = resolution.width
cc.max_preview_video_h = resolution.height
cc.num_preview_video_frames = max(3, fps_high // 10)
cc.stills_capture_circular_buffer_height = 0
cc.fast_preview_resume = 0
cc.use_stc_timestamp = clock_mode
self._camera.control.params[mmal.MMAL_PARAMETER_CAMERA_CONFIG] = cc
# Clamp preview resolution to camera's resolution
if (
preview_resolution.width > resolution.width or
preview_resolution.height > resolution.height
):
preview_resolution = resolution
for port in self._camera.outputs:
port.params[mmal.MMAL_PARAMETER_FPS_RANGE] = fps_range
if port.index == self.CAMERA_PREVIEW_PORT:
port.framesize = preview_resolution
else:
port.framesize = resolution
port.framerate = framerate
port.commit()
except:
# If anything goes wrong, restore original resolution and
# framerate otherwise the camera can be left in unusual states
# (camera config not matching ports, etc).
self._camera.control.params[mmal.MMAL_PARAMETER_CAMERA_CONFIG] = old_cc
self._camera_config = old_cc
for port, (res, fps, fps_range) in zip(self._camera.outputs, old_ports):
port.framesize = res
port.framerate = fps
port.params[mmal.MMAL_PARAMETER_FPS_RANGE] = fps_range
port.commit()
raise
def _get_framerate(self):
self._check_camera_open()
port_num = (
self.CAMERA_VIDEO_PORT
if self._encoders else
self.CAMERA_PREVIEW_PORT
)
return mo.PiCameraFraction(self._camera.outputs[port_num].framerate)
def _set_framerate(self, value):
self._check_camera_open()
self._check_recording_stopped()
value = mo.to_fraction(value, den_limit=256)
if not (0 < value <= self.MAX_FRAMERATE):
raise PiCameraValueError("Invalid framerate: %.2ffps" % value)
sensor_mode = self.sensor_mode
clock_mode = self.CLOCK_MODES[self.clock_mode]
resolution = self.resolution
self._disable_camera()
self._configure_camera(
sensor_mode=sensor_mode, framerate=value, resolution=resolution,
clock_mode=clock_mode)
self._configure_splitter()
self._enable_camera()
framerate = property(_get_framerate, _set_framerate, doc="""\
Retrieves or sets the framerate at which video-port based image
captures, video recordings, and previews will run.
When queried, the :attr:`framerate` property returns the rate at which
the camera's video and preview ports will operate as a
:class:`~fractions.Fraction` instance (which can be easily converted to
an :class:`int` or :class:`float`). If :attr:`framerate_range` has been
set, then :attr:`framerate` will be 0 which indicates that a dynamic
range of framerates is being used.
.. note::
For backwards compatibility, a derivative of the
:class:`~fractions.Fraction` class is actually used which permits
the value to be treated as a tuple of ``(numerator, denominator)``.
Setting and retrieving framerate as a ``(numerator, denominator)``
tuple is deprecated and will be removed in 2.0. Please use a
:class:`~fractions.Fraction` instance instead (which is just as
accurate and also permits direct use with math operators).
When set, the property configures the camera so that the next call to
recording and previewing methods will use the new framerate. Setting
this property implicitly sets :attr:`framerate_range` so that the low
and high values are equal to the new framerate. The framerate can be
specified as an :ref:`int <typesnumeric>`, :ref:`float <typesnumeric>`,
:class:`~fractions.Fraction`, or a ``(numerator, denominator)`` tuple.
For example, the following definitions are all equivalent::
from fractions import Fraction
camera.framerate = 30
camera.framerate = 30 / 1
camera.framerate = Fraction(30, 1)
camera.framerate = (30, 1) # deprecated
The camera must not be closed, and no recording must be active when the
property is set.
.. note::
This attribute, in combination with :attr:`resolution`, determines
the mode that the camera operates in. The actual sensor framerate
and resolution used by the camera is influenced, but not directly
set, by this property. See :attr:`sensor_mode` for more
information.
The initial value of this property can be specified with the
*framerate* parameter in the :class:`PiCamera` constructor, and will
default to 30 if not specified.
""")
def _get_sensor_mode(self):
self._check_camera_open()
return self._camera.control.params[mmal.MMAL_PARAMETER_CAMERA_CUSTOM_SENSOR_CONFIG]
def _set_sensor_mode(self, value):
self._check_camera_open()
self._check_recording_stopped()
try:
if not (0 <= value <= 7):
raise PiCameraValueError(
"Invalid sensor mode: %d (valid range 0..7)" % value)
except TypeError:
raise PiCameraValueError("Invalid sensor mode: %s" % value)
sensor_mode = self.sensor_mode
clock_mode = self.CLOCK_MODES[self.clock_mode]
resolution = self.resolution
framerate = Fraction(self.framerate)
if framerate == 0:
framerate = self.framerate_range
self._disable_camera()
self._configure_camera(
old_sensor_mode=sensor_mode, sensor_mode=value,
framerate=framerate, resolution=resolution,
clock_mode=clock_mode)
self._configure_splitter()
self._enable_camera()
sensor_mode = property(_get_sensor_mode, _set_sensor_mode, doc="""\
Retrieves or sets the input mode of the camera's sensor.
This is an advanced property which can be used to control the camera's
sensor mode. By default, mode 0 is used which allows the camera to
automatically select an input mode based on the requested
:attr:`resolution` and :attr:`framerate`. Valid values are currently
between 0 and 7. The set of valid sensor modes (along with the
heuristic used to select one automatically) are detailed in the
:ref:`camera_modes` section of the documentation.
.. note::
At the time of writing, setting this property does nothing unless
the camera has been initialized with a sensor mode other than 0.
Furthermore, some mode transitions appear to require setting the
property twice (in a row). This appears to be a firmware
limitation.
The initial value of this property can be specified with the
*sensor_mode* parameter in the :class:`PiCamera` constructor, and will
default to 0 if not specified.
.. versionadded:: 1.9
""")
def _get_clock_mode(self):
self._check_camera_open()
return self._CLOCK_MODES_R[self._camera_config.use_stc_timestamp]
def _set_clock_mode(self, value):
self._check_camera_open()
self._check_recording_stopped()
try:
clock_mode = self.CLOCK_MODES[value]
except KeyError:
raise PiCameraValueError("Invalid clock mode %s" % value)
sensor_mode = self.sensor_mode
framerate = Fraction(self.framerate)
if framerate == 0:
framerate = self.framerate_range
resolution = self.resolution
self._disable_camera()
self._configure_camera(
sensor_mode=sensor_mode, framerate=framerate,
resolution=resolution, clock_mode=clock_mode)
self._configure_splitter()
self._enable_camera()
clock_mode = property(_get_clock_mode, _set_clock_mode, doc="""\
Retrieves or sets the mode of the camera's clock.
This is an advanced property which can be used to control the nature of
the frame timestamps available from the :attr:`frame` property. When
this is "reset" (the default) each frame's timestamp will be relative
to the start of the recording. When this is "raw", each frame's
timestamp will be relative to the last initialization of the camera.
The initial value of this property can be specified with the
*clock_mode* parameter in the :class:`PiCamera` constructor, and will
default to "reset" if not specified.
.. versionadded:: 1.11
""")
def _get_resolution(self):
self._check_camera_open()
return mo.PiResolution(
int(self._camera_config.max_stills_w),
int(self._camera_config.max_stills_h)
)
def _set_resolution(self, value):
self._check_camera_open()
self._check_recording_stopped()
value = mo.to_resolution(value)
if not (
(0 < value.width <= self.MAX_RESOLUTION.width) and
(0 < value.height <= self.MAX_RESOLUTION.height)):
raise PiCameraValueError(
"Invalid resolution requested: %r" % (value,))
sensor_mode = self.sensor_mode
clock_mode = self.CLOCK_MODES[self.clock_mode]
framerate = Fraction(self.framerate)
if framerate == 0:
framerate = self.framerate_range
self._disable_camera()
self._configure_camera(
sensor_mode=sensor_mode, framerate=framerate,
resolution=value, clock_mode=clock_mode)
self._configure_splitter()
self._enable_camera()
resolution = property(_get_resolution, _set_resolution, doc="""
Retrieves or sets the resolution at which image captures, video
recordings, and previews will be captured.
When queried, the :attr:`resolution` property returns the resolution at
which the camera will operate as a tuple of ``(width, height)``
measured in pixels. This is the resolution that the :meth:`capture`
method will produce images at, and the resolution that
:meth:`start_recording` will produce videos at.
When set, the property configures the camera so that the next call to
these methods will use the new resolution. The resolution can be
specified as a ``(width, height)`` tuple, as a string formatted
``'WIDTHxHEIGHT'``, or as a string containing a commonly recognized
`display resolution`_ name (e.g. "VGA", "HD", "1080p", etc). For
example, the following definitions are all equivalent::
camera.resolution = (1280, 720)
camera.resolution = '1280x720'
camera.resolution = '1280 x 720'
camera.resolution = 'HD'
camera.resolution = '720p'
The camera must not be closed, and no recording must be active when the
property is set.
.. note::
This attribute, in combination with :attr:`framerate`, determines
the mode that the camera operates in. The actual sensor framerate
and resolution used by the camera is influenced, but not directly
set, by this property. See :attr:`sensor_mode` for more
information.
The initial value of this property can be specified with the
*resolution* parameter in the :class:`PiCamera` constructor, and will
default to the display's resolution or 1280x720 if the display has
been disabled (with ``tvservice -o``).
.. versionchanged:: 1.11
Resolution permitted to be set as a string. Preview resolution
added as separate property.
.. _display resolution: https://en.wikipedia.org/wiki/Graphics_display_resolution
""")
def _get_framerate_range(self):
self._check_camera_open()
port_num = (
self.CAMERA_VIDEO_PORT
if self._encoders else
self.CAMERA_PREVIEW_PORT
)
mp = self._camera.outputs[port_num].params[mmal.MMAL_PARAMETER_FPS_RANGE]
return mo.PiFramerateRange(
mo.to_fraction(mp.fps_low), mo.to_fraction(mp.fps_high))
def _set_framerate_range(self, value):
self._check_camera_open()
self._check_recording_stopped()
low, high = value
low = mo.to_fraction(low, den_limit=256)
high = mo.to_fraction(high, den_limit=256)
if not (0 < low <= self.MAX_FRAMERATE):
raise PiCameraValueError("Invalid low framerate: %.2ffps" % low)
if not (0 < high <= self.MAX_FRAMERATE):
raise PiCameraValueError("Invalid high framerate: %.2ffps" % high)
if high < low:
raise PiCameraValueError("framerate_range is backwards")
sensor_mode = self.sensor_mode
clock_mode = self.CLOCK_MODES[self.clock_mode]
resolution = self.resolution
self._disable_camera()
self._configure_camera(
sensor_mode=sensor_mode, framerate=(low, high),
resolution=resolution, clock_mode=clock_mode)
self._configure_splitter()
self._enable_camera()
framerate_range = property(_get_framerate_range, _set_framerate_range, doc="""\
Retrieves or sets a range between which the camera's framerate is
allowed to float.
When queried, the :attr:`framerate_range` property returns a
:func:`~collections.namedtuple` derivative with ``low`` and ``high``
components (index 0 and 1 respectively) which specify the limits of the
permitted framerate range.
When set, the property configures the camera so that the next call to
recording and previewing methods will use the new framerate range.
Setting this property will implicitly set the :attr:`framerate`
property to 0 (indicating that a dynamic range of framerates is in use
by the camera).
.. note::
Use of this property prevents use of :attr:`framerate_delta` (there
would be little point in making fractional adjustments to the
framerate when the framerate itself is variable).
The low and high framerates can be specified as :ref:`int
<typesnumeric>`, :ref:`float <typesnumeric>`, or
:class:`~fractions.Fraction` values. For example, the following
definitions are all equivalent::
from fractions import Fraction
camera.framerate_range = (0.16666, 30)
camera.framerate_range = (Fraction(1, 6), 30 / 1)
camera.framerate_range = (Fraction(1, 6), Fraction(30, 1))
The camera must not be closed, and no recording must be active when the
property is set.
.. note::
This attribute, like :attr:`framerate`, determines the mode that
the camera operates in. The actual sensor framerate and resolution
used by the camera is influenced, but not directly set, by this
property. See :attr:`sensor_mode` for more information.
.. versionadded:: 1.13
""")
def _get_framerate_delta(self):
self._check_camera_open()
if self.framerate == 0:
raise PiCameraValueError(
'framerate_delta cannot be used with framerate_range')
port_num = (
self.CAMERA_VIDEO_PORT
if self._encoders else
self.CAMERA_PREVIEW_PORT
)
return self._camera.outputs[port_num].params[mmal.MMAL_PARAMETER_FRAME_RATE] - self.framerate
def _set_framerate_delta(self, value):
self._check_camera_open()
if self.framerate == 0:
raise PiCameraValueError(
'framerate_delta cannot be used with framerate_range')
value = mo.to_fraction(self.framerate + value, den_limit=256)
self._camera.outputs[self.CAMERA_PREVIEW_PORT].params[mmal.MMAL_PARAMETER_FRAME_RATE] = value
self._camera.outputs[self.CAMERA_VIDEO_PORT].params[mmal.MMAL_PARAMETER_FRAME_RATE] = value
framerate_delta = property(_get_framerate_delta, _set_framerate_delta, doc="""\
Retrieves or sets a fractional amount that is added to the camera's
framerate for the purpose of minor framerate adjustments.
When queried, the :attr:`framerate_delta` property returns the amount
that the camera's :attr:`framerate` has been adjusted. This defaults
to 0 (so the camera's framerate is the actual framerate used).
When set, the property adjusts the camera's framerate on the fly. The
property can be set while recordings or previews are in progress. Thus
the framerate used by the camera is actually :attr:`framerate` +
:attr:`framerate_delta`.
.. note::
Framerates deltas can be fractional with adjustments as small as
1/256th of an fps possible (finer adjustments will be rounded).
With an appropriately tuned PID controller, this can be used to
achieve synchronization between the camera framerate and other
devices.
If the new framerate demands a mode switch (such as moving between a
low framerate and a high framerate mode), currently active recordings
may drop a frame. This should only happen when specifying quite large
deltas, or when framerate is at the boundary of a sensor mode (e.g.
49fps).
The framerate delta can be specified as an :ref:`int <typesnumeric>`,
:ref:`float <typesnumeric>`, :class:`~fractions.Fraction` or a
``(numerator, denominator)`` tuple. For example, the following
definitions are all equivalent::
from fractions import Fraction
camera.framerate_delta = 0.5
camera.framerate_delta = 1 / 2 # in python 3
camera.framerate_delta = Fraction(1, 2)
camera.framerate_delta = (1, 2) # deprecated
.. note::
This property is implicitly reset to 0 when :attr:`framerate` or
:attr:`framerate_range` is set. When :attr:`framerate` is 0
(indicating that :attr:`framerate_range` is set), this property
cannot be used. (there would be little point in making fractional
adjustments to the framerate when the framerate itself is
variable).
.. versionadded:: 1.11
""")
def _get_still_stats(self):
self._check_camera_open()
return self._camera.control.params[mmal.MMAL_PARAMETER_CAPTURE_STATS_PASS]
def _set_still_stats(self, value):
self._check_camera_open()
self._camera.control.params[mmal.MMAL_PARAMETER_CAPTURE_STATS_PASS] = value
still_stats = property(_get_still_stats, _set_still_stats, doc="""\
Retrieves or sets whether statistics will be calculated from still
frames or the prior preview frame.
When queried, the :attr:`still_stats` property returns a boolean value
indicating when scene statistics will be calculated for still captures
(that is, captures where the *use_video_port* parameter of
:meth:`capture` is ``False``). When this property is ``False`` (the
default), statistics will be calculated from the preceding preview
frame (this also applies when the preview is not visible). When `True`,
statistics will be calculated from the captured image itself.
When set, the propetry controls when scene statistics will be
calculated for still captures. The property can be set while recordings
or previews are in progress. The default value is ``False``.
The advantages to calculating scene statistics from the captured image
are that time between startup and capture is reduced as only the AGC
(automatic gain control) has to converge. The downside is that
processing time for captures increases and that white balance and gain
won't necessarily match the preview.
.. warning::
Enabling the still statistics pass will `override fixed white
balance`_ gains (set via :attr:`awb_gains` and :attr:`awb_mode`).
.. _override fixed white balance: https://www.raspberrypi.org/forums/viewtopic.php?p=875772&sid=92fa4ea70d1fe24590a4cdfb4a10c489#p875772
.. versionadded:: 1.9
""")
def _get_saturation(self):
self._check_camera_open()
return int(self._camera.control.params[mmal.MMAL_PARAMETER_SATURATION] * 100)
def _set_saturation(self, value):
self._check_camera_open()
if not (-100 <= value <= 100):
raise PiCameraValueError(
"Invalid saturation value: %d (valid range -100..100)" % value)
self._camera.control.params[mmal.MMAL_PARAMETER_SATURATION] = Fraction(value, 100)
saturation = property(_get_saturation, _set_saturation, doc="""\
Retrieves or sets the saturation setting of the camera.
When queried, the :attr:`saturation` property returns the color
saturation of the camera as an integer between -100 and 100. When set,
the property adjusts the saturation of the camera. Saturation can be
adjusted while previews or recordings are in progress. The default
value is 0.
""")
def _get_sharpness(self):
self._check_camera_open()
return int(self._camera.control.params[mmal.MMAL_PARAMETER_SHARPNESS] * 100)
def _set_sharpness(self, value):
self._check_camera_open()
if not (-100 <= value <= 100):
raise PiCameraValueError(
"Invalid sharpness value: %d (valid range -100..100)" % value)
self._camera.control.params[mmal.MMAL_PARAMETER_SHARPNESS] = Fraction(value, 100)
sharpness = property(_get_sharpness, _set_sharpness, doc="""\
Retrieves or sets the sharpness setting of the camera.
When queried, the :attr:`sharpness` property returns the sharpness
level of the camera (a measure of the amount of post-processing to
reduce or increase image sharpness) as an integer between -100 and 100.
When set, the property adjusts the sharpness of the camera. Sharpness
can be adjusted while previews or recordings are in progress. The
default value is 0.
""")
def _get_contrast(self):
self._check_camera_open()
return int(self._camera.control.params[mmal.MMAL_PARAMETER_CONTRAST] * 100)
def _set_contrast(self, value):
self._check_camera_open()
if not (-100 <= value <= 100):
raise PiCameraValueError(
"Invalid contrast value: %d (valid range -100..100)" % value)
self._camera.control.params[mmal.MMAL_PARAMETER_CONTRAST] = Fraction(value, 100)
contrast = property(_get_contrast, _set_contrast, doc="""\
Retrieves or sets the contrast setting of the camera.
When queried, the :attr:`contrast` property returns the contrast level
of the camera as an integer between -100 and 100. When set, the
property adjusts the contrast of the camera. Contrast can be adjusted
while previews or recordings are in progress. The default value is 0.
""")
def _get_brightness(self):
self._check_camera_open()
return int(self._camera.control.params[mmal.MMAL_PARAMETER_BRIGHTNESS] * 100)
def _set_brightness(self, value):
self._check_camera_open()
if not (0 <= value <= 100):
raise PiCameraValueError(
"Invalid brightness value: %d (valid range 0..100)" % value)
self._camera.control.params[mmal.MMAL_PARAMETER_BRIGHTNESS] = Fraction(value, 100)
brightness = property(_get_brightness, _set_brightness, doc="""\
Retrieves or sets the brightness setting of the camera.
When queried, the :attr:`brightness` property returns the brightness
level of the camera as an integer between 0 and 100. When set, the
property adjusts the brightness of the camera. Brightness can be
adjusted while previews or recordings are in progress. The default
value is 50.
""")
def _get_shutter_speed(self):
self._check_camera_open()
return int(self._camera.control.params[mmal.MMAL_PARAMETER_SHUTTER_SPEED])
def _set_shutter_speed(self, value):
self._check_camera_open()
self._camera.control.params[mmal.MMAL_PARAMETER_SHUTTER_SPEED] = value
shutter_speed = property(_get_shutter_speed, _set_shutter_speed, doc="""\
Retrieves or sets the shutter speed of the camera in microseconds.
When queried, the :attr:`shutter_speed` property returns the shutter
speed of the camera in microseconds, or 0 which indicates that the
speed will be automatically determined by the auto-exposure algorithm.
Faster shutter times naturally require greater amounts of illumination
and vice versa.
When set, the property adjusts the shutter speed of the camera, which
most obviously affects the illumination of subsequently captured
images. Shutter speed can be adjusted while previews or recordings are
running. The default value is 0 (auto).
.. note::
You can query the :attr:`exposure_speed` attribute to determine the
actual shutter speed being used when this attribute is set to 0.
Please note that this capability requires an up to date firmware
(#692 or later).
.. note::
In later firmwares, this attribute is limited by the value of the
:attr:`framerate` attribute. For example, if framerate is set to
30fps, the shutter speed cannot be slower than 33,333µs (1/fps).
""")
def _get_exposure_speed(self):
self._check_camera_open()
return self._camera.control.params[mmal.MMAL_PARAMETER_CAMERA_SETTINGS].exposure
exposure_speed = property(_get_exposure_speed, doc="""\
Retrieves the current shutter speed of the camera.
When queried, this property returns the shutter speed currently being
used by the camera. If you have set :attr:`shutter_speed` to a non-zero
value, then :attr:`exposure_speed` and :attr:`shutter_speed` should be
equal. However, if :attr:`shutter_speed` is set to 0 (auto), then you
can read the actual shutter speed being used from this attribute. The
value is returned as an integer representing a number of microseconds.
This is a read-only property.
.. versionadded:: 1.6
""")
def _get_analog_gain(self):
self._check_camera_open()
return mo.to_fraction(
self._camera.control.params[mmal.MMAL_PARAMETER_CAMERA_SETTINGS].analog_gain)
analog_gain = property(_get_analog_gain, doc="""\
Retrieves the current analog gain of the camera.
When queried, this property returns the analog gain currently being
used by the camera. The value represents the analog gain of the sensor
prior to digital conversion. The value is returned as a
:class:`~fractions.Fraction` instance.
.. versionadded:: 1.6
""")
def _get_digital_gain(self):
self._check_camera_open()
return mo.to_fraction(
self._camera.control.params[mmal.MMAL_PARAMETER_CAMERA_SETTINGS].digital_gain)
digital_gain = property(_get_digital_gain, doc="""\
Retrieves the current digital gain of the camera.
When queried, this property returns the digital gain currently being
used by the camera. The value represents the digital gain the camera
applies after conversion of the sensor's analog output. The value is
returned as a :class:`~fractions.Fraction` instance.
.. versionadded:: 1.6
""")
def _get_video_denoise(self):
self._check_camera_open()
return self._camera.control.params[mmal.MMAL_PARAMETER_VIDEO_DENOISE]
def _set_video_denoise(self, value):
self._check_camera_open()
self._camera.control.params[mmal.MMAL_PARAMETER_VIDEO_DENOISE] = value
video_denoise = property(_get_video_denoise, _set_video_denoise, doc="""\
Retrieves or sets whether denoise will be applied to video recordings.
When queried, the :attr:`video_denoise` property returns a boolean
value indicating whether or not the camera software will apply a
denoise algorithm to video recordings.
When set, the property activates or deactivates the denoise algorithm
for video recordings. The property can be set while recordings or
previews are in progress. The default value is ``True``.
.. versionadded:: 1.7
""")
def _get_image_denoise(self):
self._check_camera_open()
return self._camera.control.params[mmal.MMAL_PARAMETER_STILLS_DENOISE]
def _set_image_denoise(self, value):
self._check_camera_open()
self._camera.control.params[mmal.MMAL_PARAMETER_STILLS_DENOISE] = value
image_denoise = property(_get_image_denoise, _set_image_denoise, doc="""\
Retrieves or sets whether denoise will be applied to image captures.
When queried, the :attr:`image_denoise` property returns a boolean
value indicating whether or not the camera software will apply a
denoise algorithm to image captures.
When set, the property activates or deactivates the denoise algorithm
for image captures. The property can be set while recordings or
previews are in progress. The default value is ``True``.
.. versionadded:: 1.7
""")
def _get_drc_strength(self):
self._check_camera_open()
return self._DRC_STRENGTHS_R[
self._camera.control.params[mmal.MMAL_PARAMETER_DYNAMIC_RANGE_COMPRESSION].strength
]
def _set_drc_strength(self, value):
self._check_camera_open()
try:
mp = self._camera.control.params[mmal.MMAL_PARAMETER_DYNAMIC_RANGE_COMPRESSION]
mp.strength = self.DRC_STRENGTHS[value]
except KeyError:
raise PiCameraValueError(
"Invalid dynamic range compression strength: %s" % value)
self._camera.control.params[mmal.MMAL_PARAMETER_DYNAMIC_RANGE_COMPRESSION] = mp
drc_strength = property(_get_drc_strength, _set_drc_strength, doc="""\
Retrieves or sets the dynamic range compression strength of the camera.
When queried, the :attr:`drc_strength` property returns a string
indicating the amount of `dynamic range compression`_ the camera
applies to images.
When set, the attributes adjusts the strength of the dynamic range
compression applied to the camera's output. Valid values are given
in the list below:
{values}
The default value is ``'off'``. All possible values for the attribute
can be obtained from the ``PiCamera.DRC_STRENGTHS`` attribute.
.. warning::
Enabling DRC will `override fixed white balance`_ gains (set via
:attr:`awb_gains` and :attr:`awb_mode`).
.. _dynamic range compression: https://en.wikipedia.org/wiki/Gain_compression
.. _override fixed white balance: https://www.raspberrypi.org/forums/viewtopic.php?p=875772&sid=92fa4ea70d1fe24590a4cdfb4a10c489#p875772
.. versionadded:: 1.6
""".format(values=docstring_values(DRC_STRENGTHS)))
def _get_ISO(self):
warnings.warn(
PiCameraDeprecated(
'PiCamera.ISO is deprecated; use PiCamera.iso instead'))
return self.iso
def _set_ISO(self, value):
warnings.warn(
PiCameraDeprecated(
'PiCamera.ISO is deprecated; use PiCamera.iso instead'))
self.iso = value
ISO = property(_get_ISO, _set_ISO, doc="""
Retrieves or sets the apparent ISO setting of the camera.
.. deprecated:: 1.8
Please use the :attr:`iso` attribute instead.
""")
def _get_iso(self):
self._check_camera_open()
return self._camera.control.params[mmal.MMAL_PARAMETER_ISO]
def _set_iso(self, value):
self._check_camera_open()
try:
if not (0 <= value <= 1600):
raise PiCameraValueError(
"Invalid iso value: %d (valid range 0..800)" % value)
except TypeError:
raise PiCameraValueError("Invalid iso value: %s" % value)
self._camera.control.params[mmal.MMAL_PARAMETER_ISO] = value
iso = property(_get_iso, _set_iso, doc="""\
Retrieves or sets the apparent ISO setting of the camera.
When queried, the :attr:`iso` property returns the ISO setting of the
camera, a value which represents the `sensitivity of the camera to
light`_. Lower values (e.g. 100) imply less sensitivity than higher
values (e.g. 400 or 800). Lower sensitivities tend to produce less
"noisy" (smoother) images, but operate poorly in low light conditions.
When set, the property adjusts the sensitivity of the camera (by
adjusting the :attr:`analog_gain` and :attr:`digital_gain`). Valid
values are between 0 (auto) and 1600. The actual value used when iso is
explicitly set will be one of the following values (whichever is
closest): 100, 200, 320, 400, 500, 640, 800.
On the V1 camera module, non-zero ISO values attempt to fix overall
gain at various levels. For example, ISO 100 attempts to provide an
overall gain of 1.0, ISO 200 attempts to provide overall gain of 2.0,
etc. The algorithm prefers analog gain over digital gain to reduce
noise.
On the V2 camera module, ISO 100 attempts to produce overall gain of
~1.84, and ISO 800 attempts to produce overall gain of ~14.72 (the V2
camera module was calibrated against the `ISO film speed`_ standard).
The attribute can be adjusted while previews or recordings are in
progress. The default value is 0 which means automatically determine a
value according to image-taking conditions.
.. note::
Some users on the Pi camera forum have noted that higher ISO values
than 800 (specifically up to 1600) can be achieved in certain
conditions with :attr:`exposure_mode` set to ``'sports'`` and
:attr:`iso` set to 0. It doesn't appear to be possible to manually
request an ISO setting higher than 800, but the picamera library
will permit settings up to 1600 in case the underlying firmware
permits such settings in particular circumstances.
.. note::
Certain :attr:`exposure_mode` values override the ISO setting. For
example, ``'off'`` fixes :attr:`analog_gain` and
:attr:`digital_gain` entirely, preventing this property from
adjusting them when set.
.. _sensitivity of the camera to light: https://en.wikipedia.org/wiki/Film_speed#Digital
.. _ISO film speed: https://en.wikipedia.org/wiki/Film_speed#Current_system:_ISO
""")
def _get_meter_mode(self):
self._check_camera_open()
return self._METER_MODES_R[
self._camera.control.params[mmal.MMAL_PARAMETER_EXP_METERING_MODE].value
]
def _set_meter_mode(self, value):
self._check_camera_open()
try:
mp = self._camera.control.params[mmal.MMAL_PARAMETER_EXP_METERING_MODE]
mp.value = self.METER_MODES[value]
except KeyError:
raise PiCameraValueError("Invalid metering mode: %s" % value)
self._camera.control.params[mmal.MMAL_PARAMETER_EXP_METERING_MODE] = mp
meter_mode = property(_get_meter_mode, _set_meter_mode, doc="""\
Retrieves or sets the metering mode of the camera.
When queried, the :attr:`meter_mode` property returns the method by
which the camera `determines the exposure`_ as one of the following
strings:
{values}
When set, the property adjusts the camera's metering mode. All modes
set up two regions: a center region, and an outer region. The major
`difference between each mode`_ is the size of the center region. The
``'backlit'`` mode has the largest central region (30% of the width),
while ``'spot'`` has the smallest (10% of the width).
The property can be set while recordings or previews are in progress.
The default value is ``'average'``. All possible values for the
attribute can be obtained from the ``PiCamera.METER_MODES`` attribute.
.. _determines the exposure: https://en.wikipedia.org/wiki/Metering_mode
.. _difference between each mode: https://www.raspberrypi.org/forums/viewtopic.php?p=565644#p565644
""".format(values=docstring_values(METER_MODES)))
def _get_video_stabilization(self):
self._check_camera_open()
return self._camera.control.params[mmal.MMAL_PARAMETER_VIDEO_STABILISATION]
def _set_video_stabilization(self, value):
self._check_camera_open()
self._camera.control.params[mmal.MMAL_PARAMETER_VIDEO_STABILISATION] = value
video_stabilization = property(
_get_video_stabilization, _set_video_stabilization, doc="""\
Retrieves or sets the video stabilization mode of the camera.
When queried, the :attr:`video_stabilization` property returns a
boolean value indicating whether or not the camera attempts to
compensate for motion.
When set, the property activates or deactivates video stabilization.
The property can be set while recordings or previews are in progress.
The default value is ``False``.
.. note::
The built-in video stabilization only accounts for `vertical and
horizontal motion`_, not rotation.
.. _vertical and horizontal motion: https://www.raspberrypi.org/forums/viewtopic.php?p=342667&sid=ec7d95e887ab74a90ffaab87888c48cd#p342667
""")
def _get_exposure_compensation(self):
self._check_camera_open()
return self._camera.control.params[mmal.MMAL_PARAMETER_EXPOSURE_COMP]
def _set_exposure_compensation(self, value):
self._check_camera_open()
try:
if not (-25 <= value <= 25):
raise PiCameraValueError(
"Invalid exposure compensation value: "
"%d (valid range -25..25)" % value)
except TypeError:
raise PiCameraValueError(
"Invalid exposure compensation value: %s" % value)
self._camera.control.params[mmal.MMAL_PARAMETER_EXPOSURE_COMP] = value
exposure_compensation = property(
_get_exposure_compensation, _set_exposure_compensation, doc="""\
Retrieves or sets the exposure compensation level of the camera.
When queried, the :attr:`exposure_compensation` property returns an
integer value between -25 and 25 indicating the exposure level of the
camera. Larger values result in brighter images.
When set, the property adjusts the camera's exposure compensation
level. Each increment represents 1/6th of a stop. Hence setting the
attribute to 6 increases exposure by 1 stop. The property can be set
while recordings or previews are in progress. The default value is 0.
""")
def _get_exposure_mode(self):
self._check_camera_open()
return self._EXPOSURE_MODES_R[
self._camera.control.params[mmal.MMAL_PARAMETER_EXPOSURE_MODE].value
]
def _set_exposure_mode(self, value):
self._check_camera_open()
try:
mp = self._camera.control.params[mmal.MMAL_PARAMETER_EXPOSURE_MODE]
mp.value = self.EXPOSURE_MODES[value]
except KeyError:
raise PiCameraValueError("Invalid exposure mode: %s" % value)
self._camera.control.params[mmal.MMAL_PARAMETER_EXPOSURE_MODE] = mp
exposure_mode = property(_get_exposure_mode, _set_exposure_mode, doc="""\
Retrieves or sets the exposure mode of the camera.
When queried, the :attr:`exposure_mode` property returns a string
representing the exposure setting of the camera. The possible values
can be obtained from the ``PiCamera.EXPOSURE_MODES`` attribute, and
are as follows:
{values}
When set, the property adjusts the camera's exposure mode. The
property can be set while recordings or previews are in progress. The
default value is ``'auto'``.
.. note::
Exposure mode ``'off'`` is special: this disables the camera's
automatic gain control, fixing the values of :attr:`digital_gain`
and :attr:`analog_gain`.
Please note that these properties are not directly settable
(although they can be influenced by setting :attr:`iso` *prior* to
fixing the gains), and default to low values when the camera is
first initialized. Therefore it is important to let them settle on
higher values before disabling automatic gain control otherwise all
frames captured will appear black.
""".format(values=docstring_values(EXPOSURE_MODES)))
def _get_flash_mode(self):
self._check_camera_open()
return self._FLASH_MODES_R[
self._camera.control.params[mmal.MMAL_PARAMETER_FLASH].value
]
def _set_flash_mode(self, value):
self._check_camera_open()
try:
mp = self._camera.control.params[mmal.MMAL_PARAMETER_FLASH]
mp.value = self.FLASH_MODES[value]
except KeyError:
raise PiCameraValueError("Invalid flash mode: %s" % value)
self._camera.control.params[mmal.MMAL_PARAMETER_FLASH] = mp
flash_mode = property(_get_flash_mode, _set_flash_mode, doc="""\
Retrieves or sets the flash mode of the camera.
When queried, the :attr:`flash_mode` property returns a string
representing the flash setting of the camera. The possible values can
be obtained from the ``PiCamera.FLASH_MODES`` attribute, and are as
follows:
{values}
When set, the property adjusts the camera's flash mode. The property
can be set while recordings or previews are in progress. The default
value is ``'off'``.
.. note::
You must define which GPIO pins the camera is to use for flash and
privacy indicators. This is done within the `Device Tree
configuration`_ which is considered an advanced topic.
Specifically, you need to define pins ``FLASH_0_ENABLE`` and
optionally ``FLASH_0_INDICATOR`` (for the privacy indicator). More
information can be found in this :ref:`recipe
<flash_configuration>`.
.. _Device Tree configuration: https://www.raspberrypi.org/documentation/configuration/pin-configuration.md
.. versionadded:: 1.10
""".format(values=docstring_values(FLASH_MODES)))
def _get_awb_mode(self):
self._check_camera_open()
return self._AWB_MODES_R[
self._camera.control.params[mmal.MMAL_PARAMETER_AWB_MODE].value
]
def _set_awb_mode(self, value):
self._check_camera_open()
try:
mp = self._camera.control.params[mmal.MMAL_PARAMETER_AWB_MODE]
mp.value = self.AWB_MODES[value]
except KeyError:
raise PiCameraValueError("Invalid auto-white-balance mode: %s" % value)
self._camera.control.params[mmal.MMAL_PARAMETER_AWB_MODE] = mp
awb_mode = property(_get_awb_mode, _set_awb_mode, doc="""\
Retrieves or sets the auto-white-balance mode of the camera.
When queried, the :attr:`awb_mode` property returns a string
representing the auto white balance setting of the camera. The possible
values can be obtained from the ``PiCamera.AWB_MODES`` attribute, and
are as follows:
{values}
When set, the property adjusts the camera's auto-white-balance mode.
The property can be set while recordings or previews are in progress.
The default value is ``'auto'``.
.. note::
AWB mode ``'off'`` is special: this disables the camera's automatic
white balance permitting manual control of the white balance via
the :attr:`awb_gains` property. However, even with AWB disabled,
some attributes (specifically :attr:`still_stats` and
:attr:`drc_strength`) can cause AWB re-calculations.
""".format(values=docstring_values(AWB_MODES)))
def _get_awb_gains(self):
self._check_camera_open()
mp = self._camera.control.params[mmal.MMAL_PARAMETER_CAMERA_SETTINGS]
return (
mo.to_fraction(mp.awb_red_gain),
mo.to_fraction(mp.awb_blue_gain),
)
def _set_awb_gains(self, value):
self._check_camera_open()
try:
red_gain, blue_gain = value
except (ValueError, TypeError):
red_gain = blue_gain = value
if not (0.0 <= red_gain <= 8.0 and 0.0 <= blue_gain <= 8.0):
raise PiCameraValueError(
"Invalid gain(s) in (%f, %f) (valid range: 0.0-8.0)" % (
red_gain, blue_gain))
mp = mmal.MMAL_PARAMETER_AWB_GAINS_T(
mmal.MMAL_PARAMETER_HEADER_T(
mmal.MMAL_PARAMETER_CUSTOM_AWB_GAINS,
ct.sizeof(mmal.MMAL_PARAMETER_AWB_GAINS_T)
),
mo.to_rational(red_gain),
mo.to_rational(blue_gain),
)
self._camera.control.params[mmal.MMAL_PARAMETER_CUSTOM_AWB_GAINS] = mp
awb_gains = property(_get_awb_gains, _set_awb_gains, doc="""\
Gets or sets the auto-white-balance gains of the camera.
When queried, this attribute returns a tuple of values representing
the `(red, blue)` balance of the camera. The `red` and `blue` values
are returned :class:`~fractions.Fraction` instances. The values will
be between 0.0 and 8.0.
When set, this attribute adjusts the camera's auto-white-balance gains.
The property can be specified as a single value in which case both red
and blue gains will be adjusted equally, or as a `(red, blue)` tuple.
Values can be specified as an :ref:`int <typesnumeric>`, :ref:`float
<typesnumeric>` or :class:`~fractions.Fraction` and each gain must be
between 0.0 and 8.0. Typical values for the gains are between 0.9 and
1.9. The property can be set while recordings or previews are in
progress.
.. note::
This attribute only has an effect when :attr:`awb_mode` is set to
``'off'``. Also note that even with AWB disabled, some attributes
(specifically :attr:`still_stats` and :attr:`drc_strength`) can
cause AWB re-calculations.
.. versionchanged:: 1.6
Prior to version 1.6, this attribute was write-only.
""")
def _get_image_effect(self):
self._check_camera_open()
return self._IMAGE_EFFECTS_R[
self._camera.control.params[mmal.MMAL_PARAMETER_IMAGE_EFFECT].value
]
def _set_image_effect(self, value):
self._check_camera_open()
try:
mp = self._camera.control.params[mmal.MMAL_PARAMETER_IMAGE_EFFECT]
mp.value = self.IMAGE_EFFECTS[value]
self._image_effect_params = None
except KeyError:
raise PiCameraValueError("Invalid image effect: %s" % value)
self._camera.control.params[mmal.MMAL_PARAMETER_IMAGE_EFFECT] = mp
image_effect = property(_get_image_effect, _set_image_effect, doc="""\
Retrieves or sets the current image effect applied by the camera.
When queried, the :attr:`image_effect` property returns a string
representing the effect the camera will apply to captured video. The
possible values can be obtained from the ``PiCamera.IMAGE_EFFECTS``
attribute, and are as follows:
{values}
When set, the property changes the effect applied by the camera. The
property can be set while recordings or previews are in progress, but
only certain effects work while recording video (notably ``'negative'``
and ``'solarize'``). The default value is ``'none'``.
""".format(values=docstring_values(IMAGE_EFFECTS)))
def _get_image_effect_params(self):
self._check_camera_open()
return self._image_effect_params
def _set_image_effect_params(self, value):
self._check_camera_open()
to_int = lambda x: int(x)
to_byte = lambda x: max(0, min(255, int(x)))
to_bool = lambda x: (0, 1)[bool(x)]
to_8dot8 = lambda x: int(x * 256)
valid_transforms = {
'solarize': [
(to_bool, to_byte, to_byte, to_byte, to_byte),
(to_byte, to_byte, to_byte, to_byte),
(to_bool,),
],
'colorpoint': [
(lambda x: max(0, min(3, int(x))),),
],
'colorbalance': [
(to_8dot8, to_8dot8, to_8dot8, to_8dot8, to_int, to_int),
(to_8dot8, to_8dot8, to_8dot8, to_8dot8),
(to_8dot8, to_8dot8, to_8dot8),
],
'colorswap': [
(to_bool,),
],
'posterise': [
(lambda x: max(2, min(31, int(x))),),
],
'blur': [
(lambda x: max(1, min(2, int(x))),),
],
'film': [
(to_byte, to_byte, to_byte),
],
'watercolor': [
(),
(to_byte, to_byte),
]
}
# Ensure params is a tuple
try:
params = tuple(i for i in value)
except TypeError:
params = (value,)
# Find the parameter combination for the current effect
effect = self.image_effect
param_transforms = [
transforms for transforms in valid_transforms.get(effect, [])
if len(transforms) == len(params)
]
if not param_transforms:
raise PiCameraValueError(
'invalid set of parameters for effect "%s"' % effect)
param_transforms = param_transforms[0]
params = tuple(
transform(p)
for (transform, p) in zip(param_transforms, params)
)
mp = mmal.MMAL_PARAMETER_IMAGEFX_PARAMETERS_T(
mmal.MMAL_PARAMETER_HEADER_T(
mmal.MMAL_PARAMETER_IMAGE_EFFECT_PARAMETERS,
ct.sizeof(mmal.MMAL_PARAMETER_IMAGEFX_PARAMETERS_T)
),
effect=self.IMAGE_EFFECTS[effect],
num_effect_params=len(params),
effect_parameter=params,
)
self._camera.control.params[mmal.MMAL_PARAMETER_IMAGE_EFFECT_PARAMETERS] = mp
self._image_effect_params = value
image_effect_params = property(
_get_image_effect_params, _set_image_effect_params, doc="""\
Retrieves or sets the parameters for the current :attr:`effect
<image_effect>`.
When queried, the :attr:`image_effect_params` property either returns
``None`` (for effects which have no configurable parameters, or if no
parameters have been configured), or a tuple of numeric values up to
six elements long.
When set, the property changes the parameters of the current
:attr:`effect <image_effect>` as a sequence of numbers, or a single
number. Attempting to set parameters on an effect which does not
support parameters, or providing an incompatible set of parameters for
an effect will raise a :exc:`PiCameraValueError` exception.
The effects which have parameters, and what combinations those
parameters can take is as follows:
.. tabularcolumns:: |p{30mm}|p{25mm}|p{75mm}|
+--------------------+----------------+-----------------------------------------+
| Effect | Parameters | Description |
+====================+================+=========================================+
| ``'solarize'`` | *yuv*, | *yuv* controls whether data is |
| | *x0*, *y1*, | processed as RGB (0) or YUV(1). Input |
| | *y2*, *y3* | values from 0 to *x0* - 1 are remapped |
| | | linearly onto the range 0 to *y0*. |
| | | Values from *x0* to 255 are remapped |
| | | linearly onto the range *y1* to *y2*. |
| +----------------+-----------------------------------------+
| | *x0*, *y0*, | Same as above, but *yuv* defaults to |
| | *y1*, *y2* | 0 (process as RGB). |
| +----------------+-----------------------------------------+
| | *yuv* | Same as above, but *x0*, *y0*, *y1*, |
| | | *y2* default to 128, 128, 128, 0 |
| | | respectively. |
+--------------------+----------------+-----------------------------------------+
| ``'colorpoint'`` | *quadrant* | *quadrant* specifies which quadrant |
| | | of the U/V space to retain chroma |
| | | from: 0=green, 1=red/yellow, 2=blue, |
| | | 3=purple. There is no default; this |
| | | effect does nothing until parameters |
| | | are set. |
+--------------------+----------------+-----------------------------------------+
| ``'colorbalance'`` | *lens*, | *lens* specifies the lens shading |
| | *r*, *g*, *b*, | strength (0.0 to 256.0, where 0.0 |
| | *u*, *v* | indicates lens shading has no effect). |
| | | *r*, *g*, *b* are multipliers for their |
| | | respective color channels (0.0 to |
| | | 256.0). *u* and *v* are offsets added |
| | | to the U/V plane (0 to 255). |
| +----------------+-----------------------------------------+
| | *lens*, | Same as above but *u* are defaulted |
| | *r*, *g*, *b* | to 0. |
| +----------------+-----------------------------------------+
| | *lens*, | Same as above but *g* also defaults to |
| | *r*, *b* | to 1.0. |
+--------------------+----------------+-----------------------------------------+
| ``'colorswap'`` | *dir* | If *dir* is 0, swap RGB to BGR. If |
| | | *dir* is 1, swap RGB to BRG. |
+--------------------+----------------+-----------------------------------------+
| ``'posterise'`` | *steps* | Control the quantization steps for the |
| | | image. Valid values are 2 to 32, and |
| | | the default is 4. |
+--------------------+----------------+-----------------------------------------+
| ``'blur'`` | *size* | Specifies the size of the kernel. Valid |
| | | values are 1 or 2. |
+--------------------+----------------+-----------------------------------------+
| ``'film'`` | *strength*, | *strength* specifies the strength of |
| | *u*, *v* | effect. *u* and *v* are offsets added |
| | | to the U/V plane (0 to 255). |
+--------------------+----------------+-----------------------------------------+
| ``'watercolor'`` | *u*, *v* | *u* and *v* specify offsets to add to |
| | | the U/V plane (0 to 255). |
| +----------------+-----------------------------------------+
| | | No parameters indicates no U/V effect. |
+--------------------+----------------+-----------------------------------------+
.. versionadded:: 1.8
""")
def _get_color_effects(self):
self._check_camera_open()
mp = self._camera.control.params[mmal.MMAL_PARAMETER_COLOUR_EFFECT]
if mp.enable != mmal.MMAL_FALSE:
return (mp.u, mp.v)
else:
return None
def _set_color_effects(self, value):
self._check_camera_open()
if value is None:
enable = mmal.MMAL_FALSE
u = v = 128
else:
enable = mmal.MMAL_TRUE
try:
u, v = value
except (TypeError, ValueError) as e:
raise PiCameraValueError(
"Invalid color effect (u, v) tuple: %s" % value)
if not ((0 <= u <= 255) and (0 <= v <= 255)):
raise PiCameraValueError(
"(u, v) values must be between 0 and 255")
mp = mmal.MMAL_PARAMETER_COLOURFX_T(
mmal.MMAL_PARAMETER_HEADER_T(
mmal.MMAL_PARAMETER_COLOUR_EFFECT,
ct.sizeof(mmal.MMAL_PARAMETER_COLOURFX_T)
),
enable, u, v
)
self._camera.control.params[mmal.MMAL_PARAMETER_COLOUR_EFFECT] = mp
color_effects = property(_get_color_effects, _set_color_effects, doc="""\
Retrieves or sets the current color effect applied by the camera.
When queried, the :attr:`color_effects` property either returns
``None`` which indicates that the camera is using normal color
settings, or a ``(u, v)`` tuple where ``u`` and ``v`` are integer
values between 0 and 255.
When set, the property changes the color effect applied by the camera.
The property can be set while recordings or previews are in progress.
For example, to make the image black and white set the value to ``(128,
128)``. The default value is ``None``.
""")
def _get_rotation(self):
self._check_camera_open()
return self._camera.outputs[0].params[mmal.MMAL_PARAMETER_ROTATION]
def _set_rotation(self, value):
self._check_camera_open()
try:
value = ((int(value) % 360) // 90) * 90
except ValueError:
raise PiCameraValueError("Invalid rotation angle: %s" % value)
for port in self._camera.outputs:
port.params[mmal.MMAL_PARAMETER_ROTATION] = value
rotation = property(_get_rotation, _set_rotation, doc="""\
Retrieves or sets the current rotation of the camera's image.
When queried, the :attr:`rotation` property returns the rotation
applied to the image. Valid values are 0, 90, 180, and 270.
When set, the property changes the rotation applied to the camera's
input. The property can be set while recordings or previews are in
progress. The default value is ``0``.
""")
def _get_vflip(self):
self._check_camera_open()
return self._camera.outputs[0].params[mmal.MMAL_PARAMETER_MIRROR] in (
mmal.MMAL_PARAM_MIRROR_VERTICAL, mmal.MMAL_PARAM_MIRROR_BOTH)
def _set_vflip(self, value):
self._check_camera_open()
value = {
(False, False): mmal.MMAL_PARAM_MIRROR_NONE,
(True, False): mmal.MMAL_PARAM_MIRROR_VERTICAL,
(False, True): mmal.MMAL_PARAM_MIRROR_HORIZONTAL,
(True, True): mmal.MMAL_PARAM_MIRROR_BOTH,
}[(bool(value), self.hflip)]
for port in self._camera.outputs:
port.params[mmal.MMAL_PARAMETER_MIRROR] = value
vflip = property(_get_vflip, _set_vflip, doc="""\
Retrieves or sets whether the camera's output is vertically flipped.
When queried, the :attr:`vflip` property returns a boolean indicating
whether or not the camera's output is vertically flipped. The property
can be set while recordings or previews are in progress. The default
value is ``False``.
""")
def _get_hflip(self):
self._check_camera_open()
return self._camera.outputs[0].params[mmal.MMAL_PARAMETER_MIRROR] in (
mmal.MMAL_PARAM_MIRROR_HORIZONTAL, mmal.MMAL_PARAM_MIRROR_BOTH)
def _set_hflip(self, value):
self._check_camera_open()
value = {
(False, False): mmal.MMAL_PARAM_MIRROR_NONE,
(True, False): mmal.MMAL_PARAM_MIRROR_VERTICAL,
(False, True): mmal.MMAL_PARAM_MIRROR_HORIZONTAL,
(True, True): mmal.MMAL_PARAM_MIRROR_BOTH,
}[(self.vflip, bool(value))]
for port in self._camera.outputs:
port.params[mmal.MMAL_PARAMETER_MIRROR] = value
hflip = property(_get_hflip, _set_hflip, doc="""\
Retrieves or sets whether the camera's output is horizontally flipped.
When queried, the :attr:`hflip` property returns a boolean indicating
whether or not the camera's output is horizontally flipped. The
property can be set while recordings or previews are in progress. The
default value is ``False``.
""")
def _get_zoom(self):
self._check_camera_open()
mp = self._camera.control.params[mmal.MMAL_PARAMETER_INPUT_CROP]
return (
mp.rect.x / 65535.0,
mp.rect.y / 65535.0,
mp.rect.width / 65535.0,
mp.rect.height / 65535.0,
)
def _set_zoom(self, value):
self._check_camera_open()
try:
x, y, w, h = value
except (TypeError, ValueError) as e:
raise PiCameraValueError(
"Invalid zoom rectangle (x, y, w, h) tuple: %s" % value)
mp = mmal.MMAL_PARAMETER_INPUT_CROP_T(
mmal.MMAL_PARAMETER_HEADER_T(
mmal.MMAL_PARAMETER_INPUT_CROP,
ct.sizeof(mmal.MMAL_PARAMETER_INPUT_CROP_T)
),
mmal.MMAL_RECT_T(
max(0, min(65535, int(65535 * x))),
max(0, min(65535, int(65535 * y))),
max(0, min(65535, int(65535 * w))),
max(0, min(65535, int(65535 * h))),
),
)
self._camera.control.params[mmal.MMAL_PARAMETER_INPUT_CROP] = mp
zoom = property(_get_zoom, _set_zoom, doc="""\
Retrieves or sets the zoom applied to the camera's input.
When queried, the :attr:`zoom` property returns a ``(x, y, w, h)``
tuple of floating point values ranging from 0.0 to 1.0, indicating the
proportion of the image to include in the output (this is also known as
the "Region of Interest" or ROI). The default value is ``(0.0, 0.0,
1.0, 1.0)`` which indicates that everything should be included. The
property can be set while recordings or previews are in progress.
The `zoom` is applied to the processed image, after rotation and rescale.
If rotation has been used, zoom is composed of ``(y, x, h, w)`` instead.
The values `w` and `h` can modify the aspect ratio of the image: use equal
values for `w` and `h` if you want to keep the same the aspect ratio.
""")
def _get_crop(self):
warnings.warn(
PiCameraDeprecated(
'PiCamera.crop is deprecated; use PiCamera.zoom instead'))
return self.zoom
def _set_crop(self, value):
warnings.warn(
PiCameraDeprecated(
'PiCamera.crop is deprecated; use PiCamera.zoom instead'))
self.zoom = value
crop = property(_get_crop, _set_crop, doc="""
Retrieves or sets the zoom applied to the camera's input.
.. deprecated:: 1.8
Please use the :attr:`zoom` attribute instead.
""")
def _get_overlays(self):
self._check_camera_open()
return self._overlays
overlays = property(_get_overlays, doc="""\
Retrieves all active :class:`PiRenderer` overlays.
If no overlays are current active, :attr:`overlays` will return an
empty iterable. Otherwise, it will return an iterable of
:class:`PiRenderer` instances which are currently acting as overlays.
Note that the preview renderer is an exception to this: it is *not*
included as an overlay despite being derived from :class:`PiRenderer`.
.. versionadded:: 1.8
""")
def _get_preview(self):
self._check_camera_open()
if isinstance(self._preview, PiPreviewRenderer):
return self._preview
preview = property(_get_preview, doc="""\
Retrieves the :class:`PiRenderer` displaying the camera preview.
If no preview is currently active, :attr:`preview` will return
``None``. Otherwise, it will return the instance of
:class:`PiRenderer` which is currently connected to the camera's
preview port for rendering what the camera sees. You can use the
attributes of the :class:`PiRenderer` class to configure the appearance
of the preview. For example, to make the preview semi-transparent::
import picamera
with picamera.PiCamera() as camera:
camera.start_preview()
camera.preview.alpha = 128
.. versionadded:: 1.8
""")
def _get_preview_alpha(self):
self._check_camera_open()
warnings.warn(
PiCameraDeprecated(
'PiCamera.preview_alpha is deprecated; use '
'PiCamera.preview.alpha instead'))
if self.preview:
return self.preview.alpha
else:
return self._preview_alpha
def _set_preview_alpha(self, value):
self._check_camera_open()
warnings.warn(
PiCameraDeprecated(
'PiCamera.preview_alpha is deprecated; use '
'PiCamera.preview.alpha instead'))
if self.preview:
self.preview.alpha = value
else:
self._preview_alpha = value
preview_alpha = property(_get_preview_alpha, _set_preview_alpha, doc="""\
Retrieves or sets the opacity of the preview window.
.. deprecated:: 1.8
Please use the :attr:`~PiRenderer.alpha` attribute of the
:attr:`preview` object instead.
""")
def _get_preview_layer(self):
self._check_camera_open()
warnings.warn(
PiCameraDeprecated(
'PiCamera.preview_layer is deprecated; '
'use PiCamera.preview.layer instead'))
if self.preview:
return self.preview.layer
else:
return self._preview_layer
def _set_preview_layer(self, value):
self._check_camera_open()
warnings.warn(
PiCameraDeprecated(
'PiCamera.preview_layer is deprecated; '
'use PiCamera.preview.layer instead'))
if self.preview:
self.preview.layer = value
else:
self._preview_layer = value
preview_layer = property(_get_preview_layer, _set_preview_layer, doc="""\
Retrieves or sets the layer of the preview window.
.. deprecated:: 1.8
Please use the :attr:`~PiRenderer.layer` attribute of the
:attr:`preview` object instead.
""")
def _get_preview_fullscreen(self):
self._check_camera_open()
warnings.warn(
PiCameraDeprecated(
'PiCamera.preview_fullscreen is deprecated; '
'use PiCamera.preview.fullscreen instead'))
if self.preview:
return self.preview.fullscreen
else:
return self._preview_fullscreen
def _set_preview_fullscreen(self, value):
self._check_camera_open()
warnings.warn(
PiCameraDeprecated(
'PiCamera.preview_fullscreen is deprecated; '
'use PiCamera.preview.fullscreen instead'))
if self.preview:
self.preview.fullscreen = value
else:
self._preview_fullscreen = value
preview_fullscreen = property(
_get_preview_fullscreen, _set_preview_fullscreen, doc="""\
Retrieves or sets full-screen for the preview window.
.. deprecated:: 1.8
Please use the :attr:`~PiRenderer.fullscreen` attribute of the
:attr:`preview` object instead.
""")
def _get_preview_window(self):
self._check_camera_open()
warnings.warn(
PiCameraDeprecated(
'PiCamera.preview_window is deprecated; '
'use PiCamera.preview.window instead'))
if self.preview:
return self.preview.window
else:
return self._preview_window
def _set_preview_window(self, value):
self._check_camera_open()
warnings.warn(
PiCameraDeprecated(
'PiCamera.preview_window is deprecated; '
'use PiCamera.preview.window instead'))
if self.preview:
self.preview.window = value
else:
self._preview_window = value
preview_window = property(
_get_preview_window, _set_preview_window, doc="""\
Retrieves or sets the size of the preview window.
.. deprecated:: 1.8
Please use the :attr:`~PiRenderer.window` attribute of the
:attr:`preview` object instead.
""")
def _get_annotate_text(self):
self._check_camera_open()
mp = self._camera.control.params[mmal.MMAL_PARAMETER_ANNOTATE]
if mp.enable:
return mp.text.decode('ascii')
else:
return ''
def _set_annotate_text(self, value):
self._check_camera_open()
mp = self._camera.control.params[mmal.MMAL_PARAMETER_ANNOTATE]
mp.enable = bool(value or mp.show_frame_num)
if mp.enable:
try:
mp.text = value.encode('ascii')
except ValueError as e:
raise PiCameraValueError(str(e))
self._camera.control.params[mmal.MMAL_PARAMETER_ANNOTATE] = mp
annotate_text = property(_get_annotate_text, _set_annotate_text, doc="""\
Retrieves or sets a text annotation for all output.
When queried, the :attr:`annotate_text` property returns the current
annotation (if no annotation has been set, this is simply a blank
string).
When set, the property immediately applies the annotation to the
preview (if it is running) and to any future captures or video
recording. Strings longer than 255 characters, or strings containing
non-ASCII characters will raise a :exc:`PiCameraValueError`. The
default value is ``''``.
.. versionchanged:: 1.8
Text annotations can now be 255 characters long. The prior limit
was 32 characters.
""")
def _get_annotate_frame_num(self):
self._check_camera_open()
mp = self._camera.control.params[mmal.MMAL_PARAMETER_ANNOTATE]
return mp.show_frame_num.value != mmal.MMAL_FALSE
def _set_annotate_frame_num(self, value):
self._check_camera_open()
mp = self._camera.control.params[mmal.MMAL_PARAMETER_ANNOTATE]
mp.enable = bool(value or mp.text)
mp.show_frame_num = bool(value)
self._camera.control.params[mmal.MMAL_PARAMETER_ANNOTATE] = mp
annotate_frame_num = property(
_get_annotate_frame_num, _set_annotate_frame_num, doc="""\
Controls whether the current frame number is drawn as an annotation.
The :attr:`annotate_frame_num` attribute is a bool indicating whether
or not the current frame number is rendered as an annotation, similar
to :attr:`annotate_text`. The default is ``False``.
.. versionadded:: 1.8
""")
def _get_annotate_text_size(self):
self._check_camera_open()
if self._camera.annotate_rev == 3:
mp = self._camera.control.params[mmal.MMAL_PARAMETER_ANNOTATE]
return mp.text_size or self.DEFAULT_ANNOTATE_SIZE
else:
return self.DEFAULT_ANNOTATE_SIZE
def _set_annotate_text_size(self, value):
self._check_camera_open()
if not (6 <= value <= 160):
raise PiCameraValueError(
"Invalid annotation text size: %d (valid range 6-160)" % value)
if self._camera.annotate_rev == 3:
mp = self._camera.control.params[mmal.MMAL_PARAMETER_ANNOTATE]
mp.text_size = value
self._camera.control.params[mmal.MMAL_PARAMETER_ANNOTATE] = mp
elif value != self.DEFAULT_ANNOTATE_SIZE:
warnings.warn(
PiCameraFallback(
"Firmware does not support setting annotation text "
"size; using default (%d) instead" % self.DEFAULT_ANNOTATE_SIZE))
annotate_text_size = property(
_get_annotate_text_size, _set_annotate_text_size, doc="""\
Controls the size of the annotation text.
The :attr:`annotate_text_size` attribute is an int which determines how
large the annotation text will appear on the display. Valid values are
in the range 6 to 160, inclusive. The default is {size}.
.. versionadded:: 1.10
""".format(size=DEFAULT_ANNOTATE_SIZE))
def _get_annotate_foreground(self):
self._check_camera_open()
mp = self._camera.control.params[mmal.MMAL_PARAMETER_ANNOTATE]
if self._camera.annotate_rev == 3 and mp.custom_text_color:
return Color.from_yuv_bytes(
mp.custom_text_Y,
mp.custom_text_U,
mp.custom_text_V)
else:
return Color('white')
def _set_annotate_foreground(self, value):
self._check_camera_open()
if not isinstance(value, Color):
raise PiCameraValueError(
'annotate_foreground must be a Color')
elif self._camera.annotate_rev < 3:
if value.rgb_bytes != (255, 255, 255):
warnings.warn(
PiCameraFallback(
"Firmware does not support setting a custom foreground "
"annotation color; using white instead"))
return
mp = self._camera.control.params[mmal.MMAL_PARAMETER_ANNOTATE]
mp.custom_text_color = True
(
mp.custom_text_Y,
mp.custom_text_U,
mp.custom_text_V,
) = value.yuv_bytes
self._camera.control.params[mmal.MMAL_PARAMETER_ANNOTATE] = mp
annotate_foreground = property(
_get_annotate_foreground, _set_annotate_foreground, doc="""\
Controls the color of the annotation text.
The :attr:`annotate_foreground` attribute specifies, partially, the
color of the annotation text. The value is specified as a
:class:`Color`. The default is white.
.. note::
The underlying firmware does not directly support setting all
components of the text color, only the Y' component of a `Y'UV`_
tuple. This is roughly (but not precisely) analogous to the
"brightness" of a color, so you may choose to think of this as
setting how bright the annotation text will be relative to its
background. In order to specify just the Y' component when setting
this attribute, you may choose to construct the
:class:`Color` instance as follows::
camera.annotate_foreground = picamera.Color(y=0.2, u=0, v=0)
.. _Y'UV: https://en.wikipedia.org/wiki/YUV
.. versionadded:: 1.10
""")
def _get_annotate_background(self):
self._check_camera_open()
mp = self._camera.control.params[mmal.MMAL_PARAMETER_ANNOTATE]
if self._camera.annotate_rev == 3:
if mp.enable_text_background:
if mp.custom_background_color:
return Color.from_yuv_bytes(
mp.custom_background_Y,
mp.custom_background_U,
mp.custom_background_V)
else:
return Color('black')
else:
return None
else:
if mp.black_text_background:
return Color('black')
else:
return None
def _set_annotate_background(self, value):
self._check_camera_open()
if value is True:
warnings.warn(
PiCameraDeprecated(
'Setting PiCamera.annotate_background to True is '
'deprecated; use PiCamera.color.Color("black") instead'))
value = Color('black')
elif value is False:
warnings.warn(
PiCameraDeprecated(
'Setting PiCamera.annotate_background to False is '
'deprecated; use None instead'))
value = None
elif value is None:
pass
elif not isinstance(value, Color):
raise PiCameraValueError(
'annotate_background must be a Color or None')
elif self._camera.annotate_rev < 3 and value.rgb_bytes != (0, 0, 0):
warnings.warn(
PiCameraFallback(
"Firmware does not support setting a custom background "
"annotation color; using black instead"))
mp = self._camera.control.params[mmal.MMAL_PARAMETER_ANNOTATE]
if self._camera.annotate_rev == 3:
if value is None:
mp.enable_text_background = False
else:
mp.enable_text_background = True
mp.custom_background_color = True
(
mp.custom_background_Y,
mp.custom_background_U,
mp.custom_background_V,
) = value.yuv_bytes
else:
if value is None:
mp.black_text_background = False
else:
mp.black_text_background = True
self._camera.control.params[mmal.MMAL_PARAMETER_ANNOTATE] = mp
annotate_background = property(
_get_annotate_background, _set_annotate_background, doc="""\
Controls what background is drawn behind the annotation.
The :attr:`annotate_background` attribute specifies if a background
will be drawn behind the :attr:`annotation text <annotate_text>` and,
if so, what color it will be. The value is specified as a
:class:`Color` or ``None`` if no background should be drawn. The
default is ``None``.
.. note::
For backward compatibility purposes, the value ``False`` will be
treated as ``None``, and the value ``True`` will be treated as the
color black. The "truthiness" of the values returned by the
attribute are backward compatible although the values themselves
are not.
.. versionadded:: 1.8
.. versionchanged:: 1.10
In prior versions this was a bool value with ``True`` representing
a black background.
""")
| picamera/camera.py | 174,185 | Provides a pure Python interface to the Raspberry Pi's camera module.
Upon construction, this class initializes the camera. The *camera_num*
parameter (which defaults to 0) selects the camera module that the instance
will represent. Only the Raspberry Pi compute module currently supports
more than one camera.
The *sensor_mode*, *resolution*, *framerate*, *framerate_range*, and
*clock_mode* parameters provide initial values for the :attr:`sensor_mode`,
:attr:`resolution`, :attr:`framerate`, :attr:`framerate_range`, and
:attr:`clock_mode` attributes of the class (these attributes are all
relatively expensive to set individually, hence setting them all upon
construction is a speed optimization). Please refer to the attribute
documentation for more information and default values.
The *stereo_mode* and *stereo_decimate* parameters configure dual cameras
on a compute module for sterescopic mode. These parameters can only be set
at construction time; they cannot be altered later without closing the
:class:`PiCamera` instance and recreating it. The *stereo_mode* parameter
defaults to ``'none'`` (no stereoscopic mode) but can be set to
``'side-by-side'`` or ``'top-bottom'`` to activate a stereoscopic mode. If
the *stereo_decimate* parameter is ``True``, the resolution of the two
cameras will be halved so that the resulting image has the same dimensions
as if stereoscopic mode were not being used.
The *led_pin* parameter can be used to specify the GPIO pin which should be
used to control the camera's LED via the :attr:`led` attribute. If this is
not specified, it should default to the correct value for your Pi platform.
You should only need to specify this parameter if you are using a custom
DeviceTree blob (this is only typical on the `Compute Module`_ platform).
No preview or recording is started automatically upon construction. Use
the :meth:`capture` method to capture images, the :meth:`start_recording`
method to begin recording video, or the :meth:`start_preview` method to
start live display of the camera's input.
Several attributes are provided to adjust the camera's configuration. Some
of these can be adjusted while a recording is running, like
:attr:`brightness`. Others, like :attr:`resolution`, can only be adjusted
when the camera is idle.
When you are finished with the camera, you should ensure you call the
:meth:`close` method to release the camera resources::
camera = PiCamera()
try:
# do something with the camera
pass
finally:
camera.close()
The class supports the context manager protocol to make this particularly
easy (upon exiting the :keyword:`with` statement, the :meth:`close` method
is automatically called)::
with PiCamera() as camera:
# do something with the camera
pass
.. versionchanged:: 1.8
Added *stereo_mode* and *stereo_decimate* parameters.
.. versionchanged:: 1.9
Added *resolution*, *framerate*, and *sensor_mode* parameters.
.. versionchanged:: 1.10
Added *led_pin* parameter.
.. versionchanged:: 1.11
Added *clock_mode* parameter, and permitted setting of resolution as
appropriately formatted string.
.. versionchanged:: 1.13
Added *framerate_range* parameter.
.. _Compute Module: https://www.raspberrypi.org/documentation/hardware/computemodule/cmio-camera.md
Singleton representing the maximum framerate of the camera module.
Singleton representing the maximum resolution of the camera module.
Raise an exception if the camera is already closed, or if the camera
has encountered a fatal error.
Raise an exception if the camera is currently recording.
An internal method for setting a new camera mode, framerate,
resolution, and/or clock_mode.
This method is used by the setters of the :attr:`resolution`,
:attr:`framerate`, and :attr:`sensor_mode` properties. It assumes the
camera is currently disabled. The *old_mode* and *new_mode* arguments
are required to ensure correct operation on older firmwares
(specifically that we don't try to set the sensor mode when both old
and new modes are 0 or automatic).
Ensures all splitter output ports have a sensible format (I420) and
buffer sizes.
This method is used to ensure the splitter configuration is sane,
typically after :meth:`_configure_camera` is called.
An internal method for disabling the camera, e.g. for re-configuration.
This disables the splitter and preview connections (if they exist).
An internal method for enabling the camera after re-configuration.
This ensures the splitter configuration is consistent, then re-enables
the camera along with the splitter and preview connections.
Construct an image encoder for the requested parameters.
This method is called by :meth:`capture` and :meth:`capture_continuous`
to construct an image encoder. The *camera_port* parameter gives the
MMAL camera port that should be enabled for capture by the encoder. The
*output_port* parameter gives the MMAL port that the encoder should
read output from (this may be the same as the camera port, but may be
different if other component(s) like a splitter have been placed in the
pipeline). The *format* parameter indicates the image format and will
be one of:
* ``'jpeg'``
* ``'png'``
* ``'gif'``
* ``'bmp'``
* ``'yuv'``
* ``'rgb'``
* ``'rgba'``
* ``'bgr'``
* ``'bgra'``
The *resize* parameter indicates the size that the encoder should
resize the output to (presumably by including a resizer in the
pipeline). Finally, *options* includes extra keyword arguments that
should be passed verbatim to the encoder.
Given an output object and an optional format, attempt to determine the
requested image format.
This method is used by all capture methods to determine the requested
output format. If *format* is specified as a MIME-type the "image/"
prefix is stripped. If *format* is not specified, then
:meth:`_get_output_format` will be called to attempt to determine
format from the *output* object.
Construct a multi-image encoder for the requested parameters.
This method is largely equivalent to :meth:`_get_image_encoder` with
the exception that the encoder returned should expect to be passed an
iterable of outputs to its :meth:`~PiEncoder.start` method, rather than
a single output object. This method is called by the
:meth:`capture_sequence` method.
All parameters are the same as in :meth:`_get_image_encoder`. Please
refer to the documentation for that method for further information.
Given an output object, attempt to determine the requested format.
We attempt to determine the filename of the *output* object and derive
a MIME type from the extension. If *output* has no filename, an error
is raised.
Determine the camera and output ports for given capture options.
See :ref:`camera_hardware` for more information on picamera's usage of
camera, splitter, and encoder ports. The general idea here is that the
capture (still) port operates on its own, while the video port is
always connected to a splitter component, so requests for a video port
also have to specify which splitter port they want to use.
Construct a video encoder for the requested parameters.
This method is called by :meth:`start_recording` and
:meth:`record_sequence` to construct a video encoder. The
*camera_port* parameter gives the MMAL camera port that should be
enabled for capture by the encoder. The *output_port* parameter gives
the MMAL port that the encoder should read output from (this may be the
same as the camera port, but may be different if other component(s)
like a splitter have been placed in the pipeline). The *format*
parameter indicates the video format and will be one of:
* ``'h264'``
* ``'mjpeg'``
The *resize* parameter indicates the size that the encoder should
resize the output to (presumably by including a resizer in the
pipeline). Finally, *options* includes extra keyword arguments that
should be passed verbatim to the encoder.
Given an output object and an optional format, attempt to determine the
requested video format.
This method is used by all recording methods to determine the requested
output format. If *format* is specified as a MIME-type the "video/" or
"application/" prefix will be stripped. If *format* is not specified,
then :meth:`_get_output_format` will be called to attempt to determine
format from the *output* object.
Adds a static overlay to the preview output.
This method creates a new static overlay using the same rendering
mechanism as the preview. Overlays will appear on the Pi's video
output, but will not appear in captures or video recordings. Multiple
overlays can exist; each call to :meth:`add_overlay` returns a new
:class:`PiOverlayRenderer` instance representing the overlay.
The *source* must be an object that supports the :ref:`buffer protocol
<bufferobjects>` in one of the supported unencoded formats: ``'yuv'``,
``'rgb'``, ``'rgba'``, ``'bgr'``, or ``'bgra'``. The format can
specified explicitly with the optional *format* parameter. If not
specified, the method will attempt to guess the format based on the
length of *source* and the *size* (assuming 3 bytes per pixel for RGB,
and 4 bytes for RGBA).
The optional *size* parameter specifies the size of the source image as
a ``(width, height)`` tuple. If this is omitted or ``None`` then the
size is assumed to be the same as the camera's current
:attr:`resolution`.
The length of *source* must take into account that widths are rounded
up to the nearest multiple of 32, and heights to the nearest multiple
of 16. For example, if *size* is ``(1280, 720)``, and *format* is
``'rgb'``, then *source* must be a buffer with length 1280 × 720 × 3
bytes, or 2,764,800 bytes (because 1280 is a multiple of 32, and 720 is
a multiple of 16 no extra rounding is required). However, if *size* is
``(97, 57)``, and *format* is ``'rgb'`` then *source* must be a buffer
with length 128 × 64 × 3 bytes, or 24,576 bytes (pixels beyond column
97 and row 57 in the source will be ignored).
New overlays default to *layer* 0, whilst the preview defaults to layer
2. Higher numbered layers obscure lower numbered layers, hence new
overlays will be invisible (if the preview is running) by default. You
can make the new overlay visible either by making any existing preview
transparent (with the :attr:`~PiRenderer.alpha` property) or by moving
the overlay into a layer higher than the preview (with the
:attr:`~PiRenderer.layer` property).
All keyword arguments captured in *options* are passed onto the
:class:`PiRenderer` constructor. All camera properties except
:attr:`resolution` and :attr:`framerate` can be modified while overlays
exist. The reason for these exceptions is that the overlay has a static
resolution and changing the camera's mode would require resizing of the
source.
.. warning::
If too many overlays are added, the display output will be disabled
and a reboot will generally be required to restore the display.
Overlays are composited "on the fly". Hence, a real-time constraint
exists wherein for each horizontal line of HDMI output, the content
of all source layers must be fetched, resized, converted, and
blended to produce the output pixels.
If enough overlays exist (where "enough" is a number dependent on
overlay size, display resolution, bus frequency, and several other
factors making it unrealistic to calculate in advance), this
process breaks down and video output fails. One solution is to add
``dispmanx_offline=1`` to ``/boot/config.txt`` to force the use of
an off-screen buffer. Be aware that this requires more GPU memory
and may reduce the update rate.
.. _RGB: https://en.wikipedia.org/wiki/RGB
.. _RGBA: https://en.wikipedia.org/wiki/RGBA_color_space
.. versionadded:: 1.8
.. versionchanged:: 1.13
Added *format* parameter
Capture an image from the camera, storing it in *output*.
If *output* is a string, it will be treated as a filename for a new
file which the image will be written to. If *output* is not a string,
but is an object with a ``write`` method, it is assumed to be a
file-like object and the image data is appended to it (the
implementation only assumes the object has a ``write`` method - no
other methods are required but ``flush`` will be called at the end of
capture if it is present). If *output* is not a string, and has no
``write`` method it is assumed to be a writeable object implementing
the buffer protocol. In this case, the image data will be written
directly to the underlying buffer (which must be large enough to accept
the image data).
If *format* is ``None`` (the default), the method will attempt to guess
the required image format from the extension of *output* (if it's a
string), or from the *name* attribute of *output* (if it has one). In
the case that the format cannot be determined, a
:exc:`PiCameraValueError` will be raised.
If *format* is not ``None``, it must be a string specifying the format
that you want the image output in. The format can be a MIME-type or
one of the following strings:
* ``'jpeg'`` - Write a JPEG file
* ``'png'`` - Write a PNG file
* ``'gif'`` - Write a GIF file
* ``'bmp'`` - Write a Windows bitmap file
* ``'yuv'`` - Write the raw image data to a file in YUV420 format
* ``'rgb'`` - Write the raw image data to a file in 24-bit RGB format
* ``'rgba'`` - Write the raw image data to a file in 32-bit RGBA format
* ``'bgr'`` - Write the raw image data to a file in 24-bit BGR format
* ``'bgra'`` - Write the raw image data to a file in 32-bit BGRA format
* ``'raw'`` - Deprecated option for raw captures; the format is taken
from the deprecated :attr:`raw_format` attribute
The *use_video_port* parameter controls whether the camera's image or
video port is used to capture images. It defaults to ``False`` which
means that the camera's image port is used. This port is slow but
produces better quality pictures. If you need rapid capture up to the
rate of video frames, set this to ``True``.
When *use_video_port* is ``True``, the *splitter_port* parameter
specifies the port of the video splitter that the image encoder will be
attached to. This defaults to ``0`` and most users will have no need to
specify anything different. This parameter is ignored when
*use_video_port* is ``False``. See :ref:`mmal` for more information
about the video splitter.
If *resize* is not ``None`` (the default), it must be a two-element
tuple specifying the width and height that the image should be resized
to.
.. warning::
If *resize* is specified, or *use_video_port* is ``True``, Exif
metadata will **not** be included in JPEG output. This is due to an
underlying firmware limitation.
Certain file formats accept additional options which can be specified
as keyword arguments. Currently, only the ``'jpeg'`` encoder accepts
additional options, which are:
* *quality* - Defines the quality of the JPEG encoder as an integer
ranging from 1 to 100. Defaults to 85. Please note that JPEG quality
is not a percentage and `definitions of quality`_ vary widely.
* *restart* - Defines the restart interval for the JPEG encoder as a
number of JPEG MCUs. The actual restart interval used will be a
multiple of the number of MCUs per row in the resulting image.
* *thumbnail* - Defines the size and quality of the thumbnail to embed
in the Exif metadata. Specifying ``None`` disables thumbnail
generation. Otherwise, specify a tuple of ``(width, height,
quality)``. Defaults to ``(64, 48, 35)``.
* *bayer* - If ``True``, the raw bayer data from the camera's sensor
is included in the Exif metadata.
.. note::
The so-called "raw" formats listed above (``'yuv'``, ``'rgb'``,
etc.) do not represent the raw bayer data from the camera's sensor.
Rather they provide access to the image data after GPU processing,
but before format encoding (JPEG, PNG, etc). Currently, the only
method of accessing the raw bayer data is via the *bayer* parameter
described above.
.. versionchanged:: 1.0
The *resize* parameter was added, and raw capture formats can now
be specified directly
.. versionchanged:: 1.3
The *splitter_port* parameter was added, and *bayer* was added as
an option for the ``'jpeg'`` format
.. versionchanged:: 1.11
Support for buffer outputs was added.
.. _definitions of quality: http://photo.net/learn/jpeg/#qual
Capture images continuously from the camera as an infinite iterator.
This method returns an infinite iterator of images captured
continuously from the camera. If *output* is a string, each captured
image is stored in a file named after *output* after substitution of
two values with the :meth:`~str.format` method. Those two values are:
* ``{counter}`` - a simple incrementor that starts at 1 and increases
by 1 for each image taken
* ``{timestamp}`` - a :class:`~datetime.datetime` instance
The table below contains several example values of *output* and the
sequence of filenames those values could produce:
.. tabularcolumns:: |p{80mm}|p{40mm}|p{10mm}|
+--------------------------------------------+--------------------------------------------+-------+
| *output* Value | Filenames | Notes |
+============================================+============================================+=======+
| ``'image{counter}.jpg'`` | image1.jpg, image2.jpg, image3.jpg, ... | |
+--------------------------------------------+--------------------------------------------+-------+
| ``'image{counter:02d}.jpg'`` | image01.jpg, image02.jpg, image03.jpg, ... | |
+--------------------------------------------+--------------------------------------------+-------+
| ``'image{timestamp}.jpg'`` | image2013-10-05 12:07:12.346743.jpg, | (1) |
| | image2013-10-05 12:07:32.498539, ... | |
+--------------------------------------------+--------------------------------------------+-------+
| ``'image{timestamp:%H-%M-%S-%f}.jpg'`` | image12-10-02-561527.jpg, | |
| | image12-10-14-905398.jpg | |
+--------------------------------------------+--------------------------------------------+-------+
| ``'{timestamp:%H%M%S}-{counter:03d}.jpg'`` | 121002-001.jpg, 121013-002.jpg, | (2) |
| | 121014-003.jpg, ... | |
+--------------------------------------------+--------------------------------------------+-------+
1. Note that because timestamp's default output includes colons (:),
the resulting filenames are not suitable for use on Windows. For
this reason (and the fact the default contains spaces) it is
strongly recommended you always specify a format when using
``{timestamp}``.
2. You can use both ``{timestamp}`` and ``{counter}`` in a single
format string (multiple times too!) although this tends to be
redundant.
If *output* is not a string, but has a ``write`` method, it is assumed
to be a file-like object and each image is simply written to this
object sequentially. In this case you will likely either want to write
something to the object between the images to distinguish them, or
clear the object between iterations. If *output* is not a string, and
has no ``write`` method, it is assumed to be a writeable object
supporting the buffer protocol; each image is simply written to the
buffer sequentially.
The *format*, *use_video_port*, *splitter_port*, *resize*, and
*options* parameters are the same as in :meth:`capture`.
If *use_video_port* is ``False`` (the default), the *burst* parameter
can be used to make still port captures faster. Specifically, this
prevents the preview from switching resolutions between captures which
significantly speeds up consecutive captures from the still port. The
downside is that this mode is currently has several bugs; the major
issue is that if captures are performed too quickly some frames will
come back severely underexposed. It is recommended that users avoid the
*burst* parameter unless they absolutely require it and are prepared to
work around such issues.
For example, to capture 60 images with a one second delay between them,
writing the output to a series of JPEG files named image01.jpg,
image02.jpg, etc. one could do the following::
import time
import picamera
with picamera.PiCamera() as camera:
camera.start_preview()
try:
for i, filename in enumerate(
camera.capture_continuous('image{counter:02d}.jpg')):
print(filename)
time.sleep(1)
if i == 59:
break
finally:
camera.stop_preview()
Alternatively, to capture JPEG frames as fast as possible into an
in-memory stream, performing some processing on each stream until
some condition is satisfied::
import io
import time
import picamera
with picamera.PiCamera() as camera:
stream = io.BytesIO()
for foo in camera.capture_continuous(stream, format='jpeg'):
# Truncate the stream to the current position (in case
# prior iterations output a longer image)
stream.truncate()
stream.seek(0)
if process(stream):
break
.. versionchanged:: 1.0
The *resize* parameter was added, and raw capture formats can now
be specified directly
.. versionchanged:: 1.3
The *splitter_port* parameter was added
.. versionchanged:: 1.11
Support for buffer outputs was added.
Capture a sequence of consecutive images from the camera.
This method accepts a sequence or iterator of *outputs* each of which
must either be a string specifying a filename for output, or a
file-like object with a ``write`` method, or a writeable buffer object.
For each item in the sequence or iterator of outputs, the camera
captures a single image as fast as it can.
The *format*, *use_video_port*, *splitter_port*, *resize*, and
*options* parameters are the same as in :meth:`capture`, but *format*
defaults to ``'jpeg'``. The format is **not** derived from the
filenames in *outputs* by this method.
If *use_video_port* is ``False`` (the default), the *burst* parameter
can be used to make still port captures faster. Specifically, this
prevents the preview from switching resolutions between captures which
significantly speeds up consecutive captures from the still port. The
downside is that this mode is currently has several bugs; the major
issue is that if captures are performed too quickly some frames will
come back severely underexposed. It is recommended that users avoid the
*burst* parameter unless they absolutely require it and are prepared to
work around such issues.
For example, to capture 3 consecutive images::
import time
import picamera
with picamera.PiCamera() as camera:
camera.start_preview()
time.sleep(2)
camera.capture_sequence([
'image1.jpg',
'image2.jpg',
'image3.jpg',
])
camera.stop_preview()
If you wish to capture a large number of images, a list comprehension
or generator expression can be used to construct the list of filenames
to use::
import time
import picamera
with picamera.PiCamera() as camera:
camera.start_preview()
time.sleep(2)
camera.capture_sequence([
'image%02d.jpg' % i
for i in range(100)
])
camera.stop_preview()
More complex effects can be obtained by using a generator function to
provide the filenames or output objects.
.. versionchanged:: 1.0
The *resize* parameter was added, and raw capture formats can now
be specified directly
.. versionchanged:: 1.3
The *splitter_port* parameter was added
.. versionchanged:: 1.11
Support for buffer outputs was added.
Finalizes the state of the camera.
After successfully constructing a :class:`PiCamera` object, you should
ensure you call the :meth:`close` method once you are finished with the
camera (e.g. in the ``finally`` section of a ``try..finally`` block).
This method stops all recording and preview activities and releases all
resources associated with the camera; this is necessary to prevent GPU
memory leaks.
Returns ``True`` if the :meth:`close` method has been called.
Formats a dictionary of values for inclusion in a docstring.
Holds a mapping of the Exif tags to apply to captured images.
.. note::
Please note that Exif tagging is only supported with the ``jpeg``
format.
By default several Exif tags are automatically applied to any images
taken with the :meth:`capture` method: ``IFD0.Make`` (which is set to
``RaspberryPi``), ``IFD0.Model`` (which is set to ``RP_OV5647``), and
three timestamp tags: ``IFD0.DateTime``, ``EXIF.DateTimeOriginal``, and
``EXIF.DateTimeDigitized`` which are all set to the current date and
time just before the picture is taken.
If you wish to set additional Exif tags, or override any of the
aforementioned tags, simply add entries to the exif_tags map before
calling :meth:`capture`. For example::
camera.exif_tags['IFD0.Copyright'] = 'Copyright (c) 2013 Foo Industries'
The Exif standard mandates ASCII encoding for all textual values, hence
strings containing non-ASCII characters will cause an encoding error to
be raised when :meth:`capture` is called. If you wish to set binary
values, use a :func:`bytes` value::
camera.exif_tags['EXIF.UserComment'] = b'Something containing\x00NULL characters'
.. warning::
Binary Exif values are currently ignored; this appears to be a
libmmal or firmware bug.
You may also specify datetime values, integer, or float values, all of
which will be converted to appropriate ASCII strings (datetime values
are formatted as ``YYYY:MM:DD HH:MM:SS`` in accordance with the Exif
standard).
The currently supported Exif tags are:
+-------+-------------------------------------------------------------+
| Group | Tags |
+=======+=============================================================+
| IFD0, | ImageWidth, ImageLength, BitsPerSample, Compression, |
| IFD1 | PhotometricInterpretation, ImageDescription, Make, Model, |
| | StripOffsets, Orientation, SamplesPerPixel, RowsPerString, |
| | StripByteCounts, Xresolution, Yresolution, |
| | PlanarConfiguration, ResolutionUnit, TransferFunction, |
| | Software, DateTime, Artist, WhitePoint, |
| | PrimaryChromaticities, JPEGInterchangeFormat, |
| | JPEGInterchangeFormatLength, YcbCrCoefficients, |
| | YcbCrSubSampling, YcbCrPositioning, ReferenceBlackWhite, |
| | Copyright |
+-------+-------------------------------------------------------------+
| EXIF | ExposureTime, FNumber, ExposureProgram, |
| | SpectralSensitivity, ISOSpeedRatings, OECF, ExifVersion, |
| | DateTimeOriginal, DateTimeDigitized, |
| | ComponentsConfiguration, CompressedBitsPerPixel, |
| | ShutterSpeedValue, ApertureValue, BrightnessValue, |
| | ExposureBiasValue, MaxApertureValue, SubjectDistance, |
| | MeteringMode, LightSource, Flash, FocalLength, SubjectArea, |
| | MakerNote, UserComment, SubSecTime, SubSecTimeOriginal, |
| | SubSecTimeDigitized, FlashpixVersion, ColorSpace, |
| | PixelXDimension, PixelYDimension, RelatedSoundFile, |
| | FlashEnergy, SpacialFrequencyResponse, |
| | FocalPlaneXResolution, FocalPlaneYResolution, |
| | FocalPlaneResolutionUnit, SubjectLocation, ExposureIndex, |
| | SensingMethod, FileSource, SceneType, CFAPattern, |
| | CustomRendered, ExposureMode, WhiteBalance, |
| | DigitalZoomRatio, FocalLengthIn35mmFilm, SceneCaptureType, |
| | GainControl, Contrast, Saturation, Sharpness, |
| | DeviceSettingDescription, SubjectDistanceRange, |
| | ImageUniqueID |
+-------+-------------------------------------------------------------+
| GPS | GPSVersionID, GPSLatitudeRef, GPSLatitude, GPSLongitudeRef, |
| | GPSLongitude, GPSAltitudeRef, GPSAltitude, GPSTimeStamp, |
| | GPSSatellites, GPSStatus, GPSMeasureMode, GPSDOP, |
| | GPSSpeedRef, GPSSpeed, GPSTrackRef, GPSTrack, |
| | GPSImgDirectionRef, GPSImgDirection, GPSMapDatum, |
| | GPSDestLatitudeRef, GPSDestLatitude, GPSDestLongitudeRef, |
| | GPSDestLongitude, GPSDestBearingRef, GPSDestBearing, |
| | GPSDestDistanceRef, GPSDestDistance, GPSProcessingMethod, |
| | GPSAreaInformation, GPSDateStamp, GPSDifferential |
+-------+-------------------------------------------------------------+
| EINT | InteroperabilityIndex, InteroperabilityVersion, |
| | RelatedImageFileFormat, RelatedImageWidth, |
| | RelatedImageLength |
+-------+-------------------------------------------------------------+
Returns ``True`` if the :meth:`start_preview` method has been called,
and no :meth:`stop_preview` call has been made yet.
.. deprecated:: 1.8
Test whether :attr:`preview` is ``None`` instead.
Record a sequence of video clips from the camera.
This method accepts a sequence or iterator of *outputs* each of which
must either be a string specifying a filename for output, or a
file-like object with a ``write`` method.
The method acts as an iterator itself, yielding each item of the
sequence in turn. In this way, the caller can control how long to
record to each item by only permitting the loop to continue when ready
to switch to the next output.
The *format*, *splitter_port*, *resize*, and *options* parameters are
the same as in :meth:`start_recording`, but *format* defaults to
``'h264'``. The format is **not** derived from the filenames in
*outputs* by this method.
For example, to record 3 consecutive 10-second video clips, writing the
output to a series of H.264 files named clip01.h264, clip02.h264, and
clip03.h264 one could use the following::
import picamera
with picamera.PiCamera() as camera:
for filename in camera.record_sequence([
'clip01.h264',
'clip02.h264',
'clip03.h264']):
print('Recording to %s' % filename)
camera.wait_recording(10)
Alternatively, a more flexible method of writing the previous example
(which is easier to expand to a large number of output files) is by
using a generator expression as the input sequence::
import picamera
with picamera.PiCamera() as camera:
for filename in camera.record_sequence(
'clip%02d.h264' % i for i in range(3)):
print('Recording to %s' % filename)
camera.wait_recording(10)
More advanced techniques are also possible by utilising infinite
sequences, such as those generated by :func:`itertools.cycle`. In the
following example, recording is switched between two in-memory streams.
Whilst one stream is recording, the other is being analysed. The script
only stops recording when a video recording meets some criteria defined
by the ``process`` function::
import io
import itertools
import picamera
with picamera.PiCamera() as camera:
analyse = None
for stream in camera.record_sequence(
itertools.cycle((io.BytesIO(), io.BytesIO()))):
if analyse is not None:
if process(analyse):
break
analyse.seek(0)
analyse.truncate()
camera.wait_recording(5)
analyse = stream
.. versionadded:: 1.3
Returns ``True`` if the :meth:`start_recording` method has been called,
and no :meth:`stop_recording` call has been made yet.
Removes a static overlay from the preview output.
This method removes an overlay which was previously created by
:meth:`add_overlay`. The *overlay* parameter specifies the
:class:`PiRenderer` instance that was returned by :meth:`add_overlay`.
.. versionadded:: 1.8
Request the encoder generate a key-frame as soon as possible.
When called, the video encoder running on the specified *splitter_port*
will attempt to produce a key-frame (full-image frame) as soon as
possible. The *splitter_port* defaults to ``1``. Valid values are
between ``0`` and ``3`` inclusive.
.. note::
This method is only meaningful for recordings encoded in the H264
format as MJPEG produces full frames for every frame recorded.
Furthermore, there's no guarantee that the *next* frame will be
a key-frame; this is simply a request to produce one as soon as
possible after the call.
.. versionadded:: 1.11
Returns a string representing the revision of the Pi's camera module.
At the time of writing, the string returned is 'ov5647' for the V1
module, and 'imx219' for the V2 module.
Continue the recording in the specified output; close existing output.
When called, the video encoder will wait for the next appropriate
split point (an inline SPS header), then will cease writing to the
current output (and close it, if it was specified as a filename), and
continue writing to the newly specified *output*.
The *output* parameter is treated as in the :meth:`start_recording`
method (it can be a string, a file-like object, or a writeable
buffer object).
The *motion_output* parameter can be used to redirect the output of the
motion vector data in the same fashion as *output*. If *motion_output*
is ``None`` (the default) then motion vector data will not be
redirected and will continue being written to the output specified by
the *motion_output* parameter given to :meth:`start_recording`.
Alternatively, if you only wish to redirect motion vector data, you can
set *output* to ``None`` and given a new value for *motion_output*.
The *splitter_port* parameter specifies which port of the video
splitter the encoder you wish to change outputs is attached to. This
defaults to ``1`` and most users will have no need to specify anything
different. Valid values are between ``0`` and ``3`` inclusive.
Note that unlike :meth:`start_recording`, you cannot specify format or
other options as these cannot be changed in the middle of recording.
Only the new *output* (and *motion_output*) can be specified.
Furthermore, the format of the recording is currently limited to H264,
and *inline_headers* must be ``True`` when :meth:`start_recording` is
called (this is the default).
.. versionchanged:: 1.3
The *splitter_port* parameter was added
.. versionchanged:: 1.5
The *motion_output* parameter was added
.. versionchanged:: 1.11
Support for buffer outputs was added.
Displays the preview overlay.
This method starts a camera preview as an overlay on the Pi's primary
display (HDMI or composite). A :class:`PiRenderer` instance (more
specifically, a :class:`PiPreviewRenderer`) is constructed with the
keyword arguments captured in *options*, and is returned from the
method (this instance is also accessible from the :attr:`preview`
attribute for as long as the renderer remains active). By default, the
renderer will be opaque and fullscreen.
This means the default preview overrides whatever is currently visible
on the display. More specifically, the preview does not rely on a
graphical environment like X-Windows (it can run quite happily from a
TTY console); it is simply an overlay on the Pi's video output. To stop
the preview and reveal the display again, call :meth:`stop_preview`.
The preview can be started and stopped multiple times during the
lifetime of the :class:`PiCamera` object.
All other camera properties can be modified "live" while the preview is
running (e.g. :attr:`brightness`).
.. note::
Because the default preview typically obscures the screen, ensure
you have a means of stopping a preview before starting one. If the
preview obscures your interactive console you won't be able to
Alt+Tab back to it as the preview isn't in a window. If you are in
an interactive Python session, simply pressing Ctrl+D usually
suffices to terminate the environment, including the camera and its
associated preview.
Start recording video from the camera, storing it in *output*.
If *output* is a string, it will be treated as a filename for a new
file which the video will be written to. If *output* is not a string,
but is an object with a ``write`` method, it is assumed to be a
file-like object and the video data is appended to it (the
implementation only assumes the object has a ``write()`` method - no
other methods are required but ``flush`` will be called at the end of
recording if it is present). If *output* is not a string, and has no
``write`` method it is assumed to be a writeable object implementing
the buffer protocol. In this case, the video frames will be written
sequentially to the underlying buffer (which must be large enough to
accept all frame data).
If *format* is ``None`` (the default), the method will attempt to guess
the required video format from the extension of *output* (if it's a
string), or from the *name* attribute of *output* (if it has one). In
the case that the format cannot be determined, a
:exc:`PiCameraValueError` will be raised.
If *format* is not ``None``, it must be a string specifying the format
that you want the video output in. The format can be a MIME-type or
one of the following strings:
* ``'h264'`` - Write an H.264 video stream
* ``'mjpeg'`` - Write an M-JPEG video stream
* ``'yuv'`` - Write the raw video data to a file in YUV420 format
* ``'rgb'`` - Write the raw video data to a file in 24-bit RGB format
* ``'rgba'`` - Write the raw video data to a file in 32-bit RGBA format
* ``'bgr'`` - Write the raw video data to a file in 24-bit BGR format
* ``'bgra'`` - Write the raw video data to a file in 32-bit BGRA format
If *resize* is not ``None`` (the default), it must be a two-element
tuple specifying the width and height that the video recording should
be resized to. This is particularly useful for recording video using
the full resolution of the camera sensor (which is not possible in
H.264 without down-sizing the output).
The *splitter_port* parameter specifies the port of the built-in
splitter that the video encoder will be attached to. This defaults to
``1`` and most users will have no need to specify anything different.
If you wish to record multiple (presumably resized) streams
simultaneously, specify a value between ``0`` and ``3`` inclusive for
this parameter, ensuring that you do not specify a port that is
currently in use.
Certain formats accept additional options which can be specified
as keyword arguments. The ``'h264'`` format accepts the following
additional options:
* *profile* - The H.264 profile to use for encoding. Defaults to
'high', but can be one of 'baseline', 'main', 'extended', 'high', or
'constrained'.
* *level* - The `H.264 level`_ to use for encoding. Defaults to '4',
but can be any H.264 level up to '4.2'.
* *intra_period* - The key frame rate (the rate at which I-frames are
inserted in the output). Defaults to ``None``, but can be any 32-bit
integer value representing the number of frames between successive
I-frames. The special value 0 causes the encoder to produce a single
initial I-frame, and then only P-frames subsequently. Note that
:meth:`split_recording` will fail in this mode.
* *intra_refresh* - The key frame format (the way in which I-frames
will be inserted into the output stream). Defaults to ``None``, but
can be one of 'cyclic', 'adaptive', 'both', or 'cyclicrows'.
* *inline_headers* - When ``True``, specifies that the encoder should
output SPS/PPS headers within the stream to ensure GOPs (groups of
pictures) are self describing. This is important for streaming
applications where the client may wish to seek within the stream, and
enables the use of :meth:`split_recording`. Defaults to ``True`` if
not specified.
* *sei* - When ``True``, specifies the encoder should include
"Supplemental Enhancement Information" within the output stream.
Defaults to ``False`` if not specified.
* *sps_timing* - When ``True`` the encoder includes the camera's
framerate in the SPS header. Defaults to ``False`` if not specified.
* *motion_output* - Indicates the output destination for motion vector
estimation data. When ``None`` (the default), motion data is not
output. Otherwise, this can be a filename string, a file-like object,
or a writeable buffer object (as with the *output* parameter).
All encoded formats accept the following additional options:
* *bitrate* - The bitrate at which video will be encoded. Defaults to
17000000 (17Mbps) if not specified. The maximum value depends on the
selected `H.264 level`_ and profile. Bitrate 0 indicates the encoder
should not use bitrate control (the encoder is limited by the quality
only).
* *quality* - Specifies the quality that the encoder should attempt
to maintain. For the ``'h264'`` format, use values between 10 and 40
where 10 is extremely high quality, and 40 is extremely low (20-25 is
usually a reasonable range for H.264 encoding). For the ``mjpeg``
format, use JPEG quality values between 1 and 100 (where higher
values are higher quality). Quality 0 is special and seems to be
a "reasonable quality" default.
* *quantization* - Deprecated alias for *quality*.
.. versionchanged:: 1.0
The *resize* parameter was added, and ``'mjpeg'`` was added as a
recording format
.. versionchanged:: 1.3
The *splitter_port* parameter was added
.. versionchanged:: 1.5
The *quantization* parameter was deprecated in favor of *quality*,
and the *motion_output* parameter was added.
.. versionchanged:: 1.11
Support for buffer outputs was added.
.. _H.264 level: https://en.wikipedia.org/wiki/H.264/MPEG-4_AVC#Levels
Hides the preview overlay.
If :meth:`start_preview` has previously been called, this method shuts
down the preview display which generally results in the underlying
display becoming visible again. If a preview is not currently running,
no exception is raised - the method will simply do nothing.
Stop recording video from the camera.
After calling this method the video encoder will be shut down and
output will stop being written to the file-like object specified with
:meth:`start_recording`. If an error occurred during recording and
:meth:`wait_recording` has not been called since the error then this
method will raise the exception.
The *splitter_port* parameter specifies which port of the video
splitter the encoder you wish to stop is attached to. This defaults to
``1`` and most users will have no need to specify anything different.
Valid values are between ``0`` and ``3`` inclusive.
.. versionchanged:: 1.3
The *splitter_port* parameter was added
Wait on the video encoder for timeout seconds.
It is recommended that this method is called while recording to check
for exceptions. If an error occurs during recording (for example out of
disk space) the recording will stop, but an exception will only be
raised when the :meth:`wait_recording` or :meth:`stop_recording`
methods are called.
If ``timeout`` is 0 (the default) the function will immediately return
(or raise an exception if an error has occurred).
The *splitter_port* parameter specifies which port of the video
splitter the encoder you wish to wait on is attached to. This
defaults to ``1`` and most users will have no need to specify anything
different. Valid values are between ``0`` and ``3`` inclusive.
.. versionchanged:: 1.3
The *splitter_port* parameter was added
vim: set et sw=4 sts=4 fileencoding=utf-8: Python camera library for the Rasperry-Pi camera module Copyright (c) 2013-2017 Dave Jones <dave@waveform.org.uk> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Make Py2's str equivalent to Py3's Can't find RPi.GPIO so just null-out the reference modified by PiCamera.__init__ modified by PiCamera.__init__ The following don't work'posterize': mmal.MMAL_PARAM_IMAGEFX_POSTERIZE,'whiteboard': mmal.MMAL_PARAM_IMAGEFX_WHITEBOARD,'blackboard': mmal.MMAL_PARAM_IMAGEFX_BLACKBOARD, compute module (default for cam 0) compute module (default for cam 1) Pi 1 model B rev 1 Pi 1 model B rev 2 or model A Pi 1 model B+ or Pi 2 model B Get screen resolution We're probably not running as root. In this case, forget the GPIO reference so we don't try anything further Don't attempt to set this if stereo mode isn't requested as it'll break compatibility on older firmwares Must be done *after* stereo-scopic setting auto Create a splitter component for the video port. This is to permit video recordings and captures where use_video_port=True to occur simultaneously (26) Create a null-sink component, enable it and connect it to the camera's preview port. If nothing is connected to the preview port, the camera doesn't measure exposure and captured images gradually fade to black (issue 22) Only enable capture if the port is the camera's still port, or if there's a single active encoder on the video splitter Only disable capture if the port is the camera's still port, or if there's a single active encoder on the video splitter Wait for the callback to set the event indicating the end of image capture If we're fed a bytes string, assume it's UTF-8 encoded and convert it to Unicode. Technically this is wrong (file-systems use all sorts of encodings), but UTF-8 is a reasonable default and this keeps compatibility with Python 2 simple although it breaks the edge cases of non-UTF-8 encoded bytes strings with non-UTF-8 encoded file-systems Pass the exception to the main thread; next time check_camera_open() is called this will get raised Initial setup Clamp preview resolution to camera's resolution If anything goes wrong, restore original resolution and framerate otherwise the camera can be left in unusual states (camera config not matching ports, etc). Ensure params is a tuple Find the parameter combination for the current effect | 47,902 | en | 0.801599 |
# Copyright 2020 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.
# ============================================================================
"""logical_and_impl"""
from mindspore.ops.composite import base
from mindspore.ops import functional as F
# logical_and is a metagraph object which will generate function according to input type
# using ".register" decorator
logical_and = base.MultitypeFuncGraph("logical_and")
@logical_and.register("Number", "Number")
def _logical_and_scala(x, y):
"""
Return logical and operation result of x and y.
Args:
x(Number): Number.
y(Number): Number.
Returns:
bool, Return logical and operation result of x and y.
"""
return F.bool_and(x.__bool__(), y.__bool__())
@logical_and.register("Tensor", "Tensor")
def _logical_and_tensor(x, y):
"""
Return logical and operation result of x and y.
Args:
x(Tensor): Tensor.
y(Tensor): Tensor.
Returns:
Tensor, Return logical and operation result of x and y.
"""
return F.logical_and(x, y)
| mindspore/ops/composite/multitype_ops/logical_and_impl.py | 1,590 | Return logical and operation result of x and y.
Args:
x(Number): Number.
y(Number): Number.
Returns:
bool, Return logical and operation result of x and y.
Return logical and operation result of x and y.
Args:
x(Tensor): Tensor.
y(Tensor): Tensor.
Returns:
Tensor, Return logical and operation result of x and y.
logical_and_impl
Copyright 2020 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. ============================================================================ logical_and is a metagraph object which will generate function according to input type using ".register" decorator | 1,106 | en | 0.799561 |
from jsonrpc import ServiceProxy
import sys
import string
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:9332")
else:
access = ServiceProxy("http://"+rpcuser+":"+rpcpass+"@127.0.0.1:9332")
cmd = sys.argv[1].lower()
if cmd == "backupwallet":
try:
path = raw_input("Enter destination path/filename: ")
print access.backupwallet(path)
except:
print "\n---An error occurred---\n"
elif cmd == "getaccount":
try:
addr = raw_input("Enter a Sarnath address: ")
print access.getaccount(addr)
except:
print "\n---An error occurred---\n"
elif cmd == "getaccountaddress":
try:
acct = raw_input("Enter an account name: ")
print access.getaccountaddress(acct)
except:
print "\n---An error occurred---\n"
elif cmd == "getaddressesbyaccount":
try:
acct = raw_input("Enter an account name: ")
print access.getaddressesbyaccount(acct)
except:
print "\n---An error occurred---\n"
elif cmd == "getbalance":
try:
acct = raw_input("Enter an account (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getbalance(acct, mc)
except:
print access.getbalance()
except:
print "\n---An error occurred---\n"
elif cmd == "getblockbycount":
try:
height = raw_input("Height: ")
print access.getblockbycount(height)
except:
print "\n---An error occurred---\n"
elif cmd == "getblockcount":
try:
print access.getblockcount()
except:
print "\n---An error occurred---\n"
elif cmd == "getblocknumber":
try:
print access.getblocknumber()
except:
print "\n---An error occurred---\n"
elif cmd == "getconnectioncount":
try:
print access.getconnectioncount()
except:
print "\n---An error occurred---\n"
elif cmd == "getdifficulty":
try:
print access.getdifficulty()
except:
print "\n---An error occurred---\n"
elif cmd == "getgenerate":
try:
print access.getgenerate()
except:
print "\n---An error occurred---\n"
elif cmd == "gethashespersec":
try:
print access.gethashespersec()
except:
print "\n---An error occurred---\n"
elif cmd == "getinfo":
try:
print access.getinfo()
except:
print "\n---An error occurred---\n"
elif cmd == "getnewaddress":
try:
acct = raw_input("Enter an account name: ")
try:
print access.getnewaddress(acct)
except:
print access.getnewaddress()
except:
print "\n---An error occurred---\n"
elif cmd == "getreceivedbyaccount":
try:
acct = raw_input("Enter an account (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getreceivedbyaccount(acct, mc)
except:
print access.getreceivedbyaccount()
except:
print "\n---An error occurred---\n"
elif cmd == "getreceivedbyaddress":
try:
addr = raw_input("Enter a Sarnath address (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getreceivedbyaddress(addr, mc)
except:
print access.getreceivedbyaddress()
except:
print "\n---An error occurred---\n"
elif cmd == "gettransaction":
try:
txid = raw_input("Enter a transaction ID: ")
print access.gettransaction(txid)
except:
print "\n---An error occurred---\n"
elif cmd == "getwork":
try:
data = raw_input("Data (optional): ")
try:
print access.gettransaction(data)
except:
print access.gettransaction()
except:
print "\n---An error occurred---\n"
elif cmd == "help":
try:
cmd = raw_input("Command (optional): ")
try:
print access.help(cmd)
except:
print access.help()
except:
print "\n---An error occurred---\n"
elif cmd == "listaccounts":
try:
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.listaccounts(mc)
except:
print access.listaccounts()
except:
print "\n---An error occurred---\n"
elif cmd == "listreceivedbyaccount":
try:
mc = raw_input("Minimum confirmations (optional): ")
incemp = raw_input("Include empty? (true/false, optional): ")
try:
print access.listreceivedbyaccount(mc, incemp)
except:
print access.listreceivedbyaccount()
except:
print "\n---An error occurred---\n"
elif cmd == "listreceivedbyaddress":
try:
mc = raw_input("Minimum confirmations (optional): ")
incemp = raw_input("Include empty? (true/false, optional): ")
try:
print access.listreceivedbyaddress(mc, incemp)
except:
print access.listreceivedbyaddress()
except:
print "\n---An error occurred---\n"
elif cmd == "listtransactions":
try:
acct = raw_input("Account (optional): ")
count = raw_input("Number of transactions (optional): ")
frm = raw_input("Skip (optional):")
try:
print access.listtransactions(acct, count, frm)
except:
print access.listtransactions()
except:
print "\n---An error occurred---\n"
elif cmd == "move":
try:
frm = raw_input("From: ")
to = raw_input("To: ")
amt = raw_input("Amount:")
mc = raw_input("Minimum confirmations (optional): ")
comment = raw_input("Comment (optional): ")
try:
print access.move(frm, to, amt, mc, comment)
except:
print access.move(frm, to, amt)
except:
print "\n---An error occurred---\n"
elif cmd == "sendfrom":
try:
frm = raw_input("From: ")
to = raw_input("To: ")
amt = raw_input("Amount:")
mc = raw_input("Minimum confirmations (optional): ")
comment = raw_input("Comment (optional): ")
commentto = raw_input("Comment-to (optional): ")
try:
print access.sendfrom(frm, to, amt, mc, comment, commentto)
except:
print access.sendfrom(frm, to, amt)
except:
print "\n---An error occurred---\n"
elif cmd == "sendmany":
try:
frm = raw_input("From: ")
to = raw_input("To (in format address1:amount1,address2:amount2,...): ")
mc = raw_input("Minimum confirmations (optional): ")
comment = raw_input("Comment (optional): ")
try:
print access.sendmany(frm,to,mc,comment)
except:
print access.sendmany(frm,to)
except:
print "\n---An error occurred---\n"
elif cmd == "sendtoaddress":
try:
to = raw_input("To (in format address1:amount1,address2:amount2,...): ")
amt = raw_input("Amount:")
comment = raw_input("Comment (optional): ")
commentto = raw_input("Comment-to (optional): ")
try:
print access.sendtoaddress(to,amt,comment,commentto)
except:
print access.sendtoaddress(to,amt)
except:
print "\n---An error occurred---\n"
elif cmd == "setaccount":
try:
addr = raw_input("Address: ")
acct = raw_input("Account:")
print access.setaccount(addr,acct)
except:
print "\n---An error occurred---\n"
elif cmd == "setgenerate":
try:
gen= raw_input("Generate? (true/false): ")
cpus = raw_input("Max processors/cores (-1 for unlimited, optional):")
try:
print access.setgenerate(gen, cpus)
except:
print access.setgenerate(gen)
except:
print "\n---An error occurred---\n"
elif cmd == "settxfee":
try:
amt = raw_input("Amount:")
print access.settxfee(amt)
except:
print "\n---An error occurred---\n"
elif cmd == "stop":
try:
print access.stop()
except:
print "\n---An error occurred---\n"
elif cmd == "validateaddress":
try:
addr = raw_input("Address: ")
print access.validateaddress(addr)
except:
print "\n---An error occurred---\n"
elif cmd == "walletpassphrase":
try:
pwd = raw_input("Enter wallet passphrase: ")
access.walletpassphrase(pwd, 60)
print "\n---Wallet unlocked---\n"
except:
print "\n---An error occurred---\n"
elif cmd == "walletpassphrasechange":
try:
pwd = raw_input("Enter old wallet passphrase: ")
pwd2 = raw_input("Enter new wallet passphrase: ")
access.walletpassphrasechange(pwd, pwd2)
print
print "\n---Passphrase changed---\n"
except:
print
print "\n---An error occurred---\n"
print
else:
print "Command not found or not supported"
| contrib/bitrpc/bitrpc.py | 7,836 | ===== BEGIN USER SETTINGS ===== if you do not set these you will be prompted for a password for every command ====== END USER SETTINGS ====== | 141 | en | 0.820638 |
###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename('chart_data_labels17.xlsx')
self.ignore_elements = {'xl/charts/chart1.xml': ['<c:formatCode']}
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'stock'})
date_format = workbook.add_format({'num_format': 14})
chart.axis_ids = [45740032, 45747200]
data = [
[39083, 39084, 39085, 39086, 39087],
[27.2, 25.03, 19.05, 20.34, 18.5],
[23.49, 19.55, 15.12, 17.84, 16.34],
[25.45, 23.05, 17.32, 20.45, 17.34],
]
for row in range(5):
worksheet.write(row, 0, data[0][row], date_format)
worksheet.write(row, 1, data[1][row])
worksheet.write(row, 2, data[2][row])
worksheet.write(row, 3, data[3][row])
worksheet.set_column('A:D', 11)
chart.add_series({
'categories': '=Sheet1!$A$1:$A$5',
'values': '=Sheet1!$B$1:$B$5',
})
chart.add_series({
'categories': '=Sheet1!$A$1:$A$5',
'values': '=Sheet1!$C$1:$C$5',
})
chart.add_series({
'categories': '=Sheet1!$A$1:$A$5',
'values': '=Sheet1!$D$1:$D$5',
'data_labels': {'value': 1, 'position': 'right'},
})
worksheet.insert_chart('E9', chart)
workbook.close()
self.assertExcelEqual()
| xlsxwriter/test/comparison/test_chart_data_labels17.py | 2,002 | Test file created by XlsxWriter against a file created by Excel.
Test the creation of a simple XlsxWriter file.
Tests for XlsxWriter. SPDX-License-Identifier: BSD-2-Clause Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org | 233 | en | 0.847261 |
from datetime import timedelta
from typing import NamedTuple, Optional
class ErdAdvantiumKitchenTimerMinMax(NamedTuple):
"""Defines min/max kitchen timer settings"""
min_time: timedelta
max_time: timedelta
raw_value: Optional[str]
| gehomesdk/erd/values/advantium/erd_advantium_kitchen_timer_min_max.py | 249 | Defines min/max kitchen timer settings | 38 | en | 0.536529 |
#!/usr/bin/env python3
# Copyright (c) 2018-2020 The Ludirium Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Useful util functions for testing the wallet"""
from collections import namedtuple
from test_framework.address import (
byte_to_base58,
key_to_p2pkh,
key_to_p2sh_p2wpkh,
key_to_p2wpkh,
script_to_p2sh,
script_to_p2sh_p2wsh,
script_to_p2wsh,
)
from test_framework.key import ECKey
from test_framework.script import (
CScript,
OP_2,
OP_3,
OP_CHECKMULTISIG,
)
from test_framework.script_util import (
key_to_p2pkh_script,
key_to_p2wpkh_script,
script_to_p2sh_script,
script_to_p2wsh_script,
)
from test_framework.util import hex_str_to_bytes
Key = namedtuple('Key', ['privkey',
'pubkey',
'p2pkh_script',
'p2pkh_addr',
'p2wpkh_script',
'p2wpkh_addr',
'p2sh_p2wpkh_script',
'p2sh_p2wpkh_redeem_script',
'p2sh_p2wpkh_addr'])
Multisig = namedtuple('Multisig', ['privkeys',
'pubkeys',
'p2sh_script',
'p2sh_addr',
'redeem_script',
'p2wsh_script',
'p2wsh_addr',
'p2sh_p2wsh_script',
'p2sh_p2wsh_addr'])
def get_key(node):
"""Generate a fresh key on node
Returns a named tuple of privkey, pubkey and all address and scripts."""
addr = node.getnewaddress()
pubkey = node.getaddressinfo(addr)['pubkey']
return Key(privkey=node.dumpprivkey(addr),
pubkey=pubkey,
p2pkh_script=key_to_p2pkh_script(pubkey).hex(),
p2pkh_addr=key_to_p2pkh(pubkey),
p2wpkh_script=key_to_p2wpkh_script(pubkey).hex(),
p2wpkh_addr=key_to_p2wpkh(pubkey),
p2sh_p2wpkh_script=script_to_p2sh_script(key_to_p2wpkh_script(pubkey)).hex(),
p2sh_p2wpkh_redeem_script=key_to_p2wpkh_script(pubkey).hex(),
p2sh_p2wpkh_addr=key_to_p2sh_p2wpkh(pubkey))
def get_generate_key():
"""Generate a fresh key
Returns a named tuple of privkey, pubkey and all address and scripts."""
eckey = ECKey()
eckey.generate()
privkey = bytes_to_wif(eckey.get_bytes())
pubkey = eckey.get_pubkey().get_bytes().hex()
return Key(privkey=privkey,
pubkey=pubkey,
p2pkh_script=key_to_p2pkh_script(pubkey).hex(),
p2pkh_addr=key_to_p2pkh(pubkey),
p2wpkh_script=key_to_p2wpkh_script(pubkey).hex(),
p2wpkh_addr=key_to_p2wpkh(pubkey),
p2sh_p2wpkh_script=script_to_p2sh_script(key_to_p2wpkh_script(pubkey)).hex(),
p2sh_p2wpkh_redeem_script=key_to_p2wpkh_script(pubkey).hex(),
p2sh_p2wpkh_addr=key_to_p2sh_p2wpkh(pubkey))
def get_multisig(node):
"""Generate a fresh 2-of-3 multisig on node
Returns a named tuple of privkeys, pubkeys and all address and scripts."""
addrs = []
pubkeys = []
for _ in range(3):
addr = node.getaddressinfo(node.getnewaddress())
addrs.append(addr['address'])
pubkeys.append(addr['pubkey'])
script_code = CScript([OP_2] + [hex_str_to_bytes(pubkey) for pubkey in pubkeys] + [OP_3, OP_CHECKMULTISIG])
witness_script = script_to_p2wsh_script(script_code)
return Multisig(privkeys=[node.dumpprivkey(addr) for addr in addrs],
pubkeys=pubkeys,
p2sh_script=script_to_p2sh_script(script_code).hex(),
p2sh_addr=script_to_p2sh(script_code),
redeem_script=script_code.hex(),
p2wsh_script=witness_script.hex(),
p2wsh_addr=script_to_p2wsh(script_code),
p2sh_p2wsh_script=script_to_p2sh_script(witness_script).hex(),
p2sh_p2wsh_addr=script_to_p2sh_p2wsh(script_code))
def test_address(node, address, **kwargs):
"""Get address info for `address` and test whether the returned values are as expected."""
addr_info = node.getaddressinfo(address)
for key, value in kwargs.items():
if value is None:
if key in addr_info.keys():
raise AssertionError("key {} unexpectedly returned in getaddressinfo.".format(key))
elif addr_info[key] != value:
raise AssertionError("key {} value {} did not match expected value {}".format(key, addr_info[key], value))
def bytes_to_wif(b, compressed=True):
if compressed:
b += b'\x01'
return byte_to_base58(b, 239)
def generate_wif_key():
# Makes a WIF privkey for imports
k = ECKey()
k.generate()
return bytes_to_wif(k.get_bytes(), k.is_compressed)
| test/functional/test_framework/wallet_util.py | 5,074 | Generate a fresh key
Returns a named tuple of privkey, pubkey and all address and scripts.
Generate a fresh key on node
Returns a named tuple of privkey, pubkey and all address and scripts.
Generate a fresh 2-of-3 multisig on node
Returns a named tuple of privkeys, pubkeys and all address and scripts.
Get address info for `address` and test whether the returned values are as expected.
Useful util functions for testing the wallet
!/usr/bin/env python3 Copyright (c) 2018-2020 The Ludirium Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. Makes a WIF privkey for imports | 676 | en | 0.786577 |
import pymongo
import sys
# establish a connection to the database
# note this uses the now deprecated Connection class, as we did in the lecture.
# MongoClient is the preferred way of connecting.
connection = pymongo.Connection("mongodb://localhost", safe=True)
# get a handle to the school database
db=connection.school
scores = db.scores
query = {''}
try:
doc = scores.find_one(query)
except:
print "Unexpected error:", sys.exc_info()[0]
print doc
| src/m101p/week02/lesson_files/hemmerling_week2_01.py | 508 | establish a connection to the database note this uses the now deprecated Connection class, as we did in the lecture. MongoClient is the preferred way of connecting. get a handle to the school database | 201 | en | 0.942386 |
from django.contrib import admin
from .models import Arts, Comments, Tags, ArtworksTags, Stili, Umetnina, Umetnik
# Register your models here.
admin.site.register(Umetnik)
admin.site.register(Umetnina)
admin.site.register(Stili)
admin.site.register(Arts)
admin.site.register(Comments)
admin.site.register(Tags)
admin.site.register(ArtworksTags)
# admin.site.register(ArtworkLikes)
| umetnine/artists/admin.py | 384 | Register your models here. admin.site.register(ArtworkLikes) | 60 | en | 0.795785 |
# Copyright Istio Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import collections
import os
import json
import argparse
import subprocess
import shlex
import uuid
from fortio import METRICS_START_SKIP_DURATION, METRICS_END_SKIP_DURATION
import sys
if sys.version_info.major == 2:
from commands import getoutput
else:
from subprocess import getoutput
POD = collections.namedtuple('Pod', ['name', 'namespace', 'ip', 'labels'])
def pod_info(filterstr="", namespace="twopods", multi_ok=True):
cmd = "kubectl -n {namespace} get pod {filterstr} -o json".format(
namespace=namespace, filterstr=filterstr)
op = getoutput(cmd)
o = json.loads(op)
items = o['items']
if not multi_ok and len(items) > 1:
raise Exception("more than one found " + op)
if not items:
raise Exception("no pods found with command [" + cmd + "]")
i = items[0]
return POD(i['metadata']['name'], i['metadata']['namespace'],
i['status']['podIP'], i['metadata']['labels'])
def run_command(command):
process = subprocess.Popen(shlex.split(command))
process.wait()
def run_command_sync(command):
op = getoutput(command)
return op.strip()
class Fortio:
ports = {
"http": {"direct_port": 8077, "port": 8080, "ingress": 80},
"grpc": {"direct_port": 8076, "port": 8079, "ingress": 80},
"direct_envoy": {"direct_port": 8076, "port": 8079},
}
def __init__(
self,
conn=None,
qps=None,
duration=None,
size=None,
mode="http",
mixer_mode="mixer",
mixer_cache=True,
perf_record=False,
server="fortioserver",
client="fortioclient",
additional_args=None,
filter_fn=None,
labels=None,
baseline=False,
serversidecar=False,
clientsidecar=True,
ingress=None,
mesh="istio"):
self.run_id = str(uuid.uuid4()).partition('-')[0]
self.conn = conn
self.qps = qps
self.size = size
self.duration = duration
self.mode = mode
self.ns = os.environ.get("NAMESPACE", "twopods")
# bucket resolution in seconds
self.r = "0.00005"
self.mixer_mode = mixer_mode
self.mixer_cache = mixer_cache
self.perf_record = perf_record
self.server = pod_info("-lapp=" + server, namespace=self.ns)
self.client = pod_info("-lapp=" + client, namespace=self.ns)
self.additional_args = additional_args
self.filter_fn = filter_fn
self.labels = labels
self.run_baseline = baseline
self.run_serversidecar = serversidecar
self.run_clientsidecar = clientsidecar
self.run_ingress = ingress
if mesh == "linkerd":
self.mesh = "linkerd"
elif mesh == "istio":
self.mesh = "istio"
else:
sys.exit("invalid mesh %s, must be istio or linkerd" % mesh)
def nosidecar(self, fortio_cmd):
basestr = "http://{svc}:{port}/echo?size={size}"
if self.mode == "grpc":
basestr = "-payload-size {size} {svc}:{port}"
return fortio_cmd + "_base " + basestr.format(
svc=self.server.ip, port=self.ports[self.mode]["direct_port"], size=self.size)
def serversidecar(self, fortio_cmd):
basestr = "http://{svc}:{port}/echo?size={size}"
if self.mode == "grpc":
basestr = "-payload-size {size} {svc}:{port}"
return fortio_cmd + "_serveronly " + basestr.format(
svc=self.server.ip, port=self.ports[self.mode]["port"], size=self.size)
def bothsidecar(self, fortio_cmd):
basestr = "http://{svc}:{port}/echo?size={size}"
if self.mode == "grpc":
basestr = "-payload-size {size} {svc}:{port}"
return fortio_cmd + "_both " + basestr.format(
svc=self.server.labels["app"], port=self.ports[self.mode]["port"], size=self.size)
def ingress(self, fortio_cmd):
svc = self.run_ingress
if ':' not in svc:
svc += ":{port}".format(port=self.ports[self.mode]["ingress"])
return fortio_cmd + "_ingress http://{svc}/echo?size={size}".format(
svc=svc, size=self.size)
def run(self, conn, qps, size, duration):
size = size or self.size
if duration is None:
duration = self.duration
labels = self.run_id
labels += "_qps_" + str(qps)
labels += "_c_" + str(conn)
labels += "_" + str(size)
# Mixer label
labels += "_"
labels += self.mixer_mode
if self.labels is not None:
labels += "_" + self.labels
grpc = ""
if self.mode == "grpc":
grpc = "-grpc -ping"
fortio_cmd = (
"fortio load -c {conn} -qps {qps} -t {duration}s -a -r {r} {grpc} -httpbufferkb=128 " +
"-labels {labels}").format(
conn=conn,
qps=qps,
duration=duration,
r=self.r,
grpc=grpc,
labels=labels)
if self.run_ingress:
kubectl_exec(self.client.name, self.ingress(fortio_cmd))
if self.perf_record:
run_perf(
self.mesh,
self.server.name,
labels + "_srv_ingress",
duration=40)
if self.run_serversidecar:
kubectl_exec(self.client.name, self.serversidecar(fortio_cmd))
if self.perf_record:
run_perf(
self.mesh,
self.server.name,
labels + "_srv_serveronly",
duration=40)
if self.run_clientsidecar:
kubectl_exec(self.client.name, self.bothsidecar(fortio_cmd))
if self.perf_record:
run_perf(
self.mesh,
self.server.name,
labels + "_srv_bothsidecars",
duration=40)
if self.run_baseline:
kubectl_exec(self.client.name, self.nosidecar(fortio_cmd))
PERFCMD = "/usr/lib/linux-tools/4.4.0-131-generic/perf"
PERFSH = "get_perfdata.sh"
PERFWD = "/etc/istio/proxy/"
def run_perf(mesh, pod, labels, duration=20):
filename = labels + "_perf.data"
filepath = PERFWD + filename
perfpath = PERFWD + PERFSH
# copy executable over
kubectl_cp(PERFSH, pod + ":" + perfpath, mesh + "-proxy")
kubectl_exec(
pod,
"{perf_cmd} {filename} {duration}".format(
perf_cmd=perfpath,
filename=filename,
duration=duration),
container=mesh + "-proxy")
kubectl_cp(pod + ":" + filepath + ".perf", filename + ".perf", mesh + "-proxy")
run_command_sync("../flame/flame.sh " + filename + ".perf")
def kubectl_cp(from_file, to_file, container):
namespace = os.environ.get("NAMESPACE", "twopods")
cmd = "kubectl --namespace {namespace} cp {from_file} {to_file} -c {container}".format(
namespace=namespace,
from_file=from_file,
to_file=to_file,
container=container)
print(cmd)
run_command_sync(cmd)
def kubectl_exec(pod, remote_cmd, runfn=run_command, container=None):
namespace = os.environ.get("NAMESPACE", "twopods")
c = ""
if container is not None:
c = "-c " + container
cmd = "kubectl --namespace {namespace} exec -i -t {pod} {c} -- {remote_cmd}".format(
pod=pod,
remote_cmd=remote_cmd,
c=c,
namespace=namespace)
print(cmd)
runfn(cmd)
def rc(command):
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
print(output.strip() + "\n")
return process.poll()
def run(args):
min_duration = METRICS_START_SKIP_DURATION + METRICS_END_SKIP_DURATION
if args.duration <= min_duration:
print("Duration must be greater than {min_duration}".format(
min_duration=min_duration))
exit(1)
fortio = Fortio(
conn=args.conn,
qps=args.qps,
duration=args.duration,
size=args.size,
perf_record=args.perf,
labels=args.labels,
baseline=args.baseline,
serversidecar=args.serversidecar,
clientsidecar=args.clientsidecar,
ingress=args.ingress,
mode=args.mode,
mesh=args.mesh,
mixer_mode=args.mixer_mode)
for conn in args.conn:
for qps in args.qps:
fortio.run(conn=conn, qps=qps,
duration=args.duration, size=args.size)
def csv_to_int(s):
return [int(i) for i in s.split(",")]
def get_parser():
parser = argparse.ArgumentParser("Run performance test")
parser.add_argument(
"conn",
help="number of connections, comma separated list",
type=csv_to_int,)
parser.add_argument(
"qps",
help="qps, comma separated list",
type=csv_to_int,)
parser.add_argument(
"duration",
help="duration in seconds of the extract",
type=int)
parser.add_argument(
"--size",
help="size of the payload",
type=int,
default=1024)
parser.add_argument(
"--mesh",
help="istio or linkerd",
default="istio")
parser.add_argument(
"--mixer_mode",
help="run with different mixer configurations: mixer, nomixer, mixerv2",
default="mixer")
parser.add_argument(
"--client",
help="where to run the test from",
default=None)
parser.add_argument(
"--server",
help="pod ip of the server",
default=None)
parser.add_argument(
"--perf",
help="also run perf and produce flame graph",
default=False)
parser.add_argument(
"--ingress",
help="run traffic through ingress",
default=None)
parser.add_argument(
"--labels",
help="extra labels",
default=None)
parser.add_argument(
"--mode",
help="http or grpc",
default="http")
define_bool(parser, "baseline", "run baseline for all", False)
define_bool(parser, "serversidecar",
"run serversidecar-only for all", False)
define_bool(parser, "clientsidecar",
"run clientsidecar and serversidecar for all", True)
return parser
def define_bool(parser, opt, help_arg, default_val):
parser.add_argument(
"--" + opt, help=help_arg, dest=opt, action='store_true')
parser.add_argument(
"--no-" + opt, help="do not " + help_arg, dest=opt, action='store_false')
val = {opt: default_val}
parser.set_defaults(**val)
def main(argv):
args = get_parser().parse_args(argv)
print(args)
return run(args)
if __name__ == "__main__":
import sys
sys.exit(main(sys.argv[1:]))
| perf/benchmark/runner/runner.py | 11,681 | Copyright Istio Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. bucket resolution in seconds Mixer label copy executable over | 606 | en | 0.853207 |
# Usage: testWordsInCorpus.py [language] {corpus file}
# If no corpus file is named, the programme will try to load a corresponding cPickle file.
#
# German corpus: /mounts/data/proj/huiming/SIGMORPHON/dewiki-20151102-pages-articles-multistream.xml
#
# This script finds words that should belong to a paradigm in the corpus and adds them (for training?).
from getEditTrees import editTreesByPos
from getEditTrees import applyOnlyTree
import sys
import pickle as cPickle
toAdd = {} # lemma to things that should be autocompleted
uniquenessCheck = {} # (lemma, form) -> word, avoiding that we add things we are unsure about
# New autocomplete. Finds union and checks if paradigms can complete each other.
# We suppose the union consists of at least 2 edit trees.
# TODO: account for Umlaute.
# Returns a dictinary lemma -> (et, tags) with things to add to the original one.
# TODO: irgendwas stimmt hier nicht. korrigiere es
def autoComplete(lemma1, etTag1, lemma2, etTag2, corpusWords):
etAndTagToAdd = set()
notFound = 0
allRight1 = True
allRight2 = True
for (et, form) in etTag1.difference(etTag2):
result = applyOnlyTree(lemma2, et)
if result == '#error#':
allRight = False
break
if result not in corpusWords or corpusWords[result] <=3: # orig is 3
notFound += 1
if notFound == 2:
allRight = False
break
else:
etAndTagToAdd.add((et, form))
if allRight and etAndTagToAdd:
if lemma2 not in toAdd:
toAdd[lemma2] = set()
toAdd[lemma2] = toAdd[lemma2].union(etAndTagToAdd)
for (et, form) in etAndTagToAdd:
if (lemma2, form) not in uniquenessCheck:
uniquenessCheck[(lemma2, form)] = set()
else:
if applyOnlyTree(lemma2,et) not in uniquenessCheck[(lemma2, form)]:
print("yeay")
uniquenessCheck[(lemma2, form)].add(applyOnlyTree(lemma2, et))
# Lemma 1 has more ETs than lemma 2.
# Returns a dictinary lemma -> (et, tags) with things to add to the original one.
def autoComplete2(lemma1, etTag1, lemma2, etTag2, corpusWords):
etAndTagToAdd = set()
notFound = 0
allRight = True
for (et, form) in etTag1.difference(etTag2):
result = applyOnlyTree(lemma2, et)
if result == '#error#':
allRight = False
break
if result not in corpusWords or corpusWords[result] <=3: # orig is 3
notFound += 1
if notFound == 2:
allRight = False
break
else:
etAndTagToAdd.add((et, form))
if allRight and etAndTagToAdd:
if lemma2 not in toAdd:
toAdd[lemma2] = set()
toAdd[lemma2] = toAdd[lemma2].union(etAndTagToAdd)
for (et, form) in etAndTagToAdd:
if (lemma2, form) not in uniquenessCheck:
uniquenessCheck[(lemma2, form)] = set()
uniquenessCheck[(lemma2, form)].add(applyOnlyTree(lemma2, et))
# Test if a group of (edit tree, tag) combinations for a lemma is subset of the one for another lemma.
# If yes, try if the missing edit trees are applicable and if the corresponding word appears in the corpus.
def getAdditionalWords(lemmaToEtAndTag, corpusWords):
isTrue = 0
isFalse = 0
for lemma1, etTag1 in lemmaToEtAndTag.items():
for lemma2, etTag2 in lemmaToEtAndTag.items():
if len(etTag1) <= 1 or len(etTag2) <= 1: # for now, don't complete things with 0 or only 1 entry. We are just not sure enough.
isFalse += 1
continue
maybeSame = False
if len(etTag1) > len(etTag2)+2:
if len(etTag1) >= 3 and len(etTag2.union(etTag1)) > 1 and etTag2.issubset(etTag1):
maybeSame = True
autoComplete(lemma1, etTag1, lemma2, etTag2, corpusWords)
isTrue += 1
else:
isFalse += 1
elif len(etTag2) > len(etTag1)+2:
if len(etTag2) >= 3 and len(etTag2.union(etTag1)) > 1 and etTag1.issubset(etTag2):
maybeSame = True
autoComplete(lemma2, etTag2, lemma1, etTag1, corpusWords)
isTrue += 1
else:
isFalse += 1
#print(str(len(toAdd)) + ' words have been added.')
#print("Is subset: " + str(isTrue))
#print("No subset: " + str(isFalse))
#sys.exit(0)
noWordsToAdd = 0
for lemma, aSet in toAdd.items():
noWordsToAdd += len(aSet)
'''
for (lemma, form), word in uniquenessCheck.items():
if len(word) > 1:
print(word)
sys.exit(0)
'''
return noWordsToAdd
def announce(*objs):
print("# ", *objs, file = sys.stderr)
if __name__ == "__main__":
lang = sys.argv[1]
if len(sys.argv) == 2:
usePickle = True
else:
usePickle = False
posToEt, lemmaToEtAndTag = editTreesByPos(lang)
for lemma, aSet in lemmaToEtAndTag.items():
for (et, form) in aSet:
if (lemma, form) not in uniquenessCheck:
uniquenessCheck[(lemma, form)] = set()
uniquenessCheck[(lemma, form)].add(applyOnlyTree(lemma, et))
#print(applyOnlyTree(lemma, et))
#sys.exit(0)
if not usePickle:
# Read the bonus corpus.
announce('Start reading corpus...')
corpusWords = {} # word to its frequency
with open(sys.argv[2], 'r') as corpus_file:
for line in corpus_file:
#tokens = tokenize.word_tokenize(line.strip())
tokens = line.strip().split(' ')
for token in tokens:
if token not in corpusWords:
corpusWords[token] = 0
corpusWords[token] += 1
announce('Done reading corpus.')
# Store the dictionary to a binary file.
print('Store the dictionary with the corpus words to a binary file...')
save_file = open('/mounts/data/proj/huiming/SIGMORPHON/corpusWords_' + lang, 'wb')
cPickle.dump(corpusWords, save_file, -1)
save_file.close()
print('Done.')
else:
# Load the corpusWords dictionary.
announce('Load the words with cPickle...')
vocListFile = open('/mounts/data/proj/huiming/SIGMORPHON/corpusWords_' + lang, 'rb')
corpusWords = cPickle.load(vocListFile)
vocListFile.close()
announce('Words loaded.')
lastNumber = 0
noWordsToAdd = 1
while noWordsToAdd > lastNumber:
lastNumber = noWordsToAdd
noWordsToAdd = getAdditionalWords(lemmaToEtAndTag, corpusWords)
for lemma, aSet in lemmaToEtAndTag.items():
if lemma in toAdd:
lemmaToEtAndTag[lemma] = lemmaToEtAndTag[lemma].union(toAdd[lemma])
announce('Number word to add: ' + str(noWordsToAdd))
# The union did not work well for some reason. Therefore, use toAdd directly.
additionalWordsCounter = 0
with open('/mounts/Users/cisintern/huiming/SIGMORPHON/Code/data/' + lang + '-bigger-task1-train', 'w') as out_file:
with open('/mounts/Users/cisintern/huiming/SIGMORPHON/Code/data/' + lang + '-task1-train', 'r') as original_file:
for line in original_file:
out_file.write(line)
for lemma, etAndTagSet in toAdd.items():
for (et, form) in etAndTagSet:
if len(uniquenessCheck[(lemma, form)]) > 1:
continue
out_file.write(lemma + '\t' + form + '\t' + applyOnlyTree(lemma, et) + '\n')
additionalWordsCounter += 1
print(str(additionalWordsCounter) + ' words have been added.')
| MyAlgorithm/addWordsToParadigms_old.py | 7,156 | Usage: testWordsInCorpus.py [language] {corpus file} If no corpus file is named, the programme will try to load a corresponding cPickle file. German corpus: /mounts/data/proj/huiming/SIGMORPHON/dewiki-20151102-pages-articles-multistream.xml This script finds words that should belong to a paradigm in the corpus and adds them (for training?). lemma to things that should be autocompleted (lemma, form) -> word, avoiding that we add things we are unsure about New autocomplete. Finds union and checks if paradigms can complete each other. We suppose the union consists of at least 2 edit trees. TODO: account for Umlaute. Returns a dictinary lemma -> (et, tags) with things to add to the original one. TODO: irgendwas stimmt hier nicht. korrigiere es orig is 3 Lemma 1 has more ETs than lemma 2. Returns a dictinary lemma -> (et, tags) with things to add to the original one. orig is 3 Test if a group of (edit tree, tag) combinations for a lemma is subset of the one for another lemma. If yes, try if the missing edit trees are applicable and if the corresponding word appears in the corpus. for now, don't complete things with 0 or only 1 entry. We are just not sure enough.print(str(len(toAdd)) + ' words have been added.')print("Is subset: " + str(isTrue))print("No subset: " + str(isFalse))sys.exit(0)print(applyOnlyTree(lemma, et))sys.exit(0) Read the bonus corpus. word to its frequencytokens = tokenize.word_tokenize(line.strip()) Store the dictionary to a binary file. Load the corpusWords dictionary. The union did not work well for some reason. Therefore, use toAdd directly. | 1,586 | en | 0.755291 |
#!/usr/bin/env python2
from setuptools import setup
from setuptools import find_packages
setup(
name="rover",
version="0.1",
description="Algorithm for risk and sensor quality aware sensor" +
"coverage for quadrotors",
author="Alex Wallar",
author_email="wallarelvo@gmail.com",
packages=find_packages(),
install_requires=[
"numpy",
"scipy"
],
data_files=[
(
'config',
['configs/config.json'],
)
]
)
| setup.py | 501 | !/usr/bin/env python2 | 21 | fr | 0.26923 |
#!/usr/bin/python
#coding:utf-8
import time
import json
import requests
from selenium import webdriver
filename = 'a.csv'
url = 'http://www.icourse163.org/university/view/all.htm#/'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}
# with open(filename, 'w+') as file:
# file.write("大学,课程,课程时长,课程负载,内容类型,课程分类\n")
file = open(filename, 'w+')
print("大学,课程,课程时长,课程负载,内容类型,课程分类")
file.write("大学,课程,课程时长,课程负载,内容类型,课程分类\n")
browser = webdriver.PhantomJS()
browser2 = webdriver.PhantomJS()
browser3 = webdriver.PhantomJS()
browser.get(url)
# 大学
university = browser.find_elements_by_class_name("u-usity")
for i in university:
university_url = i.get_attribute("href")
university_name = i.find_element_by_id("").get_attribute("alt")
browser2.get(university_url)
# 课程
course = browser2.find_elements_by_class_name("g-cell1")
for j in course:
course_url = "http://www.icourse163.org" + j.get_attribute("data-href")
course_name = j.find_element_by_class_name("card").find_element_by_class_name("f-f0").text
browser3.get(course_url)
# 课程信息
course_text = browser3.find_elements_by_class_name("block")
try:
k0 = course_text[0].find_element_by_class_name("t2").text
k1 = course_text[1].find_element_by_class_name("t2").text
k2 = course_text[2].find_element_by_class_name("t2").text
k3 = course_text[3].find_element_by_class_name("t2").text
except Exception as e:
k3 = k2
k2 = k1
k1 = None
K0 = None
finally:
print("%s,%s,%s,%s,%s,%s" % (university_name,course_name,k0,k1,k2,k3))
file.write("%s,%s,%s,%s,%s,%s\n" % (university_name,course_name,k0,k1,k2,k3))
# with open(filename, 'a+') as file:
# file.write("%s,%s,%s,%s,%s,%s\n" % (university_name,course_name,k0,k1,k2,k3))
browser3.close()
browser2.close()
browser.close()
| spider.py | 2,236 | !/usr/bin/pythoncoding:utf-8 with open(filename, 'w+') as file: file.write("大学,课程,课程时长,课程负载,内容类型,课程分类\n") 大学 课程 课程信息 with open(filename, 'a+') as file: file.write("%s,%s,%s,%s,%s,%s\n" % (university_name,course_name,k0,k1,k2,k3)) | 237 | en | 0.462415 |
#!/usr/bin/env python
# This example uses Uvicorn package that must be installed. However, it can be
# replaced with any other ASGI-compliant server.
#
# NOTE: Python 3.6 requires aiocontextvars package to be installed.
#
# Run: python app_global_request.py
import rollbar
import uvicorn
from rollbar.contrib.starlette import LoggerMiddleware
from starlette.applications import Starlette
from starlette.responses import JSONResponse
# Integrate Rollbar with Starlette application
app = Starlette()
app.add_middleware(LoggerMiddleware) # should be added as the last middleware
async def get_user_agent():
# Global access to the current request object
request = rollbar.get_request()
user_agent = request.headers['User-Agent']
return user_agent
# $ curl -i http://localhost:8888
@app.route('/')
async def root(request):
user_agent = await get_user_agent()
return JSONResponse({'user-agent': user_agent})
if __name__ == '__main__':
uvicorn.run(app, host='localhost', port=8888)
| rollbar/examples/starlette/app_global_request.py | 1,015 | !/usr/bin/env python This example uses Uvicorn package that must be installed. However, it can be replaced with any other ASGI-compliant server. NOTE: Python 3.6 requires aiocontextvars package to be installed. Run: python app_global_request.py Integrate Rollbar with Starlette application should be added as the last middleware Global access to the current request object $ curl -i http://localhost:8888 | 404 | en | 0.773295 |
# Configuration file for jupyter-notebook.
#------------------------------------------------------------------------------
# Configurable configuration
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# SingletonConfigurable configuration
#------------------------------------------------------------------------------
# A configurable that only allows one instance.
#
# This class is for classes that should only have one instance of itself or
# *any* subclass. To create and retrieve such a class use the
# :meth:`SingletonConfigurable.instance` method.
#------------------------------------------------------------------------------
# Application configuration
#------------------------------------------------------------------------------
# This is an application.
# The date format used by logging formatters for %(asctime)s
# c.Application.log_datefmt = '%Y-%m-%d %H:%M:%S'
# The Logging format template
# c.Application.log_format = '[%(name)s]%(highlevel)s %(message)s'
# Set the log level by value or name.
# c.Application.log_level = 30
#------------------------------------------------------------------------------
# JupyterApp configuration
#------------------------------------------------------------------------------
# Base class for Jupyter applications
# Answer yes to any prompts.
c.JupyterApp.answer_yes = True
# Full path of a config file.
# c.JupyterApp.config_file = u''
# Generate default config file.
# c.JupyterApp.generate_config = False
# Specify a config file to load.
# c.JupyterApp.config_file_name = u''
#------------------------------------------------------------------------------
# NotebookApp configuration
#------------------------------------------------------------------------------
# The number of additional ports to try if the specified port is not available.
c.NotebookApp.port_retries = 0
# Extra variables to supply to jinja templates when rendering.
# c.NotebookApp.jinja_template_vars = traitlets.Undefined
# The url for MathJax.js.
# c.NotebookApp.mathjax_url = ''
# Supply extra arguments that will be passed to Jinja environment.
# c.NotebookApp.jinja_environment_options = traitlets.Undefined
# The IP address the notebook server will listen on.
c.NotebookApp.ip = '*'
# DEPRECATED use base_url
# c.NotebookApp.base_project_url = '/'
# Python modules to load as notebook server extensions. This is an experimental
# API, and may change in future releases.
# c.NotebookApp.server_extensions = traitlets.Undefined
# Note: These extensions require the ~/.jupyter path to exist otherwise, errors will occur on startup
c.NotebookApp.server_extensions=['ipyparallel.nbextension']
# The random bytes used to secure cookies. By default this is a new random
# number every time you start the Notebook. Set it to a value in a config file
# to enable logins to persist across server sessions.
#
# Note: Cookie secrets should be kept private, do not share config files with
# cookie_secret stored in plaintext (you can read the value from a file).
# c.NotebookApp.cookie_secret = ''
# The default URL to redirect to from `/`
# c.NotebookApp.default_url = '/tree'
# The port the notebook server will listen on.
c.NotebookApp.port = 8754
# The kernel spec manager class to use. Should be a subclass of
# `jupyter_client.kernelspec.KernelSpecManager`.
#
# The Api of KernelSpecManager is provisional and might change without warning
# between this version of IPython and the next stable one.
# c.NotebookApp.kernel_spec_manager_class = <class 'jupyter_client.kernelspec.KernelSpecManager'>
# Set the Access-Control-Allow-Origin header
#
# Use '*' to allow any origin to access your server.
#
# Takes precedence over allow_origin_pat.
c.NotebookApp.allow_origin = '*'
# The notebook manager class to use.
# c.NotebookApp.contents_manager_class = <class 'notebook.services.contents.filemanager.FileContentsManager'>
# Use a regular expression for the Access-Control-Allow-Origin header
#
# Requests from an origin matching the expression will get replies with:
#
# Access-Control-Allow-Origin: origin
#
# where `origin` is the origin of the request.
#
# Ignored if allow_origin is set.
# c.NotebookApp.allow_origin_pat = ''
# The full path to an SSL/TLS certificate file.
# c.NotebookApp.certfile = u''
# The logout handler class to use.
# c.NotebookApp.logout_handler_class = <class 'notebook.auth.logout.LogoutHandler'>
# The base URL for the notebook server.
#
# Leading and trailing slashes can be omitted, and will automatically be added.
c.NotebookApp.base_url = '/'
# The session manager class to use.
# c.NotebookApp.session_manager_class = <class 'notebook.services.sessions.sessionmanager.SessionManager'>
# Supply overrides for the tornado.web.Application that the IPython notebook
# uses.
# c.NotebookApp.tornado_settings = traitlets.Undefined
# The directory to use for notebooks and kernels.
c.NotebookApp.notebook_dir = u'/root/pipeline/myapps/jupyter/'
# The kernel manager class to use.
# c.NotebookApp.kernel_manager_class = <class 'notebook.services.kernels.kernelmanager.MappingKernelManager'>
# The file where the cookie secret is stored.
# c.NotebookApp.cookie_secret_file = u''
# Supply SSL options for the tornado HTTPServer. See the tornado docs for
# details.
# c.NotebookApp.ssl_options = traitlets.Undefined
#
# c.NotebookApp.file_to_run = ''
# DISABLED: use %pylab or %matplotlib in the notebook to enable matplotlib.
# c.NotebookApp.pylab = 'disabled'
# Whether to enable MathJax for typesetting math/TeX
#
# MathJax is the javascript library IPython uses to render math/LaTeX. It is
# very large, so you may want to disable it if you have a slow internet
# connection, or for offline use of the notebook.
#
# When disabled, equations etc. will appear as their untransformed TeX source.
# c.NotebookApp.enable_mathjax = True
# Reraise exceptions encountered loading server extensions?
# c.NotebookApp.reraise_server_extension_failures = False
# The base URL for websockets, if it differs from the HTTP server (hint: it
# almost certainly doesn't).
#
# Should be in the form of an HTTP origin: ws[s]://hostname[:port]
# c.NotebookApp.websocket_url = ''
# Whether to open in a browser after starting. The specific browser used is
# platform dependent and determined by the python standard library `webbrowser`
# module, unless it is overridden using the --browser (NotebookApp.browser)
# configuration option.
c.NotebookApp.open_browser = False
# Hashed password to use for web authentication.
#
# To generate, type in a python/IPython shell:
#
# from notebook.auth import passwd; passwd()
#
# The string should be of the form type:salt:hashed-password.
# c.NotebookApp.password = u''
# extra paths to look for Javascript notebook extensions
# c.NotebookApp.extra_nbextensions_path = traitlets.Undefined
# Set the Access-Control-Allow-Credentials: true header
# c.NotebookApp.allow_credentials = False
# Extra paths to search for serving static files.
#
# This allows adding javascript/css to be available from the notebook server
# machine, or overriding individual files in the IPython
# c.NotebookApp.extra_static_paths = traitlets.Undefined
# The login handler class to use.
# c.NotebookApp.login_handler_class = <class 'notebook.auth.login.LoginHandler'>
# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if the proxy handles
# SSL
# c.NotebookApp.trust_xheaders = False
# Extra paths to search for serving jinja templates.
#
# Can be used to override templates from notebook.templates.
# c.NotebookApp.extra_template_paths = traitlets.Undefined
# The config manager class to use
# c.NotebookApp.config_manager_class = <class 'notebook.services.config.manager.ConfigManager'>
# The full path to a private key file for usage with SSL/TLS.
# c.NotebookApp.keyfile = u''
# DEPRECATED, use tornado_settings
# c.NotebookApp.webapp_settings = traitlets.Undefined
# Specify what command to use to invoke a web browser when opening the notebook.
# If not specified, the default browser will be determined by the `webbrowser`
# standard library module, which allows setting of the BROWSER environment
# variable to override it.
# c.NotebookApp.browser = u''
#------------------------------------------------------------------------------
# LoggingConfigurable configuration
#------------------------------------------------------------------------------
# A parent class for Configurables that log.
#
# Subclasses have a log trait, and the default behavior is to get the logger
# from the currently running Application.
#------------------------------------------------------------------------------
# ConnectionFileMixin configuration
#------------------------------------------------------------------------------
# Mixin for configurable classes that work with connection files
# set the stdin (ROUTER) port [default: random]
# c.ConnectionFileMixin.stdin_port = 0
# Set the kernel's IP address [default localhost]. If the IP address is
# something other than localhost, then Consoles on other machines will be able
# to connect to the Kernel, so be careful!
# c.ConnectionFileMixin.ip = u''
# JSON file in which to store connection info [default: kernel-<pid>.json]
#
# This file will contain the IP, ports, and authentication key needed to connect
# clients to this kernel. By default, this file will be created in the security
# dir of the current profile, but can be specified by absolute path.
# c.ConnectionFileMixin.connection_file = ''
# set the control (ROUTER) port [default: random]
# c.ConnectionFileMixin.control_port = 0
# set the heartbeat port [default: random]
# c.ConnectionFileMixin.hb_port = 0
# set the shell (ROUTER) port [default: random]
# c.ConnectionFileMixin.shell_port = 0
#
# c.ConnectionFileMixin.transport = 'tcp'
# set the iopub (PUB) port [default: random]
# c.ConnectionFileMixin.iopub_port = 0
#------------------------------------------------------------------------------
# KernelManager configuration
#------------------------------------------------------------------------------
# Manages a single kernel in a subprocess on this host.
#
# This version starts kernels with Popen.
# DEPRECATED: Use kernel_name instead.
#
# The Popen Command to launch the kernel. Override this if you have a custom
# kernel. If kernel_cmd is specified in a configuration file, Jupyter does not
# pass any arguments to the kernel, because it cannot make any assumptions about
# the arguments that the kernel understands. In particular, this means that the
# kernel does not receive the option --debug if it given on the Jupyter command
# line.
# c.KernelManager.kernel_cmd = traitlets.Undefined
# Should we autorestart the kernel if it dies.
# c.KernelManager.autorestart = False
#------------------------------------------------------------------------------
# Session configuration
#------------------------------------------------------------------------------
# Object for handling serialization and sending of messages.
#
# The Session object handles building messages and sending them with ZMQ sockets
# or ZMQStream objects. Objects can communicate with each other over the
# network via Session objects, and only need to work with the dict-based IPython
# message spec. The Session will handle serialization/deserialization, security,
# and metadata.
#
# Sessions support configurable serialization via packer/unpacker traits, and
# signing with HMAC digests via the key/keyfile traits.
#
# Parameters ----------
#
# debug : bool
# whether to trigger extra debugging statements
# packer/unpacker : str : 'json', 'pickle' or import_string
# importstrings for methods to serialize message parts. If just
# 'json' or 'pickle', predefined JSON and pickle packers will be used.
# Otherwise, the entire importstring must be used.
#
# The functions must accept at least valid JSON input, and output *bytes*.
#
# For example, to use msgpack:
# packer = 'msgpack.packb', unpacker='msgpack.unpackb'
# pack/unpack : callables
# You can also set the pack/unpack callables for serialization directly.
# session : bytes
# the ID of this Session object. The default is to generate a new UUID.
# username : unicode
# username added to message headers. The default is to ask the OS.
# key : bytes
# The key used to initialize an HMAC signature. If unset, messages
# will not be signed or checked.
# keyfile : filepath
# The file containing a key. If this is set, `key` will be initialized
# to the contents of the file.
# Username for the Session. Default is your system username.
# c.Session.username = u'username'
# Threshold (in bytes) beyond which a buffer should be sent without copying.
# c.Session.copy_threshold = 65536
# The name of the packer for serializing messages. Should be one of 'json',
# 'pickle', or an import name for a custom callable serializer.
# c.Session.packer = 'json'
# Metadata dictionary, which serves as the default top-level metadata dict for
# each message.
# c.Session.metadata = traitlets.Undefined
# The maximum number of digests to remember.
#
# The digest history will be culled when it exceeds this value.
# c.Session.digest_history_size = 65536
# The UUID identifying this session.
# c.Session.session = u''
# The digest scheme used to construct the message signatures. Must have the form
# 'hmac-HASH'.
# c.Session.signature_scheme = 'hmac-sha256'
# execution key, for signing messages.
# c.Session.key = ''
# Debug output in the Session
# c.Session.debug = False
# The name of the unpacker for unserializing messages. Only used with custom
# functions for `packer`.
# c.Session.unpacker = 'json'
# path to file containing execution key.
# c.Session.keyfile = ''
# Threshold (in bytes) beyond which an object's buffer should be extracted to
# avoid pickling.
# c.Session.buffer_threshold = 1024
# The maximum number of items for a container to be introspected for custom
# serialization. Containers larger than this are pickled outright.
# c.Session.item_threshold = 64
#------------------------------------------------------------------------------
# MultiKernelManager configuration
#------------------------------------------------------------------------------
# A class for managing multiple kernels.
# The name of the default kernel to start
# c.MultiKernelManager.default_kernel_name = 'python2'
# The kernel manager class. This is configurable to allow subclassing of the
# KernelManager for customized behavior.
# c.MultiKernelManager.kernel_manager_class = 'jupyter_client.ioloop.IOLoopKernelManager'
#------------------------------------------------------------------------------
# MappingKernelManager configuration
#------------------------------------------------------------------------------
# A KernelManager that handles notebook mapping and HTTP error handling
#
# c.MappingKernelManager.root_dir = u''
#------------------------------------------------------------------------------
# ContentsManager configuration
#------------------------------------------------------------------------------
# Base class for serving files and directories.
#
# This serves any text or binary file, as well as directories, with special
# handling for JSON notebook documents.
#
# Most APIs take a path argument, which is always an API-style unicode path, and
# always refers to a directory.
#
# - unicode, not url-escaped
# - '/'-separated
# - leading and trailing '/' will be stripped
# - if unspecified, path defaults to '',
# indicating the root path.
# The base name used when creating untitled files.
# c.ContentsManager.untitled_file = 'untitled'
# Python callable or importstring thereof
#
# To be called on a contents model prior to save.
#
# This can be used to process the structure, such as removing notebook outputs
# or other side effects that should not be saved.
#
# It will be called as (all arguments passed by keyword)::
#
# hook(path=path, model=model, contents_manager=self)
#
# - model: the model to be saved. Includes file contents.
# Modifying this dict will affect the file that is stored.
# - path: the API path of the save destination
# - contents_manager: this ContentsManager instance
# c.ContentsManager.pre_save_hook = None
#
# c.ContentsManager.checkpoints_class = <class 'notebook.services.contents.checkpoints.Checkpoints'>
# Glob patterns to hide in file and directory listings.
# c.ContentsManager.hide_globs = traitlets.Undefined
# The base name used when creating untitled notebooks.
# c.ContentsManager.untitled_notebook = 'Untitled'
# The base name used when creating untitled directories.
# c.ContentsManager.untitled_directory = 'Untitled Folder'
#
# c.ContentsManager.checkpoints = traitlets.Undefined
#
# c.ContentsManager.checkpoints_kwargs = traitlets.Undefined
#------------------------------------------------------------------------------
# FileContentsManager configuration
#------------------------------------------------------------------------------
# DEPRECATED, use post_save_hook
# c.FileContentsManager.save_script = False
#
# c.FileContentsManager.root_dir = u''
# Python callable or importstring thereof
#
# to be called on the path of a file just saved.
#
# This can be used to process the file on disk, such as converting the notebook
# to a script or HTML via nbconvert.
#
# It will be called as (all arguments passed by keyword)::
#
# hook(os_path=os_path, model=model, contents_manager=instance)
#
# - path: the filesystem path to the file just written - model: the model
# representing the file - contents_manager: this ContentsManager instance
# c.FileContentsManager.post_save_hook = None
#------------------------------------------------------------------------------
# NotebookNotary configuration
#------------------------------------------------------------------------------
# A class for computing and verifying notebook signatures.
# The number of notebook signatures to cache. When the number of signatures
# exceeds this value, the oldest 25% of signatures will be culled.
# c.NotebookNotary.cache_size = 65535
# The secret key with which notebooks are signed.
# c.NotebookNotary.secret = ''
# The sqlite file in which to store notebook signatures. By default, this will
# be in your Jupyter runtime directory. You can set it to ':memory:' to disable
# sqlite writing to the filesystem.
# c.NotebookNotary.db_file = u''
# The hashing algorithm used to sign notebooks.
# c.NotebookNotary.algorithm = 'sha256'
# The file where the secret key is stored.
# c.NotebookNotary.secret_file = u''
#------------------------------------------------------------------------------
# KernelSpecManager configuration
#------------------------------------------------------------------------------
# Whitelist of allowed kernel names.
#
# By default, all installed kernels are allowed.
# c.KernelSpecManager.whitelist = traitlets.Undefined
| config/jupyter/jupyter_notebook_config.py | 19,173 | Configuration file for jupyter-notebook.------------------------------------------------------------------------------ Configurable configuration------------------------------------------------------------------------------------------------------------------------------------------------------------ SingletonConfigurable configuration------------------------------------------------------------------------------ A configurable that only allows one instance. This class is for classes that should only have one instance of itself or *any* subclass. To create and retrieve such a class use the :meth:`SingletonConfigurable.instance` method.------------------------------------------------------------------------------ Application configuration------------------------------------------------------------------------------ This is an application. The date format used by logging formatters for %(asctime)s c.Application.log_datefmt = '%Y-%m-%d %H:%M:%S' The Logging format template c.Application.log_format = '[%(name)s]%(highlevel)s %(message)s' Set the log level by value or name. c.Application.log_level = 30------------------------------------------------------------------------------ JupyterApp configuration------------------------------------------------------------------------------ Base class for Jupyter applications Answer yes to any prompts. Full path of a config file. c.JupyterApp.config_file = u'' Generate default config file. c.JupyterApp.generate_config = False Specify a config file to load. c.JupyterApp.config_file_name = u''------------------------------------------------------------------------------ NotebookApp configuration------------------------------------------------------------------------------ The number of additional ports to try if the specified port is not available. Extra variables to supply to jinja templates when rendering. c.NotebookApp.jinja_template_vars = traitlets.Undefined The url for MathJax.js. c.NotebookApp.mathjax_url = '' Supply extra arguments that will be passed to Jinja environment. c.NotebookApp.jinja_environment_options = traitlets.Undefined The IP address the notebook server will listen on. DEPRECATED use base_url c.NotebookApp.base_project_url = '/' Python modules to load as notebook server extensions. This is an experimental API, and may change in future releases. c.NotebookApp.server_extensions = traitlets.Undefined Note: These extensions require the ~/.jupyter path to exist otherwise, errors will occur on startup The random bytes used to secure cookies. By default this is a new random number every time you start the Notebook. Set it to a value in a config file to enable logins to persist across server sessions. Note: Cookie secrets should be kept private, do not share config files with cookie_secret stored in plaintext (you can read the value from a file). c.NotebookApp.cookie_secret = '' The default URL to redirect to from `/` c.NotebookApp.default_url = '/tree' The port the notebook server will listen on. The kernel spec manager class to use. Should be a subclass of `jupyter_client.kernelspec.KernelSpecManager`. The Api of KernelSpecManager is provisional and might change without warning between this version of IPython and the next stable one. c.NotebookApp.kernel_spec_manager_class = <class 'jupyter_client.kernelspec.KernelSpecManager'> Set the Access-Control-Allow-Origin header Use '*' to allow any origin to access your server. Takes precedence over allow_origin_pat. The notebook manager class to use. c.NotebookApp.contents_manager_class = <class 'notebook.services.contents.filemanager.FileContentsManager'> Use a regular expression for the Access-Control-Allow-Origin header Requests from an origin matching the expression will get replies with: Access-Control-Allow-Origin: origin where `origin` is the origin of the request. Ignored if allow_origin is set. c.NotebookApp.allow_origin_pat = '' The full path to an SSL/TLS certificate file. c.NotebookApp.certfile = u'' The logout handler class to use. c.NotebookApp.logout_handler_class = <class 'notebook.auth.logout.LogoutHandler'> The base URL for the notebook server. Leading and trailing slashes can be omitted, and will automatically be added. The session manager class to use. c.NotebookApp.session_manager_class = <class 'notebook.services.sessions.sessionmanager.SessionManager'> Supply overrides for the tornado.web.Application that the IPython notebook uses. c.NotebookApp.tornado_settings = traitlets.Undefined The directory to use for notebooks and kernels. The kernel manager class to use. c.NotebookApp.kernel_manager_class = <class 'notebook.services.kernels.kernelmanager.MappingKernelManager'> The file where the cookie secret is stored. c.NotebookApp.cookie_secret_file = u'' Supply SSL options for the tornado HTTPServer. See the tornado docs for details. c.NotebookApp.ssl_options = traitlets.Undefined c.NotebookApp.file_to_run = '' DISABLED: use %pylab or %matplotlib in the notebook to enable matplotlib. c.NotebookApp.pylab = 'disabled' Whether to enable MathJax for typesetting math/TeX MathJax is the javascript library IPython uses to render math/LaTeX. It is very large, so you may want to disable it if you have a slow internet connection, or for offline use of the notebook. When disabled, equations etc. will appear as their untransformed TeX source. c.NotebookApp.enable_mathjax = True Reraise exceptions encountered loading server extensions? c.NotebookApp.reraise_server_extension_failures = False The base URL for websockets, if it differs from the HTTP server (hint: it almost certainly doesn't). Should be in the form of an HTTP origin: ws[s]://hostname[:port] c.NotebookApp.websocket_url = '' Whether to open in a browser after starting. The specific browser used is platform dependent and determined by the python standard library `webbrowser` module, unless it is overridden using the --browser (NotebookApp.browser) configuration option. Hashed password to use for web authentication. To generate, type in a python/IPython shell: from notebook.auth import passwd; passwd() The string should be of the form type:salt:hashed-password. c.NotebookApp.password = u'' extra paths to look for Javascript notebook extensions c.NotebookApp.extra_nbextensions_path = traitlets.Undefined Set the Access-Control-Allow-Credentials: true header c.NotebookApp.allow_credentials = False Extra paths to search for serving static files. This allows adding javascript/css to be available from the notebook server machine, or overriding individual files in the IPython c.NotebookApp.extra_static_paths = traitlets.Undefined The login handler class to use. c.NotebookApp.login_handler_class = <class 'notebook.auth.login.LoginHandler'> Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded- For headerssent by the upstream reverse proxy. Necessary if the proxy handles SSL c.NotebookApp.trust_xheaders = False Extra paths to search for serving jinja templates. Can be used to override templates from notebook.templates. c.NotebookApp.extra_template_paths = traitlets.Undefined The config manager class to use c.NotebookApp.config_manager_class = <class 'notebook.services.config.manager.ConfigManager'> The full path to a private key file for usage with SSL/TLS. c.NotebookApp.keyfile = u'' DEPRECATED, use tornado_settings c.NotebookApp.webapp_settings = traitlets.Undefined Specify what command to use to invoke a web browser when opening the notebook. If not specified, the default browser will be determined by the `webbrowser` standard library module, which allows setting of the BROWSER environment variable to override it. c.NotebookApp.browser = u''------------------------------------------------------------------------------ LoggingConfigurable configuration------------------------------------------------------------------------------ A parent class for Configurables that log. Subclasses have a log trait, and the default behavior is to get the logger from the currently running Application.------------------------------------------------------------------------------ ConnectionFileMixin configuration------------------------------------------------------------------------------ Mixin for configurable classes that work with connection files set the stdin (ROUTER) port [default: random] c.ConnectionFileMixin.stdin_port = 0 Set the kernel's IP address [default localhost]. If the IP address is something other than localhost, then Consoles on other machines will be able to connect to the Kernel, so be careful! c.ConnectionFileMixin.ip = u'' JSON file in which to store connection info [default: kernel-<pid>.json] This file will contain the IP, ports, and authentication key needed to connect clients to this kernel. By default, this file will be created in the security dir of the current profile, but can be specified by absolute path. c.ConnectionFileMixin.connection_file = '' set the control (ROUTER) port [default: random] c.ConnectionFileMixin.control_port = 0 set the heartbeat port [default: random] c.ConnectionFileMixin.hb_port = 0 set the shell (ROUTER) port [default: random] c.ConnectionFileMixin.shell_port = 0 c.ConnectionFileMixin.transport = 'tcp' set the iopub (PUB) port [default: random] c.ConnectionFileMixin.iopub_port = 0------------------------------------------------------------------------------ KernelManager configuration------------------------------------------------------------------------------ Manages a single kernel in a subprocess on this host. This version starts kernels with Popen. DEPRECATED: Use kernel_name instead. The Popen Command to launch the kernel. Override this if you have a custom kernel. If kernel_cmd is specified in a configuration file, Jupyter does not pass any arguments to the kernel, because it cannot make any assumptions about the arguments that the kernel understands. In particular, this means that the kernel does not receive the option --debug if it given on the Jupyter command line. c.KernelManager.kernel_cmd = traitlets.Undefined Should we autorestart the kernel if it dies. c.KernelManager.autorestart = False------------------------------------------------------------------------------ Session configuration------------------------------------------------------------------------------ Object for handling serialization and sending of messages. The Session object handles building messages and sending them with ZMQ sockets or ZMQStream objects. Objects can communicate with each other over the network via Session objects, and only need to work with the dict-based IPython message spec. The Session will handle serialization/deserialization, security, and metadata. Sessions support configurable serialization via packer/unpacker traits, and signing with HMAC digests via the key/keyfile traits. Parameters ---------- debug : bool whether to trigger extra debugging statements packer/unpacker : str : 'json', 'pickle' or import_string importstrings for methods to serialize message parts. If just 'json' or 'pickle', predefined JSON and pickle packers will be used. Otherwise, the entire importstring must be used. The functions must accept at least valid JSON input, and output *bytes*. For example, to use msgpack: packer = 'msgpack.packb', unpacker='msgpack.unpackb' pack/unpack : callables You can also set the pack/unpack callables for serialization directly. session : bytes the ID of this Session object. The default is to generate a new UUID. username : unicode username added to message headers. The default is to ask the OS. key : bytes The key used to initialize an HMAC signature. If unset, messages will not be signed or checked. keyfile : filepath The file containing a key. If this is set, `key` will be initialized to the contents of the file. Username for the Session. Default is your system username. c.Session.username = u'username' Threshold (in bytes) beyond which a buffer should be sent without copying. c.Session.copy_threshold = 65536 The name of the packer for serializing messages. Should be one of 'json', 'pickle', or an import name for a custom callable serializer. c.Session.packer = 'json' Metadata dictionary, which serves as the default top-level metadata dict for each message. c.Session.metadata = traitlets.Undefined The maximum number of digests to remember. The digest history will be culled when it exceeds this value. c.Session.digest_history_size = 65536 The UUID identifying this session. c.Session.session = u'' The digest scheme used to construct the message signatures. Must have the form 'hmac-HASH'. c.Session.signature_scheme = 'hmac-sha256' execution key, for signing messages. c.Session.key = '' Debug output in the Session c.Session.debug = False The name of the unpacker for unserializing messages. Only used with custom functions for `packer`. c.Session.unpacker = 'json' path to file containing execution key. c.Session.keyfile = '' Threshold (in bytes) beyond which an object's buffer should be extracted to avoid pickling. c.Session.buffer_threshold = 1024 The maximum number of items for a container to be introspected for custom serialization. Containers larger than this are pickled outright. c.Session.item_threshold = 64------------------------------------------------------------------------------ MultiKernelManager configuration------------------------------------------------------------------------------ A class for managing multiple kernels. The name of the default kernel to start c.MultiKernelManager.default_kernel_name = 'python2' The kernel manager class. This is configurable to allow subclassing of the KernelManager for customized behavior. c.MultiKernelManager.kernel_manager_class = 'jupyter_client.ioloop.IOLoopKernelManager'------------------------------------------------------------------------------ MappingKernelManager configuration------------------------------------------------------------------------------ A KernelManager that handles notebook mapping and HTTP error handling c.MappingKernelManager.root_dir = u''------------------------------------------------------------------------------ ContentsManager configuration------------------------------------------------------------------------------ Base class for serving files and directories. This serves any text or binary file, as well as directories, with special handling for JSON notebook documents. Most APIs take a path argument, which is always an API-style unicode path, and always refers to a directory. - unicode, not url-escaped - '/'-separated - leading and trailing '/' will be stripped - if unspecified, path defaults to '', indicating the root path. The base name used when creating untitled files. c.ContentsManager.untitled_file = 'untitled' Python callable or importstring thereof To be called on a contents model prior to save. This can be used to process the structure, such as removing notebook outputs or other side effects that should not be saved. It will be called as (all arguments passed by keyword):: hook(path=path, model=model, contents_manager=self) - model: the model to be saved. Includes file contents. Modifying this dict will affect the file that is stored. - path: the API path of the save destination - contents_manager: this ContentsManager instance c.ContentsManager.pre_save_hook = None c.ContentsManager.checkpoints_class = <class 'notebook.services.contents.checkpoints.Checkpoints'> Glob patterns to hide in file and directory listings. c.ContentsManager.hide_globs = traitlets.Undefined The base name used when creating untitled notebooks. c.ContentsManager.untitled_notebook = 'Untitled' The base name used when creating untitled directories. c.ContentsManager.untitled_directory = 'Untitled Folder' c.ContentsManager.checkpoints = traitlets.Undefined c.ContentsManager.checkpoints_kwargs = traitlets.Undefined------------------------------------------------------------------------------ FileContentsManager configuration------------------------------------------------------------------------------ DEPRECATED, use post_save_hook c.FileContentsManager.save_script = False c.FileContentsManager.root_dir = u'' Python callable or importstring thereof to be called on the path of a file just saved. This can be used to process the file on disk, such as converting the notebook to a script or HTML via nbconvert. It will be called as (all arguments passed by keyword):: hook(os_path=os_path, model=model, contents_manager=instance) - path: the filesystem path to the file just written - model: the model representing the file - contents_manager: this ContentsManager instance c.FileContentsManager.post_save_hook = None------------------------------------------------------------------------------ NotebookNotary configuration------------------------------------------------------------------------------ A class for computing and verifying notebook signatures. The number of notebook signatures to cache. When the number of signatures exceeds this value, the oldest 25% of signatures will be culled. c.NotebookNotary.cache_size = 65535 The secret key with which notebooks are signed. c.NotebookNotary.secret = '' The sqlite file in which to store notebook signatures. By default, this will be in your Jupyter runtime directory. You can set it to ':memory:' to disable sqlite writing to the filesystem. c.NotebookNotary.db_file = u'' The hashing algorithm used to sign notebooks. c.NotebookNotary.algorithm = 'sha256' The file where the secret key is stored. c.NotebookNotary.secret_file = u''------------------------------------------------------------------------------ KernelSpecManager configuration------------------------------------------------------------------------------ Whitelist of allowed kernel names. By default, all installed kernels are allowed. c.KernelSpecManager.whitelist = traitlets.Undefined | 17,935 | en | 0.622204 |
import asyncio
import logging
import os
import shutil
import warnings
from types import TracebackType
from typing import Any, Coroutine, Dict, List, Optional, Text, Type, TypeVar
import rasa.core.utils
import rasa.utils.io
from rasa.constants import (
DEFAULT_LOG_LEVEL_LIBRARIES,
ENV_LOG_LEVEL_LIBRARIES,
)
from rasa.shared.constants import DEFAULT_LOG_LEVEL, ENV_LOG_LEVEL
import rasa.shared.utils.io
logger = logging.getLogger(__name__)
T = TypeVar("T")
class TempDirectoryPath(str):
"""Represents a path to an temporary directory. When used as a context
manager, it erases the contents of the directory on exit.
"""
def __enter__(self) -> "TempDirectoryPath":
return self
def __exit__(
self,
_exc: Optional[Type[BaseException]],
_value: Optional[Exception],
_tb: Optional[TracebackType],
) -> bool:
if os.path.exists(self):
shutil.rmtree(self)
def read_global_config(path: Text) -> Dict[Text, Any]:
"""Read global Rasa configuration.
Args:
path: Path to the configuration
Returns:
The global configuration
"""
# noinspection PyBroadException
try:
return rasa.shared.utils.io.read_config_file(path)
except Exception:
# if things go south we pretend there is no config
return {}
def set_log_level(log_level: Optional[int] = None):
"""Set log level of Rasa and Tensorflow either to the provided log level or
to the log level specified in the environment variable 'LOG_LEVEL'. If none is set
a default log level will be used."""
if not log_level:
log_level = os.environ.get(ENV_LOG_LEVEL, DEFAULT_LOG_LEVEL)
log_level = logging.getLevelName(log_level)
logging.getLogger("rasa").setLevel(log_level)
update_tensorflow_log_level()
update_asyncio_log_level()
update_apscheduler_log_level()
update_socketio_log_level()
os.environ[ENV_LOG_LEVEL] = logging.getLevelName(log_level)
def update_apscheduler_log_level() -> None:
log_level = os.environ.get(ENV_LOG_LEVEL_LIBRARIES, DEFAULT_LOG_LEVEL_LIBRARIES)
apscheduler_loggers = [
"apscheduler",
"apscheduler.scheduler",
"apscheduler.executors",
"apscheduler.executors.default",
]
for logger_name in apscheduler_loggers:
logging.getLogger(logger_name).setLevel(log_level)
logging.getLogger(logger_name).propagate = False
def update_socketio_log_level() -> None:
log_level = os.environ.get(ENV_LOG_LEVEL_LIBRARIES, DEFAULT_LOG_LEVEL_LIBRARIES)
socketio_loggers = ["websockets.protocol", "engineio.server", "socketio.server"]
for logger_name in socketio_loggers:
logging.getLogger(logger_name).setLevel(log_level)
logging.getLogger(logger_name).propagate = False
def update_tensorflow_log_level() -> None:
"""Set the log level of Tensorflow to the log level specified in the environment
variable 'LOG_LEVEL_LIBRARIES'."""
# Disables libvinfer, tensorRT, cuda, AVX2 and FMA warnings (CPU support). This variable needs to be set before the
# first import since some warnings are raised on the first import.
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import tensorflow as tf
log_level = os.environ.get(ENV_LOG_LEVEL_LIBRARIES, DEFAULT_LOG_LEVEL_LIBRARIES)
if log_level == "DEBUG":
tf_log_level = tf.compat.v1.logging.DEBUG
elif log_level == "INFO":
tf_log_level = tf.compat.v1.logging.INFO
elif log_level == "WARNING":
tf_log_level = tf.compat.v1.logging.WARN
else:
tf_log_level = tf.compat.v1.logging.ERROR
tf.compat.v1.logging.set_verbosity(tf_log_level)
logging.getLogger("tensorflow").propagate = False
def update_sanic_log_level(log_file: Optional[Text] = None):
"""Set the log level of sanic loggers to the log level specified in the environment
variable 'LOG_LEVEL_LIBRARIES'."""
from sanic.log import logger, error_logger, access_logger
log_level = os.environ.get(ENV_LOG_LEVEL_LIBRARIES, DEFAULT_LOG_LEVEL_LIBRARIES)
logger.setLevel(log_level)
error_logger.setLevel(log_level)
access_logger.setLevel(log_level)
logger.propagate = False
error_logger.propagate = False
access_logger.propagate = False
if log_file is not None:
formatter = logging.Formatter("%(asctime)s [%(levelname)-5.5s] %(message)s")
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
error_logger.addHandler(file_handler)
access_logger.addHandler(file_handler)
def update_asyncio_log_level() -> None:
"""Set the log level of asyncio to the log level specified in the environment
variable 'LOG_LEVEL_LIBRARIES'."""
log_level = os.environ.get(ENV_LOG_LEVEL_LIBRARIES, DEFAULT_LOG_LEVEL_LIBRARIES)
logging.getLogger("asyncio").setLevel(log_level)
def set_log_and_warnings_filters() -> None:
"""
Set log filters on the root logger, and duplicate filters for warnings.
Filters only propagate on handlers, not loggers.
"""
for handler in logging.getLogger().handlers:
handler.addFilter(RepeatedLogFilter())
warnings.filterwarnings("once", category=UserWarning)
def obtain_verbosity() -> int:
"""Returns a verbosity level according to the set log level."""
log_level = os.environ.get(ENV_LOG_LEVEL, DEFAULT_LOG_LEVEL)
verbosity = 0
if log_level == "DEBUG":
verbosity = 2
if log_level == "INFO":
verbosity = 1
return verbosity
def sort_list_of_dicts_by_first_key(dicts: List[Dict]) -> List[Dict]:
"""Sorts a list of dictionaries by their first key."""
return sorted(dicts, key=lambda d: list(d.keys())[0])
def write_global_config_value(name: Text, value: Any) -> None:
"""Read global Rasa configuration."""
# need to use `rasa.constants.GLOBAL_USER_CONFIG_PATH` to allow patching
# in tests
config_path = rasa.constants.GLOBAL_USER_CONFIG_PATH
try:
os.makedirs(os.path.dirname(config_path), exist_ok=True)
c = read_global_config(config_path)
c[name] = value
rasa.core.utils.dump_obj_as_yaml_to_file(
rasa.constants.GLOBAL_USER_CONFIG_PATH, c
)
except Exception as e:
logger.warning(f"Failed to write global config. Error: {e}. Skipping.")
def read_global_config_value(name: Text, unavailable_ok: bool = True) -> Any:
"""Read a value from the global Rasa configuration."""
def not_found():
if unavailable_ok:
return None
else:
raise ValueError(f"Configuration '{name}' key not found.")
# need to use `rasa.constants.GLOBAL_USER_CONFIG_PATH` to allow patching
# in tests
config_path = rasa.constants.GLOBAL_USER_CONFIG_PATH
if not os.path.exists(config_path):
return not_found()
c = read_global_config(config_path)
if name in c:
return c[name]
else:
return not_found()
def update_existing_keys(
original: Dict[Any, Any], updates: Dict[Any, Any]
) -> Dict[Any, Any]:
"""Iterate through all the updates and update a value in the original dictionary.
If the updates contain a key that is not present in the original dict, it will
be ignored."""
updated = original.copy()
for k, v in updates.items():
if k in updated:
updated[k] = v
return updated
class RepeatedLogFilter(logging.Filter):
"""Filter repeated log records."""
last_log = None
def filter(self, record):
current_log = (
record.levelno,
record.pathname,
record.lineno,
record.msg,
record.args,
)
if current_log != self.last_log:
self.last_log = current_log
return True
return False
def run_in_loop(
f: Coroutine[Any, Any, T], loop: Optional[asyncio.AbstractEventLoop] = None
) -> T:
"""Execute the awaitable in the passed loop.
If no loop is passed, the currently existing one is used or a new one is created
if no loop has been started in the current context.
After the awaitable is finished, all remaining tasks on the loop will be
awaited as well (background tasks).
WARNING: don't use this if there are never ending background tasks scheduled.
in this case, this function will never return.
Args:
f: function to execute
loop: loop to use for the execution
Returns:
return value from the function
"""
if loop is None:
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
result = loop.run_until_complete(f)
# Let's also finish all running tasks:
pending = asyncio.Task.all_tasks()
loop.run_until_complete(asyncio.gather(*pending))
return result
| rasa/utils/common.py | 9,003 | Filter repeated log records.
Represents a path to an temporary directory. When used as a context
manager, it erases the contents of the directory on exit.
Returns a verbosity level according to the set log level.
Read global Rasa configuration.
Args:
path: Path to the configuration
Returns:
The global configuration
Read a value from the global Rasa configuration.
Execute the awaitable in the passed loop.
If no loop is passed, the currently existing one is used or a new one is created
if no loop has been started in the current context.
After the awaitable is finished, all remaining tasks on the loop will be
awaited as well (background tasks).
WARNING: don't use this if there are never ending background tasks scheduled.
in this case, this function will never return.
Args:
f: function to execute
loop: loop to use for the execution
Returns:
return value from the function
Set log filters on the root logger, and duplicate filters for warnings.
Filters only propagate on handlers, not loggers.
Set log level of Rasa and Tensorflow either to the provided log level or
to the log level specified in the environment variable 'LOG_LEVEL'. If none is set
a default log level will be used.
Sorts a list of dictionaries by their first key.
Set the log level of asyncio to the log level specified in the environment
variable 'LOG_LEVEL_LIBRARIES'.
Iterate through all the updates and update a value in the original dictionary.
If the updates contain a key that is not present in the original dict, it will
be ignored.
Set the log level of sanic loggers to the log level specified in the environment
variable 'LOG_LEVEL_LIBRARIES'.
Set the log level of Tensorflow to the log level specified in the environment
variable 'LOG_LEVEL_LIBRARIES'.
Read global Rasa configuration.
noinspection PyBroadException if things go south we pretend there is no config Disables libvinfer, tensorRT, cuda, AVX2 and FMA warnings (CPU support). This variable needs to be set before the first import since some warnings are raised on the first import. need to use `rasa.constants.GLOBAL_USER_CONFIG_PATH` to allow patching in tests need to use `rasa.constants.GLOBAL_USER_CONFIG_PATH` to allow patching in tests Let's also finish all running tasks: | 2,258 | en | 0.826978 |
"""
ECB没有偏移量
"""
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
from utils import DES_decrypt, DES_encrypt
def add_to_16(text):
if len(text.encode('utf-8')) % 16:
add = 16 - (len(text.encode('utf-8')) % 16)
else:
add = 0
text = text + ('\0' * add)
return text.encode('utf-8')
# 加密函数
def encrypt(text):
key = '9999999999999999'.encode('utf-8')
mode = AES.MODE_ECB
text = add_to_16(text)
cryptos = AES.new(key, mode)
cipher_text = cryptos.encrypt(text)
return b2a_hex(cipher_text)
# 解密后,去掉补足的空格用strip() 去掉
def decrypt(text):
key = '9999999999999999'.encode('utf-8')
mode = AES.MODE_ECB
cryptor = AES.new(key, mode)
plain_text = cryptor.decrypt(a2b_hex(text))
return bytes.decode(plain_text).rstrip('\0')
if __name__ == '__main__':
e = DES_encrypt("hello world") # 加密
print(type(e))
d = DES_decrypt(e) # 解密
print("加密:", e)
print("解密:", d) | try.py | 1,024 | ECB没有偏移量
加密函数 解密后,去掉补足的空格用strip() 去掉 加密 解密 | 44 | zh | 0.980871 |
"""This module contains the general information for ChassisPowerMonitor ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class ChassisPowerMonitorConsts:
pass
class ChassisPowerMonitor(ManagedObject):
"""This is ChassisPowerMonitor class."""
consts = ChassisPowerMonitorConsts()
naming_props = set([])
mo_meta = {
"modular": MoMeta("ChassisPowerMonitor", "chassisPowerMonitor", "pwrmonitor", VersionMeta.Version2013e, "OutputOnly", 0xf, [], ["admin", "read-only", "user"], ['equipmentChassis'], [], ["Get"])
}
prop_meta = {
"modular": {
"average": MoPropertyMeta("average", "average", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_ONLY, None, None, None, None, [], []),
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version2013e, MoPropertyMeta.INTERNAL, None, None, None, None, [], []),
"current": MoPropertyMeta("current", "current", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_ONLY, None, None, None, None, [], []),
"dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_ONLY, 0x2, 0, 255, None, [], []),
"maximum": MoPropertyMeta("maximum", "maximum", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_ONLY, None, None, None, None, [], []),
"minimum": MoPropertyMeta("minimum", "minimum", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_ONLY, None, None, None, None, [], []),
"period": MoPropertyMeta("period", "period", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_ONLY, None, None, None, None, [], []),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_ONLY, 0x4, 0, 255, None, [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_ONLY, 0x8, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []),
},
}
prop_map = {
"modular": {
"average": "average",
"childAction": "child_action",
"current": "current",
"dn": "dn",
"maximum": "maximum",
"minimum": "minimum",
"period": "period",
"rn": "rn",
"status": "status",
},
}
def __init__(self, parent_mo_or_dn, **kwargs):
self._dirty_mask = 0
self.average = None
self.child_action = None
self.current = None
self.maximum = None
self.minimum = None
self.period = None
self.status = None
ManagedObject.__init__(self, "ChassisPowerMonitor", parent_mo_or_dn, **kwargs)
| imcsdk/mometa/chassis/ChassisPowerMonitor.py | 2,870 | This is ChassisPowerMonitor class.
This module contains the general information for ChassisPowerMonitor ManagedObject. | 118 | en | 0.748867 |
"""
FILE : BiLSTM.py
FUNCTION : None
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import random
from DataUtils.Common import *
from models.initialize import *
from models.modelHelp import prepare_pack_padded_sequence
torch.manual_seed(seed_num)
random.seed(seed_num)
class BiLSTM(nn.Module):
"""
BiLSTM
"""
def __init__(self, **kwargs):
super(BiLSTM, self).__init__()
for k in kwargs:
self.__setattr__(k, kwargs[k])
V = self.embed_num
D = self.embed_dim
C = self.label_num
paddingId = self.paddingId
self.embed = nn.Embedding(V, D, padding_idx=paddingId)
if self.pretrained_embed:
self.embed.weight.data.copy_(self.pretrained_weight)
else:
init_embedding(self.embed.weight)
self.dropout_embed = nn.Dropout(self.dropout_emb)
self.dropout = nn.Dropout(self.dropout)
self.bilstm = nn.LSTM(input_size=D, hidden_size=self.lstm_hiddens, num_layers=self.lstm_layers,
bidirectional=True, batch_first=True, bias=True)
self.linear = nn.Linear(in_features=self.lstm_hiddens * 2, out_features=C, bias=True)
init_linear(self.linear)
def forward(self, word, sentence_length):
"""
:param word:
:param sentence_length:
:param desorted_indices:
:return:
"""
word, sentence_length, desorted_indices = prepare_pack_padded_sequence(word, sentence_length, device=self.device)
x = self.embed(word) # (N,W,D)
x = self.dropout_embed(x)
packed_embed = pack_padded_sequence(x, sentence_length, batch_first=True)
x, _ = self.bilstm(packed_embed)
x, _ = pad_packed_sequence(x, batch_first=True)
x = x[desorted_indices]
x = self.dropout(x)
x = torch.tanh(x)
logit = self.linear(x)
return logit
class BiLSTM(nn.Module):
def __init__(self, vocab_size, emb_size, hidden_size, out_size):
""":
vocab_size:
emb_size:
hidden_size:
out_size:
"""
super(BiLSTM, self).__init__()
self.embedding = nn.Embedding(vocab_size, emb_size)
self.bilstm = nn.LSTM(emb_size, hidden_size,
batch_first=True,
bidirectional=True)
self.lin = nn.Linear(2*hidden_size, out_size)
def forward(self, sents_tensor, lengths):
emb = self.embedding(sents_tensor) # [B, L, emb_size]
packed = pack_padded_sequence(emb, lengths, batch_first=True)
rnn_out, _ = self.bilstm(packed)
# rnn_out:[B, L, hidden_size*2]
rnn_out, _ = pad_packed_sequence(rnn_out, batch_first=True)
scores = self.lin(rnn_out) # [B, L, out_size]
return scores
def test(self, sents_tensor, lengths, _):
logits = self.forward(sents_tensor, lengths) # [B, L, out_size]
_, batch_tagids = torch.max(logits, dim=2)
return batch_tagids
| models/BiLSTM.py | 3,155 | BiLSTM
:
vocab_size:
emb_size:
hidden_size:
out_size:
:param word:
:param sentence_length:
:param desorted_indices:
:return:
FILE : BiLSTM.py
FUNCTION : None
(N,W,D) [B, L, emb_size] rnn_out:[B, L, hidden_size*2] [B, L, out_size] [B, L, out_size] | 249 | en | 0.362757 |
'''
@author: kris
'''
# import modules; set up logging
from gensim.models import Word2Vec
from gensim.models import KeyedVectors
from gensim.test.utils import datapath
import numpy as np
import logging, os, sys, gzip
import datetime
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', filename='word2vec.out', level=logging.INFO)
# Path to a file that contains lines with the locations of files
# containing the sentences we want for our Word2Vec model
# Also works with entities that are just stacked line by line
pathsLocator = "./sentencesPaths.txt"
outputPath = "./entity_embeddings.txt"
# Model to load
to_load = '/vol2/cb/crunchbase-201806/embeddings/dim200-iter10-win5/CB_sg1_size200_mincount1_window5_neg15_iter10.wv.vectors.npy'
#'/home/faerberm/mag-training/MAG_sg1_size128_minCount5_window5_neg15_iter10_alpha_cbowMean.wv.vectors.npy'
#'/vol2/cb/crunchbase-201806/embeddings/dim200-iter10-win5/CB_sg1_size200_mincount1_window5_neg15_iter10'
#'MAG_sg1_size128_minCount5_window5_neg15_iter5'
loadKeyedVector = True
#'dbpedia_sg1_size200_mincount1_window5_neg15_iter10'
#'RDF2Vec_sg1_size200_mincount1_window5_neg15_iter20'
#'MAG_sg1_size200_mincount1_window5_neg15_iter15'
#What is the newline character on the machine
newline = '\n'
ignorePrefix = '#'
#What separates one walk from another (aka. one sentence from another)?
walkSeparator = "\t"
#What separates the single 'units' of a given walk?
hopSeparator = '->'
# Mapping dict
entity_mapping_dict = {}
# Mapping file
mapping_file = "/home/noulletk/prog/bmw/dbpedia_full/resources/data/walks/walk_entity_mapping.txt"
mapping_sep = "\t"
hasMapping = False
iterationCounter = {'val': 0}
#Load mappings if there are any
if hasMapping:
for mapping_line in open(mapping_file, mode='rt'):
mapping_tokens = mapping_line.rstrip(newline).split(mapping_sep)
if len(mapping_tokens) == 2:
entity_mapping_dict[mapping_tokens[0]] = mapping_tokens[1]
print("Loaded %s mappings!" % (len(entity_mapping_dict)))
class MySentences:
def __init__(self, iterationCounter):
self.iterationCounter = iterationCounter
def __iter__(self):
print("Running Iteration #%s" % (iterationCounter['val']))
iterationCounter['val'] += 1
# Iterate to find which files are to be read
for fname in open(pathsLocator, mode='rt'): # os.listdir(self.dirname):
sentencesPath = fname.rstrip(newline)
# Ignore commented-out lines
if sentencesPath.startswith(ignorePrefix):
continue
now = datetime.datetime.now()
print("[%s] Grabbing sentences from: %s" % (now.strftime("%Y-%m-%d %H:%M"), sentencesPath))
try:
# Go through all paths
for line in open(sentencesPath, mode='rt'):
# If you're NOT grouping the walks and separating them by tabs
sentence = line.rstrip(newline).split(hopSeparator)
for tokenPos in range(len(sentence)):
token = sentence[tokenPos]
# Give the proper URL for the entity IF it exists, otherwise return the entity itself
sentence[tokenPos] = entity_mapping_dict.get(token, token)
#print(sentence)
yield sentence
except Exception:
print("Failed reading file:")
print(sentencesPath)
#load model
if loadKeyedVector:
print("Loading [KeyedVectors] from: ",to_load)
#model_wv = KeyedVectors.load(to_load, mmap='r')
#model_wv = KeyedVectors.load_word2vec_format(to_load, binary=True)
#model_wv = KeyedVectors.load_word2vec_format(to_load)
model_wv = KeyedVectors.load(to_load)
#model_wv = KeyedVectors.load_word2vec_format(datapath('word2vec_pre_kv_c'), binary=False) # C text format
#model_wv = KeyedVectors.load_word2vec_format(to_load, binary=True, unicode_errors='ignore')
else:
print("Loading [MODEL] from: ",to_load)
model_wv = Word2Vec.load(to_load).wv
print("Vocab keys size:",len(model_wv.vocab.keys()))
print("Outputting entity embeddings to: ",outputPath)
sentences = MySentences(iterationCounter)
#Open the output file for the entity embeddings
outFile = open(outputPath, "w")
#Make a dictionary for in-memory aggregation while going over sentences
default_val = None
entity_embeddings_dict = {}
vocab_keys = model_wv.vocab.keys()
displayCounter = 0
maxDisplay = 10
for voc in vocab_keys:
print(voc)
if displayCounter >= maxDisplay:
break
displayCounter+=1
print("Compute entity embeddings (through combination of word embeddings)...")
counter = 0
'''
for sentence in sentences:
entity = sentence[0]
entity_embedding = None
#Sum over all words' embeddings and then output the resulting embedding
for word in sentence:
word_embedding = model.wv[word]
if default_val is None:
#Initialise default_val if it isn't yet
default_val = np.zeros(word_embedding.shape)
if entity_embedding is None:
entity_embedding = np.zeros(word_embedding.shape)
entity_embedding += word_embedding
entity_embeddings_dict[entity] = entity_embeddings_dict.get(entity, default_val) + entity_embedding
if (counter % 1000000 == 0):
print("Combined word embeddings: ",counter)
print("Last one completed: ",entity)
counter+=1
'''
#Go through all sentences to see which entities we want
for sentence in sentences:
# idea is that the entity is in the document, so we check what it is like and
# since every entity has 'the same' treatment, that we can determine their probabilities based on that
entity = sentence[0]
if hasMapping:
entity = entity_mapping_dict.get(entity, entity)
entity_embedding = None
dict_val = entity_embeddings_dict.get(entity, None)
if (dict_val is None):
if entity in vocab_keys:
entity_embedding = model_wv[entity]
entity_embeddings_dict[entity] = entity_embedding
#Encountered first time, so output it
outFile.write("%s" % entity)
for number in entity_embedding:
outFile.write("\t%s" % number)
outFile.write("\n")
if (counter % 1000000 == 0):
print("Lines passed through: ",counter)
print("Current line's entity: ",entity)
print("Embeddings output: ",len(entity_embeddings_dict))
counter+=1
#print("Output computed entity embeddings!")
#for (entity, entity_embedding) in entity_embeddings_dict.items():
# #Output computed embedding
# outFile.write("%s" % entity)
# for number in entity_embedding:
# outFile.write("\t%s" % number)
# outFile.write("\n")
#Close the output file post finishing output operations
outFile.close()
print("Finished outputting entity embeddings")
| scripts/loadModelDoEntityEmbeddingsUnsorted.py | 6,357 | @author: kris
import modules; set up logging Path to a file that contains lines with the locations of files containing the sentences we want for our Word2Vec model Also works with entities that are just stacked line by line Model to load'/home/faerberm/mag-training/MAG_sg1_size128_minCount5_window5_neg15_iter10_alpha_cbowMean.wv.vectors.npy''/vol2/cb/crunchbase-201806/embeddings/dim200-iter10-win5/CB_sg1_size200_mincount1_window5_neg15_iter10''MAG_sg1_size128_minCount5_window5_neg15_iter5''dbpedia_sg1_size200_mincount1_window5_neg15_iter10''RDF2Vec_sg1_size200_mincount1_window5_neg15_iter20''MAG_sg1_size200_mincount1_window5_neg15_iter15'What is the newline character on the machineWhat separates one walk from another (aka. one sentence from another)?What separates the single 'units' of a given walk? Mapping dict Mapping fileLoad mappings if there are any Iterate to find which files are to be read os.listdir(self.dirname): Ignore commented-out lines Go through all paths If you're NOT grouping the walks and separating them by tabs Give the proper URL for the entity IF it exists, otherwise return the entity itselfprint(sentence)load modelmodel_wv = KeyedVectors.load(to_load, mmap='r')model_wv = KeyedVectors.load_word2vec_format(to_load, binary=True)model_wv = KeyedVectors.load_word2vec_format(to_load)model_wv = KeyedVectors.load_word2vec_format(datapath('word2vec_pre_kv_c'), binary=False) C text formatmodel_wv = KeyedVectors.load_word2vec_format(to_load, binary=True, unicode_errors='ignore') Open the output file for the entity embeddingsMake a dictionary for in-memory aggregation while going over sentencesGo through all sentences to see which entities we want idea is that the entity is in the document, so we check what it is like and since every entity has 'the same' treatment, that we can determine their probabilities based on thatEncountered first time, so output itprint("Output computed entity embeddings!")for (entity, entity_embedding) in entity_embeddings_dict.items(): Output computed embedding outFile.write("%s" % entity) for number in entity_embedding: outFile.write("\t%s" % number) outFile.write("\n")Close the output file post finishing output operations | 2,206 | en | 0.763448 |
"""inter-base steganography
producing base32 and base64 decodable strings"""
from base64 import b64encode, b64decode
import string
from itertools import product
from argparse import ArgumentParser
CHARSET = string.printable.encode()
B32_CHARSET = (string.ascii_uppercase + '234567').encode()
B64_CHARSET = (
string.ascii_lowercase +
string.ascii_uppercase +
string.digits +
'+/').encode()
ASCII_LOWER = string.ascii_lowercase.encode()
WHITESPACE = string.whitespace.encode()
ALPHA_SPACE = (
string.ascii_uppercase +
string.ascii_lowercase +
string.whitespace).encode()
ASCII_SUBS = {"a": ["a", "A", "4", "@"],
"b": ["b", "B", "8", "6"],
"c": ["c", "C", "("],
"d": ["d", "D"],
"e": ["e", "E", "3"],
"f": ["f", "F"],
"g": ["g", "G", "6", "9"],
"h": ["h", "H", "#"],
"i": ["i", "I", "1", "|", "!"],
"j": ["j", "J", "]", ";"],
"k": ["k", "K"],
"l": ["l", "L", "1", "|"],
"m": ["m", "M"],
"n": ["n", "N"],
"o": ["o", "O", "0"],
"p": ["p", "P"],
"q": ["q", "Q", "9"],
"r": ["r", "R", "2"],
"s": ["s", "S", "5", "$"],
"t": ["t", "T", "7", "+"],
"u": ["u", "U"],
"v": ["v", "V"],
"w": ["w", "W"],
"x": ["x", "X"],
"y": ["y", "Y"],
"z": ["z", "Z", "2", "%"],
"0": ["0"],
"1": ["1"],
"2": ["2"],
"3": ["3"],
"4": ["4"],
"5": ["5"],
"6": ["6"],
"7": ["7"],
"8": ["8"],
"9": ["9"],
" ": [" ", "\t", "_"]
}
def all_variations(word: str) -> list:
"""
Produce all single-character leet variations of a string
"""
ans = [""]
for leet_letter in [ASCII_SUBS[i] for i in word]:
ans = [x + y for x in ans for y in leet_letter]
return ans
def variation_gen(word: str):
"""
Produces all single-character leet variations of a string
Args:
word: a 3 character string to generate all variations
Returns:
generator: generator for all possible leet variations
"""
return product(*(ASCII_SUBS[i] for i in word))
def all_valid_variations(word: str) -> list:
"""
Returns all leet variations of a triplet which result in a
Base32 only charset words on base64 encoding
Args:
word: An english triplet
Returns:
list: of all valid variations
"""
result = []
for variation in variation_gen(word):
if all(i in B32_CHARSET for i in b64encode(
''.join(variation).encode())):
result.append("".join(variation))
return result
def valid_variation(word: str) -> str:
"""
Generates a single valid variation
Args:
word: the triplet to generate a variation from
Returns:
str: A valid variation of `word` or None otherwise
"""
for variation in variation_gen(word):
if all(i in B32_CHARSET for i in b64encode(
''.join(variation).encode())):
return "".join(variation)
return None
# List to precompute the triplets for which there doesnt exist a valid
# variation
NON_LEET = []
for perm in product(string.ascii_lowercase + ' ' + string.digits, repeat=3):
if not valid_variation(''.join(perm)):
NON_LEET.append(''.join(perm))
def transform(strng: str) -> str:
"""
Transform the string to only lower alpha and numerics and spaces
Converts uppercase to lower case and strips all other characters except
space
"""
for char in string.punctuation + string.whitespace[1:]:
strng = strng.replace(char, '')
return strng.lower() + ' ' * (8 - len(strng) % 8)
def master_encode(strng: str) -> bytes:
"""
Encodes a string to its leet equivalent (sans punctuation) which when
base64 encoded contains only base32 characters
"""
if isinstance(strng, (bytes, bytearray)):
strng = strng.decode()
strng = transform(strng)
result = ''
i = 0
while i < len(strng):
try:
current = strng[i:i + 3]
if current in NON_LEET:
if current[:2] + ' ' not in NON_LEET:
result += valid_variation(current[:2] + ' ')
i += 2
elif current[0] + ' ' not in NON_LEET:
result += valid_variation(current[0] + ' ')
i += 1
elif ' {} '.format(current[0]) not in NON_LEET:
result += valid_variation(' {} '.format(current[0]))
i += 1
elif ' {}'.format(current[0]) not in NON_LEET:
result += valid_variation(' {}'.format(current[0]))
i += 1
else:
i += 1
else:
result += valid_variation(current)
i += 3
except TypeError:
i += 1
return b64encode(result.encode())
if __name__ == "__main__":
PARSER = ArgumentParser(description="")
PARSER.add_argument(
'--input',
help='read a single line directly from input',
action="store_true")
PARSER.add_argument(
'--show',
help='shows the transformed input which results in correct encoding',
action="store_true")
PARSER.add_argument(
'--file',
help='reading text from file for conversion',
action="append")
ARGS = PARSER.parse_args()
TEST_STRING = """Steganography is the practice of concealing a file,
message, image, or video within another file, message, image, or video.
The word steganography comes from Greek steganographia, which combines
the words steganos meaning "covered or concealed", and graphia meaning
"writing". The first recorded use of the term was by Johannes Trithemius
in his Steganographia, a treatise on cryptography and steganography,
disguised as a book on magic. Generally, the hidden messages appear to
be (or to be part of) something else: images, articles, shopping lists,
or some other cover text. For example, the hidden message may be in
invisible ink between the visible lines of a private letter. Some
implementations of steganography that lack a shared secret are forms
of security through obscurity, and key-dependent steganographic schemes
adhere to Kerckhoffs's principle."""
if ARGS.file:
with open(ARGS.file[0], 'rb') as inp_file:
TEST_STRING = inp_file.read()
else:
TEST_STRING = input("input the line to encode:\n")
ENCODED_STRING = master_encode(TEST_STRING)
print("ENCODED STRING: {}".format(ENCODED_STRING))
if ARGS.show:
print("Transformed string: {}".format(b64decode(ENCODED_STRING)))
# WTBVICAJV2VSZSBFWHBFY3RJIG4JOSBGTGFHNSBCVXQJYTFMICAJWTBVIDZFVCBJNSB3ZTFS\
# ZCBCYXNFNSBCYSAJTWJPMDJMZSAJTWVOVCBET25UICAJICB3T3JSWSBJVHMJIGYJVW4JIG4JZXZ\
# FIHIJVCNFTGVTNSAJ
| encode.py | 7,222 | Returns all leet variations of a triplet which result in a
Base32 only charset words on base64 encoding
Args:
word: An english triplet
Returns:
list: of all valid variations
Produce all single-character leet variations of a string
Encodes a string to its leet equivalent (sans punctuation) which when
base64 encoded contains only base32 characters
Transform the string to only lower alpha and numerics and spaces
Converts uppercase to lower case and strips all other characters except
space
Generates a single valid variation
Args:
word: the triplet to generate a variation from
Returns:
str: A valid variation of `word` or None otherwise
Produces all single-character leet variations of a string
Args:
word: a 3 character string to generate all variations
Returns:
generator: generator for all possible leet variations
inter-base steganography
producing base32 and base64 decodable strings
List to precompute the triplets for which there doesnt exist a valid variation WTBVICAJV2VSZSBFWHBFY3RJIG4JOSBGTGFHNSBCVXQJYTFMICAJWTBVIDZFVCBJNSB3ZTFS\ ZCBCYXNFNSBCYSAJTWJPMDJMZSAJTWVOVCBET25UICAJICB3T3JSWSBJVHMJIGYJVW4JIG4JZXZ\ FIHIJVCNFTGVTNSAJ | 1,168 | en | 0.565786 |
#!/usr/bin/python3
import time
import datetime
from gpiozero import InputDevice, LED
import subprocess
import requests
# RPI enumeration is:
# pin 5 & 6 are used for the button (3 & ground)
# pin 7 & 9 are used for the LED (4 & ground)
button_pin = 3
led_pin = 4
button = InputDevice(button_pin, pull_up=True)
last_active = False
last_press = None
led = LED(led_pin)
led.on()
def button_hold(now, seconds):
if seconds > 3:
print('button hold')
led.blink(.05, .5)
requests.get('http://localhost:8080/home')
time.sleep(2)
subprocess.call(['shutdown', '-h', 'now'], shell=False)
def button_release(now, seconds):
print('button release')
requests.get('http://localhost:8080/button')
while True:
cur_active = button.is_active
now = datetime.datetime.now()
if cur_active and not last_active:
last_press = now
if cur_active:
duration = now - last_press
button_hold(now, duration.total_seconds())
if not cur_active and last_active:
duration = now - last_press
button_release(now, duration.total_seconds())
last_active = cur_active
time.sleep(1/60) | pi/button/button.py | 1,171 | !/usr/bin/python3 RPI enumeration is: pin 5 & 6 are used for the button (3 & ground) pin 7 & 9 are used for the LED (4 & ground) | 128 | en | 0.817168 |
import argparse
import torch
from tqdm import tqdm
import vgg.data_loader.data_loaders as module_data
import vgg.model.loss as module_loss
import vgg.model.metric as module_metric
import vgg.model.model as module_arch
from vgg.parse_config import ConfigParser
def main(config):
logger = config.get_logger('test')
# setup data_loader instances
data_loader = getattr(module_data, config['data_loader']['type'])(
config['data_loader']['args']['data_dir'],
batch_size=512,
shuffle=False,
validation_split=0.0,
training=False,
num_workers=2
)
# build model architecture
model = config.init_obj('arch', module_arch)
logger.info(model)
# get function handles of loss and metrics
loss_fn = getattr(module_loss, config['loss'])
metric_fns = [getattr(module_metric, met) for met in config['metrics']]
logger.info('Loading checkpoint: {} ...'.format(config.resume))
checkpoint = torch.load(config.resume)
state_dict = checkpoint['state_dict']
if config['n_gpu'] > 1:
model = torch.nn.DataParallel(model)
model.load_state_dict(state_dict)
# prepare model for testing
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = model.to(device)
model.eval()
total_loss = 0.0
total_metrics = torch.zeros(len(metric_fns))
with torch.no_grad():
for i, (data, target) in enumerate(tqdm(data_loader)):
data, target = data.to(device), target.to(device)
output = model(data)
#
# save sample images, or do something with output here
#
# computing loss, metrics on test set
loss = loss_fn(output, target)
batch_size = data.shape[0]
total_loss += loss.item() * batch_size
for i, metric in enumerate(metric_fns):
total_metrics[i] += metric(output, target) * batch_size
n_samples = len(data_loader.sampler)
log = {'loss': total_loss / n_samples}
log.update({
met.__name__: total_metrics[i].item() / n_samples for i, met in enumerate(metric_fns)
})
logger.info(log)
if __name__ == '__main__':
args = argparse.ArgumentParser(description='PyTorch Template')
args.add_argument('-c', '--config', default=None, type=str,
help='config file path (default: None)')
args.add_argument('-r', '--resume', default=None, type=str,
help='path to latest checkpoint (default: None)')
args.add_argument('-d', '--device', default=None, type=str,
help='indices of GPUs to enable (default: all)')
config = ConfigParser.from_args(args)
main(config)
| vgg/test.py | 2,740 | setup data_loader instances build model architecture get function handles of loss and metrics prepare model for testing save sample images, or do something with output here computing loss, metrics on test set | 208 | en | 0.799659 |
import os
import argparse
from ops.os_operation import mkdir
import time
def write_slurm_sh_multi_H2(id,command_line, queue_name="learnfair",nodes=1,
gpu_per_node=8,wall_time=3*24*60,username="wang3702",CPU_PER_GPU=8):
import time
import datetime
today = datetime.date.today()
formatted_today = today.strftime('%y%m%d')
now = time.strftime("%H:%M:%S")
dependency_handler_path = os.path.join(os.getcwd(), "ops")
dependency_handler_path = os.path.join(dependency_handler_path, "handler.txt")
run_path = os.path.join(os.getcwd(), "log")
mkdir(run_path)
run_path = os.path.abspath(run_path)
prefix = "node%d_gpu%d"%(nodes,gpu_per_node)
batch_file = os.path.join(run_path, prefix+"slurm_job_" + str(id) + ".sh")
output_path = os.path.join(run_path, prefix+"output_" + str(id) + "_" + str(formatted_today + now) + ".log")
error_path = os.path.join(run_path, prefix+"error_" + str(id) + "_" + str(formatted_today + now) + ".log")
with open(batch_file, "w") as file:
file.write("#! /bin/bash\n")#!/bin/bash
file.write("#SBATCH --job-name=%s\n" % id)
file.write("#SBATCH --output=%s\n" % output_path)
file.write("#SBATCH --error=%s\n" % error_path)
file.write("#SBATCH --partition=%s\n"%queue_name)
file.write("#SBATCH --signal=USR1@600\n")
file.write("#SBATCH --nodes=%d\n" % nodes)
file.write("#SBATCH --ntasks-per-node=%d\n" % 1)
file.write("#SBATCH --mem=%dG\n"%(350/8*gpu_per_node))
file.write("#SBATCH --gpus=%d\n" % (nodes * gpu_per_node))
file.write("#SBATCH --gpus-per-node=%d\n" % (gpu_per_node))
file.write("#SBATCH --cpus-per-task=%d\n"%(CPU_PER_GPU*gpu_per_node))
file.write("#SBATCH --time=%d\n"%wall_time)
file.write("#SBATCH --mail-user=%s@fb.com\n"%username)
file.write("#SBATCH --mail-type=FAIL\n")
file.write("#SBATCH --mail-type=end \n")
file.write('#SBATCH --constraint="volta"\n')
report_info = "%s job failed; \t" % id
report_info += "log path: %s; \t" % output_path
report_info += "error record path: %s\t" % error_path
report_info += "command line path: %s\t" % batch_file
file.write('#SBATCH --comment="%s"\n' % (report_info))
with open(dependency_handler_path, 'r') as rfile:
line = rfile.readline()
while line:
file.write(line)
line = rfile.readline()
file.write("export GLOO_SOCKET_IFNAME=\nexport NCCL_SOCKET_IFNAME=\n")
file.write("module load cuda/10.2 cudnn/v7.6.5.32-cuda.10.2 gcc/7.3.0\n")
#file.write("bash /private/home/wang3702/.bashrc\n")
#file.write("module load anaconda3\n")
file.write("/private/home/wang3702/anaconda3/bin/conda init\n")
file.write("CONDA_BASE=$(conda info --base) ; source $CONDA_BASE/etc/profile.d/conda.sh\n")
file.write("conda activate pytorch2\n")
file.write("master_node=${SLURM_NODELIST:0:9}${SLURM_NODELIST:10:4}\n")
file.write('dist_url="tcp://"\n')
file.write("dist_url+=$master_node\n")
file.write("dist_url+=:40000\n")
file.write("export MASTER_ADDR=${SLURM_NODELIST:0:9}${SLURM_NODELIST:10:4}\n")
file.write("export MASTER_PORT=29500\n")
file.write("srun --label "+command_line + " --slurm=1 --dist_url=$dist_url &\n")
file.write("wait $!\n")
file.write("set +x \n")
file.write("echo ..::Job Finished, but No, AGI is to BE Solved::.. \n")
# signal that job is finished
os.system('sbatch ' + batch_file)
def find_checkpoint(current_dir,checkpoint_name):
if not os.path.isdir(current_dir):
return None
listfiles = os.listdir(current_dir)
for item in listfiles:
sub_dir = os.path.join(current_dir,item)
if item==checkpoint_name:
return sub_dir
elif os.path.isdir(sub_dir):
search_result = find_checkpoint(sub_dir,checkpoint_name)
if search_result is not None:
return search_result
return None
def write_slurm_sh_multi(id,command_line, queue_name="learnfair",nodes=1,
gpu_per_node=8,wall_time=3*24*60,username="wang3702",
CPU_PER_GPU=8,gpu_memory=False,environment=0):
import time
import datetime
today = datetime.date.today()
formatted_today = today.strftime('%y%m%d')
now = time.strftime("%H:%M:%S")
dependency_handler_path = os.path.join(os.getcwd(), "ops")
dependency_handler_path = os.path.join(dependency_handler_path, "handler.txt")
run_path = os.path.join(os.getcwd(), "log")
mkdir(run_path)
run_path = os.path.abspath(run_path)
prefix = "node%d_gpu%d"%(nodes,gpu_per_node)
batch_file = os.path.join(run_path, prefix+"slurm_job_" + str(id) + ".sh")
output_path = os.path.join(run_path, prefix+"output_" + str(id) + "_" + str(formatted_today + now) + ".log")
error_path = os.path.join(run_path, prefix+"error_" + str(id) + "_" + str(formatted_today + now) + ".log")
with open(batch_file, "w") as file:
file.write("#! /bin/bash\n")#!/bin/bash
file.write("#SBATCH --job-name=%s\n" % id)
file.write("#SBATCH --output=%s\n" % output_path)
file.write("#SBATCH --error=%s\n" % error_path)
file.write("#SBATCH --partition=%s\n"%queue_name)
file.write("#SBATCH --signal=USR1@600\n")
file.write("#SBATCH --nodes=%d\n" % nodes)
file.write("#SBATCH --ntasks-per-node=%d\n" % 1)
file.write("#SBATCH --mem=%dG\n"%(350/8*gpu_per_node))#--mem : Specify the real memory required per node.
file.write("#SBATCH --gpus=%d\n" % (nodes * gpu_per_node))
file.write("#SBATCH --gpus-per-node=%d\n" % (gpu_per_node))
file.write("#SBATCH --cpus-per-task=%d\n"%(CPU_PER_GPU*gpu_per_node))
file.write("#SBATCH --time=%d\n"%wall_time)
file.write("#SBATCH --mail-user=%s@fb.com\n"%username)
file.write("#SBATCH --mail-type=FAIL\n")
file.write("#SBATCH --mail-type=end \n")
if gpu_memory is False:
file.write('#SBATCH --constraint="volta"\n')
else:
file.write('#SBATCH --constraint="volta32gb"\n')
#file.write('#SBATCH --constraint="volta"\n')
report_info = "%s job failed; \t" % id
report_info += "log path: %s; \t" % output_path
report_info += "error record path: %s\t" % error_path
report_info += "command line path: %s\t" % batch_file
file.write('#SBATCH --comment="%s"\n' % (report_info))
with open(dependency_handler_path, 'r') as rfile:
line = rfile.readline()
while line:
file.write(line)
line = rfile.readline()
file.write("export GLOO_SOCKET_IFNAME=\nexport NCCL_SOCKET_IFNAME=\n")
file.write("module load cuda/10.2 cudnn/v7.6.5.32-cuda.10.2 gcc/7.3.0\n")
#file.write("bash /private/home/wang3702/.bashrc\n")
file.write("/private/home/wang3702/anaconda3/bin/conda init\n")
#file.write("module load anaconda3\n")
file.write("CONDA_BASE=$(conda info --base) ; source $CONDA_BASE/etc/profile.d/conda.sh\n")
if environment==0:
file.write("conda activate pytorch2\n")
else:
file.write("conda activate pytorch\n")
file.write("master_node=${SLURM_NODELIST:0:9}${SLURM_NODELIST:10:4}\n")
file.write('dist_url="tcp://"\n')
file.write("dist_url+=$master_node\n")
file.write("dist_url+=:40000\n")
file.write("export MASTER_ADDR=${SLURM_NODELIST:0:9}${SLURM_NODELIST:10:4}\n")
file.write("export MASTER_PORT=29500\n")
file.write("srun --label "+command_line + " --slurm=1 --dist_url=$dist_url &\n")
file.write("wait $!\n")
file.write("set +x \n")
file.write("echo ..::Job Finished, but No, AGI is to BE Solved::.. \n")
# signal that job is finished
os.system('sbatch ' + batch_file)
def write_slurm_sh_multi2(id,command_line, queue_name="learnfair",nodes=1,
gpu_per_node=8,wall_time=3*24*60,username="wang3702",CPU_PER_GPU=8,
gpu_memory=False,environment=0):
import time
import datetime
today = datetime.date.today()
formatted_today = today.strftime('%y%m%d')
now = time.strftime("%H:%M:%S")
dependency_handler_path = os.path.join(os.getcwd(), "ops")
dependency_handler_path = os.path.join(dependency_handler_path, "handler.txt")
run_path = os.path.join(os.getcwd(), "log")
mkdir(run_path)
run_path = os.path.abspath(run_path)
prefix = "node%d_gpu%d"%(nodes,gpu_per_node)
batch_file = os.path.join(run_path, prefix+"slurm_job_" + str(id) + ".sh")
output_path = os.path.join(run_path, prefix+"output_" + str(id) + "_" + str(formatted_today + now) + ".log")
error_path = os.path.join(run_path, prefix+"error_" + str(id) + "_" + str(formatted_today + now) + ".log")
with open(batch_file, "w") as file:
file.write("#! /bin/bash\n")#!/bin/bash
file.write("#SBATCH --job-name=%s\n" % id)
file.write("#SBATCH --output=%s\n" % output_path)
file.write("#SBATCH --error=%s\n" % error_path)
file.write("#SBATCH --partition=%s\n"%queue_name)
file.write("#SBATCH --signal=USR1@600\n")
file.write("#SBATCH --nodes=%d\n" % nodes)
file.write("#SBATCH --ntasks-per-node=%d\n" % 1)
file.write("#SBATCH --mem=%dG\n"%(350/8*gpu_per_node))
file.write("#SBATCH --gpus=%d\n" % (nodes * gpu_per_node))
file.write("#SBATCH --gpus-per-node=%d\n" % (gpu_per_node))
file.write("#SBATCH --cpus-per-task=%d\n"%(CPU_PER_GPU*gpu_per_node))
file.write("#SBATCH --time=%d\n"%wall_time)
file.write("#SBATCH --mail-user=%s@fb.com\n"%username)
file.write("#SBATCH --mail-type=FAIL\n")
file.write("#SBATCH --mail-type=end \n")
if gpu_memory is False:
file.write('#SBATCH --constraint="volta"\n')
else:
file.write('#SBATCH --constraint="volta32gb"\n')
report_info = "%s job failed; \t" % id
report_info += "log path: %s; \t" % output_path
report_info += "error record path: %s\t" % error_path
report_info += "command line path: %s\t" % batch_file
file.write('#SBATCH --comment="%s"\n' % (report_info))
with open(dependency_handler_path, 'r') as rfile:
line = rfile.readline()
while line:
file.write(line)
line = rfile.readline()
file.write("export GLOO_SOCKET_IFNAME=\nexport NCCL_SOCKET_IFNAME=\n")
file.write("module load cuda/10.2 cudnn/v7.6.5.32-cuda.10.2 gcc/7.3.0\n")
#file.write("bash /private/home/wang3702/.bashrc\n")
# file.write("/private/home/wang3702/anaconda3/bin/conda init\n")
file.write("/private/home/wang3702/anaconda3/bin/conda init\n")
#file.write("module load anaconda3\n")
file.write("CONDA_BASE=$(conda info --base) ; source $CONDA_BASE/etc/profile.d/conda.sh\n")
if environment==0:
file.write("conda activate pytorch2\n")
else:
file.write("conda activate pytorch\n")
#file.write("source activate\n")
file.write("master_node=${SLURM_NODELIST:0:9}${SLURM_NODELIST:10:3}\n")
file.write('dist_url="tcp://"\n')
file.write("dist_url+=$master_node\n")
file.write("dist_url+=:40000\n")
file.write("export MASTER_ADDR=${SLURM_NODELIST:0:9}${SLURM_NODELIST:10:3}\n")
file.write("export MASTER_PORT=29500\n")
file.write("srun --label "+command_line + " &\n")
file.write("wait $!\n")
file.write("set +x \n")
file.write("echo ..::Job Finished, but No, AGI is to BE Solved::.. \n")
# signal that job is finished
os.system('sbatch ' + batch_file)
def write_slurm_sh_faster(id,command_line, queue_name="learnfair",nodes=1,
gpu_per_node=8,wall_time=3*24*60,username="wang3702",CPU_PER_GPU=8,
gpu_memory=False,environment=0):
import time
import datetime
today = datetime.date.today()
formatted_today = today.strftime('%y%m%d')
now = time.strftime("%H:%M:%S")
dependency_handler_path = os.path.join(os.getcwd(), "ops")
dependency_handler_path = os.path.join(dependency_handler_path, "handler.txt")
run_path = os.path.join(os.getcwd(), "log")
mkdir(run_path)
run_path = os.path.abspath(run_path)
batch_file = os.path.join(run_path, "slurm_job_" + str(id) + ".sh")
output_path = os.path.join(run_path, "output_" + str(id) + "_" + str(formatted_today + now) + ".log")
error_path = os.path.join(run_path, "error_" + str(id) + "_" + str(formatted_today + now) + ".log")
with open(batch_file, "w") as file:
file.write("#!/bin/bash\n")#!/bin/bash
file.write("#SBATCH --job-name=%s\n" % id)
file.write("#SBATCH --output=%s\n" % output_path)
file.write("#SBATCH --error=%s\n" % error_path)
file.write("#SBATCH --partition=%s\n"%queue_name)
file.write("#SBATCH --signal=USR1@600\n")
file.write("#SBATCH --nodes=%d\n" % nodes)
file.write("#SBATCH --ntasks-per-node=%d\n" % gpu_per_node)
file.write("#SBATCH --mem=%dG\n"%(int(350/8*gpu_per_node)))
file.write("#SBATCH --gpus=%d\n" % (nodes * gpu_per_node))
file.write("#SBATCH --cpus-per-task=%d\n"%(CPU_PER_GPU))
file.write("#SBATCH --time=%d\n"%wall_time)
file.write("#SBATCH --mail-user=%s@fb.com\n"%username)
file.write("#SBATCH --mail-type=FAIL\n")
file.write("#SBATCH --mail-type=end \n")
if gpu_memory:
file.write('#SBATCH --constraint="volta32gb"\n')
else:
file.write('#SBATCH --constraint="volta"\n')
report_info = "%s job failed; \t" % id
report_info += "log path: %s; \t" % output_path
report_info += "error record path: %s\t" % error_path
report_info += "command line path: %s\t" % batch_file
file.write('#SBATCH --comment="%s"\n' % (report_info))
with open(dependency_handler_path, 'r') as rfile:
line = rfile.readline()
while line:
file.write(line)
line = rfile.readline()
file.write("module load cuda/10.2 cudnn/v7.6.5.32-cuda.10.2 gcc/7.3.0\n")
#file.write("bash /private/home/wang3702/.bashrc\n")
file.write("/private/home/wang3702/anaconda3/bin/conda init\n")
#file.write("module load anaconda3\n")
file.write("CONDA_BASE=$(conda info --base) ; source $CONDA_BASE/etc/profile.d/conda.sh\n")
if environment==0:
file.write("conda activate pytorch2\n")
else:
file.write("conda activate pytorch\n")
#file.write("source activate\n")
file.write(command_line + " &\n")
file.write("wait $!\n")
file.write("set +x \n")
file.write("echo ..::Job Finished, but No, AGI is to BE Solved::.. \n")
# signal that job is finished
os.system('sbatch ' + batch_file)
def write_slurm_sh(id,command_line, queue_name="learnfair",nodes=1,
gpu_per_node=8,wall_time=3*24*60,username="wang3702",CPU_PER_GPU=10):
"""
Args:
id: running id
command_line: command line
outlog_path: saving path
Returns:
"""
import time
import datetime
today = datetime.date.today()
formatted_today = today.strftime('%y%m%d')
now = time.strftime("%H:%M:%S")
dependency_handler_path = os.path.join(os.getcwd(),"ops")
dependency_handler_path = os.path.join(dependency_handler_path,"handler.txt")
run_path = os.path.join(os.getcwd(),"log")
mkdir(run_path)
run_path = os.path.abspath(run_path)
batch_file = os.path.join(run_path,"slurm_job_"+str(id)+".sh")
output_path = os.path.join(run_path,"output_"+str(id)+"_"+str(formatted_today+now)+".log")
error_path = os.path.join(run_path,"error_"+str(id)+"_"+str(formatted_today+now)+".log")
with open(batch_file,"w") as file:
file.write("#!/bin/sh\n")
file.write("#SBATCH --job-name=%s\n"%id)
file.write("#SBATCH --output=%s\n"%output_path)
file.write("#SBATCH --error=%s\n"%error_path)
file.write("#SBATCH --partition=%s\n"%queue_name)
file.write("#SBATCH --signal=USR1@600\n")
file.write("#SBATCH --nodes=%d\n"%nodes )
file.write("#SBATCH --ntasks-per-node=1\n")
file.write("#SBATCH --mem=350G\n")
file.write("#SBATCH --gpus=%d\n"%(nodes*gpu_per_node))
file.write("#SBATCH --gpus-per-node=%d\n" % (gpu_per_node))
file.write("#SBATCH --cpus-per-task=%d\n"%(CPU_PER_GPU*gpu_per_node))
file.write("#SBATCH --time=%d\n"%wall_time)
file.write("#SBATCH --mail-user=%s@fb.com\n"%username)
file.write("#SBATCH --mail-type=FAIL\n")
file.write("#SBATCH --mail-type=end \n")
file.write('#SBATCH --constraint="volta"\n')
report_info ="%s job failed; \t"%id
report_info += "log path: %s; \t"%output_path
report_info += "error record path: %s\t"%error_path
report_info += "command line path: %s\t"%batch_file
file.write('#SBATCH --comment="%s"\n'%(report_info))
with open(dependency_handler_path,'r') as rfile:
line = rfile.readline()
while line:
file.write(line)
line = rfile.readline()
#file.write("bash /private/home/wang3702/.bashrc\n")
# file.write("/private/home/wang3702/anaconda3/bin/conda init\n")
#file.write("CONDA_BASE=$(conda info --base) ; source $CONDA_BASE/etc/profile.d/conda.sh\n")
#file.write("module load anaconda3\n")
#file.write("conda activate pytorch2\n")
file.write("module load cuda/10.2 cudnn/v7.6.5.32-cuda.10.2 gcc/7.3.0\n")
file.write("/private/home/wang3702/anaconda3/bin/conda init\n")
file.write("CONDA_BASE=$(conda info --base) ; source $CONDA_BASE/etc/profile.d/conda.sh\n")
file.write("conda activate pytorch2\n")
file.write(command_line+" &\n")
file.write("wait $!\n")
file.write("set +x \n")
file.write("echo ..::Job Finished, but No, AGI is to BE Solved::.. \n")
# signal that job is finished
os.system('sbatch ' + batch_file)
parser = argparse.ArgumentParser(description='slurm job submission')
parser.add_argument('--data', default="imagenet", type=str, metavar='DIR',
help='path to dataset')
parser.add_argument("--mode",type=int,default=0,help="control mode for training")
parser.add_argument("--type",type=int,default=0,help="running type control")
parser.add_argument("--roi",type=int,default = 20, help="number of rois sampled here")
parser.add_argument("--queue",type=int,default=0, help="queue specified list")
parser.add_argument("-F",type=str, default=None, help="resume path for running again")
parser.add_argument("--comment", type=str,default=None,help="adding comment for script names")
parser.add_argument("--node",type=int,default=1,help="nodes needed for training")
parser.add_argument("--gpu",type=int,default=8,help="number of gpus per node")
args = parser.parse_args()
if args.queue ==0:
queue_name = "learnfair"
elif args.queue ==1:
queue_name = "dev"
elif args.queue ==2:
queue_name = "scavenge"
elif args.queue ==3:
queue_name = 'priority'
elif args.queue ==4:
queue_name = 'learnlab'
elif args.queue==5:
queue_name = 'devlab'
elif args.queue==6:
queue_name = 'prioritylab'
dump_path= os.path.join(os.getcwd(),"swav_dump_100")
from ops.os_operation import mkdir
mkdir(dump_path)
import time
import datetime
today = datetime.date.today()
formatted_today = today.strftime('%y%m%d')
now = time.strftime("%H:%M:%S")
dump_path = os.path.join(dump_path, formatted_today + now)
if args.mode==1:
if args.type==0:
# command_line = "python3 main_adco.py --mode=1 --lr=0.06 --data=%s " \
# "--dist_url=tcp://localhost:10031 --epochs=100 " \
# "--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0006 " \
# "--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
# "--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
# "--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
# "--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=57" % args.data
# write_slurm_sh("baseline_sym_moco_lr0.06_proj", command_line, queue_name)
command_line = "python3 main_adco.py --mode=1 --lr=0.06 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0006 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=16 --mask_size=32 " \
"--num_roi=1 " % args.data
write_slurm_sh("baseline_sym_moco_lr0.06", command_line, queue_name)
# command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
# "--dist_url=tcp://localhost:10031 --epochs=100 " \
# "--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
# "--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
# "--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
# "--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
# "--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=16 --mask_size=32 " \
# "--num_roi=1 --img_size=96 " % args.data
# write_slurm_sh("baseline_sym_moco_input96", command_line, queue_name)
#running all the baseline with 100 epochs
#base line moco
# command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
# "--dist_url=tcp://localhost:10031 --epochs=100 " \
# "--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
# "--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
# "--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
# "--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
# "--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=35 --mask_size=32 " \
# " --num_roi=1 " % args.data
# write_slurm_sh("baseline_sym_mocobn_100", command_line, queue_name)
# #moco multi baseline
# command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
# "--dist_url=tcp://localhost:10031 --epochs=100 " \
# "--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
# "--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
# "--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
# "--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
# "--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=18 --nmb_crops 2 6 " \
# "--size_crops 224 96 --min_scale_crops 0.14 0.05 --max_scale_crops 1.0 0.14 " % (args.data)
# write_slurm_sh("multi_moco_baseline_100_new", command_line, queue_name)
# # #moco multi sym baseline
# command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
# "--dist_url=tcp://localhost:10031 --epochs=100 " \
# "--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
# "--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
# "--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
# "--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
# "--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=20 --nmb_crops 4 " \
# "--size_crops 224 --min_scale_crops 0.14 --max_scale_crops 1.0 " % (args.data)
# write_slurm_sh("2key_multi_moco_baseline_4_224", command_line, queue_name)
# #swav multi baseline
# command_line = "python3 main_adco.py --mode=5 --type=0 --data=%s --epochs 100 --lr=0.6 " \
# "--lr_final 0.0006 --batch_size=256 --warmup_epochs 0 --freeze_prototypes_niters 5005 " \
# "--queue_length 3840 --epoch_queue_starts 15 --dist_url=tcp://localhost:10031 " \
# "--knn_batch_size=256 --cos=1 --momentum=0.9 --weight_decay=1e-6 --world_size=1 " \
# "--rank=0 --multiprocessing_distributed=1 --moco_dim=128 --moco_k=3000 --moco_t=0.1 " \
# "--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --nmb_crops 2 " \
# "--size_crops 224 --min_scale_crops 0.14 --max_scale_crops 1.0 --dump_path %s " % (args.data,dump_path)
# write_slurm_sh("swav_baseline_100_only224", command_line, queue_name)
# command_line = "python3 main_adco.py --mode=5 --type=0 --data=%s --epochs 100 --lr=0.6 " \
# "--lr_final 0.0006 --batch_size=256 --warmup_epochs 0 --freeze_prototypes_niters 5005 " \
# "--queue_length 3840 --epoch_queue_starts 15 --dist_url=tcp://localhost:10031 " \
# "--knn_batch_size=256 --cos=1 --momentum=0.9 --weight_decay=1e-6 --world_size=1 " \
# "--rank=0 --multiprocessing_distributed=1 --moco_dim=128 --moco_k=3000 --moco_t=0.1 " \
# "--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --nmb_crops 2 6 " \
# "--size_crops 224 96 --min_scale_crops 0.14 0.05 --max_scale_crops 1.0 0.14 --dump_path %s " % (
# args.data, dump_path)
# write_slurm_sh("swav_baseline_100", command_line, queue_name)
elif args.type==10:
#half dropout results
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=10 " % args.data
if args.F is not None:
resume_name = os.path.split(os.path.abspath(args.F))[1]
command_line += "--resume=%s"%args.F
write_slurm_sh("halfdropoutnew_resume%s"%resume_name, command_line, queue_name)
else:
write_slurm_sh("halfdropoutnew", command_line, queue_name)
elif args.type==11:
# to make sure overlap region can really not work
for mask_size in [96, 160]:
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=200 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=11 --shift_ratio=0 " \
" --mask_size=%d " % (args.data,mask_size)
write_slurm_sh("type11_roimatch_%s"%mask_size, command_line, queue_name)
elif args.type==13:
for mask_size in [96,160]:
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=200 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=13 " \
"--mask_size=%d "%(args.data,mask_size)
write_slurm_sh("type13_singleroi_vs_global_%d"%mask_size,command_line,queue_name)
time.sleep(1)
elif args.type==14:
#roi vs global
for mask_size in [96,160]:
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=200 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=14 " \
"--mask_size=%d "%(args.data,mask_size)
write_slurm_sh("type14_singleroi_vs_global_%d"%mask_size,command_line,queue_name)
elif args.type==16:
for mask_size in [96,128,160]:
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=200 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=16 " \
"--mask_size=%d --num_roi=10 "%(args.data,mask_size)
write_slurm_sh("type16_roi+global_vs_global_%d"%mask_size,command_line,queue_name)
elif args.type==-16:
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=200 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=16 --mask_size=32 --num_roi=1 " % args.data
if args.F is not None:
resume_name = os.path.split(os.path.abspath(args.F))[1]
command_line += " --resume=%s"%args.F
write_slurm_sh("baseline_sym_moco_resume%s"%resume_name, command_line, queue_name)
else:
write_slurm_sh("baseline_sym_moco", command_line,queue_name)
elif args.type==17:
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=200 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=17 --mask_size=32" \
" --num_roi=%d" % (args.data,args.roi)
write_slurm_sh("type17_randroi_%d"%args.roi, command_line,queue_name)
elif args.type==-17:
#roi vs roi,with global as negative
for roi in [10,20,50,100]:
for mask_size in [32, 96, 160, 196]:
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=200 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=17 --mask_size=%d" \
" --num_roi=%d" % (args.data,mask_size, roi)
write_slurm_sh("type17_randroi_%d_masksize_%d" % (roi,mask_size), command_line,queue_name)
elif args.type==18:
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=200 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=18 --nmb_crops 2 6 " \
"--size_crops 224 96 --min_scale_crops 0.14 0.05 --max_scale_crops 1.0 0.14 "% (args.data)
if args.F is not None:
resume_name = os.path.split(os.path.abspath(args.F))[1]
command_line += "--resume=%s"%args.F
write_slurm_sh("multi_moco_baseline_resume%s"%resume_name, command_line, queue_name)
else:
write_slurm_sh("multi_moco_baseline" , command_line, queue_name)
elif args.type==19:
for roi in [20]:
for mask_size in [32,160]:
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=200 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=19 --mask_size=%d" \
" --num_roi=%d" % (args.data,mask_size, roi)
write_slurm_sh("type19_randroi_%d_masksize_%d" % (roi,mask_size), command_line,queue_name)
elif args.type==20:
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=200 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=20 --nmb_crops 2 6 " \
"--size_crops 224 96 --min_scale_crops 0.14 0.05 --max_scale_crops 1.0 0.14 "% (args.data)
if args.F is not None:
resume_name = os.path.split(os.path.abspath(args.F))[1]
command_line += " --resume=%s"%args.F
write_slurm_sh("2key_multi_moco_baseline_correct_resume%s"%resume_name, command_line, queue_name)
else:
write_slurm_sh("2key_multi_moco_baseline_correct", command_line, queue_name)
elif args.type==21:
for roi in [20]:
for mask_size in [96]:
command_line = "python3 main_adco.py --mode=1 --lr=0.09 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=200 " \
"--batch_size=768 --knn_batch_size=256 --cos=1 --lr_final=0.0009 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=21 --mask_size=%d" \
" --num_roi=%d" % (args.data,mask_size, roi)
write_slurm_sh("type21_randroi_%d_masksize_%d" % (roi,mask_size), command_line,queue_name)
elif args.type==22:
for roi in [50]:
for mask_size in [96]:
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=200 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=22 --mask_size=%d" \
" --num_roi=%d" % (args.data, mask_size, roi)
write_slurm_sh("type22_randroi_%d_masksize_%d" % (roi,mask_size), command_line,queue_name)
elif args.type==23:
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=200 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=23 --nmb_crops 2 2 2 2 2 2 2 2" \
" --size_crops 96 112 128 144 160 176 192 208 " % args.data
write_slurm_sh("type23_specifyroi", command_line, queue_name)
elif args.type==-23:
# command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
# "--dist_url=tcp://localhost:10031 --epochs=200 " \
# "--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
# "--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
# "--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
# "--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
# "--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=23 --nmb_crops 6" \
# " --size_crops 96 " % args.data
# write_slurm_sh("type23_specifyroi_6_96", command_line, queue_name)
min_scale = 64
max_scale = 224
divide_list = [2,4,8,16,32]
pick_times = [1,2,3]
for pick_time in pick_times:
for divide in divide_list:
check_list = ""
num_list = ""
current_scale = min_scale
while current_scale<max_scale:
check_list+=str(current_scale)+" "
num_list+=str(pick_time)+" "
current_scale+=divide
print(check_list)
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=200 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=23 --nmb_crops %s " \
" --size_crops %s " % (args.data,num_list,check_list)
write_slurm_sh("type23_specifyroi_%d_%d"%(pick_time,divide), command_line, queue_name)
elif args.type==24:
for alpha in [0.5, 1.0, 2.0]:
for local_t in [0.1,0.2,0.3]:
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=24 --nmb_crops 1 6" \
" --size_crops 224 96 --local_t=%.4f --alpha=1.0 " % (args.data,local_t)
write_slurm_sh("type24_lg_t_%.3f_alpha_%.2f"%(local_t,alpha), command_line, queue_name)
elif args.type==25:
for alpha in [0.5]:
for local_t in [0.2]:
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=24 --nmb_crops 1 6" \
" --size_crops 224 96 --local_t=%.4f --alpha=%.2f " % (args.data, local_t,alpha)
write_slurm_sh("type25_lgq_t_%.3f_alpha_%.2f" %(local_t,alpha), command_line, queue_name)
elif args.type==26:
for alpha in [0.5,1.0]:
for local_t in [0.2]:
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=26 --nmb_crops 1 6" \
" --size_crops 224 96 --local_t=%.4f --alpha=%.2f " % (args.data, local_t,alpha)
write_slurm_sh("type26_lgq_t_%.3f_alpha_%.2f" %(local_t,alpha), command_line, queue_name)
elif args.type == 27:
min_scale = 96
max_scale = 224
divide_list = [16]
pick_times = [1]
for learning_rate in [0.05]:#[0.02,0.03,0.04,0.05,0.06,0.1,0.15]:
for pick_time in pick_times:
for divide in divide_list:
check_list = ""
num_list = ""
current_scale = min_scale
while current_scale < max_scale:
check_list += str(current_scale) + " "
num_list += str(pick_time) + " "
current_scale += divide
print(check_list)
print(num_list)
for alpha in [0.1,0.15,0.2,0.3]:#[0.3, 0.5, 1.0]:
for local_t in [0.12,0.15,0.18]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=27 --nmb_crops 1 %s" \
" --size_crops 224 %s --local_t=%.4f --alpha=%.2f " % \
(learning_rate,args.data, local_t,num_list, check_list, local_t, alpha)
write_slurm_sh("type27_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (local_t, alpha, pick_time, divide,learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type == -270:
for num_roi in [6,10,20,30]:
for crop_size in [64, 96, 128, 160, 192]:
for learning_rate in [0.05]:
for alpha in [0.1]: # [0.3, 0.5, 1.0]:
for local_t in [0.18]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=27 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --alpha=%.2f " % \
(learning_rate, args.data,local_t, num_roi,crop_size, local_t, alpha)
write_slurm_sh(
"type27crop_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (local_t, alpha, num_roi,crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==-271:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.05]:
for alpha in [0.1]: # [0.3, 0.5, 1.0]:
for local_t in [0.18,0.2]:
for moco_dim in [256,512]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=%d " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=27 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --alpha=%.2f " % \
(learning_rate, args.data,moco_dim, local_t, num_roi, crop_size, local_t, alpha)
write_slurm_sh(
"type27dim_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f_dim%d" % (
local_t, alpha, num_roi, crop_size, learning_rate,moco_dim),
command_line, queue_name)
time.sleep(1)
elif args.type == -27:
#calculate baseline 6*96 for type 27 as a direct cmp with SWAV
for learning_rate in [0.05]:
for alpha in [0.1]: # [0.3, 0.5, 1.0]:
for local_t in [0.18]:
for moco_dim in [128,256,512]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=27 --nmb_crops 1 6" \
" --size_crops 224 96 --local_t=%.4f --alpha=%.2f " % \
(learning_rate, args.data, local_t,local_t, alpha)
write_slurm_sh("type27baseline_lgq_t_%.3f_alpha_%.2f_6_96_lr%.4f" % (local_t, alpha,learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type == 28:
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=28 --nmb_crops 2 6 " \
"--size_crops 224 96 --min_scale_crops 0.14 0.05 --max_scale_crops 1.0 0.14 " % (args.data)
write_slurm_sh("type28_small_inside", command_line, queue_name)
elif args.type==29:
for learning_rate in [0.03]:
for alpha in [0.5,1.0]:
for local_t in [0.2]:
command_line = "python3 main_adco.py --mode=1 --lr=%.2f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=%.5f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=29 --nmb_crops 1 6" \
" --size_crops 224 96 --local_t=%.4f --alpha=%.2f " \
"" % (learning_rate,args.data, learning_rate/100,local_t, alpha)
write_slurm_sh("type29_lgq_t_%.3f_alpha_%.2f_lr_%.4f" % (local_t, alpha,learning_rate), command_line, queue_name)
elif args.type==30:
for learning_rate in [0.03]:
for alpha in [0.5,1.0]:
for local_t in [0.2]:
command_line = "python3 main_adco.py --mode=1 --lr=%.2f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=%.5f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=30 --nmb_crops 6 " \
" --size_crops 96 --local_t=%.4f --alpha=%.2f " \
"" % (learning_rate,args.data, learning_rate/100,local_t, alpha)
write_slurm_sh("type30_lgq_t_%.3f_alpha_%.2f_lr_%.4f" % (local_t, alpha,learning_rate), command_line, queue_name)
elif args.type==31:
for learning_rate in [0.03]:
for alpha in [0.5]:
for local_t in [0.2]:
for num_roi in [5, 10, 20]:
for mask_size in [96]:
command_line = "python3 main_adco.py --mode=1 --lr=%.2f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=%.5f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=31 " \
"--local_t=%.4f --alpha=%.2f --num_roi=%d --mask_size=%d " \
"" % (learning_rate, args.data, learning_rate / 100,
local_t, alpha,num_roi,mask_size)
write_slurm_sh("type31_lgq_t_%.3f_alpha_%.2f_lr_%.4f_roi%d_mask%d" %
(local_t, alpha, learning_rate,num_roi,mask_size),
command_line, queue_name)
elif args.type==32:
for learning_rate in [0.03]:
for alpha in [0.5]:
for local_t in [0.2]:
for num_roi in [5, 10, 20]:
for mask_size in [96]:
command_line = "python3 main_adco.py --mode=1 --lr=%.2f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=%.5f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=32 " \
"--local_t=%.4f --alpha=%.2f --num_roi=%d --mask_size=%d " \
"" % (learning_rate, args.data, learning_rate / 100,
local_t, alpha,num_roi,mask_size)
write_slurm_sh("type32_lgq_t_%.3f_alpha_%.2f_lr_%.4f_roi%d_mask%d" %
(local_t, alpha, learning_rate,num_roi,mask_size),
command_line, queue_name)
elif args.type==33:
for learning_rate in [0.03,0.04,0.05,0.06,0.09,0.12]:
for alpha in [0.5,1.0,2.0,5.0]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=%.4f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=33 --nmb_crops 2 6 " \
"--size_crops 224 96 --min_scale_crops 0.14 0.05 --max_scale_crops 1.0 0.14 " \
"--alpha=%.4f " \
" " % (learning_rate,args.data,learning_rate/100,alpha)
write_slurm_sh("multimoco_alpha_%.2f_lr_%.4f"%(alpha,learning_rate), command_line, queue_name)
elif args.type==-28:
for learning_rate in [0.06]:
for alpha in [1.0]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=%.4f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=28 --nmb_crops 2 6 " \
"--size_crops 224 96 --min_scale_crops 0.14 0.05 --max_scale_crops 1.0 0.14 " \
"--alpha=%.4f " \
" " % (learning_rate,args.data,learning_rate/100,alpha)
write_slurm_sh("multimocoinside_alpha_%.2f_lr_%.4f"%(alpha,learning_rate), command_line, queue_name)
elif args.type==34:
min_scale = 96
max_scale = 224
divide_list = [16]
pick_times = [1]
for learning_rate in [0.04, 0.05]:
for pick_time in pick_times:
for divide in divide_list:
check_list = ""
num_list = ""
current_scale = min_scale
while current_scale < max_scale:
check_list += str(current_scale) + " "
num_list += str(pick_time) + " "
current_scale += divide
print(check_list)
print(num_list)
for alpha in [0.1, 0.3, 0.5,1.0]:
for local_t in [0.2]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=34 --nmb_crops 1 %s" \
" --size_crops 224 %s --local_t=%.4f --alpha=%.2f " % \
(learning_rate, args.data, num_list, check_list, local_t, alpha)
write_slurm_sh("type34_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (
local_t, alpha, pick_time, divide, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type == 36:
min_scale = 96
max_scale = 224
divide_list = [16]
pick_times = [1]
for learning_rate in [0.04,0.05]:#[0.02,0.03,0.04,0.05,0.06,0.1,0.15]:
for pick_time in pick_times:
for divide in divide_list:
check_list = ""
num_list = ""
current_scale = min_scale
while current_scale < max_scale:
check_list += str(current_scale) + " "
num_list += str(pick_time) + " "
current_scale += divide
print(check_list)
print(num_list)
for alpha in [0.1]:#[0.3, 0.5, 1.0]:
for local_t in [0.2]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=36 --nmb_crops 1 %s" \
" --size_crops 224 %s --local_t=%.4f --alpha=%.2f " % \
(learning_rate,args.data, local_t,num_list, check_list, local_t, alpha)
write_slurm_sh("type36_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (local_t, alpha, pick_time, divide,learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==37:
for learning_rate in [0.03,0.04,0.05,0.06]:
for alpha in [0.1,0.3,0.5,1.0]: # [0.3, 0.5, 1.0]:
for local_t in [0.2]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=37 --nmb_crops 1 6" \
" --size_crops 224 96 --local_t=%.4f --alpha=%.2f " % \
(learning_rate, args.data, local_t,local_t, alpha)
write_slurm_sh("type37baseline_lgq_t_%.3f_alpha_%.2f_6_96_lr%.4f" % (local_t, alpha,learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==38:
min_scale = 96
max_scale = 224
divide_list = [16]
pick_times = [1]
for learning_rate in [0.05]: # [0.02,0.03,0.04,0.05,0.06,0.1,0.15]:
for pick_time in pick_times:
for divide in divide_list:
check_list = ""
num_list = ""
current_scale = min_scale
while current_scale < max_scale:
check_list += str(current_scale) + " "
num_list += str(pick_time) + " "
current_scale += divide
print(check_list)
print(num_list)
for alpha in [0]: #[0.1, 0.3, 0.5, 1.0]: # [0.3, 0.5, 1.0]:
for local_t in [0.2]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=38 --nmb_crops 1 %s" \
" --size_crops 224 %s --local_t=%.4f --alpha=%.2f " % \
(learning_rate, args.data, local_t,"", "", local_t, alpha)
write_slurm_sh("type38_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (
local_t, alpha, pick_time, divide, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==-38:
for learning_rate in [0.05]:
for alpha in [0.1,0.3,0.5,1.0]: # [0.3, 0.5, 1.0]:
for local_t in [0.2]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=38 --nmb_crops 1 6" \
" --size_crops 224 96 --local_t=%.4f --alpha=%.2f " % \
(learning_rate, args.data, local_t,local_t, alpha)
write_slurm_sh("type38baseline_lgq_t_%.3f_alpha_%.2f_6_96_lr%.4f" % (local_t, alpha,learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==39:
for learning_rate in [0.05]:
for alpha in [0.1]: # [0.3, 0.5, 1.0]:
for local_t in [0.2]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=39 --nmb_crops 1 6" \
" --size_crops 224 96 --local_t=%.4f --alpha=%.2f " % \
(learning_rate, args.data, local_t,local_t, alpha)
write_slurm_sh("type39baseline_lgq_t_%.3f_alpha_%.2f_6_96_lr%.4f" % (local_t, alpha,learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==40:
for learning_rate in [0.05]:
for alpha in [0.5]: # [0.3, 0.5, 1.0]:
for local_t in [0.2]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=40 --nmb_crops 1 6" \
" --size_crops 224 96 --local_t=%.4f --alpha=%.2f " % \
(learning_rate, args.data, local_t,local_t, alpha)
write_slurm_sh("type40baseline_lgq_t_%.3f_alpha_%.2f_6_96_lr%.4f" % (local_t, alpha,learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==41:
for mask_size in [96]:
command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=41 " \
"--mask_size=%d "%(args.data,mask_size)
write_slurm_sh("type41_singleroi_vs_global_%d"%mask_size,command_line,queue_name)
elif args.type==42:
for learning_rate in [0.05]:
for alpha in [0.1,0.5]: # [0.3, 0.5, 1.0]:
for local_t in [0.15,0.2]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=42 --nmb_crops 1 6" \
" --size_crops 224 96 --local_t=%.4f --alpha=%.2f " % \
(learning_rate, args.data, local_t,local_t, alpha)
write_slurm_sh("type42baseline_lgq_t_%.3f_alpha_%.2f_6_96_lr%.4f" % (local_t, alpha,learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==43:
for learning_rate in [0.05]:
for alpha in [0.1,0.5]: # [0.3, 0.5, 1.0]:
for local_t in [0.15,0.2]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=43 --nmb_crops 1 6" \
" --size_crops 224 96 --local_t=%.4f --alpha=%.2f " % \
(learning_rate, args.data, local_t,local_t, alpha)
write_slurm_sh("type43baseline_lgq_t_%.3f_alpha_%.2f_6_96_lr%.4f" % (local_t, alpha,learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type == 44:
# for num_roi in [6]:
# for crop_size in [96]:
# for learning_rate in [0.05]:
# for alpha in [0.1]: # [0.3, 0.5, 1.0]:
# for local_t in [0.15, 0.18, 0.2]:
# for sample_ratio in [2,4]:
# command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
# "--dist_url=tcp://localhost:10031 --epochs=100 " \
# "--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
# "--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
# "--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
# "--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
# "--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=44 --nmb_crops 1 %d" \
# " --size_crops 224 %d --local_t=%.4f --alpha=%.2f --sample_ratio=%d " % \
# (learning_rate, args.data,local_t, num_roi,crop_size, local_t, alpha,sample_ratio)
# write_slurm_sh(
# "type44crop_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f_ratio%d" % (local_t, alpha, num_roi,crop_size, learning_rate,sample_ratio),
# command_line, queue_name)
# time.sleep(1)
for num_roi in [6]:
for crop_size in [96,192]:
for learning_rate in [0.03,0.05,0.06]:
for alpha in [0.1,0.3,0.5,1.0]: # [0.3, 0.5, 1.0]:
for local_t in [0.20]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=44 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --alpha=%.2f " % \
(learning_rate, args.data,local_t, num_roi,crop_size, local_t, alpha)
write_slurm_sh(
"type44_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (local_t, alpha, num_roi,crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==-44:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.05]:
for alpha in [0.1,0.5]: # [0.3, 0.5, 1.0]:
for local_t in [0.20]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=44 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --alpha=%.2f --align=1 " % \
(learning_rate, args.data,local_t, num_roi,crop_size, local_t, alpha)
write_slurm_sh(
"type44align_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (local_t, alpha, num_roi,crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==45 or args.type==46:
for crop_size in [96]:
for learning_rate in [0.03,0.04,0.05]:
for alpha in [0.1,0.3,0.5,1,2]:
for local_t in [0.2]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d --mask_size %d" \
" --local_t=%.4f --alpha=%.2f " % \
(learning_rate, args.data, local_t, args.type, crop_size,local_t, alpha)
write_slurm_sh(
"type%d_crop_lgq_t_%.3f_alpha_%.2f_%d_lr%.4f" % (args.type, local_t,alpha,
crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type ==47:
min_scale = 96
max_scale = 224
divide_list = [16]
pick_times = [1]
for learning_rate in [0.03,0.05]: # [0.02,0.03,0.04,0.05,0.06,0.1,0.15]:
for pick_time in pick_times:
for divide in divide_list:
check_list = ""
num_list = ""
current_scale = min_scale
while current_scale < max_scale:
check_list += str(current_scale) + " "
num_list += str(pick_time) + " "
current_scale += divide
print(check_list)
print(num_list)
for alpha in [0.1,0.5,1.0]: # [0.1, 0.3, 0.5, 1.0]: # [0.3, 0.5, 1.0]:
for local_t in [0.2]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=47 " \
" --size_crops 224 %s --local_t=%.4f --alpha=%.2f " % \
(learning_rate, args.data, local_t, check_list, local_t, alpha)
write_slurm_sh("type47_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (
local_t, alpha, pick_time, divide, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type ==49:
min_scale = 96
max_scale = 224
divide_list = [2,4,8,16,32]
pick_times = [1]
for learning_rate in [0.06]: # [0.02,0.03,0.04,0.05,0.06,0.1,0.15]:
for pick_time in pick_times:
for divide in divide_list:
check_list = ""
num_list = ""
current_scale = min_scale
while current_scale < max_scale:
check_list += str(current_scale) + " "
num_list += str(pick_time) + " "
current_scale += divide
print(check_list)
print(num_list)
for alpha in [0]: # [0.3, 0.5, 1.0]:
for local_t in [0.2]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=49 --nmb_crops 1 %s" \
" --size_crops 224 %s --local_t=%.4f --alpha=%.2f --align=1 " % \
(learning_rate, args.data, local_t, num_list,check_list, local_t, alpha)
write_slurm_sh_faster(
"type49crop_lgq_t_%.3f_alpha_%.2f_divide%d_lr%.4f" % (
local_t, alpha, divide, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==-49:
#only run on pytorch environment, not base environment
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for alpha in [-0.1,-0.3,-0.5,-1]: # [0.3, 0.5, 1.0]:
for local_t in [0.18]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=49 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --alpha=%.2f --align=1 " % \
(learning_rate, args.data,local_t, num_roi,crop_size, local_t, alpha)
write_slurm_sh_faster(
"type49align_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (local_t, alpha, num_roi,crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==50:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.05]:
for alpha in [0, 0.1,0.5,1.0,2.0]: # [0.3, 0.5, 1.0]:
for local_t in [0.20]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=50 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --alpha=%.2f --align=1 " % \
(learning_rate, args.data,local_t, num_roi,crop_size, local_t, alpha)
write_slurm_sh_faster(
"type50align_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (local_t, alpha, num_roi,crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==51:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.05]:
for alpha in [0, 0.1,0.5,1.0]: # [0.3, 0.5, 1.0]:
for local_t in [0.20]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=51 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --alpha=%.2f --align=1 " % \
(learning_rate, args.data,local_t, num_roi,crop_size, local_t, alpha)
write_slurm_sh_faster(
"type51align_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (local_t, alpha, num_roi,crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==52:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for alpha in [0, 0.1,0.2,0.5,1.0]: # [0.3, 0.5, 1.0]:
for local_t in [0.20]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=52 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --alpha=%.2f --align=1 " % \
(learning_rate, args.data,local_t, num_roi,crop_size, local_t, alpha)
write_slurm_sh_faster(
"type52_1v1_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (local_t, alpha, num_roi,crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==53:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.05]:
for alpha in [0, 0.1,0.5,1.0]: # [0.3, 0.5, 1.0]:
for local_t in [0.20]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=53 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --alpha=%.2f --align=1 " % \
(learning_rate, args.data,local_t, num_roi,crop_size, local_t, alpha)
write_slurm_sh_faster(
"type53align_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (local_t, alpha, num_roi,crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==54:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.05]:
for alpha in [0, 0.1,0.5,1.0]: # [0.3, 0.5, 1.0]:
for local_t in [0.15,0.18,0.20]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=54 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --alpha=%.2f --align=1 " % \
(learning_rate, args.data,local_t, num_roi,crop_size, local_t, alpha)
write_slurm_sh_faster(
"type54align_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (local_t, alpha, num_roi,crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==55:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for alpha in [0.1]: # [0.3, 0.5, 1.0]:
for local_t in [0.20]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=55 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --alpha=%.2f --align=1 " % \
(learning_rate, args.data,local_t, num_roi,crop_size, local_t, alpha)
write_slurm_sh_faster(
"type55align_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (local_t, alpha, num_roi,crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==551:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for alpha in [0.1]: # [0.3, 0.5, 1.0]:
for local_t in [0.20]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=55 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --alpha=%.2f --align=1 " % \
(learning_rate, args.data,local_t, num_roi,crop_size, local_t, alpha)
write_slurm_sh_faster(
"type55align_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (local_t, alpha, num_roi,crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==550:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for alpha in [0.1]: # [0.3, 0.5, 1.0]:
for local_t in [0.20]:
for pred_dim in [256,1024,2048]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=55 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --alpha=%.2f --align=1 --pred_dim=%d " % \
(learning_rate, args.data,local_t, num_roi,crop_size, local_t, alpha,pred_dim)
write_slurm_sh_faster(
"type55dim%d_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (pred_dim,local_t, alpha, num_roi,crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==56:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.05,0.06]:
for alpha in [0, 0.05,0.1,0.2]: # [0.3, 0.5, 1.0]:
for local_t in [0.18, 0.20]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=56 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --alpha=%.2f --align=1 " % \
(learning_rate, args.data,local_t, num_roi,crop_size, local_t, alpha)
write_slurm_sh_faster(
"type56align_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (local_t, alpha, num_roi,crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==58:
for learning_rate in [0.06]:
for alpha in [1.0]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=%.4f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=58 --nmb_crops 2 6 " \
"--size_crops 224 96 --min_scale_crops 0.14 0.05 --max_scale_crops 1.0 0.14 " \
"--alpha=%.4f " \
" " % (learning_rate,args.data,learning_rate/100,alpha)
write_slurm_sh("multimoco_proj_alpha_%.2f_lr_%.4f"%(alpha,learning_rate), command_line, queue_name)
elif args.type==59:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=59 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t)
write_slurm_sh_faster(
"type59_lgq_t_%.3f_%d_%d_lr%.4f" % (local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==60:
for num_roi in [3,6,10,15,20,25,30]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=60 --num_roi=%d " \
" --mask_size=%d --local_t=%.4f --align=1 " % \
(learning_rate, args.data, epoch, 256,
256,learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t)
write_slurm_sh_faster(
"type60_lgq_t_%.3f_%d_%d_lr%.4f" % (local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==61:
#for num_roi in ['','6']:
# for crop_size in ['','96']:
indicate_list=[['',''],['6','96']]
for indication in indicate_list:
num_roi = indication[0]
crop_size= indication[1]
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=61 --nmb_crops 1 %s" \
" --size_crops 224 %s --local_t=%.4f --align=1 " % \
(learning_rate, args.data, epoch, 256, 256,
learning_rate / 100,
local_t, num_roi, crop_size, local_t)
write_slurm_sh_faster(
"type61_lgq_t_%.3f_%s_%s_lr%.4f" % (local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==62:
for learning_rate in [0.06]:
for alpha in [0,1.0]:#0 denotes only shuffling to influence
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=%.4f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=62 --nmb_crops 2 6 " \
"--size_crops 224 96 --min_scale_crops 0.14 0.05 --max_scale_crops 1.0 0.14 " \
"--alpha=%.4f " \
" " % (learning_rate,args.data,learning_rate/100,alpha)
write_slurm_sh("pixelembedshufflemoco_alpha_%.2f_lr_%.4f"%(alpha,learning_rate), command_line, queue_name)
elif args.type==63:
for learning_rate in [0.06]:
for alpha in [0,1.0]:#0 denotes only shuffling to influence
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=%.4f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=63 --nmb_crops 2 6 " \
"--size_crops 224 96 --min_scale_crops 0.14 0.05 --max_scale_crops 1.0 0.14 " \
"--alpha=%.4f " \
" " % (learning_rate,args.data,learning_rate/100,alpha)
write_slurm_sh("pixelGLsync_alpha_%.2f_lr_%.4f"%(alpha,learning_rate), command_line, queue_name)
elif args.type == 64:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for alpha in [0,0.1,0.2,0.5, 1.0]: # [0.3, 0.5, 1.0]:
for local_t in [0.20]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=64 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --alpha=%.2f --align=1 " % \
(learning_rate, args.data, local_t, num_roi, crop_size, local_t, alpha)
write_slurm_sh_faster(
"type64align_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (
local_t, alpha, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type == 65:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for alpha in [0,0.1,0.2,0.5, 1.0]: # [0.3, 0.5, 1.0]:
for local_t in [0.20]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=65 --nmb_crops 1 %d " \
" --size_crops 224 %d --local_t=%.4f --alpha=%.2f --align=1 " % \
(learning_rate, args.data, local_t, num_roi, crop_size, local_t, alpha)
write_slurm_sh_faster(
"type65align_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (
local_t, alpha, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type == 66:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for alpha in [0, 0.1, 0.2, 0.5, 1.0]: # [0.3, 0.5, 1.0]:
for local_t in [0.20]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=66 --nmb_crops 1 %d " \
" --size_crops 224 %d --local_t=%.4f --alpha=%.2f --align=1 " % \
(learning_rate, args.data, local_t, num_roi, crop_size, local_t, alpha)
write_slurm_sh_faster(
"type66align_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (
local_t, alpha, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type == 67:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06,0.08,0.09]:
for alpha in [0, 0.1, 0.2, 0.5]: # [0.3, 0.5, 1.0]:
for local_t in [0.20]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=67 --nmb_crops 1 %d " \
" --size_crops 224 %d --local_t=%.4f --alpha=%.2f --align=1 " % \
(learning_rate, args.data, local_t, num_roi, crop_size, local_t, alpha)
write_slurm_sh_faster(
"type67align_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f" % (
local_t, alpha, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==68:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=68 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t)
write_slurm_sh_faster(
"type68_lgq_t_%.3f_%d_%d_lr%.4f" % (local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==69:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=69 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t)
write_slurm_sh_faster(
"type69_lgq_t_%.3f_%d_%d_lr%.4f" % (local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==70:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=70 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t)
write_slurm_sh_faster(
"type70_lgq_t_%.3f_%d_%d_lr%.4f" % (local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==71:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for alpha in [0,0.05,0.1,0.2]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=71 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 --alpha=%.4f " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t,alpha)
write_slurm_sh_faster(
"type71_lgq_t_%.3f_%d_%d_lr%.4f_alpha%.4f" % (local_t, num_roi, crop_size, learning_rate,alpha),
command_line, queue_name)
time.sleep(1)
elif args.type==72:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=72 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t)
write_slurm_sh_faster(
"type72_lgq_t_%.3f_%d_%d_lr%.4f" % (local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==73:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=73 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t)
write_slurm_sh_faster(
"type73_lgq_t_%.3f_%d_%d_lr%.4f" % (local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==74:
for crop_size in [64,96,128,160,192]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=74 --mask_size %d " \
" --local_t=%.4f --align=1 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, crop_size, local_t)
write_slurm_sh_faster(
"type74_lgq_t_%.3f_mask%d_lr%.4f" % (local_t, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==75:
for num_roi in [3,6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=75 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t)
write_slurm_sh_faster(
"type75_lgq_t_%.3f_%d_%d_lr%.4f" % (local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==76 or args.type==98:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for shuffle_mode in range(9):
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 --shuffle_mode=%d " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, args.type,num_roi, crop_size, local_t,shuffle_mode)
write_slurm_sh_faster(
"type%d_%d_lgq_t_%.3f_%d_%d_lr%.4f" % (args.type,shuffle_mode,local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==-76:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for shuffle_mode in [0,1,7]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=76 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 --shuffle_mode=%d --mlp_bn_stat=0 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t,shuffle_mode)
write_slurm_sh_faster(
"type76_%d_lgq_t_%.3f_%d_%d_lr%.4f" % (shuffle_mode,local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==77:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for shuffle_mode in [0,1,2,3,5,6]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=77 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 --shuffle_mode=%d " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t,shuffle_mode)
write_slurm_sh_faster(
"type77_%d_lgq_t_%.3f_%d_%d_lr%.4f" % (shuffle_mode,local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==78:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for shuffle_mode in [0,1,3,4,5,7]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=78 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 --shuffle_mode=%d " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t,shuffle_mode)
write_slurm_sh_faster(
"type78_%d_lgq_t_%.3f_%d_%d_lr%.4f" % (shuffle_mode,local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==79:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for shuffle_mode in range(2,11):
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=79 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 --shuffle_mode=%d " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t, shuffle_mode)
write_slurm_sh_faster(
"type79_%d_lgq_t_%.3f_%d_%d_lr%.4f" % (
shuffle_mode, local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==80:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for shuffle_mode in [1,5,7]:
for mlp_bn_stat in [0,1]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=80 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 --shuffle_mode=%d" \
" --mlp_bn_stat=%d " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t, shuffle_mode,mlp_bn_stat)
write_slurm_sh_faster(
"type80_%d_lgq_t_%.3f_%d_%d_lr%.4f_bnmode%d" % (
shuffle_mode, local_t, num_roi, crop_size, learning_rate,mlp_bn_stat),
command_line, queue_name)
time.sleep(1)
elif args.type==81:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for shuffle_mode in [1,5,7]:
for mlp_bn_stat in [1]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=81 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 --shuffle_mode=%d" \
" --mlp_bn_stat=%d " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t, shuffle_mode,mlp_bn_stat)
write_slurm_sh_faster(
"type81_%d_lgq_t_%.3f_%d_%d_lr%.4f_bnmode%d" % (
shuffle_mode, local_t, num_roi, crop_size, learning_rate,mlp_bn_stat),
command_line, queue_name)
time.sleep(1)
elif args.type==82:
for num_roi in [6,16,32,64]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for shuffle_mode in [1,5]:
for mlp_bn_stat in [1]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=82 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 --shuffle_mode=%d" \
" --mlp_bn_stat=%d " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t, shuffle_mode,mlp_bn_stat)
write_slurm_sh_faster(
"type82_%d_lgq_t_%.3f_%d_%d_lr%.4f_bnmode%d" % (
shuffle_mode, local_t, num_roi, crop_size, learning_rate,mlp_bn_stat),
command_line, queue_name)
time.sleep(1)
elif args.type == 83 or args.type==84:
for num_roi in [1,3,5,10]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for alpha in [0.1,0.2,0.5,1.0,2.0]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d --num_roi %d" \
" --mask_size %d --local_t=%.4f --align=1 --alpha=%f " \
" " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t,args.type, num_roi, crop_size, local_t, alpha)
write_slurm_sh_faster(
"type%d_lgq_t_%.3f_%d_%d_lr%.4f_alpha%f" % (args.type,
local_t, num_roi, crop_size, learning_rate,alpha),
command_line, queue_name)
time.sleep(1)
elif args.type==85:
for num_roi in [6,16,32,64]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for shuffle_mode in [1,5]:
for mlp_bn_stat in [1]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=85 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 --shuffle_mode=%d" \
" --mlp_bn_stat=%d " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t, shuffle_mode,mlp_bn_stat)
write_slurm_sh_faster(
"type85_%d_lgq_t_%.3f_%d_%d_lr%.4f_bnmode%d" % (
shuffle_mode, local_t, num_roi, crop_size, learning_rate,mlp_bn_stat),
command_line, queue_name)
time.sleep(1)
elif args.type==86:
for num_roi in [6,16,32]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for shuffle_mode in [1,5,7]:
for mlp_bn_stat in [1]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=86 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 --shuffle_mode=%d" % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t, shuffle_mode)
write_slurm_sh_faster(
"type86_%d_lgq_t_%.3f_%d_%d_lr%.4f" % (
shuffle_mode, local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==87 or args.type==88 or args.type==93 or args.type==94 or args.type==95 or args.type==96:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t,args.type, num_roi, crop_size, local_t)
write_slurm_sh_faster(
"type%d_lgq_t_%.3f_%d_%d_lr%.4f" % (args.type,
local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==89 or args.type==90:
for num_roi in [1,5,10]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for alpha in [0.1,0.2,0.5,1.0,2.0]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d --num_roi %d" \
" --mask_size %d --local_t=%.4f --align=1 --alpha=%f " \
" " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t,args.type, num_roi, crop_size, local_t, alpha)
write_slurm_sh_faster(
"type%d_lgq_t_%.3f_%d_%d_lr%.4f_alpha%f" % (args.type,
local_t, num_roi, crop_size, learning_rate,alpha),
command_line, queue_name)
time.sleep(1)
elif args.type==91:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d " \
" --local_t=%.4f --align=1 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, args.type, local_t)
write_slurm_sh_faster(
"type%d_lgq_t_%.3f_lr%.4f" % (args.type, local_t, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==92:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for shuffle_mode in range(4):
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d " \
" --local_t=%.4f --align=1 --shuffle_mode=%d " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, args.type, local_t,shuffle_mode)
write_slurm_sh_faster(
"type%d_%d_lgq_t_%.3f_lr%.4f" % (args.type,shuffle_mode, local_t, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==97:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for shuffle_mode in range(4):
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=97 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 --shuffle_mode=%d" % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t, shuffle_mode)
write_slurm_sh_faster(
"type97_%d_lgq_t_%.3f_%d_%d_lr%.4f" % (
shuffle_mode, local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==99 or args.type==103 or args.type==104 or args.type==105 \
or args.type==106 or args.type==107 or args.type==108 or args.type==109 \
or args.type==110 or args.type==111 or args.type==112 or args.type==113:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for shuffle_mode in [1]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d " \
" --local_t=%.4f --align=1 --shuffle_mode=%d " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, args.type, local_t,shuffle_mode)
write_slurm_sh_faster(
"type%d_%d_lgq_t_%.3f_lr%.4f" % (args.type,shuffle_mode, local_t, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==126 or args.type==127 or args.type==129 or args.type==131:
for learning_rate in [0.03]:
for local_t in [0.2]:
for epoch in [100]:
for shuffle_mode in range(8):
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d " \
" --local_t=%.4f --align=1 --shuffle_mode=%d --use_fp16=1 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, args.type, local_t,shuffle_mode)
write_slurm_sh_faster(
"type%dablation_%d_lgq_t_%.3f_lr%.4f" % (args.type,shuffle_mode, local_t, learning_rate),
command_line, queue_name,environment=1)
time.sleep(1)
elif args.type==133 or args.type==134:
for learning_rate in [0.03]:
for local_t in [0.2]:
for epoch in [100]:
for shuffle_mode in range(3):
for momentum_weight_decay in [0.9,0.99,0.999]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d " \
" --local_t=%.4f --align=1 --shuffle_mode=%d --use_fp16=1 --momentum_stat=%f" % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, args.type, local_t, shuffle_mode,momentum_weight_decay)
write_slurm_sh_faster(
"type%dablation_%d_%f_lgq_t_%.3f_lr%.4f" % (
args.type, shuffle_mode,momentum_weight_decay, local_t, learning_rate),
command_line, queue_name, environment=1)
time.sleep(1)
elif args.type==128 or args.type==130 or args.type==132 or args.type==135 or args.type==136:
for learning_rate in [0.03]:
for local_t in [0.2]:
for epoch in [100]:
for group_norm_size in [1,2,4,8,16,32,64,128]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d " \
" --local_t=%.4f --align=1 --group_norm_size=%d --use_fp16=1 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, args.type, local_t,group_norm_size)
write_slurm_sh_faster(
"type%dgroupablation_%d_lgq_t_%.3f_lr%.4f" % (args.type,group_norm_size, local_t, learning_rate),
command_line, queue_name,environment=1)
time.sleep(1)
elif args.type==152:
for learning_rate in [0.03]:
for local_t in [0.2]:
for epoch in [100]:
for group_norm_size in [1,2,4,8,16,32,64,128]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d " \
" --local_t=%.4f --align=1 --group_norm_size=%d --use_fp16=1 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, args.type, local_t,group_norm_size)
write_slurm_sh_faster(
"type%dgroup_%d_lgq_t_%.3f_lr%.4f" % (args.type,group_norm_size, local_t, learning_rate),
command_line, queue_name,environment=0)
time.sleep(1)
elif args.type==137 or args.type==138:
for learning_rate in [0.03]:
for local_t in [0.2]:
for epoch in [100]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d " \
" --local_t=%.4f --align=1 --use_fp16=1 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, args.type, local_t)
write_slurm_sh_faster(
"type%d2bnablation_lgq_t_%.3f_lr%.4f" % (args.type,local_t, learning_rate),
command_line, queue_name,environment=1)
time.sleep(1)
elif args.type==118:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for shuffle_mode in [1]:
for conv_size in [1,2,3,4]:
for stride_size in [1,2,3]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d " \
" --local_t=%.4f --align=1 --shuffle_mode=%d --loco_conv_size=%d " \
"--loco_conv_stride=%d" % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, args.type, local_t, shuffle_mode,conv_size,stride_size)
write_slurm_sh_faster(
"type%d_%d_conv%d_%d_lr%.4f" % (args.type, shuffle_mode, conv_size,
stride_size,learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==114:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for group_norm_size in [1,2,4,8]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d " \
" --local_t=%.4f --align=1 --group_norm_size=%d " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, args.type, local_t,group_norm_size)
write_slurm_sh_faster(
"type%d_%d_lgq_t_%.3f_lr%.4f" % (args.type,group_norm_size, local_t, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==115 or args.type==116 or args.type==117 or args.type==120 \
or args.type==121 or args.type==122 or args.type==123 or args.type==124:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for group_norm_size in [1,8]:
for alpha in [1.0,3.0]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --min_scale_crops 0.14 0.05" \
" --size_crops 224 96 --nmb_crops 2 6 --max_scale_crops 1.0 0.14 --type=%d " \
" --local_t=%.4f --align=1 --group_norm_size=%d --alpha=%f " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, args.type, local_t,group_norm_size,alpha)
write_slurm_sh_faster(
"type%d_%d_alpha%f_lgq_t_%.3f_lr%.4f" % (args.type,group_norm_size,alpha, local_t, learning_rate),
command_line, queue_name,gpu_memory=True)
time.sleep(1)
elif args.type==-120:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for group_norm_size in [1]:
for num_crops in [4,8,16,32]:
same_alpha = int(num_crops / 2) - 1
iter_alpha =[same_alpha,1.0] if same_alpha!=1 else [1.0]
for alpha in iter_alpha:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --min_scale_crops 0.14 " \
" --size_crops 96 --nmb_crops %d --max_scale_crops 1.0 --type=%d " \
" --local_t=%.4f --align=1 --group_norm_size=%d --alpha=%f --use_fp16=1" % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_crops,abs(args.type), local_t, group_norm_size, alpha)
write_slurm_sh_faster(
"type%d_%d_%d_alpha%f_lgq_t_%.3f_lr%.4f" % (
args.type,num_crops, group_norm_size, alpha, local_t, learning_rate),
command_line, queue_name, gpu_memory=True,environment=1)
time.sleep(1)
elif args.type==139 or args.type==140 or args.type==141 or args.type==142 \
or args.type==143 or args.type==144 or args.type==145 or args.type==146 or args.type==147:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for group_norm_size in [1]:
for num_crops in [4,8,16]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --min_scale_crops 0.14 " \
" --size_crops 96 --nmb_crops %d --max_scale_crops 1.0 --type=%d " \
" --local_t=%.4f --align=1 --group_norm_size=%d --use_fp16=1 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_crops,args.type, local_t, group_norm_size)
write_slurm_sh_faster(
"type%dviewnorm_%d_%d_lgq_t_%.3f_lr%.4f" % (
args.type, num_crops,group_norm_size, local_t, learning_rate),
command_line, queue_name, gpu_memory=True,environment=1)
time.sleep(1)
elif args.type==148 or args.type==149 or args.type==150:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for group_norm_size in [1]:
for num_crops in [4,8,16,32]:
for crop_size in [224,96]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --min_scale_crops 0.2 " \
" --size_crops %d --nmb_crops %d --max_scale_crops 1.0 --type=%d " \
" --local_t=%.4f --align=1 --group_norm_size=%d --use_fp16=1 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, crop_size,num_crops, args.type, local_t, group_norm_size)
write_slurm_sh_faster(
"type%dviewnorm_%d_%d_group%d_lgq_t_%.3f_lr%.4f" % (
args.type, num_crops,crop_size, group_norm_size, local_t, learning_rate),
command_line, queue_name, gpu_memory=True, environment=1)
time.sleep(1)
elif args.type==151:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for group_norm_size in [1]:
for alpha in [1.0]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 " \
" --type=%d --min_scale_crops 0.14 0.05 " \
" --size_crops 224 96 --nmb_crops 4 6 --max_scale_crops 1.0 0.14" \
" --local_t=%.4f --align=1 --group_norm_size=%d --use_fp16=1 --alpha 1.0" % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, args.type, local_t, group_norm_size)
write_slurm_sh_faster(
"type%dmultiquery_viewkey_group%d_lgq_t_%.3f_lr%.4f" % (
args.type, group_norm_size, local_t, learning_rate),
command_line, queue_name, gpu_memory=True, environment=1)
time.sleep(1)
elif args.type==125:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for momentum_stat in [0.9,0.99,0.999]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --min_scale_crops 0.14 0.05" \
" --size_crops 224 96 --nmb_crops 2 6 --max_scale_crops 1.0 0.14 --type=%d " \
" --local_t=%.4f --align=1 --momentum_stat=%f " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,256,
learning_rate * args.node / 100,
local_t, args.type, local_t, momentum_stat)
write_slurm_sh_faster(
"type%d_momentum%f_lgq_t_%.3f_lr%.4f" % (
args.type, momentum_stat, local_t, learning_rate),
command_line, queue_name, gpu_memory=True)
time.sleep(1)
elif args.type==-108:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for batch_size in [1024]:
for shuffle_mode in [1]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d " \
" --local_t=%.4f --align=1 --shuffle_mode=%d " % \
(learning_rate * batch_size/256, args.data, epoch, batch_size,
256,
learning_rate * batch_size/256/ 100,
local_t, abs(args.type), local_t,shuffle_mode)
write_slurm_sh_faster(
"type%d_%d_lgq_t_%.3f_lr%.4f" % (args.type,shuffle_mode, local_t, learning_rate*batch_size/256),
command_line, queue_name,gpu_memory=True)
time.sleep(1)
elif args.type==100:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for group_norm_size in [1,2,4,8]:
command_line = "python3 main_adco.py --mode=1 --lr=%f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 --group_norm_size=%d " % \
(learning_rate/2, args.data, epoch, 128,
128,
learning_rate/ 200,
local_t,args.type, num_roi, crop_size, local_t,group_norm_size)
write_slurm_sh_faster(
"type%d_group%d_lgq_t_%.3f_%d_%d_lr%.4f" % (args.type,group_norm_size,
local_t, num_roi, crop_size, learning_rate),
command_line, queue_name,gpu_per_node=args.gpu)
time.sleep(1)
elif args.type==101:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for group_num in [1,2,4,8]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=101 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 --group_norm_size=%d " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t, group_num)
write_slurm_sh_faster(
"type101_%d_lgq_t_%.3f_%d_%d_lr%.4f" % (
group_num, local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.type==102:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for shuffle_mode in [0,1,7]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 --shuffle_mode=%d " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, args.type,num_roi, crop_size, local_t,shuffle_mode)
write_slurm_sh_faster(
"type%d_%d_lgq_t_%.3f_%d_%d_lr%.4f" % (args.type,shuffle_mode,local_t, num_roi, crop_size, learning_rate),
command_line, queue_name)
time.sleep(1)
elif args.mode==2:
if args.type==58:
for learning_rate in [0.06]:
for alpha in [1.0]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=100 " \
"--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=%.4f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=0.2 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=58 --nmb_crops 2 6 " \
"--size_crops 224 96 --min_scale_crops 0.14 0.05 --max_scale_crops 1.0 0.14 " \
"--alpha=%.4f " \
" " % (learning_rate,args.data,learning_rate/100,alpha)
write_slurm_sh_multi("multimoco_proj_alpha_%.2f_lr_%.4f"%(alpha,learning_rate), command_line, queue_name,
nodes=args.node,gpu_per_node=args.gpu)
elif args.type==59:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [800]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=59 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 " % \
(learning_rate*args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate*args.node / 100,
local_t, num_roi, crop_size, local_t)
write_slurm_sh_multi(
"type59_lgq_t_%.3f_%d_%d_lr%.4f" % (local_t, num_roi, crop_size, learning_rate),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu)
elif args.type==61:
for num_roi in ['','6']:
for crop_size in ['','96']:
for learning_rate in [0.04,0.06,0.08]:
for local_t in [0.2]:
for epoch in [100]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=61 --nmb_crops 1 %s" \
" --size_crops 224 %s --local_t=%.4f --align=1 --ngpu=%d " % \
(learning_rate, args.data, epoch, 256,256,
learning_rate / 100,
local_t, num_roi, crop_size, local_t,args.gpu)
write_slurm_sh_multi(
"type61_lgq_t_%.3f_%s_%s_lr%.4f" % (local_t, num_roi, crop_size, learning_rate),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu)
time.sleep(1)
elif args.type==77:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for shuffle_mode in [5]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=77 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 --shuffle_mode=%d " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t,shuffle_mode)
write_slurm_sh_multi(
"type77_%d_lgq_t_%.3f_%d_%d_lr%.4f" % (shuffle_mode,local_t, num_roi, crop_size, learning_rate*args.node),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu)
time.sleep(1)
elif args.type==87 or args.type==88 or args.type==94:
if args.type==87:
roi_num_list=[32]
elif args.type==88:
roi_num_list = [6,32]
else:
roi_num_list = [0]
for num_roi in roi_num_list:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [800]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 128,
learning_rate * args.node / 100,
local_t,args.type, num_roi, crop_size, local_t)
if args.queue<=1:
write_slurm_sh_multi2(
"type%d_lgq_t_%.3f_%d_%d_lr%.4f_epoch%d" % (args.type,
local_t, num_roi, crop_size,
learning_rate, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu)
else:
write_slurm_sh_multi(
"type%d_lgq_t_%.3f_%d_%d_lr%.4f_epoch%d" % (args.type,
local_t, num_roi, crop_size, learning_rate,epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu)
time.sleep(1)
elif args.type == 100:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for group_norm_size in [1,2,4,8,16]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 --group_norm_size=%d " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t,args.type, num_roi, crop_size, local_t,group_norm_size)
if args.node>=4:
command_line += " --warmup_epochs=10 "
if args.queue <= 1:
write_slurm_sh_multi2(
"type%d_group%d_lgq_t_%.3f_%d_%d_lr%.4f" % (args.type,group_norm_size,
local_t, num_roi, crop_size, learning_rate),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu)
else:
write_slurm_sh_multi(
"type%d_group%d_lgq_t_%.3f_%d_%d_lr%.4f" % (args.type, group_norm_size,
local_t, num_roi, crop_size,
learning_rate),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu)
time.sleep(1)
elif args.type==101:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [100]:
for group_num in [1,2,4,8,16]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=101 --nmb_crops 1 %d" \
" --size_crops 224 %d --local_t=%.4f --align=1 --group_norm_size=%d " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
args.node * 256,
learning_rate * args.node / 100,
local_t, num_roi, crop_size, local_t, group_num)
if args.node >= 4:
command_line += " --warmup_epochs=10 "
if args.queue <= 1:
write_slurm_sh_multi2(
"type101_%d_lgq_t_%.3f_%d_%d_lr%.4f" % (
group_num, local_t, num_roi, crop_size, learning_rate),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu)
else:
write_slurm_sh_multi(
"type101_%d_lgq_t_%.3f_%d_%d_lr%.4f" % (
group_num, local_t, num_roi, crop_size, learning_rate),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu)
time.sleep(1)
elif args.type==119:
for batch_size in [4096]:
#for crop_size in [96]:
if True:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [800]:
for group_num in [1,8,16,32]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=%d " \
" --local_t=%.4f --align=1 --group_norm_size=%d --use_fp16=1 " % \
(learning_rate * batch_size / 256, args.data, epoch, batch_size,
256,
learning_rate * batch_size / 256 / 100,
local_t, abs(args.type), local_t,group_num)
command_line += " --warmup_epochs=10 "
write_slurm_sh_multi(
"mocov2bigbatch_type%d_%d_%f_lgq_t_%.3f_epoch%d" % (
args.type, group_num, learning_rate, local_t, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu, gpu_memory=True,
environment=1)
elif args.type==115 or args.type==120:
for batch_size in [2048]:
for learning_rate in [0.045]:
for local_t in [0.2]:
for epoch in [800]:
for group_norm_size in [64]:
for alpha in [1.0]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=10 --tensorboard=1 --min_scale_crops 0.14 0.05" \
" --size_crops 224 96 --nmb_crops 2 6 --max_scale_crops 1.0 0.14 --type=%d " \
" --local_t=%.4f --align=1 --group_norm_size=%d --alpha=%f --use_fp16=1 " % \
(learning_rate * batch_size/256, args.data, epoch, batch_size,
256,
learning_rate * batch_size/256/ 100,
local_t, args.type, local_t,group_norm_size,alpha)
write_slurm_sh_multi(
"multimoco_type%d_%d_alpha%f_lgq_t_%.3f_lr%.4f" % (args.type,group_norm_size,alpha, local_t, learning_rate),
command_line, queue_name,nodes=args.node, gpu_per_node=args.gpu,gpu_memory=True,environment=1)
time.sleep(1)
elif args.type==149:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [1000]:
for group_norm_size in [1]:
for num_crops in [4]:
for crop_size in [224]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --min_scale_crops 0.2 " \
" --size_crops %d --nmb_crops %d --max_scale_crops 1.0 --type=%d " \
" --local_t=%.4f --align=1 --group_norm_size=%d --use_fp16=1 " % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
512,
learning_rate * args.node / 100,
local_t, crop_size,num_crops, args.type, local_t, group_norm_size)
write_slurm_sh_multi2(
"mocov2_%dview_type%d_%d_%f_lgq_t_%.3f_epoch%d" % (
args.type, num_crops,group_norm_size, learning_rate, local_t, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu, gpu_memory=False,
environment=0)
time.sleep(1)
elif args.type==151:
for learning_rate in [0.06]:
for local_t in [0.2]:
for epoch in [1000]:
for group_norm_size in [1]:
for alpha in [1.0]:
command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \
"--dist_url=tcp://localhost:10031 --epochs=%d " \
"--batch_size=%d --knn_batch_size=%d --cos=1 --lr_final=%.8f " \
"--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \
"--moco_m=0.999 --moco_k=65536 --moco_t=%.4f " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 " \
" --type=%d --min_scale_crops 0.14 0.05 " \
" --size_crops 224 96 --nmb_crops 4 6 --max_scale_crops 1.0 0.14" \
" --local_t=%.4f --align=1 --group_norm_size=%d --use_fp16=1 --alpha=1.0" % \
(learning_rate * args.node, args.data, epoch, args.node * 256,
512,
learning_rate * args.node / 100,
local_t, args.type, local_t, group_norm_size)
write_slurm_sh_multi(
"type%dmultiquery_viewkey_group%d_lgq_t_%.3f_lr%.4f" % (
args.type, group_norm_size, local_t, learning_rate),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=True, environment=1)
time.sleep(1)
elif args.mode==6:
if args.type==0 or args.type==1 or args.type==2 or args.type==3:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.9]:
for local_t in [1.0]:
for epoch in [100]:
for batch_size in [512]:
command_line = "python3 main_adco.py --mode=6 --type=%d --data=%s " \
"--epochs=%d --start_epoch=0 --batch_size=%d --lr=0.9 " \
"--weight_decay=1e-6 --dist_url=tcp://localhost:10031 --rank=0 " \
"--multiprocessing_distributed=1 --world_size=1 --moco_dim=256 " \
"--mlp_dim=4096 --moco_m=0.99 --moco_t=%f --warmup_epochs=10 --nmb_crops 1 %d " \
" --size_crops 224 %d --align=1 --knn_neighbor=20 --knn_freq=1 --tensorboard=1 " \
"--knn_batch_size=%d " \
% (
args.type, args.data, epoch, batch_size,local_t, num_roi, crop_size, args.node * 64)
if args.node == 1:
write_slurm_sh_faster("mocov3type%d_lgq_t_%.3f_%d_%d_epoch%d" % (args.type,
local_t, num_roi,
crop_size,
epoch),
command_line, queue_name)
else:
if args.queue <= 1:
write_slurm_sh_multi2(
"mocov3type%d_lgq_t_%.3f_%d_%d_epoch%d" % (args.type,
local_t, num_roi, crop_size,
epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu)
else:
write_slurm_sh_multi(
"mocov3type%d_lgq_t_%.3f_%d_%d_epoch%d" % (
args.type, local_t, num_roi, crop_size, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu)
time.sleep(1)
elif args.type==4 or args.type==5 or args.type==6:
for num_roi in [1]:
for crop_size in [96]:
for learning_rate in [0.9]:
for local_t in [1.0]:
for epoch in [100]:
for batch_size in [1024]:
for group_norm_size in [1,2,4,8]:
command_line = "python3 main_adco.py --mode=6 --type=%d --data=%s " \
"--epochs=%d --start_epoch=0 --batch_size=%d --lr=%f " \
"--weight_decay=1e-6 --dist_url=tcp://localhost:10031 --rank=0 " \
"--multiprocessing_distributed=1 --world_size=1 --moco_dim=256 " \
"--mlp_dim=4096 --moco_m=0.99 --moco_t=%f --warmup_epochs=10 --nmb_crops 1 %d " \
" --size_crops 224 %d --align=1 --knn_neighbor=20 --knn_freq=1 --tensorboard=1 " \
"--knn_batch_size=%d --group_norm_size=%d " \
% (args.type, args.data, epoch, batch_size, learning_rate,local_t, num_roi,
crop_size, args.node * 64,group_norm_size)
if args.node == 1:
write_slurm_sh_faster("mocov3type%d_%d_%flgq_t_%.3f_%d_%d_epoch%d" % (args.type,
group_norm_size,
learning_rate,
local_t,
num_roi,
crop_size,
epoch),
command_line, queue_name,gpu_memory=True)
else:
if args.queue <= 1:
write_slurm_sh_multi2(
"mocov3type%d_%d_%f_lgq_t_%.3f_%d_%d_epoch%d" % (args.type,group_norm_size,learning_rate,
local_t, num_roi, crop_size,
epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu)
else:
write_slurm_sh_multi(
"mocov3type%d_%d_%f_lgq_t_%.3f_%d_%d_epoch%d" % (
args.type, group_norm_size,learning_rate,local_t, num_roi, crop_size, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu)
time.sleep(1)
elif args.type==7 or args.type==8:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.9]:
for local_t in [1.0]:
for epoch in [100]:
for batch_size in [1024]:
for group_norm_size in [1,2,4,8]:
command_line = "python3 main_adco.py --mode=6 --type=%d --data=%s " \
"--epochs=%d --start_epoch=0 --batch_size=%d --lr=%f " \
"--weight_decay=1e-6 --dist_url=tcp://localhost:10031 --rank=0 " \
"--multiprocessing_distributed=1 --world_size=1 --moco_dim=256 " \
"--mlp_dim=4096 --moco_m=0.99 --moco_t=%f --warmup_epochs=10 --nmb_crops 1 %d " \
" --size_crops 224 %d --align=1 --knn_neighbor=20 --knn_freq=1 --tensorboard=1 " \
"--knn_batch_size=%d --group_norm_size=%d --use_fp16=1 " \
% (args.type, args.data, epoch, batch_size, learning_rate,local_t, num_roi,
crop_size, args.node * 64,group_norm_size)
if args.node == 1:
write_slurm_sh_faster("mocov3type%d_%d_%flgq_t_%.3f_%d_%d_epoch%d" % (args.type,
group_norm_size,
learning_rate,
local_t,
num_roi,
crop_size,
epoch),
command_line, queue_name,gpu_memory=True,environment=1)
else:
if args.queue <= 1:
write_slurm_sh_multi2(
"mocov3type%d_%d_%f_lgq_t_%.3f_%d_%d_epoch%d" % (args.type,group_norm_size,learning_rate,
local_t, num_roi, crop_size,
epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,gpu_memory=True,environment=1)
else:
write_slurm_sh_multi(
"mocov3type%d_%d_%f_lgq_t_%.3f_%d_%d_epoch%d" % (
args.type, group_norm_size,learning_rate,local_t, num_roi, crop_size, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,gpu_memory=True,environment=1)
time.sleep(1)
elif args.type==-7:
combine_choice=[1024,16]#[[1024,16],[2048,32],[4096,64]]
for num_roi in [10]:
for crop_size in [96]:
for learning_rate in [0.3]:
for local_t in [1.0]:
for epoch in [1000]:
for batch_size,group_norm_size in combine_choice:
command_line = "python3 main_adco.py --mode=6 --type=7 --data=%s " \
"--epochs=%d --start_epoch=0 --batch_size=%d --lr=%f " \
"--weight_decay=1.5e-6 --dist_url=tcp://localhost:10031 --rank=0 " \
"--multiprocessing_distributed=1 --world_size=1 --moco_dim=256 " \
"--mlp_dim=4096 --moco_m=0.996 --moco_t=%f --warmup_epochs=10 --nmb_crops 1 %d " \
" --size_crops 224 %d --align=1 --knn_neighbor=20 --knn_freq=1 --tensorboard=1 " \
"--knn_batch_size=%d --group_norm_size=%d --use_fp16=1 " \
% ( args.data, epoch, batch_size, learning_rate,local_t, num_roi,
crop_size, args.node * 64,group_norm_size)
if args.queue <= 1:
write_slurm_sh_multi2(
"mocov3type%d_%d_%f_lgq_t_%.3f_%d_%d_epoch%d" % (
args.type, group_norm_size, learning_rate,
local_t, num_roi, crop_size,
epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=True, environment=1)
else:
write_slurm_sh_multi(
"mocov3type%d_%d_%f_lgq_t_%.3f_%d_%d_epoch%d" % (
args.type, group_norm_size, learning_rate, local_t, num_roi, crop_size,
epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=True, environment=1)
time.sleep(1)
elif args.type==-13:
combine_choice=[[4096,1],[4096,64]]#[[1024,16],[2048,32],[4096,64]]
for num_roi in [20]:
for crop_size in [96]:
for learning_rate in [0.3]:
for local_t in [1.0]:
for epoch in [1000]:
for batch_size,group_norm_size in combine_choice:
command_line = "python3 main_adco.py --mode=6 --type=13 --data=%s " \
"--epochs=%d --start_epoch=0 --batch_size=%d --lr=%f " \
"--weight_decay=1.5e-6 --dist_url=tcp://localhost:10031 --rank=0 " \
"--multiprocessing_distributed=1 --world_size=1 --moco_dim=256 " \
"--mlp_dim=4096 --moco_m=0.996 --moco_t=%f --warmup_epochs=10 --nmb_crops 1 %d " \
" --size_crops 224 %d --align=1 --knn_neighbor=20 --knn_freq=1 --tensorboard=1 " \
"--knn_batch_size=%d --group_norm_size=%d --use_fp16=1 " \
% ( args.data, epoch, batch_size, learning_rate,local_t, num_roi,
crop_size, args.node * 64,group_norm_size)
if args.queue <= 1:
write_slurm_sh_multi2(
"mocov3type%d_%d_%f_lgq_t_%.3f_%d_%d_epoch%d" % (
args.type, group_norm_size, learning_rate,
local_t, num_roi, crop_size,
epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=True, environment=1)
else:
write_slurm_sh_multi(
"mocov3type%d_%d_%f_lgq_t_%.3f_%d_%d_epoch%d" % (
args.type, group_norm_size, learning_rate, local_t, num_roi, crop_size,
epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=True, environment=1)
time.sleep(1)
elif args.type==9 or args.type==10:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.9]:
for local_t in [1.0]:
for epoch in [100]:
for batch_size in [1024]:
for ema_param in [0.001,0.01,0.1]:
command_line = "python3 main_adco.py --mode=6 --type=%d --data=%s " \
"--epochs=%d --start_epoch=0 --batch_size=%d --lr=%f " \
"--weight_decay=1e-6 --dist_url=tcp://localhost:10031 --rank=0 " \
"--multiprocessing_distributed=1 --world_size=1 --moco_dim=256 " \
"--mlp_dim=4096 --moco_m=0.99 --moco_t=%f --warmup_epochs=10 --nmb_crops 1 %d " \
" --size_crops 224 %d --align=1 --knn_neighbor=20 --knn_freq=1 --tensorboard=1 " \
"--knn_batch_size=%d --momentum_stat=%f --use_fp16=1 " \
% (args.type, args.data, epoch, batch_size, learning_rate,local_t, num_roi,
crop_size, args.node * 64,ema_param)
if args.node == 1:
write_slurm_sh_faster("mocov3type%d_%f_%flgq_t_%.3f_%d_%d_epoch%d" % (args.type,
ema_param,
learning_rate,
local_t,
num_roi,
crop_size,
epoch),
command_line, queue_name,gpu_memory=True,environment=1)
else:
if args.queue <= 1:
write_slurm_sh_multi2(
"mocov3type%d_%d_%f_lgq_t_%.3f_%d_%d_epoch%d" % (args.type,group_norm_size,learning_rate,
local_t, num_roi, crop_size,
epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,gpu_memory=True,environment=1)
else:
write_slurm_sh_multi(
"mocov3type%d_%d_%f_lgq_t_%.3f_%d_%d_epoch%d" % (
args.type, group_norm_size,learning_rate,local_t, num_roi, crop_size, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,gpu_memory=True,environment=1)
time.sleep(1)
elif args.type==11:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.9]:
for local_t in [1.0]:
for epoch in [100]:
for batch_size in [1024]:
for ema_param in [0.999]:
for group_norm_size in [1,4,8,16]:
command_line = "python3 main_adco.py --mode=6 --type=%d --data=%s " \
"--epochs=%d --start_epoch=0 --batch_size=%d --lr=%f " \
"--weight_decay=1e-6 --dist_url=tcp://localhost:10031 --rank=0 " \
"--multiprocessing_distributed=1 --world_size=1 --moco_dim=256 " \
"--mlp_dim=4096 --moco_m=0.99 --moco_t=%f --warmup_epochs=10 --nmb_crops 1 %d " \
" --size_crops 224 %d --align=1 --knn_neighbor=20 --knn_freq=1 --tensorboard=1 " \
"--knn_batch_size=%d --momentum_stat=%f --use_fp16=1 --group_norm_size=%d " \
% (args.type, args.data, epoch, batch_size, learning_rate,local_t, num_roi,
crop_size, args.node * 64,ema_param,group_norm_size)
if args.node == 1:
write_slurm_sh_faster(
"mocov3type%d_%f_%d_%flgq_t_%.3f_%d_%d_epoch%d" % (args.type,
group_norm_size,
ema_param,
learning_rate,
local_t,
num_roi,
crop_size,
epoch),
command_line, queue_name, gpu_memory=True, environment=1)
else:
if args.queue <= 1:
write_slurm_sh_multi2(
"mocov3type%d_%d_%f_%f_lgq_t_%.3f_%d_%d_epoch%d" % (
args.type, group_norm_size,ema_param, learning_rate,
local_t, num_roi, crop_size,
epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=True, environment=1)
else:
write_slurm_sh_multi(
"mocov3type%d_%d_%f_%f_lgq_t_%.3f_%d_%d_epoch%d" % (
args.type, group_norm_size,ema_param, learning_rate, local_t, num_roi,
crop_size, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=True, environment=1)
time.sleep(1)
elif args.type==12:
for num_roi in [6]:
for crop_size in [96]:
for learning_rate in [0.9]:
for local_t in [1.0]:
for epoch in [100]:
for batch_size in [1024]:
for group_norm_size in [8]:
command_line = "python3 main_adco.py --mode=6 --type=%d --data=%s " \
"--epochs=%d --start_epoch=0 --batch_size=%d --lr=%f " \
"--weight_decay=1e-6 --dist_url=tcp://localhost:10031 --rank=0 " \
"--multiprocessing_distributed=1 --world_size=1 --moco_dim=256 " \
"--mlp_dim=4096 --moco_m=0.99 --moco_t=%f --warmup_epochs=10 --nmb_crops 1 %d " \
" --size_crops 224 %d --align=1 --knn_neighbor=20 --knn_freq=1 --tensorboard=1 " \
"--knn_batch_size=%d --group_norm_size=%d --use_fp16=1 " \
% (args.type, args.data, epoch, batch_size, learning_rate,local_t, num_roi,
crop_size, args.node * 64,group_norm_size)
if args.node == 1:
write_slurm_sh_faster("mocov3type%d_%d_%flgq_t_%.3f_%d_%d_epoch%d" % (args.type,
group_norm_size,
learning_rate,
local_t,
num_roi,
crop_size,
epoch),
command_line, queue_name,gpu_memory=True,environment=1)
else:
if args.queue <= 1:
write_slurm_sh_multi2(
"mocov3type%d_%d_%f_lgq_t_%.3f_%d_%d_epoch%d" % (args.type,group_norm_size,learning_rate,
local_t, num_roi, crop_size,
epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,gpu_memory=False,environment=0)
else:
write_slurm_sh_multi(
"mocov3type%d_%d_%f_lgq_t_%.3f_%d_%d_epoch%d" % (
args.type, group_norm_size,learning_rate,local_t, num_roi, crop_size, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,gpu_memory=True,environment=1)
time.sleep(1)
elif args.type==13 or args.type==14 or args.type==15:
for learning_rate in [0.9]:
for local_t in [1.0]:
for epoch in [100]:
for batch_size in [1024]:
for group_norm_size in [1,4,8,16]:
command_line = "python3 main_adco.py --mode=6 --type=%d --data=%s " \
"--epochs=%d --start_epoch=0 --batch_size=%d --lr=%f " \
"--weight_decay=1e-6 --dist_url=tcp://localhost:10031 --rank=0 " \
"--multiprocessing_distributed=1 --world_size=1 --moco_dim=256 " \
"--mlp_dim=4096 --moco_m=0.99 --moco_t=%f --warmup_epochs=10 " \
" --align=1 --knn_neighbor=20 --knn_freq=1 --tensorboard=1 " \
"--knn_batch_size=%d --group_norm_size=%d --use_fp16=1 " \
% (args.type, args.data, epoch, batch_size, learning_rate,
local_t, args.node * 64, group_norm_size)
if args.node == 1:
write_slurm_sh_faster("mocov3type%d_%d_%flgq_t_%.3f_epoch%d" % (args.type,
group_norm_size,
learning_rate,
local_t,
epoch),
command_line, queue_name, gpu_memory=True, environment=1)
else:
if args.queue <= 1:
write_slurm_sh_multi2(
"mocov3type%d_%d_%f_lgq_t_%.3f_epoch%d" % (
args.type, group_norm_size, learning_rate,
local_t, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=False, environment=0)
else:
write_slurm_sh_multi(
"mocov3type%d_%d_%f_lgq_t_%.3f_epoch%d" % (
args.type, group_norm_size, learning_rate, local_t, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=True, environment=1)
time.sleep(1)
elif args.type==19:
for learning_rate in [0.9]:
for local_t in [1.0]:
for epoch in [100]:
for batch_size in [1024]:
for group_norm_size in [1,4,8,16,32]:
for key_group_norm_size in [1,4,8,16,32]:
command_line = "python3 main_adco.py --mode=6 --type=%d --data=%s " \
"--epochs=%d --start_epoch=0 --batch_size=%d --lr=%f " \
"--weight_decay=1e-6 --dist_url=tcp://localhost:10031 --rank=0 " \
"--multiprocessing_distributed=1 --world_size=1 --moco_dim=256 " \
"--mlp_dim=4096 --moco_m=0.99 --moco_t=%f --warmup_epochs=10 " \
" --align=1 --knn_neighbor=20 --knn_freq=1 --tensorboard=1 " \
"--knn_batch_size=%d --group_norm_size=%d --key_group=%d " \
"--use_fp16=1 " \
% (args.type, args.data, epoch, batch_size, learning_rate,
local_t, args.node * 64, group_norm_size,key_group_norm_size)
if args.node == 1:
write_slurm_sh_faster("mocov3type%d_%d_%d_%flgq_t_%.3f_epoch%d" % (args.type,
group_norm_size,
key_group_norm_size,
learning_rate,
local_t,
epoch),
command_line, queue_name, gpu_memory=True, environment=1)
else:
if args.queue <= 3:
write_slurm_sh_multi2(
"mocov3type%d_%d_%d_%f_lgq_t_%.3f_epoch%d" % (
args.type, group_norm_size, key_group_norm_size,learning_rate,
local_t, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=False, environment=0)
else:
write_slurm_sh_multi(
"mocov3type%d_%d_%d_%f_lgq_t_%.3f_epoch%d" % (
args.type, group_norm_size, key_group_norm_size,learning_rate, local_t, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=True, environment=1)
time.sleep(1)
elif args.type==16:
for learning_rate in [0.9]:
for local_t in [1.0]:
for epoch in [100]:
for batch_size in [1024]:
for crop_size in [4,8,16]:
command_line = "python3 main_adco.py --mode=6 --type=%d --data=%s " \
"--epochs=%d --start_epoch=0 --batch_size=%d --lr=%f " \
"--weight_decay=1e-6 --dist_url=tcp://localhost:10031 --rank=0 " \
"--multiprocessing_distributed=1 --world_size=1 --moco_dim=256 " \
"--mlp_dim=4096 --moco_m=0.99 --moco_t=%f --warmup_epochs=10 " \
" --align=1 --knn_neighbor=20 --knn_freq=1 --tensorboard=1 " \
"--knn_batch_size=%d --group_norm_size=1 --use_fp16=1 " \
"--nmb_crops %d" \
% (args.type, args.data, epoch, batch_size, learning_rate,
local_t, args.node * 64,crop_size )
if args.node == 1:
write_slurm_sh_faster("mocov3type%d_%d_%flgq_t_%.3f_epoch%d" % (args.type,
crop_size,
learning_rate,
local_t,
epoch),
command_line, queue_name, gpu_memory=True, environment=1)
else:
if args.queue <= 1:
write_slurm_sh_multi2(
"mocov3type%d_%d_%f_lgq_t_%.3f_epoch%d" % (
args.type, crop_size, learning_rate,
local_t, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=False, environment=0)
else:
write_slurm_sh_multi(
"mocov3type%d_%d_%f_lgq_t_%.3f_epoch%d" % (
args.type, crop_size, learning_rate, local_t, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=True, environment=1)
time.sleep(1)
elif args.type==17 or args.type==18:
warmup_epoch=10
for learning_rate in [1.5e-4]:
for local_t in [0.2]:
for epoch in [100]:
for batch_size in [1024]:
if args.type==18:
group_list = [1,2,4,8,16,32,64,128]
else:
group_list = [1]
for group_norm_size in group_list:
command_line = "python3 main_adco.py --mode=6 --type=%d --data=%s " \
"--epochs=%d --start_epoch=0 --batch_size=%d --lr=%f " \
"--weight_decay=0.1 --dist_url=tcp://localhost:10031 --rank=0 " \
"--multiprocessing_distributed=1 --world_size=1 --moco_dim=256 " \
"--mlp_dim=4096 --moco_m=0.99 --moco_t=%f " \
" --align=1 --knn_neighbor=20 --knn_freq=1 --tensorboard=1 " \
"--knn_batch_size=%d --group_norm_size=%d --use_fp16=1 " \
"--warmup_epochs %d -a vit_small --crop_min 0.08 " \
% (args.type, args.data, epoch, batch_size, learning_rate,
local_t, 256 , group_norm_size,warmup_epoch)
if args.node == 1:
write_slurm_sh_faster("mocov3type%d_%d_%flgq_t_%.3f_epoch%d" % (args.type,
group_norm_size,
learning_rate,
local_t,
epoch),
command_line, queue_name, gpu_memory=True, environment=1)
else:
if args.queue <= 1:
write_slurm_sh_multi2(
"mocov3type%d_%d_%f_lgq_t_%.3f_epoch%d" % (
args.type, group_norm_size, learning_rate,
local_t, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=False, environment=0)
else:
write_slurm_sh_multi(
"mocov3type%d_%d_%f_lgq_t_%.3f_epoch%d" % (
args.type, group_norm_size, learning_rate, local_t, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=True, environment=1)
time.sleep(1)
elif args.mode==7:
if args.type==0 or args.type==1 or args.type==2 or args.type==3 or args.type==4:
for num_roi in [16]:
for crop_size in [96]:
for learning_rate in [0.05]:
for barch_size in [512]:
for epoch in [100]:
command_line = "python3 main_adco.py --mode=7 --type=%d " \
" --data=%s --epochs=%d --start_epoch=0 --batch_size=%d " \
"--lr=%f --weight_decay=1e-4 --dist_url=tcp://localhost:10031 " \
"--rank=0 --multiprocessing_distributed=1 --world_size=1 " \
"--moco_dim=2048 --mlp_dim=512 --nmb_crops 1 %d --size_crops 224 %d " \
"--align=1 --knn_neighbor=20 --knn_freq=1 --tensorboard=1 --knn_batch_size=%d "\
%(args.type,args.data,epoch,barch_size,learning_rate,num_roi,crop_size,max(64*args.node,256))
if args.node==1:
write_slurm_sh_faster("simsiamtype%d_%d_%d_epoch%d" % (args.type, num_roi, crop_size,
epoch),command_line, queue_name,)
else:
if args.queue <= 1:
write_slurm_sh_multi2(
"simsiamtype%d_%d_%d_epoch%d" % (args.type, num_roi, crop_size,
epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu)
else:
write_slurm_sh_multi(
"simsiamtype%d_%d_%d_epoch%d" % (args.type, num_roi, crop_size, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu)
time.sleep(1)
elif args.type==5 or args.type==6 or args.type==7 or args.type==8 or args.type==9:
for learning_rate in [0.05]:
for barch_size in [512]:
for epoch in [100]:
for group_norm_size in [1, 2, 4, 8,16,32,64]:
command_line = "python3 main_adco.py --mode=7 --type=%d " \
" --data=%s --epochs=%d --start_epoch=0 --batch_size=%d " \
"--lr=%f --weight_decay=1e-4 --dist_url=tcp://localhost:10031 " \
"--rank=0 --multiprocessing_distributed=1 --world_size=1 " \
"--moco_dim=2048 --mlp_dim=512 --group_norm_size=%d " \
"--align=1 --knn_neighbor=20 --knn_freq=1 --tensorboard=1 --knn_batch_size=%d " \
"--use_fp16=1 " \
% (args.type, args.data, epoch, barch_size, learning_rate,group_norm_size,
max(64 * args.node, 256))
if args.node == 1:
write_slurm_sh_faster("simsiamtype%d_%d_epoch%d" % (args.type,group_norm_size,
epoch), command_line, queue_name,
gpu_memory=True,environment=1)
else:
if args.queue <= 1:
write_slurm_sh_multi2(
"simsiamtype%d_%d_epoch%d" % (args.type,group_norm_size,
epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=True,environment=1)
else:
write_slurm_sh_multi(
"simsiamtype%d_%d_epoch%d" % (args.type,group_norm_size, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=True,environment=1)
time.sleep(1)
elif args.type==-6:
for learning_rate in [0.05]:
for barch_size in [256,512]:
for epoch in [800]:
for group_norm_size in [8]:
command_line = "python3 main_adco.py --mode=7 --type=%d " \
" --data=%s --epochs=%d --start_epoch=0 --batch_size=%d " \
"--lr=%f --weight_decay=1e-4 --dist_url=tcp://localhost:10031 " \
"--rank=0 --multiprocessing_distributed=1 --world_size=1 " \
"--moco_dim=2048 --mlp_dim=512 --group_norm_size=%d " \
"--align=1 --knn_neighbor=20 --knn_freq=1 --tensorboard=1 --knn_batch_size=%d " \
"--use_fp16=1 " \
% (abs(args.type), args.data, epoch, barch_size, learning_rate,group_norm_size,
max(64 * args.node, 256))
if args.node == 1:
write_slurm_sh_faster("simsiamtype%d_%d_epoch%d" % (args.type,group_norm_size,
epoch), command_line, queue_name,
gpu_memory=True )
else:
if args.queue <= 1:
write_slurm_sh_multi2(
"simsiamtype%d_%d_epoch%d" % (args.type,group_norm_size,
epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu)
else:
write_slurm_sh_multi(
"simsiamtype%d_%d_epoch%d" % (args.type,group_norm_size, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu)
time.sleep(1)
elif args.type==10:
for learning_rate in [0.05]:
for barch_size in [512]:
for epoch in [100]:
for crop_size in [4, 8,16]:
command_line = "python3 main_adco.py --mode=7 --type=%d " \
" --data=%s --epochs=%d --start_epoch=0 --batch_size=%d " \
"--lr=%f --weight_decay=1e-4 --dist_url=tcp://localhost:10031 " \
"--rank=0 --multiprocessing_distributed=1 --world_size=1 " \
"--moco_dim=2048 --mlp_dim=512 --nmb_crops %d " \
"--align=1 --knn_neighbor=20 --knn_freq=1 --tensorboard=1 --knn_batch_size=%d " \
"--use_fp16=1 " \
% (args.type, args.data, epoch, barch_size, learning_rate,crop_size,
max(64 * args.node, 256))
if args.node == 1:
write_slurm_sh_faster("simsiamtype%d_%d_epoch%d" % (args.type,crop_size,
epoch), command_line, queue_name,
gpu_memory=True,environment=1)
else:
if args.queue <= 1:
write_slurm_sh_multi2(
"simsiamtype%d_%d_epoch%d" % (args.type,crop_size,
epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=True,environment=1)
else:
write_slurm_sh_multi(
"simsiamtype%d_%d_epoch%d" % (args.type,crop_size, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=True,environment=1)
time.sleep(1)
elif args.mode==5:
#run swav baseline
if args.type==0:
if args.F is None:
command_line = "python3 main_adco.py --mode=5 --type=0 --data=%s --epochs 200 --lr=0.6 "\
"--lr_final 0.0006 --batch_size=256 --warmup_epochs 0 --freeze_prototypes_niters 5005 "\
"--queue_length 3840 --epoch_queue_starts 15 --dist_url=tcp://localhost:10031 "\
"--knn_batch_size=256 --cos=1 --momentum=0.9 --weight_decay=1e-6 --world_size=1 "\
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 --moco_k=3000 --moco_t=0.1 "\
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --nmb_crops 2 6 " \
"--size_crops 224 96 --min_scale_crops 0.14 0.05 --max_scale_crops 1.0 0.14 --dump_path %s"%(args.data,dump_path)
write_slurm_sh("swav_baseline" , command_line, queue_name)
else:
args.F= os.path.abspath(args.F)
command_line = "python3 main_adco.py --mode=5 --type=0 --data=%s --epochs 200 --lr=0.6 " \
"--lr_final 0.0006 --batch_size=256 --warmup_epochs 0 --freeze_prototypes_niters 5005 " \
"--queue_length 3840 --epoch_queue_starts 15 --dist_url=tcp://localhost:10031 " \
"--knn_batch_size=256 --cos=1 --momentum=0.9 --weight_decay=1e-6 --world_size=1 " \
"--rank=0 --multiprocessing_distributed=1 --moco_dim=128 --moco_k=3000 --moco_t=0.1 " \
"--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --nmb_crops 2 6 " \
"--size_crops 224 96 --min_scale_crops 0.14 0.05 --max_scale_crops 1.0 0.14 " \
"--resume=%s --dump_path %s " % (args.data,args.F,dump_path)
resume_name= os.path.split(os.path.abspath(args.F))[1]
write_slurm_sh("swav_baseline_resume%s"%resume_name, command_line, queue_name)
elif args.mode==8:
if args.type==0 or args.type==1:
for epoch in [100]:
for batch_size in [2048]:
for lr_w in [0.2]:
for lr_bias in [0.0048]:
for alpha in [0.51]:
command_line="python3 main.py %s --epochs=%d " \
"--batch-size=%d --learning-rate-weights=%f --learning-rate-biases=%f " \
"--weight-decay=1e-6 --lambd=%f --type=%d --knn_neighbor=20 " \
"--knn_freq=1 --knn_batch_size=%d --tensorboard=1 "%(args.data,epoch,
batch_size,lr_w,lr_bias,alpha,args.type,256 )
if args.node==1:
write_slurm_sh_faster("BTtype%d_%d_epoch%d" % (args.type,batch_size,epoch), command_line, queue_name,
gpu_memory=False, environment=0)
else:
write_slurm_sh_multi2(
"BTtype%d_%d_epoch%d" % (args.type, batch_size, epoch),
command_line, queue_name, nodes=args.node, gpu_per_node=args.gpu,
gpu_memory=False, environment=0)
elif args.type==2:
for epoch in [100]:
for batch_size in [1024]:
for lr_w in [0.2]:
for lr_bias in [0.0048]:
for alpha in [0.51]:
for group_size in [2,4,8,16,32]:
command_line = "python3 main.py %s --epochs=%d " \
"--batch-size=%d --learning-rate-weights=%f --learning-rate-biases=%f " \
"--weight-decay=1e-6 --lambd=%f --type=%d --knn_neighbor=20 " \
"--knn_freq=1 --knn_batch_size=%d --tensorboard=1 --group_norm_size=%d " % (args.data, epoch,
batch_size, lr_w,
lr_bias, alpha,
args.type, 256,group_size)
write_slurm_sh_faster("BTtype%d_%d_%d_epoch%d" % (args.type,group_size, batch_size,epoch), command_line, queue_name,
gpu_memory=False, environment=0)
elif args.mode==0:
#used for finetuning, which will submit finetune jobs and a comment for which
use_bn=args.type
for lr in [20]:
for weight_decay in [1e-6,1e-7,1e-8,1e-9]:
command_line = "python3 lincls.py --data=%s --dist-url=tcp://localhost:10031 " \
"--pretrained='%s' --lr=%.4f --final_lr=%.8f --dataset=ImageNet --use_bn=%d --wd %.8f" % (
args.data, args.F, lr, lr / 100, use_bn,weight_decay)
write_slurm_sh("linear_eval_%s_%.4f_bn%d_wd_%f" % (args.comment, lr, use_bn,weight_decay), command_line, queue_name)
time.sleep(1)
elif args.mode==-2:
use_bn = args.type
#type 3:l2 norm linear
for lr in [1.0]:
for weight_decay in [1e-5,1e-6,1e-7,1e-8,1e-9]:
command_line = "python3 lincls.py --data=%s --dist-url=tcp://localhost:10031 --batch-size=4096 " \
"--pretrained='%s' --lr=%.4f --final_lr=%.8f --dataset=ImageNet --use_bn=%d --wd %.8f" % (
args.data, args.F, lr, lr / 100, use_bn, weight_decay)
write_slurm_sh("linearb4096_eval_%s_%.4f_bn%d_wd_%.8f" % (args.comment, lr, use_bn, weight_decay), command_line,
queue_name)
elif args.mode==-1:
command_line = "python3 encode.py --data=%s --dist-url=tcp://localhost:10031 " \
"--pretrained='%s' --dataset=ImageNet " % (args.data, args.F)
write_slurm_sh("encode_%s" % (args.comment), command_line, queue_name)
elif args.mode==-3:
command_line = "python3 main_adco.py --sym=0 --lr=0.03 --memory_lr=3 --moco_t=0.12 " \
"--mem_t=0.02 --data=%s --dist_url=tcp://localhost:10001 --mode=0 " \
"--epochs=200 --moco_dim=128 --moco_m=0.999 --moco_k=65536 --cluster=65536 " \
"--knn_neighbor=20 --knn_freq=1 --data=imagenet --batch_size=256 --ad_init=1 "%(args.data)
write_slurm_sh("type0",command_line,queue_name)
elif args.mode==-4:
use_bn = args.type
vit_model =True
for lr in [0.05,0.1]:
for weight_decay in [0]:
for model_type in [0]:
command_line ="python lincls_lars.py -a resnet50 --dist-url 'tcp://localhost:10001' " \
"--multiprocessing-distributed --world-size 1 --rank 0 --pretrained='%s' --lr %f --wd %f " \
"--lars --data %s --use_bn=%d --model_type=%d "%(args.F,lr,
weight_decay,args.data,use_bn,model_type)
if vit_model:
command_line +=" --arch vit_small"
write_slurm_sh("linear_larsb4096_eval_%s_bn%d_%.4f_wd_%.8f" % (args.comment, use_bn,lr,weight_decay),
command_line,
queue_name)
elif args.mode==-40:
use_bn = args.type
study_dir = os.path.abspath(args.F)
checkpoint_name = "checkpoint_0099.pth.tar"
for item in os.listdir(study_dir):
if item== checkpoint_name:
current_model_path = os.path.join(study_dir,item)
current_dir = study_dir
current_comment = os.path.split(current_dir)[1]
else:
current_dir = os.path.join(study_dir,item)
current_comment = os.path.split(current_dir)[1]
current_model_path = find_checkpoint(current_dir,checkpoint_name)
if current_model_path is None:
print("%s dir did not find checkpoint"%current_dir)
continue
if not os.path.exists(current_model_path):
print("%s model path did not exist"%current_model_path)
continue
print("fintune %s model"%current_model_path)
for lr in [0.05, 0.1]:
for weight_decay in [0]:
for model_type in [0]:
command_line = "python lincls_lars.py -a resnet50 --dist-url 'tcp://localhost:10001' " \
"--multiprocessing-distributed --world-size 1 --rank 0 --pretrained='%s' --lr %f --wd %f " \
"--lars --data %s --use_bn=%d --model_type=%d " % (current_model_path, lr,
weight_decay, args.data, use_bn,
model_type)
write_slurm_sh(
"linear_larsb4096_eval_%s_bn%d_%.4f_wd_%.8f" % (str(args.comment)+current_comment, use_bn, lr, weight_decay),
command_line,
queue_name)
elif args.mode==-5:
config_dict={}
config_path = os.path.join(os.getcwd(),"detection")
config_path = os.path.join(config_path,"configs")
config_dict['VOC']=os.path.join(config_path,"pascal_voc_R_50_C4_24k_loco.yaml")
config_dict['VOC_freeze'] = os.path.join(config_path, "pascal_voc_R_50_C4_24k_loco_freeze.yaml")
config_dict['COCO'] = os.path.join(config_path,"coco_R_50_C4_2x.yaml_loco.yaml")
config_dict['COCO_freeze'] =os.path.join(config_path,"coco_R_50_C4_2x.yaml_loco_freeze.yaml")
model_path = os.path.abspath(args.F)
model_name = os.path.split(model_path)[1].replace(".pkl","")
for kk in range(5):
for config_now in ['VOC','VOC_freeze']:
command_line = "python detection/train_net.py --config-file %s --num-gpus 8" \
" MODEL.WEIGHTS %s"%(config_dict[config_now],args.F)
write_slurm_sh_faster("detection_%s_run%d_%s" % (config_now, kk,model_name),
command_line, queue_name, gpu_memory=True)
for config_now in ['COCO',"COCO_freeze"]:
command_line = "python detection/train_net.py --config-file %s --num-gpus 8" \
" MODEL.WEIGHTS %s" % (config_dict[config_now], args.F)
write_slurm_sh_faster("detection_%s_%s" % (config_now, model_name),
command_line, queue_name, gpu_memory=True)
elif args.mode==-6:
#finetune with mocov3 protocol
for lr in [0.03,0.06,0.1,0.15,0.12]:
for weight_decay in [0]:
command_line ="python main_lincls.py -a resnet50 --dist-url 'tcp://localhost:10001' " \
"--multiprocessing-distributed --world-size 1 --rank 0 --pretrained='%s' --lr %f --wd %f " \
" %s "%(args.F,lr,weight_decay,args.data)
write_slurm_sh("linear_main_lincls_%s_%.4f_wd_%.8f" % (args.comment, lr,weight_decay),
command_line,
queue_name)
| run_slurm.py | 266,956 | Args:
id: running id
command_line: command line
outlog_path: saving path
Returns:
!/bin/bashfile.write("bash /private/home/wang3702/.bashrc\n")file.write("module load anaconda3\n") signal that job is finished!/bin/bash--mem : Specify the real memory required per node.file.write('SBATCH --constraint="volta"\n')file.write("bash /private/home/wang3702/.bashrc\n")file.write("module load anaconda3\n") signal that job is finished!/bin/bashfile.write("bash /private/home/wang3702/.bashrc\n") file.write("/private/home/wang3702/anaconda3/bin/conda init\n")file.write("module load anaconda3\n")file.write("source activate\n") signal that job is finished!/bin/bashfile.write("bash /private/home/wang3702/.bashrc\n")file.write("module load anaconda3\n")file.write("source activate\n") signal that job is finishedfile.write("bash /private/home/wang3702/.bashrc\n") file.write("/private/home/wang3702/anaconda3/bin/conda init\n")file.write("CONDA_BASE=$(conda info --base) ; source $CONDA_BASE/etc/profile.d/conda.sh\n")file.write("module load anaconda3\n")file.write("conda activate pytorch2\n") signal that job is finished command_line = "python3 main_adco.py --mode=1 --lr=0.06 --data=%s " \ "--dist_url=tcp://localhost:10031 --epochs=100 " \ "--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0006 " \ "--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \ "--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \ "--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \ "--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=57" % args.data write_slurm_sh("baseline_sym_moco_lr0.06_proj", command_line, queue_name) command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \ "--dist_url=tcp://localhost:10031 --epochs=100 " \ "--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \ "--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \ "--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \ "--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \ "--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=16 --mask_size=32 " \ "--num_roi=1 --img_size=96 " % args.data write_slurm_sh("baseline_sym_moco_input96", command_line, queue_name)running all the baseline with 100 epochsbase line moco command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \ "--dist_url=tcp://localhost:10031 --epochs=100 " \ "--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \ "--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \ "--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \ "--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \ "--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=35 --mask_size=32 " \ " --num_roi=1 " % args.data write_slurm_sh("baseline_sym_mocobn_100", command_line, queue_name) moco multi baseline command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \ "--dist_url=tcp://localhost:10031 --epochs=100 " \ "--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \ "--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \ "--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \ "--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \ "--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=18 --nmb_crops 2 6 " \ "--size_crops 224 96 --min_scale_crops 0.14 0.05 --max_scale_crops 1.0 0.14 " % (args.data) write_slurm_sh("multi_moco_baseline_100_new", command_line, queue_name) moco multi sym baseline command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \ "--dist_url=tcp://localhost:10031 --epochs=100 " \ "--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \ "--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \ "--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \ "--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \ "--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=20 --nmb_crops 4 " \ "--size_crops 224 --min_scale_crops 0.14 --max_scale_crops 1.0 " % (args.data) write_slurm_sh("2key_multi_moco_baseline_4_224", command_line, queue_name) swav multi baseline command_line = "python3 main_adco.py --mode=5 --type=0 --data=%s --epochs 100 --lr=0.6 " \ "--lr_final 0.0006 --batch_size=256 --warmup_epochs 0 --freeze_prototypes_niters 5005 " \ "--queue_length 3840 --epoch_queue_starts 15 --dist_url=tcp://localhost:10031 " \ "--knn_batch_size=256 --cos=1 --momentum=0.9 --weight_decay=1e-6 --world_size=1 " \ "--rank=0 --multiprocessing_distributed=1 --moco_dim=128 --moco_k=3000 --moco_t=0.1 " \ "--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --nmb_crops 2 " \ "--size_crops 224 --min_scale_crops 0.14 --max_scale_crops 1.0 --dump_path %s " % (args.data,dump_path) write_slurm_sh("swav_baseline_100_only224", command_line, queue_name) command_line = "python3 main_adco.py --mode=5 --type=0 --data=%s --epochs 100 --lr=0.6 " \ "--lr_final 0.0006 --batch_size=256 --warmup_epochs 0 --freeze_prototypes_niters 5005 " \ "--queue_length 3840 --epoch_queue_starts 15 --dist_url=tcp://localhost:10031 " \ "--knn_batch_size=256 --cos=1 --momentum=0.9 --weight_decay=1e-6 --world_size=1 " \ "--rank=0 --multiprocessing_distributed=1 --moco_dim=128 --moco_k=3000 --moco_t=0.1 " \ "--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --nmb_crops 2 6 " \ "--size_crops 224 96 --min_scale_crops 0.14 0.05 --max_scale_crops 1.0 0.14 --dump_path %s " % ( args.data, dump_path) write_slurm_sh("swav_baseline_100", command_line, queue_name)half dropout results to make sure overlap region can really not workroi vs globalroi vs roi,with global as negative command_line = "python3 main_adco.py --mode=1 --lr=0.03 --data=%s " \ "--dist_url=tcp://localhost:10031 --epochs=200 " \ "--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \ "--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \ "--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \ "--moco_m=0.999 --moco_k=65536 --moco_t=0.2 --choose=0,1,2,3,4,5,6,7 " \ "--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=23 --nmb_crops 6" \ " --size_crops 96 " % args.data write_slurm_sh("type23_specifyroi_6_96", command_line, queue_name)[0.02,0.03,0.04,0.05,0.06,0.1,0.15]:[0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]:calculate baseline 6*96 for type 27 as a direct cmp with SWAV [0.3, 0.5, 1.0]:[0.02,0.03,0.04,0.05,0.06,0.1,0.15]:[0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.02,0.03,0.04,0.05,0.06,0.1,0.15]:[0.1, 0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: for num_roi in [6]: for crop_size in [96]: for learning_rate in [0.05]: for alpha in [0.1]: [0.3, 0.5, 1.0]: for local_t in [0.15, 0.18, 0.2]: for sample_ratio in [2,4]: command_line = "python3 main_adco.py --mode=1 --lr=%.4f --data=%s " \ "--dist_url=tcp://localhost:10031 --epochs=100 " \ "--batch_size=256 --knn_batch_size=256 --cos=1 --lr_final=0.0003 " \ "--momentum=0.9 --weight_decay=1e-4 --world_size=1 " \ "--rank=0 --multiprocessing_distributed=1 --moco_dim=128 " \ "--moco_m=0.999 --moco_k=65536 --moco_t=%.4f --choose=0,1,2,3,4,5,6,7 " \ "--knn_neighbor=20 --knn_freq=1 --tensorboard=1 --type=44 --nmb_crops 1 %d" \ " --size_crops 224 %d --local_t=%.4f --alpha=%.2f --sample_ratio=%d " % \ (learning_rate, args.data,local_t, num_roi,crop_size, local_t, alpha,sample_ratio) write_slurm_sh( "type44crop_lgq_t_%.3f_alpha_%.2f_%d_%d_lr%.4f_ratio%d" % (local_t, alpha, num_roi,crop_size, learning_rate,sample_ratio), command_line, queue_name) time.sleep(1) [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.02,0.03,0.04,0.05,0.06,0.1,0.15]: [0.1, 0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.02,0.03,0.04,0.05,0.06,0.1,0.15]: [0.3, 0.5, 1.0]:only run on pytorch environment, not base environment [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]:for num_roi in ['','6']: for crop_size in ['','96']:0 denotes only shuffling to influence0 denotes only shuffling to influence [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]: [0.3, 0.5, 1.0]:for crop_size in [96]:[[1024,16],[2048,32],[4096,64]][[1024,16],[2048,32],[4096,64]]run swav baselineused for finetuning, which will submit finetune jobs and a comment for whichtype 3:l2 norm linearfinetune with mocov3 protocol | 9,603 | en | 0.301468 |
# -*- coding: UTF-8 -*-
#
# Copyright 2018 Joachim Lusiardi
#
# 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.
#
"""
Implements the Secure Remote Password (SRP) algorithm. More information can be found on
https://tools.ietf.org/html/rfc5054. See HomeKit spec page 36 for adjustments imposed by Apple.
"""
import math
import hashlib
import os
class Srp:
def __init__(self):
# generator as defined by 3072bit group of RFC 5054
self.g = int(b'5', 16)
# modulus as defined by 3072bit group of RFC 5054
self.n = int(b'''\
FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08\
8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B\
302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9\
A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6\
49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8\
FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D\
670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C\
180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718\
3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D\
04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D\
B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226\
1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C\
BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC\
E0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF''', 16)
# HomeKit requires SHA-512 (See page 36)
self.h = hashlib.sha512
self.A = None
self.B = None
self.salt = None
self.username = None
self.password = None
@staticmethod
def generate_private_key():
"""
Static function to generate a 16 byte random key.
:return: the key as an integer
"""
# see
# - https://github.com/jlusiardi/homekit_python/issues/185#issuecomment-616344895 and
# - https://cryptography.io/en/latest/random-numbers/
return int.from_bytes(os.urandom(16), byteorder="big")
def _calculate_k(self) -> int:
# calculate k (see https://tools.ietf.org/html/rfc5054#section-2.5.3)
hash_instance = self.h()
n = Srp.to_byte_array(self.n)
g = bytearray.fromhex((383 * '00' + '05')) # 383 * b'0' + '5'.encode()
hash_instance.update(n)
hash_instance.update(g)
k = int.from_bytes(hash_instance.digest(), "big")
return k
def _calculate_u(self) -> int:
if self.A is None:
raise RuntimeError('Client\'s public key is missing')
if self.B is None:
raise RuntimeError('Server\'s public key is missing')
hash_instance = self.h()
A_b = Srp.to_byte_array(self.A)
B_b = Srp.to_byte_array(self.B)
hash_instance.update(A_b)
hash_instance.update(B_b)
u = int.from_bytes(hash_instance.digest(), "big")
return u
def get_session_key(self) -> int:
hash_instance = self.h()
hash_instance.update(Srp.to_byte_array(self.get_shared_secret()))
hash_value = int.from_bytes(hash_instance.digest(), "big")
return hash_value
@staticmethod
def to_byte_array(num: int) -> bytearray:
return bytearray(num.to_bytes(int(math.ceil(num.bit_length() / 8)), "big"))
def _calculate_x(self) -> int:
i = (self.username + ':' + self.password).encode()
hash_instance = self.h()
hash_instance.update(i)
hash_value = hash_instance.digest()
hash_instance = self.h()
hash_instance.update(Srp.to_byte_array(self.salt))
hash_instance.update(hash_value)
return int.from_bytes(hash_instance.digest(), "big")
def get_shared_secret(self):
raise NotImplementedError()
class SrpClient(Srp):
"""
Implements all functions that are required to simulate an iOS HomeKit controller
"""
def __init__(self, username: str, password: str):
Srp.__init__(self)
self.username = username
self.password = password
self.salt = None
self.a = self.generate_private_key()
self.A = pow(self.g, self.a, self.n)
self.B = None
def set_salt(self, salt):
if isinstance(salt, bytearray) or isinstance(salt, bytes):
self.salt = int.from_bytes(salt, "big")
else:
self.salt = salt
def get_public_key(self):
return pow(self.g, self.a, self.n)
def set_server_public_key(self, B):
if isinstance(B, bytearray) or isinstance(B, bytes):
self.B = int.from_bytes(B, "big")
else:
self.B = B
def get_shared_secret(self):
if self.B is None:
raise RuntimeError('Server\'s public key is missing')
u = self._calculate_u()
x = self._calculate_x()
k = self._calculate_k()
tmp1 = (self.B - (k * pow(self.g, x, self.n)))
tmp2 = (self.a + (u * x)) # % self.n
S = pow(tmp1, tmp2, self.n)
return S
def get_proof(self):
if self.B is None:
raise RuntimeError('Server\'s public key is missing')
hash_instance = self.h()
hash_instance.update(Srp.to_byte_array(self.n))
hN = bytearray(hash_instance.digest())
hash_instance = self.h()
hash_instance.update(Srp.to_byte_array(self.g))
hg = bytearray(hash_instance.digest())
for index in range(0, len(hN)):
hN[index] ^= hg[index]
u = self.username.encode()
hash_instance = self.h()
hash_instance.update(u)
hu = hash_instance.digest()
K = Srp.to_byte_array(self.get_session_key())
hash_instance = self.h()
hash_instance.update(hN)
hash_instance.update(hu)
hash_instance.update(Srp.to_byte_array(self.salt))
hash_instance.update(Srp.to_byte_array(self.A))
hash_instance.update(Srp.to_byte_array(self.B))
hash_instance.update(K)
return int.from_bytes(hash_instance.digest(), "big")
def verify_servers_proof(self, M):
if isinstance(M, bytearray) or isinstance(M, bytes):
tmp = int.from_bytes(M, "big")
else:
tmp = M
hash_instance = self.h()
hash_instance.update(Srp.to_byte_array(self.A))
hash_instance.update(Srp.to_byte_array(self.get_proof()))
hash_instance.update(Srp.to_byte_array(self.get_session_key()))
return tmp == int.from_bytes(hash_instance.digest(), "big")
class SrpServer(Srp):
"""
Implements all functions that are required to simulate an iOS HomeKit accessory
"""
def __init__(self, username, password):
Srp.__init__(self)
self.username = username
self.salt = SrpServer._create_salt()
self.password = password
self.verifier = self._get_verifier()
self.b = self.generate_private_key()
k = self._calculate_k()
g_b = pow(self.g, self.b, self.n)
self.B = (k * self.verifier + g_b) % self.n
self.A = None
@staticmethod
def _create_salt() -> int:
# see
# - https://github.com/jlusiardi/homekit_python/issues/185#issuecomment-616344895 and
# - https://cryptography.io/en/latest/random-numbers/
return int.from_bytes(os.urandom(16), byteorder="big")
def _get_verifier(self) -> int:
hash_value = self._calculate_x()
v = pow(self.g, hash_value, self.n)
return v
def set_client_public_key(self, A):
self.A = A
def get_salt(self):
return self.salt
def get_public_key(self):
k = self._calculate_k()
return (k * self.verifier + pow(self.g, self.b, self.n)) % self.n
def get_shared_secret(self):
if self.A is None:
raise RuntimeError('Client\'s public key is missing')
tmp1 = self.A * pow(self.verifier, self._calculate_u(), self.n)
return pow(tmp1, self.b, self.n)
def verify_clients_proof(self, m) -> bool:
if self.B is None:
raise RuntimeError('Server\'s public key is missing')
hash_instance = self.h()
hash_instance.update(Srp.to_byte_array(self.n))
hN = bytearray(hash_instance.digest())
hash_instance = self.h()
hash_instance.update(Srp.to_byte_array(self.g))
hg = bytearray(hash_instance.digest())
for index in range(0, len(hN)):
hN[index] ^= hg[index]
u = self.username.encode()
hash_instance = self.h()
hash_instance.update(u)
hu = hash_instance.digest()
K = Srp.to_byte_array(self.get_session_key())
hash_instance = self.h()
hash_instance.update(hN)
hash_instance.update(hu)
hash_instance.update(Srp.to_byte_array(self.salt))
hash_instance.update(Srp.to_byte_array(self.A))
hash_instance.update(Srp.to_byte_array(self.B))
hash_instance.update(K)
return m == int.from_bytes(hash_instance.digest(), "big")
def get_proof(self, m) -> int:
hash_instance = self.h()
hash_instance.update(Srp.to_byte_array(self.A))
hash_instance.update(Srp.to_byte_array(m))
hash_instance.update(Srp.to_byte_array(self.get_session_key()))
return int.from_bytes(hash_instance.digest(), "big")
| homekit/crypto/srp.py | 9,763 | Implements all functions that are required to simulate an iOS HomeKit controller
Implements all functions that are required to simulate an iOS HomeKit accessory
Static function to generate a 16 byte random key.
:return: the key as an integer
Implements the Secure Remote Password (SRP) algorithm. More information can be found on
https://tools.ietf.org/html/rfc5054. See HomeKit spec page 36 for adjustments imposed by Apple.
-*- coding: UTF-8 -*- Copyright 2018 Joachim Lusiardi 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. generator as defined by 3072bit group of RFC 5054 modulus as defined by 3072bit group of RFC 5054 HomeKit requires SHA-512 (See page 36) see - https://github.com/jlusiardi/homekit_python/issues/185issuecomment-616344895 and - https://cryptography.io/en/latest/random-numbers/ calculate k (see https://tools.ietf.org/html/rfc5054section-2.5.3) 383 * b'0' + '5'.encode() % self.n see - https://github.com/jlusiardi/homekit_python/issues/185issuecomment-616344895 and - https://cryptography.io/en/latest/random-numbers/ | 1,524 | en | 0.77815 |
# Created by MechAviv
# ID :: [140010000]
# Snow Island : Dangerous Forest
if not "o" in sm.getQuestEx(21019, "arr"):
sm.avatarOriented("Effect/OnUserEff.img/guideEffect/aranTutorial/tutorialArrow3")
sm.setQuestEx(21019, "arr", "o") | scripts/field/rienArrow.py | 240 | Created by MechAviv ID :: [140010000] Snow Island : Dangerous Forest | 68 | en | 0.843514 |
import json
import random
import uuid
import numpy as np
import time
import requests
import traceback
import pdb
import math
import ast
import pandas as pd
import pickle
from qwikidata.linked_data_interface import get_entity_dict_from_api
from qwikidata.sparql import return_sparql_query_results
from urllib3.exceptions import MaxRetryError, ConnectionError
from qwikidata.linked_data_interface import LdiResponseNotOk
import hashlib
class CachedWikidataAPI():
def __init__(self, cache_path = 'entity_cache.p', save_every_x_queries=1):
self.save_every_x_queries = save_every_x_queries
self.x_queries_passed = 0
self.languages = ['en','fr','es','pt','pt-br','it','de']
self.cache_path = cache_path
try:
with open(self.cache_path,'rb') as f:
self.entity_cache = pickle.load(f)
except FileNotFoundError:
self.entity_cache = {}
def get_unique_id_from_str(self, my_str):
return hashlib.md5(str.encode(my_str)).hexdigest()
def save_entity_cache(self, force=False):
if force:
self.x_queries_passed = self.save_every_x_queries
self.x_queries_passed = self.x_queries_passed+1
if self.x_queries_passed >= self.save_every_x_queries:
with open(self.cache_path,'wb') as f:
pickle.dump(self.entity_cache,f)
self.x_queries_passed = 0
def get_entity(self, item_id):
if item_id in self.entity_cache:
return self.entity_cache[item_id]
while True:
try:
entity = get_entity_dict_from_api(item_id)
self.entity_cache[item_id] = entity
self.save_entity_cache()
return entity
except (ConnectionError, MaxRetryError) as e:
#traceback.print_exc()
time.sleep(1)
continue
except LdiResponseNotOk:
#traceback.print_exc()
self.entity_cache[item_id] = 'deleted'
self.save_entity_cache()
return 'deleted'
def get_label(self, item, non_language_set=False):
if type(item) == str:
entity = self.get_entity(item)
if entity == 'deleted':
return (entity, 'none')
labels = entity['labels' if 'labels' in entity else 'lemmas']
elif type(item) == dict:
if 'labels' in item:
labels = item['labels']
elif 'lemmas' in item:
labels = item['lemmas']
for l in self.languages:
if l in labels:
return (labels[l]['value'], l)
if non_language_set:
all_labels = list(labels.keys())
if len(all_labels)>0:
return (labels[all_labels[0]]['value'], all_labels[0])
return ('no-label', 'none')
def get_desc(self, item, non_language_set=False):
if type(item) == str:
entity = self.get_entity(item)
if entity == 'deleted':
return (entity, 'none')
descriptions = entity['descriptions']
elif type(item) == dict:
if 'descriptions' in item:
descriptions = item['descriptions']
for l in self.languages:
if l in descriptions:
return (descriptions[l]['value'], l)
if non_language_set:
all_descriptions = list(descriptions.keys())
if len(all_descriptions)>0:
return (descriptions[all_descriptions[0]]['value'], all_descriptions[0])
return ('no-desc', 'none')
def get_alias(self, item, non_language_set=False):
if type(item) == str:
entity = self.get_entity(item)
if entity == 'deleted':
return ([entity], 'none')
aliases = entity['aliases']
elif type(item) == dict:
if 'aliases' in item:
aliases = item['aliases']
for l in self.languages:
if l in aliases:
return ([alias['value'] for alias in aliases[l]], l)
if non_language_set:
all_aliases = list(aliases.keys())
if len(all_aliases)>0:
return (aliases[all_aliases[0]]['value'], all_aliases[0])
return ([alias['value'] for alias in aliases[all_aliases[0]]], all_aliases[0])
return ('no-alias', 'none')
def get_datatype(self, item):
try:
if type(item) == str:
entity = self.get_entity(item)
if entity == 'deleted':
return entity
datatype = entity['datatype']
elif type(item) == dict:
datatype = item['datatype']
return datatype
except KeyError:
return 'none'
def get_claim_values_of(self, item, property_id):
if type(item) == str:
entity = self.get_entity(item)
if entity == 'deleted':
return entity
claims = entity['claims']
elif type(item) == dict:
claims = item['claims']
if property_id in claims:
instance_of_claims = claims[property_id]
return [i['mainsnak']['datavalue']['value']['id'] for i in instance_of_claims]
else:
return []
def query_sparql_endpoint(self, sparql_query):
sparql_query_id = self.get_unique_id_from_str(sparql_query)
if sparql_query_id in self.entity_cache:
return self.entity_cache[sparql_query_id]
else:
wikidata_sparql_url = 'https://query.wikidata.org/sparql'
try:
while True:
res = requests.get(wikidata_sparql_url, params={"query": sparql_query, "format": "json"})
if res.status_code in (429,504):
time.sleep(1)
continue
elif res.status_code == 200:
res = res.json()
self.entity_cache[sparql_query_id] = res
self.save_entity_cache()
return res
else:
print(res.status_code)
raise Exception
except json.JSONDecodeError as e:
#pdb.set_trace()
print(res, res.__dict__)
raise e
| WikidataClaims/wikidata_utils.py | 6,536 | traceback.print_exc()traceback.print_exc()pdb.set_trace() | 57 | en | 0.22115 |
# Generated by Django 3.2.3 on 2021-05-26 11:31
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('spa', '0003_alter_service_master'),
('user_profile', '0002_auto_20210526_1647'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='age',
field=models.IntegerField(),
),
migrations.CreateModel(
name='Order',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_created', models.DateTimeField(auto_now_add=True)),
('status', models.CharField(max_length=40)),
('service', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='spa.service')),
('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
],
),
]
| django_project/user_profile/migrations/0003_auto_20210526_1731.py | 1,171 | Generated by Django 3.2.3 on 2021-05-26 11:31 | 45 | en | 0.790673 |
#climber.py
#Robot Code For BlueCrew 6153
import wpilib
#Commands to make the robot climb.
class Climber:
climb_motor = wpilib.Talon
#Set robot to climb when motor is on.
def climb(self):
self.climb_motor.set(1)
#Stops the robot from climbing when motor is off.
def stop_climb(self):
self.climb_motor.set(0)
#Execute is a necessary method for robotpy
#DO NO DELETE
def execute(self):
pass
| components/climber.py | 461 | climber.pyRobot Code For BlueCrew 6153Commands to make the robot climb.Set robot to climb when motor is on.Stops the robot from climbing when motor is off.Execute is a necessary method for robotpyDO NO DELETE | 208 | en | 0.885724 |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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 numbers
from abc import ABCMeta
from itertools import chain
from typing import Any, Optional, Union
import numpy as np
import pandas as pd
from pandas.api.types import CategoricalDtype
from pyspark.sql import functions as F, Column
from pyspark.sql.types import (
ArrayType,
BinaryType,
BooleanType,
DataType,
DateType,
DecimalType,
FractionalType,
IntegralType,
MapType,
NullType,
NumericType,
StringType,
StructType,
TimestampType,
TimestampNTZType,
UserDefinedType,
)
from pyspark.pandas._typing import Dtype, IndexOpsLike, SeriesOrIndex
from pyspark.pandas.spark import functions as SF
from pyspark.pandas.typedef import extension_dtypes
from pyspark.pandas.typedef.typehints import (
extension_dtypes_available,
extension_float_dtypes_available,
extension_object_dtypes_available,
spark_type_to_pandas_dtype,
)
if extension_dtypes_available:
from pandas import Int8Dtype, Int16Dtype, Int32Dtype, Int64Dtype
if extension_float_dtypes_available:
from pandas import Float32Dtype, Float64Dtype
if extension_object_dtypes_available:
from pandas import BooleanDtype, StringDtype
def is_valid_operand_for_numeric_arithmetic(operand: Any, *, allow_bool: bool = True) -> bool:
"""Check whether the `operand` is valid for arithmetic operations against numerics."""
from pyspark.pandas.base import IndexOpsMixin
if isinstance(operand, numbers.Number):
return not isinstance(operand, bool) or allow_bool
elif isinstance(operand, IndexOpsMixin):
if isinstance(operand.dtype, CategoricalDtype):
return False
else:
return isinstance(operand.spark.data_type, NumericType) or (
allow_bool and isinstance(operand.spark.data_type, BooleanType)
)
else:
return False
def transform_boolean_operand_to_numeric(
operand: Any, *, spark_type: Optional[DataType] = None
) -> Any:
"""Transform boolean operand to numeric.
If the `operand` is:
- a boolean IndexOpsMixin, transform the `operand` to the `spark_type`.
- a boolean literal, transform to the int value.
Otherwise, return the operand as it is.
"""
from pyspark.pandas.base import IndexOpsMixin
if isinstance(operand, IndexOpsMixin) and isinstance(operand.spark.data_type, BooleanType):
assert spark_type, "spark_type must be provided if the operand is a boolean IndexOpsMixin"
assert isinstance(spark_type, NumericType), "spark_type must be NumericType"
dtype = spark_type_to_pandas_dtype(
spark_type, use_extension_dtypes=operand._internal.data_fields[0].is_extension_dtype
)
return operand._with_new_scol(
operand.spark.column.cast(spark_type),
field=operand._internal.data_fields[0].copy(dtype=dtype, spark_type=spark_type),
)
elif isinstance(operand, bool):
return int(operand)
else:
return operand
def _as_categorical_type(
index_ops: IndexOpsLike, dtype: CategoricalDtype, spark_type: DataType
) -> IndexOpsLike:
"""Cast `index_ops` to categorical dtype, given `dtype` and `spark_type`."""
assert isinstance(dtype, CategoricalDtype)
if dtype.categories is None:
codes, uniques = index_ops.factorize()
return codes._with_new_scol(
codes.spark.column,
field=codes._internal.data_fields[0].copy(dtype=CategoricalDtype(categories=uniques)),
)
else:
categories = dtype.categories
if len(categories) == 0:
scol = SF.lit(-1)
else:
kvs = chain(
*[(SF.lit(category), SF.lit(code)) for code, category in enumerate(categories)]
)
map_scol = F.create_map(*kvs)
scol = F.coalesce(map_scol[index_ops.spark.column], SF.lit(-1))
return index_ops._with_new_scol(
scol.cast(spark_type),
field=index_ops._internal.data_fields[0].copy(
dtype=dtype, spark_type=spark_type, nullable=False
),
)
def _as_bool_type(index_ops: IndexOpsLike, dtype: Union[str, type, Dtype]) -> IndexOpsLike:
"""Cast `index_ops` to BooleanType Spark type, given `dtype`."""
spark_type = BooleanType()
if isinstance(dtype, extension_dtypes):
scol = index_ops.spark.column.cast(spark_type)
else:
scol = F.when(index_ops.spark.column.isNull(), SF.lit(False)).otherwise(
index_ops.spark.column.cast(spark_type)
)
return index_ops._with_new_scol(
scol, field=index_ops._internal.data_fields[0].copy(dtype=dtype, spark_type=spark_type)
)
def _as_string_type(
index_ops: IndexOpsLike, dtype: Union[str, type, Dtype], *, null_str: str = str(None)
) -> IndexOpsLike:
"""Cast `index_ops` to StringType Spark type, given `dtype` and `null_str`,
representing null Spark column. Note that `null_str` is for non-extension dtypes only.
"""
spark_type = StringType()
if isinstance(dtype, extension_dtypes):
scol = index_ops.spark.column.cast(spark_type)
else:
casted = index_ops.spark.column.cast(spark_type)
scol = F.when(index_ops.spark.column.isNull(), null_str).otherwise(casted)
return index_ops._with_new_scol(
scol, field=index_ops._internal.data_fields[0].copy(dtype=dtype, spark_type=spark_type)
)
def _as_other_type(
index_ops: IndexOpsLike, dtype: Union[str, type, Dtype], spark_type: DataType
) -> IndexOpsLike:
"""Cast `index_ops` to a `dtype` (`spark_type`) that needs no pre-processing.
Destination types that need pre-processing: CategoricalDtype, BooleanType, and StringType.
"""
from pyspark.pandas.internal import InternalField
need_pre_process = (
isinstance(dtype, CategoricalDtype)
or isinstance(spark_type, BooleanType)
or isinstance(spark_type, StringType)
)
assert not need_pre_process, "Pre-processing is needed before the type casting."
scol = index_ops.spark.column.cast(spark_type)
return index_ops._with_new_scol(scol, field=InternalField(dtype=dtype))
def _sanitize_list_like(operand: Any) -> None:
"""Raise TypeError if operand is list-like."""
if isinstance(operand, (list, tuple, dict, set)):
raise TypeError("The operation can not be applied to %s." % type(operand).__name__)
def _is_valid_for_logical_operator(right: Any) -> bool:
from pyspark.pandas.base import IndexOpsMixin
return isinstance(right, (int, bool)) or (
isinstance(right, IndexOpsMixin)
and (
isinstance(right.spark.data_type, BooleanType)
or isinstance(right.spark.data_type, IntegralType)
)
)
def _is_boolean_type(right: Any) -> bool:
from pyspark.pandas.base import IndexOpsMixin
return isinstance(right, bool) or (
isinstance(right, IndexOpsMixin) and isinstance(right.spark.data_type, BooleanType)
)
class DataTypeOps(object, metaclass=ABCMeta):
"""The base class for binary operations of pandas-on-Spark objects (of different data types)."""
def __new__(cls, dtype: Dtype, spark_type: DataType) -> "DataTypeOps":
from pyspark.pandas.data_type_ops.binary_ops import BinaryOps
from pyspark.pandas.data_type_ops.boolean_ops import BooleanOps, BooleanExtensionOps
from pyspark.pandas.data_type_ops.categorical_ops import CategoricalOps
from pyspark.pandas.data_type_ops.complex_ops import ArrayOps, MapOps, StructOps
from pyspark.pandas.data_type_ops.date_ops import DateOps
from pyspark.pandas.data_type_ops.datetime_ops import DatetimeOps, DatetimeNTZOps
from pyspark.pandas.data_type_ops.null_ops import NullOps
from pyspark.pandas.data_type_ops.num_ops import (
DecimalOps,
FractionalExtensionOps,
FractionalOps,
IntegralExtensionOps,
IntegralOps,
)
from pyspark.pandas.data_type_ops.string_ops import StringOps, StringExtensionOps
from pyspark.pandas.data_type_ops.udt_ops import UDTOps
if isinstance(dtype, CategoricalDtype):
return object.__new__(CategoricalOps)
elif isinstance(spark_type, DecimalType):
return object.__new__(DecimalOps)
elif isinstance(spark_type, FractionalType):
if extension_float_dtypes_available and type(dtype) in [Float32Dtype, Float64Dtype]:
return object.__new__(FractionalExtensionOps)
else:
return object.__new__(FractionalOps)
elif isinstance(spark_type, IntegralType):
if extension_dtypes_available and type(dtype) in [
Int8Dtype,
Int16Dtype,
Int32Dtype,
Int64Dtype,
]:
return object.__new__(IntegralExtensionOps)
else:
return object.__new__(IntegralOps)
elif isinstance(spark_type, StringType):
if extension_object_dtypes_available and isinstance(dtype, StringDtype):
return object.__new__(StringExtensionOps)
else:
return object.__new__(StringOps)
elif isinstance(spark_type, BooleanType):
if extension_object_dtypes_available and isinstance(dtype, BooleanDtype):
return object.__new__(BooleanExtensionOps)
else:
return object.__new__(BooleanOps)
elif isinstance(spark_type, TimestampType):
return object.__new__(DatetimeOps)
elif isinstance(spark_type, TimestampNTZType):
return object.__new__(DatetimeNTZOps)
elif isinstance(spark_type, DateType):
return object.__new__(DateOps)
elif isinstance(spark_type, BinaryType):
return object.__new__(BinaryOps)
elif isinstance(spark_type, ArrayType):
return object.__new__(ArrayOps)
elif isinstance(spark_type, MapType):
return object.__new__(MapOps)
elif isinstance(spark_type, StructType):
return object.__new__(StructOps)
elif isinstance(spark_type, NullType):
return object.__new__(NullOps)
elif isinstance(spark_type, UserDefinedType):
return object.__new__(UDTOps)
else:
raise TypeError("Type %s was not understood." % dtype)
def __init__(self, dtype: Dtype, spark_type: DataType):
self.dtype = dtype
self.spark_type = spark_type
@property
def pretty_name(self) -> str:
raise NotImplementedError()
def add(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("Addition can not be applied to %s." % self.pretty_name)
def sub(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("Subtraction can not be applied to %s." % self.pretty_name)
def mul(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("Multiplication can not be applied to %s." % self.pretty_name)
def truediv(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("True division can not be applied to %s." % self.pretty_name)
def floordiv(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("Floor division can not be applied to %s." % self.pretty_name)
def mod(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("Modulo can not be applied to %s." % self.pretty_name)
def pow(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("Exponentiation can not be applied to %s." % self.pretty_name)
def radd(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("Addition can not be applied to %s." % self.pretty_name)
def rsub(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("Subtraction can not be applied to %s." % self.pretty_name)
def rmul(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("Multiplication can not be applied to %s." % self.pretty_name)
def rtruediv(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("True division can not be applied to %s." % self.pretty_name)
def rfloordiv(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("Floor division can not be applied to %s." % self.pretty_name)
def rmod(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("Modulo can not be applied to %s." % self.pretty_name)
def rpow(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("Exponentiation can not be applied to %s." % self.pretty_name)
def __and__(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("Bitwise and can not be applied to %s." % self.pretty_name)
def xor(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("Bitwise xor can not be applied to %s." % self.pretty_name)
def __or__(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("Bitwise or can not be applied to %s." % self.pretty_name)
def rand(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
return left.__and__(right)
def rxor(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
return left ^ right
def ror(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
_sanitize_list_like(right)
return left.__or__(right)
def neg(self, operand: IndexOpsLike) -> IndexOpsLike:
raise TypeError("Unary - can not be applied to %s." % self.pretty_name)
def abs(self, operand: IndexOpsLike) -> IndexOpsLike:
raise TypeError("abs() can not be applied to %s." % self.pretty_name)
def lt(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("< can not be applied to %s." % self.pretty_name)
def le(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("<= can not be applied to %s." % self.pretty_name)
def gt(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError("> can not be applied to %s." % self.pretty_name)
def ge(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
raise TypeError(">= can not be applied to %s." % self.pretty_name)
def eq(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
from pyspark.pandas.base import column_op
_sanitize_list_like(right)
return column_op(Column.__eq__)(left, right)
def ne(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:
from pyspark.pandas.base import column_op
_sanitize_list_like(right)
return column_op(Column.__ne__)(left, right)
def invert(self, operand: IndexOpsLike) -> IndexOpsLike:
raise TypeError("Unary ~ can not be applied to %s." % self.pretty_name)
def restore(self, col: pd.Series) -> pd.Series:
"""Restore column when to_pandas."""
return col
def prepare(self, col: pd.Series) -> pd.Series:
"""Prepare column when from_pandas."""
return col.replace({np.nan: None})
def isnull(self, index_ops: IndexOpsLike) -> IndexOpsLike:
return index_ops._with_new_scol(
index_ops.spark.column.isNull(),
field=index_ops._internal.data_fields[0].copy(
dtype=np.dtype("bool"), spark_type=BooleanType(), nullable=False
),
)
def nan_to_null(self, index_ops: IndexOpsLike) -> IndexOpsLike:
return index_ops.copy()
def astype(self, index_ops: IndexOpsLike, dtype: Union[str, type, Dtype]) -> IndexOpsLike:
raise TypeError("astype can not be applied to %s." % self.pretty_name)
| python/pyspark/pandas/data_type_ops/base.py | 16,753 | The base class for binary operations of pandas-on-Spark objects (of different data types).
Cast `index_ops` to BooleanType Spark type, given `dtype`.
Cast `index_ops` to categorical dtype, given `dtype` and `spark_type`.
Cast `index_ops` to a `dtype` (`spark_type`) that needs no pre-processing.
Destination types that need pre-processing: CategoricalDtype, BooleanType, and StringType.
Cast `index_ops` to StringType Spark type, given `dtype` and `null_str`,
representing null Spark column. Note that `null_str` is for non-extension dtypes only.
Raise TypeError if operand is list-like.
Check whether the `operand` is valid for arithmetic operations against numerics.
Prepare column when from_pandas.
Restore column when to_pandas.
Transform boolean operand to numeric.
If the `operand` is:
- a boolean IndexOpsMixin, transform the `operand` to the `spark_type`.
- a boolean literal, transform to the int value.
Otherwise, return the operand as it is.
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You 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. | 1,716 | en | 0.735159 |
#! python
from nose.tools import assert_true, assert_raises
import random
from networkx import random_reference, lattice_reference, sigma, omega
import networkx as nx
rng = random.Random(0)
rng = 42
def test_random_reference():
G = nx.connected_watts_strogatz_graph(50, 6, 0.1, seed=rng)
Gr = random_reference(G, niter=1, seed=rng)
C = nx.average_clustering(G)
Cr = nx.average_clustering(Gr)
assert_true(C > Cr)
assert_raises(nx.NetworkXError, random_reference, nx.Graph())
assert_raises(nx.NetworkXNotImplemented, random_reference, nx.DiGraph())
H = nx.Graph(((0, 1), (2, 3)))
Hl = random_reference(H, niter=1, seed=rng)
def test_lattice_reference():
G = nx.connected_watts_strogatz_graph(50, 6, 1, seed=rng)
Gl = lattice_reference(G, niter=1, seed=rng)
L = nx.average_shortest_path_length(G)
Ll = nx.average_shortest_path_length(Gl)
assert_true(Ll > L)
assert_raises(nx.NetworkXError, lattice_reference, nx.Graph())
assert_raises(nx.NetworkXNotImplemented, lattice_reference, nx.DiGraph())
H = nx.Graph(((0, 1), (2, 3)))
Hl = lattice_reference(H, niter=1)
def test_sigma():
Gs = nx.connected_watts_strogatz_graph(50, 6, 0.1, seed=rng)
Gr = nx.connected_watts_strogatz_graph(50, 6, 1, seed=rng)
sigmas = sigma(Gs, niter=1, nrand=2, seed=rng)
sigmar = sigma(Gr, niter=1, nrand=2, seed=rng)
assert_true(sigmar < sigmas)
def test_omega():
Gl = nx.connected_watts_strogatz_graph(50, 6, 0, seed=rng)
Gr = nx.connected_watts_strogatz_graph(50, 6, 1, seed=rng)
Gs = nx.connected_watts_strogatz_graph(50, 6, 0.1, seed=rng)
omegal = omega(Gl, niter=1, nrand=1, seed=rng)
omegar = omega(Gr, niter=1, nrand=1, seed=rng)
omegas = omega(Gs, niter=1, nrand=1, seed=rng)
print("omegas, omegal, omegar")
print(omegas, omegal, omegar)
assert_true(omegal < omegas and omegas < omegar)
# fixture for nose tests
def setup_module(module):
from nose import SkipTest
try:
import numpy
except:
raise SkipTest("NumPy not available")
| SLpackage/private/thirdparty/pythonpkgs/networkx/networkx_2.2/lib/python2.7/site-packages/networkx/algorithms/tests/test_smallworld.py | 2,081 | ! python fixture for nose tests | 31 | en | 0.746336 |
# Copyright (c) 2015 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to the Shotgun Pipeline Toolkit Source Code License. All rights
# not expressly granted therein are reserved by Shotgun Software Inc.
from sgtk.platform.qt import QtCore, QtGui
import sgtk
class WorkAreaButton(QtGui.QToolButton):
"""
UX for switching work area.
This displays a "change work area" button which a user can interact with
The button is designed to expand so that it is subtle until a user
hovers over it.
:signal clicked(str, int): Fires when someone clicks the change
work area button. Arguments passed are the entity type and entity id
"""
WIDGET_WIDTH_COLLAPSED = 30
WIDGET_HEIGHT = 30
NON_WORK_AREA_TYPES = [
"PublishedFile",
"Project",
"TankPublishedFile",
"Version",
"Note",
"Group",
"HumanUser",
"ScriptUser",
"ApiUser",
"ClientUser",
"Department",
"Cut",
"CutItem",
"Delivery",
"Playlist",
"Ticket"
]
change_work_area = QtCore.Signal(str, int)
def __init__(self, parent):
"""
:param parent: The model parent.
:type parent: :class:`~PySide.QtGui.QObject`
"""
super(WorkAreaButton, self).__init__(parent)
# an icon to represent all items which
# aren't the current work area
self._normal_icon = QtGui.QIcon()
self._normal_icon.addPixmap(
QtGui.QPixmap(":/tk_multi_infopanel/pin.png"),
QtGui.QIcon.Normal,
QtGui.QIcon.Off
)
# an icon to represent the current work area
self._current_work_area_icon = QtGui.QIcon()
self._current_work_area_icon.addPixmap(
QtGui.QPixmap(":/tk_multi_infopanel/pin_blue.png"),
QtGui.QIcon.Disabled,
QtGui.QIcon.Off
)
self.setIcon(self._normal_icon)
self.setIconSize(QtCore.QSize(self.WIDGET_WIDTH_COLLAPSED, self.WIDGET_HEIGHT))
self._bundle = sgtk.platform.current_bundle()
self._entity_type = None
self._entity_id = None
self._is_static = False
self._caption = "Set Work Area"
self._width = 120
self.clicked.connect(self._on_click)
self.setVisible(False)
def set_up(self, entity_type, entity_id):
"""
Sets up the button for a given entity.
:param entity_type: Entity type to set up button for
:param entity_id: Entity id to set up button for
"""
self._entity_id = entity_id
self._entity_type = entity_type
if not self._bundle.get_setting("enable_context_switch"):
# context switch button not enabled
return
# figure out if this is the current project
context = self._bundle.context
context_entity = context.task or context.entity or context.project or None
self.setVisible(True)
self.setEnabled(True)
self.setIcon(self._normal_icon)
self._is_static = False
if context_entity and context_entity["type"] == entity_type and context_entity["id"] == entity_id:
# the current work area
self.setPopupMode(QtGui.QToolButton.DelayedPopup)
self.setToolTip(
"This is your current work area.\n"
"The work you do will be associated with this item in Shotgun."
)
# set blue icon
self.setIcon(self._current_work_area_icon)
# disable the button
self.setEnabled(False)
# make sure it doesn't pop on mouseover
self._is_static = True
elif entity_type in self.NON_WORK_AREA_TYPES:
# don't show the ctx selector for some types
self.setToolTip("This cannot be a work area.")
# disable the button
self.setEnabled(False)
# make sure it doesn't pop on mouse over
self._is_static = True
else:
if entity_type == "Task":
self._caption = "Set Work Area"
self.setToolTip("Click to set your work area to the current task.")
else:
self._caption = "Pick Work Area"
self.setToolTip("Click to select a task.")
self._init_default_state()
def _init_default_state(self):
"""
Sets up the default collapsed state of the button
"""
self.setText("")
self.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)
self.setMinimumSize(QtCore.QSize(self.WIDGET_WIDTH_COLLAPSED, self.WIDGET_HEIGHT))
self.setMaximumSize(QtCore.QSize(self.WIDGET_WIDTH_COLLAPSED, self.WIDGET_HEIGHT))
# tell the style sheet to adjust
self.setProperty("is_expanded", False)
self.style().unpolish(self)
self.style().polish(self)
def _on_click(self):
"""
Executed when the button is clicked
"""
self.change_work_area.emit(self._entity_type, self._entity_id)
def enterEvent(self, evt):
"""
QT Mouse enter event
"""
if not self._is_static:
# not the current work area. so expand the button
self.setText(self._caption)
self.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
self.setMinimumSize(QtCore.QSize(self._width, self.WIDGET_HEIGHT))
self.setMaximumSize(QtCore.QSize(self._width, self.WIDGET_HEIGHT))
# tell the style sheet to adjust
self.setProperty("is_expanded", True)
self.style().unpolish(self)
self.style().polish(self)
return super(WorkAreaButton, self).enterEvent(evt)
def leaveEvent(self, evt):
"""
QT Mouse leave event
"""
if not self._is_static:
# collapse button after a delay
QtCore.QTimer.singleShot(300, self._init_default_state)
return super(WorkAreaButton, self).leaveEvent(evt)
class FloatingWorkAreaButton(WorkAreaButton):
"""
UX for switching work area.
This displays a "change work area" button which a user can interact with
The button is designed to expand so that it is subtle until a user
hovers over it.
Derives from :class:`WorkAreaButton` and positions the widget
relative to the bottom-right corner of the parent widget.
:signal clicked(str, int): Fires when someone clicks the change
work area button. Arguments passed are the entity type and entity id
"""
RIGHT_OFFSET = 6
BOTTOM_OFFSET = 6
def __init__(self, parent):
"""
:param right_side_offset: Right hand side offset in pixels
:param bottom_offset: Bottom offset in pixels
:param parent: The model parent.
:type parent: :class:`~PySide.QtGui.QObject`
"""
super(FloatingWorkAreaButton, self).__init__(parent)
# hook up a listener to the parent window so this widget
# follows along when the parent window changes size
filter = ResizeEventFilter(parent)
filter.resized.connect(self._on_parent_resized)
parent.installEventFilter(filter)
def set_up(self, entity_type, entity_id):
"""
Sets up the button for a given entity.
:param entity_type: Entity type to set up button for
:param entity_id: Entity id to set up button for
"""
if entity_type in self.NON_WORK_AREA_TYPES:
# hide the widget
self.setVisible(False)
else:
# base class implementation
super(FloatingWorkAreaButton, self).set_up(entity_type, entity_id)
def __position_widget(self):
"""
Moves the widget to the bottom-right corner of the parent widget.
"""
self.move(
self.parentWidget().width() - self.width() - self.RIGHT_OFFSET,
self.parentWidget().height() - self.height() - self.BOTTOM_OFFSET
)
def _init_default_state(self):
"""
Sets up the default collapsed state of the button
"""
super(FloatingWorkAreaButton, self)._init_default_state()
self.__position_widget()
def enterEvent(self, evt):
"""
QT Mouse enter event
"""
status = super(FloatingWorkAreaButton, self).enterEvent(evt)
if not self._is_static:
self.__position_widget()
return status
def _on_parent_resized(self):
"""
Special slot hooked up to the event filter.
When associated widget is resized this slot is being called.
"""
self.__position_widget()
class ResizeEventFilter(QtCore.QObject):
"""
Utility and helper.
Event filter which emits a resized signal whenever
the monitored widget resizes.
You use it like this:
# create the filter object. Typically, it's
# it's easiest to parent it to the object that is
# being monitored (in this case self.ui.thumbnail)
filter = ResizeEventFilter(self.ui.thumbnail)
# now set up a signal/slot connection so that the
# __on_thumb_resized slot gets called every time
# the widget is resized
filter.resized.connect(self.__on_thumb_resized)
# finally, install the event filter into the QT
# event system
self.ui.thumbnail.installEventFilter(filter)
"""
resized = QtCore.Signal()
def eventFilter(self, obj, event):
"""
Event filter implementation.
For information, see the QT docs:
http://doc.qt.io/qt-4.8/qobject.html#eventFilter
This will emit the resized signal (in this class)
whenever the linked up object is being resized.
:param obj: The object that is being watched for events
:param event: Event object that the object has emitted
:returns: Always returns False to indicate that no events
should ever be discarded by the filter.
"""
# peek at the message
if event.type() == QtCore.QEvent.Resize:
# re-broadcast any resize events
self.resized.emit()
# pass it on!
return False
| install/app_store/tk-multi-shotgunpanel/v1.4.8/python/app/work_area_button.py | 10,492 | UX for switching work area.
This displays a "change work area" button which a user can interact with
The button is designed to expand so that it is subtle until a user
hovers over it.
Derives from :class:`WorkAreaButton` and positions the widget
relative to the bottom-right corner of the parent widget.
:signal clicked(str, int): Fires when someone clicks the change
work area button. Arguments passed are the entity type and entity id
Utility and helper.
Event filter which emits a resized signal whenever
the monitored widget resizes.
You use it like this:
# create the filter object. Typically, it's
# it's easiest to parent it to the object that is
# being monitored (in this case self.ui.thumbnail)
filter = ResizeEventFilter(self.ui.thumbnail)
# now set up a signal/slot connection so that the
# __on_thumb_resized slot gets called every time
# the widget is resized
filter.resized.connect(self.__on_thumb_resized)
# finally, install the event filter into the QT
# event system
self.ui.thumbnail.installEventFilter(filter)
UX for switching work area.
This displays a "change work area" button which a user can interact with
The button is designed to expand so that it is subtle until a user
hovers over it.
:signal clicked(str, int): Fires when someone clicks the change
work area button. Arguments passed are the entity type and entity id
:param parent: The model parent.
:type parent: :class:`~PySide.QtGui.QObject`
:param right_side_offset: Right hand side offset in pixels
:param bottom_offset: Bottom offset in pixels
:param parent: The model parent.
:type parent: :class:`~PySide.QtGui.QObject`
Moves the widget to the bottom-right corner of the parent widget.
Sets up the default collapsed state of the button
Sets up the default collapsed state of the button
Executed when the button is clicked
Special slot hooked up to the event filter.
When associated widget is resized this slot is being called.
QT Mouse enter event
QT Mouse enter event
Event filter implementation.
For information, see the QT docs:
http://doc.qt.io/qt-4.8/qobject.html#eventFilter
This will emit the resized signal (in this class)
whenever the linked up object is being resized.
:param obj: The object that is being watched for events
:param event: Event object that the object has emitted
:returns: Always returns False to indicate that no events
should ever be discarded by the filter.
QT Mouse leave event
Sets up the button for a given entity.
:param entity_type: Entity type to set up button for
:param entity_id: Entity id to set up button for
Sets up the button for a given entity.
:param entity_type: Entity type to set up button for
:param entity_id: Entity id to set up button for
Copyright (c) 2015 Shotgun Software Inc. CONFIDENTIAL AND PROPRIETARY This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit Source Code License included in this distribution package. See LICENSE. By accessing, using, copying or modifying this work you indicate your agreement to the Shotgun Pipeline Toolkit Source Code License. All rights not expressly granted therein are reserved by Shotgun Software Inc. an icon to represent all items which aren't the current work area an icon to represent the current work area context switch button not enabled figure out if this is the current project the current work area set blue icon disable the button make sure it doesn't pop on mouseover don't show the ctx selector for some types disable the button make sure it doesn't pop on mouse over tell the style sheet to adjust not the current work area. so expand the button tell the style sheet to adjust collapse button after a delay hook up a listener to the parent window so this widget follows along when the parent window changes size hide the widget base class implementation peek at the message re-broadcast any resize events pass it on! | 3,869 | en | 0.836694 |
#!/usr/bin/env python
"""The setup script."""
from setuptools import find_packages, setup
with open('requirements.txt') as f:
INSTALL_REQUIREs = f.read().strip().split('\n')
with open('README.md', encoding='utf8') as f:
LONG_DESCRIPTION = f.read()
CLASSIFIERS = [
'Development Status :: 4 - Beta',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Topic :: Scientific/Engineering',
]
setup(
name='repo2singularity',
description='Repo2singularity: Wrapper around repo2docker producing producing Jupyter enabled Singularity images.',
long_description=LONG_DESCRIPTION,
python_requires='>=3.6',
maintainer='Anderson Banihirwe',
classifiers=CLASSIFIERS,
url='https://github.com/andersy005/repo2singularity',
packages=find_packages(exclude=('tests',)),
include_package_data=True,
install_requires=INSTALL_REQUIREs,
license='Apache 2.0',
zip_safe=False,
entry_points={'console_scripts': ['repo2singularity = repo2singularity.core:main']},
keywords='reproducible science environments docker singularity',
use_scm_version={'version_scheme': 'post-release', 'local_scheme': 'dirty-tag'},
setup_requires=['setuptools_scm', 'setuptools>=30.3.0'],
)
| setup.py | 1,533 | The setup script.
!/usr/bin/env python | 39 | en | 0.349468 |
from functools import partial
from itertools import product
import numpy as np
from tlz import curry
from ..base import tokenize
from ..utils import funcname
from .blockwise import BlockwiseCreateArray
from .core import Array, normalize_chunks
from .utils import (
meta_from_array,
empty_like_safe,
full_like_safe,
ones_like_safe,
zeros_like_safe,
)
def _parse_wrap_args(func, args, kwargs, shape):
if isinstance(shape, np.ndarray):
shape = shape.tolist()
if not isinstance(shape, (tuple, list)):
shape = (shape,)
name = kwargs.pop("name", None)
chunks = kwargs.pop("chunks", "auto")
dtype = kwargs.pop("dtype", None)
if dtype is None:
dtype = func(shape, *args, **kwargs).dtype
dtype = np.dtype(dtype)
chunks = normalize_chunks(chunks, shape, dtype=dtype)
name = name or funcname(func) + "-" + tokenize(
func, shape, chunks, dtype, args, kwargs
)
return {
"shape": shape,
"dtype": dtype,
"kwargs": kwargs,
"chunks": chunks,
"name": name,
}
def wrap_func_shape_as_first_arg(func, *args, **kwargs):
"""
Transform np creation function into blocked version
"""
if "shape" not in kwargs:
shape, args = args[0], args[1:]
else:
shape = kwargs.pop("shape")
if isinstance(shape, Array):
raise TypeError(
"Dask array input not supported. "
"Please use tuple, list, or a 1D numpy array instead."
)
parsed = _parse_wrap_args(func, args, kwargs, shape)
shape = parsed["shape"]
dtype = parsed["dtype"]
chunks = parsed["chunks"]
name = parsed["name"]
kwargs = parsed["kwargs"]
func = partial(func, dtype=dtype, **kwargs)
graph = BlockwiseCreateArray(
name,
func,
shape,
chunks,
)
return Array(graph, name, chunks, dtype=dtype, meta=kwargs.get("meta", None))
def wrap_func_like(func, *args, **kwargs):
"""
Transform np creation function into blocked version
"""
x = args[0]
meta = meta_from_array(x)
shape = kwargs.get("shape", x.shape)
parsed = _parse_wrap_args(func, args, kwargs, shape)
shape = parsed["shape"]
dtype = parsed["dtype"]
chunks = parsed["chunks"]
name = parsed["name"]
kwargs = parsed["kwargs"]
keys = product([name], *[range(len(bd)) for bd in chunks])
shapes = product(*chunks)
shapes = list(shapes)
kw = [kwargs for _ in shapes]
for i, s in enumerate(list(shapes)):
kw[i]["shape"] = s
vals = ((partial(func, dtype=dtype, **k),) + args for (k, s) in zip(kw, shapes))
dsk = dict(zip(keys, vals))
return Array(dsk, name, chunks, meta=meta.astype(dtype))
def wrap_func_like_safe(func, func_like, *args, **kwargs):
"""
Safe implementation for wrap_func_like(), attempts to use func_like(),
if the shape keyword argument, falls back to func().
"""
try:
return func_like(*args, **kwargs)
except TypeError:
return func(*args, **kwargs)
@curry
def wrap(wrap_func, func, **kwargs):
func_like = kwargs.pop("func_like", None)
if func_like is None:
f = partial(wrap_func, func, **kwargs)
else:
f = partial(wrap_func, func_like, **kwargs)
template = """
Blocked variant of %(name)s
Follows the signature of %(name)s exactly except that it also features
optional keyword arguments ``chunks: int, tuple, or dict`` and ``name: str``.
Original signature follows below.
"""
if func.__doc__ is not None:
f.__doc__ = template % {"name": func.__name__} + func.__doc__
f.__name__ = "blocked_" + func.__name__
return f
w = wrap(wrap_func_shape_as_first_arg)
@curry
def _broadcast_trick_inner(func, shape, meta=(), *args, **kwargs):
if shape == ():
return np.broadcast_to(func(meta, shape=(), *args, **kwargs), shape)
else:
return np.broadcast_to(func(meta, shape=1, *args, **kwargs), shape)
def broadcast_trick(func):
"""
Provide a decorator to wrap common numpy function with a broadcast trick.
Dask arrays are currently immutable; thus when we know an array is uniform,
we can replace the actual data by a single value and have all elements point
to it, thus reducing the size.
>>> x = np.broadcast_to(1, (100,100,100))
>>> x.base.nbytes
8
Those array are not only more efficient locally, but dask serialisation is
aware of the _real_ size of those array and thus can send them around
efficiently and schedule accordingly.
Note that those array are read-only and numpy will refuse to assign to them,
so should be safe.
"""
inner = _broadcast_trick_inner(func)
if func.__doc__ is not None:
inner.__doc__ = func.__doc__
inner.__name__ = func.__name__
if inner.__name__.endswith("_like_safe"):
inner.__name__ = inner.__name__[:-10]
return inner
ones = w(broadcast_trick(ones_like_safe), dtype="f8")
zeros = w(broadcast_trick(zeros_like_safe), dtype="f8")
empty = w(broadcast_trick(empty_like_safe), dtype="f8")
w_like = wrap(wrap_func_like_safe)
empty_like = w_like(np.empty, func_like=np.empty_like)
# full and full_like require special casing due to argument check on fill_value
# Generate wrapped functions only once
_full = w(broadcast_trick(full_like_safe))
_full_like = w_like(np.full, func_like=np.full_like)
# workaround for numpy doctest failure: https://github.com/numpy/numpy/pull/17472
_full.__doc__ = _full.__doc__.replace(
"array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])",
"array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])",
)
def full(shape, fill_value, *args, **kwargs):
# np.isscalar has somewhat strange behavior:
# https://docs.scipy.org/doc/numpy/reference/generated/numpy.isscalar.html
if np.ndim(fill_value) != 0:
raise ValueError(
f"fill_value must be scalar. Received {type(fill_value).__name__} instead."
)
return _full(shape=shape, fill_value=fill_value, *args, **kwargs)
def full_like(a, fill_value, *args, **kwargs):
if np.ndim(fill_value) != 0:
raise ValueError(
f"fill_value must be scalar. Received {type(fill_value).__name__} instead."
)
return _full_like(
a=a,
fill_value=fill_value,
*args,
**kwargs,
)
full.__doc__ = _full.__doc__
full_like.__doc__ = _full_like.__doc__
| dask/array/wrap.py | 6,472 | Provide a decorator to wrap common numpy function with a broadcast trick.
Dask arrays are currently immutable; thus when we know an array is uniform,
we can replace the actual data by a single value and have all elements point
to it, thus reducing the size.
>>> x = np.broadcast_to(1, (100,100,100))
>>> x.base.nbytes
8
Those array are not only more efficient locally, but dask serialisation is
aware of the _real_ size of those array and thus can send them around
efficiently and schedule accordingly.
Note that those array are read-only and numpy will refuse to assign to them,
so should be safe.
Transform np creation function into blocked version
Safe implementation for wrap_func_like(), attempts to use func_like(),
if the shape keyword argument, falls back to func().
Transform np creation function into blocked version
full and full_like require special casing due to argument check on fill_value Generate wrapped functions only once workaround for numpy doctest failure: https://github.com/numpy/numpy/pull/17472 np.isscalar has somewhat strange behavior: https://docs.scipy.org/doc/numpy/reference/generated/numpy.isscalar.html | 1,143 | en | 0.799889 |
"""
Tests for lyrics_tagger
"""
from __future__ import unicode_literals
from __future__ import print_function
import unittest
import mock
import lyricstagger.misc as misc
import test.fakers as fakers
# pylint: disable=R0904
class MiscCheck(unittest.TestCase):
"""Test miscelanous functions"""
def test_get_tags_multi(self):
"""Test get_tags with multi-tag file"""
for mime in ['audio/mp3', 'audio/ogg']:
audio = fakers.FakeFile(mime, ['Artist'], ['Album'],
['Title'], 'Lyrics')
tags = misc.get_tags(audio)
self.assertEqual(tags['album'], "Album")
self.assertEqual(tags['artist'], "Artist")
self.assertEqual(tags['title'], "Title")
self.assertEqual(tags['lyrics'], "Lyrics")
def test_get_tags_single(self):
"""Test get_tags with single-tag file"""
for mime in ['audio/mp3', 'audio/ogg']:
audio = fakers.FakeFile(mime, 'Artist', 'Album', 'Title', 'Lyrics')
tags = misc.get_tags(audio)
self.assertEqual(tags['album'], "Album")
self.assertEqual(tags['artist'], "Artist")
self.assertEqual(tags['title'], "Title")
self.assertEqual(tags['lyrics'], "Lyrics")
def test_get_tags_broken(self):
"""Test get_tags with broken tags"""
audio = fakers.BrokenFile('audio/ogg', {'test': 'Test',
'album': 'Album',
'title': 'Title'})
tags = misc.get_tags(audio)
self.assertEqual(tags, None)
@mock.patch('lyricstagger.misc.click.edit', fakers.mock_edit_ok)
def test_edit_lyrics_empty_ok(self):
"""Test edit_lyrics with empty lyrics and correct edit"""
audio = fakers.FakeFile('audio/ogg', 'Artist', 'Album', 'Title')
lyrics = misc.edit_lyrics(audio)
self.assertEqual(lyrics, "")
@mock.patch('lyricstagger.misc.click.edit', fakers.mock_edit_fail)
def test_edit_lyrics_empty_fail(self):
"""Test edit_lyrics with empty lyrics and errored edit"""
audio = fakers.FakeFile('audio/ogg', 'Artist', 'Album', 'Title')
lyrics = misc.edit_lyrics(audio)
self.assertEqual(lyrics, None)
@mock.patch('lyricstagger.misc.click.edit', fakers.mock_edit_ok)
def test_edit_lyrics_nonempty_ok(self):
"""Test edit_lyrics with non-empty lyrics and correct edit"""
audio = fakers.FakeFile('audio/ogg', 'Artist', 'Album',
'Title', 'Lyrics')
lyrics = misc.edit_lyrics(audio)
self.assertEqual(lyrics, "Lyrics")
@mock.patch('lyricstagger.misc.click.edit', fakers.mock_edit_fail)
def test_edit_lyrics_nonempty_fail(self):
"""Test edit_lyrics with non-empty lyrics and errored edit"""
audio = fakers.FakeFile('audio/ogg', 'Artist', 'Album',
'Title', 'Lyrics')
lyrics = misc.edit_lyrics(audio)
self.assertEqual(lyrics, None)
def test_get_file_list(self):
file_list = list(misc.get_file_list(["test/test_data"]))
self.assertIn("test/test_data/test_dir_0/test_file_0.ogg", file_list)
self.assertIn("test/test_data/test_dir_1/test_file_1.ogg", file_list)
# pylint: enable=R0904
if __name__ == '__main__':
unittest.main()
| test/test_misc.py | 3,385 | Test miscelanous functions
Test edit_lyrics with empty lyrics and errored edit
Test edit_lyrics with empty lyrics and correct edit
Test edit_lyrics with non-empty lyrics and errored edit
Test edit_lyrics with non-empty lyrics and correct edit
Test get_tags with broken tags
Test get_tags with multi-tag file
Test get_tags with single-tag file
Tests for lyrics_tagger
pylint: disable=R0904 pylint: enable=R0904 | 411 | en | 0.720331 |
import copy
import torch
import logging
import numpy as np
from sacred import Experiment
from noge.data_loaders import get_datasets, get_test_loader, get_train_generator
from noge.factory import make_env, make_memory
from noge.network import make_network
from noge.agent import Actor, main_loop, loop_ing
from noge.trainers import DQNTrainer, Replay
from noge.policies import LinearSchedule, GraphDQNPolicy
from noge.preprocessors import Preprocessor
from noge.evaluation import Evaluator, eval_ing
from noge.constants import CONFIGS_DIR, EVAL_DIR
from xlog.utils import get_logger
from xlog.mlflow_observer import MlflowObserver
ex = Experiment(name='NOGE_DQN', ingredients=[eval_ing, loop_ing])
ex.add_config(str(CONFIGS_DIR / 'dqn.yaml'))
ex.logger = get_logger(__name__, level=logging.INFO)
ex.observers = [MlflowObserver(tracking_uri=str(EVAL_DIR.absolute()))]
@ex.automain
def train(dataset, test_size, max_episode_steps, reward_type, input_meas_type, meas_transform,
target_transform, node_history, gamma, target_update_freq,
cat_features, feature_range, replay_capacity, min_horizon, epsilon_start, epsilon_end,
exploration_frac, n_train_steps, train_freq, loss, batch_size, lr, n_test_episodes, init_eval,
n_eval_artifacts, test_freq, log_freq, device, seed, data_seed, save_model, _log, _run, _config):
np.set_printoptions(precision=2, suppress=True)
if device.startswith('cuda'):
assert torch.cuda.is_available()
logger = _log
device = torch.device(device)
# data source
train_set, test_set = get_datasets(dataset, seed=data_seed, test_size=test_size)
max_nodes = max(train_set.max_nodes, test_set.max_nodes)
max_edges = 2 * max(train_set.max_edges, test_set.max_edges) # for undirected graphs, consider both directions
test_loader = get_test_loader(test_set, seed=seed, num_samples=n_test_episodes)
train_gen = get_train_generator(train_set, seed=seed)
preprocessor = Preprocessor(input_meas_type=input_meas_type,
output_meas_type=input_meas_type,
feature_range=feature_range,
meas_transform=meas_transform,
target_transform=target_transform,
temporal_offsets=[1.],
max_nodes=max_nodes,
device=device)
# environment
train_env_config = dict(
max_episode_steps=max_episode_steps,
reward_type=reward_type,
max_nodes=max_nodes,
max_edges=max_edges,
nn_feat='N' in cat_features,
)
train_env = make_env(**train_env_config, data_generator=train_gen, seed=seed)
test_env_config = copy.deepcopy(train_env_config)
test_env_config.update(sample_goals=False, data_generator=None)
test_env = make_env(**test_env_config, seed=seed)
# graph memory + graph preprocessing
neg_label, pos_label = feature_range
mem_features = dict(cat=cat_features)
graph_mem_config = dict(
max_episode_steps=max_episode_steps,
max_nodes=max_nodes,
max_edges=max_edges,
history=node_history,
memory_type='cat',
features=mem_features,
neg_label=neg_label,
pos_label=pos_label
)
eval_memory = make_memory(online=True, **graph_mem_config)
acting_memory = make_memory(online=True, **graph_mem_config)
# model
model_config = dict(
dim_node=eval_memory.dim_node,
dim_meas=preprocessor.dim_input_meas,
dim_goal=1,
max_edges=max_edges,
**_config['model']
)
network = make_network(**model_config).to(device)
# evaluation
eval_policy = GraphDQNPolicy(network, eval_memory, preprocessor=preprocessor, device=device)
evaluator = Evaluator(test_loader, test_env, eval_policy)
# experience collecting policy
exploration_steps = int(exploration_frac * n_train_steps)
exploration_schedule = LinearSchedule(epsilon_start, epsilon_end, exploration_steps)
acting_policy = GraphDQNPolicy(network,
graph_memory=acting_memory,
preprocessor=preprocessor,
exploration_schedule=exploration_schedule,
device=device)
# replay buffer
replay_buffer = Replay(capacity=replay_capacity,
ob_space=train_env.observation_space,
graph_mem_config=graph_mem_config,
min_horizon=min_horizon)
# actor: runs the simulation forward and stores to the replay buffer
actor = Actor(train_env, acting_policy, replay_buffer)
# trainer
optimizer = torch.optim.Adam(network.parameters(), lr=lr)
if loss == 'mse':
criterion = torch.nn.MSELoss()
else:
raise ValueError(f"Unsupported loss: {loss}")
trainer = DQNTrainer(gamma=gamma,
target_update_freq=target_update_freq,
replay_buffer=replay_buffer,
batch_size=batch_size,
network=network,
preprocessor=preprocessor,
criterion=criterion,
optimizer=optimizer,
device=device)
# fill up the replay buffer
network.eval()
logger.info(f"Filling up the replay buffer...")
actor.step(n=replay_capacity, use_tqdm=True)
logger.info(f"Replay buffer filled: [{len(replay_buffer)} / {replay_capacity}]")
# fit the preprocessor with buffer data
preprocessor.fit(replay_buffer._measurements)
best_perf = main_loop(actor, trainer, evaluator, network, exploration_schedule,
init_eval, n_eval_artifacts, n_train_steps, train_freq, log_freq, test_freq, save_model)
train_env.close()
evaluator.close()
return best_perf
| scripts/train_dqn.py | 6,004 | data source for undirected graphs, consider both directions environment graph memory + graph preprocessing model evaluation experience collecting policy replay buffer actor: runs the simulation forward and stores to the replay buffer trainer fill up the replay buffer fit the preprocessor with buffer data | 305 | en | 0.850947 |
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from Constants import *
from Gifts.getRecommendations.RS import Users, Recommendations
import json
# Create your views here.
def check_input(request, mandatory_fields, optional_fields=None):
if not optional_fields: optional_fields = []
for key in request.keys():
if key not in mandatory_fields and key not in optional_fields:
return {'result': 'Error', 'message': key + ' is not a valid field'}
for field in mandatory_fields:
if field not in request.keys():
return {'result': 'Error', 'message': field + ' do not presented'}
return {"result": "Success"}
def add_user(request):
if 'userProfile' not in request:
return JsonResponse({'result': 'Error', 'message': 'userProfile do not presented'})
result = check_input(request['userProfile'], ["sex", "age", "hobbies", "userType"],
["alreadyGifted", "lovedCategories"])
if result['result'] == "Error":
return JsonResponse(result)
if request['userProfile']['sex'] not in ['Female', 'Male']:
return JsonResponse({'result': 'Error', 'message': request['userProfile']['sex'] +
' is not a valid sex'})
if 'alreadyGifted' not in request['userProfile']:
request['userProfile']['alreadyGifted'] = []
if 'lovedCategories' not in request['userProfile']:
request['userProfile']['lovedCategories'] = []
try:
user_id = Users.add_user(request['userProfile'])
except Exception as e:
print e
return JsonResponse({'result': 'Error', 'message': 'error while adding user'})
return JsonResponse({'result': 'Success', 'data': {'userId': user_id}})
def make_list(request):
result = check_input(request, ["userId"], ["filter"])
if result['result'] == "Error":
return JsonResponse(result)
if 'filter' in request:
result = check_input(request['filter'], [], ["minPrice", "maxPrice"])
if result['result'] == "Error":
return JsonResponse(result)
min_price = None
max_price = None
if 'filter' in request:
if 'minPrice' in request['filter']:
min_price = request['filter']['minPrice']
if 'maxPrice' in request['filter']:
max_price = request['filter']['maxPrice']
try:
Recommendations.generate_list(request['userId'], min_price, max_price)
number_of_pages = Recommendations.get_number_of_pages(request['userId'])
except Exception as e:
print e
return JsonResponse({'result': 'error', 'message': 'error while making list'})
return JsonResponse({'result': 'Success', 'data': {'numberOfPages': number_of_pages}})
def get_suggestions(request):
result = check_input(request, ["page", "userId"])
if result['result'] == "Error":
return JsonResponse(result)
try:
items = Recommendations.get_page(request['userId'], request['page'])
number_of_pages = Recommendations.get_number_of_pages(request['userId'])
except Exception as e:
print e
return JsonResponse({'result': 'Error', 'message': 'error during getting list'})
if items:
request = {'result': 'Success', 'data': {'items': items, "numberOfPages": number_of_pages}}
elif items == []:
request = {'result': 'Error', 'message': 'page out of range'}
else:
request = {'result': 'Error', 'message': 'error during getting list'}
return JsonResponse(request)
def rate_item(request):
result = check_input(request, ["userId", "itemId", "rating"])
if result['result'] == "Error":
return JsonResponse(result)
try:
Recommendations.rate_and_remove(request['userId'], request['itemId'], request['rating'])
number_of_pages = Recommendations.get_number_of_pages(request['userId'])
except Exception as e:
print e
return JsonResponse({"result": "Error", "message": "error during rating item"})
return JsonResponse({"result": "Success", 'data': {'numberOfPages': number_of_pages}})
@csrf_exempt
def home(request):
if request.method == "POST":
try:
request_dict = json.loads(request.body)
print(request_dict)
if 'task' not in request_dict:
return JsonResponse({'result': 'Error', 'message': 'task do not presented'})
if 'data' not in request_dict:
return JsonResponse({'result': 'Error', 'message': 'data do not presented'})
if request_dict['task'] == 'addUser':
return add_user(request_dict['data'])
if request_dict['task'] == 'makeList':
return make_list(request_dict['data'])
if request_dict['task'] == 'getSuggestions':
return get_suggestions(request_dict['data'])
if request_dict['task'] == 'rateItem':
return rate_item(request_dict['data'])
return JsonResponse({'result': 'Error', 'message':
request_dict['task'] + " is not a valid task"})
except Exception as e:
print e
return JsonResponse({'result': 'Error', 'message': "strange error"})
return HttpResponse('''
<h1>Welcome on GRS</h1>
''')
| backend/Gifts/views.py | 5,472 | Create your views here. Create your views here. | 47 | en | 0.930111 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutTuples(Koan):
def test_creating_a_tuple(self):
count_of_three = (1, 2, 5)
self.assertEqual(5, count_of_three[2])
def test_tuples_are_immutable_so_item_assignment_is_not_possible(self):
count_of_three = (1, 2, 5)
try:
count_of_three[2] = "three"
except TypeError as ex:
self.assertMatch('upl', ex[0])
def test_tuples_are_immutable_so_appending_is_not_possible(self):
count_of_three = (1, 2, 5)
try:
count_of_three.append("boom")
except Exception as ex:
self.assertEqual(AttributeError, type(ex))
# Note, assertMatch() uses regular expression pattern matching,
# so you don't have to copy the whole message.
self.assertMatch('object', ex[0])
# Tuples are less flexible than lists, but faster.
def test_tuples_can_only_be_changed_through_replacement(self):
count_of_three = (1, 2, 5)
list_count = list(count_of_three)
list_count.append("boom")
count_of_three = tuple(list_count)
self.assertEqual((1, 2, 5, 'boom'), count_of_three)
def test_tuples_of_one_look_peculiar(self):
self.assertEqual(type(int(1)), (1).__class__)
self.assertEqual(type((1,2)), (1,).__class__)
self.assertEqual(('Hello comma!',), ("Hello comma!", ))
def test_tuple_constructor_can_be_surprising(self):
self.assertEqual(('S', 'u', 'r', 'p', 'r', 'i', 's', 'e', '!'), tuple("Surprise!"))
def test_creating_empty_tuples(self):
self.assertEqual(tuple(), ())
self.assertEqual((), tuple()) # Sometimes less confusing
def test_tuples_can_be_embedded(self):
lat = (37, 14, 6, 'N')
lon = (115, 48, 40, 'W')
place = ('Area 51', lat, lon)
self.assertEqual(('Area 51',(37,14,6,'N'),(115,48,40,'W')), place)
def test_tuples_are_good_for_representing_records(self):
locations = [
("Illuminati HQ", (38, 52, 15.56, 'N'), (77, 3, 21.46, 'W')),
("Stargate B", (41, 10, 43.92, 'N'), (1, 49, 34.29, 'W')),
]
locations.append(
("Cthulhu", (26, 40, 1, 'N'), (70, 45, 7, 'W'))
)
self.assertEqual('Cthulhu', locations[2][0])
self.assertEqual(15.56, locations[0][1][2])
| koans/koans/about_tuples.py | 2,413 | !/usr/bin/env python -*- coding: utf-8 -*- Note, assertMatch() uses regular expression pattern matching, so you don't have to copy the whole message. Tuples are less flexible than lists, but faster. Sometimes less confusing | 223 | en | 0.870872 |
# NLP written by GAMS Convert at 04/21/18 13:51:47
#
# Equation counts
# Total E G L N X C B
# 73 73 0 0 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc si
# Total cont binary integer sos1 sos2 scont sint
# 116 116 0 0 0 0 0 0
# FX 0 0 0 0 0 0 0 0
#
# Nonzero counts
# Total const NL DLL
# 576 128 448 0
#
# Reformulation has removed 1 variable and 1 equation
from pyomo.environ import *
model = m = ConcreteModel()
m.x2 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x3 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x4 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x5 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x6 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x7 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x8 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x9 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x10 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x11 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x12 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x13 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x14 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x15 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x16 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x17 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x18 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x19 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x20 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x21 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x22 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x23 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x24 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x25 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x26 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x27 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x28 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x29 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x30 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x31 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x32 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x33 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x34 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x35 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x36 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x37 = Var(within=Reals,bounds=(0,1000),initialize=100)
m.x38 = Var(within=Reals,bounds=(0,1000),initialize=100)
m.x39 = Var(within=Reals,bounds=(0,1000),initialize=100)
m.x40 = Var(within=Reals,bounds=(0,1000),initialize=100)
m.x41 = Var(within=Reals,bounds=(0,1000),initialize=100)
m.x42 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x43 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x44 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x45 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x46 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x47 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x48 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x49 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x50 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x51 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x52 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x53 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x54 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x55 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x56 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x57 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x58 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x59 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x60 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x61 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x62 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x63 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x64 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x65 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x66 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x67 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x68 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x69 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x70 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x71 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x72 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x73 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x74 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x75 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x76 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x77 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x78 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x79 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x80 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x81 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x82 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x83 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x84 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x85 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x86 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x87 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x88 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x89 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x90 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x91 = Var(within=Reals,bounds=(0,1000),initialize=50)
m.x92 = Var(within=Reals,bounds=(0,1000),initialize=100)
m.x93 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x94 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x95 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x96 = Var(within=Reals,bounds=(0,1),initialize=0.2)
m.x97 = Var(within=Reals,bounds=(0,10000),initialize=1)
m.x98 = Var(within=Reals,bounds=(0,10000),initialize=1)
m.x99 = Var(within=Reals,bounds=(0,10000),initialize=1)
m.x100 = Var(within=Reals,bounds=(0,10000),initialize=1)
m.x101 = Var(within=Reals,bounds=(0,10000),initialize=1)
m.x102 = Var(within=Reals,bounds=(300,800),initialize=400)
m.x103 = Var(within=Reals,bounds=(300,800),initialize=400)
m.x104 = Var(within=Reals,bounds=(300,800),initialize=400)
m.x105 = Var(within=Reals,bounds=(300,800),initialize=400)
m.x106 = Var(within=Reals,bounds=(300,800),initialize=400)
m.x107 = Var(within=Reals,bounds=(0,10000),initialize=0)
m.x108 = Var(within=Reals,bounds=(0,10000),initialize=0)
m.x109 = Var(within=Reals,bounds=(0,10000),initialize=0)
m.x110 = Var(within=Reals,bounds=(0,10000),initialize=0)
m.x111 = Var(within=Reals,bounds=(0,10000),initialize=0)
m.x112 = Var(within=Reals,bounds=(0,10000),initialize=0)
m.x113 = Var(within=Reals,bounds=(0,10000),initialize=0)
m.x114 = Var(within=Reals,bounds=(0,10000),initialize=0)
m.x115 = Var(within=Reals,bounds=(0,10000),initialize=0)
m.x116 = Var(within=Reals,bounds=(0,10000),initialize=0)
m.obj = Objective(expr= - 100*m.x95 + m.x97 + m.x98 + m.x99 + m.x100 + m.x101, sense=minimize)
m.c2 = Constraint(expr= - m.x2 - m.x3 - m.x4 - m.x5 - m.x6 == -50)
m.c3 = Constraint(expr= - m.x7 - m.x8 - m.x9 - m.x10 - m.x11 == -50)
m.c4 = Constraint(expr= - m.x2 - m.x7 + m.x12 - m.x62 - m.x67 - m.x72 - m.x77 - m.x82 == 0)
m.c5 = Constraint(expr= - m.x3 - m.x8 + m.x13 - m.x63 - m.x68 - m.x73 - m.x78 - m.x83 == 0)
m.c6 = Constraint(expr= - m.x4 - m.x9 + m.x14 - m.x64 - m.x69 - m.x74 - m.x79 - m.x84 == 0)
m.c7 = Constraint(expr= - m.x5 - m.x10 + m.x15 - m.x65 - m.x70 - m.x75 - m.x80 - m.x85 == 0)
m.c8 = Constraint(expr= - m.x6 - m.x11 + m.x16 - m.x66 - m.x71 - m.x76 - m.x81 - m.x86 == 0)
m.c9 = Constraint(expr=m.x17*m.x12 - (m.x42*m.x62 + m.x46*m.x67 + m.x50*m.x72 + m.x54*m.x77 + m.x58*m.x82) - m.x2 == 0)
m.c10 = Constraint(expr=m.x18*m.x12 - (m.x43*m.x62 + m.x47*m.x67 + m.x51*m.x72 + m.x55*m.x77 + m.x59*m.x82) - m.x7 == 0)
m.c11 = Constraint(expr=m.x19*m.x12 - (m.x44*m.x62 + m.x48*m.x67 + m.x52*m.x72 + m.x56*m.x77 + m.x60*m.x82) == 0)
m.c12 = Constraint(expr=m.x20*m.x12 - (m.x45*m.x62 + m.x49*m.x67 + m.x53*m.x72 + m.x57*m.x77 + m.x61*m.x82) == 0)
m.c13 = Constraint(expr=m.x21*m.x13 - (m.x42*m.x63 + m.x46*m.x68 + m.x50*m.x73 + m.x54*m.x78 + m.x58*m.x83) - m.x3 == 0)
m.c14 = Constraint(expr=m.x22*m.x13 - (m.x43*m.x63 + m.x47*m.x68 + m.x51*m.x73 + m.x55*m.x78 + m.x59*m.x83) - m.x8 == 0)
m.c15 = Constraint(expr=m.x23*m.x13 - (m.x44*m.x63 + m.x48*m.x68 + m.x52*m.x73 + m.x56*m.x78 + m.x60*m.x83) == 0)
m.c16 = Constraint(expr=m.x24*m.x13 - (m.x45*m.x63 + m.x49*m.x68 + m.x53*m.x73 + m.x57*m.x78 + m.x61*m.x83) == 0)
m.c17 = Constraint(expr=m.x25*m.x14 - (m.x42*m.x64 + m.x46*m.x69 + m.x50*m.x74 + m.x54*m.x79 + m.x58*m.x84) - m.x4 == 0)
m.c18 = Constraint(expr=m.x26*m.x14 - (m.x43*m.x64 + m.x47*m.x69 + m.x51*m.x74 + m.x55*m.x79 + m.x59*m.x84) - m.x9 == 0)
m.c19 = Constraint(expr=m.x27*m.x14 - (m.x44*m.x64 + m.x48*m.x69 + m.x52*m.x74 + m.x56*m.x79 + m.x60*m.x84) == 0)
m.c20 = Constraint(expr=m.x28*m.x14 - (m.x45*m.x64 + m.x49*m.x69 + m.x53*m.x74 + m.x57*m.x79 + m.x61*m.x84) == 0)
m.c21 = Constraint(expr=m.x29*m.x15 - (m.x42*m.x65 + m.x46*m.x70 + m.x50*m.x75 + m.x54*m.x80 + m.x58*m.x85) - m.x5 == 0)
m.c22 = Constraint(expr=m.x30*m.x15 - (m.x43*m.x65 + m.x47*m.x70 + m.x51*m.x75 + m.x55*m.x80 + m.x59*m.x85) - m.x10
== 0)
m.c23 = Constraint(expr=m.x31*m.x15 - (m.x44*m.x65 + m.x48*m.x70 + m.x52*m.x75 + m.x56*m.x80 + m.x60*m.x85) == 0)
m.c24 = Constraint(expr=m.x32*m.x15 - (m.x45*m.x65 + m.x49*m.x70 + m.x53*m.x75 + m.x57*m.x80 + m.x61*m.x85) == 0)
m.c25 = Constraint(expr=m.x33*m.x16 - (m.x42*m.x66 + m.x46*m.x71 + m.x50*m.x76 + m.x54*m.x81 + m.x58*m.x86) - m.x6 == 0)
m.c26 = Constraint(expr=m.x34*m.x16 - (m.x43*m.x66 + m.x47*m.x71 + m.x51*m.x76 + m.x55*m.x81 + m.x59*m.x86) - m.x11
== 0)
m.c27 = Constraint(expr=m.x35*m.x16 - (m.x44*m.x66 + m.x48*m.x71 + m.x52*m.x76 + m.x56*m.x81 + m.x60*m.x86) == 0)
m.c28 = Constraint(expr=m.x36*m.x16 - (m.x45*m.x66 + m.x49*m.x71 + m.x53*m.x76 + m.x57*m.x81 + m.x61*m.x86) == 0)
m.c29 = Constraint(expr= - m.x12 + m.x37 == 0)
m.c30 = Constraint(expr= - m.x13 + m.x38 == 0)
m.c31 = Constraint(expr= - m.x14 + m.x39 == 0)
m.c32 = Constraint(expr= - m.x15 + m.x40 == 0)
m.c33 = Constraint(expr= - m.x16 + m.x41 == 0)
m.c34 = Constraint(expr=m.x42*m.x37 - (m.x17*m.x12 + m.x97*(-m.x107 - m.x108)) == 0)
m.c35 = Constraint(expr=m.x43*m.x37 - (m.x18*m.x12 + m.x97*(-m.x107 - m.x108)) == 0)
m.c36 = Constraint(expr=m.x44*m.x37 - (m.x19*m.x12 + m.x97*m.x107) == 0)
m.c37 = Constraint(expr=m.x45*m.x37 - (m.x20*m.x12 + m.x97*m.x108) == 0)
m.c38 = Constraint(expr=m.x46*m.x38 - (m.x21*m.x13 + m.x98*(-m.x109 - m.x110)) == 0)
m.c39 = Constraint(expr=m.x47*m.x38 - (m.x22*m.x13 + m.x98*(-m.x109 - m.x110)) == 0)
m.c40 = Constraint(expr=m.x48*m.x38 - (m.x23*m.x13 + m.x98*m.x109) == 0)
m.c41 = Constraint(expr=m.x49*m.x38 - (m.x24*m.x13 + m.x98*m.x110) == 0)
m.c42 = Constraint(expr=m.x50*m.x39 - (m.x25*m.x14 + m.x99*(-m.x111 - m.x112)) == 0)
m.c43 = Constraint(expr=m.x51*m.x39 - (m.x26*m.x14 + m.x99*(-m.x111 - m.x112)) == 0)
m.c44 = Constraint(expr=m.x52*m.x39 - (m.x27*m.x14 + m.x99*m.x111) == 0)
m.c45 = Constraint(expr=m.x53*m.x39 - (m.x28*m.x14 + m.x99*m.x112) == 0)
m.c46 = Constraint(expr=m.x54*m.x40 - (m.x29*m.x15 + m.x100*(-m.x113 - m.x114)) == 0)
m.c47 = Constraint(expr=m.x55*m.x40 - (m.x30*m.x15 + m.x100*(-m.x113 - m.x114)) == 0)
m.c48 = Constraint(expr=m.x56*m.x40 - (m.x31*m.x15 + m.x100*m.x113) == 0)
m.c49 = Constraint(expr=m.x57*m.x40 - (m.x32*m.x15 + m.x100*m.x114) == 0)
m.c50 = Constraint(expr=m.x58*m.x41 - (m.x33*m.x16 + m.x101*(-m.x115 - m.x116)) == 0)
m.c51 = Constraint(expr=m.x59*m.x41 - (m.x34*m.x16 + m.x101*(-m.x115 - m.x116)) == 0)
m.c52 = Constraint(expr=m.x60*m.x41 - (m.x35*m.x16 + m.x101*m.x115) == 0)
m.c53 = Constraint(expr=m.x61*m.x41 - (m.x36*m.x16 + m.x101*m.x116) == 0)
m.c54 = Constraint(expr=-54000000*exp(-9631.60543532964/m.x102)*m.x42*m.x43**0.3 + m.x107 == 0)
m.c55 = Constraint(expr=-54000000*exp(-9631.60543532964/m.x103)*m.x46*m.x47**0.3 + m.x109 == 0)
m.c56 = Constraint(expr=-54000000*exp(-9631.60543532964/m.x104)*m.x50*m.x51**0.3 + m.x111 == 0)
m.c57 = Constraint(expr=-54000000*exp(-9631.60543532964/m.x105)*m.x54*m.x55**0.3 + m.x113 == 0)
m.c58 = Constraint(expr=-54000000*exp(-9631.60543532964/m.x106)*m.x58*m.x59**0.3 + m.x115 == 0)
m.c59 = Constraint(expr=-360000*exp(-4815.80271766482/m.x102)*m.x42**0.5*m.x43**1.8 + m.x108 == 0)
m.c60 = Constraint(expr=-360000*exp(-4815.80271766482/m.x103)*m.x46**0.5*m.x47**1.8 + m.x110 == 0)
m.c61 = Constraint(expr=-360000*exp(-4815.80271766482/m.x104)*m.x50**0.5*m.x51**1.8 + m.x112 == 0)
m.c62 = Constraint(expr=-360000*exp(-4815.80271766482/m.x105)*m.x54**0.5*m.x55**1.8 + m.x114 == 0)
m.c63 = Constraint(expr=-360000*exp(-4815.80271766482/m.x106)*m.x58**0.5*m.x59**1.8 + m.x116 == 0)
m.c64 = Constraint(expr= m.x37 - m.x62 - m.x63 - m.x64 - m.x65 - m.x66 - m.x87 == 0)
m.c65 = Constraint(expr= m.x38 - m.x67 - m.x68 - m.x69 - m.x70 - m.x71 - m.x88 == 0)
m.c66 = Constraint(expr= m.x39 - m.x72 - m.x73 - m.x74 - m.x75 - m.x76 - m.x89 == 0)
m.c67 = Constraint(expr= m.x40 - m.x77 - m.x78 - m.x79 - m.x80 - m.x81 - m.x90 == 0)
m.c68 = Constraint(expr= m.x41 - m.x82 - m.x83 - m.x84 - m.x85 - m.x86 - m.x91 == 0)
m.c69 = Constraint(expr= - m.x87 - m.x88 - m.x89 - m.x90 - m.x91 + m.x92 == 0)
m.c70 = Constraint(expr=m.x92*m.x93 - (m.x87*m.x42 + m.x88*m.x46 + m.x89*m.x50 + m.x90*m.x54 + m.x91*m.x58) == 0)
m.c71 = Constraint(expr=m.x92*m.x94 - (m.x87*m.x43 + m.x88*m.x47 + m.x89*m.x51 + m.x90*m.x55 + m.x91*m.x59) == 0)
m.c72 = Constraint(expr=m.x92*m.x95 - (m.x87*m.x44 + m.x88*m.x48 + m.x89*m.x52 + m.x90*m.x56 + m.x91*m.x60) == 0)
m.c73 = Constraint(expr=m.x92*m.x96 - (m.x87*m.x45 + m.x88*m.x49 + m.x89*m.x53 + m.x90*m.x57 + m.x91*m.x61) == 0)
| tests/examples/minlplib/ex8_3_13.py | 14,087 | NLP written by GAMS Convert at 04/21/18 13:51:47 Equation counts Total E G L N X C B 73 73 0 0 0 0 0 0 Variable counts x b i s1s s2s sc si Total cont binary integer sos1 sos2 scont sint 116 116 0 0 0 0 0 0 FX 0 0 0 0 0 0 0 0 Nonzero counts Total const NL DLL 576 128 448 0 Reformulation has removed 1 variable and 1 equation | 678 | en | 0.714293 |
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Hashing function to make a stochastic classifier deterministic."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import hashlib
from absl import app
import numpy as np
def compute_hash(features, hash_matrix, hash_vector):
"""Compute hash values for features using the hash function (A * x + c) mod 2.
Args:
features: NumPy float array of shape (n, d), the features to hash.
hash_matrix: NumPy float array of shape (num_feature_bits, num_hash_bits),
a random matrix A to construct the hash function.
hash_vector: NumPy float array of shape (1, num_hash_bits),
a random vector c to construct the hash function.
Returns:
NumPy float array of shape (n, 1) containing the hashed values in [0, 1].
"""
# Helper function to convert an int array to a bit string array.
def convert_int_to_bin(x, dimension):
# Converts x to an array of bit strings of size dimension.
return '{:b}'.format(x).zfill(dimension)[-dimension:]
convert_int_to_bin = np.vectorize(convert_int_to_bin)
# Helper function to convert a bit string array to an into array.
convert_bin_to_int = np.vectorize(lambda x: int(x, 2))
# Number of features and hash bits.
num_features = features.shape[0]
num_feature_bits, num_hash_bits = hash_matrix.shape
# Concatenate features and apply MD5 hash to get a fixed length encoding.
feature_sum_str = [''.join(x) for x in features.astype('str')]
feature_sum_hex = [hashlib.md5(s).hexdigest() for s in feature_sum_str]
feature_sum_int = [int(h, 16) for h in feature_sum_hex]
# Binarize features
feature_sum_bin = convert_int_to_bin(
feature_sum_int, dimension=num_feature_bits)
feature_sum_bin_matrix = np.array(
[[int(c) for c in s] for s in feature_sum_bin])
# Compute hash (Ax + c) mod 2.
feature_hashed = (
np.dot(feature_sum_bin_matrix, hash_matrix) +
np.repeat(hash_vector, repeats=num_features, axis=0))
feature_hashed_bits = np.mod(feature_hashed, 2)
# Convert hash to bit string.
feature_hashed_bit_char = convert_int_to_bin(feature_hashed_bits, 1)
feature_hashed_bit_str = [''.join(s) for s in feature_hashed_bit_char]
feature_hashed_int = convert_bin_to_int(feature_hashed_bit_str)
hashed_val = feature_hashed_int * 1. / 2 ** num_hash_bits
# Return normalized hashed values in [0, 1].
return hashed_val.reshape(-1, 1)
def main(argv):
"""Example usage of hash function."""
del argv
num_feature_bits = 128
num_hash_bits = 32
# Random hash matrix and vector to construct hash function.
hash_matrix = (np.random.rand(
num_feature_bits, num_hash_bits) > 0.5).astype('int')
hash_vector = (np.random.rand(1, num_hash_bits) > 0.5).astype('int')
# Generate random features.
num_examples = 10
dimension = 4
features = np.random.normal(size=(num_examples, dimension)).astype(np.float32)
# Compute hash.
hash_val = compute_hash(features, hash_matrix, hash_vector)
print('Feature matrix:')
print(features)
print('\nHashed values:')
print(hash_val)
if __name__ == '__main__':
app.run(main)
| stochastic_to_deterministic/hashing.py | 3,742 | Compute hash values for features using the hash function (A * x + c) mod 2.
Args:
features: NumPy float array of shape (n, d), the features to hash.
hash_matrix: NumPy float array of shape (num_feature_bits, num_hash_bits),
a random matrix A to construct the hash function.
hash_vector: NumPy float array of shape (1, num_hash_bits),
a random vector c to construct the hash function.
Returns:
NumPy float array of shape (n, 1) containing the hashed values in [0, 1].
Example usage of hash function.
Hashing function to make a stochastic classifier deterministic.
coding=utf-8 Copyright 2020 The Google Research Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Helper function to convert an int array to a bit string array. Converts x to an array of bit strings of size dimension. Helper function to convert a bit string array to an into array. Number of features and hash bits. Concatenate features and apply MD5 hash to get a fixed length encoding. Binarize features Compute hash (Ax + c) mod 2. Convert hash to bit string. Return normalized hashed values in [0, 1]. Random hash matrix and vector to construct hash function. Generate random features. Compute hash. | 1,667 | en | 0.762199 |
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
from openvino.tools.mo.front.common.partial_infer.elemental import copy_shape_infer
from openvino.tools.mo.graph.graph import Graph
from openvino.tools.mo.ops.op import Op
class PReLU(Op):
op = 'PReLU'
enabled = True
def __init__(self, graph: Graph, attrs: dict):
super().__init__(graph, {
'op': self.op,
'type': self.op,
'version': 'opset1',
'infer': self.infer,
'force_precision_in_ports': {1: 'float'},
'in_ports_count': 2,
'out_ports_count': 1,
}, attrs)
@staticmethod
def infer(node):
if len(node.in_nodes()) == 2:
gamma_vector = node.in_node(1)
if np.all(gamma_vector.shape == [1]):
node['channel_shared'] = 1
else:
node['channel_shared'] = 0
node.in_node(1)['correct_data_type'] = True
copy_shape_infer(node)
| tools/mo/openvino/tools/mo/ops/prelu.py | 1,043 | Copyright (C) 2018-2022 Intel Corporation SPDX-License-Identifier: Apache-2.0 | 77 | en | 0.237368 |
import assemblyline_client
import mocks
import mock
from base64 import b64decode
def test_bad_cert():
"""Make sure that the client detects that the test cert is self signed."""
with mocks.Server() as server:
try:
assemblyline_client.get_client(server.address)
assert False
except assemblyline_client.ClientError as ce:
assert 'CERTIFICATE_VERIFY_FAILED' in str(ce) or 'certificate verify failed' in str(ce)
def test_noauth():
"""The test server should let us login with no authentication."""
with mocks.Server() as server:
assemblyline_client.get_client(server.address, verify=False)
assert len(server.logins) == 1
def test_noauth_submit(mocker):
"""Submit a file and ensure that the same file is unpacked."""
with mocks.Server() as server:
client = assemblyline_client.get_client(server.address, verify=False)
submits = server.submits
# Submit a file with contents
client.submit(path='readme.txt', contents=b'abc123')
assert len(submits) == 1
assert b64decode(submits[0]['binary']) == b'abc123'
assert submits[0]['name'] == 'readme.txt'
submits.pop()
# Submit a file from a file
mocker.patch('os.path.exists', return_value=True)
mocker.patch('assemblyline_client.v3_client.open', mock.mock_open(read_data=b'abc123'), create=True)
client.submit(path='readme.txt')
assert len(submits) == 1
assert b64decode(submits[0]['binary']) == b'abc123'
assert submits[0]['name'] == 'readme.txt'
submits.pop()
def test_encrypt_password_auth():
"""Send an encryped password and decrypt it."""
with mocks.Server() as server:
assemblyline_client.get_client(server.address, verify=False, auth=('username', 'password'))
assert len(server.logins) == 1
assert server.logins[0]['user'] == 'username'
assert server.logins[0]['password'] != 'password'
assert server.private_key.decrypt(b64decode(server.logins[0]['password']), 'ERROR') == b'password'
def test_encrypt_apikey_auth():
"""Send an encryped apikey and decrypt it."""
with mocks.Server() as server:
assemblyline_client.get_client(server.address, verify=False, apikey=('username', 'ANAPIKEY'))
assert len(server.logins) == 1
assert server.logins[0]['user'] == 'username'
assert server.logins[0]['apikey'] != 'ANAPIKEY'
assert server.private_key.decrypt(b64decode(server.logins[0]['apikey']), 'ERROR') == b'ANAPIKEY'
| test/test_v3_client.py | 2,584 | Make sure that the client detects that the test cert is self signed.
Send an encryped apikey and decrypt it.
Send an encryped password and decrypt it.
The test server should let us login with no authentication.
Submit a file and ensure that the same file is unpacked.
Submit a file with contents Submit a file from a file | 323 | en | 0.954281 |
from datetime import datetime, timedelta
from typing import List, Optional
from sqlalchemy import or_
from dispatch.plugin import service as plugin_service
from dispatch.event import service as event_service
from dispatch.incident import flows as incident_flows
from dispatch.incident.flows import incident_service
from dispatch.ticket import service as ticket_service
from .models import Task, TaskStatus, TaskUpdate, TaskCreate
def get(*, db_session, task_id: int) -> Optional[Task]:
"""Get a single task by ID."""
return db_session.query(Task).filter(Task.id == task_id).first()
def get_by_resource_id(*, db_session, resource_id: str) -> Optional[Task]:
"""Get a single task by resource id."""
return db_session.query(Task).filter(Task.resource_id == resource_id).first()
def get_all(*, db_session) -> List[Optional[Task]]:
"""Return all tasks."""
return db_session.query(Task)
def get_all_by_incident_id(*, db_session, incident_id: int) -> List[Optional[Task]]:
"""Get all tasks by incident id."""
return db_session.query(Task).filter(Task.incident_id == incident_id)
def get_all_by_incident_id_and_status(
*, db_session, incident_id: int, status: str
) -> List[Optional[Task]]:
"""Get all tasks by incident id and status."""
return (
db_session.query(Task).filter(Task.incident_id == incident_id).filter(Task.status == status)
)
def get_overdue_tasks(*, db_session) -> List[Optional[Task]]:
"""Returns all tasks that have not been resolved and are past due date."""
# TODO ensure that we don't send reminders more than their interval
return (
db_session.query(Task)
.filter(Task.status == TaskStatus.open)
.filter(Task.reminders == True) # noqa
.filter(Task.resolve_by < datetime.utcnow())
.filter(
or_(
Task.last_reminder_at + timedelta(days=1)
< datetime.utcnow(), # daily reminders after due date.
Task.last_reminder_at == None,
)
)
.all()
)
def create(*, db_session, task_in: TaskCreate) -> Task:
"""Create a new task."""
incident = incident_service.get(db_session=db_session, incident_id=task_in.incident.id)
tickets = [
ticket_service.get_or_create_by_weblink(
db_session=db_session, weblink=t.weblink, resource_type="task-ticket"
)
for t in task_in.tickets
]
assignees = []
for i in task_in.assignees:
assignee = incident_flows.incident_add_or_reactivate_participant_flow(
db_session=db_session,
incident_id=incident.id,
user_email=i.individual.email,
)
# due to the freeform nature of task assignment, we can sometimes pick up other emails
# e.g. a google group that we cannont resolve to an individual assignee
if assignee:
assignees.append(assignee)
creator_email = None
if not task_in.creator:
creator_email = task_in.owner.individual.email
else:
creator_email = task_in.creator.individual.email
# add creator as a participant if they are not one already
creator = incident_flows.incident_add_or_reactivate_participant_flow(
db_session=db_session,
incident_id=incident.id,
user_email=creator_email,
)
# if we cannot find any assignees, the creator becomes the default assignee
if not assignees:
assignees.append(creator)
# we add owner as a participant if they are not one already
if task_in.owner:
owner = incident_flows.incident_add_or_reactivate_participant_flow(
db_session=db_session,
incident_id=incident.id,
user_email=task_in.owner.individual.email,
)
else:
owner = incident.commander
task = Task(
**task_in.dict(exclude={"assignees", "owner", "incident", "creator", "tickets"}),
creator=creator,
owner=owner,
assignees=assignees,
incident=incident,
tickets=tickets,
)
event_service.log(
db_session=db_session,
source="Dispatch Core App",
description="New incident task created",
details={"weblink": task.weblink},
incident_id=incident.id,
)
db_session.add(task)
db_session.commit()
return task
def update(*, db_session, task: Task, task_in: TaskUpdate, sync_external: bool = True) -> Task:
"""Update an existing task."""
# ensure we add assignee as participant if they are not one already
assignees = []
for i in task_in.assignees:
assignees.append(
incident_flows.incident_add_or_reactivate_participant_flow(
db_session=db_session,
incident_id=task.incident.id,
user_email=i.individual.email,
)
)
task.assignees = assignees
# we add owner as a participant if they are not one already
if task_in.owner:
task.owner = incident_flows.incident_add_or_reactivate_participant_flow(
db_session=db_session,
incident_id=task.incident.id,
user_email=task_in.owner.individual.email,
)
update_data = task_in.dict(
skip_defaults=True, exclude={"assignees", "owner", "creator", "incident", "tickets"}
)
for field in update_data.keys():
setattr(task, field, update_data[field])
# if we have an external task plugin enabled, attempt to update the external resource as well
# we don't currently have a good way to get the correct file_id (we don't store a task <-> relationship)
# lets try in both the incident doc and PIR doc
drive_task_plugin = plugin_service.get_active(db_session=db_session, plugin_type="task")
if drive_task_plugin:
if sync_external:
try:
if task.incident.incident_document:
file_id = task.incident.incident_document.resource_id
drive_task_plugin.instance.update(
file_id, task.resource_id, resolved=task.status
)
except Exception:
if task.incident.incident_review_document:
file_id = task.incident.incident_review_document.resource_id
drive_task_plugin.instance.update(
file_id, task.resource_id, resolved=task.status
)
db_session.add(task)
db_session.commit()
return task
def delete(*, db_session, task_id: int):
"""Delete an existing task."""
task = db_session.query(Task).filter(Task.id == task_id).first()
db_session.delete(task)
db_session.commit()
| src/dispatch/task/service.py | 6,715 | Create a new task.
Delete an existing task.
Get a single task by ID.
Return all tasks.
Get all tasks by incident id.
Get all tasks by incident id and status.
Get a single task by resource id.
Returns all tasks that have not been resolved and are past due date.
Update an existing task.
TODO ensure that we don't send reminders more than their interval noqa daily reminders after due date. due to the freeform nature of task assignment, we can sometimes pick up other emails e.g. a google group that we cannont resolve to an individual assignee add creator as a participant if they are not one already if we cannot find any assignees, the creator becomes the default assignee we add owner as a participant if they are not one already ensure we add assignee as participant if they are not one already we add owner as a participant if they are not one already if we have an external task plugin enabled, attempt to update the external resource as well we don't currently have a good way to get the correct file_id (we don't store a task <-> relationship) lets try in both the incident doc and PIR doc | 1,099 | en | 0.938454 |
import logging
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
from sentry_sdk.integrations.logging import LoggingIntegration
from sentry_sdk.integrations.celery import CeleryIntegration
from .base import * # noqa
from .base import env
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = env("DJANGO_SECRET_KEY")
# https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=["veritas.ke"])
# DATABASES
# ------------------------------------------------------------------------------
DATABASES["default"] = env.db("DATABASE_URL") # noqa F405
DATABASES["default"]["ATOMIC_REQUESTS"] = True # noqa F405
DATABASES["default"]["CONN_MAX_AGE"] = env.int("CONN_MAX_AGE", default=60) # noqa F405
# CACHES
# ------------------------------------------------------------------------------
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": env("REDIS_URL"),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
# Mimicing memcache behavior.
# http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior
"IGNORE_EXCEPTIONS": True,
},
}
}
# SECURITY
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-proxy-ssl-header
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-ssl-redirect
SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True)
# https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-secure
SESSION_COOKIE_SECURE = True
# https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-secure
CSRF_COOKIE_SECURE = True
# https://docs.djangoproject.com/en/dev/topics/security/#ssl-https
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-seconds
# TODO: set this to 60 seconds first and then to 518400 once you prove the former works
SECURE_HSTS_SECONDS = 60
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-include-subdomains
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(
"DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True
)
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-preload
SECURE_HSTS_PRELOAD = env.bool("DJANGO_SECURE_HSTS_PRELOAD", default=True)
# https://docs.djangoproject.com/en/dev/ref/middleware/#x-content-type-options-nosniff
SECURE_CONTENT_TYPE_NOSNIFF = env.bool(
"DJANGO_SECURE_CONTENT_TYPE_NOSNIFF", default=True
)
# STORAGES
# ------------------------------------------------------------------------------
# https://django-storages.readthedocs.io/en/latest/#installation
INSTALLED_APPS += ["storages"] # noqa F405
# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings
AWS_ACCESS_KEY_ID = env("DJANGO_AWS_ACCESS_KEY_ID")
# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings
AWS_SECRET_ACCESS_KEY = env("DJANGO_AWS_SECRET_ACCESS_KEY")
# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings
AWS_STORAGE_BUCKET_NAME = env("DJANGO_AWS_STORAGE_BUCKET_NAME")
# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings
AWS_QUERYSTRING_AUTH = False
# DO NOT change these unless you know what you're doing.
_AWS_EXPIRY = 60 * 60 * 24 * 7
# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings
AWS_DEFAULT_ACL = None
# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings
AWS_S3_REGION_NAME = env("DJANGO_AWS_S3_REGION_NAME", default=None)
AWS_S3_ENDPOINT_URL = env("AWS_S3_ENDPOINT_URL")
# STATIC
# ------------------------
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
# MEDIA
# ------------------------------------------------------------------------------
MEDIAFILES_STORAGE="storages.backends.s3boto3.S3Boto3Storage"
# region http://stackoverflow.com/questions/10390244/
# Full-fledge class: https://stackoverflow.com/a/18046120/104731
from storages.backends.s3boto3 import S3Boto3Storage # noqa E402
class StaticRootS3Boto3Storage(S3Boto3Storage):
location = "static"
default_acl = "public-read"
class MediaRootS3Boto3Storage(S3Boto3Storage):
location = "media"
file_overwrite = False
# endregion
DEFAULT_FILE_STORAGE = "config.settings.production.MediaRootS3Boto3Storage"
MEDIA_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/media/"
# TEMPLATES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#templates
TEMPLATES[0]["OPTIONS"]["loaders"] = [ # noqa F405
(
"django.template.loaders.cached.Loader",
[
"django.template.loaders.filesystem.Loader",
"django.template.loaders.app_directories.Loader",
],
)
]
# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#default-from-email
DEFAULT_FROM_EMAIL = env(
"DJANGO_DEFAULT_FROM_EMAIL", default="Veritas <noreply@veritas.ke>"
)
# https://docs.djangoproject.com/en/dev/ref/settings/#server-email
SERVER_EMAIL = env("DJANGO_SERVER_EMAIL", default=DEFAULT_FROM_EMAIL)
# https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix
EMAIL_SUBJECT_PREFIX = env(
"DJANGO_EMAIL_SUBJECT_PREFIX", default="[Veritas]"
)
# ADMIN
# ------------------------------------------------------------------------------
# Django Admin URL regex.
ADMIN_URL = env("DJANGO_ADMIN_URL")
# Anymail (Mailgun)
# ------------------------------------------------------------------------------
# https://anymail.readthedocs.io/en/stable/installation/#installing-anymail
INSTALLED_APPS += ["anymail"] # noqa F405
EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend"
# https://anymail.readthedocs.io/en/stable/installation/#anymail-settings-reference
ANYMAIL = {
"MAILGUN_API_KEY": env("MAILGUN_API_KEY"),
"MAILGUN_SENDER_DOMAIN": env("MAILGUN_DOMAIN"),
"MAILGUN_API_URL": env("MAILGUN_API_URL", default="https://api.mailgun.net/v3"),
}
# WhiteNoise
# ------------------------------------------------------------------------------
# http://whitenoise.evans.io/en/latest/django.html#enable-whitenoise
MIDDLEWARE.insert(1, "whitenoise.middleware.WhiteNoiseMiddleware") # noqa F405
# LOGGING
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#logging
# See https://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
"version": 1,
"disable_existing_loggers": True,
"formatters": {
"verbose": {
"format": "%(levelname)s %(asctime)s %(module)s "
"%(process)d %(thread)d %(message)s"
}
},
"handlers": {
"console": {
"level": "DEBUG",
"class": "logging.StreamHandler",
"formatter": "verbose",
}
},
"root": {"level": "INFO", "handlers": ["console"]},
"loggers": {
"django.db.backends": {
"level": "ERROR",
"handlers": ["console"],
"propagate": False,
},
# Errors logged by the SDK itself
"sentry_sdk": {"level": "ERROR", "handlers": ["console"], "propagate": False},
"django.security.DisallowedHost": {
"level": "ERROR",
"handlers": ["console"],
"propagate": False,
},
},
}
# Sentry
# ------------------------------------------------------------------------------
SENTRY_DSN = env("SENTRY_DSN")
SENTRY_LOG_LEVEL = env.int("DJANGO_SENTRY_LOG_LEVEL", logging.INFO)
sentry_logging = LoggingIntegration(
level=SENTRY_LOG_LEVEL, # Capture info and above as breadcrumbs
event_level=logging.ERROR, # Send errors as events
)
sentry_sdk.init(
dsn=SENTRY_DSN,
integrations=[sentry_logging, DjangoIntegration(), CeleryIntegration()],
)
# Your stuff...
# ------------------------------------------------------------------------------
| config/settings/production.py | 8,558 | noqa GENERAL ------------------------------------------------------------------------------ https://docs.djangoproject.com/en/dev/ref/settings/secret-key https://docs.djangoproject.com/en/dev/ref/settings/allowed-hosts DATABASES ------------------------------------------------------------------------------ noqa F405 noqa F405 noqa F405 CACHES ------------------------------------------------------------------------------ Mimicing memcache behavior. http://niwinz.github.io/django-redis/latest/_memcached_exceptions_behavior SECURITY ------------------------------------------------------------------------------ https://docs.djangoproject.com/en/dev/ref/settings/secure-proxy-ssl-header https://docs.djangoproject.com/en/dev/ref/settings/secure-ssl-redirect https://docs.djangoproject.com/en/dev/ref/settings/session-cookie-secure https://docs.djangoproject.com/en/dev/ref/settings/csrf-cookie-secure https://docs.djangoproject.com/en/dev/topics/security/ssl-https https://docs.djangoproject.com/en/dev/ref/settings/secure-hsts-seconds TODO: set this to 60 seconds first and then to 518400 once you prove the former works https://docs.djangoproject.com/en/dev/ref/settings/secure-hsts-include-subdomains https://docs.djangoproject.com/en/dev/ref/settings/secure-hsts-preload https://docs.djangoproject.com/en/dev/ref/middleware/x-content-type-options-nosniff STORAGES ------------------------------------------------------------------------------ https://django-storages.readthedocs.io/en/latest/installation noqa F405 https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.htmlsettings https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.htmlsettings https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.htmlsettings https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.htmlsettings DO NOT change these unless you know what you're doing. https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.htmlsettings https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.htmlsettings https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.htmlsettings STATIC ------------------------ MEDIA ------------------------------------------------------------------------------ region http://stackoverflow.com/questions/10390244/ Full-fledge class: https://stackoverflow.com/a/18046120/104731 noqa E402 endregion TEMPLATES ------------------------------------------------------------------------------ https://docs.djangoproject.com/en/dev/ref/settings/templates noqa F405 EMAIL ------------------------------------------------------------------------------ https://docs.djangoproject.com/en/dev/ref/settings/default-from-email https://docs.djangoproject.com/en/dev/ref/settings/server-email https://docs.djangoproject.com/en/dev/ref/settings/email-subject-prefix ADMIN ------------------------------------------------------------------------------ Django Admin URL regex. Anymail (Mailgun) ------------------------------------------------------------------------------ https://anymail.readthedocs.io/en/stable/installation/installing-anymail noqa F405 https://anymail.readthedocs.io/en/stable/installation/anymail-settings-reference WhiteNoise ------------------------------------------------------------------------------ http://whitenoise.evans.io/en/latest/django.htmlenable-whitenoise noqa F405 LOGGING ------------------------------------------------------------------------------ https://docs.djangoproject.com/en/dev/ref/settings/logging See https://docs.djangoproject.com/en/dev/topics/logging for more details on how to customize your logging configuration. Errors logged by the SDK itself Sentry ------------------------------------------------------------------------------ Capture info and above as breadcrumbs Send errors as events Your stuff... ------------------------------------------------------------------------------ | 3,922 | en | 0.501514 |
#!/usr/bin/env python3
import boto3
s3_client = boto3.client('s3')
raw_response = s3_client.list_buckets()
for bucket in raw_response['Buckets']:
print(bucket['Name'])
| labs/lab2.py | 172 | !/usr/bin/env python3 | 21 | fr | 0.448822 |
# -*- coding: utf-8 -*-
import os
import sys
import datetime
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from django.conf import settings
from app1.models import Thing
class Command(BaseCommand):
args = '<id name>'
help = 'create or update thing model.'
use_settings = 'settings'
def handle(self, *args, **options):
"""
finished when raise CommandError, exit code = 1.
other exit code = 0
"""
_retcode = 1
_dbname = 'default'
try:
print('settings.ENV_MODE = %s' % (settings.ENV_MODE))
print('settings.DATABASES = %s' % (settings.DATABASES))
_id = int(args[0])
_name = args[1]
print('id: %s, name:%s' % (_id, _name))
qs = Thing.objects.filter(id=_id)
_nowdt = timezone.now()
if 0 < len(qs):
print('do update.')
_r = qs[0]
# _r.id
_r.name = _name
# _r.create_at
_r.update_at = _nowdt
_r.save(using=_dbname)
else:
print('do insert.')
if _id < 1:
_id = None
_t = Thing(
id=_id,
name=_name,
create_at=_nowdt,
update_at=_nowdt)
_t.save(using=_dbname)
except:
print('EXCEPT: %s(%s)' % (sys.exc_info()[0], sys.exc_info()[1]))
print('finished(ng)')
raise CommandError('ng')
# raise CommandError('ok')
print('finished(ok)')
sys.exit(0)
| python-django/djmultidb/app1/management/commands/set_thing.py | 1,803 | finished when raise CommandError, exit code = 1.
other exit code = 0
-*- coding: utf-8 -*- _r.id _r.create_at raise CommandError('ok') | 136 | en | 0.536392 |
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.utils import timezone
# Create your models here.
class Article(models.Model):
title=models.CharField(max_length=100)
slug=models.SlugField(blank=True)
body= models.TextField()
date= models.DateTimeField(default=timezone.now)
thumb=models.ImageField(default='default.jpg',blank=True)
Author= models.ForeignKey(User,default=None,on_delete=models.CASCADE)
#Thumbnails
def __str__(self):
return self.title
def snippets(self):
return self.body[:80] + '...'
| articles/models.py | 668 | Create your models here.Thumbnails | 34 | en | 0.557331 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.dialogs.memory import scope_path
from .memory_scope import MemoryScope
class SettingsMemoryScope(MemoryScope):
def __init__(self):
super().__init__(scope_path.SETTINGS)
self._empty_settings = {}
self.include_in_snapshot = False
def get_memory(self, dialog_context: "DialogContext") -> object:
if not dialog_context:
raise TypeError(f"Expecting: DialogContext, but received None")
settings: dict = dialog_context.context.turn_state.get(
scope_path.SETTINGS, None
)
if not settings:
settings = self._empty_settings
return settings
def set_memory(self, dialog_context: "DialogContext", memory: object):
raise Exception(
f"{self.__class__.__name__}.set_memory not supported (read only)"
)
| libraries/botbuilder-dialogs/botbuilder/dialogs/memory/scopes/settings_memory_scope.py | 944 | Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. | 89 | en | 0.69103 |
# coding: utf-8
"""
FlashArray REST API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.11
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re
import six
import typing
from ....properties import Property
if typing.TYPE_CHECKING:
from pypureclient.flasharray.FA_2_11 import models
class PortCommon(object):
"""
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 = {
'iqn': 'str',
'nqn': 'str',
'portal': 'str',
'wwn': 'str'
}
attribute_map = {
'iqn': 'iqn',
'nqn': 'nqn',
'portal': 'portal',
'wwn': 'wwn'
}
required_args = {
}
def __init__(
self,
iqn=None, # type: str
nqn=None, # type: str
portal=None, # type: str
wwn=None, # type: str
):
"""
Keyword args:
iqn (str): The iSCSI Qualified Name (or `null` if target is not iSCSI).
nqn (str): NVMe Qualified Name (or `null` if target is not NVMeoF).
portal (str): IP and port number (or `null` if target is not iSCSI).
wwn (str): Fibre Channel World Wide Name (or `null` if target is not Fibre Channel).
"""
if iqn is not None:
self.iqn = iqn
if nqn is not None:
self.nqn = nqn
if portal is not None:
self.portal = portal
if wwn is not None:
self.wwn = wwn
def __setattr__(self, key, value):
if key not in self.attribute_map:
raise KeyError("Invalid key `{}` for `PortCommon`".format(key))
self.__dict__[key] = value
def __getattribute__(self, item):
value = object.__getattribute__(self, item)
if isinstance(value, Property):
raise AttributeError
else:
return value
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
if hasattr(self, attr):
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(PortCommon, 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, PortCommon):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| pypureclient/flasharray/FA_2_11/models/port_common.py | 3,769 | 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.
Returns true if both objects are equal
Keyword args:
iqn (str): The iSCSI Qualified Name (or `null` if target is not iSCSI).
nqn (str): NVMe Qualified Name (or `null` if target is not NVMeoF).
portal (str): IP and port number (or `null` if target is not iSCSI).
wwn (str): Fibre Channel World Wide Name (or `null` if target is not Fibre Channel).
Returns true if both objects are not equal
For `print` and `pprint`
Returns the model properties as a dict
Returns the string representation of the model
FlashArray REST API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.11
Generated by: https://github.com/swagger-api/swagger-codegen.git
coding: utf-8 type: str type: str type: str type: str | 1,023 | en | 0.652044 |
# Generated by Django 3.0.6 on 2020-06-22 13:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('src', '0010_temporaryuser'),
]
operations = [
migrations.RemoveField(
model_name='admin',
name='username',
),
migrations.AlterField(
model_name='temporaryuser',
name='mail',
field=models.EmailField(max_length=320),
),
]
| visitor_manage/src/migrations/0011_auto_20200622_1909.py | 488 | Generated by Django 3.0.6 on 2020-06-22 13:39 | 45 | en | 0.64577 |
# # Python Week-7 Day-42
# Python Classes and Objects 2
print(" -- Let us create a method in the Person class --")
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name )
p1 = Person("John", "36")
p1.myfunc()
print("----")
class Car:
def __init__(self, brand, price):
self.brand = brand
self.price = price
def myfunc(self):
print("Car brand Is: " + self.brand, "\nCar Price Is: " + self.price)
p1 = Car("Kia", "10000")
p1.myfunc()
print("\n -- Modify Object Properties -- ")
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.age = 40
print(p1.age)
print("\n -- Delete Object Properties --")
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
try :
del p1.age
print(p1.age)
except AttributeError as err:
print("Properties 'age' not Exist")
print("\n -- Delete Objects --")
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
del p1
try :
print(p1.age)
except NameError as err:
print("p1 is not Defined")
| Week-7/Day-42.py | 1,501 | Python Week-7 Day-42 Python Classes and Objects 2 | 49 | en | 0.745573 |
"""
@brief Pure python implementation of the Bayesian Blocks algorithm
described by Jackson, Scargle et al. 2005, IEEE Signal Processing
Letters, 12, 105. (http://arxiv.org/abs/math/0309285)
@author J. Chiang <jchiang@slac.stanford.edu>
"""
#
# $Id: BayesianBlocks_python.py,v 1.1.1.1 2011/09/03 00:55:59 jchiang Exp $
#
import copy
import numpy as num
def gammln(xx):
cof = [76.18009172947146, -86.50532032941677,
24.01409824083091, -1.231739572450155,
0.1208650973866179e-2, -0.5395239384953e-5]
y = xx
x = xx
tmp = x + 5.5
tmp -= (x + 0.5)*num.log(tmp)
ser = 1.000000000190015
for j in range(6):
y += 1
ser += cof[j]/y
return -tmp + num.log(2.5066282746310005*ser/x)
class BayesianBlocks(object):
"""
Unbinned mode:
>>> bb = BayesianBlocks(arrival_times)
Binned:
>>> bb = BayesianBlocks(bin_content, bin_sizes, start_time)
Point measurements:
>>> bb = BayesianBlocks(time, flux, errors)
Obtaining the piecewise constant light curve:
>>> time, rate = bb.globalOpt(ncp_prior=1)
"""
def __init__(self, *argv):
self.point_mode = False
self.use_ml = True
if len(argv) == 1:
events = list(argv[0])
events.sort()
events = num.array(events)
self.cellContent = num.ones(len(argv[0]))
self.cellSizes = self._generateCells(events)
self.binned = False
else:
try:
self._readPointData(argv)
except TypeError:
self.cellContent = copy.deepcopy(argv[0])
self.cellSizes = copy.deepcopy(argv[1])
self.tstart = argv[2]
self.binned = True
def _readPointData(self, argv):
x, y, dy = (list(copy.deepcopy(argv[0])),
list(copy.deepcopy(argv[1])),
list(copy.deepcopy(argv[2])))
if len(x) != len(y) or len(y) != len(dy):
raise RuntimeError("Point measurement mode: " +
"input array sizes do not match")
x.insert(0, x[0] - (x[1] - x[0]))
x.append(x[-1] + (x[-1] - x[-2]))
x = num.array(x)
cell_bounds = (x[1:] + x[:-1])/2.
self.tstart = cell_bounds[0]
self.cellSizes = cell_bounds[1:] - cell_bounds[:-1]
self.cellContent = y
self.fluxes = num.array(y)
self.errors = num.array(dy)
self.point_mode = True
def lightCurve(self, ncp_prior=1, use_ml=True):
return self.globalOpt(ncp_prior, use_ml)
def globalOpt(self, ncp_prior=1, use_ml=True):
if self.point_mode:
blockCost = self.blockCost_point
else:
blockCost = self.blockCost
self.use_ml = use_ml
opt, last = [], []
opt.append(blockCost(0, 0) - ncp_prior)
last.append(0)
npts = len(self.cellContent)
for nn in range(1, npts):
max_opt = blockCost(0, nn) - ncp_prior
jmax = 0
for j in range(1, nn+1):
my_opt = opt[j-1] + blockCost(j, nn) - ncp_prior
if my_opt > max_opt:
max_opt = my_opt
jmax = j
opt.append(max_opt)
last.append(jmax)
changePoints = []
indx = last[-1]
while indx > 0:
changePoints.insert(0, indx)
indx = last[indx-1]
changePoints.insert(0, 0)
changePoints.append(npts)
return self._lightCurve(changePoints)
def _lightCurve(self, changePoints):
xx = []
yy = []
cell_sizes = self.cellSizes
for imin, imax in zip(changePoints[:-1], changePoints[1:]):
try:
xx.extend([self.tstart + sum(cell_sizes[:imin]),
self.tstart + sum(cell_sizes[:imax])])
except IndexError:
xx.extend([self.tstart + imin*cell_sizes,
self.tstart + imax*cell_sizes])
if self.point_mode:
f, sig, weights = self._point_block_data(imin, imax-1)
yval = sum(weights*f)
else:
yval = (sum(self.cellContent[imin:imax])
/sum(cell_sizes[imin:imax]))
yy.extend([yval, yval])
return xx, yy
def _point_block_data(self, imin, imax):
f, sig = self.fluxes[imin:imax+1], self.errors[imin:imax+1]
weights = 1./sig**2/sum(1./sig**2)
return f, sig, weights
def blockCost_point(self, imin, imax):
f, sig, weights = self._point_block_data(imin, imax)
sigx2 = sum(weights*f**2) - (sum(weights*f))**2
return -sigx2/2*sum(1./sig**2)
def blockCost(self, imin, imax):
size = self.blockSize(imin, imax)
content = self.blockContent(imin, imax)
if content == 0:
return 0
my_cost = content*(num.log(content/size) - 1)
return my_cost
def blockSize(self, imin, imax):
try:
return sum(self.cellSizes[imin:imax+1])
except IndexError:
return self.cellSizes*(imax - imin)
def blockContent(self, imin, imax):
return sum(self.cellContent[imin:imax+1])
def _generateCells(self, events):
self.tstart = (3*events[0] - events[1])/2.
bounds = ((events[1:] + events[:-1])/2.).tolist()
bounds.insert(0, self.tstart)
bounds.append((3*events[-1] - events[-2])/2.)
bounds = num.array(bounds)
return bounds[1:] - bounds[:-1]
if __name__ == '__main__':
# import hippoplotter as plot
# import distributions as dist
# nsamp = 200
# events = dist.sample(dist.stepFunction(0.5, 0.7, amp=0.7), nsamp)
#
# output = open('events.dat', 'w')
# for event in events:
# output.write("%12.4e\n" % event)
# output.close()
class Histogram(object):
def __init__(self, xmin, xmax, nx):
self.xmin = xmin
self.dx = (xmax - xmin)/float(nx)
self.binContent = num.zeros(nx)
self.binSizes = self.dx*num.ones(nx)
def add(self, xx, wt=1):
indx = int((xx - self.xmin)/self.dx)
self.binContent[indx] += wt
events = [float(x.strip()) for x in open('events.dat', 'r')]
hist = Histogram(0, 1, 50)
for event in events:
hist.add(event)
bb = BayesianBlocks(events)
xx, yy = bb.globalOpt(ncp_prior=1)
bb2 = BayesianBlocks(hist.binContent, hist.binSizes, 0)
xx2, yy2 = bb2.globalOpt(ncp_prior=1)
# plot.histogram(events)
# plot.scatter(xx, yy, oplot=1, pointRep='Line', color='red', autoscale=1)
# plot.scatter(xx2, yy2, oplot=1, pointRep='Line', color='blue')
| python/BayesianBlocks_python.py | 6,753 | Unbinned mode:
>>> bb = BayesianBlocks(arrival_times)
Binned:
>>> bb = BayesianBlocks(bin_content, bin_sizes, start_time)
Point measurements:
>>> bb = BayesianBlocks(time, flux, errors)
Obtaining the piecewise constant light curve:
>>> time, rate = bb.globalOpt(ncp_prior=1)
@brief Pure python implementation of the Bayesian Blocks algorithm
described by Jackson, Scargle et al. 2005, IEEE Signal Processing
Letters, 12, 105. (http://arxiv.org/abs/math/0309285)
@author J. Chiang <jchiang@slac.stanford.edu>
$Id: BayesianBlocks_python.py,v 1.1.1.1 2011/09/03 00:55:59 jchiang Exp $ import hippoplotter as plot import distributions as dist nsamp = 200 events = dist.sample(dist.stepFunction(0.5, 0.7, amp=0.7), nsamp) output = open('events.dat', 'w') for event in events: output.write("%12.4e\n" % event) output.close() plot.histogram(events) plot.scatter(xx, yy, oplot=1, pointRep='Line', color='red', autoscale=1) plot.scatter(xx2, yy2, oplot=1, pointRep='Line', color='blue') | 1,020 | en | 0.595403 |
#!/usr/bin/env python3
# PYTHON_ARGCOMPLETE_OK
"""Entry point for cwltool."""
import argparse
import copy
import functools
import io
import logging
import os
import signal
import subprocess # nosec
import sys
import time
import urllib
import warnings
from codecs import StreamWriter, getwriter
from collections.abc import MutableMapping, MutableSequence
from typing import (
IO,
Any,
Callable,
Dict,
List,
Mapping,
MutableMapping,
MutableSequence,
Optional,
Sized,
TextIO,
Tuple,
Union,
cast,
)
import argcomplete
import coloredlogs
import pkg_resources # part of setuptools
import ruamel.yaml
from ruamel.yaml.comments import CommentedMap, CommentedSeq
from ruamel.yaml.main import YAML
from schema_salad.exceptions import ValidationException
from schema_salad.ref_resolver import Loader, file_uri, uri_file_path
from schema_salad.sourceline import cmap, strip_dup_lineno
from schema_salad.utils import ContextType, FetcherCallableType, json_dumps, yaml_no_ts
from . import CWL_CONTENT_TYPES, workflow
from .argparser import arg_parser, generate_parser, get_default_args
from .context import LoadingContext, RuntimeContext, getdefault
from .cwlrdf import printdot, printrdf
from .errors import (
ArgumentException,
GraphTargetMissingException,
UnsupportedRequirement,
WorkflowException,
)
from .executors import JobExecutor, MultithreadedJobExecutor, SingleJobExecutor
from .load_tool import (
default_loader,
fetch_document,
jobloaderctx,
load_overrides,
make_tool,
resolve_and_validate_document,
resolve_overrides,
resolve_tool_uri,
)
from .loghandler import _logger, configure_logging, defaultStreamHandler
from .mpi import MpiConfig
from .mutation import MutationManager
from .pack import pack
from .process import (
CWL_IANA,
Process,
add_sizes,
mergedirs,
scandeps,
shortname,
use_custom_schema,
use_standard_schema,
)
from .procgenerator import ProcessGenerator
from .provenance import ResearchObject, WritableBagFile
from .resolver import ga4gh_tool_registries, tool_resolver
from .secrets import SecretStore
from .software_requirements import (
DependenciesConfiguration,
get_container_from_software_requirements,
)
from .stdfsaccess import StdFsAccess
from .subgraph import get_process, get_step, get_subgraph
from .update import ALLUPDATES, UPDATES
from .utils import (
DEFAULT_TMP_PREFIX,
CWLObjectType,
CWLOutputAtomType,
CWLOutputType,
HasReqsHints,
adjustDirObjs,
normalizeFilesDirs,
processes_to_kill,
trim_listing,
versionstring,
visit_class,
)
from .workflow import Workflow
def _terminate_processes() -> None:
"""Kill all spawned processes.
Processes to be killed must be appended to `utils.processes_to_kill`
as they are spawned.
An important caveat: since there's no supported way to kill another
thread in Python, this function cannot stop other threads from
continuing to execute while it kills the processes that they've
spawned. This may occasionally lead to unexpected behaviour.
"""
# It's possible that another thread will spawn a new task while
# we're executing, so it's not safe to use a for loop here.
while processes_to_kill:
process = processes_to_kill.popleft()
if isinstance(process.args, MutableSequence):
args = process.args
else:
args = [process.args]
cidfile = [str(arg).split("=")[1] for arg in args if "--cidfile" in str(arg)]
if cidfile: # Try to be nice
try:
with open(cidfile[0]) as inp_stream:
p = subprocess.Popen( # nosec
["docker", "kill", inp_stream.read()], shell=False # nosec
)
try:
p.wait(timeout=10)
except subprocess.TimeoutExpired:
p.kill()
except FileNotFoundError:
pass
if process.stdin:
process.stdin.close()
try:
process.wait(10)
except subprocess.TimeoutExpired:
pass
process.kill() # Always kill, even if we tried with the cidfile
def _signal_handler(signum: int, _: Any) -> None:
"""Kill all spawned processes and exit.
Note that it's possible for another thread to spawn a process after
all processes have been killed, but before Python exits.
Refer to the docstring for _terminate_processes() for other caveats.
"""
_terminate_processes()
sys.exit(signum)
def generate_example_input(
inptype: Optional[CWLOutputType],
default: Optional[CWLOutputType],
) -> Tuple[Any, str]:
"""Convert a single input schema into an example."""
example = None
comment = ""
defaults = {
"null": "null",
"Any": "null",
"boolean": False,
"int": 0,
"long": 0,
"float": 0.1,
"double": 0.1,
"string": "a_string",
"File": ruamel.yaml.comments.CommentedMap(
[("class", "File"), ("path", "a/file/path")]
),
"Directory": ruamel.yaml.comments.CommentedMap(
[("class", "Directory"), ("path", "a/directory/path")]
),
} # type: CWLObjectType
if isinstance(inptype, MutableSequence):
optional = False
if "null" in inptype:
inptype.remove("null")
optional = True
if len(inptype) == 1:
example, comment = generate_example_input(inptype[0], default)
if optional:
if comment:
comment = f"{comment} (optional)"
else:
comment = "optional"
else:
example = CommentedSeq()
for index, entry in enumerate(inptype):
value, e_comment = generate_example_input(entry, default)
example.append(value)
example.yaml_add_eol_comment(e_comment, index)
if optional:
comment = "optional"
elif isinstance(inptype, Mapping) and "type" in inptype:
if inptype["type"] == "array":
first_item = cast(MutableSequence[CWLObjectType], inptype["items"])[0]
items_len = len(cast(Sized, inptype["items"]))
if items_len == 1 and "type" in first_item and first_item["type"] == "enum":
# array of just an enum then list all the options
example = first_item["symbols"]
if "name" in first_item:
comment = 'array of type "{}".'.format(first_item["name"])
else:
value, comment = generate_example_input(inptype["items"], None)
comment = "array of " + comment
if items_len == 1:
example = [value]
else:
example = value
if default is not None:
example = default
elif inptype["type"] == "enum":
symbols = cast(List[str], inptype["symbols"])
if default is not None:
example = default
elif "default" in inptype:
example = inptype["default"]
elif len(cast(Sized, inptype["symbols"])) == 1:
example = symbols[0]
else:
example = "{}_enum_value".format(inptype.get("name", "valid"))
comment = 'enum; valid values: "{}"'.format('", "'.join(symbols))
elif inptype["type"] == "record":
example = ruamel.yaml.comments.CommentedMap()
if "name" in inptype:
comment = '"{}" record type.'.format(inptype["name"])
else:
comment = "Anonymous record type."
for field in cast(List[CWLObjectType], inptype["fields"]):
value, f_comment = generate_example_input(field["type"], None)
example.insert(0, shortname(cast(str, field["name"])), value, f_comment)
elif "default" in inptype:
example = inptype["default"]
comment = 'default value of type "{}".'.format(inptype["type"])
else:
example = defaults.get(cast(str, inptype["type"]), str(inptype))
comment = 'type "{}".'.format(inptype["type"])
else:
if not default:
example = defaults.get(str(inptype), str(inptype))
comment = f'type "{inptype}"'
else:
example = default
comment = f'default value of type "{inptype}".'
return example, comment
def realize_input_schema(
input_types: MutableSequence[Union[str, CWLObjectType]],
schema_defs: MutableMapping[str, CWLObjectType],
) -> MutableSequence[Union[str, CWLObjectType]]:
"""Replace references to named typed with the actual types."""
for index, entry in enumerate(input_types):
if isinstance(entry, str):
if "#" in entry:
_, input_type_name = entry.split("#")
else:
input_type_name = entry
if input_type_name in schema_defs:
entry = input_types[index] = schema_defs[input_type_name]
if isinstance(entry, MutableMapping):
if isinstance(entry["type"], str) and "#" in entry["type"]:
_, input_type_name = entry["type"].split("#")
if input_type_name in schema_defs:
entry["type"] = cast(
CWLOutputAtomType,
realize_input_schema(
cast(
MutableSequence[Union[str, CWLObjectType]],
schema_defs[input_type_name],
),
schema_defs,
),
)
if isinstance(entry["type"], MutableSequence):
entry["type"] = cast(
CWLOutputAtomType,
realize_input_schema(
cast(MutableSequence[Union[str, CWLObjectType]], entry["type"]),
schema_defs,
),
)
if isinstance(entry["type"], Mapping):
entry["type"] = cast(
CWLOutputAtomType,
realize_input_schema(
[cast(CWLObjectType, entry["type"])], schema_defs
),
)
if entry["type"] == "array":
items = (
entry["items"]
if not isinstance(entry["items"], str)
else [entry["items"]]
)
entry["items"] = cast(
CWLOutputAtomType,
realize_input_schema(
cast(MutableSequence[Union[str, CWLObjectType]], items),
schema_defs,
),
)
if entry["type"] == "record":
entry["fields"] = cast(
CWLOutputAtomType,
realize_input_schema(
cast(
MutableSequence[Union[str, CWLObjectType]], entry["fields"]
),
schema_defs,
),
)
return input_types
def generate_input_template(tool: Process) -> CWLObjectType:
"""Generate an example input object for the given CWL process."""
template = ruamel.yaml.comments.CommentedMap()
for inp in cast(
List[MutableMapping[str, str]],
realize_input_schema(tool.tool["inputs"], tool.schemaDefs),
):
name = shortname(inp["id"])
value, comment = generate_example_input(inp["type"], inp.get("default", None))
template.insert(0, name, value, comment)
return template
def load_job_order(
args: argparse.Namespace,
stdin: IO[Any],
fetcher_constructor: Optional[FetcherCallableType],
overrides_list: List[CWLObjectType],
tool_file_uri: str,
) -> Tuple[Optional[CWLObjectType], str, Loader]:
job_order_object = None
job_order_file = None
_jobloaderctx = jobloaderctx.copy()
loader = Loader(_jobloaderctx, fetcher_constructor=fetcher_constructor)
if len(args.job_order) == 1 and args.job_order[0][0] != "-":
job_order_file = args.job_order[0]
elif len(args.job_order) == 1 and args.job_order[0] == "-":
yaml = yaml_no_ts()
job_order_object = yaml.load(stdin)
job_order_object, _ = loader.resolve_all(
job_order_object, file_uri(os.getcwd()) + "/"
)
else:
job_order_file = None
if job_order_object is not None:
input_basedir = args.basedir if args.basedir else os.getcwd()
elif job_order_file is not None:
input_basedir = (
args.basedir
if args.basedir
else os.path.abspath(os.path.dirname(job_order_file))
)
job_order_object, _ = loader.resolve_ref(
job_order_file,
checklinks=False,
content_types=CWL_CONTENT_TYPES,
)
if (
job_order_object is not None
and "http://commonwl.org/cwltool#overrides" in job_order_object
):
ov_uri = file_uri(job_order_file or input_basedir)
overrides_list.extend(
resolve_overrides(job_order_object, ov_uri, tool_file_uri)
)
del job_order_object["http://commonwl.org/cwltool#overrides"]
if job_order_object is None:
input_basedir = args.basedir if args.basedir else os.getcwd()
if job_order_object is not None and not isinstance(
job_order_object, MutableMapping
):
_logger.error(
"CWL input object at %s is not formatted correctly, it should be a "
"JSON/YAML dictionay, not %s.\n"
"Raw input object:\n%s",
job_order_file or "stdin",
type(job_order_object),
job_order_object,
)
sys.exit(1)
return (job_order_object, input_basedir, loader)
def init_job_order(
job_order_object: Optional[CWLObjectType],
args: argparse.Namespace,
process: Process,
loader: Loader,
stdout: Union[TextIO, StreamWriter],
print_input_deps: bool = False,
relative_deps: str = "primary",
make_fs_access: Callable[[str], StdFsAccess] = StdFsAccess,
input_basedir: str = "",
secret_store: Optional[SecretStore] = None,
input_required: bool = True,
runtime_context: Optional[RuntimeContext] = None,
) -> CWLObjectType:
secrets_req, _ = process.get_requirement("http://commonwl.org/cwltool#Secrets")
if job_order_object is None:
namemap = {} # type: Dict[str, str]
records = [] # type: List[str]
toolparser = generate_parser(
argparse.ArgumentParser(prog=args.workflow),
process,
namemap,
records,
input_required,
loader.fetcher.urljoin,
file_uri(os.getcwd()) + "/",
)
if args.tool_help:
toolparser.print_help(cast(IO[str], stdout))
exit(0)
cmd_line = vars(toolparser.parse_args(args.job_order))
for record_name in records:
record = {}
record_items = {
k: v for k, v in cmd_line.items() if k.startswith(record_name)
}
for key, value in record_items.items():
record[key[len(record_name) + 1 :]] = value
del cmd_line[key]
cmd_line[str(record_name)] = record
if "job_order" in cmd_line and cmd_line["job_order"]:
try:
job_order_object = cast(
CWLObjectType,
loader.resolve_ref(cmd_line["job_order"])[0],
)
except Exception:
_logger.exception(
"Failed to resolv job_order: %s", cmd_line["job_order"]
)
exit(1)
else:
job_order_object = {"id": args.workflow}
del cmd_line["job_order"]
job_order_object.update({namemap[k]: v for k, v in cmd_line.items()})
if secret_store and secrets_req:
secret_store.store(
[shortname(sc) for sc in cast(List[str], secrets_req["secrets"])],
job_order_object,
)
if _logger.isEnabledFor(logging.DEBUG):
_logger.debug(
"Parsed job order from command line: %s",
json_dumps(job_order_object, indent=4, default=str),
)
for inp in process.tool["inputs"]:
if "default" in inp and (
not job_order_object or shortname(inp["id"]) not in job_order_object
):
if not job_order_object:
job_order_object = {}
job_order_object[shortname(inp["id"])] = inp["default"]
def path_to_loc(p: CWLObjectType) -> None:
if "location" not in p and "path" in p:
p["location"] = p["path"]
del p["path"]
ns = {} # type: ContextType
ns.update(cast(ContextType, job_order_object.get("$namespaces", {})))
ns.update(cast(ContextType, process.metadata.get("$namespaces", {})))
ld = Loader(ns)
def expand_formats(p: CWLObjectType) -> None:
if "format" in p:
p["format"] = ld.expand_url(cast(str, p["format"]), "")
visit_class(job_order_object, ("File", "Directory"), path_to_loc)
visit_class(
job_order_object,
("File",),
functools.partial(add_sizes, make_fs_access(input_basedir)),
)
visit_class(job_order_object, ("File",), expand_formats)
adjustDirObjs(job_order_object, trim_listing)
normalizeFilesDirs(job_order_object)
if print_input_deps:
if not runtime_context:
raise RuntimeError("runtime_context is required for print_input_deps.")
runtime_context.toplevel = True
builder = process._init_job(job_order_object, runtime_context)
builder.loadListing = "no_listing"
builder.bind_input(
process.inputs_record_schema, job_order_object, discover_secondaryFiles=True
)
basedir: Optional[str] = None
uri = cast(str, job_order_object["id"])
if uri == args.workflow:
basedir = os.path.dirname(uri)
uri = ""
printdeps(
job_order_object,
loader,
stdout,
relative_deps,
uri,
basedir=basedir,
nestdirs=False,
)
exit(0)
if secret_store and secrets_req:
secret_store.store(
[shortname(sc) for sc in cast(List[str], secrets_req["secrets"])],
job_order_object,
)
if "cwl:tool" in job_order_object:
del job_order_object["cwl:tool"]
if "id" in job_order_object:
del job_order_object["id"]
return job_order_object
def make_relative(base: str, obj: CWLObjectType) -> None:
"""Relativize the location URI of a File or Directory object."""
uri = cast(str, obj.get("location", obj.get("path")))
if ":" in uri.split("/")[0] and not uri.startswith("file://"):
pass
else:
if uri.startswith("file://"):
uri = uri_file_path(uri)
obj["location"] = os.path.relpath(uri, base)
def printdeps(
obj: CWLObjectType,
document_loader: Loader,
stdout: Union[TextIO, StreamWriter],
relative_deps: str,
uri: str,
basedir: Optional[str] = None,
nestdirs: bool = True,
) -> None:
"""Print a JSON representation of the dependencies of the CWL document."""
deps = find_deps(obj, document_loader, uri, basedir=basedir, nestdirs=nestdirs)
if relative_deps == "primary":
base = basedir if basedir else os.path.dirname(uri_file_path(str(uri)))
elif relative_deps == "cwd":
base = os.getcwd()
visit_class(deps, ("File", "Directory"), functools.partial(make_relative, base))
print(json_dumps(deps, indent=4, default=str), file=stdout)
def prov_deps(
obj: CWLObjectType,
document_loader: Loader,
uri: str,
basedir: Optional[str] = None,
) -> CWLObjectType:
deps = find_deps(obj, document_loader, uri, basedir=basedir)
def remove_non_cwl(deps: CWLObjectType) -> None:
if "secondaryFiles" in deps:
sec_files = cast(List[CWLObjectType], deps["secondaryFiles"])
for index, entry in enumerate(sec_files):
if not ("format" in entry and entry["format"] == CWL_IANA):
del sec_files[index]
else:
remove_non_cwl(entry)
remove_non_cwl(deps)
return deps
def find_deps(
obj: CWLObjectType,
document_loader: Loader,
uri: str,
basedir: Optional[str] = None,
nestdirs: bool = True,
) -> CWLObjectType:
"""Find the dependencies of the CWL document."""
deps = {
"class": "File",
"location": uri,
"format": CWL_IANA,
} # type: CWLObjectType
def loadref(base: str, uri: str) -> Union[CommentedMap, CommentedSeq, str, None]:
return document_loader.fetch(document_loader.fetcher.urljoin(base, uri))
sfs = scandeps(
basedir if basedir else uri,
obj,
{"$import", "run"},
{"$include", "$schemas", "location"},
loadref,
nestdirs=nestdirs,
)
if sfs is not None:
deps["secondaryFiles"] = cast(
MutableSequence[CWLOutputAtomType], mergedirs(sfs)
)
return deps
def print_pack(
loadingContext: LoadingContext,
uri: str,
) -> str:
"""Return a CWL serialization of the CWL document in JSON."""
packed = pack(loadingContext, uri)
if len(cast(Sized, packed["$graph"])) > 1:
return json_dumps(packed, indent=4, default=str)
return json_dumps(
cast(MutableSequence[CWLObjectType], packed["$graph"])[0], indent=4, default=str
)
def supported_cwl_versions(enable_dev: bool) -> List[str]:
# ALLUPDATES and UPDATES are dicts
if enable_dev:
versions = list(ALLUPDATES)
else:
versions = list(UPDATES)
versions.sort()
return versions
def setup_schema(
args: argparse.Namespace, custom_schema_callback: Optional[Callable[[], None]]
) -> None:
if custom_schema_callback is not None:
custom_schema_callback()
elif args.enable_ext:
with pkg_resources.resource_stream(__name__, "extensions.yml") as res:
ext10 = res.read().decode("utf-8")
with pkg_resources.resource_stream(__name__, "extensions-v1.1.yml") as res:
ext11 = res.read().decode("utf-8")
use_custom_schema("v1.0", "http://commonwl.org/cwltool", ext10)
use_custom_schema("v1.1", "http://commonwl.org/cwltool", ext11)
use_custom_schema("v1.2", "http://commonwl.org/cwltool", ext11)
use_custom_schema("v1.2.0-dev1", "http://commonwl.org/cwltool", ext11)
use_custom_schema("v1.2.0-dev2", "http://commonwl.org/cwltool", ext11)
use_custom_schema("v1.2.0-dev3", "http://commonwl.org/cwltool", ext11)
else:
use_standard_schema("v1.0")
use_standard_schema("v1.1")
use_standard_schema("v1.2")
use_standard_schema("v1.2.0-dev1")
use_standard_schema("v1.2.0-dev2")
use_standard_schema("v1.2.0-dev3")
class ProvLogFormatter(logging.Formatter):
"""Enforce ISO8601 with both T and Z."""
def __init__(self) -> None:
"""Use the default formatter with our custom formatstring."""
super().__init__("[%(asctime)sZ] %(message)s")
def formatTime(
self, record: logging.LogRecord, datefmt: Optional[str] = None
) -> str:
formatted_time = time.strftime(
"%Y-%m-%dT%H:%M:%S", time.gmtime(float(record.created))
)
with_msecs = f"{formatted_time},{record.msecs:03f}"
return with_msecs
ProvOut = Union[io.TextIOWrapper, WritableBagFile]
def setup_provenance(
args: argparse.Namespace,
argsl: List[str],
runtimeContext: RuntimeContext,
) -> Tuple[ProvOut, "logging.StreamHandler[ProvOut]"]:
if not args.compute_checksum:
_logger.error("--provenance incompatible with --no-compute-checksum")
raise ArgumentException()
ro = ResearchObject(
getdefault(runtimeContext.make_fs_access, StdFsAccess)(""),
temp_prefix_ro=args.tmpdir_prefix,
orcid=args.orcid,
full_name=args.cwl_full_name,
)
runtimeContext.research_obj = ro
log_file_io = ro.open_log_file_for_activity(ro.engine_uuid)
prov_log_handler = logging.StreamHandler(log_file_io)
prov_log_handler.setFormatter(ProvLogFormatter())
_logger.addHandler(prov_log_handler)
_logger.debug("[provenance] Logging to %s", log_file_io)
if argsl is not None:
# Log cwltool command line options to provenance file
_logger.info("[cwltool] %s %s", sys.argv[0], " ".join(argsl))
_logger.debug("[cwltool] Arguments: %s", args)
return log_file_io, prov_log_handler
def setup_loadingContext(
loadingContext: Optional[LoadingContext],
runtimeContext: RuntimeContext,
args: argparse.Namespace,
) -> LoadingContext:
"""Prepare a LoadingContext from the given arguments."""
if loadingContext is None:
loadingContext = LoadingContext(vars(args))
loadingContext.singularity = runtimeContext.singularity
loadingContext.podman = runtimeContext.podman
else:
loadingContext = loadingContext.copy()
loadingContext.loader = default_loader(
loadingContext.fetcher_constructor,
enable_dev=args.enable_dev,
doc_cache=args.doc_cache,
)
loadingContext.research_obj = runtimeContext.research_obj
loadingContext.disable_js_validation = args.disable_js_validation or (
not args.do_validate
)
loadingContext.construct_tool_object = getdefault(
loadingContext.construct_tool_object, workflow.default_make_tool
)
loadingContext.resolver = getdefault(loadingContext.resolver, tool_resolver)
if loadingContext.do_update is None:
loadingContext.do_update = not (args.pack or args.print_subgraph)
return loadingContext
def make_template(
tool: Process,
) -> None:
"""Make a template CWL input object for the give Process."""
def my_represent_none(
self: Any, data: Any
) -> Any: # pylint: disable=unused-argument
"""Force clean representation of 'null'."""
return self.represent_scalar("tag:yaml.org,2002:null", "null")
ruamel.yaml.representer.RoundTripRepresenter.add_representer(
type(None), my_represent_none
)
yaml = YAML()
yaml.default_flow_style = False
yaml.indent = 4
yaml.block_seq_indent = 2
yaml.dump(
generate_input_template(tool),
sys.stdout,
)
def inherit_reqshints(tool: Process, parent: Process) -> None:
"""Copy down requirements and hints from ancestors of a given process."""
for parent_req in parent.requirements:
found = False
for tool_req in tool.requirements:
if parent_req["class"] == tool_req["class"]:
found = True
break
if not found:
tool.requirements.append(parent_req)
for parent_hint in parent.hints:
found = False
for tool_req in tool.requirements:
if parent_hint["class"] == tool_req["class"]:
found = True
break
if not found:
for tool_hint in tool.hints:
if parent_hint["class"] == tool_hint["class"]:
found = True
break
if not found:
tool.hints.append(parent_hint)
def choose_target(
args: argparse.Namespace,
tool: Process,
loading_context: LoadingContext,
) -> Optional[Process]:
"""Walk the Workflow, extract the subset matches all the args.targets."""
if loading_context.loader is None:
raise Exception("loading_context.loader cannot be None")
if isinstance(tool, Workflow):
url = urllib.parse.urlparse(tool.tool["id"])
if url.fragment:
extracted = get_subgraph(
[tool.tool["id"] + "/" + r for r in args.target], tool, loading_context
)
else:
extracted = get_subgraph(
[
loading_context.loader.fetcher.urljoin(tool.tool["id"], "#" + r)
for r in args.target
],
tool,
loading_context,
)
else:
_logger.error("Can only use --target on Workflows")
return None
if isinstance(loading_context.loader.idx, MutableMapping):
loading_context.loader.idx[extracted["id"]] = extracted
tool = make_tool(extracted["id"], loading_context)
else:
raise Exception("Missing loading_context.loader.idx!")
return tool
def choose_step(
args: argparse.Namespace,
tool: Process,
loading_context: LoadingContext,
) -> Optional[Process]:
"""Walk the given Workflow and extract just args.single_step."""
if loading_context.loader is None:
raise Exception("loading_context.loader cannot be None")
if isinstance(tool, Workflow):
url = urllib.parse.urlparse(tool.tool["id"])
if url.fragment:
step_id = tool.tool["id"] + "/" + args.single_step
else:
step_id = loading_context.loader.fetcher.urljoin(
tool.tool["id"], "#" + args.single_step
)
extracted = get_step(tool, step_id, loading_context)
else:
_logger.error("Can only use --single-step on Workflows")
return None
if isinstance(loading_context.loader.idx, MutableMapping):
loading_context.loader.idx[extracted["id"]] = cast(
Union[CommentedMap, CommentedSeq, str, None], cmap(extracted)
)
tool = make_tool(extracted["id"], loading_context)
else:
raise Exception("Missing loading_context.loader.idx!")
return tool
def choose_process(
args: argparse.Namespace,
tool: Process,
loadingContext: LoadingContext,
) -> Optional[Process]:
"""Walk the given Workflow and extract just args.single_process."""
if loadingContext.loader is None:
raise Exception("loadingContext.loader cannot be None")
if isinstance(tool, Workflow):
url = urllib.parse.urlparse(tool.tool["id"])
if url.fragment:
step_id = tool.tool["id"] + "/" + args.single_process
else:
step_id = loadingContext.loader.fetcher.urljoin(
tool.tool["id"], "#" + args.single_process
)
extracted, workflow_step = get_process(
tool,
step_id,
loadingContext,
)
else:
_logger.error("Can only use --single-process on Workflows")
return None
if isinstance(loadingContext.loader.idx, MutableMapping):
loadingContext.loader.idx[extracted["id"]] = extracted
new_tool = make_tool(extracted["id"], loadingContext)
else:
raise Exception("Missing loadingContext.loader.idx!")
inherit_reqshints(new_tool, workflow_step)
return new_tool
def check_working_directories(
runtimeContext: RuntimeContext,
) -> Optional[int]:
"""Make any needed working directories."""
for dirprefix in ("tmpdir_prefix", "tmp_outdir_prefix", "cachedir"):
if (
getattr(runtimeContext, dirprefix)
and getattr(runtimeContext, dirprefix) != DEFAULT_TMP_PREFIX
):
sl = (
"/"
if getattr(runtimeContext, dirprefix).endswith("/")
or dirprefix == "cachedir"
else ""
)
setattr(
runtimeContext,
dirprefix,
os.path.abspath(getattr(runtimeContext, dirprefix)) + sl,
)
if not os.path.exists(os.path.dirname(getattr(runtimeContext, dirprefix))):
try:
os.makedirs(os.path.dirname(getattr(runtimeContext, dirprefix)))
except Exception:
_logger.exception("Failed to create directory.")
return 1
return None
def print_targets(
tool: Process,
stdout: Union[TextIO, StreamWriter],
loading_context: LoadingContext,
prefix: str = "",
) -> None:
"""Recursively find targets for --subgraph and friends."""
for f in ("outputs", "inputs"):
if tool.tool[f]:
_logger.info("%s %s%s targets:", prefix[:-1], f[0].upper(), f[1:-1])
print(
" "
+ "\n ".join([f"{prefix}{shortname(t['id'])}" for t in tool.tool[f]]),
file=stdout,
)
if "steps" in tool.tool:
loading_context = copy.copy(loading_context)
loading_context.requirements = tool.requirements
loading_context.hints = tool.hints
_logger.info("%s steps targets:", prefix[:-1])
for t in tool.tool["steps"]:
print(f" {prefix}{shortname(t['id'])}", file=stdout)
run: Union[str, Process, Dict[str, Any]] = t["run"]
if isinstance(run, str):
process = make_tool(run, loading_context)
elif isinstance(run, dict):
process = make_tool(cast(CommentedMap, cmap(run)), loading_context)
else:
process = run
print_targets(
process, stdout, loading_context, f"{prefix}{shortname(t['id'])}/"
)
def main(
argsl: Optional[List[str]] = None,
args: Optional[argparse.Namespace] = None,
job_order_object: Optional[CWLObjectType] = None,
stdin: IO[Any] = sys.stdin,
stdout: Optional[Union[TextIO, StreamWriter]] = None,
stderr: IO[Any] = sys.stderr,
versionfunc: Callable[[], str] = versionstring,
logger_handler: Optional[logging.Handler] = None,
custom_schema_callback: Optional[Callable[[], None]] = None,
executor: Optional[JobExecutor] = None,
loadingContext: Optional[LoadingContext] = None,
runtimeContext: Optional[RuntimeContext] = None,
input_required: bool = True,
) -> int:
if not stdout: # force UTF-8 even if the console is configured differently
if hasattr(sys.stdout, "encoding") and sys.stdout.encoding.upper() not in (
"UTF-8",
"UTF8",
):
if hasattr(sys.stdout, "detach"):
stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
else:
stdout = getwriter("utf-8")(sys.stdout) # type: ignore
else:
stdout = sys.stdout
_logger.removeHandler(defaultStreamHandler)
stderr_handler = logger_handler
if stderr_handler is not None:
_logger.addHandler(stderr_handler)
else:
coloredlogs.install(logger=_logger, stream=stderr)
stderr_handler = _logger.handlers[-1]
workflowobj = None
prov_log_handler: Optional[logging.StreamHandler[ProvOut]] = None
try:
if args is None:
if argsl is None:
argsl = sys.argv[1:]
addl = [] # type: List[str]
if "CWLTOOL_OPTIONS" in os.environ:
addl = os.environ["CWLTOOL_OPTIONS"].split(" ")
parser = arg_parser()
argcomplete.autocomplete(parser)
args = parser.parse_args(addl + argsl)
if args.record_container_id:
if not args.cidfile_dir:
args.cidfile_dir = os.getcwd()
del args.record_container_id
if runtimeContext is None:
runtimeContext = RuntimeContext(vars(args))
else:
runtimeContext = runtimeContext.copy()
# If caller parsed its own arguments, it may not include every
# cwltool option, so fill in defaults to avoid crashing when
# dereferencing them in args.
for key, val in get_default_args().items():
if not hasattr(args, key):
setattr(args, key, val)
configure_logging(
stderr_handler,
args.quiet,
runtimeContext.debug,
args.enable_color,
args.timestamps,
)
if args.version:
print(versionfunc(), file=stdout)
return 0
_logger.info(versionfunc())
if args.print_supported_versions:
print("\n".join(supported_cwl_versions(args.enable_dev)), file=stdout)
return 0
if not args.workflow:
if os.path.isfile("CWLFile"):
args.workflow = "CWLFile"
else:
_logger.error("CWL document required, no input file was provided")
parser.print_help(stderr)
return 1
if args.ga4gh_tool_registries:
ga4gh_tool_registries[:] = args.ga4gh_tool_registries
if not args.enable_ga4gh_tool_registry:
del ga4gh_tool_registries[:]
if args.mpi_config_file is not None:
runtimeContext.mpi_config = MpiConfig.load(args.mpi_config_file)
setup_schema(args, custom_schema_callback)
prov_log_stream: Optional[Union[io.TextIOWrapper, WritableBagFile]] = None
if args.provenance:
if argsl is None:
raise Exception("argsl cannot be None")
try:
prov_log_stream, prov_log_handler = setup_provenance(
args, argsl, runtimeContext
)
except ArgumentException:
return 1
loadingContext = setup_loadingContext(loadingContext, runtimeContext, args)
uri, tool_file_uri = resolve_tool_uri(
args.workflow,
resolver=loadingContext.resolver,
fetcher_constructor=loadingContext.fetcher_constructor,
)
try_again_msg = (
"" if args.debug else ", try again with --debug for more information"
)
try:
job_order_object, input_basedir, jobloader = load_job_order(
args,
stdin,
loadingContext.fetcher_constructor,
loadingContext.overrides_list,
tool_file_uri,
)
if args.overrides:
loadingContext.overrides_list.extend(
load_overrides(
file_uri(os.path.abspath(args.overrides)), tool_file_uri
)
)
loadingContext, workflowobj, uri = fetch_document(uri, loadingContext)
if args.print_deps and loadingContext.loader:
printdeps(
workflowobj, loadingContext.loader, stdout, args.relative_deps, uri
)
return 0
loadingContext, uri = resolve_and_validate_document(
loadingContext,
workflowobj,
uri,
preprocess_only=(args.print_pre or args.pack),
skip_schemas=args.skip_schemas,
)
if loadingContext.loader is None:
raise Exception("Impossible code path.")
processobj, metadata = loadingContext.loader.resolve_ref(uri)
processobj = cast(Union[CommentedMap, CommentedSeq], processobj)
if args.pack:
print(print_pack(loadingContext, uri), file=stdout)
return 0
if args.provenance and runtimeContext.research_obj:
# Can't really be combined with args.pack at same time
runtimeContext.research_obj.packed_workflow(
print_pack(loadingContext, uri)
)
if args.print_pre:
print(
json_dumps(
processobj,
indent=4,
sort_keys=True,
separators=(",", ": "),
default=str,
),
file=stdout,
)
return 0
try:
tool = make_tool(uri, loadingContext)
except GraphTargetMissingException as main_missing_exc:
if args.validate:
logging.warn(
"File contains $graph of multiple objects and no default "
"process (#main). Validating all objects:"
)
for entry in workflowobj["$graph"]:
entry_id = entry["id"]
make_tool(entry_id, loadingContext)
print(f"{entry_id} is valid CWL.", file=stdout)
else:
raise main_missing_exc
if args.make_template:
make_template(tool)
return 0
if args.validate:
print(f"{args.workflow} is valid CWL.", file=stdout)
return 0
if args.print_rdf:
print(
printrdf(tool, loadingContext.loader.ctx, args.rdf_serializer),
file=stdout,
)
return 0
if args.print_dot:
printdot(tool, loadingContext.loader.ctx, stdout)
return 0
if args.print_targets:
print_targets(tool, stdout, loadingContext)
return 0
if args.target:
ctool = choose_target(args, tool, loadingContext)
if ctool is None:
return 1
else:
tool = ctool
elif args.single_step:
ctool = choose_step(args, tool, loadingContext)
if ctool is None:
return 1
else:
tool = ctool
elif args.single_process:
ctool = choose_process(args, tool, loadingContext)
if ctool is None:
return 1
else:
tool = ctool
if args.print_subgraph:
if "name" in tool.tool:
del tool.tool["name"]
print(
json_dumps(
tool.tool,
indent=4,
sort_keys=True,
separators=(",", ": "),
default=str,
),
file=stdout,
)
return 0
except (ValidationException) as exc:
_logger.error(
"Tool definition failed validation:\n%s", str(exc), exc_info=args.debug
)
return 1
except (RuntimeError, WorkflowException) as exc:
_logger.error(
"Tool definition failed initialization:\n%s",
str(exc),
exc_info=args.debug,
)
return 1
except Exception as exc:
_logger.error(
"I'm sorry, I couldn't load this CWL file%s.\nThe error was: %s",
try_again_msg,
str(exc) if not args.debug else "",
exc_info=args.debug,
)
return 1
if isinstance(tool, int):
return tool
# If on MacOS platform, TMPDIR must be set to be under one of the
# shared volumes in Docker for Mac
# More info: https://dockstore.org/docs/faq
if sys.platform == "darwin":
default_mac_path = "/private/tmp/docker_tmp"
if runtimeContext.tmp_outdir_prefix == DEFAULT_TMP_PREFIX:
runtimeContext.tmp_outdir_prefix = default_mac_path
if runtimeContext.tmpdir_prefix == DEFAULT_TMP_PREFIX:
runtimeContext.tmpdir_prefix = default_mac_path
if check_working_directories(runtimeContext) is not None:
return 1
if args.cachedir:
if args.move_outputs == "move":
runtimeContext.move_outputs = "copy"
runtimeContext.tmp_outdir_prefix = args.cachedir
runtimeContext.log_dir = args.log_dir
runtimeContext.secret_store = getdefault(
runtimeContext.secret_store, SecretStore()
)
runtimeContext.make_fs_access = getdefault(
runtimeContext.make_fs_access, StdFsAccess
)
if not executor:
if args.parallel:
temp_executor = MultithreadedJobExecutor()
runtimeContext.select_resources = temp_executor.select_resources
real_executor = temp_executor # type: JobExecutor
else:
real_executor = SingleJobExecutor()
else:
real_executor = executor
try:
runtimeContext.basedir = input_basedir
if isinstance(tool, ProcessGenerator):
tfjob_order = {} # type: CWLObjectType
if loadingContext.jobdefaults:
tfjob_order.update(loadingContext.jobdefaults)
if job_order_object:
tfjob_order.update(job_order_object)
tfout, tfstatus = real_executor(
tool.embedded_tool, tfjob_order, runtimeContext
)
if not tfout or tfstatus != "success":
raise WorkflowException(
"ProcessGenerator failed to generate workflow"
)
tool, job_order_object = tool.result(tfjob_order, tfout, runtimeContext)
if not job_order_object:
job_order_object = None
try:
initialized_job_order_object = init_job_order(
job_order_object,
args,
tool,
jobloader,
stdout,
print_input_deps=args.print_input_deps,
relative_deps=args.relative_deps,
make_fs_access=runtimeContext.make_fs_access,
input_basedir=input_basedir,
secret_store=runtimeContext.secret_store,
input_required=input_required,
runtime_context=runtimeContext,
)
except SystemExit as err:
return err.code
del args.workflow
del args.job_order
conf_file = getattr(
args, "beta_dependency_resolvers_configuration", None
) # str
use_conda_dependencies = getattr(
args, "beta_conda_dependencies", None
) # str
if conf_file or use_conda_dependencies:
runtimeContext.job_script_provider = DependenciesConfiguration(args)
else:
runtimeContext.find_default_container = functools.partial(
find_default_container,
default_container=runtimeContext.default_container,
use_biocontainers=args.beta_use_biocontainers,
)
(out, status) = real_executor(
tool, initialized_job_order_object, runtimeContext, logger=_logger
)
if out is not None:
if runtimeContext.research_obj is not None:
runtimeContext.research_obj.create_job(out, True)
def remove_at_id(doc: CWLObjectType) -> None:
for key in list(doc.keys()):
if key == "@id":
del doc[key]
else:
value = doc[key]
if isinstance(value, MutableMapping):
remove_at_id(value)
elif isinstance(value, MutableSequence):
for entry in value:
if isinstance(entry, MutableMapping):
remove_at_id(entry)
remove_at_id(out)
visit_class(
out,
("File",),
functools.partial(add_sizes, runtimeContext.make_fs_access("")),
)
def loc_to_path(obj: CWLObjectType) -> None:
for field in ("path", "nameext", "nameroot", "dirname"):
if field in obj:
del obj[field]
if cast(str, obj["location"]).startswith("file://"):
obj["path"] = uri_file_path(cast(str, obj["location"]))
visit_class(out, ("File", "Directory"), loc_to_path)
# Unsetting the Generation from final output object
visit_class(out, ("File",), MutationManager().unset_generation)
print(
json_dumps(out, indent=4, ensure_ascii=False, default=str),
file=stdout,
)
if hasattr(stdout, "flush"):
stdout.flush()
if status != "success":
_logger.warning("Final process status is %s", status)
return 1
_logger.info("Final process status is %s", status)
return 0
except (ValidationException) as exc:
_logger.error(
"Input object failed validation:\n%s", str(exc), exc_info=args.debug
)
return 1
except UnsupportedRequirement as exc:
_logger.error(
"Workflow or tool uses unsupported feature:\n%s",
str(exc),
exc_info=args.debug,
)
return 33
except WorkflowException as exc:
_logger.error(
"Workflow error%s:\n%s",
try_again_msg,
strip_dup_lineno(str(exc)),
exc_info=args.debug,
)
return 1
except Exception as exc: # pylint: disable=broad-except
_logger.error(
"Unhandled error%s:\n %s",
try_again_msg,
str(exc),
exc_info=args.debug,
)
return 1
finally:
if (
args
and runtimeContext
and runtimeContext.research_obj
and workflowobj
and loadingContext
):
research_obj = runtimeContext.research_obj
if loadingContext.loader is not None:
research_obj.generate_snapshot(
prov_deps(workflowobj, loadingContext.loader, uri)
)
else:
_logger.warning(
"Unable to generate provenance snapshot "
" due to missing loadingContext.loader."
)
if prov_log_handler is not None:
# Stop logging so we won't half-log adding ourself to RO
_logger.debug(
"[provenance] Closing provenance log file %s", prov_log_handler
)
_logger.removeHandler(prov_log_handler)
# Ensure last log lines are written out
prov_log_handler.flush()
# Underlying WritableBagFile will add the tagfile to the manifest
if prov_log_stream:
prov_log_stream.close()
# Why not use prov_log_handler.stream ? That is not part of the
# public API for logging.StreamHandler
prov_log_handler.close()
research_obj.close(args.provenance)
_logger.removeHandler(stderr_handler)
_logger.addHandler(defaultStreamHandler)
def find_default_container(
builder: HasReqsHints,
default_container: Optional[str] = None,
use_biocontainers: Optional[bool] = None,
) -> Optional[str]:
"""Find a container."""
if not default_container and use_biocontainers:
default_container = get_container_from_software_requirements(
use_biocontainers, builder
)
return default_container
def windows_check() -> None:
"""See if we are running on MS Windows and warn about the lack of support."""
if os.name == "nt":
warnings.warn(
"The CWL reference runner (cwltool) no longer supports running "
"CWL workflows natively on MS Windows as its previous MS Windows "
"support was incomplete and untested. Instead, please see "
"https://pypi.org/project/cwltool/#ms-windows-users "
"for instructions on running cwltool via "
"Windows Subsystem for Linux 2 (WSL2). If don't need to execute "
"CWL documents, then you can ignore this warning, but please "
"consider migrating to https://pypi.org/project/cwl-utils/ "
"for your CWL document processing needs."
)
def run(*args: Any, **kwargs: Any) -> None:
"""Run cwltool."""
windows_check()
signal.signal(signal.SIGTERM, _signal_handler)
try:
sys.exit(main(*args, **kwargs))
finally:
_terminate_processes()
if __name__ == "__main__":
run(sys.argv[1:])
| cwltool/main.py | 53,715 | Enforce ISO8601 with both T and Z.
Use the default formatter with our custom formatstring.
Kill all spawned processes and exit.
Note that it's possible for another thread to spawn a process after
all processes have been killed, but before Python exits.
Refer to the docstring for _terminate_processes() for other caveats.
Kill all spawned processes.
Processes to be killed must be appended to `utils.processes_to_kill`
as they are spawned.
An important caveat: since there's no supported way to kill another
thread in Python, this function cannot stop other threads from
continuing to execute while it kills the processes that they've
spawned. This may occasionally lead to unexpected behaviour.
Make any needed working directories.
Walk the given Workflow and extract just args.single_process.
Walk the given Workflow and extract just args.single_step.
Walk the Workflow, extract the subset matches all the args.targets.
Find a container.
Find the dependencies of the CWL document.
Convert a single input schema into an example.
Generate an example input object for the given CWL process.
Copy down requirements and hints from ancestors of a given process.
Relativize the location URI of a File or Directory object.
Make a template CWL input object for the give Process.
Force clean representation of 'null'.
Return a CWL serialization of the CWL document in JSON.
Recursively find targets for --subgraph and friends.
Print a JSON representation of the dependencies of the CWL document.
Replace references to named typed with the actual types.
Run cwltool.
Prepare a LoadingContext from the given arguments.
See if we are running on MS Windows and warn about the lack of support.
Entry point for cwltool.
!/usr/bin/env python3 PYTHON_ARGCOMPLETE_OK nosec part of setuptools It's possible that another thread will spawn a new task while we're executing, so it's not safe to use a for loop here. Try to be nice nosec nosec Always kill, even if we tried with the cidfile type: CWLObjectType array of just an enum then list all the options type: Dict[str, str] type: List[str] type: ContextType type: CWLObjectType ALLUPDATES and UPDATES are dicts Log cwltool command line options to provenance file pylint: disable=unused-argument force UTF-8 even if the console is configured differently type: ignore type: List[str] If caller parsed its own arguments, it may not include every cwltool option, so fill in defaults to avoid crashing when dereferencing them in args. Can't really be combined with args.pack at same time If on MacOS platform, TMPDIR must be set to be under one of the shared volumes in Docker for Mac More info: https://dockstore.org/docs/faq type: JobExecutor type: CWLObjectType str str Unsetting the Generation from final output object pylint: disable=broad-except Stop logging so we won't half-log adding ourself to RO Ensure last log lines are written out Underlying WritableBagFile will add the tagfile to the manifest Why not use prov_log_handler.stream ? That is not part of the public API for logging.StreamHandler | 3,041 | en | 0.831436 |
from scrapy import Spider
from scrapy.spiders import CrawlSpider, Rule
from scrapy.selector import Selector
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.linkextractors import LinkExtractor
import scrapy
from scrapy.spidermiddlewares.httperror import HttpError
from twisted.internet.error import DNSLookupError
from twisted.internet.error import TimeoutError, TCPTimedOutError
from UW_Madison.items import UwMadisonItem
class Madison_courses( CrawlSpider ):
name = 'uw_madison5'
allowed_domains = ['wisc.edu']
start_urls = [
"http://guide.wisc.edu/courses/",
]
rules = (
Rule( LinkExtractor( allow = ( r'ttp://guide.wisc.edu/courses/' )),
callback = 'parse_httpbin',
follow = True
),
)
'''
def start_requests( self ):
for u in self.start_urls:
yield scrapy.Request( u, callback = self.parse_httpbin,
errback = self.errback_httpbin,
dont_filter = True )
'''
def parse_httpbin( self, response ):
#self.logger.info("Got successful response {}".format(response.url) )
items = UwMadisonItem()
course = response.css('span.courseblockcode::text').extract()
#course = response.css('span.courseblockcode::text').extract_first()
title = response.css('div.sc_sccoursedescs > div.courseblock > p.courseblocktitle > strong::text').extract()
#title = response.css('div.sc_sccoursedescs > div.courseblock > p.courseblocktitle > strong::text').extract_first()
unit = response.css('.courseblockcredits::text').extract()
#unit = response.css('.courseblockcredits::text').extract_first()
description = response.css('.courseblockdesc::text').extract()
#description = response.css('.courseblockdesc::text').extract_first()
prerequisites = response.css('p.courseblockextra.noindent.clearfix > span.cbextra-data > .bubblelink::text').extract()
#prerequisites = response.css('p.courseblockextra.noindent.clearfix > span.cbextra-data > .bubblelink::text').extract_first()
items['course'] = course
items['title'] = title
items['unit'] = unit
items['description'] = description
items['prerequisites'] = prerequisites
yield items
'''
def errback_httpbin( self, failure):
# log all failures
self.logger.error(repr(failure))
# in case you want to do something special for some errors,
# you may need the failure's type:
if failure.check(HttpError):
# These exception come from HttpError spider middleware
# you can get the non-200 response
response = failure.value.response
self.logger.error("HttpError on %s", response.url )
elif failure.check(DNSLookupError):
# This is the original request
request = failure.request
self.logger.error('DNSLookupError on %s', request.url )
elif failure.check(TimeoutError, TCPTimeOutError ):
request = failure.request
self.logger.error('TimeoutError on %s', request.url)
'''
| UW_Madison/UW_Madison/spiders/uw_madison_courses3.py | 3,358 | self.logger.info("Got successful response {}".format(response.url) )course = response.css('span.courseblockcode::text').extract_first()title = response.css('div.sc_sccoursedescs > div.courseblock > p.courseblocktitle > strong::text').extract_first()unit = response.css('.courseblockcredits::text').extract_first()description = response.css('.courseblockdesc::text').extract_first()prerequisites = response.css('p.courseblockextra.noindent.clearfix > span.cbextra-data > .bubblelink::text').extract_first() | 506 | en | 0.321796 |
import unittest
import pandas as pd
import numpy as np
from resources.backend_scripts.is_data import DataEnsurer
from resources.backend_scripts.load_data import LoaderCreator
from resources.backend_scripts.split_data import SplitterReturner
class MyTestCase(unittest.TestCase):
_loader_creator = LoaderCreator()
def test_single_split_columns_match(self):
# load diabetes.csv from disk
folder_name = "datasets"
file_name = "diabetes.csv"
test_full_path = ".\\..\\" + folder_name + "\\" + file_name
csv_type = self._loader_creator.create_loader(test_full_path, "CSV")
df = csv_type.get_file_transformed()
expected_y_len, expected_x_len = df.shape # true prediction and data len with shape method
# shape returns original column value. x doesn't have prediction column, so it must be original value - 1
expected_x_len -= 1
# use of splitterReturner with a NormalSplitter implementation
splitter = SplitterReturner()
x, y = splitter.split_x_y_from_df(df)
# do the values match in both x and y dataframes
self.assertEqual(len(x.columns), expected_x_len)
self.assertEqual(len(y), expected_y_len)
def test_single_split_returns_a_tuple(self):
# load diabetes.csv from disk
folder_name = "datasets"
file_name = "diabetes.csv"
test_full_path = ".\\..\\" + folder_name + "\\" + file_name
csv_type = self._loader_creator.create_loader(test_full_path, "CSV")
df = csv_type.get_file_transformed()
# use of splitterReturner with a NormalSplitter implementation
splitter = SplitterReturner()
# split dataframe into x and y
data = splitter.split_x_y_from_df(df)
result = DataEnsurer.validate_py_data(data, tuple)
self.assertTrue(result)
def test_single_split_x_and_y_is_a_dataframe_and_numpy_array(self):
# load diabetes.csv from disk
folder_name = "datasets"
file_name = "diabetes.csv"
test_full_path = ".\\..\\" + folder_name + "\\" + file_name
csv_type = self._loader_creator.create_loader(test_full_path, "CSV")
df = csv_type.get_file_transformed()
# use of splitterReturner with a NormalSplitter implementation
splitter = SplitterReturner()
# split dataframe into x and y
data = splitter.split_x_y_from_df(df)
results = [isinstance(data[0], pd.DataFrame), isinstance(data[-1], np.ndarray)]
# are all outputs True?
for r in results:
self.assertTrue(r)
def test_train_test_split_size_zero_is_wrong(self):
# load diabetes.csv from disk
folder_name = "datasets"
file_name = "diabetes.csv"
test_full_path = ".\\..\\" + folder_name + "\\" + file_name
csv_type = self._loader_creator.create_loader(test_full_path, "CSV")
df = csv_type.get_file_transformed()
# use of splitterReturner with a NormalSplitter implementation
with self.assertRaises(ValueError):
splitter = SplitterReturner()
# split dataframe into x and y, then use train_and_test_split
x, y = splitter.split_x_y_from_df(df)
_ = splitter.train_and_test_split(x, y, 0.0) # 80 percent of data should be training and the other 20 is
def test_train_test_split_size_less_than_zero_is_wrong(self):
# load diabetes.csv from disk
folder_name = "datasets"
file_name = "diabetes.csv"
test_full_path = ".\\..\\" + folder_name + "\\" + file_name
csv_type = self._loader_creator.create_loader(test_full_path, "CSV")
df = csv_type.get_file_transformed()
# this should raise a ValueError because size = -0.5 is not a valid number
with self.assertRaises(ValueError):
# use of splitterReturner with a NormalSplitter implementation
splitter = SplitterReturner()
# split dataframe into x and y, then use train_and_test_split
x, y = splitter.split_x_y_from_df(df)
_ = splitter.train_and_test_split(x, y, -0.5) # -0.5 is not a valid value
def test_split_into_x_and_y_is_not_a_valid_dataframe(self):
# dummy dictionary
temp_dict = {'x': [i for i in range(200)]}
# transform dictionary to dataframe
df = pd.DataFrame.from_dict(temp_dict)
# this should raise a TypeError because dataframe doesnt meet column requirements
with self.assertRaises(TypeError):
splitter = SplitterReturner()
_, _ = splitter.split_x_y_from_df(df)
if __name__ == '__main__':
unittest.main()
| AppVoor/tests/split_data_test.py | 4,673 | load diabetes.csv from disk true prediction and data len with shape method shape returns original column value. x doesn't have prediction column, so it must be original value - 1 use of splitterReturner with a NormalSplitter implementation do the values match in both x and y dataframes load diabetes.csv from disk use of splitterReturner with a NormalSplitter implementation split dataframe into x and y load diabetes.csv from disk use of splitterReturner with a NormalSplitter implementation split dataframe into x and y are all outputs True? load diabetes.csv from disk use of splitterReturner with a NormalSplitter implementation split dataframe into x and y, then use train_and_test_split 80 percent of data should be training and the other 20 is load diabetes.csv from disk this should raise a ValueError because size = -0.5 is not a valid number use of splitterReturner with a NormalSplitter implementation split dataframe into x and y, then use train_and_test_split -0.5 is not a valid value dummy dictionary transform dictionary to dataframe this should raise a TypeError because dataframe doesnt meet column requirements | 1,130 | en | 0.701944 |
import sys
import os
import json
import re
import numpy as np
import pandas as pd
from Bio import motifs
from Bio import SeqIO
from Bio.Alphabet import IUPAC
from io import StringIO
def build_mfmd_command(inputFilePath, motiflen, prb):
if not os.path.exists('/kb/module/work/tmp/mfmd'):
os.mkdir('/kb/module/work/tmp/mfmd')
outputFilePath = '/kb/module/work/tmp/mfmd/mfmd_out/mfmd_output.txt'
command = 'java -jar mfmd.jar ' + inputFilePath + ' ' + parameter + ' ' + prb + ' > ' + outputFilePath
return command
def run_mfmd_command(command):
os.system(command)
def parse_mfmd_output(path):
pfmList = []
pfmDict={}
outputFileList = []
pfmMatrix=False
seqflag=False
motifList={}
motifDict={}
locList=[]
alphabet=['A','C','G','T']
motifSet=[]
motifList['Condition']='temp'
motifList['SequenceSet_ref']='123'
background={}
background['A']=0.0
background['C']=0.0
background['G']=0.0
background['T']=0.0
motifDict['Motif_Locations'] = []
motifDict['PWM'] = []
motifDict['PFM'] = []
motiflen=0
a=[]
c=[]
g=[]
t=[]
pwmList=[]
pwmDict={}
rowList = []
rowDict={}
for filename in os.listdir(path):
outputFileList.append(path + '/' + filename)
if(filename=="mfmd_out.txt"):
outputFilePath=path+'/'+filename
mfmdFile = open(outputFilePath,'r')
for line in mfmdFile:
if(re.search("PPM Matrix",line)):
pfmMatrix=True
if(pfmMatrix):
if(line[0].isdigit()):
line=line.strip()
out=line.split()
pfmList.append(out)
a.append(out[0])
c.append(out[1])
g.append(out[2])
t.append(out[3])
rowList = []
rowList.append(('A',float(out[0])))
rowList.append(('C',float(out[1])))
rowList.append(('G',float(out[2])))
rowList.append(('T',float(out[3])))
rowDict['A']=float(out[0])
rowDict['C']=float(out[1])
rowDict['G']=float(out[2])
rowDict['T']=float(out[3])
if(re.search("PSSM Matrix",line)):
pfmMatrix=False
if(re.search("Sequences",line)):
seqflag=True
if(seqflag==True):
line=line.strip()
if(re.search('\*',line)):
seqflag=False
if((line) and not (line.startswith("Seq")) and not (line.startswith("*"))):
line=line.rstrip()
seq=line.split()
seqid=seq[0]
seq_start=int(seq[1])
seq_end=int(seq_start)+int(motiflen)
sequence=seq[2]
orientation='+'
locDict={}
locDict['sequence_id']=seqid;
locDict['start']=seq_start;
locDict['end']=seq_end;
locDict['sequence']=sequence;
locDict['orientation']=orientation;
motifDict['Motif_Locations'].append(locDict)
if(re.search("Width",line)):
arr=line.split(" ")
motiflen=arr[1].split("\t")[0]
a=[float(x) for x in a]
c=[float(x) for x in c]
g=[float(x) for x in g]
t=[float(x) for x in t]
pwmDict['A']=a
pwmDict['C']=c
pwmDict['G']=g
pwmDict['T']=t
pfmDict['A']=[]
pfmDict['C']=[]
pfmDict['G']=[]
pfmDict['T']=[]
motifStr = '>test\n'
motifStr += 'A ' + str(a).replace(',','') + '\n'
motifStr += 'C ' + str(c).replace(',','') + '\n'
motifStr += 'G ' + str(g).replace(',','') + '\n'
motifStr += 'T ' + str(t).replace(',','') + '\n'
handle = StringIO(motifStr)
BioMotif = motifs.read(handle, 'jaspar')
motifDict['PWM']=pwmDict
motifDict['PFM']=pfmDict
motifDict['Iupac_sequence']=str(BioMotif.degenerate_consensus)
motifSet.append(motifDict) #keep in loop for multiple motifs
motifList['Motifs']=motifSet
motifList['Background']=background
motifList['Alphabet']=alphabet
return motifList
output=parse_mfmd_output("/home/manish/Desktop/Data/motifs/man4ish_guptamfmd/test_local/workdir/tmp/mfmd_out")
jsondata = json.dumps(output)
with open('ReportMotif.json', 'w') as outfile:
json.dump(output, outfile)
print(jsondata)
#print(output)
| lib/MotifFindermfmd/Utils/obsolete/parser.py | 5,677 | keep in loop for multiple motifsprint(output) | 45 | en | 0.638019 |
# coding=utf-8
# Copyright 2021 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Datasets of the Open Images Challange 2019.
https://storage.googleapis.com/openimages/web/challenge2019.html
"""
import abc
import tensorflow.compat.v2 as tf
import tensorflow_datasets.public_api as tfds
_DESCRIPTION = """\
Open Images is a collaborative release of ~9 million images annotated with
image-level labels, object bounding boxes, object segmentation masks, and
visual relationships. This uniquely large and diverse dataset is designed to
spur state of the art advances in analyzing and understanding images.
"""
_DESCRIPTION_DETECTION = """\
This contains the data from thee Object Detection track of the competition.
The goal in this track is to predict a tight bounding box around all object
instances of 500 classes.
The images are annotated with positive image-level labels, indicating certain
object classes are present, and with negative image-level labels, indicating
certain classes are absent. In the competition, all other unannotated classes
are excluded from evaluation in that image. For each positive image-level label
in an image, every instance of that object class in the image was annotated.
"""
_URL = "https://storage.googleapis.com/openimages/web/challenge2019.html"
_GOOGLE_URL_PREFIX = (
"https://storage.googleapis.com/openimages/challenge_2019/challenge-2019-")
_FIGURE_EIGHT_BASE_URL = (
"https://datasets.figure-eight.com/figure_eight_datasets/open-images/")
_TRAIN_IMAGES_URLS = [
"{}zip_files_copy/train_{:02d}.zip".format(_FIGURE_EIGHT_BASE_URL, n)
for n in range(9)
]
_VALIDATION_IMAGES_URL = (
_FIGURE_EIGHT_BASE_URL + "zip_files_copy/validation.zip")
_TEST_IMAGES_URL = _FIGURE_EIGHT_BASE_URL + "test_challenge.zip"
_NUM_CLASSES = 500
class OpenImagesChallenge2019Config(tfds.core.BuilderConfig):
"""BuilderConfig for OpenImages Challenge 2019 datasets."""
def __init__(self, target_pixels=None, **kwargs):
kwargs.setdefault("version", tfds.core.Version("1.0.0"))
super(OpenImagesChallenge2019Config, self).__init__(**kwargs)
self._target_pixels = target_pixels
@property
def target_pixels(self):
return self._target_pixels
class _OpenImagesChallenge2019(tfds.core.BeamBasedBuilder):
"""Base abstract class for Open Images Challenge 2019 datasets."""
BUILDER_CONFIGS = [
OpenImagesChallenge2019Config(
name="200k",
description="Images have at most 200,000 pixels, at 72 JPEG quality.",
target_pixels=200000),
OpenImagesChallenge2019Config(
name="300k",
description="Images have at most 300,000 pixels, at 72 JPEG quality.",
target_pixels=300000),
]
@property
@abc.abstractmethod
def annotation_urls(self):
"""Dictionary passed to the DownloadManager to download annotations.
An example:
{"test_annotations": "https://somewebpage.com/data/openimages/test.txt"}
Returns:
A dictionary whose values are the URLs to download the annotations of the
dataset, and the keys are some short string identifying the URL.
This dictionary is passed to the DownloadManager.
"""
def _split_generators(self, dl_manager):
urls = {
"train_images": _TRAIN_IMAGES_URLS,
"test_images": [_TEST_IMAGES_URL],
"validation_images": [_VALIDATION_IMAGES_URL]
}
urls.update(self.annotation_urls)
paths = dl_manager.download(urls)
return [
tfds.core.SplitGenerator(
name=tfds.Split.TRAIN,
gen_kwargs=dict(paths=paths, split="train"),
),
tfds.core.SplitGenerator(
name=tfds.Split.TEST,
gen_kwargs=dict(paths=paths, split="test"),
),
tfds.core.SplitGenerator(
name=tfds.Split.VALIDATION,
gen_kwargs=dict(paths=paths, split="validation"),
),
]
class OpenImagesChallenge2019Detection(_OpenImagesChallenge2019):
"""Dataset for the Detection Track."""
@property
def annotation_urls(self):
return {
"train_image_label":
_GOOGLE_URL_PREFIX + "train-detection-human-imagelabels.csv",
"train_boxes":
_GOOGLE_URL_PREFIX + "train-detection-bbox.csv",
"validation_image_label":
_GOOGLE_URL_PREFIX + "validation-detection-human-imagelabels.csv",
"validation_boxes":
_GOOGLE_URL_PREFIX + "validation-detection-bbox.csv",
"classes":
_GOOGLE_URL_PREFIX + "classes-description-500.csv",
"hierarchy":
_GOOGLE_URL_PREFIX + "label500-hierarchy.json",
}
def _info(self):
label = tfds.features.ClassLabel(num_classes=_NUM_CLASSES)
return tfds.core.DatasetInfo(
builder=self,
description=_DESCRIPTION + "\n\n" + _DESCRIPTION_DETECTION,
features=tfds.features.FeaturesDict({
"id":
tfds.features.Text(),
"image":
tfds.features.Image(),
# A sequence of image-level labels.
"objects":
tfds.features.Sequence({
"label": label,
# All labels have been verified by humans.
# - If confidence is 1.0, the object IS in the image.
# - If confidence is 0.0, the object is NOT in the image.
"confidence": tf.float32,
"source": tfds.features.Text(),
}),
# A sequence of bounding boxes.
"bobjects":
tfds.features.Sequence({
"label": label,
"bbox": tfds.features.BBoxFeature(),
"is_group_of": tf.bool,
}),
}),
homepage=_URL,
)
def _build_pcollection(self, pipeline, paths, split):
beam = tfds.core.lazy_imports.apache_beam
# We need to lazily import the oi_beam module (and thus, violate the
# "imports only at the top" rule), so that beam is only required during the
# generation of the dataset, and not to use the dataset itself (once built).
# See: https://www.tensorflow.org/datasets/beam_datasets.
import tensorflow_datasets.object_detection.open_images_challenge2019_beam as oi_beam # pylint: disable=g-import-not-at-top,import-outside-toplevel
if split == "test":
# Note: annotations are not available for the test split.
generate_examples_kwargs = dict(
image_labels_filepath=None,
box_labels_filepath=None,
hierarchy_filepath=None,
classes_filepath=None,
)
else:
generate_examples_kwargs = dict(
image_labels_filepath=paths["{}_image_label".format(split)],
box_labels_filepath=paths["{}_boxes".format(split)],
hierarchy_filepath=paths["hierarchy"],
classes_filepath=paths["classes"],
)
# Fill class names after the data has been downloaded.
oi_beam.fill_class_names_in_tfds_info(paths["classes"], self.info.features)
return (pipeline | beam.Create(paths["{}_images".format(split)])
| "ReadImages" >> beam.ParDo(oi_beam.ReadZipFn())
| "ProcessImages" >> beam.ParDo(
oi_beam.ProcessImageFn(
target_pixels=self.builder_config.target_pixels,
jpeg_quality=72))
| "GenerateExamples" >> beam.ParDo(
oi_beam.CreateDetectionExampleFn(**generate_examples_kwargs)))
| tensorflow_datasets/object_detection/open_images_challenge2019.py | 8,015 | BuilderConfig for OpenImages Challenge 2019 datasets.
Dataset for the Detection Track.
Base abstract class for Open Images Challenge 2019 datasets.
Dictionary passed to the DownloadManager to download annotations.
An example:
{"test_annotations": "https://somewebpage.com/data/openimages/test.txt"}
Returns:
A dictionary whose values are the URLs to download the annotations of the
dataset, and the keys are some short string identifying the URL.
This dictionary is passed to the DownloadManager.
Datasets of the Open Images Challange 2019.
https://storage.googleapis.com/openimages/web/challenge2019.html
coding=utf-8 Copyright 2021 The TensorFlow Datasets Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. A sequence of image-level labels. All labels have been verified by humans. - If confidence is 1.0, the object IS in the image. - If confidence is 0.0, the object is NOT in the image. A sequence of bounding boxes. We need to lazily import the oi_beam module (and thus, violate the "imports only at the top" rule), so that beam is only required during the generation of the dataset, and not to use the dataset itself (once built). See: https://www.tensorflow.org/datasets/beam_datasets. pylint: disable=g-import-not-at-top,import-outside-toplevel Note: annotations are not available for the test split. Fill class names after the data has been downloaded. | 1,857 | en | 0.831136 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2021-10-02 20:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0017_user_email_subscribed'),
]
operations = [
migrations.CreateModel(
name='LoginRequest',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ip', models.CharField(max_length=30)),
('latestRequest', models.DateTimeField()),
('login_tries', models.IntegerField(default=1)),
],
),
]
| user/migrations/0018_loginrequest.py | 707 | -*- coding: utf-8 -*- Generated by Django 1.11.28 on 2021-10-02 20:31 | 69 | en | 0.715421 |
import logging
from typing import Text, List, Optional, Dict, Any
from rasa.nlu.config import RasaNLUModelConfig
from rasa.nlu.training_data import TrainingData, Message
from rasa.nlu.components import Component
from rasa.nlu.constants import (
RESPONSE_ATTRIBUTE,
TEXT_ATTRIBUTE,
CLS_TOKEN,
TOKENS_NAMES,
MESSAGE_ATTRIBUTES,
INTENT_ATTRIBUTE,
)
logger = logging.getLogger(__name__)
class Token(object):
def __init__(
self,
text: Text,
start: int,
data: Optional[Dict[Text, Any]] = None,
lemma: Optional[Text] = None,
end: Optional[int] = None,
) -> None:
self.start = start
self.text = text
self.end = start + len(text)
self.data = data if data else {}
self.lemma = lemma or text
self.end = end if end else start + len(text)
def set(self, prop: Text, info: Any) -> None:
self.data[prop] = info
def get(self, prop: Text, default: Optional[Any] = None) -> Any:
return self.data.get(prop, default)
def __eq__(self, other):
if not isinstance(other, Token):
return NotImplemented
return (self.start, self.end, self.text, self.lemma) == (
other.start,
other.end,
other.text,
other.lemma,
)
def __lt__(self, other):
if not isinstance(other, Token):
return NotImplemented
return (self.start, self.end, self.text, self.lemma) < (
other.start,
other.end,
other.text,
other.lemma,
)
class Tokenizer(Component):
def __init__(self, component_config: Dict[Text, Any] = None) -> None:
"""Construct a new tokenizer using the WhitespaceTokenizer framework."""
super().__init__(component_config)
# flag to check whether to split intents
self.intent_tokenization_flag = self.component_config.get(
"intent_tokenization_flag", False
)
# split symbol for intents
self.intent_split_symbol = self.component_config.get("intent_split_symbol", "_")
def tokenize(self, message: Message, attribute: Text) -> List[Token]:
"""Tokenizes the text of the provided attribute of the incoming message."""
raise NotImplementedError
def train(
self,
training_data: TrainingData,
config: Optional[RasaNLUModelConfig] = None,
**kwargs: Any,
) -> None:
"""Tokenize all training data."""
for example in training_data.training_examples:
for attribute in MESSAGE_ATTRIBUTES:
if example.get(attribute) is not None:
if attribute == INTENT_ATTRIBUTE:
tokens = self._split_intent(example)
else:
tokens = self.tokenize(example, attribute)
tokens = self.add_cls_token(tokens, attribute)
example.set(TOKENS_NAMES[attribute], tokens)
def process(self, message: Message, **kwargs: Any) -> None:
"""Tokenize the incoming message."""
tokens = self.tokenize(message, TEXT_ATTRIBUTE)
tokens = self.add_cls_token(tokens, TEXT_ATTRIBUTE)
message.set(TOKENS_NAMES[TEXT_ATTRIBUTE], tokens)
def _split_intent(self, message: Message):
text = message.get(INTENT_ATTRIBUTE)
words = (
text.split(self.intent_split_symbol)
if self.intent_tokenization_flag
else [text]
)
return self._convert_words_to_tokens(words, text)
@staticmethod
def _convert_words_to_tokens(words: List[Text], text: Text) -> List[Token]:
running_offset = 0
tokens = []
for word in words:
word_offset = text.index(word, running_offset)
word_len = len(word)
running_offset = word_offset + word_len
tokens.append(Token(word, word_offset))
return tokens
@staticmethod
def add_cls_token(tokens: List[Token], attribute: Text) -> List[Token]:
if attribute in [RESPONSE_ATTRIBUTE, TEXT_ATTRIBUTE] and tokens:
# +1 to have a space between the last token and the __cls__ token
idx = tokens[-1].end + 1
tokens.append(Token(CLS_TOKEN, idx))
return tokens
| rasa/nlu/tokenizers/tokenizer.py | 4,367 | Construct a new tokenizer using the WhitespaceTokenizer framework.
Tokenize the incoming message.
Tokenizes the text of the provided attribute of the incoming message.
Tokenize all training data.
flag to check whether to split intents split symbol for intents +1 to have a space between the last token and the __cls__ token | 325 | en | 0.668973 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-04 21:24
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('registration', '0013_eventresult_scoresubmittedby'),
]
operations = [
migrations.AddField(
model_name='eventresult',
name='timeStamp',
field=models.DateTimeField(default=django.utils.timezone.now, editable=False),
),
]
| registration/migrations/0014_eventresult_timestamp.py | 541 | -*- coding: utf-8 -*- Generated by Django 1.10.5 on 2017-02-04 21:24 | 68 | en | 0.589463 |
# Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Internal dispatcher for training loops."""
import contextlib
import os.path
import pprint
import time
from typing import Any, Callable, Dict, List, Optional
from absl import logging
import tensorflow as tf
import tensorflow_federated as tff
class IterativeProcessCompatibilityError(TypeError):
pass
def create_if_not_exists(path):
try:
tf.io.gfile.makedirs(path)
except tf.errors.OpError:
logging.info('Skipping creation of directory [%s], already exists', path)
def _setup_outputs(root_output_dir,
experiment_name,
rounds_per_profile=0):
"""Set up directories for experiment loops, write hyperparameters to disk."""
if not experiment_name:
raise ValueError('experiment_name must be specified.')
create_if_not_exists(root_output_dir)
checkpoint_dir = os.path.join(root_output_dir, 'checkpoints', experiment_name)
create_if_not_exists(checkpoint_dir)
checkpoint_mngr = tff.simulation.FileCheckpointManager(checkpoint_dir)
results_dir = os.path.join(root_output_dir, 'results', experiment_name)
create_if_not_exists(results_dir)
csv_file = os.path.join(results_dir, 'experiment.metrics.csv')
metrics_mngr = tff.simulation.CSVMetricsManager(csv_file)
summary_logdir = os.path.join(root_output_dir, 'logdir', experiment_name)
tb_mngr = tff.simulation.TensorBoardManager(summary_dir=summary_logdir)
logging.info('Writing...')
logging.info(' checkpoints to: %s', checkpoint_dir)
logging.info(' metrics csv to: %s', metrics_mngr.metrics_filename)
logging.info(' summaries to: %s', summary_logdir)
@contextlib.contextmanager
def profiler(round_num):
if (rounds_per_profile > 0 and round_num % rounds_per_profile == 0):
with tf.profiler.experimental.Profile(summary_logdir):
yield
else:
yield
return checkpoint_mngr, metrics_mngr, tb_mngr, profiler
def _write_metrics(metrics_mngr, tb_mngr, metrics, round_num):
"""Atomic metrics writer which inlines logic from MetricsHook class."""
if not isinstance(metrics, dict):
raise TypeError('metrics should be type `dict`.')
if not isinstance(round_num, int):
raise TypeError('round_num should be type `int`.')
logging.info('Metrics at round {:d}:\n{!s}'.format(round_num,
pprint.pformat(metrics)))
metrics_mngr.save_metrics(metrics, round_num)
tb_mngr.save_metrics(metrics, round_num)
def _compute_numpy_l2_difference(model, previous_model):
squared_norms = tf.nest.map_structure(lambda x, y: tf.linalg.norm(x - y)**2,
model, previous_model)
l2_total_tensor = tf.reduce_sum(tf.nest.flatten(squared_norms))**0.5
return l2_total_tensor.numpy()
def _check_iterative_process_compatibility(iterative_process):
"""Checks the compatibility of an iterative process with the training loop."""
error_message = (
'The iterative_process argument must be of '
'type`tff.templates.IterativeProcess`, and must have an '
'attribute `get_model_weights`, which must be a `tff.Computation`. This '
'computation must accept as input the state of `iterative_process`, and '
'its output must be a nested structure of tensors matching the input '
'shape of `validation_fn`.')
compatibility_error = IterativeProcessCompatibilityError(error_message)
if not isinstance(iterative_process, tff.templates.IterativeProcess):
raise compatibility_error
if not hasattr(iterative_process, 'get_model_weights'):
raise compatibility_error
elif not callable(iterative_process.get_model_weights):
raise compatibility_error
get_model_weights_fn = iterative_process.get_model_weights
if not isinstance(get_model_weights_fn, tff.Computation):
raise compatibility_error
input_type = get_model_weights_fn.type_signature.parameter
server_state_type = iterative_process.state_type.member
server_state_type.is_assignable_from(input_type)
# TODO(b/174268978): Once we enforce federated evaluations, we can check
# compatibility with `validation_fn` without actually running the function.
def run(iterative_process: tff.templates.IterativeProcess,
client_datasets_fn: Callable[[int], List[tf.data.Dataset]],
validation_fn: Callable[[Any, int], Dict[str, float]],
total_rounds: int,
experiment_name: str,
test_fn: Optional[Callable[[Any], Dict[str, float]]] = None,
root_output_dir: Optional[str] = '/tmp/fed_opt',
rounds_per_eval: Optional[int] = 1,
rounds_per_checkpoint: Optional[int] = 50,
rounds_per_profile: Optional[int] = 0):
"""Runs federated training for a given `tff.templates.IterativeProcess`.
We assume that the iterative process has the following functional type
signatures:
* `initialize`: `( -> S@SERVER)` where `S` represents the server state.
* `next`: `<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>` where `S`
represents the server state, `{B*}` represents the client datasets,
and `T` represents a python `Mapping` object.
The iterative process must also have a callable attribute `get_model_weights`
that takes as input the state of the iterative process, and returns a
`tff.learning.ModelWeights` object.
Args:
iterative_process: A `tff.templates.IterativeProcess` instance to run.
client_datasets_fn: Function accepting an integer argument (the round
number) and returning a list of client datasets to use as federated data
for that round.
validation_fn: A callable accepting a `tff.learning.ModelWeights` and the
current round number, and returning a dict of evaluation metrics. Used to
compute validation metrics throughout the training process.
total_rounds: The number of federated training rounds to perform.
experiment_name: The name of the experiment being run. This will be appended
to the `root_output_dir` for purposes of writing outputs.
test_fn: An optional callable accepting a `tff.learning.ModelWeights` and
returning a dict of test set metrics. Used to compute test metrics at the
end of the training process.
root_output_dir: The name of the root output directory for writing
experiment outputs.
rounds_per_eval: How often to compute validation metrics.
rounds_per_checkpoint: How often to checkpoint the iterative process state.
If you expect the job to restart frequently, this should be small. If no
interruptions are expected, this can be made larger.
rounds_per_profile: Experimental setting. If set to a value greater than 0,
this dictates how often a TensorFlow profiler is run.
Returns:
The final `state` of the iterative process after training.
"""
_check_iterative_process_compatibility(iterative_process)
if not callable(client_datasets_fn):
raise TypeError('client_datasets_fn should be callable.')
if not callable(validation_fn):
raise TypeError('validation_fn should be callable.')
if test_fn is not None and not callable(test_fn):
raise TypeError('test_fn should be callable.')
logging.info('Starting iterative_process training loop...')
initial_state = iterative_process.initialize()
checkpoint_mngr, metrics_mngr, tb_mngr, profiler = _setup_outputs(
root_output_dir, experiment_name, rounds_per_profile)
logging.info('Asking checkpoint manager to load checkpoint.')
state, round_num = checkpoint_mngr.load_latest_checkpoint(initial_state)
if state is None:
logging.info('Initializing experiment from scratch.')
state = initial_state
round_num = 0
else:
logging.info('Restarted from checkpoint round %d', round_num)
round_num += 1 # Increment to avoid overwriting current checkpoint
metrics_mngr.clear_metrics(round_num)
current_model = iterative_process.get_model_weights(state)
loop_start_time = time.time()
loop_start_round = round_num
while round_num < total_rounds:
data_prep_start_time = time.time()
federated_train_data = client_datasets_fn(round_num)
train_metrics = {
'prepare_datasets_secs': time.time() - data_prep_start_time
}
training_start_time = time.time()
prev_model = current_model
# TODO(b/145604851): This try/except is used to circumvent ambiguous TF
# errors during training, and should be removed once the root cause is
# determined (and possibly fixed).
try:
with profiler(round_num):
state, round_metrics = iterative_process.next(state,
federated_train_data)
except (tf.errors.FailedPreconditionError, tf.errors.NotFoundError,
tf.errors.InternalError) as e:
logging.warning('Caught %s exception while running round %d:\n\t%s',
type(e), round_num, e)
continue # restart the loop without incrementing the round number
current_model = iterative_process.get_model_weights(state)
train_metrics['training_secs'] = time.time() - training_start_time
train_metrics['model_delta_l2_norm'] = _compute_numpy_l2_difference(
current_model, prev_model)
train_metrics['client_drift'] = state.client_drift
train_metrics.update(round_metrics)
loop_time = time.time() - loop_start_time
loop_rounds = (round_num - loop_start_round + 1)
logging.info('Round {:2d}, {:.2f}s per round in average.'.format(
round_num, loop_time / loop_rounds))
if (round_num % rounds_per_checkpoint == 0 or
round_num == total_rounds - 1):
save_checkpoint_start_time = time.time()
checkpoint_mngr.save_checkpoint(state, round_num)
train_metrics['save_checkpoint_secs'] = (
time.time() - save_checkpoint_start_time)
metrics = {'train': train_metrics}
if round_num % rounds_per_eval == 0:
# Compute validation metrics
evaluate_start_time = time.time()
validation_metrics = validation_fn(current_model, round_num)
validation_metrics['evaluate_secs'] = time.time() - evaluate_start_time
metrics['eval'] = validation_metrics
_write_metrics(metrics_mngr, tb_mngr, metrics, round_num)
round_num += 1
# Final metrics evaluation once the training has completed
metrics = {}
# Validation metrics
evaluate_start_time = time.time()
validation_metrics = validation_fn(current_model, round_num)
validation_metrics['evaluate_secs'] = time.time() - evaluate_start_time
metrics['eval'] = validation_metrics
# Test set metrics
if test_fn:
test_start_time = time.time()
test_metrics = test_fn(current_model)
test_metrics['evaluate_secs'] = time.time() - test_start_time
metrics['test'] = test_metrics
_write_metrics(metrics_mngr, tb_mngr, metrics, total_rounds)
return state
| utils/training_loop.py | 11,381 | Checks the compatibility of an iterative process with the training loop.
Set up directories for experiment loops, write hyperparameters to disk.
Atomic metrics writer which inlines logic from MetricsHook class.
Runs federated training for a given `tff.templates.IterativeProcess`.
We assume that the iterative process has the following functional type
signatures:
* `initialize`: `( -> S@SERVER)` where `S` represents the server state.
* `next`: `<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>` where `S`
represents the server state, `{B*}` represents the client datasets,
and `T` represents a python `Mapping` object.
The iterative process must also have a callable attribute `get_model_weights`
that takes as input the state of the iterative process, and returns a
`tff.learning.ModelWeights` object.
Args:
iterative_process: A `tff.templates.IterativeProcess` instance to run.
client_datasets_fn: Function accepting an integer argument (the round
number) and returning a list of client datasets to use as federated data
for that round.
validation_fn: A callable accepting a `tff.learning.ModelWeights` and the
current round number, and returning a dict of evaluation metrics. Used to
compute validation metrics throughout the training process.
total_rounds: The number of federated training rounds to perform.
experiment_name: The name of the experiment being run. This will be appended
to the `root_output_dir` for purposes of writing outputs.
test_fn: An optional callable accepting a `tff.learning.ModelWeights` and
returning a dict of test set metrics. Used to compute test metrics at the
end of the training process.
root_output_dir: The name of the root output directory for writing
experiment outputs.
rounds_per_eval: How often to compute validation metrics.
rounds_per_checkpoint: How often to checkpoint the iterative process state.
If you expect the job to restart frequently, this should be small. If no
interruptions are expected, this can be made larger.
rounds_per_profile: Experimental setting. If set to a value greater than 0,
this dictates how often a TensorFlow profiler is run.
Returns:
The final `state` of the iterative process after training.
Internal dispatcher for training loops.
Copyright 2019, Google LLC. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. TODO(b/174268978): Once we enforce federated evaluations, we can check compatibility with `validation_fn` without actually running the function. Increment to avoid overwriting current checkpoint TODO(b/145604851): This try/except is used to circumvent ambiguous TF errors during training, and should be removed once the root cause is determined (and possibly fixed). restart the loop without incrementing the round number Compute validation metrics Final metrics evaluation once the training has completed Validation metrics Test set metrics | 3,397 | en | 0.84904 |
def setup_inp(inp):
"""Convert list of strings into list of lists, with glves/goblins replaced by tuples"""
grid = []
for rowI,row in enumerate(inp.split("\n")):
grid.append([x for x in row])
for colI,col in enumerate(row):
if col in ["G","E"]:
#Replace enemies with tuples so we can track them - (character_type, hit_points, moved_already_bool)
char_tup = (col, 200, False)
grid[rowI][colI] = char_tup
return grid
def print_board(inp):
for row in inp:
extra = []
print_row = [] #In case we append hitpoints
for char in row:
if isinstance(char,tuple):
print_row.append(char[0])
extra.append(str(char[1]))
else:
print_row.append(char)
print("".join(print_row)," ", " ".join(extra))
def move_character(inp, from_row, from_col, to_row, to_col, char):
"""Move character on grid, and increment the i value so we can tell we already moved it"""
inp[from_row][from_col] = "."
inp[to_row][to_col] = (char[0],char[1],True)
return inp
def attack(inp, row, col, enemy, damage=3):
"""
Attack weakest adjacent enemy, if one is there
If multiple weakest enemies, attack in reading order
Return the modified board, and a boolean indicating whether anyone died
"""
if not adjacent_enemy(inp, row, col, enemy):
return inp, False
#Create a dict of {coordinates: hp} for each adjacent enemy
enemies = {}
for coords in [(row-1,col), (row+1,col), (row,col-1), (row,col+1)]:
if inp[coords[0]][coords[1]][0] == enemy:
#enemy is a tuple, (char_type, hp, already_moved_bool)
enemies[coords] = inp[coords[0]][coords[1]][1]
#Filter to only the enemies with minimum hp
min_hp = min(enemies.values())
enemies = [x for x in enemies if enemies[x]==min_hp]
#Now we have a list of coordinates, we can sort to get reading order, then take the first to get our enemy
enemies.sort()
coords = enemies[0]
enemy = inp[coords[0]][coords[1]]
enemy_pts = enemy[1] - damage
enemy_tup = (enemy[0], enemy_pts, enemy[2])
#Check for killed
if enemy_pts <= 0:
inp[coords[0]][coords[1]] = "."
return inp, True
else:
inp[coords[0]][coords[1]] = enemy_tup
return inp, False
def adjacent_enemy(inp, rowI, colI, enemy):
"""Check for enemy in adjacent square"""
if any(x[0]==enemy for x in [inp[rowI+1][colI], inp[rowI-1][colI], inp[rowI][colI+1], inp[rowI][colI-1]]):
return True
return False
def get_best_move(best_moves):
"""
Takes a list of tuples of
(first_move, number_of_moves, tile_coordinates), which might look like -
((12, 22), 8, (17, 25))
((12, 22), 8, (18, 24))
((12, 22), 8, (19, 21))
((13, 21), 6, (19, 21))
((13, 23), 6, (17, 25))
((13, 23), 6, (18, 24))
((14, 22), 6, (17, 25))
((14, 22), 6, (18, 24))
((14, 22), 6, (19, 21))
And filters/sorts them to satisfy all the conditions
"""
if not best_moves:
return None
#First condition - fewest number of moves away
min_steps = min([x[1] for x in best_moves])
best_moves = [x for x in best_moves if x[1]==min_steps]
#Second condition - if tie, choose the first tile in reading order
best_moves.sort(key = lambda x:x[2])
best_moves = [x for x in best_moves if x[2]==best_moves[0][2]]
#Third condition - if tie, take the first step in reading order
best_moves.sort(key = lambda x:x[0])
best_moves = [x for x in best_moves if x[0]==best_moves[0][0]]
return best_moves[0][0]
def count_characters(inp):
seen = {"G":0,"E":0}
for row in inp:
for col in row:
if col[0] in ["G","E"]:
seen[col[0]]+=1
return seen
def bfs_move(inp, rowI, colI, hero, enemy):
"""
Perform a breadth first search for each adjacent tile
Although not the most efficient, the approach is still fast and makes it
easy to sort in such a way that satisfies all the conditions
"""
#If an enemy is located adjacent to our current location - no move!
if adjacent_enemy(inp, rowI, colI, enemy):
return None
first_moves = [(rowI+1,colI),(rowI-1,colI),(rowI,colI-1),(rowI,colI+1)]
#Filter down to valid first moves - must be a '.' there
first_moves = [x for x in first_moves if inp[x[0]][x[1]]=="."]
#Keep the list of tuples nearest tiles we've found, in format -
#(first_move, number_of_moves, tile_coordinates)
#At the end we'll need to use all these values to find the proper move
best_moves = []
for move in first_moves:
r,c = move
#We might immediately have an adjacent enemy and not need to search further
if adjacent_enemy(inp, r, c, enemy):
best_moves.append((move, 1, move))
continue
#We'll need to keep track of two things -
#seen_coordinates - the tiles we've already visited
#stack - the "new" tiles accessible from the current furthest points
seen_coordinates = {(rowI,colI),(r,c)}
stack = [(r+1,c),(r-1,c),(r,c-1),(r,c+1)]
#Filter stack to only include "." tiles, which we haven't already seen
stack = [x for x in stack if inp[x[0]][x[1]]=="." and (x[0],x[1]) not in seen_coordinates]
#Now do the search -
i=1 #Already have moved one tile at this point
run = True
while run:
i+=1
#Keep track of the new tiles here
new_stack = []
#Loop through and look for new tiles to add
for tile in stack:
if tile in seen_coordinates:
continue
seen_coordinates.add(tile)
r,c = tile
if adjacent_enemy(inp, r, c, enemy):
best_moves.append((move,i,(r,c)))
#We want to complete this iteration to find all other reachable tiles at the same distance
run = False
continue
#Add all newly accessible tiles to stack
new_tiles = [(r+1,c),(r-1,c),(r,c-1),(r,c+1)]
new_stack += [x for x in new_tiles if inp[x[0]][x[1]]=="." and (x[0],x[1]) not in seen_coordinates]
stack = list(set(new_stack))
#We might also need to end at this point if we have no more newly accessible tiles
if not stack:
run = False
#Take our list of the best_moves from each starting point that we generated, and find the one move we'll take
return get_best_move(best_moves)
def score_game(inp, rounds):
pts = 0
for rowI,row in enumerate(inp):
for colI,col in enumerate(row):
if col[0] in ["G","E"]:
pts+=col[1]
return rounds*pts
def reset_moved_bools(inp):
"""Reset the third value in our character tuples, which tracks whether they've moved in a round"""
for rowI,row in enumerate(inp):
for colI,col in enumerate(row):
if col[0] in ["G","E"]:
char_tup = (col[0],col[1],False)
inp[rowI][colI] = char_tup
return inp
t0 = """#######
#.G...#
#...EG#
#.#.#G#
#..G#E#
#.....#
#######"""
t1 = """#######
#G..#E#
#E#E.E#
#G.##.#
#...#E#
#...E.#
#######"""
t2 = """#######
#E..EG#
#.#G.E#
#E.##E#
#G..#.#
#..E#.#
#######"""
t3 = """#######
#E.G#.#
#.#G..#
#G.#.G#
#G..#.#
#...E.#
#######"""
t4 = """#######
#.E...#
#.#..G#
#.###.#
#E#G#G#
#...#G#
#######"""
t5 = """#########
#G......#
#.E.#...#
#..##..G#
#...##..#
#...#...#
#.G...G.#
#.....G.#
#########"""
def problem1(inp, print_=False):
grid = setup_inp(inp)
rounds = 0
while True:
#Count the current number of each character type
#We can use this to determine if the game has ended in the middle or end of a round
counts = count_characters(grid)
seen = {}
for rowI,row in enumerate(grid):
for colI,col in enumerate(row):
char = grid[rowI][colI]
if isinstance(char, tuple):
#Indicates we already moved it this round
if char[2]:
continue
r,c = rowI,colI #Keep track of our current coordinates in case we move
hero = char[0]
enemy = "G" if hero=="E" else "E"
counts[hero]-=1
move_to = bfs_move(grid, rowI, colI, hero, enemy)
if move_to:
r,c = move_to #Need to update our current coordinates for the impending attack
grid = move_character(grid, rowI, colI, r, c, char)
grid, death = attack(grid, r, c, enemy)
if death:
#Check to see if it's over - all of one side dead
current_counts = count_characters(grid)
game_over = any(x==0 for x in current_counts.values())
#If game is over, we need to see if the round is complete or not
if game_over:
#Means we ended midround
if counts[hero]>0:
final_score = score_game(grid, rounds)
#Otherwise round is complete- add 1 to rounds when calculating
else:
rounds+=1
final_score = score_game(grid, rounds)
if print_:
print("GAME ENDED",rounds)
print_board(grid)
return final_score
#Reset the variable that tracks whether a character has moved in a round
grid = reset_moved_bools(grid)
rounds += 1
if print_:
print(rounds)
print_board(grid)
def problem2_loop(inp, damage_dict, print_=False):
grid = setup_inp(inp)
rounds = 0
while True:
#Count the current number of each character type
#We can use this to determine if the game has ended in the middle or end of a round
counts = count_characters(grid)
seen = {}
for rowI,row in enumerate(grid):
for colI,col in enumerate(row):
char = grid[rowI][colI]
if isinstance(char, tuple):
#Indicates we already moved it this round
if char[2]:
continue
r,c = rowI,colI #Keep track of our current coordinates in case we move
hero = char[0]
enemy = "G" if hero=="E" else "E"
counts[hero]-=1
move_to = bfs_move(grid, rowI, colI, hero, enemy)
if move_to:
r,c = move_to #Need to update our current coordinates for the impending attack
grid = move_character(grid, rowI, colI, r, c, char)
damage = damage_dict[hero]
grid, death = attack(grid, r, c, enemy, damage)
if death and enemy=="E":
#FAILED
return False
#If goblin death, same logic as before
elif death:
#Check to see if it's over - all of one side dead
current_counts = count_characters(grid)
game_over = any(x==0 for x in current_counts.values())
#If game is over, we need to see if the round is complete or not
if game_over:
#Means we ended midround
if counts[hero]>0:
final_score = score_game(grid, rounds)
#Otherwise round is complete- add 1 to rounds when calculating
else:
rounds+=1
final_score = score_game(grid, rounds)
if print_:
print("GAME ENDED",rounds)
print_board(grid)
return final_score
#Reset the variable that tracks whether a character has moved in a round
grid = reset_moved_bools(grid)
rounds += 1
if print_:
print(rounds)
print_board(grid)
def problem2(inp, print_=False):
score = False
damage_dict = {"G":3, "E":3}
while not score:
damage_dict["E"] += 1
print("Elf power", damage_dict["E"])
score = problem2_loop(inp, damage_dict, print_)
return score
if __name__=="__main__":
with open("input15.txt","r") as f:
data = f.read().strip()
for row in data.split("\n"):
print(row)
assert problem1(t0)==27730
assert problem1(t1)==36334
assert problem1(t2)==39514
assert problem1(t3)==27755
assert problem1(t4)==28944
assert problem1(t5)==18740
print(problem1(data))
print(problem2(data)) | 2018/15/helpme.py | 13,744 | Check for enemy in adjacent square
Attack weakest adjacent enemy, if one is there
If multiple weakest enemies, attack in reading order
Return the modified board, and a boolean indicating whether anyone died
Perform a breadth first search for each adjacent tile
Although not the most efficient, the approach is still fast and makes it
easy to sort in such a way that satisfies all the conditions
Takes a list of tuples of
(first_move, number_of_moves, tile_coordinates), which might look like -
((12, 22), 8, (17, 25))
((12, 22), 8, (18, 24))
((12, 22), 8, (19, 21))
((13, 21), 6, (19, 21))
((13, 23), 6, (17, 25))
((13, 23), 6, (18, 24))
((14, 22), 6, (17, 25))
((14, 22), 6, (18, 24))
((14, 22), 6, (19, 21))
And filters/sorts them to satisfy all the conditions
Move character on grid, and increment the i value so we can tell we already moved it
Reset the third value in our character tuples, which tracks whether they've moved in a round
Convert list of strings into list of lists, with glves/goblins replaced by tuples
Replace enemies with tuples so we can track them - (character_type, hit_points, moved_already_bool)In case we append hitpointsCreate a dict of {coordinates: hp} for each adjacent enemyenemy is a tuple, (char_type, hp, already_moved_bool)Filter to only the enemies with minimum hpNow we have a list of coordinates, we can sort to get reading order, then take the first to get our enemyCheck for killedFirst condition - fewest number of moves awaySecond condition - if tie, choose the first tile in reading orderThird condition - if tie, take the first step in reading orderIf an enemy is located adjacent to our current location - no move!Filter down to valid first moves - must be a '.' thereKeep the list of tuples nearest tiles we've found, in format -(first_move, number_of_moves, tile_coordinates)At the end we'll need to use all these values to find the proper moveWe might immediately have an adjacent enemy and not need to search furtherWe'll need to keep track of two things -seen_coordinates - the tiles we've already visitedstack - the "new" tiles accessible from the current furthest pointsFilter stack to only include "." tiles, which we haven't already seenNow do the search -Already have moved one tile at this pointKeep track of the new tiles hereLoop through and look for new tiles to addWe want to complete this iteration to find all other reachable tiles at the same distanceAdd all newly accessible tiles to stackWe might also need to end at this point if we have no more newly accessible tilesTake our list of the best_moves from each starting point that we generated, and find the one move we'll takeCount the current number of each character typeWe can use this to determine if the game has ended in the middle or end of a roundIndicates we already moved it this roundKeep track of our current coordinates in case we moveNeed to update our current coordinates for the impending attackCheck to see if it's over - all of one side deadIf game is over, we need to see if the round is complete or notMeans we ended midroundOtherwise round is complete- add 1 to rounds when calculatingReset the variable that tracks whether a character has moved in a roundCount the current number of each character typeWe can use this to determine if the game has ended in the middle or end of a roundIndicates we already moved it this roundKeep track of our current coordinates in case we moveNeed to update our current coordinates for the impending attackFAILEDIf goblin death, same logic as beforeCheck to see if it's over - all of one side deadIf game is over, we need to see if the round is complete or notMeans we ended midroundOtherwise round is complete- add 1 to rounds when calculatingReset the variable that tracks whether a character has moved in a round | 3,790 | en | 0.899012 |
#!/usr/bin/env python3
import math
import csv
import itertools
from pprint import pprint
import func
INPUTFILE = './task04.input'
def main():
accept = 0
with open(INPUTFILE, mode='r') as csvfile:
reader = csv.reader(csvfile, delimiter=" ")
lines = list(reader)
for line in lines:
reject_line = False
for word in line:
if line.count(word) > 1:
reject_line = True
break
if not reject_line:
accept = accept + 1
print("file {} has {} lines".format(INPUTFILE, len(lines)))
print("we accept {} of them".format(accept))
if __name__ == '__main__':
main()
| task04_a.py | 738 | !/usr/bin/env python3 | 21 | fr | 0.448822 |
# Date 3/10/2020
# __Author__ : AdityaLata
# __Package__ : Python 3
# __GitHub__ : https://www.github.com/adityalata
from Python.DataStructure.TreeDS.Node import Node
# A utility function to check if 'c' is an operator
def isOperator(c):
if c == '+' or c == '-' or c == '*' or c == '/' or c == '^':
return True
else:
return False
# Returns root of constructed tree for given postfix expression string
def getExpressionTree(postfix):
stack = []
# Traverse through every character of input expression
for char in postfix:
# for space separated postfix
if char == " ":
continue
# if operand, simply push into stack
elif not isOperator(char):
t = Node(char)
stack.append(t)
# Operator
else:
# Pop two top nodes
t = Node(char)
t1 = stack.pop()
t2 = stack.pop()
# make them children
t.right = t1
t.left = t2
# Add this subexpression to stack
stack.append(t)
# Only element will be the root of expression tree
t = stack.pop()
return t
# Returns value evaluated from given root of valid(full binary tree) expression tree
def evaluateExpressionTree(rootNode):
# empty tree
if rootNode is None:
return 0
# leaf node
if rootNode.left is None and rootNode.right is None:
return int(rootNode.value)
# evaluate left tree
leftSubtreeValue = evaluateExpressionTree(rootNode.left)
# evaluate right tree
rightSubtreeValue = evaluateExpressionTree(rootNode.right)
# check which operation to apply on non leaf node
if rootNode.value == '+':
return leftSubtreeValue + rightSubtreeValue
elif rootNode.value == '-':
return leftSubtreeValue - rightSubtreeValue
elif rootNode.value == '*':
return leftSubtreeValue * rightSubtreeValue
elif rootNode.value == '^':
return leftSubtreeValue ** rightSubtreeValue
elif rootNode.value == '/':
return leftSubtreeValue / rightSubtreeValue
| Python/DataStructure/TreeDS/ExpressionTree.py | 2,147 | Date 3/10/2020 __Author__ : AdityaLata __Package__ : Python 3 __GitHub__ : https://www.github.com/adityalata A utility function to check if 'c' is an operator Returns root of constructed tree for given postfix expression string Traverse through every character of input expression for space separated postfix if operand, simply push into stack Operator Pop two top nodes make them children Add this subexpression to stack Only element will be the root of expression tree Returns value evaluated from given root of valid(full binary tree) expression tree empty tree leaf node evaluate left tree evaluate right tree check which operation to apply on non leaf node | 673 | en | 0.720372 |
# Copyright (c) 2019 by LatentAI Inc.
# All rights reserved.
# This file is part of the LEIP(tm) SDK,
# and is released under the "LatentAI Commercial Software License".
# Please see the LICENSE file that should have been included as part of
# this package.
#
# @file tf_inference.py
#
# @author Videet Parekh
#
# @date Wed 16 Dec 20
#
# @brief TF inference engine designed with the same interface as leip_inference for parallel comparison
# from time import time
# import tensorflow as tf
import glob
import os
import logging
import utils.common_utils as utils
import argparse
import numpy as np
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
# tf.debugging.set_log_device_placement(True)
class TFModel():
def __init__(self, base_path, context, config):
self.context = context
self.config = config
self.load(base_path)
def load(self, base):
h5_path = glob.glob(os.path.join(base, '*.h5'))[0]
self.model = utils.load_keras_model(h5_path)
def infer(self, data):
# Here's how you may measure runtime speed
# start = time()
output_data = self.model.predict(data)
# end = time()
pred = {'label': output_data}
return pred
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--input_path', type=str, default=None, required=True, help='Path to model directory.')
parser.add_argument('--test_path', type=str, default=None, required=True, help='Path to output test file')
parser.add_argument('--class_names', type=str, default=None, required=True, help='Path to class names list.')
parser.add_argument('--data_type', type=str, default="float32", required=False, help='Data Type.')
parser.add_argument('--preprocessor', type=str, default="none", required=False, help='Preprocessor function')
parser.add_argument('--inference_context', type=str, default="none", required=False, help='cpu/gpu/cuda.')
parser.add_argument('--loglevel', type=str, default="WARNING", required=False, help='Logging verbosity.')
args = parser.parse_args()
base = args.input_path
test_path = args.test_path
class_names = args.class_names
data_type = args.data_type
preprocessor = args.preprocessor
context = args.inference_context
loglevel = args.loglevel
# Set Logger Parameters
logging.basicConfig(level=utils.get_numeric_loglevel(loglevel))
# Get class_names for model
with open(class_names) as f:
synset = f.readlines()
config = utils.load_json(os.path.join(base, 'model_schema.json'))
config['input_shapes'] = utils.parse_input_shapes(config['input_shapes'])
# Load dataset and collect preprocessor function
data_index = utils.load_index(test_path)
preprocessor = utils.collect_preprocessor(preprocessor)
# Create model object for inference
model = TFModel(base, context, config)
acc = 0
# Loop over data and call infer()
for data in data_index:
# Load and preprocess image
img = utils.collect_image(data[0], data_type, preprocessor, config['input_shapes'])
# Infer
pred = model.infer(img)
pred_label = np.argmax(pred['label'])
acc += 1 if pred_label == data[1] else 0
print(acc*100/len(data_index))
| inference/tf_inference.py | 3,401 | Copyright (c) 2019 by LatentAI Inc. All rights reserved. This file is part of the LEIP(tm) SDK, and is released under the "LatentAI Commercial Software License". Please see the LICENSE file that should have been included as part of this package. @file tf_inference.py @author Videet Parekh @date Wed 16 Dec 20 @brief TF inference engine designed with the same interface as leip_inference for parallel comparison from time import time import tensorflow as tf print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU'))) tf.debugging.set_log_device_placement(True) Here's how you may measure runtime speed start = time() end = time() Set Logger Parameters Get class_names for model Load dataset and collect preprocessor function Create model object for inference Loop over data and call infer() Load and preprocess image Infer | 865 | en | 0.818275 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
評価用のテストパターン作成ツール集
"""
import os
import cv2
import matplotlib.pyplot as plt
import numpy as np
from colour.colorimetry import CMFS, ILLUMINANTS
from colour.models import XYZ_to_xy, xy_to_XYZ, XYZ_to_RGB, RGB_to_XYZ
from colour.models import xy_to_xyY, xyY_to_XYZ, Lab_to_XYZ
from colour.models import BT709_COLOURSPACE
from colour.utilities import normalise_maximum
from colour import models
from colour import RGB_COLOURSPACES, COLOURCHECKERS
from scipy.spatial import Delaunay
from scipy.ndimage.filters import convolve
import math
import transfer_functions as tf
CMFS_NAME = 'CIE 1931 2 Degree Standard Observer'
D65_WHITE = ILLUMINANTS[CMFS_NAME]['D65']
YCBCR_CHECK_MARKER = [0, 0, 0]
UNIVERSAL_COLOR_LIST = ["#F6AA00", "#FFF100", "#03AF7A",
"#005AFF", "#4DC4FF", "#804000"]
def preview_image(img, order='rgb', over_disp=False):
if order == 'rgb':
cv2.imshow('preview', img[:, :, ::-1])
elif order == 'bgr':
cv2.imshow('preview', img)
elif order == 'mono':
cv2.imshow('preview', img)
else:
raise ValueError("order parameter is invalid")
if over_disp:
cv2.resizeWindow('preview', )
cv2.waitKey(0)
cv2.destroyAllWindows()
def equal_devision(length, div_num):
"""
# 概要
length を div_num で分割する。
端数が出た場合は誤差拡散法を使って上手い具合に分散させる。
"""
base = length / div_num
ret_array = [base for x in range(div_num)]
# 誤差拡散法を使った辻褄合わせを適用
# -------------------------------------------
diff = 0
for idx in range(div_num):
diff += math.modf(ret_array[idx])[0]
if diff >= 1.0:
diff -= 1.0
ret_array[idx] = int(math.floor(ret_array[idx]) + 1)
else:
ret_array[idx] = int(math.floor(ret_array[idx]))
# 計算誤差により最終点が +1 されない場合への対処
# -------------------------------------------
diff = length - sum(ret_array)
if diff != 0:
ret_array[-1] += diff
# 最終確認
# -------------------------------------------
if length != sum(ret_array):
raise ValueError("the output of equal_division() is abnormal.")
return ret_array
def do_matrix(img, mtx):
"""
img に対して mtx を適用する。
"""
base_shape = img.shape
r, g, b = img[..., 0], img[..., 1], img[..., 2]
ro = r * mtx[0][0] + g * mtx[0][1] + b * mtx[0][2]
go = r * mtx[1][0] + g * mtx[1][1] + b * mtx[1][2]
bo = r * mtx[2][0] + g * mtx[2][1] + b * mtx[2][2]
out_img = np.dstack((ro, go, bo)).reshape(base_shape)
return out_img
def _get_cmfs_xy():
"""
xy色度図のプロットのための馬蹄形の外枠のxy値を求める。
Returns
-------
array_like
xy coordinate for chromaticity diagram
"""
# 基本パラメータ設定
# ------------------
cmf = CMFS.get(CMFS_NAME)
d65_white = D65_WHITE
# 馬蹄形のxy値を算出
# --------------------------
cmf_xy = XYZ_to_xy(cmf.values, d65_white)
return cmf_xy
def get_primaries(name='ITU-R BT.2020'):
"""
prmary color の座標を求める
Parameters
----------
name : str
a name of the color space.
Returns
-------
array_like
prmaries. [[rx, ry], [gx, gy], [bx, by], [rx, ry]]
"""
primaries = RGB_COLOURSPACES[name].primaries
primaries = np.append(primaries, [primaries[0, :]], axis=0)
rgb = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])
return primaries, rgb
def xy_to_rgb(xy, name='ITU-R BT.2020', normalize='maximum', specific=None):
"""
xy値からRGB値を算出する。
いい感じに正規化もしておく。
Parameters
----------
xy : array_like
xy value.
name : string
color space name.
normalize : string
normalize method. You can select 'maximum', 'specific' or None.
Returns
-------
array_like
rgb value. the value is normalized.
"""
illuminant_XYZ = D65_WHITE
illuminant_RGB = D65_WHITE
chromatic_adaptation_transform = 'CAT02'
large_xyz_to_rgb_matrix = get_xyz_to_rgb_matrix(name)
if normalize == 'specific':
xyY = xy_to_xyY(xy)
xyY[..., 2] = specific
large_xyz = xyY_to_XYZ(xyY)
else:
large_xyz = xy_to_XYZ(xy)
rgb = XYZ_to_RGB(large_xyz, illuminant_XYZ, illuminant_RGB,
large_xyz_to_rgb_matrix,
chromatic_adaptation_transform)
"""
そのままだとビデオレベルが低かったりするので、
各ドット毎にRGB値を正規化&最大化する。必要であれば。
"""
if normalize == 'maximum':
rgb = normalise_maximum(rgb, axis=-1)
else:
if(np.sum(rgb > 1.0) > 0):
print("warning: over flow has occured at xy_to_rgb")
if(np.sum(rgb < 0.0) > 0):
print("warning: under flow has occured at xy_to_rgb")
rgb[rgb < 0] = 0
rgb[rgb > 1.0] = 1.0
return rgb
def get_white_point(name):
"""
white point を求める。CIE1931ベース。
"""
if name != "DCI-P3":
illuminant = RGB_COLOURSPACES[name].illuminant
white_point = ILLUMINANTS[CMFS_NAME][illuminant]
else:
white_point = ILLUMINANTS[CMFS_NAME]["D65"]
return white_point
def get_secondaries(name='ITU-R BT.2020'):
"""
secondary color の座標を求める
Parameters
----------
name : str
a name of the color space.
Returns
-------
array_like
secondaries. the order is magenta, yellow, cyan.
"""
secondary_rgb = np.array([[1.0, 0.0, 1.0],
[1.0, 1.0, 0.0],
[0.0, 1.0, 1.0]])
illuminant_XYZ = D65_WHITE
illuminant_RGB = D65_WHITE
chromatic_adaptation_transform = 'CAT02'
rgb_to_xyz_matrix = get_rgb_to_xyz_matrix(name)
large_xyz = RGB_to_XYZ(secondary_rgb, illuminant_RGB,
illuminant_XYZ, rgb_to_xyz_matrix,
chromatic_adaptation_transform)
xy = XYZ_to_xy(large_xyz, illuminant_XYZ)
return xy, secondary_rgb.reshape((3, 3))
# def plot_chromaticity_diagram(
# rate=480/755.0*2, xmin=0.0, xmax=0.8, ymin=0.0, ymax=0.9, **kwargs):
# # キーワード引数の初期値設定
# # ------------------------------------
# monitor_primaries = kwargs.get('monitor_primaries', None)
# secondaries = kwargs.get('secondaries', None)
# test_scatter = kwargs.get('test_scatter', None)
# intersection = kwargs.get('intersection', None)
# # プロット用データ準備
# # ---------------------------------
# xy_image = get_chromaticity_image(
# xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax)
# cmf_xy = _get_cmfs_xy()
# bt709_gamut, _ = get_primaries(name=cs.BT709)
# bt2020_gamut, _ = get_primaries(name=cs.BT2020)
# dci_p3_gamut, _ = get_primaries(name=cs.P3_D65)
# ap0_gamut, _ = get_primaries(name=cs.ACES_AP0)
# ap1_gamut, _ = get_primaries(name=cs.ACES_AP1)
# xlim = (min(0, xmin), max(0.8, xmax))
# ylim = (min(0, ymin), max(0.9, ymax))
# ax1 = pu.plot_1_graph(fontsize=20 * rate,
# figsize=((xmax - xmin) * 10 * rate,
# (ymax - ymin) * 10 * rate),
# graph_title="CIE1931 Chromaticity Diagram",
# graph_title_size=None,
# xlabel=None, ylabel=None,
# axis_label_size=None,
# legend_size=18 * rate,
# xlim=xlim, ylim=ylim,
# xtick=[x * 0.1 + xmin for x in
# range(int((xlim[1] - xlim[0])/0.1) + 1)],
# ytick=[x * 0.1 + ymin for x in
# range(int((ylim[1] - ylim[0])/0.1) + 1)],
# xtick_size=17 * rate,
# ytick_size=17 * rate,
# linewidth=4 * rate,
# minor_xtick_num=2,
# minor_ytick_num=2)
# ax1.plot(cmf_xy[..., 0], cmf_xy[..., 1], '-k', lw=3.5*rate, label=None)
# ax1.plot((cmf_xy[-1, 0], cmf_xy[0, 0]), (cmf_xy[-1, 1], cmf_xy[0, 1]),
# '-k', lw=3.5*rate, label=None)
# ax1.plot(bt709_gamut[:, 0], bt709_gamut[:, 1],
# c=UNIVERSAL_COLOR_LIST[0], label="BT.709", lw=2.75*rate)
# ax1.plot(bt2020_gamut[:, 0], bt2020_gamut[:, 1],
# c=UNIVERSAL_COLOR_LIST[1], label="BT.2020", lw=2.75*rate)
# ax1.plot(dci_p3_gamut[:, 0], dci_p3_gamut[:, 1],
# c=UNIVERSAL_COLOR_LIST[2], label="DCI-P3", lw=2.75*rate)
# ax1.plot(ap1_gamut[:, 0], ap1_gamut[:, 1],
# c=UNIVERSAL_COLOR_LIST[3], label="ACES AP1", lw=2.75*rate)
# ax1.plot(ap0_gamut[:, 0], ap0_gamut[:, 1],
# c=UNIVERSAL_COLOR_LIST[4], label="ACES AP0", lw=2.75*rate)
# if monitor_primaries is not None:
# ax1.plot(monitor_primaries[:, 0], monitor_primaries[:, 1],
# c="#202020", label="???", lw=3*rate)
# if secondaries is not None:
# xy, rgb = secondaries
# ax1.scatter(xy[..., 0], xy[..., 1], s=700*rate, marker='s', c=rgb,
# edgecolors='#404000', linewidth=2*rate)
# if test_scatter is not None:
# xy, rgb = test_scatter
# ax1.scatter(xy[..., 0], xy[..., 1], s=300*rate, marker='s', c=rgb,
# edgecolors='#404040', linewidth=2*rate)
# if intersection is not None:
# ax1.scatter(intersection[..., 0], intersection[..., 1],
# s=300*rate, marker='s', c='#CCCCCC',
# edgecolors='#404040', linewidth=2*rate)
# ax1.imshow(xy_image, extent=(xmin, xmax, ymin, ymax))
# plt.legend(loc='upper right')
# plt.savefig('temp_fig.png', bbox_inches='tight')
# plt.show()
def get_chromaticity_image(samples=1024, antialiasing=True, bg_color=0.9,
xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0):
"""
xy色度図の馬蹄形の画像を生成する
Returns
-------
ndarray
rgb image.
"""
"""
色域設定。sRGBだと狭くて少し変だったのでBT.2020に設定。
若干色が薄くなるのが難点。暇があれば改良したい。
"""
# color_space = models.BT2020_COLOURSPACE
# color_space = models.S_GAMUT3_COLOURSPACE
color_space = models.ACES_CG_COLOURSPACE
# 馬蹄形のxy値を算出
# --------------------------
cmf_xy = _get_cmfs_xy()
"""
馬蹄の内外の判別をするために三角形で領域分割する(ドロネー図を作成)。
ドロネー図を作れば後は外積計算で領域の内外を判別できる(たぶん)。
なお、作成したドロネー図は以下のコードでプロット可能。
1点補足しておくと、```plt.triplot``` の第三引数は、
第一、第二引数から三角形を作成するための **インデックス** のリスト
になっている。[[0, 1, 2], [2, 4, 3], ...]的な。
```python
plt.figure()
plt.triplot(xy[:, 0], xy[:, 1], triangulation.simplices.copy(), '-o')
plt.title('triplot of Delaunay triangulation')
plt.show()
```
"""
triangulation = Delaunay(cmf_xy)
"""
```triangulation.find_simplex()``` で xy がどのインデックスの領域か
調べることができる。戻り値が ```-1``` の場合は領域に含まれないため、
0以下のリストで領域判定の mask を作ることができる。
"""
xx, yy\
= np.meshgrid(np.linspace(xmin, xmax, samples),
np.linspace(ymax, ymin, samples))
xy = np.dstack((xx, yy))
mask = (triangulation.find_simplex(xy) < 0).astype(np.float)
# アンチエイリアシングしてアルファチャンネルを滑らかに
# ------------------------------------------------
if antialiasing:
kernel = np.array([
[0, 1, 0],
[1, 2, 1],
[0, 1, 0],
]).astype(np.float)
kernel /= np.sum(kernel)
mask = convolve(mask, kernel)
# ネガポジ反転
# --------------------------------
mask = 1 - mask[:, :, np.newaxis]
# xy のメッシュから色を復元
# ------------------------
illuminant_XYZ = D65_WHITE
illuminant_RGB = color_space.whitepoint
chromatic_adaptation_transform = 'XYZ Scaling'
large_xyz_to_rgb_matrix = color_space.XYZ_to_RGB_matrix
xy[xy == 0.0] = 1.0 # ゼロ割対策
large_xyz = xy_to_XYZ(xy)
rgb = XYZ_to_RGB(large_xyz, illuminant_XYZ, illuminant_RGB,
large_xyz_to_rgb_matrix,
chromatic_adaptation_transform)
"""
そのままだとビデオレベルが低かったりするので、
各ドット毎にRGB値を正規化&最大化する。
"""
rgb[rgb == 0] = 1.0 # ゼロ割対策
rgb = normalise_maximum(rgb, axis=-1)
# mask 適用
# -------------------------------------
mask_rgb = np.dstack((mask, mask, mask))
rgb *= mask_rgb
# 背景色をグレーに変更
# -------------------------------------
bg_rgb = np.ones_like(rgb)
bg_rgb *= (1 - mask_rgb) * bg_color
rgb += bg_rgb
rgb = rgb ** (1/2.2)
return rgb
def get_csf_color_image(width=640, height=480,
lv1=np.uint16(np.array([1.0, 1.0, 1.0]) * 1023 * 0x40),
lv2=np.uint16(np.array([1.0, 1.0, 1.0]) * 512 * 0x40),
stripe_num=18):
"""
長方形を複数個ズラして重ねることでCSFパターンっぽいのを作る。
入力信号レベルは16bitに限定する。
Parameters
----------
width : numeric.
width of the pattern image.
height : numeric.
height of the pattern image.
lv1 : numeric
video level 1. this value must be 10bit.
lv2 : numeric
video level 2. this value must be 10bit.
stripe_num : numeric
number of the stripe.
Returns
-------
array_like
a cms pattern image.
"""
width_list = equal_devision(width, stripe_num)
height_list = equal_devision(height, stripe_num)
h_pos_list = equal_devision(width // 2, stripe_num)
v_pos_list = equal_devision(height // 2, stripe_num)
lv1_16bit = lv1
lv2_16bit = lv2
img = np.zeros((height, width, 3), dtype=np.uint16)
width_temp = width
height_temp = height
h_pos_temp = 0
v_pos_temp = 0
for idx in range(stripe_num):
lv = lv1_16bit if (idx % 2) == 0 else lv2_16bit
temp_img = np.ones((height_temp, width_temp, 3), dtype=np.uint16)
# temp_img *= lv
temp_img[:, :] = lv
ed_pos_h = h_pos_temp + width_temp
ed_pos_v = v_pos_temp + height_temp
img[v_pos_temp:ed_pos_v, h_pos_temp:ed_pos_h] = temp_img
width_temp -= width_list[stripe_num - 1 - idx]
height_temp -= height_list[stripe_num - 1 - idx]
h_pos_temp += h_pos_list[idx]
v_pos_temp += v_pos_list[idx]
return img
def plot_xyY_color_space(name='ITU-R BT.2020', samples=1024,
antialiasing=True):
"""
SONY の HDR説明資料にあるような xyY の図を作る。
Parameters
----------
name : str
name of the target color space.
Returns
-------
None
"""
# 馬蹄の領域判別用データ作成
# --------------------------
primary_xy, _ = get_primaries(name=name)
triangulation = Delaunay(primary_xy)
xx, yy\
= np.meshgrid(np.linspace(0, 1, samples), np.linspace(1, 0, samples))
xy = np.dstack((xx, yy))
mask = (triangulation.find_simplex(xy) < 0).astype(np.float)
# アンチエイリアシングしてアルファチャンネルを滑らかに
# ------------------------------------------------
if antialiasing:
kernel = np.array([
[0, 1, 0],
[1, 2, 1],
[0, 1, 0],
]).astype(np.float)
kernel /= np.sum(kernel)
mask = convolve(mask, kernel)
# ネガポジ反転
# --------------------------------
mask = 1 - mask[:, :, np.newaxis]
# xy のメッシュから色を復元
# ------------------------
illuminant_XYZ = D65_WHITE
illuminant_RGB = RGB_COLOURSPACES[name].whitepoint
chromatic_adaptation_transform = 'CAT02'
large_xyz_to_rgb_matrix = get_xyz_to_rgb_matrix(name)
rgb_to_large_xyz_matrix = get_rgb_to_xyz_matrix(name)
large_xyz = xy_to_XYZ(xy)
rgb = XYZ_to_RGB(large_xyz, illuminant_XYZ, illuminant_RGB,
large_xyz_to_rgb_matrix,
chromatic_adaptation_transform)
"""
そのままだとビデオレベルが低かったりするので、
各ドット毎にRGB値を正規化&最大化する。
"""
rgb_org = normalise_maximum(rgb, axis=-1)
# mask 適用
# -------------------------------------
mask_rgb = np.dstack((mask, mask, mask))
rgb = rgb_org * mask_rgb
rgba = np.dstack((rgb, mask))
# こっからもういちど XYZ に変換。Yを求めるために。
# ---------------------------------------------
large_xyz2 = RGB_to_XYZ(rgb, illuminant_RGB, illuminant_XYZ,
rgb_to_large_xyz_matrix,
chromatic_adaptation_transform)
# ログスケールに変換する準備
# --------------------------
large_y = large_xyz2[..., 1] * 1000
large_y[large_y < 1] = 1.0
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# ax.plot_wireframe(xy[..., 0], xy[..., 1], np.log10(large_y),
# rcount=100, ccount=100)
ax.plot_surface(xy[..., 0], xy[..., 1], np.log10(large_y),
rcount=64, ccount=64, facecolors=rgb_org)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("Y")
ax.set_zticks([0, 1, 2, 3])
ax.set_zticklabels([1, 10, 100, 1000])
# chromatcity_image の取得。z=0 の位置に貼り付ける
# ----------------------------------------------
cie1931_rgb = get_chromaticity_image(samples=samples, bg_color=0.0)
alpha = np.zeros_like(cie1931_rgb[..., 0])
rgb_sum = np.sum(cie1931_rgb, axis=-1)
alpha[rgb_sum > 0.00001] = 1
cie1931_rgb = np.dstack((cie1931_rgb[..., 0], cie1931_rgb[..., 1],
cie1931_rgb[..., 2], alpha))
zz = np.zeros_like(xy[..., 0])
ax.plot_surface(xy[..., 0], xy[..., 1], zz,
facecolors=cie1931_rgb)
plt.show()
def log_tick_formatter(val, pos=None):
return "{:.0e}".format(10**val)
def get_3d_grid_cube_format(grid_num=4):
"""
# 概要
(0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 0, 1), ...
みたいな配列を返す。
CUBE形式の3DLUTを作成する時に便利。
"""
base = np.linspace(0, 1, grid_num)
ones_x = np.ones((grid_num, grid_num, 1))
ones_y = np.ones((grid_num, 1, grid_num))
ones_z = np.ones((1, grid_num, grid_num))
r_3d = base[np.newaxis, np.newaxis, :] * ones_x
g_3d = base[np.newaxis, :, np.newaxis] * ones_y
b_3d = base[:, np.newaxis, np.newaxis] * ones_z
r_3d = r_3d.flatten()
g_3d = g_3d.flatten()
b_3d = b_3d.flatten()
return np.dstack((r_3d, g_3d, b_3d))
def quadratic_bezier_curve(t, p0, p1, p2, samples=1024):
# x = ((1 - t) ** 2) * p0[0] + 2 * (1 - t) * t * p1[0]\
# + (t ** 2) * p2[0]
# y = ((1 - t) ** 2) * p0[1] + 2 * (1 - t) * t * p1[1]\
# + (t ** 2) * p2[1]
x = ((1 - t) ** 2) * p0[0] + 2 * (1 - t) * t * p1[0]\
+ (t ** 2) * p2[0]
y = ((1 - t) ** 2) * p0[1] + 2 * (1 - t) * t * p1[1]\
+ (t ** 2) * p2[1]
# ax1 = pu.plot_1_graph(fontsize=20,
# figsize=(10, 8),
# graph_title="Title",
# graph_title_size=None,
# xlabel="X Axis Label", ylabel="Y Axis Label",
# axis_label_size=None,
# legend_size=17,
# xlim=None,
# ylim=None,
# xtick=None,
# ytick=None,
# xtick_size=None, ytick_size=None,
# linewidth=3,
# minor_xtick_num=None,
# minor_ytick_num=None)
# ax1.plot(x, y, label='aaa')
# plt.legend(loc='upper left')
# plt.show()
def gen_step_gradation(width=1024, height=128, step_num=17,
bit_depth=10, color=(1.0, 1.0, 1.0),
direction='h', debug=False):
"""
# 概要
階段状に変化するグラデーションパターンを作る。
なお、引数の調整により正確に1階調ずつ変化するパターンも作成可能。
# 注意事項
正確に1階調ずつ変化するグラデーションを作る場合は
```step_num = (2 ** bit_depth) + 1```
となるようにパラメータを指定すること。具体例は以下のExample参照。
# Example
```
grad_8 = gen_step_gradation(width=grad_width, height=grad_height,
step_num=257, bit_depth=8,
color=(1.0, 1.0, 1.0), direction='h')
grad_10 = gen_step_gradation(width=grad_width, height=grad_height,
step_num=1025, bit_depth=10,
color=(1.0, 1.0, 1.0), direction='h')
```
"""
max = 2 ** bit_depth
# グラデーション方向設定
# ----------------------
if direction == 'h':
pass
else:
temp = height
height = width
width = temp
if (max + 1 != step_num):
"""
1階調ずつの増加では無いパターン。
末尾のデータが 256 や 1024 になるため -1 する。
"""
val_list = np.linspace(0, max, step_num)
val_list[-1] -= 1
else:
"""
正確に1階調ずつ変化するパターン。
末尾のデータが 256 や 1024 になるため除外する。
"""
val_list = np.linspace(0, max, step_num)[0:-1]
step_num -= 1 # step_num は 引数で余計に +1 されてるので引く
# 念のため1階調ずつの変化か確認
# ---------------------------
diff = val_list[1:] - val_list[0:-1]
if (diff == 1).all():
pass
else:
raise ValueError("calculated value is invalid.")
# まずは水平1LINEのグラデーションを作る
# -----------------------------------
step_length_list = equal_devision(width, step_num)
step_bar_list = []
for step_idx, length in enumerate(step_length_list):
step = [np.ones((length)) * color[c_idx] * val_list[step_idx]
for c_idx in range(3)]
if direction == 'h':
step = np.dstack(step)
step_bar_list.append(step)
step_bar = np.hstack(step_bar_list)
else:
step = np.dstack(step).reshape((length, 1, 3))
step_bar_list.append(step)
step_bar = np.vstack(step_bar_list)
# ブロードキャストを利用して2次元に拡張する
# ------------------------------------------
if direction == 'h':
img = step_bar * np.ones((height, 1, 3))
else:
img = step_bar * np.ones((1, height, 3))
# np.uint16 にコンバート
# ------------------------------
# img = np.uint16(np.round(img * (2 ** (16 - bit_depth))))
if debug:
preview_image(img, 'rgb')
return img
def merge(img_a, img_b, pos=(0, 0)):
"""
img_a に img_b をマージする。
img_a にデータを上書きする。
pos = (horizontal_st, vertical_st)
"""
b_width = img_b.shape[1]
b_height = img_b.shape[0]
img_a[pos[1]:b_height+pos[1], pos[0]:b_width+pos[0]] = img_b
def merge_with_alpha(bg_img, fg_img, tf_str=tf.SRGB, pos=(0, 0)):
"""
合成する。
Parameters
----------
bg_img : array_like(float, 3-channel)
image data.
fg_img : array_like(float, 4-channel)
image data
tf : strings
transfer function
pos : list(int)
(pos_h, pos_v)
"""
f_width = fg_img.shape[1]
f_height = fg_img.shape[0]
bg_merge_area = bg_img[pos[1]:f_height+pos[1], pos[0]:f_width+pos[0]]
bg_linear = tf.eotf_to_luminance(bg_merge_area, tf_str)
fg_linear = tf.eotf_to_luminance(fg_img, tf_str)
alpha = fg_linear[:, :, 3:] / tf.PEAK_LUMINANCE[tf_str]
out_linear = (1 - alpha) * bg_linear + fg_linear[:, :, :-1]
out_merge_area = tf.oetf_from_luminance(out_linear, tf_str)
bg_img[pos[1]:f_height+pos[1], pos[0]:f_width+pos[0]] = out_merge_area
return bg_img
def dot_pattern(dot_size=4, repeat=4, color=np.array([1.0, 1.0, 1.0])):
"""
dot pattern 作る。
Parameters
----------
dot_size : integer
dot size.
repeat : integer
The number of high-low pairs.
color : array_like
color value.
Returns
-------
array_like
dot pattern image.
"""
# 水平・垂直のピクセル数
pixel_num = dot_size * 2 * repeat
# High-Log の 論理配列を生成
even_logic = [(np.arange(pixel_num) % (dot_size * 2)) - dot_size < 0]
even_logic = np.dstack((even_logic, even_logic, even_logic))
odd_logic = np.logical_not(even_logic)
# 着色
color = color.reshape((1, 1, 3))
even_line = (np.ones((1, pixel_num, 3)) * even_logic) * color
odd_line = (np.ones((1, pixel_num, 3)) * odd_logic) * color
# V方向にコピー&Even-Oddの結合
even_block = np.repeat(even_line, dot_size, axis=0)
odd_block = np.repeat(odd_line, dot_size, axis=0)
pair_block = np.vstack((even_block, odd_block))
img = np.vstack([pair_block for x in range(repeat)])
return img
def complex_dot_pattern(kind_num=3, whole_repeat=2,
fg_color=np.array([1.0, 1.0, 1.0]),
bg_color=np.array([0.15, 0.15, 0.15])):
"""
dot pattern 作る。
Parameters
----------
kind_num : integer
作成するドットサイズの種類。
例えば、kind_num=3 ならば、1dot, 2dot, 4dot のパターンを作成。
whole_repeat : integer
異なる複数種類のドットパターンの組数。
例えば、kind_num=3, whole_repeat=2 ならば、
1dot, 2dot, 4dot のパターンを水平・垂直に2組作る。
fg_color : array_like
foreground color value.
bg_color : array_like
background color value.
reduce : bool
HDRテストパターンの3840x2160専用。縦横を半分にする。
Returns
-------
array_like
dot pattern image.
"""
max_dot_width = 2 ** kind_num
img_list = []
for size_idx in range(kind_num)[::-1]:
dot_size = 2 ** size_idx
repeat = max_dot_width // dot_size
dot_img = dot_pattern(dot_size, repeat, fg_color)
img_list.append(dot_img)
img_list.append(np.ones_like(dot_img) * bg_color)
# preview_image(dot_img)
line_upper_img = np.hstack(img_list)
line_upper_img = np.hstack([line_upper_img for x in range(whole_repeat)])
line_lower_img = line_upper_img.copy()[:, ::-1, :]
h_unit_img = np.vstack((line_upper_img, line_lower_img))
img = np.vstack([h_unit_img for x in range(kind_num * whole_repeat)])
# preview_image(img)
# cv2.imwrite("hoge.tiff", np.uint8(img * 0xFF)[..., ::-1])
return img
def make_csf_color_image(width=640, height=640,
lv1=np.array([940, 940, 940], dtype=np.uint16),
lv2=np.array([1023, 1023, 1023], dtype=np.uint16),
stripe_num=6):
"""
長方形を複数個ズラして重ねることでCSFパターンっぽいのを作る。
入力信号レベルは10bitに限定する。
Parameters
----------
width : numeric.
width of the pattern image.
height : numeric.
height of the pattern image.
lv1 : array_like
video level 1. this value must be 10bit.
lv2 : array_like
video level 2. this value must be 10bit.
stripe_num : numeric
number of the stripe.
Returns
-------
array_like
a cms pattern image.
"""
width_list = equal_devision(width, stripe_num)
height_list = equal_devision(height, stripe_num)
h_pos_list = equal_devision(width // 2, stripe_num)
v_pos_list = equal_devision(height // 2, stripe_num)
img = np.zeros((height, width, 3), dtype=np.uint16)
width_temp = width
height_temp = height
h_pos_temp = 0
v_pos_temp = 0
for idx in range(stripe_num):
lv = lv1 if (idx % 2) == 0 else lv2
temp_img = np.ones((height_temp, width_temp, 3), dtype=np.uint16)
temp_img = temp_img * lv.reshape((1, 1, 3))
ed_pos_h = h_pos_temp + width_temp
ed_pos_v = v_pos_temp + height_temp
img[v_pos_temp:ed_pos_v, h_pos_temp:ed_pos_h] = temp_img
width_temp -= width_list[stripe_num - 1 - idx]
height_temp -= height_list[stripe_num - 1 - idx]
h_pos_temp += h_pos_list[idx]
v_pos_temp += v_pos_list[idx]
# preview_image(img / 1023)
return img
def make_tile_pattern(width=480, height=960, h_tile_num=4,
v_tile_num=4, low_level=(940, 940, 940),
high_level=(1023, 1023, 1023)):
"""
タイル状の縞々パターンを作る
"""
width_array = equal_devision(width, h_tile_num)
height_array = equal_devision(height, v_tile_num)
high_level = np.array(high_level, dtype=np.uint16)
low_level = np.array(low_level, dtype=np.uint16)
v_buf = []
for v_idx, height in enumerate(height_array):
h_buf = []
for h_idx, width in enumerate(width_array):
tile_judge = (h_idx + v_idx) % 2 == 0
h_temp = np.zeros((height, width, 3), dtype=np.uint16)
h_temp[:, :] = high_level if tile_judge else low_level
h_buf.append(h_temp)
v_buf.append(np.hstack(h_buf))
img = np.vstack(v_buf)
# preview_image(img/1024.0)
return img
def get_marker_idx(img, marker_value):
return np.all(img == marker_value, axis=-1)
def make_ycbcr_checker(height=480, v_tile_num=4):
"""
YCbCr係数誤りを確認するテストパターンを作る。
正直かなり汚い組み方です。雑に作ったパターンを悪魔合体させています。
Parameters
----------
height : numeric.
height of the pattern image.
v_tile_num : numeric
number of the tile in the vertical direction.
Note
----
横長のパターンになる。以下の式が成立する。
```
h_tile_num = v_tile_num * 2
width = height * 2
```
Returns
-------
array_like
ycbcr checker image
"""
cyan_img = make_tile_pattern(width=height, height=height,
h_tile_num=v_tile_num,
v_tile_num=v_tile_num,
low_level=[0, 990, 990],
high_level=[0, 1023, 1023])
magenta_img = make_tile_pattern(width=height, height=height,
h_tile_num=v_tile_num,
v_tile_num=v_tile_num,
low_level=[990, 0, 312],
high_level=[1023, 0, 312])
out_img = np.hstack([cyan_img, magenta_img])
# preview_image(out_img/1023.0)
return out_img
def plot_color_checker_image(rgb, rgb2=None, size=(1920, 1080),
block_size=1/4.5, padding=0.01):
"""
ColorCheckerをプロットする
Parameters
----------
rgb : array_like
RGB value of the ColorChecker.
RGB's shape must be (24, 3).
rgb2 : array_like
It's a optional parameter.
If You want to draw two different ColorCheckers,
set the RGB value to this variable.
size : tuple
canvas size.
block_size : float
A each block's size.
This value is ratio to height of the canvas.
padding : float
A padding to the block.
Returns
-------
array_like
A ColorChecker image.
"""
IMG_HEIGHT = size[1]
IMG_WIDTH = size[0]
COLOR_CHECKER_SIZE = block_size
COLOR_CHECKER_H_NUM = 6
COLOR_CHECKER_V_NUM = 4
COLOR_CHECKER_PADDING = 0.01
# 基本パラメータ算出
# --------------------------------------
COLOR_CHECKER_H_NUM = 6
COLOR_CHECKER_V_NUM = 4
img_height = IMG_HEIGHT
img_width = IMG_WIDTH
patch_st_h = int(IMG_WIDTH / 2.0
- (IMG_HEIGHT * COLOR_CHECKER_SIZE
* COLOR_CHECKER_H_NUM / 2.0
+ (IMG_HEIGHT * COLOR_CHECKER_PADDING
* (COLOR_CHECKER_H_NUM / 2.0 - 0.5)) / 2.0))
patch_st_v = int(IMG_HEIGHT / 2.0
- (IMG_HEIGHT * COLOR_CHECKER_SIZE
* COLOR_CHECKER_V_NUM / 2.0
+ (IMG_HEIGHT * COLOR_CHECKER_PADDING
* (COLOR_CHECKER_V_NUM / 2.0 - 0.5)) / 2.0))
patch_width = int(img_height * COLOR_CHECKER_SIZE)
patch_height = patch_width
patch_space = int(img_height * COLOR_CHECKER_PADDING)
# 24ループで1枚の画像に24パッチを描画
# -------------------------------------------------
img_all_patch = np.zeros((img_height, img_width, 3), dtype=np.uint8)
for idx in range(COLOR_CHECKER_H_NUM * COLOR_CHECKER_V_NUM):
v_idx = idx // COLOR_CHECKER_H_NUM
h_idx = (idx % COLOR_CHECKER_H_NUM)
patch = np.ones((patch_height, patch_width, 3))
patch[:, :] = rgb[idx]
st_h = patch_st_h + (patch_width + patch_space) * h_idx
st_v = patch_st_v + (patch_height + patch_space) * v_idx
img_all_patch[st_v:st_v+patch_height, st_h:st_h+patch_width] = patch
# pt1 = (st_h, st_v) # upper left
pt2 = (st_h + patch_width, st_v) # upper right
pt3 = (st_h, st_v + patch_height) # lower left
pt4 = (st_h + patch_width, st_v + patch_height) # lower right
pts = np.array((pt2, pt3, pt4))
sub_color = rgb[idx].tolist() if rgb2 is None else rgb2[idx].tolist()
cv2.fillPoly(img_all_patch, [pts], sub_color)
preview_image(img_all_patch)
return img_all_patch
def get_log10_x_scale(
sample_num=8, ref_val=1.0, min_exposure=-1, max_exposure=6):
"""
Log10スケールのx軸データを作る。
Examples
--------
>>> get_log2_x_scale(
... sample_num=8, ref_val=1.0, min_exposure=-1, max_exposure=6)
array([ 1.0000e-01 1.0000e+00 1.0000e+01 1.0000e+02
1.0000e+03 1.0000e+04 1.0000e+05 1.0000e+06])
"""
x_min = np.log10(ref_val * (10 ** min_exposure))
x_max = np.log10(ref_val * (10 ** max_exposure))
x = np.linspace(x_min, x_max, sample_num)
return 10.0 ** x
def get_log2_x_scale(
sample_num=32, ref_val=1.0, min_exposure=-6.5, max_exposure=6.5):
"""
Log2スケールのx軸データを作る。
Examples
--------
>>> get_log2_x_scale(sample_num=10, min_exposure=-4.0, max_exposure=4.0)
array([[ 0.0625 0.11573434 0.214311 0.39685026 0.73486725
1.36079 2.5198421 4.66611616 8.64047791 16. ]])
"""
x_min = np.log2(ref_val * (2 ** min_exposure))
x_max = np.log2(ref_val * (2 ** max_exposure))
x = np.linspace(x_min, x_max, sample_num)
return 2.0 ** x
def shaper_func_linear_to_log2(
x, mid_gray=0.18, min_exposure=-6.5, max_exposure=6.5):
"""
ACESutil.Lin_to_Log2_param.ctl を参考に作成。
https://github.com/ampas/aces-dev/blob/master/transforms/ctl/utilities/ACESutil.Lin_to_Log2_param.ctl
Parameters
----------
x : array_like
linear data.
mid_gray : float
18% gray value on linear scale.
min_exposure : float
minimum value on log scale.
max_exposure : float
maximum value on log scale.
Returns
-------
array_like
log2 value that is transformed from linear x value.
Examples
--------
>>> shaper_func_linear_to_log2(
... x=0.18, mid_gray=0.18, min_exposure=-6.5, max_exposure=6.5)
0.5
>>> shaper_func_linear_to_log2(
... x=np.array([0.00198873782209, 16.2917402385])
... mid_gray=0.18, min_exposure=-6.5, max_exposure=6.5)
array([ 1.58232402e-13 1.00000000e+00])
"""
# log2空間への変換。mid_gray が 0.0 となるように補正
y = np.log2(x / mid_gray)
# min, max の範囲で正規化。
y_normalized = (y - min_exposure) / (max_exposure - min_exposure)
y_normalized[y_normalized < 0] = 0
return y_normalized
def shaper_func_log2_to_linear(
x, mid_gray=0.18, min_exposure=-6.5, max_exposure=6.5):
"""
ACESutil.Log2_to_Lin_param.ctl を参考に作成。
https://github.com/ampas/aces-dev/blob/master/transforms/ctl/utilities/ACESutil.Log2_to_Lin_param.ctl
Log2空間の補足は shaper_func_linear_to_log2() の説明を参照
Examples
--------
>>> x = np.array([0.0, 1.0])
>>> shaper_func_log2_to_linear(
... x, mid_gray=0.18, min_exposure=-6.5, max_exposure=6.5)
array([0.00198873782209, 16.2917402385])
"""
x_re_scale = x * (max_exposure - min_exposure) + min_exposure
y = (2.0 ** x_re_scale) * mid_gray
# plt.plot(x, y)
# plt.show()
return y
def draw_straight_line(img, pt1, pt2, color, thickness):
"""
直線を引く。OpenCV だと 8bit しか対応してないっぽいので自作。
Parameters
----------
img : array_like
image data.
pt1 : list(pos_h, pos_v)
start point.
pt2 : list(pos_h, pos_v)
end point.
color : array_like
color
thickness : int
thickness.
Returns
-------
array_like
image data with line.
Notes
-----
thickness のパラメータは pt1 の点から右下方向に効きます。
pt1 を中心として太さではない事に注意。
Examples
--------
>>> pt1 = (0, 0)
>>> pt2 = (1920, 0)
>>> color = (940, 940, 940)
>>> thickness = 4
>>> draw_straight_line(img, pt1, pt2, color, thickness)
"""
# parameter check
if (pt1[0] != pt2[0]) and (pt1[1] != pt2[1]):
raise ValueError("invalid pt1, pt2 parameters")
# check direction
if pt1[0] == pt2[0]:
thickness_direction = 'h'
else:
thickness_direction = 'v'
if thickness_direction == 'h':
for h_idx in range(thickness):
img[pt1[1]:pt2[1], pt1[0] + h_idx, :] = color
elif thickness_direction == 'v':
for v_idx in range(thickness):
img[pt1[1] + v_idx, pt1[0]:pt2[0], :] = color
def draw_outline(img, fg_color, outline_width):
"""
img に対して外枠線を引く
Parameters
----------
img : array_like
image data.
fg_color : array_like
color
outline_width : int
thickness.
Returns
-------
array_like
image data with line.
Examples
--------
>>> img = np.zeros((1080, 1920, 3))
>>> color = (940, 940, 940)
>>> thickness = 2
>>> draw_outline(img, color, thickness)
"""
width = img.shape[1]
height = img.shape[0]
# upper left
pt1 = (0, 0)
pt2 = (width, 0)
draw_straight_line(
img, pt1, pt2, fg_color, outline_width)
pt1 = (0, 0)
pt2 = (0, height)
draw_straight_line(
img, pt1, pt2, fg_color, outline_width)
# lower right
pt1 = (width - outline_width, 0)
pt2 = (width - outline_width, height)
draw_straight_line(
img, pt1, pt2, fg_color, outline_width)
pt1 = (0, height - outline_width)
pt2 = (width, height - outline_width)
draw_straight_line(
img, pt1, pt2, fg_color, outline_width)
def convert_luminance_to_color_value(luminance, transfer_function):
"""
輝度[cd/m2] から code value の RGB値に変換する。
luminance の単位は [cd/m2]。無彩色である。
Examples
--------
>>> convert_luminance_to_color_value(100, tf.GAMMA24)
>>> [ 1.0 1.0 1.0 ]
>>> convert_luminance_to_color_value(100, tf.ST2084)
>>> [ 0.50807842 0.50807842 0.50807842 ]
"""
code_value = convert_luminance_to_code_value(
luminance, transfer_function)
return np.array([code_value, code_value, code_value])
def convert_luminance_to_code_value(luminance, transfer_function):
"""
輝度[cd/m2] から code value に変換する。
luminance の単位は [cd/m2]
"""
return tf.oetf_from_luminance(luminance, transfer_function)
def calc_rad_patch_idx2(outmost_num=5, current_num=3):
"""
以下のような、中心がGray、周りは CIELAB 空間の a*b*平面のカラーパッチの
RGB値のリストを得る。
https://user-images.githubusercontent.com/3609012/75444470-d3bc5600-59a6-11ea-962b-c315648782a9.png
得られたデータは並べ替えが済んでいないため、calc_rad_patch_idx2() で
得られる変換テーブルを使った変換が必要。
本関数はまさにその変換を行う。
"""
base = np.arange(outmost_num ** 2).reshape((outmost_num, outmost_num))
# print(base)
t_idx = (outmost_num - current_num) // 2
trimmed = base[t_idx:t_idx+current_num, t_idx:t_idx+current_num]
# print(trimmed)
# print(np.arange(current_num**2).reshape((current_num, current_num)))
half_num = current_num // 2
conv_idx = []
for idx in range(half_num):
val = (current_num ** 2) // 2 + half_num - current_num * idx
conv_idx.append(val)
for idx in range(current_num)[::-1]:
conv_idx.append(idx)
for idx in range(1, current_num - 1):
conv_idx.append(idx * current_num)
for idx in range(current_num):
val = (current_num ** 2) - current_num + idx
conv_idx.append(val)
for idx in range(1, half_num):
val = (current_num ** 2) - 1 - idx * current_num
conv_idx.append(val)
conv_idx = trimmed.flatten()[conv_idx]
return conv_idx
def _calc_rgb_from_same_lstar_radial_data(
lstar, temp_chroma, current_num, color_space):
"""
以下のような、中心がGray、周りは CIELAB 空間の a*b*平面のカラーパッチの
RGB値のリストを得る。
https://user-images.githubusercontent.com/3609012/75444470-d3bc5600-59a6-11ea-962b-c315648782a9.png
得られたデータは並べ替えが済んでいないため、calc_rad_patch_idx2() で
得られる変換テーブルを使った変換が必要。
"""
current_patch_num = (current_num - 1) * 4 if current_num > 1 else 1
rad = np.linspace(0, 2 * np.pi, current_patch_num, endpoint=False)
ll = np.ones((current_patch_num)) * lstar
aa = np.cos(rad) * temp_chroma
bb = np.sin(rad) * temp_chroma
lab = np.dstack((ll, aa, bb))
large_xyz = Lab_to_XYZ(lab)
rgb = XYZ_to_RGB(large_xyz, D65_WHITE, D65_WHITE,
color_space.XYZ_to_RGB_matrix)
return np.clip(rgb, 0.0, 1.0)
def calc_same_lstar_radial_color_patch_data(
lstar=58, chroma=32.5, outmost_num=9,
color_space=BT709_COLOURSPACE,
transfer_function=tf.GAMMA24):
"""
以下のような、中心がGray、周りは CIELAB 空間の a*b*平面のカラーパッチの
RGB値のリストを得る。
https://user-images.githubusercontent.com/3609012/75444470-d3bc5600-59a6-11ea-962b-c315648782a9.png
得られた RGB値のリストは最初のデータが画像左上の緑データ、
最後のデータが画像右下の紫データとなるよう既に**並べ替え**が行われている。
よってパッチをプロットする場合はRGB値リストの先頭から順にデータを取り出し、
右下に向かって並べていけば良い。
"""
patch_num = outmost_num ** 2
transfer_function = tf.GAMMA24
rgb_list = np.ones((patch_num, 3))
current_num_list = range(1, outmost_num + 1, 2)
chroma_list = np.linspace(0, chroma, len(current_num_list))
for temp_chroma, current_num in zip(chroma_list, current_num_list):
current_patch_num = (current_num - 1) * 4 if current_num > 1 else 1
rgb = _calc_rgb_from_same_lstar_radial_data(
lstar, temp_chroma, current_num, color_space)
rgb = np.reshape(rgb, (current_patch_num, 3))
rgb = tf.oetf(rgb, transfer_function)
conv_idx = calc_rad_patch_idx2(
outmost_num=outmost_num, current_num=current_num)
for idx in range(current_patch_num):
rgb_list[conv_idx[idx]] = rgb[idx]
return rgb_list
def _plot_same_lstar_radial_color_patch_data(
lstar=58, chroma=32.5, outmost_num=9,
color_space=BT709_COLOURSPACE,
transfer_function=tf.GAMMA24):
patch_size = 1080 // outmost_num
img = np.ones((1080, 1080, 3)) * 0.0
rgb = calc_same_lstar_radial_color_patch_data(
lstar=lstar, chroma=chroma, outmost_num=outmost_num,
color_space=color_space, transfer_function=transfer_function)
for idx in range(outmost_num ** 2):
h_idx = idx % outmost_num
v_idx = idx // outmost_num
st_pos = (h_idx * patch_size, v_idx * patch_size)
temp_img = np.ones((patch_size, patch_size, 3))\
* rgb[idx][np.newaxis, np.newaxis, :]
merge(img, temp_img, st_pos)
cv2.imwrite("hoge2.tiff", np.uint16(np.round(img[:, :, ::-1] * 0xFFFF)))
def get_accelerated_x_1x(sample_num=64):
"""
単調増加ではなく、加速度が 0→1→0 となるような x を作る
Parameters
----------
sample_num : int
the number of the sample.
Returns
-------
array_like
accelerated value list
Examples
--------
>>> x0 = np.linspace(0, 1, 8)
>>> x1 = get_accelerated_x_1x(8)
>>> print(x0)
>>> [ 0. 0.142 0.285 0.428 0.571 0.714 0.857 1. ]
>>> print(x1)
>>> [ 0. 0.049 0.188 0.388 0.611 0.811 0.950 1. ]
"""
rad = np.linspace(-0.5 * np.pi, 0.5 * np.pi, sample_num)
x = (np.sin(rad) + 1) / 2
return x
def get_accelerated_x_2x(sample_num=64):
"""
単調増加ではなく、加速度が 0→1→0 となるような x を作る。
加速度が `get_accelerated_x_1x` の2倍!!
Parameters
----------
sample_num : int
the number of the sample.
Returns
-------
array_like
accelerated value list
Examples
--------
>>> x0 = np.linspace(0, 1, 8)
>>> x2 = get_accelerated_x_2x(8)
>>> print(x0)
>>> [ 0. 0.142 0.285 0.428 0.571 0.714 0.857 1. ]
>>> print(x2)
>>> [ 0. 0.006 0.084 0.328 0.671 0.915 0.993 1. ]
"""
rad = np.linspace(-0.5 * np.pi, 0.5 * np.pi, sample_num)
rad = np.sin(rad) * 0.5 * np.pi
x = (np.sin(rad) + 1) / 2
return x
def get_accelerated_x_4x(sample_num=64):
"""
単調増加ではなく、加速度が 0→1→0 となるような x を作る。
加速度が `get_accelerated_x_1x` の4倍!!
Parameters
----------
sample_num : int
the number of the sample.
Returns
-------
array_like
accelerated value list
"""
rad = np.linspace(-0.5 * np.pi, 0.5 * np.pi, sample_num)
rad = np.sin(rad) * 0.5 * np.pi
rad = np.sin(rad) * 0.5 * np.pi
x = (np.sin(rad) + 1) / 2
return x
def get_accelerated_x_8x(sample_num=64):
"""
単調増加ではなく、加速度が 0→1→0 となるような x を作る。
加速度が `get_accelerated_x_1x` の4倍!!
Parameters
----------
sample_num : int
the number of the sample.
Returns
-------
array_like
accelerated value list
"""
rad = np.linspace(-0.5 * np.pi, 0.5 * np.pi, sample_num)
rad = np.sin(rad) * 0.5 * np.pi
rad = np.sin(rad) * 0.5 * np.pi
rad = np.sin(rad) * 0.5 * np.pi
x = (np.sin(rad) + 1) / 2
return x
def generate_color_checker_rgb_value(
color_space=BT709_COLOURSPACE, target_white=D65_WHITE):
"""
Generate the 24 RGB values of the color checker.
Parameters
----------
color_space : color space
color space object in `colour` module.
target_white : array_like
the xy values of the white point of target color space.
Returns
-------
array_like
24 RGB values. This is linear. OETF is not applied.
Examples
--------
>>> generate_color_checker_rgb_value(
... color_space=colour.models.BT709_COLOURSPACE,
... target_white=[0.3127, 0.3290])
>>> [[ 0.17289286 0.08205728 0.05714562]
>>> [ 0.5680292 0.29250401 0.21951748]
>>> [ 0.10435534 0.19656108 0.32958666]
>>> [ 0.1008804 0.14839018 0.05327639]
>>> [ 0.22303549 0.2169701 0.43166537]
>>> [ 0.10715338 0.513512 0.41415978]
>>> [ 0.74639182 0.20020473 0.03081343]
>>> [ 0.05947812 0.10659045 0.39897686]
>>> [ 0.5673215 0.08485376 0.11945382]
>>> [ 0.11177253 0.04285397 0.14166202]
>>> [ 0.34250836 0.5062777 0.0557734 ]
>>> [ 0.79262553 0.35803886 0.025485 ]
>>> [ 0.01864598 0.05139665 0.28886469]
>>> [ 0.054392 0.29876719 0.07187681]
>>> [ 0.45628547 0.03075684 0.04092033]
>>> [ 0.85379178 0.56503558 0.01475575]
>>> [ 0.53533883 0.09006355 0.3047824 ]
>>> [-0.03662977 0.24753781 0.39824679]
>>> [ 0.91177068 0.91497623 0.89427332]
>>> [ 0.57973934 0.59203191 0.59370647]
>>> [ 0.35495537 0.36538027 0.36772001]
>>> [ 0.19009594 0.19180133 0.19316719]
>>> [ 0.08524707 0.08890587 0.09255774]
>>> [ 0.03038879 0.03118623 0.03279615]]
"""
colour_checker_param = COLOURCHECKERS.get('ColorChecker 2005')
# 今回の処理では必要ないデータもあるので xyY と whitepoint だけ抽出
# -------------------------------------------------------------
_name, data, whitepoint = colour_checker_param
temp_xyY = []
for key in data.keys():
temp_xyY.append(data[key])
temp_xyY = np.array(temp_xyY)
large_xyz = xyY_to_XYZ(temp_xyY)
rgb_white_point = D65_WHITE
illuminant_XYZ = whitepoint # ColorCheckerのオリジナルデータの白色点
illuminant_RGB = rgb_white_point # XYZ to RGB 変換後の白色点を設定
chromatic_adaptation_transform = 'CAT02'
large_xyz_to_rgb_matrix = color_space.XYZ_to_RGB_matrix
rgb = XYZ_to_RGB(
large_xyz, illuminant_XYZ, illuminant_RGB,
large_xyz_to_rgb_matrix, chromatic_adaptation_transform)
return rgb
def make_color_checker_image(rgb, width=1920, padding_rate=0.01):
"""
6x4 の カラーチェッカーの画像を作る。
Height は Width から自動計算される。padding_rate で少し値が変わる。
"""
h_patch_num = 6
v_patch_num = 4
# 各種パラメータ計算
each_padding = int(width * padding_rate + 0.5)
h_padding_total = each_padding * (h_patch_num + 1)
h_patch_width_total = width - h_padding_total
patch_height = h_patch_width_total // h_patch_num
height = patch_height * v_patch_num + each_padding * (v_patch_num + 1)
patch_width_list = equal_devision(h_patch_width_total, h_patch_num)
# パッチを並べる
img = np.zeros((height, width, 3))
for v_idx in range(v_patch_num):
h_pos_st = each_padding
v_pos_st = each_padding + v_idx * (patch_height + each_padding)
for h_idx in range(h_patch_num):
rgb_idx = v_idx * h_patch_num + h_idx
pos = (h_pos_st, v_pos_st)
patch_img = np.ones((patch_height, patch_width_list[h_idx], 3))\
* rgb[rgb_idx]
merge(img, patch_img, pos)
h_pos_st += (patch_width_list[h_idx] + each_padding)
return img
def calc_st_pos_for_centering(bg_size, fg_size):
"""
Calculate start postion for centering.
Parameters
----------
bg_size : touple(int)
(width, height) of the background image.
fg_size : touple(int)
(width, height) of the foreground image.
Returns
-------
touple (int)
(st_pos_h, st_pos_v)
Examples
--------
>>> calc_st_pos_for_centering(bg_size=(1920, 1080), fg_size=(640, 480))
>>> (640, 300)
"""
bg_width = bg_size[0]
bg_height = bg_size[1]
fg_width = fg_size[0]
fg_height = fg_size[1]
st_pos_h = bg_width // 2 - fg_width // 2
st_pos_v = bg_height // 2 - fg_height // 2
return (st_pos_h, st_pos_v)
def get_size_from_image(img):
"""
`calc_st_pos_for_centering()` の引数計算が面倒だったので関数化。
"""
return (img.shape[1], img.shape[0])
if __name__ == '__main__':
os.chdir(os.path.dirname(os.path.abspath(__file__)))
# print(calc_rad_patch_idx(outmost_num=9, current_num=1))
# _plot_same_lstar_radial_color_patch_data(
# lstar=58, chroma=32.5, outmost_num=7,
# color_space=BT709_COLOURSPACE,
# transfer_function=tf.GAMMA24)
# calc_rad_patch_idx2(outmost_num=9, current_num=7)
# print(convert_luminance_to_color_value(100, tf.ST2084))
# print(generate_color_checker_rgb_value(target_white=[0.3127, 0.3290]))
print(calc_st_pos_for_centering(bg_size=(1920, 1080), fg_size=(640, 480)))
| ty_lib/test_pattern_generator2.py | 54,415 | 以下のような、中心がGray、周りは CIELAB 空間の a*b*平面のカラーパッチの
RGB値のリストを得る。
https://user-images.githubusercontent.com/3609012/75444470-d3bc5600-59a6-11ea-962b-c315648782a9.png
得られたデータは並べ替えが済んでいないため、calc_rad_patch_idx2() で
得られる変換テーブルを使った変換が必要。
xy色度図のプロットのための馬蹄形の外枠のxy値を求める。
Returns
-------
array_like
xy coordinate for chromaticity diagram
以下のような、中心がGray、周りは CIELAB 空間の a*b*平面のカラーパッチの
RGB値のリストを得る。
https://user-images.githubusercontent.com/3609012/75444470-d3bc5600-59a6-11ea-962b-c315648782a9.png
得られたデータは並べ替えが済んでいないため、calc_rad_patch_idx2() で
得られる変換テーブルを使った変換が必要。
本関数はまさにその変換を行う。
以下のような、中心がGray、周りは CIELAB 空間の a*b*平面のカラーパッチの
RGB値のリストを得る。
https://user-images.githubusercontent.com/3609012/75444470-d3bc5600-59a6-11ea-962b-c315648782a9.png
得られた RGB値のリストは最初のデータが画像左上の緑データ、
最後のデータが画像右下の紫データとなるよう既に**並べ替え**が行われている。
よってパッチをプロットする場合はRGB値リストの先頭から順にデータを取り出し、
右下に向かって並べていけば良い。
Calculate start postion for centering.
Parameters
----------
bg_size : touple(int)
(width, height) of the background image.
fg_size : touple(int)
(width, height) of the foreground image.
Returns
-------
touple (int)
(st_pos_h, st_pos_v)
Examples
--------
>>> calc_st_pos_for_centering(bg_size=(1920, 1080), fg_size=(640, 480))
>>> (640, 300)
dot pattern 作る。
Parameters
----------
kind_num : integer
作成するドットサイズの種類。
例えば、kind_num=3 ならば、1dot, 2dot, 4dot のパターンを作成。
whole_repeat : integer
異なる複数種類のドットパターンの組数。
例えば、kind_num=3, whole_repeat=2 ならば、
1dot, 2dot, 4dot のパターンを水平・垂直に2組作る。
fg_color : array_like
foreground color value.
bg_color : array_like
background color value.
reduce : bool
HDRテストパターンの3840x2160専用。縦横を半分にする。
Returns
-------
array_like
dot pattern image.
輝度[cd/m2] から code value に変換する。
luminance の単位は [cd/m2]
輝度[cd/m2] から code value の RGB値に変換する。
luminance の単位は [cd/m2]。無彩色である。
Examples
--------
>>> convert_luminance_to_color_value(100, tf.GAMMA24)
>>> [ 1.0 1.0 1.0 ]
>>> convert_luminance_to_color_value(100, tf.ST2084)
>>> [ 0.50807842 0.50807842 0.50807842 ]
img に対して mtx を適用する。
dot pattern 作る。
Parameters
----------
dot_size : integer
dot size.
repeat : integer
The number of high-low pairs.
color : array_like
color value.
Returns
-------
array_like
dot pattern image.
img に対して外枠線を引く
Parameters
----------
img : array_like
image data.
fg_color : array_like
color
outline_width : int
thickness.
Returns
-------
array_like
image data with line.
Examples
--------
>>> img = np.zeros((1080, 1920, 3))
>>> color = (940, 940, 940)
>>> thickness = 2
>>> draw_outline(img, color, thickness)
直線を引く。OpenCV だと 8bit しか対応してないっぽいので自作。
Parameters
----------
img : array_like
image data.
pt1 : list(pos_h, pos_v)
start point.
pt2 : list(pos_h, pos_v)
end point.
color : array_like
color
thickness : int
thickness.
Returns
-------
array_like
image data with line.
Notes
-----
thickness のパラメータは pt1 の点から右下方向に効きます。
pt1 を中心として太さではない事に注意。
Examples
--------
>>> pt1 = (0, 0)
>>> pt2 = (1920, 0)
>>> color = (940, 940, 940)
>>> thickness = 4
>>> draw_straight_line(img, pt1, pt2, color, thickness)
# 概要
length を div_num で分割する。
端数が出た場合は誤差拡散法を使って上手い具合に分散させる。
# 概要
階段状に変化するグラデーションパターンを作る。
なお、引数の調整により正確に1階調ずつ変化するパターンも作成可能。
# 注意事項
正確に1階調ずつ変化するグラデーションを作る場合は
```step_num = (2 ** bit_depth) + 1```
となるようにパラメータを指定すること。具体例は以下のExample参照。
# Example
```
grad_8 = gen_step_gradation(width=grad_width, height=grad_height,
step_num=257, bit_depth=8,
color=(1.0, 1.0, 1.0), direction='h')
grad_10 = gen_step_gradation(width=grad_width, height=grad_height,
step_num=1025, bit_depth=10,
color=(1.0, 1.0, 1.0), direction='h')
```
Generate the 24 RGB values of the color checker.
Parameters
----------
color_space : color space
color space object in `colour` module.
target_white : array_like
the xy values of the white point of target color space.
Returns
-------
array_like
24 RGB values. This is linear. OETF is not applied.
Examples
--------
>>> generate_color_checker_rgb_value(
... color_space=colour.models.BT709_COLOURSPACE,
... target_white=[0.3127, 0.3290])
>>> [[ 0.17289286 0.08205728 0.05714562]
>>> [ 0.5680292 0.29250401 0.21951748]
>>> [ 0.10435534 0.19656108 0.32958666]
>>> [ 0.1008804 0.14839018 0.05327639]
>>> [ 0.22303549 0.2169701 0.43166537]
>>> [ 0.10715338 0.513512 0.41415978]
>>> [ 0.74639182 0.20020473 0.03081343]
>>> [ 0.05947812 0.10659045 0.39897686]
>>> [ 0.5673215 0.08485376 0.11945382]
>>> [ 0.11177253 0.04285397 0.14166202]
>>> [ 0.34250836 0.5062777 0.0557734 ]
>>> [ 0.79262553 0.35803886 0.025485 ]
>>> [ 0.01864598 0.05139665 0.28886469]
>>> [ 0.054392 0.29876719 0.07187681]
>>> [ 0.45628547 0.03075684 0.04092033]
>>> [ 0.85379178 0.56503558 0.01475575]
>>> [ 0.53533883 0.09006355 0.3047824 ]
>>> [-0.03662977 0.24753781 0.39824679]
>>> [ 0.91177068 0.91497623 0.89427332]
>>> [ 0.57973934 0.59203191 0.59370647]
>>> [ 0.35495537 0.36538027 0.36772001]
>>> [ 0.19009594 0.19180133 0.19316719]
>>> [ 0.08524707 0.08890587 0.09255774]
>>> [ 0.03038879 0.03118623 0.03279615]]
# 概要
(0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 0, 1), ...
みたいな配列を返す。
CUBE形式の3DLUTを作成する時に便利。
単調増加ではなく、加速度が 0→1→0 となるような x を作る
Parameters
----------
sample_num : int
the number of the sample.
Returns
-------
array_like
accelerated value list
Examples
--------
>>> x0 = np.linspace(0, 1, 8)
>>> x1 = get_accelerated_x_1x(8)
>>> print(x0)
>>> [ 0. 0.142 0.285 0.428 0.571 0.714 0.857 1. ]
>>> print(x1)
>>> [ 0. 0.049 0.188 0.388 0.611 0.811 0.950 1. ]
単調増加ではなく、加速度が 0→1→0 となるような x を作る。
加速度が `get_accelerated_x_1x` の2倍!!
Parameters
----------
sample_num : int
the number of the sample.
Returns
-------
array_like
accelerated value list
Examples
--------
>>> x0 = np.linspace(0, 1, 8)
>>> x2 = get_accelerated_x_2x(8)
>>> print(x0)
>>> [ 0. 0.142 0.285 0.428 0.571 0.714 0.857 1. ]
>>> print(x2)
>>> [ 0. 0.006 0.084 0.328 0.671 0.915 0.993 1. ]
単調増加ではなく、加速度が 0→1→0 となるような x を作る。
加速度が `get_accelerated_x_1x` の4倍!!
Parameters
----------
sample_num : int
the number of the sample.
Returns
-------
array_like
accelerated value list
単調増加ではなく、加速度が 0→1→0 となるような x を作る。
加速度が `get_accelerated_x_1x` の4倍!!
Parameters
----------
sample_num : int
the number of the sample.
Returns
-------
array_like
accelerated value list
xy色度図の馬蹄形の画像を生成する
Returns
-------
ndarray
rgb image.
長方形を複数個ズラして重ねることでCSFパターンっぽいのを作る。
入力信号レベルは16bitに限定する。
Parameters
----------
width : numeric.
width of the pattern image.
height : numeric.
height of the pattern image.
lv1 : numeric
video level 1. this value must be 10bit.
lv2 : numeric
video level 2. this value must be 10bit.
stripe_num : numeric
number of the stripe.
Returns
-------
array_like
a cms pattern image.
Log10スケールのx軸データを作る。
Examples
--------
>>> get_log2_x_scale(
... sample_num=8, ref_val=1.0, min_exposure=-1, max_exposure=6)
array([ 1.0000e-01 1.0000e+00 1.0000e+01 1.0000e+02
1.0000e+03 1.0000e+04 1.0000e+05 1.0000e+06])
Log2スケールのx軸データを作る。
Examples
--------
>>> get_log2_x_scale(sample_num=10, min_exposure=-4.0, max_exposure=4.0)
array([[ 0.0625 0.11573434 0.214311 0.39685026 0.73486725
1.36079 2.5198421 4.66611616 8.64047791 16. ]])
prmary color の座標を求める
Parameters
----------
name : str
a name of the color space.
Returns
-------
array_like
prmaries. [[rx, ry], [gx, gy], [bx, by], [rx, ry]]
secondary color の座標を求める
Parameters
----------
name : str
a name of the color space.
Returns
-------
array_like
secondaries. the order is magenta, yellow, cyan.
`calc_st_pos_for_centering()` の引数計算が面倒だったので関数化。
white point を求める。CIE1931ベース。
6x4 の カラーチェッカーの画像を作る。
Height は Width から自動計算される。padding_rate で少し値が変わる。
長方形を複数個ズラして重ねることでCSFパターンっぽいのを作る。
入力信号レベルは10bitに限定する。
Parameters
----------
width : numeric.
width of the pattern image.
height : numeric.
height of the pattern image.
lv1 : array_like
video level 1. this value must be 10bit.
lv2 : array_like
video level 2. this value must be 10bit.
stripe_num : numeric
number of the stripe.
Returns
-------
array_like
a cms pattern image.
タイル状の縞々パターンを作る
YCbCr係数誤りを確認するテストパターンを作る。
正直かなり汚い組み方です。雑に作ったパターンを悪魔合体させています。
Parameters
----------
height : numeric.
height of the pattern image.
v_tile_num : numeric
number of the tile in the vertical direction.
Note
----
横長のパターンになる。以下の式が成立する。
```
h_tile_num = v_tile_num * 2
width = height * 2
```
Returns
-------
array_like
ycbcr checker image
img_a に img_b をマージする。
img_a にデータを上書きする。
pos = (horizontal_st, vertical_st)
合成する。
Parameters
----------
bg_img : array_like(float, 3-channel)
image data.
fg_img : array_like(float, 4-channel)
image data
tf : strings
transfer function
pos : list(int)
(pos_h, pos_v)
ColorCheckerをプロットする
Parameters
----------
rgb : array_like
RGB value of the ColorChecker.
RGB's shape must be (24, 3).
rgb2 : array_like
It's a optional parameter.
If You want to draw two different ColorCheckers,
set the RGB value to this variable.
size : tuple
canvas size.
block_size : float
A each block's size.
This value is ratio to height of the canvas.
padding : float
A padding to the block.
Returns
-------
array_like
A ColorChecker image.
SONY の HDR説明資料にあるような xyY の図を作る。
Parameters
----------
name : str
name of the target color space.
Returns
-------
None
ACESutil.Lin_to_Log2_param.ctl を参考に作成。
https://github.com/ampas/aces-dev/blob/master/transforms/ctl/utilities/ACESutil.Lin_to_Log2_param.ctl
Parameters
----------
x : array_like
linear data.
mid_gray : float
18% gray value on linear scale.
min_exposure : float
minimum value on log scale.
max_exposure : float
maximum value on log scale.
Returns
-------
array_like
log2 value that is transformed from linear x value.
Examples
--------
>>> shaper_func_linear_to_log2(
... x=0.18, mid_gray=0.18, min_exposure=-6.5, max_exposure=6.5)
0.5
>>> shaper_func_linear_to_log2(
... x=np.array([0.00198873782209, 16.2917402385])
... mid_gray=0.18, min_exposure=-6.5, max_exposure=6.5)
array([ 1.58232402e-13 1.00000000e+00])
ACESutil.Log2_to_Lin_param.ctl を参考に作成。
https://github.com/ampas/aces-dev/blob/master/transforms/ctl/utilities/ACESutil.Log2_to_Lin_param.ctl
Log2空間の補足は shaper_func_linear_to_log2() の説明を参照
Examples
--------
>>> x = np.array([0.0, 1.0])
>>> shaper_func_log2_to_linear(
... x, mid_gray=0.18, min_exposure=-6.5, max_exposure=6.5)
array([0.00198873782209, 16.2917402385])
xy値からRGB値を算出する。
いい感じに正規化もしておく。
Parameters
----------
xy : array_like
xy value.
name : string
color space name.
normalize : string
normalize method. You can select 'maximum', 'specific' or None.
Returns
-------
array_like
rgb value. the value is normalized.
評価用のテストパターン作成ツール集
!/usr/bin/env python3 -*- coding: utf-8 -*- 誤差拡散法を使った辻褄合わせを適用 ------------------------------------------- 計算誤差により最終点が +1 されない場合への対処 ------------------------------------------- 最終確認 ------------------------------------------- 基本パラメータ設定 ------------------ 馬蹄形のxy値を算出 -------------------------- def plot_chromaticity_diagram( rate=480/755.0*2, xmin=0.0, xmax=0.8, ymin=0.0, ymax=0.9, **kwargs): キーワード引数の初期値設定 ------------------------------------ monitor_primaries = kwargs.get('monitor_primaries', None) secondaries = kwargs.get('secondaries', None) test_scatter = kwargs.get('test_scatter', None) intersection = kwargs.get('intersection', None) プロット用データ準備 --------------------------------- xy_image = get_chromaticity_image( xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax) cmf_xy = _get_cmfs_xy() bt709_gamut, _ = get_primaries(name=cs.BT709) bt2020_gamut, _ = get_primaries(name=cs.BT2020) dci_p3_gamut, _ = get_primaries(name=cs.P3_D65) ap0_gamut, _ = get_primaries(name=cs.ACES_AP0) ap1_gamut, _ = get_primaries(name=cs.ACES_AP1) xlim = (min(0, xmin), max(0.8, xmax)) ylim = (min(0, ymin), max(0.9, ymax)) ax1 = pu.plot_1_graph(fontsize=20 * rate, figsize=((xmax - xmin) * 10 * rate, (ymax - ymin) * 10 * rate), graph_title="CIE1931 Chromaticity Diagram", graph_title_size=None, xlabel=None, ylabel=None, axis_label_size=None, legend_size=18 * rate, xlim=xlim, ylim=ylim, xtick=[x * 0.1 + xmin for x in range(int((xlim[1] - xlim[0])/0.1) + 1)], ytick=[x * 0.1 + ymin for x in range(int((ylim[1] - ylim[0])/0.1) + 1)], xtick_size=17 * rate, ytick_size=17 * rate, linewidth=4 * rate, minor_xtick_num=2, minor_ytick_num=2) ax1.plot(cmf_xy[..., 0], cmf_xy[..., 1], '-k', lw=3.5*rate, label=None) ax1.plot((cmf_xy[-1, 0], cmf_xy[0, 0]), (cmf_xy[-1, 1], cmf_xy[0, 1]), '-k', lw=3.5*rate, label=None) ax1.plot(bt709_gamut[:, 0], bt709_gamut[:, 1], c=UNIVERSAL_COLOR_LIST[0], label="BT.709", lw=2.75*rate) ax1.plot(bt2020_gamut[:, 0], bt2020_gamut[:, 1], c=UNIVERSAL_COLOR_LIST[1], label="BT.2020", lw=2.75*rate) ax1.plot(dci_p3_gamut[:, 0], dci_p3_gamut[:, 1], c=UNIVERSAL_COLOR_LIST[2], label="DCI-P3", lw=2.75*rate) ax1.plot(ap1_gamut[:, 0], ap1_gamut[:, 1], c=UNIVERSAL_COLOR_LIST[3], label="ACES AP1", lw=2.75*rate) ax1.plot(ap0_gamut[:, 0], ap0_gamut[:, 1], c=UNIVERSAL_COLOR_LIST[4], label="ACES AP0", lw=2.75*rate) if monitor_primaries is not None: ax1.plot(monitor_primaries[:, 0], monitor_primaries[:, 1], c="202020", label="???", lw=3*rate) if secondaries is not None: xy, rgb = secondaries ax1.scatter(xy[..., 0], xy[..., 1], s=700*rate, marker='s', c=rgb, edgecolors='404000', linewidth=2*rate) if test_scatter is not None: xy, rgb = test_scatter ax1.scatter(xy[..., 0], xy[..., 1], s=300*rate, marker='s', c=rgb, edgecolors='404040', linewidth=2*rate) if intersection is not None: ax1.scatter(intersection[..., 0], intersection[..., 1], s=300*rate, marker='s', c='CCCCCC', edgecolors='404040', linewidth=2*rate) ax1.imshow(xy_image, extent=(xmin, xmax, ymin, ymax)) plt.legend(loc='upper right') plt.savefig('temp_fig.png', bbox_inches='tight') plt.show() color_space = models.BT2020_COLOURSPACE color_space = models.S_GAMUT3_COLOURSPACE 馬蹄形のxy値を算出 -------------------------- アンチエイリアシングしてアルファチャンネルを滑らかに ------------------------------------------------ ネガポジ反転 -------------------------------- xy のメッシュから色を復元 ------------------------ ゼロ割対策 ゼロ割対策 mask 適用 ------------------------------------- 背景色をグレーに変更 ------------------------------------- temp_img *= lv 馬蹄の領域判別用データ作成 -------------------------- アンチエイリアシングしてアルファチャンネルを滑らかに ------------------------------------------------ ネガポジ反転 -------------------------------- xy のメッシュから色を復元 ------------------------ mask 適用 ------------------------------------- こっからもういちど XYZ に変換。Yを求めるために。 --------------------------------------------- ログスケールに変換する準備 -------------------------- ax.plot_wireframe(xy[..., 0], xy[..., 1], np.log10(large_y), rcount=100, ccount=100) chromatcity_image の取得。z=0 の位置に貼り付ける ---------------------------------------------- x = ((1 - t) ** 2) * p0[0] + 2 * (1 - t) * t * p1[0]\ + (t ** 2) * p2[0] y = ((1 - t) ** 2) * p0[1] + 2 * (1 - t) * t * p1[1]\ + (t ** 2) * p2[1] ax1 = pu.plot_1_graph(fontsize=20, figsize=(10, 8), graph_title="Title", graph_title_size=None, xlabel="X Axis Label", ylabel="Y Axis Label", axis_label_size=None, legend_size=17, xlim=None, ylim=None, xtick=None, ytick=None, xtick_size=None, ytick_size=None, linewidth=3, minor_xtick_num=None, minor_ytick_num=None) ax1.plot(x, y, label='aaa') plt.legend(loc='upper left') plt.show() グラデーション方向設定 ---------------------- step_num は 引数で余計に +1 されてるので引く 念のため1階調ずつの変化か確認 --------------------------- まずは水平1LINEのグラデーションを作る ----------------------------------- ブロードキャストを利用して2次元に拡張する ------------------------------------------ np.uint16 にコンバート ------------------------------ img = np.uint16(np.round(img * (2 ** (16 - bit_depth)))) 水平・垂直のピクセル数 High-Log の 論理配列を生成 着色 V方向にコピー&Even-Oddの結合 preview_image(dot_img) preview_image(img) cv2.imwrite("hoge.tiff", np.uint8(img * 0xFF)[..., ::-1]) preview_image(img / 1023) preview_image(img/1024.0) preview_image(out_img/1023.0) 基本パラメータ算出 -------------------------------------- 24ループで1枚の画像に24パッチを描画 ------------------------------------------------- pt1 = (st_h, st_v) upper left upper right lower left lower right log2空間への変換。mid_gray が 0.0 となるように補正 min, max の範囲で正規化。 plt.plot(x, y) plt.show() parameter check check direction upper left lower right print(base) print(trimmed) print(np.arange(current_num**2).reshape((current_num, current_num))) 今回の処理では必要ないデータもあるので xyY と whitepoint だけ抽出 ------------------------------------------------------------- ColorCheckerのオリジナルデータの白色点 XYZ to RGB 変換後の白色点を設定 各種パラメータ計算 パッチを並べる print(calc_rad_patch_idx(outmost_num=9, current_num=1)) _plot_same_lstar_radial_color_patch_data( lstar=58, chroma=32.5, outmost_num=7, color_space=BT709_COLOURSPACE, transfer_function=tf.GAMMA24) calc_rad_patch_idx2(outmost_num=9, current_num=7) print(convert_luminance_to_color_value(100, tf.ST2084)) print(generate_color_checker_rgb_value(target_white=[0.3127, 0.3290])) | 18,232 | ja | 0.470357 |
__license__ = "MIT"
__copyright__ = r"""
MIT License
Copyright (c) 2017 Gregor Engberding
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 sys
import json
from PySide2.QtCore import QAbstractItemModel, QAbstractListModel, QByteArray, QDataStream, QJsonParseError, QJsonValue, QMimeData, QModelIndex, Qt
from PySide2.QtWidgets import QApplication, QFileDialog
class QJsonTreeItem(object):
def __init__(self, parent=None):
self.mParent = parent
self.mChilds = []
self.mType = None
self.mValue = None
def appendChild(self, item):
self.mChilds.append(item)
def child(self, row: int):
return self.mChilds[row]
def parent(self):
return self.mParent
def childCount(self):
return len(self.mChilds)
def row(self):
if self.mParent is not None:
return self.mParent.mChilds.index(self)
return 0
def setKey(self, key: str):
self.mKey = key
def setValue(self, value: str):
self.mValue = value
def setType(self, type: QJsonValue.Type):
self.mType = type
def key(self):
return self.mKey
def value(self):
return self.mValue
def type(self):
return self.mType
def load(self, value, parent=None):
rootItem = QJsonTreeItem(parent)
rootItem.setKey("root")
jsonType = None
jsonType = value.__class__.__name__
if isinstance(value, dict):
# process the key/value pairs
for key in value:
v = value[key]
child = self.load(v, rootItem)
child.setKey(key)
child.setType(v.__class__.__name__)
rootItem.appendChild(child)
elif isinstance(value, list):
# process the values in the list
for i, v in enumerate(value):
child = self.load(v, rootItem)
child.setKey(str(i))
child.setType(v.__class__)
rootItem.appendChild(child)
else:
# value is processed
rootItem.setValue(value)
try:
rootItem.setType(value.type())
except AttributeError:
if jsonType is not None:
rootItem.setType(jsonType)
else:
rootItem.setType(value.__class__)
return rootItem
class QJsonModel(QAbstractItemModel):
def __init__(self, parent=None):
super().__init__(parent)
self.mRootItem = QJsonTreeItem()
self.mHeaders = ["key", "value", "type"]
def load(self, fileName):
if fileName is None or fileName is False:
return False
with open(fileName, "rb") as file:
if file is None:
return False
else:
jsonTxt = file.read()
self.loadJson(jsonTxt)
def loadJson(self, json):
error = QJsonParseError()
return self.loadDict(QJsonDocument.fromJson(json, error))
def loadDict(self, dic):
self.mDocument = dic
if self.mDocument is not None:
self.beginResetModel()
if isinstance(self.mDocument, list):
self.mRootItem.load(list(self.mDocument))
else:
self.mRootItem = self.mRootItem.load(self.mDocument)
self.endResetModel()
return True
# print("QJsonModel: error loading Json")
return False
def data(self, index: QModelIndex, role: int = ...):
if not index.isValid():
return None
item = index.internalPointer()
col = index.column()
if role == Qt.DisplayRole:
if col == 0:
return str(item.key())
elif col == 1:
return str(item.value())
elif col == 2:
return str(item.type())
return None
def headerData(self, section: int, orientation: Qt.Orientation, role: int = ...):
if role != Qt.DisplayRole:
return None
if orientation == Qt.Horizontal:
return self.mHeaders[section]
return QVariant()
def index(self, row: int, column: int, parent: QModelIndex = ...):
if not self.hasIndex(row, column, parent):
return QModelIndex()
if not parent.isValid():
parentItem = self.mRootItem
else:
parentItem = parent.internalPointer()
try:
childItem = parentItem.child(row)
return self.createIndex(row, column, childItem)
except IndexError:
return QModelIndex()
def parent(self, index: QModelIndex):
if not index.isValid():
return QModelIndex()
childItem = index.internalPointer()
parentItem = childItem.parent()
if parentItem == self.mRootItem:
return QModelIndex()
return self.createIndex(parentItem.row(), 0, parentItem)
def rowCount(self, parent: QModelIndex = ...):
if parent.column() > 0:
return 0
if not parent.isValid():
parentItem = self.mRootItem
else:
parentItem = parent.internalPointer()
return parentItem.childCount()
def columnCount(self, parent: QModelIndex = ...):
return 3
| WindowsTelemetryViewer/PyQtJsonModel.py | 5,359 | process the key/value pairs process the values in the list value is processed print("QJsonModel: error loading Json") | 117 | en | 0.456805 |
"""
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Ontology Engineering Group
http://www.oeg-upm.net/
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Copyright (C) 2016 Ontology Engineering Group.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
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 json
from setuptools import setup, find_packages
__author__ = 'Fernando Serena'
with open("kg_search/metadata.json", 'r') as stream:
metadata = json.load(stream)
setup(
name="kg-search",
version=metadata['version'],
author=metadata['author'],
author_email=metadata['email'],
description=metadata['description'],
license="Apache 2",
keywords=["knowledge graph", "wikidata"],
url=metadata['github'],
download_url="https://github.com/fserena/kg-search/tarball/{}".format(metadata['version']),
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
install_requires=['Flask', 'Flask-Cache', 'gunicorn', 'futures', 'requests', 'urllib3', 'rdflib==4.2.0',
'python-dateutil', 'pyld', 'rdflib-jsonld', 'shortuuid', 'wikipedia==1.4.0'],
classifiers=[],
package_dir={'kg_search': 'kg_search'},
package_data={'kg_search': ['metadata.json']},
scripts=['kg-search']
)
| setup.py | 1,939 | #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Ontology Engineering Group
http://www.oeg-upm.net/
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Copyright (C) 2016 Ontology Engineering Group.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
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.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# | 965 | en | 0.4306 |
"""
The primary specified return wavefunction quantities.
"""
result_wavefunction = {}
# Orbitals
result_wavefunction["orbitals_a"] = {
"type": "string",
"description": "Alpha-spin orbitals in the AO basis of the primary return. "
}
result_wavefunction["orbitals_b"] = {
"type": "string",
"description": "Beta-spin orbitals in the AO basis of the primary return."
}
# Density
result_wavefunction["density_a"] = {
"type": "string",
"description": "Alpha-spin density in the AO basis of the primary return."
}
result_wavefunction["density_b"] = {
"type": "string",
"description": "Beta-spin density in the AO basis of the primary return."
}
# Fock matrix
result_wavefunction["fock_a"] = {
"type": "string",
"description": "Alpha-spin Fock matrix in the AO basis of the primary return."
}
result_wavefunction["fock_b"] = {
"type": "string",
"description": "Beta-spin Fock matrix in the AO basis of the primary return."
}
# Eigenvalues
result_wavefunction["eigenvalues_a"] = {
"type": "string",
"description": "Alpha-spin orbital eigenvalues of the primary return."
}
result_wavefunction["eigenvalues_b"] = {
"type": "string",
"description": "Beta-spin orbital eigenvalues of the primary return."
}
# Occupations
result_wavefunction["occupations_a"] = {
"type": "string",
"description": "Alpha-spin orbital occupations of the primary return."
}
result_wavefunction["occupations_b"] = {
"type": "string",
"description": "Beta-spin orbital occupations of the primary return."
}
| qcschema/dev/wavefunction/result_wavefunction.py | 1,572 | The primary specified return wavefunction quantities.
Orbitals Density Fock matrix Eigenvalues Occupations | 109 | en | 0.487226 |
# Copyright 2017 Red Hat, Inc.
# 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.
import mock
import uuid
from os_vif import objects as osv_objects
from oslo_config import cfg
from kuryr_kubernetes.cni.binding import base
from kuryr_kubernetes import objects
from kuryr_kubernetes.tests import base as test_base
from kuryr_kubernetes.tests import fake
CONF = cfg.CONF
class TestDriverMixin(test_base.TestCase):
def setUp(self):
super(TestDriverMixin, self).setUp()
self.instance_info = osv_objects.instance_info.InstanceInfo(
uuid=uuid.uuid4(), name='foo')
self.ifname = 'c_interface'
self.netns = '/proc/netns/1234'
# Mock IPDB context managers
self.ipdbs = {}
self.m_bridge_iface = mock.Mock(__exit__=mock.Mock(return_value=None))
self.m_c_iface = mock.Mock()
self.m_h_iface = mock.Mock()
self.h_ipdb, self.h_ipdb_exit = self._mock_ipdb_context_manager(None)
self.c_ipdb, self.c_ipdb_exit = self._mock_ipdb_context_manager(
self.netns)
self.m_create = mock.Mock()
self.h_ipdb.create = mock.Mock(
return_value=mock.Mock(
__enter__=mock.Mock(return_value=self.m_create),
__exit__=mock.Mock(return_value=None)))
self.c_ipdb.create = mock.Mock(
return_value=mock.Mock(
__enter__=mock.Mock(return_value=self.m_create),
__exit__=mock.Mock(return_value=None)))
def _mock_ipdb_context_manager(self, netns):
mock_ipdb = mock.Mock(
interfaces={
'bridge': mock.Mock(
__enter__=mock.Mock(return_value=self.m_bridge_iface),
__exit__=mock.Mock(return_value=None),
),
'c_interface': mock.Mock(
__enter__=mock.Mock(return_value=self.m_c_iface),
__exit__=mock.Mock(return_value=None),
),
'h_interface': mock.Mock(
__enter__=mock.Mock(return_value=self.m_h_iface),
__exit__=mock.Mock(return_value=None),
),
}
)
mock_exit = mock.Mock(return_value=None)
mock_ipdb.__exit__ = mock_exit
mock_ipdb.__enter__ = mock.Mock(return_value=mock_ipdb)
self.ipdbs[netns] = mock_ipdb
return mock_ipdb, mock_exit
@mock.patch('kuryr_kubernetes.cni.binding.base.get_ipdb')
@mock.patch('os_vif.plug')
def _test_connect(self, m_vif_plug, m_get_ipdb, report=None):
def get_ipdb(netns=None):
return self.ipdbs[netns]
m_get_ipdb.side_effect = get_ipdb
base.connect(self.vif, self.instance_info, self.ifname, self.netns,
report)
m_vif_plug.assert_called_once_with(self.vif, self.instance_info)
self.m_c_iface.add_ip.assert_called_once_with('192.168.0.2/24')
if report:
report.assert_called_once()
@mock.patch('os_vif.unplug')
def _test_disconnect(self, m_vif_unplug, report=None):
base.disconnect(self.vif, self.instance_info, self.ifname, self.netns,
report)
m_vif_unplug.assert_called_once_with(self.vif, self.instance_info)
if report:
report.assert_called_once()
class TestOpenVSwitchDriver(TestDriverMixin, test_base.TestCase):
def setUp(self):
super(TestOpenVSwitchDriver, self).setUp()
self.vif = fake._fake_vif(osv_objects.vif.VIFOpenVSwitch)
@mock.patch('kuryr_kubernetes.cni.plugins.k8s_cni_registry.'
'K8sCNIRegistryPlugin.report_drivers_health')
@mock.patch('os.getpid', mock.Mock(return_value=123))
@mock.patch('kuryr_kubernetes.linux_net_utils.create_ovs_vif_port')
def test_connect(self, mock_create_ovs, m_report):
self._test_connect(report=m_report)
self.assertEqual(3, self.h_ipdb_exit.call_count)
self.assertEqual(2, self.c_ipdb_exit.call_count)
self.c_ipdb.create.assert_called_once_with(
ifname=self.ifname, peer='h_interface', kind='veth')
self.assertEqual(1, self.m_create.mtu)
self.assertEqual(str(self.vif.address),
self.m_create.address)
self.m_create.up.assert_called_once_with()
self.assertEqual(123, self.m_h_iface.net_ns_pid)
self.assertEqual(1, self.m_h_iface.mtu)
self.m_h_iface.up.assert_called_once_with()
mock_create_ovs.assert_called_once_with(
'bridge', 'h_interface', '89eccd45-43e9-43d8-b4cc-4c13db13f782',
'3e:94:b7:31:a0:83', 'kuryr')
@mock.patch('kuryr_kubernetes.cni.plugins.k8s_cni_registry.'
'K8sCNIRegistryPlugin.report_drivers_health')
@mock.patch('kuryr_kubernetes.linux_net_utils.delete_ovs_vif_port')
def test_disconnect(self, mock_delete_ovs, m_report):
self._test_disconnect(report=m_report)
mock_delete_ovs.assert_called_once_with('bridge', 'h_interface')
class TestBridgeDriver(TestDriverMixin, test_base.TestCase):
def setUp(self):
super(TestBridgeDriver, self).setUp()
self.vif = fake._fake_vif(osv_objects.vif.VIFBridge)
@mock.patch('os.getpid', mock.Mock(return_value=123))
def test_connect(self):
self._test_connect()
self.m_h_iface.remove.assert_called_once_with()
self.assertEqual(3, self.h_ipdb_exit.call_count)
self.assertEqual(2, self.c_ipdb_exit.call_count)
self.c_ipdb.create.assert_called_once_with(
ifname=self.ifname, peer='h_interface', kind='veth')
self.assertEqual(1, self.m_create.mtu)
self.assertEqual(str(self.vif.address),
self.m_create.address)
self.m_create.up.assert_called_once_with()
self.assertEqual(123, self.m_h_iface.net_ns_pid)
self.assertEqual(1, self.m_h_iface.mtu)
self.m_h_iface.up.assert_called_once_with()
self.m_bridge_iface.add_port.assert_called_once_with('h_interface')
def test_disconnect(self):
self._test_disconnect()
class TestNestedVlanDriver(TestDriverMixin, test_base.TestCase):
def setUp(self):
super(TestNestedVlanDriver, self).setUp()
self.vif = fake._fake_vif(objects.vif.VIFVlanNested)
self.vif.vlan_id = 7
CONF.set_override('link_iface', 'bridge', group='binding')
self.addCleanup(CONF.clear_override, 'link_iface', group='binding')
def test_connect(self):
self._test_connect()
self.assertEqual(1, self.h_ipdb_exit.call_count)
self.assertEqual(2, self.c_ipdb_exit.call_count)
self.assertEqual(self.ifname, self.m_h_iface.ifname)
self.assertEqual(1, self.m_h_iface.mtu)
self.assertEqual(str(self.vif.address), self.m_h_iface.address)
self.m_h_iface.up.assert_called_once_with()
def test_disconnect(self):
self._test_disconnect()
class TestNestedMacvlanDriver(TestDriverMixin, test_base.TestCase):
def setUp(self):
super(TestNestedMacvlanDriver, self).setUp()
self.vif = fake._fake_vif(objects.vif.VIFMacvlanNested)
CONF.set_override('link_iface', 'bridge', group='binding')
self.addCleanup(CONF.clear_override, 'link_iface', group='binding')
def test_connect(self):
self._test_connect()
self.assertEqual(1, self.h_ipdb_exit.call_count)
self.assertEqual(2, self.c_ipdb_exit.call_count)
self.assertEqual(self.ifname, self.m_h_iface.ifname)
self.assertEqual(1, self.m_h_iface.mtu)
self.assertEqual(str(self.vif.address), self.m_h_iface.address)
self.m_h_iface.up.assert_called_once_with()
def test_disconnect(self):
self._test_disconnect()
class TestSriovDriver(TestDriverMixin, test_base.TestCase):
def setUp(self):
super(TestSriovDriver, self).setUp()
self.vif = fake._fake_vif(objects.vif.VIFSriov)
self.vif.physnet = 'test_physnet'
@mock.patch('kuryr_kubernetes.cni.binding.sriov.VIFSriovDriver.'
'_get_host_pf_names')
@mock.patch('kuryr_kubernetes.cni.binding.sriov.VIFSriovDriver.'
'_get_available_vf_info')
def test_connect(self, m_avail_vf_info, m_host_pf_names):
m_avail_vf_info.return_value = [self.ifname, 1, 'h_interface']
m_host_pf_names.return_value = 'h_interface'
self._test_connect()
self.assertEqual(self.ifname, self.m_c_iface.ifname)
self.assertEqual(1, self.m_c_iface.mtu)
self.assertEqual(str(self.vif.address), self.m_c_iface.address)
self.m_c_iface.up.assert_called_once_with()
def test_disconnect(self):
self._test_disconnect()
| kuryr_kubernetes/tests/unit/cni/test_binding.py | 9,287 | Copyright 2017 Red Hat, Inc. 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. Mock IPDB context managers | 626 | en | 0.866552 |
# -*- coding: utf-8 -*- #
# Copyright 2017 Google Inc. 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.
"""Command for creating VM instances running Docker images."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import containers_utils
from googlecloudsdk.api_lib.compute import image_utils
from googlecloudsdk.api_lib.compute import instance_utils
from googlecloudsdk.api_lib.compute import metadata_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.compute import completers
from googlecloudsdk.command_lib.compute.instances import flags as instances_flags
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import log
from six.moves import zip
def _Args(parser, deprecate_maintenance_policy=False,
container_mount_enabled=False):
"""Add flags shared by all release tracks."""
parser.display_info.AddFormat(instances_flags.DEFAULT_LIST_FORMAT)
metadata_utils.AddMetadataArgs(parser)
instances_flags.AddDiskArgs(
parser, True, container_mount_enabled=container_mount_enabled)
instances_flags.AddCreateDiskArgs(
parser, container_mount_enabled=container_mount_enabled)
instances_flags.AddCanIpForwardArgs(parser)
instances_flags.AddAddressArgs(parser, instances=True)
instances_flags.AddMachineTypeArgs(parser)
instances_flags.AddMaintenancePolicyArgs(
parser, deprecate=deprecate_maintenance_policy)
instances_flags.AddNoRestartOnFailureArgs(parser)
instances_flags.AddPreemptibleVmArgs(parser)
instances_flags.AddServiceAccountAndScopeArgs(parser, False)
instances_flags.AddTagsArgs(parser)
instances_flags.AddCustomMachineTypeArgs(parser)
instances_flags.AddNetworkArgs(parser)
instances_flags.AddPrivateNetworkIpArgs(parser)
instances_flags.AddKonletArgs(parser)
instances_flags.AddPublicDnsArgs(parser, instance=True)
instances_flags.AddPublicPtrArgs(parser, instance=True)
instances_flags.AddImageArgs(parser)
labels_util.AddCreateLabelsFlags(parser)
parser.add_argument(
'--description',
help='Specifies a textual description of the instances.')
instances_flags.INSTANCES_ARG.AddArgument(parser, operation_type='create')
CreateWithContainer.SOURCE_INSTANCE_TEMPLATE = (
instances_flags.MakeSourceInstanceTemplateArg())
CreateWithContainer.SOURCE_INSTANCE_TEMPLATE.AddArgument(parser)
parser.display_info.AddCacheUpdater(completers.InstancesCompleter)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class CreateWithContainer(base.CreateCommand):
"""Command for creating VM instances running container images."""
@staticmethod
def Args(parser):
"""Register parser args."""
_Args(parser)
instances_flags.AddNetworkTierArgs(parser, instance=True)
instances_flags.AddMinCpuPlatformArgs(parser, base.ReleaseTrack.GA)
def _ValidateArgs(self, args):
instances_flags.ValidateNicFlags(args)
instances_flags.ValidateNetworkTierArgs(args)
instances_flags.ValidateKonletArgs(args)
instances_flags.ValidateDiskCommonFlags(args)
instances_flags.ValidateServiceAccountAndScopeArgs(args)
if instance_utils.UseExistingBootDisk(args.disk or []):
raise exceptions.InvalidArgumentException(
'--disk',
'Boot disk specified for containerized VM.')
def GetImageUri(self, args, client, holder, instance_refs):
if (args.IsSpecified('image') or args.IsSpecified('image_family') or
args.IsSpecified('image_project')):
image_expander = image_utils.ImageExpander(client, holder.resources)
image_uri, _ = image_expander.ExpandImageFlag(
user_project=instance_refs[0].project,
image=args.image,
image_family=args.image_family,
image_project=args.image_project)
if holder.resources.Parse(image_uri).project != 'cos-cloud':
log.warning('This container deployment mechanism requires a '
'Container-Optimized OS image in order to work. Select an '
'image from a cos-cloud project (cost-stable, cos-beta, '
'cos-dev image families).')
else:
image_uri = containers_utils.ExpandKonletCosImageFlag(client)
return image_uri
def _GetNetworkInterfaces(
self, args, client, holder, instance_refs, skip_defaults):
return instance_utils.GetNetworkInterfaces(args, client, holder,
instance_refs, skip_defaults)
def GetNetworkInterfaces(
self, args, resources, client, holder, instance_refs, skip_defaults):
if args.network_interface:
return instance_utils.CreateNetworkInterfaceMessages(
resources=resources,
compute_client=client,
network_interface_arg=args.network_interface,
instance_refs=instance_refs)
return self._GetNetworkInterfaces(
args, client, holder, instance_refs, skip_defaults)
def Run(self, args):
self._ValidateArgs(args)
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
source_instance_template = instance_utils.GetSourceInstanceTemplate(
args, holder.resources, self.SOURCE_INSTANCE_TEMPLATE)
skip_defaults = instance_utils.GetSkipDefaults(source_instance_template)
scheduling = instance_utils.GetScheduling(args, client, skip_defaults)
service_accounts = instance_utils.GetServiceAccounts(
args, client, skip_defaults)
user_metadata = instance_utils.GetValidatedMetadata(args, client)
boot_disk_size_gb = instance_utils.GetBootDiskSizeGb(args)
instance_refs = instance_utils.GetInstanceRefs(args, client, holder)
network_interfaces = self.GetNetworkInterfaces(
args, holder.resources, client, holder, instance_refs, skip_defaults)
machine_type_uris = instance_utils.GetMachineTypeUris(
args, client, holder, instance_refs, skip_defaults)
image_uri = self.GetImageUri(args, client, holder, instance_refs)
labels = containers_utils.GetLabelsMessageWithCosVersion(
args.labels, image_uri, holder.resources, client.messages.Instance)
can_ip_forward = instance_utils.GetCanIpForward(args, skip_defaults)
tags = containers_utils.CreateTagsMessage(client.messages, args.tags)
requests = []
for instance_ref, machine_type_uri in zip(instance_refs, machine_type_uris):
metadata = containers_utils.CreateKonletMetadataMessage(
client.messages, args, instance_ref.Name(), user_metadata)
disks = instance_utils.CreateDiskMessages(
holder, args, boot_disk_size_gb, image_uri, instance_ref,
skip_defaults)
request = client.messages.ComputeInstancesInsertRequest(
instance=client.messages.Instance(
canIpForward=can_ip_forward,
disks=disks,
description=args.description,
labels=labels,
machineType=machine_type_uri,
metadata=metadata,
minCpuPlatform=args.min_cpu_platform,
name=instance_ref.Name(),
networkInterfaces=network_interfaces,
serviceAccounts=service_accounts,
scheduling=scheduling,
tags=tags),
sourceInstanceTemplate=source_instance_template,
project=instance_ref.project,
zone=instance_ref.zone)
requests.append((client.apitools_client.instances,
'Insert', request))
return client.MakeRequests(requests)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class CreateWithContainerBeta(CreateWithContainer):
"""Command for creating VM instances running container images."""
@staticmethod
def Args(parser):
"""Register parser args."""
_Args(parser, container_mount_enabled=True)
instances_flags.AddNetworkTierArgs(parser, instance=True)
instances_flags.AddContainerMountDiskFlag(parser)
instances_flags.AddLocalSsdArgsWithSize(parser)
instances_flags.AddMinCpuPlatformArgs(parser, base.ReleaseTrack.BETA)
def _ValidateArgs(self, args):
instances_flags.ValidateLocalSsdFlags(args)
super(CreateWithContainerBeta, self)._ValidateArgs(args)
def GetImageUri(self, args, client, holder, instance_refs):
if (args.IsSpecified('image') or args.IsSpecified('image_family') or
args.IsSpecified('image_project')):
image_expander = image_utils.ImageExpander(client, holder.resources)
image_uri, _ = image_expander.ExpandImageFlag(
user_project=instance_refs[0].project,
image=args.image,
image_family=args.image_family,
image_project=args.image_project)
if holder.resources.Parse(image_uri).project != 'cos-cloud':
log.warning('This container deployment mechanism requires a '
'Container-Optimized OS image in order to work. Select an '
'image from a cos-cloud project (cost-stable, cos-beta, '
'cos-dev image families).')
else:
image_uri = containers_utils.ExpandKonletCosImageFlag(client)
return image_uri
def Run(self, args):
self._ValidateArgs(args)
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
container_mount_disk = instances_flags.GetValidatedContainerMountDisk(
holder,
args.container_mount_disk,
args.disk,
args.create_disk)
client = holder.client
source_instance_template = instance_utils.GetSourceInstanceTemplate(
args, holder.resources, self.SOURCE_INSTANCE_TEMPLATE)
skip_defaults = instance_utils.GetSkipDefaults(source_instance_template)
scheduling = instance_utils.GetScheduling(args, client, skip_defaults)
service_accounts = instance_utils.GetServiceAccounts(
args, client, skip_defaults)
user_metadata = instance_utils.GetValidatedMetadata(args, client)
boot_disk_size_gb = instance_utils.GetBootDiskSizeGb(args)
instance_refs = instance_utils.GetInstanceRefs(args, client, holder)
network_interfaces = self.GetNetworkInterfaces(
args, holder.resources, client, holder, instance_refs, skip_defaults)
machine_type_uris = instance_utils.GetMachineTypeUris(
args, client, holder, instance_refs, skip_defaults)
image_uri = self.GetImageUri(args, client, holder, instance_refs)
labels = containers_utils.GetLabelsMessageWithCosVersion(
args.labels, image_uri, holder.resources, client.messages.Instance)
can_ip_forward = instance_utils.GetCanIpForward(args, skip_defaults)
tags = containers_utils.CreateTagsMessage(client.messages, args.tags)
requests = []
for instance_ref, machine_type_uri in zip(instance_refs, machine_type_uris):
metadata = containers_utils.CreateKonletMetadataMessage(
client.messages, args, instance_ref.Name(), user_metadata,
container_mount_disk_enabled=True,
container_mount_disk=container_mount_disk)
disks = instance_utils.CreateDiskMessages(
holder, args, boot_disk_size_gb, image_uri, instance_ref,
skip_defaults, match_container_mount_disks=True)
request = client.messages.ComputeInstancesInsertRequest(
instance=client.messages.Instance(
canIpForward=can_ip_forward,
disks=disks,
description=args.description,
labels=labels,
machineType=machine_type_uri,
metadata=metadata,
minCpuPlatform=args.min_cpu_platform,
name=instance_ref.Name(),
networkInterfaces=network_interfaces,
serviceAccounts=service_accounts,
scheduling=scheduling,
tags=tags),
sourceInstanceTemplate=source_instance_template,
project=instance_ref.project,
zone=instance_ref.zone)
requests.append((client.apitools_client.instances,
'Insert', request))
return client.MakeRequests(requests)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateWithContainerAlpha(CreateWithContainerBeta):
"""Alpha version of compute instances create-with-container command."""
@staticmethod
def Args(parser):
_Args(parser, deprecate_maintenance_policy=True,
container_mount_enabled=True)
instances_flags.AddNetworkTierArgs(parser, instance=True)
instances_flags.AddContainerMountDiskFlag(parser)
instances_flags.AddLocalSsdArgsWithSize(parser)
instances_flags.AddLocalNvdimmArgs(parser)
instances_flags.AddMinCpuPlatformArgs(parser, base.ReleaseTrack.ALPHA)
def _GetNetworkInterfaces(
self, args, client, holder, instance_refs, skip_defaults):
return instance_utils.GetNetworkInterfacesAlpha(
args, client, holder, instance_refs, skip_defaults)
def Run(self, args):
self._ValidateArgs(args)
instances_flags.ValidatePublicDnsFlags(args)
instances_flags.ValidatePublicPtrFlags(args)
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
container_mount_disk = instances_flags.GetValidatedContainerMountDisk(
holder,
args.container_mount_disk,
args.disk,
args.create_disk)
client = holder.client
source_instance_template = instance_utils.GetSourceInstanceTemplate(
args, holder.resources, self.SOURCE_INSTANCE_TEMPLATE)
skip_defaults = instance_utils.GetSkipDefaults(source_instance_template)
scheduling = instance_utils.GetScheduling(args, client, skip_defaults)
service_accounts = instance_utils.GetServiceAccounts(
args, client, skip_defaults)
user_metadata = instance_utils.GetValidatedMetadata(args, client)
boot_disk_size_gb = instance_utils.GetBootDiskSizeGb(args)
instance_refs = instance_utils.GetInstanceRefs(args, client, holder)
network_interfaces = self.GetNetworkInterfaces(
args, holder.resources, client, holder, instance_refs, skip_defaults)
machine_type_uris = instance_utils.GetMachineTypeUris(
args, client, holder, instance_refs, skip_defaults)
image_uri = self.GetImageUri(args, client, holder, instance_refs)
labels = containers_utils.GetLabelsMessageWithCosVersion(
args.labels, image_uri, holder.resources, client.messages.Instance)
can_ip_forward = instance_utils.GetCanIpForward(args, skip_defaults)
tags = containers_utils.CreateTagsMessage(client.messages, args.tags)
requests = []
for instance_ref, machine_type_uri in zip(instance_refs, machine_type_uris):
metadata = containers_utils.CreateKonletMetadataMessage(
client.messages, args, instance_ref.Name(), user_metadata,
container_mount_disk_enabled=True,
container_mount_disk=container_mount_disk)
disks = instance_utils.CreateDiskMessages(
holder, args, boot_disk_size_gb, image_uri, instance_ref,
skip_defaults, match_container_mount_disks=True)
request = client.messages.ComputeInstancesInsertRequest(
instance=client.messages.Instance(
canIpForward=can_ip_forward,
disks=disks,
description=args.description,
labels=labels,
machineType=machine_type_uri,
metadata=metadata,
minCpuPlatform=args.min_cpu_platform,
name=instance_ref.Name(),
networkInterfaces=network_interfaces,
serviceAccounts=service_accounts,
scheduling=scheduling,
tags=tags),
sourceInstanceTemplate=source_instance_template,
project=instance_ref.project,
zone=instance_ref.zone)
requests.append((client.apitools_client.instances,
'Insert', request))
return client.MakeRequests(requests)
CreateWithContainer.detailed_help = {
'brief':
"""\
Creates Google Compute engine virtual machine instances running
container images.
""",
'DESCRIPTION':
"""\
*{command}* creates Google Compute Engine virtual
machines that runs a Docker image. For example:
$ {command} instance-1 --zone us-central1-a \
--container-image=gcr.io/google-containers/busybox
creates an instance called instance-1, in the us-central1-a zone,
running the 'busybox' image.
For more examples, refer to the *EXAMPLES* section below.
""",
'EXAMPLES':
"""\
To run the gcr.io/google-containers/busybox image on an instance named
'instance-1' that executes 'echo "Hello world"' as a run command, run:
$ {command} instance-1 \
--container-image=gcr.io/google-containers/busybox \
--container-command='echo "Hello world"'
To run the gcr.io/google-containers/busybox image in privileged mode,
run:
$ {command} instance-1 \
--container-image=gcr.io/google-containers/busybox
--container-privileged
"""
}
| lib/surface/compute/instances/create_with_container.py | 17,613 | Command for creating VM instances running container images.
Alpha version of compute instances create-with-container command.
Command for creating VM instances running container images.
Register parser args.
Register parser args.
Add flags shared by all release tracks.
Command for creating VM instances running Docker images.
-*- coding: utf-8 -*- Copyright 2017 Google Inc. 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. | 920 | en | 0.830743 |
"""Utility functions and classes
"""
import sys
import inspect
import warnings
import importlib.util
from enum import Enum
from pathlib import Path
from weakref import WeakSet
from collections import namedtuple
from functools import partial, wraps
from types import ModuleType, MethodType
from typing import Union, Callable, Optional, Mapping, Any, Dict, Tuple
import numpy as np
from numpy import random
from scipy import sparse
from anndata import AnnData, __version__ as anndata_version
from textwrap import dedent
from packaging import version
from ._settings import settings
from ._compat import Literal
from . import logging as logg
class Empty(Enum):
token = 0
_empty = Empty.token
# e.g. https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html
AnyRandom = Union[None, int, random.RandomState] # maybe in the future random.Generator
EPS = 1e-15
def check_versions():
from ._compat import pkg_version
umap_version = pkg_version("umap-learn")
if version.parse(anndata_version) < version.parse('0.6.10'):
from . import __version__
raise ImportError(
f'Scanpy {__version__} needs anndata version >=0.6.10, '
f'not {anndata_version}.\nRun `pip install anndata -U --no-deps`.'
)
if umap_version < version.parse('0.3.0'):
from . import __version__
# make this a warning, not an error
# it might be useful for people to still be able to run it
logg.warning(
f'Scanpy {__version__} needs umap ' f'version >=0.3.0, not {umap_version}.'
)
def getdoc(c_or_f: Union[Callable, type]) -> Optional[str]:
if getattr(c_or_f, '__doc__', None) is None:
return None
doc = inspect.getdoc(c_or_f)
if isinstance(c_or_f, type) and hasattr(c_or_f, '__init__'):
sig = inspect.signature(c_or_f.__init__)
else:
sig = inspect.signature(c_or_f)
def type_doc(name: str):
param: inspect.Parameter = sig.parameters[name]
cls = getattr(param.annotation, '__qualname__', repr(param.annotation))
if param.default is not param.empty:
return f'{cls}, optional (default: {param.default!r})'
else:
return cls
return '\n'.join(
f'{line} : {type_doc(line)}' if line.strip() in sig.parameters else line
for line in doc.split('\n')
)
def deprecated_arg_names(arg_mapping: Mapping[str, str]):
"""
Decorator which marks a functions keyword arguments as deprecated. It will
result in a warning being emitted when the deprecated keyword argument is
used, and the function being called with the new argument.
Parameters
----------
arg_mapping
Mapping from deprecated argument name to current argument name.
"""
def decorator(func):
@wraps(func)
def func_wrapper(*args, **kwargs):
warnings.simplefilter('always', DeprecationWarning) # turn off filter
for old, new in arg_mapping.items():
if old in kwargs:
warnings.warn(
f"Keyword argument '{old}' has been "
f"deprecated in favour of '{new}'. "
f"'{old}' will be removed in a future version.",
category=DeprecationWarning,
stacklevel=2,
)
val = kwargs.pop(old)
kwargs[new] = val
# reset filter
warnings.simplefilter('default', DeprecationWarning)
return func(*args, **kwargs)
return func_wrapper
return decorator
def _one_of_ours(obj, root: str):
return (
hasattr(obj, "__name__")
and not obj.__name__.split(".")[-1].startswith("_")
and getattr(
obj, '__module__', getattr(obj, '__qualname__', obj.__name__)
).startswith(root)
)
def descend_classes_and_funcs(mod: ModuleType, root: str, encountered=None):
if encountered is None:
encountered = WeakSet()
for obj in vars(mod).values():
if not _one_of_ours(obj, root):
continue
if callable(obj) and not isinstance(obj, MethodType):
yield obj
if isinstance(obj, type):
for m in vars(obj).values():
if callable(m) and _one_of_ours(m, root):
yield m
elif isinstance(obj, ModuleType) and obj not in encountered:
if obj.__name__.startswith('scanpy.tests'):
# Python’s import mechanism seems to add this to `scanpy`’s attributes
continue
encountered.add(obj)
yield from descend_classes_and_funcs(obj, root, encountered)
def annotate_doc_types(mod: ModuleType, root: str):
for c_or_f in descend_classes_and_funcs(mod, root):
c_or_f.getdoc = partial(getdoc, c_or_f)
def _doc_params(**kwds):
"""\
Docstrings should start with "\" in the first line for proper formatting.
"""
def dec(obj):
obj.__orig_doc__ = obj.__doc__
obj.__doc__ = dedent(obj.__doc__).format_map(kwds)
return obj
return dec
def _check_array_function_arguments(**kwargs):
"""Checks for invalid arguments when an array is passed.
Helper for functions that work on either AnnData objects or array-likes.
"""
# TODO: Figure out a better solution for documenting dispatched functions
invalid_args = [k for k, v in kwargs.items() if v is not None]
if len(invalid_args) > 0:
raise TypeError(
f"Arguments {invalid_args} are only valid if an AnnData object is passed."
)
def _check_use_raw(adata: AnnData, use_raw: Union[None, bool]) -> bool:
"""
Normalize checking `use_raw`.
My intentention here is to also provide a single place to throw a deprecation warning from in future.
"""
if use_raw is not None:
return use_raw
else:
if adata.raw is not None:
return True
else:
return False
# --------------------------------------------------------------------------------
# Graph stuff
# --------------------------------------------------------------------------------
def get_igraph_from_adjacency(adjacency, directed=None):
"""Get igraph graph from adjacency matrix."""
import igraph as ig
sources, targets = adjacency.nonzero()
weights = adjacency[sources, targets]
if isinstance(weights, np.matrix):
weights = weights.A1
g = ig.Graph(directed=directed)
g.add_vertices(adjacency.shape[0]) # this adds adjacency.shape[0] vertices
g.add_edges(list(zip(sources, targets)))
try:
g.es['weight'] = weights
except:
pass
if g.vcount() != adjacency.shape[0]:
logg.warning(
f'The constructed graph has only {g.vcount()} nodes. '
'Your adjacency matrix contained redundant nodes.'
)
return g
def get_sparse_from_igraph(graph, weight_attr=None):
from scipy.sparse import csr_matrix
edges = graph.get_edgelist()
if weight_attr is None:
weights = [1] * len(edges)
else:
weights = graph.es[weight_attr]
if not graph.is_directed():
edges.extend([(v, u) for u, v in edges])
weights.extend(weights)
shape = graph.vcount()
shape = (shape, shape)
if len(edges) > 0:
return csr_matrix((weights, zip(*edges)), shape=shape)
else:
return csr_matrix(shape)
# --------------------------------------------------------------------------------
# Group stuff
# --------------------------------------------------------------------------------
def compute_association_matrix_of_groups(
adata: AnnData,
prediction: str,
reference: str,
normalization: Literal['prediction', 'reference'] = 'prediction',
threshold: float = 0.01,
max_n_names: Optional[int] = 2,
):
"""Compute overlaps between groups.
See ``identify_groups`` for identifying the groups.
Parameters
----------
adata
prediction
Field name of adata.obs.
reference
Field name of adata.obs.
normalization
Whether to normalize with respect to the predicted groups or the
reference groups.
threshold
Do not consider associations whose overlap is below this fraction.
max_n_names
Control how many reference names you want to be associated with per
predicted name. Set to `None`, if you want all.
Returns
-------
asso_names
List of associated reference names
(`max_n_names` for each predicted name).
asso_matrix
Matrix where rows correspond to the predicted labels and columns to the
reference labels, entries are proportional to degree of association.
"""
if normalization not in {'prediction', 'reference'}:
raise ValueError(
'`normalization` needs to be either "prediction" or "reference".'
)
sanitize_anndata(adata)
cats = adata.obs[reference].cat.categories
for cat in cats:
if cat in settings.categories_to_ignore:
logg.info(
f'Ignoring category {cat!r} '
'as it’s in `settings.categories_to_ignore`.'
)
asso_names = []
asso_matrix = []
for ipred_group, pred_group in enumerate(adata.obs[prediction].cat.categories):
if '?' in pred_group:
pred_group = str(ipred_group)
# starting from numpy version 1.13, subtractions of boolean arrays are deprecated
mask_pred = adata.obs[prediction].values == pred_group
mask_pred_int = mask_pred.astype(np.int8)
asso_matrix += [[]]
for ref_group in adata.obs[reference].cat.categories:
mask_ref = (adata.obs[reference].values == ref_group).astype(np.int8)
mask_ref_or_pred = mask_ref.copy()
mask_ref_or_pred[mask_pred] = 1
# e.g. if the pred group is contained in mask_ref, mask_ref and
# mask_ref_or_pred are the same
if normalization == 'prediction':
# compute which fraction of the predicted group is contained in
# the ref group
ratio_contained = (
np.sum(mask_pred_int) - np.sum(mask_ref_or_pred - mask_ref)
) / np.sum(mask_pred_int)
else:
# compute which fraction of the reference group is contained in
# the predicted group
ratio_contained = (
np.sum(mask_ref) - np.sum(mask_ref_or_pred - mask_pred_int)
) / np.sum(mask_ref)
asso_matrix[-1] += [ratio_contained]
name_list_pred = [
cats[i] if cats[i] not in settings.categories_to_ignore else ''
for i in np.argsort(asso_matrix[-1])[::-1]
if asso_matrix[-1][i] > threshold
]
asso_names += ['\n'.join(name_list_pred[:max_n_names])]
Result = namedtuple(
'compute_association_matrix_of_groups', ['asso_names', 'asso_matrix']
)
return Result(asso_names=asso_names, asso_matrix=np.array(asso_matrix))
def get_associated_colors_of_groups(reference_colors, asso_matrix):
return [
{
reference_colors[i_ref]: asso_matrix[i_pred, i_ref]
for i_ref in range(asso_matrix.shape[1])
}
for i_pred in range(asso_matrix.shape[0])
]
def identify_groups(ref_labels, pred_labels, return_overlaps=False):
"""Which predicted label explains which reference label?
A predicted label explains the reference label which maximizes the minimum
of ``relative_overlaps_pred`` and ``relative_overlaps_ref``.
Compare this with ``compute_association_matrix_of_groups``.
Returns
-------
A dictionary of length ``len(np.unique(ref_labels))`` that stores for each
reference label the predicted label that best explains it.
If ``return_overlaps`` is ``True``, this will in addition return the overlap
of the reference group with the predicted group; normalized with respect to
the reference group size and the predicted group size, respectively.
"""
ref_unique, ref_counts = np.unique(ref_labels, return_counts=True)
ref_dict = dict(zip(ref_unique, ref_counts))
pred_unique, pred_counts = np.unique(pred_labels, return_counts=True)
pred_dict = dict(zip(pred_unique, pred_counts))
associated_predictions = {}
associated_overlaps = {}
for ref_label in ref_unique:
sub_pred_unique, sub_pred_counts = np.unique(
pred_labels[ref_label == ref_labels], return_counts=True
)
relative_overlaps_pred = [
sub_pred_counts[i] / pred_dict[n] for i, n in enumerate(sub_pred_unique)
]
relative_overlaps_ref = [
sub_pred_counts[i] / ref_dict[ref_label]
for i, n in enumerate(sub_pred_unique)
]
relative_overlaps = np.c_[relative_overlaps_pred, relative_overlaps_ref]
relative_overlaps_min = np.min(relative_overlaps, axis=1)
pred_best_index = np.argsort(relative_overlaps_min)[::-1]
associated_predictions[ref_label] = sub_pred_unique[pred_best_index]
associated_overlaps[ref_label] = relative_overlaps[pred_best_index]
if return_overlaps:
return associated_predictions, associated_overlaps
else:
return associated_predictions
# --------------------------------------------------------------------------------
# Other stuff
# --------------------------------------------------------------------------------
# backwards compat... remove this in the future
def sanitize_anndata(adata):
"""Transform string annotations to categoricals."""
adata._sanitize()
def view_to_actual(adata):
if adata.is_view:
warnings.warn(
"Revieved a view of an AnnData. Making a copy.",
stacklevel=2,
)
adata._init_as_actual(adata.copy())
def moving_average(a: np.ndarray, n: int):
"""Moving average over one-dimensional array.
Parameters
----------
a
One-dimensional array.
n
Number of entries to average over. n=2 means averaging over the currrent
the previous entry.
Returns
-------
An array view storing the moving average.
"""
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1 :] / n
# --------------------------------------------------------------------------------
# Deal with tool parameters
# --------------------------------------------------------------------------------
def update_params(
old_params: Mapping[str, Any],
new_params: Mapping[str, Any],
check=False,
) -> Dict[str, Any]:
"""\
Update old_params with new_params.
If check==False, this merely adds and overwrites the content of old_params.
If check==True, this only allows updating of parameters that are already
present in old_params.
Parameters
----------
old_params
new_params
check
Returns
-------
updated_params
"""
updated_params = dict(old_params)
if new_params: # allow for new_params to be None
for key, val in new_params.items():
if key not in old_params and check:
raise ValueError(
'\''
+ key
+ '\' is not a valid parameter key, '
+ 'consider one of \n'
+ str(list(old_params.keys()))
)
if val is not None:
updated_params[key] = val
return updated_params
# --------------------------------------------------------------------------------
# Others
# --------------------------------------------------------------------------------
def check_nonnegative_integers(X: Union[np.ndarray, sparse.spmatrix]):
"""Checks values of X to ensure it is count data"""
from numbers import Integral
data = X if isinstance(X, np.ndarray) else X.data
# Check no negatives
if np.signbit(data).any():
return False
# Check all are integers
elif issubclass(data.dtype.type, Integral):
return True
elif np.any(~np.equal(np.mod(data, 1), 0)):
return False
else:
return True
def select_groups(adata, groups_order_subset='all', key='groups'):
"""Get subset of groups in adata.obs[key]."""
groups_order = adata.obs[key].cat.categories
if key + '_masks' in adata.uns:
groups_masks = adata.uns[key + '_masks']
else:
groups_masks = np.zeros(
(len(adata.obs[key].cat.categories), adata.obs[key].values.size), dtype=bool
)
for iname, name in enumerate(adata.obs[key].cat.categories):
# if the name is not found, fallback to index retrieval
if adata.obs[key].cat.categories[iname] in adata.obs[key].values:
mask = adata.obs[key].cat.categories[iname] == adata.obs[key].values
else:
mask = str(iname) == adata.obs[key].values
groups_masks[iname] = mask
groups_ids = list(range(len(groups_order)))
if groups_order_subset != 'all':
groups_ids = []
for name in groups_order_subset:
groups_ids.append(
np.where(adata.obs[key].cat.categories.values == name)[0][0]
)
if len(groups_ids) == 0:
# fallback to index retrieval
groups_ids = np.where(
np.in1d(
np.arange(len(adata.obs[key].cat.categories)).astype(str),
np.array(groups_order_subset),
)
)[0]
if len(groups_ids) == 0:
logg.debug(
f'{np.array(groups_order_subset)} invalid! specify valid '
f'groups_order (or indices) from {adata.obs[key].cat.categories}',
)
from sys import exit
exit(0)
groups_masks = groups_masks[groups_ids]
groups_order_subset = adata.obs[key].cat.categories[groups_ids].values
else:
groups_order_subset = groups_order.values
return groups_order_subset, groups_masks
def warn_with_traceback(message, category, filename, lineno, file=None, line=None):
"""Get full tracebacks when warning is raised by setting
warnings.showwarning = warn_with_traceback
See also
--------
http://stackoverflow.com/questions/22373927/get-traceback-of-warnings
"""
import traceback
traceback.print_stack()
log = file if hasattr(file, 'write') else sys.stderr
settings.write(warnings.formatwarning(message, category, filename, lineno, line))
def subsample(
X: np.ndarray,
subsample: int = 1,
seed: int = 0,
) -> Tuple[np.ndarray, np.ndarray]:
"""\
Subsample a fraction of 1/subsample samples from the rows of X.
Parameters
----------
X
Data array.
subsample
1/subsample is the fraction of data sampled, n = X.shape[0]/subsample.
seed
Seed for sampling.
Returns
-------
Xsampled
Subsampled X.
rows
Indices of rows that are stored in Xsampled.
"""
if subsample == 1 and seed == 0:
return X, np.arange(X.shape[0], dtype=int)
if seed == 0:
# this sequence is defined simply by skipping rows
# is faster than sampling
rows = np.arange(0, X.shape[0], subsample, dtype=int)
n = rows.size
Xsampled = np.array(X[rows])
else:
if seed < 0:
raise ValueError(f'Invalid seed value < 0: {seed}')
n = int(X.shape[0] / subsample)
np.random.seed(seed)
Xsampled, rows = subsample_n(X, n=n)
logg.debug(f'... subsampled to {n} of {X.shape[0]} data points')
return Xsampled, rows
def subsample_n(
X: np.ndarray, n: int = 0, seed: int = 0
) -> Tuple[np.ndarray, np.ndarray]:
"""Subsample n samples from rows of array.
Parameters
----------
X
Data array.
n
Sample size.
seed
Seed for sampling.
Returns
-------
Xsampled
Subsampled X.
rows
Indices of rows that are stored in Xsampled.
"""
if n < 0:
raise ValueError('n must be greater 0')
np.random.seed(seed)
n = X.shape[0] if (n == 0 or n > X.shape[0]) else n
rows = np.random.choice(X.shape[0], size=n, replace=False)
Xsampled = X[rows]
return Xsampled, rows
def check_presence_download(filename: Path, backup_url):
"""Check if file is present otherwise download."""
if not filename.is_file():
from .readwrite import _download
_download(backup_url, filename)
def lazy_import(full_name):
"""Imports a module in a way that it’s only executed on member access"""
try:
return sys.modules[full_name]
except KeyError:
spec = importlib.util.find_spec(full_name)
module = importlib.util.module_from_spec(spec)
loader = importlib.util.LazyLoader(spec.loader)
# Make module with proper locking and get it inserted into sys.modules.
loader.exec_module(module)
return module
# --------------------------------------------------------------------------------
# Neighbors
# --------------------------------------------------------------------------------
def _fallback_to_uns(dct, conns, dists, conns_key, dists_key):
if conns is None and conns_key in dct:
conns = dct[conns_key]
if dists is None and dists_key in dct:
dists = dct[dists_key]
return conns, dists
class NeighborsView:
"""Convenience class for accessing neighbors graph representations.
Allows to access neighbors distances, connectivities and settings
dictionary in a uniform manner.
Parameters
----------
adata
AnnData object.
key
This defines where to look for neighbors dictionary,
connectivities, distances.
neigh = NeighborsView(adata, key)
neigh['distances']
neigh['connectivities']
neigh['params']
'connectivities' in neigh
'params' in neigh
is the same as
adata.obsp[adata.uns[key]['distances_key']]
adata.obsp[adata.uns[key]['connectivities_key']]
adata.uns[key]['params']
adata.uns[key]['connectivities_key'] in adata.obsp
'params' in adata.uns[key]
"""
def __init__(self, adata, key=None):
self._connectivities = None
self._distances = None
if key is None or key == 'neighbors':
if 'neighbors' not in adata.uns:
raise KeyError('No "neighbors" in .uns')
self._neighbors_dict = adata.uns['neighbors']
self._conns_key = 'connectivities'
self._dists_key = 'distances'
else:
if key not in adata.uns:
raise KeyError(f'No "{key}" in .uns')
self._neighbors_dict = adata.uns[key]
self._conns_key = self._neighbors_dict['connectivities_key']
self._dists_key = self._neighbors_dict['distances_key']
if self._conns_key in adata.obsp:
self._connectivities = adata.obsp[self._conns_key]
if self._dists_key in adata.obsp:
self._distances = adata.obsp[self._dists_key]
# fallback to uns
self._connectivities, self._distances = _fallback_to_uns(
self._neighbors_dict,
self._connectivities,
self._distances,
self._conns_key,
self._dists_key,
)
def __getitem__(self, key):
if key == 'distances':
if 'distances' not in self:
raise KeyError(f'No "{self._dists_key}" in .obsp')
return self._distances
elif key == 'connectivities':
if 'connectivities' not in self:
raise KeyError(f'No "{self._conns_key}" in .obsp')
return self._connectivities
else:
return self._neighbors_dict[key]
def __contains__(self, key):
if key == 'distances':
return self._distances is not None
elif key == 'connectivities':
return self._connectivities is not None
else:
return key in self._neighbors_dict
def _choose_graph(adata, obsp, neighbors_key):
"""Choose connectivities from neighbbors or another obsp column"""
if obsp is not None and neighbors_key is not None:
raise ValueError(
'You can\'t specify both obsp, neighbors_key. ' 'Please select only one.'
)
if obsp is not None:
return adata.obsp[obsp]
else:
neighbors = NeighborsView(adata, neighbors_key)
if 'connectivities' not in neighbors:
raise ValueError(
'You need to run `pp.neighbors` first '
'to compute a neighborhood graph.'
)
return neighbors['connectivities']
| scanpy/_utils.py | 25,073 | Convenience class for accessing neighbors graph representations.
Allows to access neighbors distances, connectivities and settings
dictionary in a uniform manner.
Parameters
----------
adata
AnnData object.
key
This defines where to look for neighbors dictionary,
connectivities, distances.
neigh = NeighborsView(adata, key)
neigh['distances']
neigh['connectivities']
neigh['params']
'connectivities' in neigh
'params' in neigh
is the same as
adata.obsp[adata.uns[key]['distances_key']]
adata.obsp[adata.uns[key]['connectivities_key']]
adata.uns[key]['params']
adata.uns[key]['connectivities_key'] in adata.obsp
'params' in adata.uns[key]
Checks for invalid arguments when an array is passed.
Helper for functions that work on either AnnData objects or array-likes.
Normalize checking `use_raw`.
My intentention here is to also provide a single place to throw a deprecation warning from in future.
Choose connectivities from neighbbors or another obsp column
Docstrings should start with "" in the first line for proper formatting.
Checks values of X to ensure it is count data
Check if file is present otherwise download.
Compute overlaps between groups.
See ``identify_groups`` for identifying the groups.
Parameters
----------
adata
prediction
Field name of adata.obs.
reference
Field name of adata.obs.
normalization
Whether to normalize with respect to the predicted groups or the
reference groups.
threshold
Do not consider associations whose overlap is below this fraction.
max_n_names
Control how many reference names you want to be associated with per
predicted name. Set to `None`, if you want all.
Returns
-------
asso_names
List of associated reference names
(`max_n_names` for each predicted name).
asso_matrix
Matrix where rows correspond to the predicted labels and columns to the
reference labels, entries are proportional to degree of association.
Decorator which marks a functions keyword arguments as deprecated. It will
result in a warning being emitted when the deprecated keyword argument is
used, and the function being called with the new argument.
Parameters
----------
arg_mapping
Mapping from deprecated argument name to current argument name.
Get igraph graph from adjacency matrix.
Which predicted label explains which reference label?
A predicted label explains the reference label which maximizes the minimum
of ``relative_overlaps_pred`` and ``relative_overlaps_ref``.
Compare this with ``compute_association_matrix_of_groups``.
Returns
-------
A dictionary of length ``len(np.unique(ref_labels))`` that stores for each
reference label the predicted label that best explains it.
If ``return_overlaps`` is ``True``, this will in addition return the overlap
of the reference group with the predicted group; normalized with respect to
the reference group size and the predicted group size, respectively.
Imports a module in a way that it’s only executed on member access
Moving average over one-dimensional array.
Parameters
----------
a
One-dimensional array.
n
Number of entries to average over. n=2 means averaging over the currrent
the previous entry.
Returns
-------
An array view storing the moving average.
Transform string annotations to categoricals.
Get subset of groups in adata.obs[key].
Subsample a fraction of 1/subsample samples from the rows of X.
Parameters
----------
X
Data array.
subsample
1/subsample is the fraction of data sampled, n = X.shape[0]/subsample.
seed
Seed for sampling.
Returns
-------
Xsampled
Subsampled X.
rows
Indices of rows that are stored in Xsampled.
Subsample n samples from rows of array.
Parameters
----------
X
Data array.
n
Sample size.
seed
Seed for sampling.
Returns
-------
Xsampled
Subsampled X.
rows
Indices of rows that are stored in Xsampled.
Update old_params with new_params.
If check==False, this merely adds and overwrites the content of old_params.
If check==True, this only allows updating of parameters that are already
present in old_params.
Parameters
----------
old_params
new_params
check
Returns
-------
updated_params
Get full tracebacks when warning is raised by setting
warnings.showwarning = warn_with_traceback
See also
--------
http://stackoverflow.com/questions/22373927/get-traceback-of-warnings
Utility functions and classes
e.g. https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html maybe in the future random.Generator make this a warning, not an error it might be useful for people to still be able to run it turn off filter reset filter Python’s import mechanism seems to add this to `scanpy`’s attributes TODO: Figure out a better solution for documenting dispatched functions -------------------------------------------------------------------------------- Graph stuff -------------------------------------------------------------------------------- this adds adjacency.shape[0] vertices -------------------------------------------------------------------------------- Group stuff -------------------------------------------------------------------------------- starting from numpy version 1.13, subtractions of boolean arrays are deprecated e.g. if the pred group is contained in mask_ref, mask_ref and mask_ref_or_pred are the same compute which fraction of the predicted group is contained in the ref group compute which fraction of the reference group is contained in the predicted group -------------------------------------------------------------------------------- Other stuff -------------------------------------------------------------------------------- backwards compat... remove this in the future -------------------------------------------------------------------------------- Deal with tool parameters -------------------------------------------------------------------------------- allow for new_params to be None -------------------------------------------------------------------------------- Others -------------------------------------------------------------------------------- Check no negatives Check all are integers if the name is not found, fallback to index retrieval fallback to index retrieval this sequence is defined simply by skipping rows is faster than sampling Make module with proper locking and get it inserted into sys.modules. -------------------------------------------------------------------------------- Neighbors -------------------------------------------------------------------------------- fallback to uns | 6,588 | en | 0.713138 |
# -*- coding: utf-8 -*-
import warnings
from datetime import datetime, timedelta
import operator
import pytest
import numpy as np
import pandas as pd
from pandas.compat.numpy import np_datetime64_compat
import pandas.util.testing as tm
from pandas.errors import PerformanceWarning, NullFrequencyError
from pandas import (Timestamp, Timedelta, Series,
DatetimeIndex, TimedeltaIndex,
date_range)
from pandas._libs import tslib
from pandas._libs.tslibs.offsets import shift_months
@pytest.fixture(params=[None, 'UTC', 'Asia/Tokyo',
'US/Eastern', 'dateutil/Asia/Singapore',
'dateutil/US/Pacific'])
def tz(request):
return request.param
@pytest.fixture(params=[pd.offsets.Hour(2), timedelta(hours=2),
np.timedelta64(2, 'h'), Timedelta(hours=2)],
ids=str)
def delta(request):
# Several ways of representing two hours
return request.param
@pytest.fixture(
params=[
datetime(2011, 1, 1),
DatetimeIndex(['2011-01-01', '2011-01-02']),
DatetimeIndex(['2011-01-01', '2011-01-02']).tz_localize('US/Eastern'),
np.datetime64('2011-01-01'),
Timestamp('2011-01-01')],
ids=lambda x: type(x).__name__)
def addend(request):
return request.param
class TestDatetimeIndexComparisons(object):
@pytest.mark.parametrize('other', [datetime(2016, 1, 1),
Timestamp('2016-01-01'),
np.datetime64('2016-01-01')])
def test_dti_cmp_datetimelike(self, other, tz):
dti = pd.date_range('2016-01-01', periods=2, tz=tz)
if tz is not None:
if isinstance(other, np.datetime64):
# no tzaware version available
return
elif isinstance(other, Timestamp):
other = other.tz_localize(dti.tzinfo)
else:
other = tslib._localize_pydatetime(other, dti.tzinfo)
result = dti == other
expected = np.array([True, False])
tm.assert_numpy_array_equal(result, expected)
result = dti > other
expected = np.array([False, True])
tm.assert_numpy_array_equal(result, expected)
result = dti >= other
expected = np.array([True, True])
tm.assert_numpy_array_equal(result, expected)
result = dti < other
expected = np.array([False, False])
tm.assert_numpy_array_equal(result, expected)
result = dti <= other
expected = np.array([True, False])
tm.assert_numpy_array_equal(result, expected)
def dti_cmp_non_datetime(self, tz):
# GH#19301 by convention datetime.date is not considered comparable
# to Timestamp or DatetimeIndex. This may change in the future.
dti = pd.date_range('2016-01-01', periods=2, tz=tz)
other = datetime(2016, 1, 1).date()
assert not (dti == other).any()
assert (dti != other).all()
with pytest.raises(TypeError):
dti < other
with pytest.raises(TypeError):
dti <= other
with pytest.raises(TypeError):
dti > other
with pytest.raises(TypeError):
dti >= other
@pytest.mark.parametrize('other', [None, np.nan, pd.NaT])
def test_dti_eq_null_scalar(self, other, tz):
# GH#19301
dti = pd.date_range('2016-01-01', periods=2, tz=tz)
assert not (dti == other).any()
@pytest.mark.parametrize('other', [None, np.nan, pd.NaT])
def test_dti_ne_null_scalar(self, other, tz):
# GH#19301
dti = pd.date_range('2016-01-01', periods=2, tz=tz)
assert (dti != other).all()
@pytest.mark.parametrize('other', [None, np.nan])
def test_dti_cmp_null_scalar_inequality(self, tz, other):
# GH#19301
dti = pd.date_range('2016-01-01', periods=2, tz=tz)
with pytest.raises(TypeError):
dti < other
with pytest.raises(TypeError):
dti <= other
with pytest.raises(TypeError):
dti > other
with pytest.raises(TypeError):
dti >= other
def test_dti_cmp_nat(self):
left = pd.DatetimeIndex([pd.Timestamp('2011-01-01'), pd.NaT,
pd.Timestamp('2011-01-03')])
right = pd.DatetimeIndex([pd.NaT, pd.NaT, pd.Timestamp('2011-01-03')])
for lhs, rhs in [(left, right),
(left.astype(object), right.astype(object))]:
result = rhs == lhs
expected = np.array([False, False, True])
tm.assert_numpy_array_equal(result, expected)
result = lhs != rhs
expected = np.array([True, True, False])
tm.assert_numpy_array_equal(result, expected)
expected = np.array([False, False, False])
tm.assert_numpy_array_equal(lhs == pd.NaT, expected)
tm.assert_numpy_array_equal(pd.NaT == rhs, expected)
expected = np.array([True, True, True])
tm.assert_numpy_array_equal(lhs != pd.NaT, expected)
tm.assert_numpy_array_equal(pd.NaT != lhs, expected)
expected = np.array([False, False, False])
tm.assert_numpy_array_equal(lhs < pd.NaT, expected)
tm.assert_numpy_array_equal(pd.NaT > lhs, expected)
def test_dti_cmp_nat_behaves_like_float_cmp_nan(self):
fidx1 = pd.Index([1.0, np.nan, 3.0, np.nan, 5.0, 7.0])
fidx2 = pd.Index([2.0, 3.0, np.nan, np.nan, 6.0, 7.0])
didx1 = pd.DatetimeIndex(['2014-01-01', pd.NaT, '2014-03-01', pd.NaT,
'2014-05-01', '2014-07-01'])
didx2 = pd.DatetimeIndex(['2014-02-01', '2014-03-01', pd.NaT, pd.NaT,
'2014-06-01', '2014-07-01'])
darr = np.array([np_datetime64_compat('2014-02-01 00:00Z'),
np_datetime64_compat('2014-03-01 00:00Z'),
np_datetime64_compat('nat'), np.datetime64('nat'),
np_datetime64_compat('2014-06-01 00:00Z'),
np_datetime64_compat('2014-07-01 00:00Z')])
cases = [(fidx1, fidx2), (didx1, didx2), (didx1, darr)]
# Check pd.NaT is handles as the same as np.nan
with tm.assert_produces_warning(None):
for idx1, idx2 in cases:
result = idx1 < idx2
expected = np.array([True, False, False, False, True, False])
tm.assert_numpy_array_equal(result, expected)
result = idx2 > idx1
expected = np.array([True, False, False, False, True, False])
tm.assert_numpy_array_equal(result, expected)
result = idx1 <= idx2
expected = np.array([True, False, False, False, True, True])
tm.assert_numpy_array_equal(result, expected)
result = idx2 >= idx1
expected = np.array([True, False, False, False, True, True])
tm.assert_numpy_array_equal(result, expected)
result = idx1 == idx2
expected = np.array([False, False, False, False, False, True])
tm.assert_numpy_array_equal(result, expected)
result = idx1 != idx2
expected = np.array([True, True, True, True, True, False])
tm.assert_numpy_array_equal(result, expected)
with tm.assert_produces_warning(None):
for idx1, val in [(fidx1, np.nan), (didx1, pd.NaT)]:
result = idx1 < val
expected = np.array([False, False, False, False, False, False])
tm.assert_numpy_array_equal(result, expected)
result = idx1 > val
tm.assert_numpy_array_equal(result, expected)
result = idx1 <= val
tm.assert_numpy_array_equal(result, expected)
result = idx1 >= val
tm.assert_numpy_array_equal(result, expected)
result = idx1 == val
tm.assert_numpy_array_equal(result, expected)
result = idx1 != val
expected = np.array([True, True, True, True, True, True])
tm.assert_numpy_array_equal(result, expected)
# Check pd.NaT is handles as the same as np.nan
with tm.assert_produces_warning(None):
for idx1, val in [(fidx1, 3), (didx1, datetime(2014, 3, 1))]:
result = idx1 < val
expected = np.array([True, False, False, False, False, False])
tm.assert_numpy_array_equal(result, expected)
result = idx1 > val
expected = np.array([False, False, False, False, True, True])
tm.assert_numpy_array_equal(result, expected)
result = idx1 <= val
expected = np.array([True, False, True, False, False, False])
tm.assert_numpy_array_equal(result, expected)
result = idx1 >= val
expected = np.array([False, False, True, False, True, True])
tm.assert_numpy_array_equal(result, expected)
result = idx1 == val
expected = np.array([False, False, True, False, False, False])
tm.assert_numpy_array_equal(result, expected)
result = idx1 != val
expected = np.array([True, True, False, True, True, True])
tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize('op', [operator.eq, operator.ne,
operator.gt, operator.ge,
operator.lt, operator.le])
def test_comparison_tzawareness_compat(self, op):
# GH#18162
dr = pd.date_range('2016-01-01', periods=6)
dz = dr.tz_localize('US/Pacific')
with pytest.raises(TypeError):
op(dr, dz)
with pytest.raises(TypeError):
op(dr, list(dz))
with pytest.raises(TypeError):
op(dz, dr)
with pytest.raises(TypeError):
op(dz, list(dr))
# Check that there isn't a problem aware-aware and naive-naive do not
# raise
assert (dr == dr).all()
assert (dr == list(dr)).all()
assert (dz == dz).all()
assert (dz == list(dz)).all()
# Check comparisons against scalar Timestamps
ts = pd.Timestamp('2000-03-14 01:59')
ts_tz = pd.Timestamp('2000-03-14 01:59', tz='Europe/Amsterdam')
assert (dr > ts).all()
with pytest.raises(TypeError):
op(dr, ts_tz)
assert (dz > ts_tz).all()
with pytest.raises(TypeError):
op(dz, ts)
@pytest.mark.parametrize('op', [operator.eq, operator.ne,
operator.gt, operator.ge,
operator.lt, operator.le])
def test_nat_comparison_tzawareness(self, op):
# GH#19276
# tzaware DatetimeIndex should not raise when compared to NaT
dti = pd.DatetimeIndex(['2014-01-01', pd.NaT, '2014-03-01', pd.NaT,
'2014-05-01', '2014-07-01'])
expected = np.array([op == operator.ne] * len(dti))
result = op(dti, pd.NaT)
tm.assert_numpy_array_equal(result, expected)
result = op(dti.tz_localize('US/Pacific'), pd.NaT)
tm.assert_numpy_array_equal(result, expected)
def test_dti_cmp_int_raises(self):
rng = date_range('1/1/2000', periods=10)
# raise TypeError for now
with pytest.raises(TypeError):
rng < rng[3].value
def test_dti_cmp_list(self):
rng = date_range('1/1/2000', periods=10)
result = rng == list(rng)
expected = rng == rng
tm.assert_numpy_array_equal(result, expected)
class TestDatetimeIndexArithmetic(object):
def test_dti_add_timestamp_raises(self):
idx = DatetimeIndex(['2011-01-01', '2011-01-02'])
msg = "cannot add DatetimeIndex and Timestamp"
with tm.assert_raises_regex(TypeError, msg):
idx + Timestamp('2011-01-01')
def test_dti_radd_timestamp_raises(self):
idx = DatetimeIndex(['2011-01-01', '2011-01-02'])
msg = "cannot add DatetimeIndex and Timestamp"
with tm.assert_raises_regex(TypeError, msg):
Timestamp('2011-01-01') + idx
# -------------------------------------------------------------
# Binary operations DatetimeIndex and int
def test_dti_add_int(self, tz, one):
# Variants of `one` for #19012
rng = pd.date_range('2000-01-01 09:00', freq='H',
periods=10, tz=tz)
result = rng + one
expected = pd.date_range('2000-01-01 10:00', freq='H',
periods=10, tz=tz)
tm.assert_index_equal(result, expected)
def test_dti_iadd_int(self, tz, one):
rng = pd.date_range('2000-01-01 09:00', freq='H',
periods=10, tz=tz)
expected = pd.date_range('2000-01-01 10:00', freq='H',
periods=10, tz=tz)
rng += one
tm.assert_index_equal(rng, expected)
def test_dti_sub_int(self, tz, one):
rng = pd.date_range('2000-01-01 09:00', freq='H',
periods=10, tz=tz)
result = rng - one
expected = pd.date_range('2000-01-01 08:00', freq='H',
periods=10, tz=tz)
tm.assert_index_equal(result, expected)
def test_dti_isub_int(self, tz, one):
rng = pd.date_range('2000-01-01 09:00', freq='H',
periods=10, tz=tz)
expected = pd.date_range('2000-01-01 08:00', freq='H',
periods=10, tz=tz)
rng -= one
tm.assert_index_equal(rng, expected)
# -------------------------------------------------------------
# DatetimeIndex.shift is used in integer addition
def test_dti_shift_tzaware(self, tz):
# GH#9903
idx = pd.DatetimeIndex([], name='xxx', tz=tz)
tm.assert_index_equal(idx.shift(0, freq='H'), idx)
tm.assert_index_equal(idx.shift(3, freq='H'), idx)
idx = pd.DatetimeIndex(['2011-01-01 10:00', '2011-01-01 11:00'
'2011-01-01 12:00'], name='xxx', tz=tz)
tm.assert_index_equal(idx.shift(0, freq='H'), idx)
exp = pd.DatetimeIndex(['2011-01-01 13:00', '2011-01-01 14:00'
'2011-01-01 15:00'], name='xxx', tz=tz)
tm.assert_index_equal(idx.shift(3, freq='H'), exp)
exp = pd.DatetimeIndex(['2011-01-01 07:00', '2011-01-01 08:00'
'2011-01-01 09:00'], name='xxx', tz=tz)
tm.assert_index_equal(idx.shift(-3, freq='H'), exp)
def test_dti_shift_freqs(self):
# test shift for DatetimeIndex and non DatetimeIndex
# GH#8083
drange = pd.date_range('20130101', periods=5)
result = drange.shift(1)
expected = pd.DatetimeIndex(['2013-01-02', '2013-01-03', '2013-01-04',
'2013-01-05',
'2013-01-06'], freq='D')
tm.assert_index_equal(result, expected)
result = drange.shift(-1)
expected = pd.DatetimeIndex(['2012-12-31', '2013-01-01', '2013-01-02',
'2013-01-03', '2013-01-04'],
freq='D')
tm.assert_index_equal(result, expected)
result = drange.shift(3, freq='2D')
expected = pd.DatetimeIndex(['2013-01-07', '2013-01-08', '2013-01-09',
'2013-01-10',
'2013-01-11'], freq='D')
tm.assert_index_equal(result, expected)
def test_dti_shift_int(self):
rng = date_range('1/1/2000', periods=20)
result = rng + 5
expected = rng.shift(5)
tm.assert_index_equal(result, expected)
result = rng - 5
expected = rng.shift(-5)
tm.assert_index_equal(result, expected)
def test_dti_shift_no_freq(self):
# GH#19147
dti = pd.DatetimeIndex(['2011-01-01 10:00', '2011-01-01'], freq=None)
with pytest.raises(NullFrequencyError):
dti.shift(2)
@pytest.mark.parametrize('tzstr', ['US/Eastern', 'dateutil/US/Eastern'])
def test_dti_shift_localized(self, tzstr):
dr = date_range('2011/1/1', '2012/1/1', freq='W-FRI')
dr_tz = dr.tz_localize(tzstr)
result = dr_tz.shift(1, '10T')
assert result.tz == dr_tz.tz
# -------------------------------------------------------------
# Binary operations DatetimeIndex and timedelta-like
def test_dti_add_timedeltalike(self, tz, delta):
rng = pd.date_range('2000-01-01', '2000-02-01', tz=tz)
result = rng + delta
expected = pd.date_range('2000-01-01 02:00',
'2000-02-01 02:00', tz=tz)
tm.assert_index_equal(result, expected)
def test_dti_iadd_timedeltalike(self, tz, delta):
rng = pd.date_range('2000-01-01', '2000-02-01', tz=tz)
expected = pd.date_range('2000-01-01 02:00',
'2000-02-01 02:00', tz=tz)
rng += delta
tm.assert_index_equal(rng, expected)
def test_dti_sub_timedeltalike(self, tz, delta):
rng = pd.date_range('2000-01-01', '2000-02-01', tz=tz)
expected = pd.date_range('1999-12-31 22:00',
'2000-01-31 22:00', tz=tz)
result = rng - delta
tm.assert_index_equal(result, expected)
def test_dti_isub_timedeltalike(self, tz, delta):
rng = pd.date_range('2000-01-01', '2000-02-01', tz=tz)
expected = pd.date_range('1999-12-31 22:00',
'2000-01-31 22:00', tz=tz)
rng -= delta
tm.assert_index_equal(rng, expected)
# -------------------------------------------------------------
# Binary operations DatetimeIndex and TimedeltaIndex/array
def test_dti_add_tdi(self, tz):
# GH 17558
dti = DatetimeIndex([Timestamp('2017-01-01', tz=tz)] * 10)
tdi = pd.timedelta_range('0 days', periods=10)
expected = pd.date_range('2017-01-01', periods=10, tz=tz)
# add with TimdeltaIndex
result = dti + tdi
tm.assert_index_equal(result, expected)
result = tdi + dti
tm.assert_index_equal(result, expected)
# add with timedelta64 array
result = dti + tdi.values
tm.assert_index_equal(result, expected)
result = tdi.values + dti
tm.assert_index_equal(result, expected)
def test_dti_iadd_tdi(self, tz):
# GH 17558
dti = DatetimeIndex([Timestamp('2017-01-01', tz=tz)] * 10)
tdi = pd.timedelta_range('0 days', periods=10)
expected = pd.date_range('2017-01-01', periods=10, tz=tz)
# iadd with TimdeltaIndex
result = DatetimeIndex([Timestamp('2017-01-01', tz=tz)] * 10)
result += tdi
tm.assert_index_equal(result, expected)
result = pd.timedelta_range('0 days', periods=10)
result += dti
tm.assert_index_equal(result, expected)
# iadd with timedelta64 array
result = DatetimeIndex([Timestamp('2017-01-01', tz=tz)] * 10)
result += tdi.values
tm.assert_index_equal(result, expected)
result = pd.timedelta_range('0 days', periods=10)
result += dti
tm.assert_index_equal(result, expected)
def test_dti_sub_tdi(self, tz):
# GH 17558
dti = DatetimeIndex([Timestamp('2017-01-01', tz=tz)] * 10)
tdi = pd.timedelta_range('0 days', periods=10)
expected = pd.date_range('2017-01-01', periods=10, tz=tz, freq='-1D')
# sub with TimedeltaIndex
result = dti - tdi
tm.assert_index_equal(result, expected)
msg = 'cannot subtract TimedeltaIndex and DatetimeIndex'
with tm.assert_raises_regex(TypeError, msg):
tdi - dti
# sub with timedelta64 array
result = dti - tdi.values
tm.assert_index_equal(result, expected)
msg = 'cannot perform __neg__ with this index type:'
with tm.assert_raises_regex(TypeError, msg):
tdi.values - dti
def test_dti_isub_tdi(self, tz):
# GH 17558
dti = DatetimeIndex([Timestamp('2017-01-01', tz=tz)] * 10)
tdi = pd.timedelta_range('0 days', periods=10)
expected = pd.date_range('2017-01-01', periods=10, tz=tz, freq='-1D')
# isub with TimedeltaIndex
result = DatetimeIndex([Timestamp('2017-01-01', tz=tz)] * 10)
result -= tdi
tm.assert_index_equal(result, expected)
msg = 'cannot subtract TimedeltaIndex and DatetimeIndex'
with tm.assert_raises_regex(TypeError, msg):
tdi -= dti
# isub with timedelta64 array
result = DatetimeIndex([Timestamp('2017-01-01', tz=tz)] * 10)
result -= tdi.values
tm.assert_index_equal(result, expected)
msg = '|'.join(['cannot perform __neg__ with this index type:',
'ufunc subtract cannot use operands with types'])
with tm.assert_raises_regex(TypeError, msg):
tdi.values -= dti
# -------------------------------------------------------------
# Binary Operations DatetimeIndex and datetime-like
# TODO: A couple other tests belong in this section. Move them in
# A PR where there isn't already a giant diff.
def test_add_datetimelike_and_dti(self, addend):
# GH#9631
dti = DatetimeIndex(['2011-01-01', '2011-01-02'])
msg = 'cannot add DatetimeIndex and {0}'.format(
type(addend).__name__)
with tm.assert_raises_regex(TypeError, msg):
dti + addend
with tm.assert_raises_regex(TypeError, msg):
addend + dti
def test_add_datetimelike_and_dti_tz(self, addend):
# GH#9631
dti_tz = DatetimeIndex(['2011-01-01',
'2011-01-02']).tz_localize('US/Eastern')
msg = 'cannot add DatetimeIndex and {0}'.format(
type(addend).__name__)
with tm.assert_raises_regex(TypeError, msg):
dti_tz + addend
with tm.assert_raises_regex(TypeError, msg):
addend + dti_tz
# -------------------------------------------------------------
def test_sub_dti_dti(self):
# previously performed setop (deprecated in 0.16.0), now changed to
# return subtraction -> TimeDeltaIndex (GH ...)
dti = date_range('20130101', periods=3)
dti_tz = date_range('20130101', periods=3).tz_localize('US/Eastern')
dti_tz2 = date_range('20130101', periods=3).tz_localize('UTC')
expected = TimedeltaIndex([0, 0, 0])
result = dti - dti
tm.assert_index_equal(result, expected)
result = dti_tz - dti_tz
tm.assert_index_equal(result, expected)
with pytest.raises(TypeError):
dti_tz - dti
with pytest.raises(TypeError):
dti - dti_tz
with pytest.raises(TypeError):
dti_tz - dti_tz2
# isub
dti -= dti
tm.assert_index_equal(dti, expected)
# different length raises ValueError
dti1 = date_range('20130101', periods=3)
dti2 = date_range('20130101', periods=4)
with pytest.raises(ValueError):
dti1 - dti2
# NaN propagation
dti1 = DatetimeIndex(['2012-01-01', np.nan, '2012-01-03'])
dti2 = DatetimeIndex(['2012-01-02', '2012-01-03', np.nan])
expected = TimedeltaIndex(['1 days', np.nan, np.nan])
result = dti2 - dti1
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize('freq', [None, 'D'])
def test_sub_period(self, freq):
# GH#13078
# not supported, check TypeError
p = pd.Period('2011-01-01', freq='D')
idx = pd.DatetimeIndex(['2011-01-01', '2011-01-02'], freq=freq)
with pytest.raises(TypeError):
idx - p
with pytest.raises(TypeError):
p - idx
def test_ufunc_coercions(self):
idx = date_range('2011-01-01', periods=3, freq='2D', name='x')
delta = np.timedelta64(1, 'D')
for result in [idx + delta, np.add(idx, delta)]:
assert isinstance(result, DatetimeIndex)
exp = date_range('2011-01-02', periods=3, freq='2D', name='x')
tm.assert_index_equal(result, exp)
assert result.freq == '2D'
for result in [idx - delta, np.subtract(idx, delta)]:
assert isinstance(result, DatetimeIndex)
exp = date_range('2010-12-31', periods=3, freq='2D', name='x')
tm.assert_index_equal(result, exp)
assert result.freq == '2D'
delta = np.array([np.timedelta64(1, 'D'), np.timedelta64(2, 'D'),
np.timedelta64(3, 'D')])
for result in [idx + delta, np.add(idx, delta)]:
assert isinstance(result, DatetimeIndex)
exp = DatetimeIndex(['2011-01-02', '2011-01-05', '2011-01-08'],
freq='3D', name='x')
tm.assert_index_equal(result, exp)
assert result.freq == '3D'
for result in [idx - delta, np.subtract(idx, delta)]:
assert isinstance(result, DatetimeIndex)
exp = DatetimeIndex(['2010-12-31', '2011-01-01', '2011-01-02'],
freq='D', name='x')
tm.assert_index_equal(result, exp)
assert result.freq == 'D'
def test_datetimeindex_sub_timestamp_overflow(self):
dtimax = pd.to_datetime(['now', pd.Timestamp.max])
dtimin = pd.to_datetime(['now', pd.Timestamp.min])
tsneg = Timestamp('1950-01-01')
ts_neg_variants = [tsneg,
tsneg.to_pydatetime(),
tsneg.to_datetime64().astype('datetime64[ns]'),
tsneg.to_datetime64().astype('datetime64[D]')]
tspos = Timestamp('1980-01-01')
ts_pos_variants = [tspos,
tspos.to_pydatetime(),
tspos.to_datetime64().astype('datetime64[ns]'),
tspos.to_datetime64().astype('datetime64[D]')]
for variant in ts_neg_variants:
with pytest.raises(OverflowError):
dtimax - variant
expected = pd.Timestamp.max.value - tspos.value
for variant in ts_pos_variants:
res = dtimax - variant
assert res[1].value == expected
expected = pd.Timestamp.min.value - tsneg.value
for variant in ts_neg_variants:
res = dtimin - variant
assert res[1].value == expected
for variant in ts_pos_variants:
with pytest.raises(OverflowError):
dtimin - variant
@pytest.mark.parametrize('names', [('foo', None, None),
('baz', 'bar', None),
('bar', 'bar', 'bar')])
@pytest.mark.parametrize('tz', [None, 'America/Chicago'])
def test_dti_add_series(self, tz, names):
# GH#13905
index = DatetimeIndex(['2016-06-28 05:30', '2016-06-28 05:31'],
tz=tz, name=names[0])
ser = Series([Timedelta(seconds=5)] * 2,
index=index, name=names[1])
expected = Series(index + Timedelta(seconds=5),
index=index, name=names[2])
# passing name arg isn't enough when names[2] is None
expected.name = names[2]
assert expected.dtype == index.dtype
result = ser + index
tm.assert_series_equal(result, expected)
result2 = index + ser
tm.assert_series_equal(result2, expected)
expected = index + Timedelta(seconds=5)
result3 = ser.values + index
tm.assert_index_equal(result3, expected)
result4 = index + ser.values
tm.assert_index_equal(result4, expected)
def test_dti_add_offset_array(self, tz):
# GH#18849
dti = pd.date_range('2017-01-01', periods=2, tz=tz)
other = np.array([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)])
with tm.assert_produces_warning(PerformanceWarning):
res = dti + other
expected = DatetimeIndex([dti[n] + other[n] for n in range(len(dti))],
name=dti.name, freq='infer')
tm.assert_index_equal(res, expected)
with tm.assert_produces_warning(PerformanceWarning):
res2 = other + dti
tm.assert_index_equal(res2, expected)
@pytest.mark.parametrize('names', [(None, None, None),
('foo', 'bar', None),
('foo', 'foo', 'foo')])
def test_dti_add_offset_index(self, tz, names):
# GH#18849, GH#19744
dti = pd.date_range('2017-01-01', periods=2, tz=tz, name=names[0])
other = pd.Index([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)],
name=names[1])
with tm.assert_produces_warning(PerformanceWarning):
res = dti + other
expected = DatetimeIndex([dti[n] + other[n] for n in range(len(dti))],
name=names[2], freq='infer')
tm.assert_index_equal(res, expected)
with tm.assert_produces_warning(PerformanceWarning):
res2 = other + dti
tm.assert_index_equal(res2, expected)
def test_dti_sub_offset_array(self, tz):
# GH#18824
dti = pd.date_range('2017-01-01', periods=2, tz=tz)
other = np.array([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)])
with tm.assert_produces_warning(PerformanceWarning):
res = dti - other
expected = DatetimeIndex([dti[n] - other[n] for n in range(len(dti))],
name=dti.name, freq='infer')
tm.assert_index_equal(res, expected)
@pytest.mark.parametrize('names', [(None, None, None),
('foo', 'bar', None),
('foo', 'foo', 'foo')])
def test_dti_sub_offset_index(self, tz, names):
# GH#18824, GH#19744
dti = pd.date_range('2017-01-01', periods=2, tz=tz, name=names[0])
other = pd.Index([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)],
name=names[1])
with tm.assert_produces_warning(PerformanceWarning):
res = dti - other
expected = DatetimeIndex([dti[n] - other[n] for n in range(len(dti))],
name=names[2], freq='infer')
tm.assert_index_equal(res, expected)
@pytest.mark.parametrize('names', [(None, None, None),
('foo', 'bar', None),
('foo', 'foo', 'foo')])
def test_dti_with_offset_series(self, tz, names):
# GH#18849
dti = pd.date_range('2017-01-01', periods=2, tz=tz, name=names[0])
other = Series([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)],
name=names[1])
expected_add = Series([dti[n] + other[n] for n in range(len(dti))],
name=names[2])
with tm.assert_produces_warning(PerformanceWarning):
res = dti + other
tm.assert_series_equal(res, expected_add)
with tm.assert_produces_warning(PerformanceWarning):
res2 = other + dti
tm.assert_series_equal(res2, expected_add)
expected_sub = Series([dti[n] - other[n] for n in range(len(dti))],
name=names[2])
with tm.assert_produces_warning(PerformanceWarning):
res3 = dti - other
tm.assert_series_equal(res3, expected_sub)
def test_dti_add_offset_tzaware(self):
dates = date_range('2012-11-01', periods=3, tz='US/Pacific')
offset = dates + pd.offsets.Hour(5)
assert dates[0] + pd.offsets.Hour(5) == offset[0]
# GH#6818
for tz in ['UTC', 'US/Pacific', 'Asia/Tokyo']:
dates = date_range('2010-11-01 00:00', periods=3, tz=tz, freq='H')
expected = DatetimeIndex(['2010-11-01 05:00', '2010-11-01 06:00',
'2010-11-01 07:00'], freq='H', tz=tz)
offset = dates + pd.offsets.Hour(5)
tm.assert_index_equal(offset, expected)
offset = dates + np.timedelta64(5, 'h')
tm.assert_index_equal(offset, expected)
offset = dates + timedelta(hours=5)
tm.assert_index_equal(offset, expected)
@pytest.mark.parametrize('klass,assert_func', [
(Series, tm.assert_series_equal),
(DatetimeIndex, tm.assert_index_equal)])
def test_dt64_with_offset_array(klass, assert_func):
# GH#10699
# array of offsets
box = Series if klass is Series else pd.Index
with tm.assert_produces_warning(PerformanceWarning):
s = klass([Timestamp('2000-1-1'), Timestamp('2000-2-1')])
result = s + box([pd.offsets.DateOffset(years=1),
pd.offsets.MonthEnd()])
exp = klass([Timestamp('2001-1-1'), Timestamp('2000-2-29')])
assert_func(result, exp)
# same offset
result = s + box([pd.offsets.DateOffset(years=1),
pd.offsets.DateOffset(years=1)])
exp = klass([Timestamp('2001-1-1'), Timestamp('2001-2-1')])
assert_func(result, exp)
@pytest.mark.parametrize('klass,assert_func', [
(Series, tm.assert_series_equal),
(DatetimeIndex, tm.assert_index_equal)])
def test_dt64_with_DateOffsets_relativedelta(klass, assert_func):
# GH#10699
vec = klass([Timestamp('2000-01-05 00:15:00'),
Timestamp('2000-01-31 00:23:00'),
Timestamp('2000-01-01'),
Timestamp('2000-03-31'),
Timestamp('2000-02-29'),
Timestamp('2000-12-31'),
Timestamp('2000-05-15'),
Timestamp('2001-06-15')])
# DateOffset relativedelta fastpath
relative_kwargs = [('years', 2), ('months', 5), ('days', 3),
('hours', 5), ('minutes', 10), ('seconds', 2),
('microseconds', 5)]
for i, kwd in enumerate(relative_kwargs):
op = pd.DateOffset(**dict([kwd]))
assert_func(klass([x + op for x in vec]), vec + op)
assert_func(klass([x - op for x in vec]), vec - op)
op = pd.DateOffset(**dict(relative_kwargs[:i + 1]))
assert_func(klass([x + op for x in vec]), vec + op)
assert_func(klass([x - op for x in vec]), vec - op)
@pytest.mark.parametrize('cls_and_kwargs', [
'YearBegin', ('YearBegin', {'month': 5}),
'YearEnd', ('YearEnd', {'month': 5}),
'MonthBegin', 'MonthEnd',
'SemiMonthEnd', 'SemiMonthBegin',
'Week', ('Week', {'weekday': 3}),
'BusinessDay', 'BDay', 'QuarterEnd', 'QuarterBegin',
'CustomBusinessDay', 'CDay', 'CBMonthEnd',
'CBMonthBegin', 'BMonthBegin', 'BMonthEnd',
'BusinessHour', 'BYearBegin', 'BYearEnd',
'BQuarterBegin', ('LastWeekOfMonth', {'weekday': 2}),
('FY5253Quarter', {'qtr_with_extra_week': 1,
'startingMonth': 1,
'weekday': 2,
'variation': 'nearest'}),
('FY5253', {'weekday': 0, 'startingMonth': 2, 'variation': 'nearest'}),
('WeekOfMonth', {'weekday': 2, 'week': 2}),
'Easter', ('DateOffset', {'day': 4}),
('DateOffset', {'month': 5})])
@pytest.mark.parametrize('normalize', [True, False])
@pytest.mark.parametrize('klass,assert_func', [
(Series, tm.assert_series_equal),
(DatetimeIndex, tm.assert_index_equal)])
def test_dt64_with_DateOffsets(klass, assert_func, normalize, cls_and_kwargs):
# GH#10699
# assert these are equal on a piecewise basis
vec = klass([Timestamp('2000-01-05 00:15:00'),
Timestamp('2000-01-31 00:23:00'),
Timestamp('2000-01-01'),
Timestamp('2000-03-31'),
Timestamp('2000-02-29'),
Timestamp('2000-12-31'),
Timestamp('2000-05-15'),
Timestamp('2001-06-15')])
if isinstance(cls_and_kwargs, tuple):
# If cls_name param is a tuple, then 2nd entry is kwargs for
# the offset constructor
cls_name, kwargs = cls_and_kwargs
else:
cls_name = cls_and_kwargs
kwargs = {}
offset_cls = getattr(pd.offsets, cls_name)
with warnings.catch_warnings(record=True):
for n in [0, 5]:
if (cls_name in ['WeekOfMonth', 'LastWeekOfMonth',
'FY5253Quarter', 'FY5253'] and n == 0):
# passing n = 0 is invalid for these offset classes
continue
offset = offset_cls(n, normalize=normalize, **kwargs)
assert_func(klass([x + offset for x in vec]), vec + offset)
assert_func(klass([x - offset for x in vec]), vec - offset)
assert_func(klass([offset + x for x in vec]), offset + vec)
# GH 10699
@pytest.mark.parametrize('klass,assert_func', zip([Series, DatetimeIndex],
[tm.assert_series_equal,
tm.assert_index_equal]))
def test_datetime64_with_DateOffset(klass, assert_func):
s = klass(date_range('2000-01-01', '2000-01-31'), name='a')
result = s + pd.DateOffset(years=1)
result2 = pd.DateOffset(years=1) + s
exp = klass(date_range('2001-01-01', '2001-01-31'), name='a')
assert_func(result, exp)
assert_func(result2, exp)
result = s - pd.DateOffset(years=1)
exp = klass(date_range('1999-01-01', '1999-01-31'), name='a')
assert_func(result, exp)
s = klass([Timestamp('2000-01-15 00:15:00', tz='US/Central'),
pd.Timestamp('2000-02-15', tz='US/Central')], name='a')
result = s + pd.offsets.Day()
result2 = pd.offsets.Day() + s
exp = klass([Timestamp('2000-01-16 00:15:00', tz='US/Central'),
Timestamp('2000-02-16', tz='US/Central')], name='a')
assert_func(result, exp)
assert_func(result2, exp)
s = klass([Timestamp('2000-01-15 00:15:00', tz='US/Central'),
pd.Timestamp('2000-02-15', tz='US/Central')], name='a')
result = s + pd.offsets.MonthEnd()
result2 = pd.offsets.MonthEnd() + s
exp = klass([Timestamp('2000-01-31 00:15:00', tz='US/Central'),
Timestamp('2000-02-29', tz='US/Central')], name='a')
assert_func(result, exp)
assert_func(result2, exp)
@pytest.mark.parametrize('years', [-1, 0, 1])
@pytest.mark.parametrize('months', [-2, 0, 2])
def test_shift_months(years, months):
s = DatetimeIndex([Timestamp('2000-01-05 00:15:00'),
Timestamp('2000-01-31 00:23:00'),
Timestamp('2000-01-01'),
Timestamp('2000-02-29'),
Timestamp('2000-12-31')])
actual = DatetimeIndex(shift_months(s.asi8, years * 12 + months))
raw = [x + pd.offsets.DateOffset(years=years, months=months)
for x in s]
expected = DatetimeIndex(raw)
tm.assert_index_equal(actual, expected)
| pandas/tests/indexes/datetimes/test_arithmetic.py | 39,525 | -*- coding: utf-8 -*- Several ways of representing two hours no tzaware version available GH19301 by convention datetime.date is not considered comparable to Timestamp or DatetimeIndex. This may change in the future. GH19301 GH19301 GH19301 Check pd.NaT is handles as the same as np.nan Check pd.NaT is handles as the same as np.nan GH18162 Check that there isn't a problem aware-aware and naive-naive do not raise Check comparisons against scalar Timestamps GH19276 tzaware DatetimeIndex should not raise when compared to NaT raise TypeError for now ------------------------------------------------------------- Binary operations DatetimeIndex and int Variants of `one` for 19012 ------------------------------------------------------------- DatetimeIndex.shift is used in integer addition GH9903 test shift for DatetimeIndex and non DatetimeIndex GH8083 GH19147 ------------------------------------------------------------- Binary operations DatetimeIndex and timedelta-like ------------------------------------------------------------- Binary operations DatetimeIndex and TimedeltaIndex/array GH 17558 add with TimdeltaIndex add with timedelta64 array GH 17558 iadd with TimdeltaIndex iadd with timedelta64 array GH 17558 sub with TimedeltaIndex sub with timedelta64 array GH 17558 isub with TimedeltaIndex isub with timedelta64 array ------------------------------------------------------------- Binary Operations DatetimeIndex and datetime-like TODO: A couple other tests belong in this section. Move them in A PR where there isn't already a giant diff. GH9631 GH9631 ------------------------------------------------------------- previously performed setop (deprecated in 0.16.0), now changed to return subtraction -> TimeDeltaIndex (GH ...) isub different length raises ValueError NaN propagation GH13078 not supported, check TypeError GH13905 passing name arg isn't enough when names[2] is None GH18849 GH18849, GH19744 GH18824 GH18824, GH19744 GH18849 GH6818 GH10699 array of offsets same offset GH10699 DateOffset relativedelta fastpath GH10699 assert these are equal on a piecewise basis If cls_name param is a tuple, then 2nd entry is kwargs for the offset constructor passing n = 0 is invalid for these offset classes GH 10699 | 2,240 | en | 0.676531 |
def user_display_name(user):
"""
Returns the preferred display name for the given user object: the result of
user.get_full_name() if implemented and non-empty, or user.get_username() otherwise.
"""
try:
full_name = user.get_full_name().strip()
if full_name:
return full_name
except AttributeError:
pass
try:
return user.get_username()
except AttributeError:
# we were passed None or something else that isn't a valid user object; return
# empty string to replicate the behaviour of {{ user.get_full_name|default:user.get_username }}
return ''
| wagtail_review/text.py | 644 | Returns the preferred display name for the given user object: the result of
user.get_full_name() if implemented and non-empty, or user.get_username() otherwise.
we were passed None or something else that isn't a valid user object; return empty string to replicate the behaviour of {{ user.get_full_name|default:user.get_username }} | 333 | en | 0.621357 |
#
# Tencent is pleased to support the open source community by making Angel available.
#
# Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# 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
#
from enum import Enum, unique
@unique
class RunningMode(Enum):
"""
Enum for running mode
"""
# Run ParameterServer & ParameterServerAgent
ANGEL_PS_PSAGENT = 0
# Only Run ParameterServer
ANGEL_PS = 1
# Run ParameterServer & Worker(embedded ParameterServerAgent)
ANGEL_PS_WORKER = 2
| angel-ps/python/build/lib/pyangel/running_mode.py | 991 | Enum for running mode
Tencent is pleased to support the open source community by making Angel available. Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://opensource.org/licenses/BSD-3-Clause 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 Run ParameterServer & ParameterServerAgent Only Run ParameterServer Run ParameterServer & Worker(embedded ParameterServerAgent) | 793 | en | 0.857331 |
#!/usr/bin/env python2
# OpenPOWER Automated Test Project
#
# Contributors Listed Below - COPYRIGHT 2015,2017
# [+] International Business Machines Corp.
#
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
# This test runs FWTS and munges the JSON report output into
# python unittest.TestCase objects, so we get the individual
# failure/successes into the TestResult output (e.g. junit XML)
import time
import subprocess
import re
import sys
import os
import OpTestConfiguration
import unittest
from common.OpTestSystem import OpSystemState
from common.Exceptions import CommandFailed
import json
class FWTSCommandFailed(unittest.TestCase):
FAIL = None
def runTest(self):
self.assertEqual(self.FAIL, None, str(self.FAIL))
class FWTSVersion(unittest.TestCase):
MAJOR = None
MINOR = None
def version_check(self):
if self.MAJOR is None and self.MINOR is None:
self.skipTest("Test not meant to be run this way.")
return (self.MAJOR == 17 and self.MINOR >=1) or self.MAJOR > 17
def runTest(self):
self.assertTrue(self.version_check(),
'FWTS must be at least Version 17.01'
)
class FWTSTest(unittest.TestCase):
SUBTEST_RESULT = None
CENTAURS_PRESENT = True
IS_FSP_SYSTEM = False
FWTS_MAJOR_VERSION = None
FWTS_MINOR_VERSION = None
def runTest(self):
if self.SUBTEST_RESULT is None:
self.skipTest("Test not meant to be run this way.")
if self.SUBTEST_RESULT.get('log_text') == 'dtc reports warnings from device tree:Warning (reg_format): "reg" property in /ibm,opal/flash@0 has invalid length (8 bytes) (#address-cells == 0, #size-cells == 0)\n':
self.skipTest('/ibm,opal/flash@0 known warning')
# Some FWTS verions barfed (incorrectly) on missing nodes
# in the device tree. If we spot this, skip the test
# this work-around should be removed when the FWTS version readily
# available from the archives no longer has this problem
if not (self.SUBTEST_RESULT.get('failure_label') == 'None'):
log_text = self.SUBTEST_RESULT.get('log_text')
if re.match('Property of "(status|manufacturer-id|part-number|serial-number)" for "/sys/firmware/devicetree/base/memory-buffer' , log_text):
self.skipTest("FWTS bug: Incorrect Missing '(status|manufacturer-id|part-number|serial-number)' property in memory-buffer/dimm");
if re.match('property "serial-number" contains unprintable characters', log_text):
self.skipTest("FWTS bug: DIMM VPD has binary serial number")
if self.FWTS_MAJOR_VERSION <= 18:
# This is a guess based on when
# https://lists.ubuntu.com/archives/fwts-devel/2018-April/010318.html
# will be merged
if self.FWTS_MAJOR_VERSION < 18 or self.FWTS_MINOR_VERSION < 5:
if re.match('CPUFreqClaimedMax', self.SUBTEST_RESULT.get('failure_label')):
self.skipTest("Bug in FWTS r.e. boost frequencies, fixed sometime after April 2018")
# On FSP machines, memory-buffers (centaurs) aren't present in DT
# and FWTS 17.03 (at least) expects them to be, so skip those failures
if not self.CENTAURS_PRESENT and re.match('No MEM devices \(memory-buffer', log_text):
self.skipTest("FWTS assumes Centaurs present on FSP systems")
if self.IS_FSP_SYSTEM and re.match('Property of "(board-info|part-number|serial-number|vendor|ibm,slot-location-code)" for "/sys/firmware/devicetree/base/xscom@.*" was not able to be retrieved. Check the installation for the CPU device config for missing nodes in the device tree if you expect CPU devices', log_text):
self.skipTest("FWTS assumes some nodes present on FSP systems which aren't")
if re.match('Attempt was made to stop the opal-prd.service but was not successful', log_text):
self.skipTest("FWTS bug: prd did actually stop, and there's something strange with FWTS")
if re.match('OPAL "/ibm,firmware-versions" firmware version from device tree node "open-power" was not found', log_text):
self.skipTest("FWTS known issue: 'open-power' version no longer required")
# We currently guess that all these are going to be merged for FWTS 18.05 :)
# To be extra cautious, allowing them to fail for all of 18.XX though
if self.FWTS_MAJOR_VERSION <= 18:
if re.match('CPUPstateLimitsTestFail', self.SUBTEST_RESULT.get('failure_label')):
self.skipTest("FWTS known issue: https://lists.ubuntu.com/archives/fwts-devel/2018-April/010315.html")
if re.match('DeviceTreeBaseDTCWarnings', self.SUBTEST_RESULT.get('failure_label')):
self.skipTest("FWTS known issue: https://lists.ubuntu.com/archives/fwts-devel/2018-April/010326.html")
if re.match('Property of "(board-info|vendor|ibm,slot-location-code)" for "/sys/firmware/devicetree/base/xscom.*" was not able to be retrieved. Check the installation for the CPU device config for missing nodes in the device tree if you expect CPU devices.', log_text):
self.skipTest("FWTS/firmware known issue: https://lists.ubuntu.com/archives/fwts-devel/2018-April/010329.html")
if re.match('No MEM DIMM devices \(memory-buffer\) were found in "/sys/firmware/devicetree/base" with a status of "okay" or "ok". This is unexpected so please check your system setup for issues.', log_text):
self.skipTest("FWTS/firmware known issue: https://lists.ubuntu.com/archives/fwts-devel/2018-April/010330.html")
self.assertEqual(self.SUBTEST_RESULT.get('failure_label'), 'None', self.SUBTEST_RESULT)
class FWTS(unittest.TestSuite):
def add_fwts_results(self, major_version, minor_version):
host = self.cv_HOST
try:
fwtsjson = host.host_run_command('fwts -q -r stdout --log-type=json')
except CommandFailed as cf:
# FWTS will have exit code of 1 if any test fails,
# we want to ignore that and parse the output.
fwtsjson = cf.output
if cf.exitcode not in [0, 1]:
command_failed = FWTSCommandFailed()
command_failed.FAIL = cf
self.real_fwts_suite.addTest(command_failed)
r = json.loads('\n'.join(fwtsjson), encoding='latin-1')
tests = []
for fwts in r['fwts']:
for k in fwts:
if k == "tests":
tests = fwts[k]
for test_container in tests:
for tr in test_container:
js_suite = test_container[tr][0]
js_subtests = test_container[tr][1]
suite = unittest.TestSuite()
for sts in js_subtests:
if sts == "subtests":
for subtest in js_subtests[sts]:
for st_info in subtest['subtest']:
if not st_info.get('subtest_results'):
continue
for st_result in st_info.get('subtest_results'):
t = FWTSTest()
t.SUBTEST_RESULT = st_result
t.CENTAURS_PRESENT = self.centaurs_present
t.FWTS_MAJOR_VERSION = major_version
t.FWTS_MINOR_VERSION = minor_version
if self.bmc_type == 'FSP':
t.IS_FSP_SYSTEM = True
suite.addTest(t)
self.real_fwts_suite.addTest(suite)
def run(self, result):
conf = OpTestConfiguration.conf
self.cv_HOST = conf.host()
self.cv_SYSTEM = conf.system()
self.bmc_type = conf.args.bmc_type
self.real_fwts_suite = unittest.TestSuite()
try:
self.cv_SYSTEM.goto_state(OpSystemState.OS)
except Exception as e:
# In the event of something going wrong during IPL,
# We need to catch that here as we're abusing UnitTest
# TestSuite infra and we don't have the catch-all that
# a TestCase provides.
f = FWTSCommandFailed()
f.FAIL = e
self.real_fwts_suite.addTest(f)
self.real_fwts_suite.run(result)
return
self.centaurs_present = self.cv_SYSTEM.has_centaurs_in_dt()
host = self.cv_HOST
fwts_version = None
try:
fwts_version = host.host_run_command('fwts --version')
except CommandFailed as cf:
command_failed = FWTSCommandFailed()
command_failed.FAIL = cf
self.real_fwts_suite.addTest(command_failed)
if fwts_version:
# We want to ensure we're at least at version 17.01
# which means we need to parse this:
# fwts, Version V17.01.00, 2017-01-19 04:20:38
v = re.search("fwts, Version V(\d+)\.(\d+)", ''.join(fwts_version))
major , minor = v.group(1) , v.group(2)
checkver = FWTSVersion()
checkver.MAJOR = major
checkver.MINOR = minor
self.real_fwts_suite.addTest(checkver)
if checkver.version_check():
self.add_fwts_results(int(major),int(minor))
self.real_fwts_suite.run(result)
| testcases/FWTS.py | 10,122 | !/usr/bin/env python2 OpenPOWER Automated Test Project Contributors Listed Below - COPYRIGHT 2015,2017 [+] International Business Machines Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This test runs FWTS and munges the JSON report output into python unittest.TestCase objects, so we get the individual failure/successes into the TestResult output (e.g. junit XML) Some FWTS verions barfed (incorrectly) on missing nodes in the device tree. If we spot this, skip the test this work-around should be removed when the FWTS version readily available from the archives no longer has this problem This is a guess based on when https://lists.ubuntu.com/archives/fwts-devel/2018-April/010318.html will be merged On FSP machines, memory-buffers (centaurs) aren't present in DT and FWTS 17.03 (at least) expects them to be, so skip those failures We currently guess that all these are going to be merged for FWTS 18.05 :) To be extra cautious, allowing them to fail for all of 18.XX though FWTS will have exit code of 1 if any test fails, we want to ignore that and parse the output. In the event of something going wrong during IPL, We need to catch that here as we're abusing UnitTest TestSuite infra and we don't have the catch-all that a TestCase provides. We want to ensure we're at least at version 17.01 which means we need to parse this: fwts, Version V17.01.00, 2017-01-19 04:20:38 | 1,863 | en | 0.894286 |
"""
My Data My Consent - Developer API
Unleashing the power of data consent by establishing trust. The Platform Core Developer API defines a set of capabilities that can be used to request, issue, manage and update data, documents and credentials by organizations. The API can be used to request, manage and update Decentralised Identifiers, Financial Data, Health Data issue Documents, Credentials directly or using OpenID Connect flows, and verify Messages signed with DIDs and much more. # noqa: E501
The version of the OpenAPI document: v1
Contact: support@mydatamyconsent.com
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
import com.mydatamyconsent
from com.mydatamyconsent.model.data_protection_officer import DataProtectionOfficer
class TestDataProtectionOfficer(unittest.TestCase):
"""DataProtectionOfficer unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testDataProtectionOfficer(self):
"""Test DataProtectionOfficer"""
# FIXME: construct object with mandatory attributes with example values
# model = DataProtectionOfficer() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| test/test_data_protection_officer.py | 1,250 | DataProtectionOfficer unit test stubs
Test DataProtectionOfficer
My Data My Consent - Developer API
Unleashing the power of data consent by establishing trust. The Platform Core Developer API defines a set of capabilities that can be used to request, issue, manage and update data, documents and credentials by organizations. The API can be used to request, manage and update Decentralised Identifiers, Financial Data, Health Data issue Documents, Credentials directly or using OpenID Connect flows, and verify Messages signed with DIDs and much more. # noqa: E501
The version of the OpenAPI document: v1
Contact: support@mydatamyconsent.com
Generated by: https://openapi-generator.tech
FIXME: construct object with mandatory attributes with example values model = DataProtectionOfficer() noqa: E501 | 806 | en | 0.801492 |
from .encoder import CKKSEncoder # noqa: F401
from .encrypter import CKKSEncrypter # noqa: F401
from .plaintext import CKKSPlaintext # noqa: F401
| src/aijack/defense/ckks/__init__.py | 149 | noqa: F401 noqa: F401 noqa: F401 | 32 | uz | 0.36552 |
"""Base classes for an Ambianic Edge device abstraction"""
from pydantic import BaseModel, Field
class DeviceInfo(BaseModel):
version: str = Field(None, description="Ambianic Edge software version.")
display_name: str = Field(
None, description="User friendly display name for this device."
)
notifications_enabled: bool = Field(
False, description="Indicates whether device notifications are enabled."
)
| src/ambianic/device.py | 443 | Base classes for an Ambianic Edge device abstraction | 52 | en | 0.491518 |
#!/usr/bin/env python
##############################################################
# $Id$
# Project: MiSeq Metagenomic Assembly pipeline for Nephele project
# Language: Python 2.7
# Author: Alex Levitsky
# History: July 2015 Start of development
##############################################################
__author__ = "Alex Levitsky"
__copyright__ = ""
__credits__ = ["Alex Levitsky"]
__license__ = ""
__version__ = "1.0.1-dev"
__maintainer__ = "Alex Levitsky"
__email__ = "levitskyaa@niaid.nih.gov"
__status__ = "Development"
import sys, os, random, time, glob
syscall = lambda cmd: (os.popen(cmd).read()).rstrip("\n")
def read_config( file_name, config ): #########################
config_file=open( file_name, 'r')
l=[]
for line in config_file:
if("" == line): # check for end of file
break
s=line.rstrip("\n")
s.strip()
if("" == s): # ignore empty lines
continue
if("#"==s[:1]): # ignore comments
continue
del l[:] # clear list
l=s.split(',')
config[l[0]]=l[1]
config_file.close()
### read_config ###
def send2log( message, log_file ): #######################
date = syscall("TZ='America/New_York' date")
os.system( "echo >> "+log_file)
if 0!=os.system( "echo '"+date+' '+message+"' >>"+log_file):
sys.exit(777)
### send2log ###
def exec_sys(cmd): #######################
#print >> sys.stderr, "Executing:",cmd
if 0!=os.system(cmd):
print >> sys.stderr, "ERROR when executing:",cmd
sys.exit(777)
### exec_sys ###
########### main ##############################
def main():
if len( sys.argv ) < 2:
print >> sys.stderr, "\n\n\nUsage: " + sys.argv[0] + " <configuration file>\n\n\n"
sys.exit(551)
# Read config file
conf_file = sys.argv[1]
if not os.path.isfile( conf_file ):
print >> sys.stderr, "ERROR: no config file:" + conf_file
sys.exit(555)
config = {}
read_config( conf_file,config )
work_dir=os.getcwd()
config['LOG_FILE']='logfile.txt'
log_file=work_dir+'/'+config['LOG_FILE']
##### Define optional and default parameters
for key in ['INPUT_TYPE', 'R1', 'R2', 'ZIP_FILE', 'LIB_FILE', 'BLAST_STEP','PREFIX']:
if(key not in config.keys()):
config[key]=''
##### Predefined and calculated options
if(''==config['LIB_FILE']):
config['INPUT_TYPE']='FASTQ_FILES'
if(''==config['PREFIX']):
config['PREFIX']='MiSEQ_metagenomic'
if(''==config['BLAST_STEP']):
config['BLAST_STEP']='YES'
send2log( 'MiSeq Metagenomic Assembly pipeline started', log_file )
# get env.json if available
if os.path.isfile('./env.json'):
send2log( 'env.json=', log_file )
syscall( 'cat ./env.json >> '+log_file)
# get number of cores
config['NUM_OF_PROC']=syscall('cat /proc/cpuinfo | grep processor | wc -l')
num_proc=int(config['NUM_OF_PROC'])
if(num_proc > 1):
num_proc-=1
config['NUM_OF_PROC']=str(num_proc)
send2log( 'number of cores='+config['NUM_OF_PROC'], log_file )
# get machine's memory
config['MEMORY']=syscall("cat /proc/meminfo | grep MemTotal | awk '{ print $2 }'")
mem=int(config['MEMORY'])
send2log( 'Memory='+config['MEMORY']+'KB', log_file )
w="MiSeq Metagenomic Assembly pipeline configuration\n"
for k in sorted(config.keys()):
if 'UseCode'==k:
continue
config[k]=config[k].replace("\"", "_")
config[k]=config[k].replace("\'", "_")
w=w+k+','+config[k]+"\n"
# print configuration to log file
send2log( w, log_file )
####################################################
os.chdir(work_dir)
# unzip reads
if os.path.isfile(work_dir+'/'+config['ZIP_FILE']):
# check files extension
w=''
if config['ZIP_FILE'][-4:]=='.zip':
send2log( 'unzip -oqj '+config['ZIP_FILE'], log_file )
w=syscall('unzip -oqj '+config['ZIP_FILE'])
send2log( w, log_file )
if (config['ZIP_FILE'][-7:]=='.tar.gz') or (config['ZIP_FILE'][-4:]=='.tgz'):
send2log( 'tar -zxvf '+config['ZIP_FILE'], log_file )
w=syscall('tar -zxvf '+config['ZIP_FILE'])
send2log( w, log_file )
if config['ZIP_FILE'][-8:]=='.tar.bz2':
send2log( 'tar -jxvf '+config['ZIP_FILE'], log_file )
w=syscall('tar -jxvf '+config['ZIP_FILE'])
send2log( w, log_file )
# unzip gzip files if any
w=''
w=syscall('ls *.gz')
if len(w)>3:
send2log( 'running gzip -d for *.gz files', log_file )
w=''
w=syscall('gzip -d *.gz')
else:
send2log( "ERROR: no zip archive with reads. Can not continue\n", log_file)
sys.exit(777)
if 'FASTQ_FILES'==config['INPUT_TYPE']:
# check reads files
w=''
w=syscall('ls *.fastq')
if len(w)<3:
w=''
w=syscall('ls *.fq')
if len(w)<3:
send2log( "ERROR: no reads files. Can not continue\n", log_file)
sys.exit(777)
l=[]
l=w.split('\n')
config['R1']=l[0]
config['R2']=l[1]
if not( os.path.exists(work_dir+'/'+config['R1']) and os.path.exists(work_dir+'/'+config['R2']) ):
send2log( "ERROR: no reads files. Can not continue\n", log_file)
sys.exit(777)
cmd='./bin/a5_pipeline.pl '+'--threads='+config['NUM_OF_PROC']+' --end=5 '+config['R1']+' '+config['R2']+' '+config['PREFIX']
send2log( "Running pipeline:\n"+cmd, log_file )
w=''
w=syscall( cmd+' 2>&1' )
send2log( w, log_file )
else:
if os.path.isfile(work_dir+'/'+config['LIB_FILE']):
send2log("contents of LIB file:", log_file)
syscall( 'cat '+config['LIB_FILE']+ ' >> ' +log_file)
send2log("\n", log_file)
else:
send2log( "ERROR: no LIB file. Can not continue\n", log_file)
sys.exit(777)
#cmd='./bin/a5_pipeline.pl '+config['LIB_FILE']+' '+config['PREFIX']
cmd='/opt/a5/bin/a5_pipeline.pl '+'--threads='+config['NUM_OF_PROC']+' --end=5 '+config['LIB_FILE']+' '+config['PREFIX']
send2log( "Running pipeline: \n"+cmd, log_file )
w=''
w=syscall( cmd+' 2>&1' )
send2log( w, log_file )
if 'YES'==config['BLAST_STEP']:
cmd ='./blast2nr.sh '+config['PREFIX']+' '+config['NUM_OF_PROC']
send2log( 'Executing:'+cmd, log_file)
w=syscall(cmd)
send2log( w, log_file )
send2log( 'MiSeq Metagenomic Assembly pipeline DONE',log_file )
if __name__ == "__main__":
main()
| Pipes/pipeline-scripts/NGOPT/ngopt.py | 6,502 | !/usr/bin/env python $Id$ Project: MiSeq Metagenomic Assembly pipeline for Nephele project Language: Python 2.7 Author: Alex Levitsky History: July 2015 Start of development check for end of file ignore empty lines ignore comments clear list read_config send2log print >> sys.stderr, "Executing:",cmd exec_sys main Read config file Define optional and default parameters Predefined and calculated options get env.json if available get number of cores get machine's memory print configuration to log file unzip reads check files extension unzip gzip files if any check reads filescmd='./bin/a5_pipeline.pl '+config['LIB_FILE']+' '+config['PREFIX'] | 659 | en | 0.519915 |
from django.shortcuts import render
from django.http import HttpResponseRedirect
# <HINT> Import any new Models here
from .models import Course, Enrollment, Question, Choice, Submission , Lesson
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404, render, redirect
from django.urls import reverse
from django.views import generic
from django.contrib.auth import login, logout, authenticate
import logging
# Get an instance of a logger
logger = logging.getLogger(__name__)
# Create your views here.
def registration_request(request):
context = {}
if request.method == 'GET':
return render(request, 'onlinecourse/user_registration_bootstrap.html', context)
elif request.method == 'POST':
# Check if user exists
username = request.POST['username']
password = request.POST['psw']
first_name = request.POST['firstname']
last_name = request.POST['lastname']
user_exist = False
try:
User.objects.get(username=username)
user_exist = True
except:
logger.error("New user")
if not user_exist:
user = User.objects.create_user(username=username, first_name=first_name, last_name=last_name,
password=password)
login(request, user)
return redirect("onlinecourse:index")
else:
context['message'] = "User already exists."
return render(request, 'onlinecourse/user_registration_bootstrap.html', context)
def login_request(request):
context = {}
if request.method == "POST":
username = request.POST['username']
password = request.POST['psw']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('onlinecourse:index')
else:
context['message'] = "Invalid username or password."
return render(request, 'onlinecourse/user_login_bootstrap.html', context)
else:
return render(request, 'onlinecourse/user_login_bootstrap.html', context)
def logout_request(request):
logout(request)
return redirect('onlinecourse:index')
def check_if_enrolled(user, course):
is_enrolled = False
if user.id is not None:
# Check if user enrolled
num_results = Enrollment.objects.filter(user=user, course=course).count()
if num_results > 0:
is_enrolled = True
return is_enrolled
# CourseListView
class CourseListView(generic.ListView):
template_name = 'onlinecourse/course_list_bootstrap.html'
context_object_name = 'course_list'
def get_queryset(self):
user = self.request.user
courses = Course.objects.order_by('-total_enrollment')[:10]
for course in courses:
if user.is_authenticated:
course.is_enrolled = check_if_enrolled(user, course)
return courses
class CourseDetailView(generic.DetailView):
model = Course
template_name = 'onlinecourse/course_detail_bootstrap.html'
def enroll(request, course_id):
course = get_object_or_404(Course, pk=course_id)
user = request.user
is_enrolled = check_if_enrolled(user, course)
if not is_enrolled and user.is_authenticated:
# Create an enrollment
Enrollment.objects.create(user=user, course=course, mode='honor')
course.total_enrollment += 1
course.save()
return HttpResponseRedirect(reverse(viewname='onlinecourse:course_details', args=(course.id,)))
# <HINT> Create a submit view to create an exam submission record for a course enrollment,
# you may implement it based on following logic:
# Get user and course object, then get the associated enrollment object created when the user enrolled the course
# Create a submission object referring to the enrollment
# Collect the selected choices from exam form
# Add each selected choice object to the submission object
# Redirect to show_exam_result with the submission id
# <HINT> A example method to collect the selected choices from the exam form from the request object
def extract_answers(request):
submitted_anwsers = []
for key in request.POST:
if key.startswith('choice'):
value = request.POST[key]
choice_id = int(value)
submitted_anwsers.append(choice_id)
return submitted_anwsers
def submit(request, course_id):
user = request.user
course = Course.objects.get(pk=course_id)
enrollment = Enrollment.objects.get(user=user, course=course)
submitted_anwsers = extract_answers(request)
submission = Submission.objects.create(enrollment=enrollment)
submission.chocies.set(submitted_anwsers)
print(submission)
return HttpResponseRedirect(reverse(viewname='onlinecourse:result', args=(course_id, submission.chocies.first().question.lesson.pk, submission.pk)))
# <HINT> Create an exam result view to check if learner passed exam and show their question results and result for each question,
# you may implement it based on the following logic:
# Get course and submission based on their ids
# Get the selected choice ids from the submission record
# For each selected choice, check if it is a correct answer or not
# Calculate the total score
def show_exam_result(request, course_id, lesson_id, submission_id):
from django.db.models import Sum
course = Course.objects.get(pk=course_id)
submission = Submission.objects.get(pk=submission_id)
selected_choices = submission.chocies.all()
lesson = Lesson.objects.get(pk=lesson_id)
questions = lesson.question_set.all()
total_mark = round(lesson.question_set.all().aggregate(Sum("grade"))["grade__sum"])
grade = 0
for question in questions:
if question.is_get_score(selected_choices):
grade += question.grade
ctx = {
'grade': round(grade),
'total_mark': total_mark,
'questions': questions,
'lesson': lesson,
'selected_choices': selected_choices,
}
return render(request , 'onlinecourse/exam_result_bootstrap.html' , ctx) | onlinecourse/views.py | 6,268 | <HINT> Import any new Models here Get an instance of a logger Create your views here. Check if user exists Check if user enrolled CourseListView Create an enrollment <HINT> Create a submit view to create an exam submission record for a course enrollment, you may implement it based on following logic: Get user and course object, then get the associated enrollment object created when the user enrolled the course Create a submission object referring to the enrollment Collect the selected choices from exam form Add each selected choice object to the submission object Redirect to show_exam_result with the submission id <HINT> A example method to collect the selected choices from the exam form from the request object <HINT> Create an exam result view to check if learner passed exam and show their question results and result for each question, you may implement it based on the following logic: Get course and submission based on their ids Get the selected choice ids from the submission record For each selected choice, check if it is a correct answer or not Calculate the total score | 1,090 | en | 0.905071 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
'''
In this file, we define the classes that live inside 'worker 0', the worker
responsible for orchestration and aggregation. The main class is the
OptimizationServer, which sends clients to the other workers to process and
combines the resulting models.
'''
import json
import logging
import os
import random
import shutil
import time
from collections import defaultdict
import numpy as np
import torch
# Internal imports
from core.globals import TRAINING_FRAMEWORK_TYPE
if TRAINING_FRAMEWORK_TYPE == 'mpi':
import core.federated as federated
else:
raise NotImplementedError('{} is not supported'.format(TRAINING_FRAMEWORK_TYPE))
from core.evaluation import Evaluation
from core.client import Client
from .strategies import select_strategy
from .trainer import (
ModelUpdater,
Trainer,
set_component_wise_lr,
)
from utils import (
get_lr,
print_rank,
update_json_log,
)
# For profiling
import cProfile
import pstats
# AzureML-related libs
from azureml.core import Run
run = Run.get_context()
class OptimizationServer(federated.Server):
def __init__(self, num_clients, model, optimizer, ss_scheduler, data_path, model_path, train_dataloader,
val_dataloader, test_dataloader, config, config_server):
'''Implement Server's orchestration and aggregation.
This is the main Server class, that actually implements orchestration
and aggregation, inheriting from `federated.Server`, which deals with
communication only.
The `train` method is central in FLUTE, as it defines good part of what
happens during training.
Args:
num_clients (int): total available clients.
model (torch.nn.Module): neural network model.
optimizer (torch.optim.Optimizer): optimizer.
ss_scheduler: scheduled sampling scheduler.
data_path (str): points to where data is.
model_path (str): points to where pretrained model is.
train_dataloader (torch.utils.data.DataLoader): dataloader for training
val_dataloader (torch.utils.data.DataLoader): dataloader for validation
test_dataloader (torch.utils.data.DataLoader): dataloader for test, can be None
config (dict): JSON style configuration parameters
config_server: deprecated, kept for API compatibility only.
'''
super().__init__()
# Initialize all attributes from arguments
self.client_idx_list = list(range(num_clients))
self.config = config
server_config = config['server_config']
decoder_config = config.get('decoder_config', None)
self.max_iteration = server_config['max_iteration']
self.do_clustering = server_config.get('clustering', False)
self.num_clients_per_iteration = [int(x) for x in server_config['num_clients_per_iteration'].split(',')] \
if isinstance(server_config['num_clients_per_iteration'], str) \
else [server_config['num_clients_per_iteration']]
self.val_freq = server_config['val_freq']
self.req_freq = server_config['rec_freq']
self.evaluation = Evaluation(config, model_path, self.process_testvalidate, val_dataloader, test_dataloader)
# TODO: does this need to be adjusted for custom metrics?
self.metrics = {
'best_val_loss': float('inf'),
'best_val_acc': 0.0,
'best_test_loss': float('inf'),
'best_test_acc': 0.0
}
self.model_backup_freq = server_config.get('model_backup_freq', 100)
self.worker_trainer_config = server_config.get('trainer_config', {})
self.aggregate_median = server_config['aggregate_median']
self.initial_lr_client = server_config.get('initial_lr_client', -1.0)
self.lr_decay_factor = server_config.get('lr_decay_factor', 1.0)
self.model_type = config['model_config']['model_type']
self.quant_thresh = config['client_config'].get('quant_thresh', None)
self.quant_bits = config['client_config'].get('quant_bits', 10)
self.list_of_train_data = config['client_config']['data_config']['train']['list_of_train_data']
self.data_path = data_path
# Get max grad norm from data config
if 'train' in server_config['data_config']:
max_grad_norm = server_config['data_config']['train'].get('max_grad_norm', None)
else:
max_grad_norm = None
# Creating an instance to update the model with stats aggregated from workers
self.worker_trainer = ModelUpdater(
model=model,
optimizer=optimizer,
ss_scheduler=ss_scheduler,
train_dataloader=train_dataloader if train_dataloader is not None else val_dataloader,
val_dataloader=val_dataloader,
max_grad_norm=max_grad_norm,
anneal_config=server_config['annealing_config'],
model_type=self.model_type,
decoder_config=decoder_config
)
self.metrics['worker_trainer'] = self.worker_trainer
# Creating an instance for the server-side trainer (runs mini-batch SGD)
self.server_replay_iterations = None
self.server_trainer = None
if train_dataloader is not None:
assert 'server_replay_config' in server_config, 'server_replay_config is not set'
assert 'optimizer_config' in server_config[
'server_replay_config'], 'server-side replay training optimizer is not set'
self.server_optimizer_config = server_config['server_replay_config']['optimizer_config']
self.server_trainer_config = server_config['server_replay_config'].get('trainer_config', {})
self.server_replay_iterations = server_config['server_replay_config']['server_iterations']
self.server_trainer = Trainer(
model=model,
optimizer=None,
ss_scheduler=ss_scheduler,
train_dataloader=train_dataloader,
server_replay_config=server_config['server_replay_config'],
val_dataloader=None,
max_grad_norm=server_config['server_replay_config']\
.get('max_grad_norm',server_config['data_config']['train']\
.get('max_grad_norm',None)),
anneal_config=server_config['server_replay_config'].get('annealing_config', None)
)
self.skip_model_update = False # will not update the model if True
self.train_loss = 0.0
self.model_path = model_path
self.best_model_criterion = server_config['best_model_criterion']
self.fall_back_to_best_model = server_config['fall_back_to_best_model']
self.last_model_path = os.path.join(self.model_path, 'latest_model.tar')
self.best_model_path = os.path.join(self.model_path,
'best_val_{}_model.tar'.format(self.best_model_criterion))
self.log_path = os.path.join(self.model_path, 'status_log.json')
self.cur_iter_no = 0 # keep the iteration number for Tensor board plotting
self.lr_weight = 1.0
self.losses = []
self.no_label_updates = 0 # no. label updates
# Update the parameters above if the log file
if server_config.get('resume_from_checkpoint', False):
self.load_saved_status()
# Decoding config
self.decoder_config = decoder_config
self.spm_model = server_config['data_config']['test'].get('spm_model', None)
self.do_profiling = server_config.get('do_profiling', False)
# Parallel processing
self.clients_in_parallel = config['client_config'].get('clients_in_parallel', None)
StrategyClass = select_strategy(config['strategy'])
self.strategy = StrategyClass('server', self.config, self.model_path)
print_rank(f'Server successfully instantiated strategy {self.strategy}', loglevel=logging.DEBUG)
def load_saved_status(self):
'''Load checkpoint from disk'''
# Check if model is on disk, if so loads it onto trainer
if os.path.exists(self.last_model_path):
print_rank('Resuming from checkpoint model {}'.format(self.last_model_path))
self.worker_trainer.load(self.last_model_path, update_lr_scheduler=True, update_ss_scheduler=True)
if self.server_trainer is not None:
self.server_trainer.model = self.worker_trainer.model # make sure that the models are in sync
# Check if log is on disk, if so loads it onto current stats
if os.path.exists(self.log_path):
with open(self.log_path, 'r') as logfp: # loading the iteration no., best loss and CER
elems = json.load(logfp)
self.cur_iter_no = elems.get('i', 0)
self.metrics['best_val_loss'] = elems.get('best_val_loss', float('inf'))
self.metrics['best_val_acc'] = elems.get('best_val_acc', 0)
self.metrics['best_test_loss'] = elems.get('best_test_loss', float('inf'))
self.metrics['best_test_acc'] = elems.get('best_test_acc', 0)
self.lr_weight = elems.get('weight', 1.0)
self.no_label_updates = elems.get('num_label_updates', 0)
print_rank(f'Resuming from status_log: cur_iter: {self.cur_iter_no}')
def run(self):
'''Trigger training.
This is a simple wrapper to the `train` method.
'''
print_rank('server started')
self.train()
print_rank('server terminated')
def train(self):
'''Main method for training.'''
self.run_stats = {
'secsPerClientRound': [],
'secsPerClient': [],
'secsPerClientTraining': [],
'secsPerClientSetup': [],
'secsPerClientFull': [],
'secsPerRoundHousekeeping': [],
'secsPerRoundTotal': [],
'mpiCosts': []
}
run.log('Max iterations', self.max_iteration)
try:
self.worker_trainer.model.cuda() if torch.cuda.is_available() else None
# Do an initial validation round to understand the pretrained model's validation accuracy
# Skip if we resumed from a checkpoint (cur_iter_no > 0)
eval_list = []
if self.cur_iter_no == 0:
if self.config['server_config']['initial_rec']:
eval_list.append('test')
if self.config['server_config']['initial_val']:
eval_list.append('val')
run.log('LR for agg. opt.', get_lr(self.worker_trainer.optimizer))
print_rank("Running {} at itr={}".format(eval_list, self.cur_iter_no))
self.metrics = self.evaluation.run(eval_list, self.metrics, metric_logger=run.log)
eval_list = [] # some cleanup
# Dump all the information in aggregate_metric
print_rank('Saving Model Before Starting Training', loglevel=logging.INFO)
for token in ['best_val_loss', 'best_val_acc', 'best_test_acc', 'latest']:
self.worker_trainer.save(
model_path=self.model_path,
token=token,
config=self.config['server_config']
)
# Training loop
self.worker_trainer.model.train()
for i in range(self.cur_iter_no, self.max_iteration):
begin = time.time()
metrics_payload = {}
def log_metric(k, v):
metrics_payload[k] = v
print_rank('==== iteration {}'.format(i))
log_metric('Current iteration', i)
# Initial value for the learning rate of the worker
initial_lr = self.initial_lr_client * self.lr_weight
print_rank('Client learning rate {}'.format(initial_lr))
# Run training on clients
self.worker_trainer.model.zero_grad()
self.train_loss = []
server_data = (
initial_lr,
[p.data.to(torch.device('cpu')) for p in self.worker_trainer.model.parameters()]
)
# Random number of clients per iteration
if len(self.num_clients_per_iteration) > 1:
num_clients_curr_iter = random.randint(
self.num_clients_per_iteration[0],
self.num_clients_per_iteration[1]
)
else:
num_clients_curr_iter = self.num_clients_per_iteration[0]
log_metric('Clients for round', num_clients_curr_iter)
# Perform annealing in quantization threshold
if self.quant_thresh is not None:
self.config['client_config']['quant_thresh'] *= self.config['client_config'].get('quant_anneal', 1.0)
self.quant_thresh = self.config['client_config']['quant_thresh']
log_metric('Quantization Thresh.', self.config['client_config']['quant_thresh'])
# Create the pool of clients -- sample from this pool to assign to workers
sampled_idx_clients = random.sample(self.client_idx_list,
num_clients_curr_iter) if num_clients_curr_iter > 0 else self.client_idx_list
sampled_clients = [
Client(
client_id,
self.config,
self.config['client_config']['type'] == 'optimization',
None
) for client_id in sampled_idx_clients
]
# Initialize stats
clients_begin = time.time()
client_losses = []
client_mag_grads = []
client_mean_grads = []
client_var_grads = []
client_norm_grads = []
self.run_stats['secsPerClient'].append([])
self.run_stats['secsPerClientFull'].append([])
self.run_stats['secsPerClientTraining'].append([])
self.run_stats['secsPerClientSetup'].append([])
self.run_stats['mpiCosts'].append([])
# Check if we want privacy metrics
apply_privacy_metrics = self.config.get('privacy_metrics_config', None) and \
self.config['privacy_metrics_config']['apply_metrics']
adaptive_leakage = apply_privacy_metrics and \
self.config['privacy_metrics_config'].get('adaptive_leakage_threshold', None)
if apply_privacy_metrics:
privacy_metrics_stats = defaultdict(list)
# Initialize profiler
profiler = None
if self.do_profiling:
profiler = cProfile.Profile()
profiler.enable()
# Reset gradient for the model before assigning the new gradients
self.worker_trainer.model.zero_grad()
for client_output in self.process_clients(sampled_clients, server_data, self.clients_in_parallel):
# Process client output
client_timestamp = client_output['ts']
client_stats = client_output['cs']
client_loss = client_output['tl']
client_mag_grad = client_output['mg']
client_mean_grad = client_output['ng']
client_var_grad = client_output['vg']
client_norm_grad = client_output['rg']
client_payload = client_output['pl']
if apply_privacy_metrics:
privacy_stats = client_output['ps']
for metric, value in privacy_stats.items():
privacy_metrics_stats[metric].append(value)
self.run_stats['mpiCosts'][-1].append(time.time() - client_timestamp)
# Get actual pseudo-gradients for aggregation
payload_processed = self.strategy.process_individual_payload(self.worker_trainer, client_payload)
if not payload_processed:
print_rank('Dropping client', loglevel=logging.DEBUG)
num_clients_curr_iter -= 1
continue
# Aggregate stats
self.train_loss.append(client_loss)
client_losses.append(client_loss)
client_mag_grads.append(client_mag_grad.item())
client_mean_grads.append(client_mean_grad.item())
client_var_grads.append(client_var_grad.item())
client_norm_grads.append(client_norm_grad.item())
# Mark the end of client processing
client_end = time.time()
self.run_stats['secsPerClientFull'][-1].append(client_stats['full cost'])
self.run_stats['secsPerClientTraining'][-1].append(client_stats['training'])
self.run_stats['secsPerClientSetup'][-1].append(client_stats['setup'])
self.run_stats['secsPerClient'][-1].append(client_end - clients_begin)
# Tear down profiler
if self.do_profiling:
profiler.disable()
stats = pstats.Stats(profiler)
stats.sort_stats('cumulative').print_stats()
# Prepare output
client_mag_grads = np.array(client_mag_grads)
client_mean_grads = np.array(client_mean_grads)
client_var_grads = np.array(client_var_grads)
client_norm_grads = np.array(client_norm_grads)
client_stats = (client_mag_grads, client_mean_grads, client_var_grads)
dump_norm_stats = self.config.get('dump_norm_stats', False)
if dump_norm_stats:
with open(os.path.join(self.model_path, 'norm_stats.txt'), 'a', encoding='utf-8') as outF:
outF.write('{}\n'.format(json.dumps(list(client_norm_grads))))
# Print the privacy metrics
if apply_privacy_metrics:
for metric, values in privacy_metrics_stats.items():
if metric == 'Dropped clients':
log_metric(metric, sum(values))
else:
log_metric(metric, max(values))
if type(adaptive_leakage) is float:
values = privacy_metrics_stats['Practical epsilon (Max leakage)']
new_threshold = list(sorted(values))[int(adaptive_leakage*len(values))]
print_rank('Updating leakage threshold to {}'.format(new_threshold))
self.config['privacy_metrics_config']['max_allowed_leakage'] = new_threshold
# Mark that all clients have been processed
end = time.time()
self.run_stats['secsPerClientRound'].append(end - begin)
begin = end
# Log the training loss to tensorboard/AML
log_metric('Training loss', sum(self.train_loss))
# Combine payloads
self.losses = self.strategy.combine_payloads(
worker_trainer=self.worker_trainer,
curr_iter=i,
num_clients_curr_iter=num_clients_curr_iter,
client_stats=client_stats,
logger=log_metric,
)
# Run a couple of iterations of training data on the server
if self.server_trainer is not None:
print_rank('Running replay iterations on server')
if 'updatable_names' in self.server_trainer_config:
set_component_wise_lr(
self.worker_trainer.model,
self.server_optimizer_config,
self.server_trainer_config['updatable_names']
)
self.server_trainer.prepare_iteration(self.worker_trainer.model)
self.server_trainer.train_desired_samples(self.server_replay_iterations)
self.worker_trainer.model.load_state_dict(self.server_trainer.model.state_dict())
torch.cuda.empty_cache()
# Update a sampling scheduler
print_rank('Run ss scheduler')
self.worker_trainer.run_ss_scheduler()
# Run inference and score on val/test depending on the iter. number
if ((i+1) % self.val_freq) == 0:
eval_list.append("val")
if ((i+1) % self.req_freq) == 0 :
eval_list.append("test")
if len(eval_list)> 0:
print_rank('Running {} at itr={}'.format(eval_list,i+1))
self.metrics['worker_trainer'] = self.worker_trainer
self.metrics = self.evaluation.run(eval_list, self.metrics, metric_logger=run.log)
self.losses = self.evaluation.losses
eval_list = []
# Create a schedule for the initial_lr (for the worker)
if 'val' in eval_list:
run.log('LR for agg. opt.', get_lr(self.worker_trainer.optimizer))
if not (self.losses[0] < self.metrics['best_val_loss']):
self.lr_weight *= self.lr_decay_factor
print_rank('LOG: Client weight of learning rate {}..'.format(self.lr_weight))
# Backup the current best models
self.backup_models(i)
# Fall back to the best model if the option is enabled
self.fall_back_to_prev_best_status()
# Logging the latest best values
update_json_log(
self.log_path,
{
'i': i + 1,
'best_val_loss': float(self.metrics['best_val_loss']),
'best_val_acc': float(self.metrics['best_val_acc']),
'best_test_loss': float(self.metrics['best_test_loss']),
'best_test_acc': float(self.metrics['best_test_acc']),
'weight': float(self.lr_weight),
'num_label_updates': int(self.no_label_updates)
},
)
end = time.time()
# Aggregate stats
self.run_stats['secsPerRoundHousekeeping'].append(end - begin)
self.run_stats['secsPerRoundTotal'].append(self.run_stats['secsPerClientRound'][-1] + \
self.run_stats['secsPerRoundHousekeeping'][-1])
log_metric('secsPerRoundTotal', self.run_stats['secsPerRoundTotal'][-1])
if self.do_profiling:
log_metric('secsPerClientRound', self.run_stats['secsPerClientRound'][-1])
log_metric('secsPerRoundHousekeeping', self.run_stats['secsPerRoundHousekeeping'][-1])
metrics_for_stats = [
'secsPerClient',
'secsPerClientTraining',
'secsPerClientFull',
'secsPerClientSetup',
'mpiCosts',
]
for metric in metrics_for_stats:
log_metric(f'{metric}Mean', np.mean(self.run_stats[metric][-1]))
log_metric(f'{metric}Median', np.median(self.run_stats[metric][-1]))
log_metric(f'{metric}Max', max(self.run_stats[metric][-1]))
for k in self.run_stats:
if k in metrics_for_stats:
print_rank('{}: {}'.format(k, max(self.run_stats[k][-1])), loglevel=logging.DEBUG)
else:
print_rank('{}: {}'.format(k, self.run_stats[k][-1]), loglevel=logging.DEBUG)
# Log all the metrics
for k in metrics_payload:
run.log(k, metrics_payload[k])
finally: # perform cleanup even if error was raised above
self.terminate_workers(terminate=(not self.do_clustering))
def backup_models(self, i):
'''Save the current best models.
Save CER model, the best loss model and the best WER model. This occurs
at a specified period.
Args:
i: no. of iterations.
'''
# Always save the latest model
self.worker_trainer.save(
model_path=self.model_path,
token='latest',
config=self.config['server_config'],
)
if (i % self.model_backup_freq) == 0: # save the current best models
self.worker_trainer.save(
model_path=self.model_path,
token='epoch{}'.format(i),
config=self.config['server_config']
)
for bodyname in ['best_val_acc', 'best_val_loss', 'best_test_acc']:
src_model_path = os.path.join(self.model_path, '{}_model.tar'.format(bodyname))
if os.path.exists(src_model_path):
dst_model_path = os.path.join(self.model_path, 'epoch{}_{}_model.tar'.format(i, bodyname))
shutil.copyfile(src_model_path, dst_model_path)
print_rank('Saved {}'.format(dst_model_path))
def fall_back_to_prev_best_status(self):
'''Go back to the past best status and switch to the recent best model.'''
if self.fall_back_to_best_model:
print_rank('falling back to model {}'.format(self.best_model_path))
# Save current learning rate
tmp_lr = get_lr(self.worker_trainer.optimizer)
# Load previous best model
self.worker_trainer.load(self.best_model_path, update_lr_scheduler=False, update_ss_scheduler=False)
# Update previous learning rate on optimizer
for g in self.worker_trainer.optimizer.param_groups:
g['lr'] = tmp_lr
if self.server_trainer is not None:
self.server_trainer.model = self.worker_trainer.model # make sure that the models are in sync
def select_server(server_type, config):
'''Select a server type using different possible strings.
Right now this just returns `OptimizationServer`, but this
function could be useful when there are multiple choices of
server.
Args:
server_type (str): indicates server choice.
config (dict): config parsed from YAML, passed so that
parameters can be used to select a given server.
'''
return OptimizationServer
| core/server.py | 27,299 | Implement Server's orchestration and aggregation.
This is the main Server class, that actually implements orchestration
and aggregation, inheriting from `federated.Server`, which deals with
communication only.
The `train` method is central in FLUTE, as it defines good part of what
happens during training.
Args:
num_clients (int): total available clients.
model (torch.nn.Module): neural network model.
optimizer (torch.optim.Optimizer): optimizer.
ss_scheduler: scheduled sampling scheduler.
data_path (str): points to where data is.
model_path (str): points to where pretrained model is.
train_dataloader (torch.utils.data.DataLoader): dataloader for training
val_dataloader (torch.utils.data.DataLoader): dataloader for validation
test_dataloader (torch.utils.data.DataLoader): dataloader for test, can be None
config (dict): JSON style configuration parameters
config_server: deprecated, kept for API compatibility only.
Save the current best models.
Save CER model, the best loss model and the best WER model. This occurs
at a specified period.
Args:
i: no. of iterations.
Go back to the past best status and switch to the recent best model.
Load checkpoint from disk
Trigger training.
This is a simple wrapper to the `train` method.
Select a server type using different possible strings.
Right now this just returns `OptimizationServer`, but this
function could be useful when there are multiple choices of
server.
Args:
server_type (str): indicates server choice.
config (dict): config parsed from YAML, passed so that
parameters can be used to select a given server.
Main method for training.
In this file, we define the classes that live inside 'worker 0', the worker
responsible for orchestration and aggregation. The main class is the
OptimizationServer, which sends clients to the other workers to process and
combines the resulting models.
Copyright (c) Microsoft Corporation. Licensed under the MIT license. Internal imports For profiling AzureML-related libs Initialize all attributes from arguments TODO: does this need to be adjusted for custom metrics? Get max grad norm from data config Creating an instance to update the model with stats aggregated from workers Creating an instance for the server-side trainer (runs mini-batch SGD) will not update the model if True keep the iteration number for Tensor board plotting no. label updates Update the parameters above if the log file Decoding config Parallel processing Check if model is on disk, if so loads it onto trainer make sure that the models are in sync Check if log is on disk, if so loads it onto current stats loading the iteration no., best loss and CER Do an initial validation round to understand the pretrained model's validation accuracy Skip if we resumed from a checkpoint (cur_iter_no > 0) some cleanup Dump all the information in aggregate_metric Training loop Initial value for the learning rate of the worker Run training on clients Random number of clients per iteration Perform annealing in quantization threshold Create the pool of clients -- sample from this pool to assign to workers Initialize stats Check if we want privacy metrics Initialize profiler Reset gradient for the model before assigning the new gradients Process client output Get actual pseudo-gradients for aggregation Aggregate stats Mark the end of client processing Tear down profiler Prepare output Print the privacy metrics Mark that all clients have been processed Log the training loss to tensorboard/AML Combine payloads Run a couple of iterations of training data on the server Update a sampling scheduler Run inference and score on val/test depending on the iter. number Create a schedule for the initial_lr (for the worker) Backup the current best models Fall back to the best model if the option is enabled Logging the latest best values Aggregate stats Log all the metrics perform cleanup even if error was raised above Always save the latest model save the current best models Save current learning rate Load previous best model Update previous learning rate on optimizer make sure that the models are in sync | 4,159 | en | 0.784774 |
KEYBOARD_INTERRUPT = 1
ARGUMENT_ERROR = 2
# When playlists, albums, artists, users aren't found.
URI_NOT_FOUND_ERROR = 5
| spotdl/command_line/exitcodes.py | 123 | When playlists, albums, artists, users aren't found. | 52 | en | 0.959479 |
import random
import numpy as np
def write_to_file(filename,no_locations,no_agents):
info_dict={}
#ID enumerates from 0 to n-1
header='Location Index:Agents:Time Interval'
n=random.randint(10,20)
f=open(filename,'w')
f.write(str(n)+'\n')
f.write(header+'\n')
for i in range(n):
line=str(random.randint(0,no_locations-1))+':'
for i in range(random.randint(0,20)):
line+=str(random.randint(0,no_agents-1))+','
line+=str(random.randint(0,no_agents-1))
line+=':'+str(random.choice([10,30,45,60]))+'\n'
f.write(line)
write_to_file('monday_events.txt',10,100)
write_to_file('tuesday_events.txt',10,100)
write_to_file('wednesday_events.txt',10,100)
write_to_file('thursday_events.txt',10,100)
write_to_file('friday_events.txt',10,100)
write_to_file('saturday_events.txt',5,100)
write_to_file('sunday_events.txt',2,100)
| examples/Basic_Disease_Models/Example_1/generate_events.py | 839 | ID enumerates from 0 to n-1 | 27 | en | 0.703547 |
# Generated by Django 2.2.2 on 2019-09-01 09:08
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('email', models.EmailField(max_length=255, unique=True)),
('name', models.CharField(max_length=255)),
('is_active', models.BooleanField(default=True)),
('is_staff', models.BooleanField(default=False)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'abstract': False,
},
),
]
| app/core/migrations/0001_initial.py | 1,701 | Generated by Django 2.2.2 on 2019-09-01 09:08 | 45 | en | 0.564323 |
"""
Thank you Funkwhale for inspiration on the HTTP signatures parts <3
https://funkwhale.audio/
"""
import datetime
import logging
from typing import Union
import pytz
from Crypto.PublicKey.RSA import RsaKey
from requests_http_signature import HTTPSignatureHeaderAuth
from federation.types import RequestType
from federation.utils.network import parse_http_date
from federation.utils.text import encode_if_text
logger = logging.getLogger("federation")
def get_http_authentication(private_key: RsaKey, private_key_id: str) -> HTTPSignatureHeaderAuth:
"""
Get HTTP signature authentication for a request.
"""
key = private_key.exportKey()
return HTTPSignatureHeaderAuth(
headers=["(request-target)", "user-agent", "host", "date"],
algorithm="rsa-sha256",
key=key,
key_id=private_key_id,
)
def verify_request_signature(request: RequestType, public_key: Union[str, bytes]):
"""
Verify HTTP signature in request against a public key.
"""
key = encode_if_text(public_key)
date_header = request.headers.get("Date")
if not date_header:
raise ValueError("Rquest Date header is missing")
ts = parse_http_date(date_header)
dt = datetime.datetime.utcfromtimestamp(ts).replace(tzinfo=pytz.utc)
past_delta = datetime.timedelta(hours=24)
future_delta = datetime.timedelta(seconds=30)
now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
if dt < now - past_delta or dt > now + future_delta:
raise ValueError("Request Date is too far in future or past")
HTTPSignatureHeaderAuth.verify(request, key_resolver=lambda **kwargs: key)
| federation/protocols/activitypub/signing.py | 1,652 | Get HTTP signature authentication for a request.
Verify HTTP signature in request against a public key.
Thank you Funkwhale for inspiration on the HTTP signatures parts <3
https://funkwhale.audio/ | 197 | en | 0.797497 |
# -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from ctypes import c_uint64
import numpy as np
from .utils import CxxPointer, _call_with_growing_buffer
from .ffi import chfl_match
class Selection(CxxPointer):
"""
Select atoms in a :py:class:`Frame` with a selection language.
The selection language is built by combining basic operations. Each basic
operation follows the ``<selector>[(<variable>)] <operator> <value>``
structure, where ``<operator>`` is a comparison operator in
``== != < <= > >=``. Refer to the `full documentation
<selections-doc>`_ to know the allowed selectors and how to use them.
.. selections-doc: https://chemfiles.org/chemfiles/latest/selections.html
"""
def __init__(self, selection):
"""
Create a new :py:class:`Selection` from the given ``selection`` string.
"""
ptr = self.ffi.chfl_selection(selection.encode("utf8"))
super(Selection, self).__init__(ptr, is_const=False)
def __copy__(self):
return Selection.from_mutable_ptr(None, self.ffi.chfl_selection_copy(self.ptr))
def __repr__(self):
return "Selection('{}')".format(self.string)
@property
def size(self):
"""
Get the size of this :py:class:`Selection`.
The size of a selection is the number of atoms we are selecting
together. This value is 1 for the 'atom' context, 2 for the 'pair' and
'bond' context, 3 for the 'three' and 'angles' contextes and 4 for the
'four' and 'dihedral' contextes.
"""
size = c_uint64()
self.ffi.chfl_selection_size(self.ptr, size)
return size.value
@property
def string(self):
"""
Get the selection string used to create this :py:class:`Selection`.
"""
return _call_with_growing_buffer(
lambda buffer, size: self.ffi.chfl_selection_string(self.ptr, buffer, size),
initial=128,
)
def evaluate(self, frame):
"""
Evaluate a :py:class:`Selection` for a given :py:class:`Frame`, and
return a list of matching atoms, either as a list of index or a list
of tuples of indexes.
"""
matching = c_uint64()
self.ffi.chfl_selection_evaluate(self.mut_ptr, frame.ptr, matching)
matches = np.zeros(matching.value, chfl_match)
self.ffi.chfl_selection_matches(self.mut_ptr, matches, matching)
size = self.size
result = []
for match in matches:
assert match[0] == size
atoms = match[1]
if size == 1:
result.append(atoms[0])
elif size == 2:
result.append((atoms[0], atoms[1]))
elif size == 3:
result.append((atoms[0], atoms[1], atoms[2]))
elif size == 4:
result.append((atoms[0], atoms[1], atoms[2], atoms[3]))
return result
| chemfiles/selection.py | 2,992 | Select atoms in a :py:class:`Frame` with a selection language.
The selection language is built by combining basic operations. Each basic
operation follows the ``<selector>[(<variable>)] <operator> <value>``
structure, where ``<operator>`` is a comparison operator in
``== != < <= > >=``. Refer to the `full documentation
<selections-doc>`_ to know the allowed selectors and how to use them.
.. selections-doc: https://chemfiles.org/chemfiles/latest/selections.html
Create a new :py:class:`Selection` from the given ``selection`` string.
Evaluate a :py:class:`Selection` for a given :py:class:`Frame`, and
return a list of matching atoms, either as a list of index or a list
of tuples of indexes.
Get the size of this :py:class:`Selection`.
The size of a selection is the number of atoms we are selecting
together. This value is 1 for the 'atom' context, 2 for the 'pair' and
'bond' context, 3 for the 'three' and 'angles' contextes and 4 for the
'four' and 'dihedral' contextes.
Get the selection string used to create this :py:class:`Selection`.
-*- coding=utf-8 -*- | 1,072 | en | 0.804614 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.